diff -Nru openjdk-8-8u392-ga/=unpacked-tar1=/README openjdk-8-8u402-ga/=unpacked-tar1=/README --- openjdk-8-8u392-ga/=unpacked-tar1=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar1=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -README: - - This file should be located at the top of the Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - - See ../README-builds.html for complete details on build machine requirements. - -Simple Build Instructions: - This repository can be loaded as a NetBeans project, built with ant, or - built with GNU make, e.g. - ant - -OR- - cd make && gnumake - - The built files that will be imported into the jdk build will be in the - "dist" directory. - Help information is available by running "ant -projecthelp" or "make help". - diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/README openjdk-8-8u402-ga/=unpacked-tar2=/README --- openjdk-8-8u392-ga/=unpacked-tar2=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -README: - This file should be located at the top of the hotspot Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - - See ../README-builds.html for complete details on build machine requirements. - -Simple Build Instructions: - - cd make && gnumake - - The files that will be imported into the jdk build will be in the "build" - directory. - diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/c1/c1_LIRGenerator.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/c1/c1_LIRGenerator.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/c1/c1_LIRGenerator.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/c1/c1_LIRGenerator.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -79,6 +79,7 @@ PhiResolver::PhiResolver(LIRGenerator* gen, int max_vregs) : _gen(gen) , _state(gen->resolver_state()) + , _loop(NULL) , _temp(LIR_OprFact::illegalOpr) { // reinitialize the shared state arrays diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/c1/c1_RangeCheckElimination.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/c1/c1_RangeCheckElimination.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/c1/c1_RangeCheckElimination.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/c1/c1_RangeCheckElimination.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -379,8 +379,11 @@ aii->_max = idx; aii->_list = new AccessIndexedList(); } else if (idx >= aii->_min && idx <= aii->_max) { - remove_range_check(ai); - return; + // Guard against underflow/overflow (see 'range_cond' check in RangeCheckEliminator::in_block_motion) + if (aii->_max < 0 || (aii->_max + min_jint) <= aii->_min) { + remove_range_check(ai); + return; + } } aii->_min = MIN2(aii->_min, idx); aii->_max = MAX2(aii->_max, idx); @@ -423,9 +426,9 @@ } } } else { - int last_integer = 0; + jint last_integer = 0; Instruction *last_instruction = index; - int base = 0; + jint base = 0; ArithmeticOp *ao = index->as_ArithmeticOp(); while (ao != NULL && (ao->x()->as_Constant() || ao->y()->as_Constant()) && (ao->op() == Bytecodes::_iadd || ao->op() == Bytecodes::_isub)) { @@ -437,12 +440,12 @@ } if (c) { - int value = c->type()->as_IntConstant()->value(); + jint value = c->type()->as_IntConstant()->value(); if (value != min_jint) { if (ao->op() == Bytecodes::_isub) { value = -value; } - base += value; + base = java_add(base, value); last_integer = base; last_instruction = other; } @@ -464,12 +467,12 @@ assert(info != NULL, "Info must not be null"); // if idx < 0, max > 0, max + idx may fall between 0 and - // length-1 and if min < 0, min + idx may overflow and be >= + // length-1 and if min < 0, min + idx may underflow/overflow and be >= // 0. The predicate wouldn't trigger but some accesses could // be with a negative index. This test guarantees that for the // min and max value that are kept the predicate can't let // some incorrect accesses happen. - bool range_cond = (info->_max < 0 || info->_max + min_jint <= info->_min); + bool range_cond = (info->_max < 0 || (info->_max + min_jint) <= info->_min); // Generate code only if more than 2 range checks can be eliminated because of that. // 2 because at least 2 comparisons are done @@ -809,7 +812,7 @@ ); remove_range_check(ai); - } else if (_optimistic && loop_header) { + } else if (false && _optimistic && loop_header) { assert(ai->array(), "Array must not be null!"); assert(ai->index(), "Index must not be null!"); diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/classfile/verifier.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/classfile/verifier.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/classfile/verifier.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/classfile/verifier.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -2081,11 +2081,12 @@ "low must be less than or equal to high in tableswitch"); return; } - keys = high - low + 1; - if (keys < 0) { + int64_t keys64 = ((int64_t)high - low) + 1; + if (keys64 > 65535) { // Max code length verify_error(ErrorContext::bad_code(bci), "too many keys in tableswitch"); return; } + keys = (int)keys64; delta = 1; } else { keys = (int)Bytes::get_Java_u4(aligned_bcp + jintSize); diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/code/nmethod.hpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/code/nmethod.hpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/code/nmethod.hpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/code/nmethod.hpp 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -363,8 +363,8 @@ // type info bool is_nmethod() const { return true; } - bool is_java_method() const { return !method()->is_native(); } - bool is_native_method() const { return method()->is_native(); } + bool is_java_method() const { return _method != NULL && !method()->is_native(); } + bool is_native_method() const { return _method != NULL && method()->is_native(); } bool is_osr_method() const { return _entry_bci != InvocationEntryBci; } bool is_compiled_by_c1() const; diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/interpreter/bytecodes.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/interpreter/bytecodes.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/interpreter/bytecodes.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/interpreter/bytecodes.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -114,12 +114,18 @@ if (end != NULL && aligned_bcp + 3*jintSize >= end) { return -1; // don't read past end of code buffer } + // Promote calculation to signed 64 bits to do range checks, used by the verifier. jlong lo = (jint)Bytes::get_Java_u4(aligned_bcp + 1*jintSize); jlong hi = (jint)Bytes::get_Java_u4(aligned_bcp + 2*jintSize); jlong len = (aligned_bcp - bcp) + (3 + hi - lo + 1)*jintSize; - // only return len if it can be represented as a positive int; - // return -1 otherwise - return (len > 0 && len == (int)len) ? len : -1; + // Only return len if it can be represented as a positive int and lo <= hi. + // The caller checks for bytecode stream overflow. + if (lo <= hi && len == (int)len) { + assert(len > 0, "must be"); + return (int)len; + } else { + return -1; + } } case _lookupswitch: // fall through @@ -131,9 +137,13 @@ } jlong npairs = (jint)Bytes::get_Java_u4(aligned_bcp + jintSize); jlong len = (aligned_bcp - bcp) + (2 + 2*npairs)*jintSize; - // only return len if it can be represented as a positive int; - // return -1 otherwise - return (len > 0 && len == (int)len) ? len : -1; + // Only return len if it can be represented as a positive int and npairs >= 0. + if (npairs >= 0 && len == (int)len) { + assert(len > 0, "must be"); + return (int)len; + } else { + return -1; + } } } // Note: Length functions must return <=0 for invalid bytecodes. diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/ifnode.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/ifnode.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/ifnode.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/ifnode.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -882,6 +882,46 @@ // then we are guaranteed to fail, so just start interpreting there. // We 'expand' the top 3 range checks to include all post-dominating // checks. + // + // Example: + // a[i+x] // (1) 1 < x < 6 + // a[i+3] // (2) + // a[i+4] // (3) + // a[i+6] // max = max of all constants + // a[i+2] + // a[i+1] // min = min of all constants + // + // If x < 3: + // (1) a[i+x]: Leave unchanged + // (2) a[i+3]: Replace with a[i+max] = a[i+6]: i+x < i+3 <= i+6 -> (2) is covered + // (3) a[i+4]: Replace with a[i+min] = a[i+1]: i+1 < i+4 <= i+6 -> (3) and all following checks are covered + // Remove all other a[i+c] checks + // + // If x >= 3: + // (1) a[i+x]: Leave unchanged + // (2) a[i+3]: Replace with a[i+min] = a[i+1]: i+1 < i+3 <= i+x -> (2) is covered + // (3) a[i+4]: Replace with a[i+max] = a[i+6]: i+1 < i+4 <= i+6 -> (3) and all following checks are covered + // Remove all other a[i+c] checks + // + // We only need the top 2 range checks if x is the min or max of all constants. + // + // This, however, only works if the interval [i+min,i+max] is not larger than max_int (i.e. abs(max - min) < max_int): + // The theoretical max size of an array is max_int with: + // - Valid index space: [0,max_int-1] + // - Invalid index space: [max_int,-1] // max_int, min_int, min_int - 1 ..., -1 + // + // The size of the consecutive valid index space is smaller than the size of the consecutive invalid index space. + // If we choose min and max in such a way that: + // - abs(max - min) < max_int + // - i+max and i+min are inside the valid index space + // then all indices [i+min,i+max] must be in the valid index space. Otherwise, the invalid index space must be + // smaller than the valid index space which is never the case for any array size. + // + // Choosing a smaller array size only makes the valid index space smaller and the invalid index space larger and + // the argument above still holds. + // + // Note that the same optimization with the same maximal accepted interval size can also be found in C1. + const jlong maximum_number_of_min_max_interval_indices = (jlong)max_jint; // The top 3 range checks seen const int NRC =3; @@ -915,13 +955,18 @@ found_immediate_dominator = true; break; } - // Gather expanded bounds - off_lo = MIN2(off_lo,offset2); - off_hi = MAX2(off_hi,offset2); - // Record top NRC range checks - prev_checks[nb_checks%NRC].ctl = prev_dom; - prev_checks[nb_checks%NRC].off = offset2; - nb_checks++; + + // "x - y" -> must add one to the difference for number of elements in [x,y] + const jlong diff = (jlong)MIN2(offset2, off_lo) - (jlong)MAX2(offset2, off_hi); + if (ABS(diff) < maximum_number_of_min_max_interval_indices) { + // Gather expanded bounds + off_lo = MIN2(off_lo, offset2); + off_hi = MAX2(off_hi, offset2); + // Record top NRC range checks + prev_checks[nb_checks % NRC].ctl = prev_dom; + prev_checks[nb_checks % NRC].off = offset2; + nb_checks++; + } } } prev_dom = dom; diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.cpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.cpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -260,6 +260,49 @@ set_early_ctrl( n ); } +void PhaseIdealLoop::insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol) { + Node* new_predicate_proj = create_new_if_for_predicate(limit_check_proj, NULL, + Deoptimization::Reason_loop_limit_check); + Node* iff = new_predicate_proj->in(0); + assert(iff->Opcode() == Op_If, "bad graph shape"); + Node* conv = iff->in(1); + assert(conv->Opcode() == Op_Conv2B, "bad graph shape"); + Node* opaq = conv->in(1); + assert(opaq->Opcode() == Op_Opaque1, "bad graph shape"); + cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); + bol = _igvn.register_new_node_with_optimizer(bol); + set_subtree_ctrl(bol); + _igvn.replace_input_of(iff, 1, bol); + +#ifndef PRODUCT + // report that the loop predication has been actually performed + // for this loop + if (TraceLoopLimitCheck) { + tty->print_cr("Counted Loop Limit Check generated:"); + debug_only( bol->dump(2); ) + } +#endif +} + +static int check_stride_overflow(jlong final_correction, const TypeInt* limit_t) { + if (final_correction > 0) { + if (limit_t->_lo > (max_jint - final_correction)) { + return -1; + } + if (limit_t->_hi > (max_jint - final_correction)) { + return 1; + } + } else { + if (limit_t->_hi < (min_jint - final_correction)) { + return -1; + } + if (limit_t->_lo < (min_jint - final_correction)) { + return 1; + } + } + return 0; +} + //------------------------------is_counted_loop-------------------------------- bool PhaseIdealLoop::is_counted_loop( Node *x, IdealLoopTree *loop ) { PhaseGVN *gvn = &_igvn; @@ -463,51 +506,256 @@ assert(x->Opcode() == Op_Loop, "regular loops only"); C->print_method(PHASE_BEFORE_CLOOPS, 3); - Node *hook = new (C) Node(6); + Node* adjusted_limit = limit; if (LoopLimitCheck) { // =================================================== - // Generate loop limit check to avoid integer overflow - // in cases like next (cyclic loops): + // We can only convert this loop to a counted loop if we can guarantee that the iv phi will never overflow at runtime. + // This is an implicit assumption taken by some loop optimizations. We therefore must ensure this property at all cost. + // At this point, we've already excluded some trivial cases where an overflow could have been proven statically. + // But even though we cannot prove that an overflow will *not* happen, we still want to speculatively convert this loop + // to a counted loop. This can be achieved by adding additional iv phi overflow checks before the loop. If they fail, + // we trap and resume execution before the loop without having executed any iteration of the loop, yet. // - // for (i=0; i <= max_jint; i++) {} - // for (i=0; i < max_jint; i+=2) {} + // These additional iv phi overflow checks can be inserted as Loop Limit Check Predicates above the Loop Limit Check + // Parse Predicate which captures a JVM state just before the entry of the loop. If there is no such Parse Predicate, + // we cannot generate a Loop Limit Check Predicate and thus cannot speculatively convert the loop to a counted loop. // + // In the following, we only focus on int loops with stride > 0 to keep things simple. The argumentation and proof + // for stride < 0 is analogously. For long loops, we would replace max_int with max_long. // - // Limit check predicate depends on the loop test: // - // for(;i != limit; i++) --> limit <= (max_jint) - // for(;i < limit; i+=stride) --> limit <= (max_jint - stride + 1) - // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride ) + // The loop to be converted does not always need to have the often used shape: // + // i = init + // i = init loop: + // do { ... + // // ... equivalent i+=stride + // i+=stride <==> if (i < limit) + // } while (i < limit); goto loop + // exit: + // ... + // + // where the loop exit check uses the post-incremented iv phi and a '<'-operator. + // + // We could also have '<='-operator (or '>='-operator for negative strides) or use the pre-incremented iv phi value + // in the loop exit check: + // + // i = init + // loop: + // ... + // if (i <= limit) + // i+=stride + // goto loop + // exit: + // ... + // + // Let's define the following terms: + // - iv_pre_i: The pre-incremented iv phi before the i-th iteration. + // - iv_post_i: The post-incremented iv phi after the i-th iteration. + // + // The iv_pre_i and iv_post_i have the following relation: + // iv_pre_i + stride = iv_post_i + // + // When converting a loop to a counted loop, we want to have a canonicalized loop exit check of the form: + // iv_post_i < adjusted_limit + // + // If that is not the case, we need to canonicalize the loop exit check by using different values for adjusted_limit: + // (LE1) iv_post_i < limit: Already canonicalized. We can directly use limit as adjusted_limit. + // -> adjusted_limit = limit. + // (LE2) iv_post_i <= limit: + // iv_post_i < limit + 1 + // -> adjusted limit = limit + 1 + // (LE3) iv_pre_i < limit: + // iv_pre_i + stride < limit + stride + // iv_post_i < limit + stride + // -> adjusted_limit = limit + stride + // (LE4) iv_pre_i <= limit: + // iv_pre_i < limit + 1 + // iv_pre_i + stride < limit + stride + 1 + // iv_post_i < limit + stride + 1 + // -> adjusted_limit = limit + stride + 1 + // + // Note that: + // (AL) limit <= adjusted_limit. + // + // The following loop invariant has to hold for counted loops with n iterations (i.e. loop exit check true after n-th + // loop iteration) and a canonicalized loop exit check to guarantee that no iv_post_i over- or underflows: + // (INV) For i = 1..n, min_int <= iv_post_i <= max_int + // + // To prove (INV), we require the following two conditions/assumptions: + // (i): adjusted_limit - 1 + stride <= max_int + // (ii): init < limit + // + // If we can prove (INV), we know that there can be no over- or underflow of any iv phi value. We prove (INV) by + // induction by assuming (i) and (ii). + // + // Proof by Induction + // ------------------ + // > Base case (i = 1): We show that (INV) holds after the first iteration: + // min_int <= iv_post_1 = init + stride <= max_int + // Proof: + // First, we note that (ii) implies + // (iii) init <= limit - 1 + // max_int >= adjusted_limit - 1 + stride [using (i)] + // >= limit - 1 + stride [using (AL)] + // >= init + stride [using (iii)] + // >= min_int [using stride > 0, no underflow] + // Thus, no overflow happens after the first iteration and (INV) holds for i = 1. + // + // Note that to prove the base case we need (i) and (ii). + // + // > Induction Hypothesis (i = j, j > 1): Assume that (INV) holds after the j-th iteration: + // min_int <= iv_post_j <= max_int + // > Step case (i = j + 1): We show that (INV) also holds after the j+1-th iteration: + // min_int <= iv_post_{j+1} = iv_post_j + stride <= max_int + // Proof: + // If iv_post_j >= adjusted_limit: + // We exit the loop after the j-th iteration, and we don't execute the j+1-th iteration anymore. Thus, there is + // also no iv_{j+1}. Since (INV) holds for iv_j, there is nothing left to prove. + // If iv_post_j < adjusted_limit: + // First, we note that: + // (iv) iv_post_j <= adjusted_limit - 1 + // max_int >= adjusted_limit - 1 + stride [using (i)] + // >= iv_post_j + stride [using (iv)] + // >= min_int [using stride > 0, no underflow] + // + // Note that to prove the step case we only need (i). + // + // Thus, by assuming (i) and (ii), we proved (INV). + // + // + // It is therefore enough to add the following two Loop Limit Check Predicates to check assumptions (i) and (ii): + // + // (1) Loop Limit Check Predicate for (i): + // Using (i): adjusted_limit - 1 + stride <= max_int + // + // This condition is now restated to use limit instead of adjusted_limit: + // + // To prevent an overflow of adjusted_limit -1 + stride itself, we rewrite this check to + // max_int - stride + 1 >= adjusted_limit + // We can merge the two constants into + // canonicalized_correction = stride - 1 + // which gives us + // max_int - canonicalized_correction >= adjusted_limit + // + // To directly use limit instead of adjusted_limit in the predicate condition, we split adjusted_limit into: + // adjusted_limit = limit + limit_correction + // Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into: + // max_int - canonicalized_correction - limit_correction >= limit + // Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant: + // final_correction = canonicalized_correction + limit_correction + // which gives us: + // + // Final predicate condition: + // max_int - final_correction >= limit + // + // (2) Loop Limit Check Predicate for (ii): + // Using (ii): init < limit + // + // This Loop Limit Check Predicate is not required if we can prove at compile time that either: + // (2.1) type(init) < type(limit) + // In this case, we know: + // all possible values of init < all possible values of limit + // and we can skip the predicate. + // + // (2.2) init < limit is already checked before (i.e. found as a dominating check) + // In this case, we do not need to re-check the condition and can skip the predicate. + // This is often found for while- and for-loops which have the following shape: + // + // if (init < limit) { // Dominating test. Do not need the Loop Limit Check Predicate below. + // i = init; + // if (init >= limit) { trap(); } // Here we would insert the Loop Limit Check Predicate + // do { + // i += stride; + // } while (i < limit); + // } + // + // (2.3) init + stride <= max_int + // In this case, there is no overflow of the iv phi after the first loop iteration. + // In the proof of the base case above we showed that init + stride <= max_int by using assumption (ii): + // init < limit + // In the proof of the step case above, we did not need (ii) anymore. Therefore, if we already know at + // compile time that init + stride <= max_int then we have trivially proven the base case and that + // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii) + // again and can skip the predicate. + + + // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check. + const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != NULL) ? stride_con : 0; + + // Accounting for (LE2) and (LE4) where we use <= or >= in the loop exit check. + const bool includes_limit = (bt == BoolTest::le || bt == BoolTest::ge); + const jlong limit_correction_for_le_ge_exit_check = (includes_limit ? (stride_con > 0 ? 1 : -1) : 0); + + const jlong limit_correction = limit_correction_for_pre_iv_exit_check + limit_correction_for_le_ge_exit_check; + const jlong canonicalized_correction = stride_con + (stride_con > 0 ? -1 : 1); + const jlong final_correction = canonicalized_correction + limit_correction; + + int sov = check_stride_overflow(final_correction, limit_t); + + // If sov==0, limit's type always satisfies the condition, for + // example, when it is an array length. + if (sov != 0) { + if (sov < 0) { + return false; // Bailout: integer overflow is certain. + } + // (1) Loop Limit Check Predicate is required because we could not statically prove that + // limit + final_correction = adjusted_limit - 1 + stride <= max_int + ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check); + if (!limit_check_proj) { + // The Loop Limit Check Parse Predicate is not generated if this method trapped here before. +#ifdef ASSERT + if (TraceLoopLimitCheck) { + tty->print("missing loop limit check:"); + loop->dump_head(); + x->dump(1); + } +#endif + return false; + } - // Check if limit is excluded to do more precise int overflow check. - bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge); - int stride_m = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1)); - - // If compare points directly to the phi we need to adjust - // the compare so that it points to the incr. Limit have - // to be adjusted to keep trip count the same and the - // adjusted limit should be checked for int overflow. - if (phi_incr != NULL) { - stride_m += stride_con; - } + IfNode* check_iff = limit_check_proj->in(0)->as_If(); - if (limit->is_Con()) { - int limit_con = limit->get_int(); - if ((stride_con > 0 && limit_con > (max_jint - stride_m)) || - (stride_con < 0 && limit_con < (min_jint - stride_m))) { - // Bailout: it could be integer overflow. + if (!is_dominator(get_ctrl(limit), check_iff->in(0))) { return false; } - } else if ((stride_con > 0 && limit_t->_hi <= (max_jint - stride_m)) || - (stride_con < 0 && limit_t->_lo >= (min_jint - stride_m))) { - // Limit's type may satisfy the condition, for example, - // when it is an array length. - } else { - // Generate loop's limit check. - // Loop limit check predicate should be near the loop. + + Node* cmp_limit; + Node* bol; + + if (stride_con > 0) { + cmp_limit = new (C) CmpINode(limit, _igvn.intcon(max_jint - final_correction)); + bol = new (C) BoolNode(cmp_limit, BoolTest::le); + } else { + cmp_limit = new (C) CmpINode(limit, _igvn.intcon(min_jint - final_correction)); + bol = new (C) BoolNode(cmp_limit, BoolTest::ge); + } + + insert_loop_limit_check(limit_check_proj, cmp_limit, bol); + } + + // (2.3) + const bool init_plus_stride_could_overflow = + (stride_con > 0 && init_t->_hi > max_jint - stride_con) || + (stride_con < 0 && init_t->_lo < min_jint - stride_con); + // (2.1) + const bool init_gte_limit = (stride_con > 0 && init_t->_hi >= limit_t->_lo) || + (stride_con < 0 && init_t->_lo <= limit_t->_hi); + + if (init_gte_limit && // (2.1) + ((bt == BoolTest::ne || init_plus_stride_could_overflow) && // (2.3) + !has_dominating_loop_limit_check(init_trip, limit, stride_con, init_control))) { // (2.2) + // (2) Iteration Loop Limit Check Predicate is required because neither (2.1), (2.2), nor (2.3) holds. + // We use the following condition: + // - stride > 0: init < limit + // - stride < 0: init > limit + // + // This predicate is always required if we have a non-equal-operator in the loop exit check (where stride = 1 is + // a requirement). We transform the loop exit check by using a less-than-operator. By doing so, we must always + // check that init < limit. Otherwise, we could have a different number of iterations at runtime. + ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check); if (!limit_check_proj) { // The limit check predicate is not generated if this method trapped here before. @@ -520,41 +768,38 @@ #endif return false; } - IfNode* check_iff = limit_check_proj->in(0)->as_If(); + + if (!is_dominator(get_ctrl(limit), check_iff->in(0)) || + !is_dominator(get_ctrl(init_trip), check_iff->in(0))) { + return false; + } + Node* cmp_limit; Node* bol; if (stride_con > 0) { - cmp_limit = new (C) CmpINode(limit, _igvn.intcon(max_jint - stride_m)); - bol = new (C) BoolNode(cmp_limit, BoolTest::le); + cmp_limit = new (C) CmpINode(init_trip, limit); + bol = new (C) BoolNode(cmp_limit, BoolTest::lt); } else { - cmp_limit = new (C) CmpINode(limit, _igvn.intcon(min_jint - stride_m)); - bol = new (C) BoolNode(cmp_limit, BoolTest::ge); + cmp_limit = new (C) CmpINode(init_trip, limit); + bol = new (C) BoolNode(cmp_limit, BoolTest::gt); } - cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); - bol = _igvn.register_new_node_with_optimizer(bol); - set_subtree_ctrl(bol); - - // Replace condition in original predicate but preserve Opaque node - // so that previous predicates could be found. - assert(check_iff->in(1)->Opcode() == Op_Conv2B && - check_iff->in(1)->in(1)->Opcode() == Op_Opaque1, ""); - Node* opq = check_iff->in(1)->in(1); - _igvn.hash_delete(opq); - opq->set_req(1, bol); - // Update ctrl. - set_ctrl(opq, check_iff->in(0)); - set_ctrl(check_iff->in(1), check_iff->in(0)); -#ifndef PRODUCT - // report that the loop predication has been actually performed - // for this loop - if (TraceLoopLimitCheck) { - tty->print_cr("Counted Loop Limit Check generated:"); - debug_only( bol->dump(2); ) + insert_loop_limit_check(limit_check_proj, cmp_limit, bol); + } + + if (bt == BoolTest::ne) { + // Now we need to canonicalize the loop condition if it is 'ne'. + assert(stride_con == 1 || stride_con == -1, "simple increment only - checked before"); + if (stride_con > 0) { + // 'ne' can be replaced with 'lt' only when init < limit. This is ensured by the inserted predicate above. + bt = BoolTest::lt; + } else { + assert(stride_con < 0, "must be"); + // 'ne' can be replaced with 'gt' only when init > limit. This is ensured by the inserted predicate above. + bt = BoolTest::gt; } -#endif } if (phi_incr != NULL) { @@ -567,26 +812,15 @@ // is converted to // i = init; do {} while(++i < limit+1); // - limit = gvn->transform(new (C) AddINode(limit, stride)); + adjusted_limit = gvn->transform(new (C) AddINode(limit, stride)); } - // Now we need to canonicalize loop condition. - if (bt == BoolTest::ne) { - assert(stride_con == 1 || stride_con == -1, "simple increment only"); - // 'ne' can be replaced with 'lt' only when init < limit. - if (stride_con > 0 && init_t->_hi < limit_t->_lo) - bt = BoolTest::lt; - // 'ne' can be replaced with 'gt' only when init > limit. - if (stride_con < 0 && init_t->_lo > limit_t->_hi) - bt = BoolTest::gt; - } - - if (incl_limit) { + if (includes_limit) { // The limit check guaranties that 'limit <= (max_jint - stride)' so // we can convert 'i <= limit' to 'i < limit+1' since stride != 0. // Node* one = (stride_con > 0) ? gvn->intcon( 1) : gvn->intcon(-1); - limit = gvn->transform(new (C) AddINode(limit, one)); + adjusted_limit = gvn->transform(new (C) AddINode(adjusted_limit, one)); if (bt == BoolTest::le) bt = BoolTest::lt; else if (bt == BoolTest::ge) @@ -594,10 +828,11 @@ else ShouldNotReachHere(); } - set_subtree_ctrl( limit ); + set_subtree_ctrl(adjusted_limit); } else { // LoopLimitCheck + Node *hook = new (C) Node(6); // If compare points to incr, we are ok. Otherwise the compare // can directly point to the phi; in this case adjust the compare so that // it points to the incr by adjusting the limit. @@ -691,6 +926,11 @@ limit = gvn->transform(new (C) AddINode(span,init_trip)); set_subtree_ctrl( limit ); + adjusted_limit = limit; + + // Free up intermediate goo + _igvn.remove_dead_node(hook); + } // LoopLimitCheck if (!UseCountedLoopSafepoints) { @@ -728,7 +968,7 @@ } cmp = cmp->clone(); cmp->set_req(1,incr); - cmp->set_req(2,limit); + cmp->set_req(2, adjusted_limit); cmp = _igvn.register_new_node_with_optimizer(cmp); set_ctrl(cmp, iff->in(0)); @@ -802,9 +1042,6 @@ } } - // Free up intermediate goo - _igvn.remove_dead_node(hook); - #ifdef ASSERT assert(l->is_valid_counted_loop(), "counted loop shape is messed up"); assert(l == loop->_head && l->phi() == phi && l->loopexit() == lex, "" ); @@ -821,6 +1058,37 @@ return true; } +// Check if there is a dominating loop limit check of the form 'init < limit' starting at the loop entry. +// If there is one, then we do not need to create an additional Loop Limit Check Predicate. +bool PhaseIdealLoop::has_dominating_loop_limit_check(Node* init_trip, Node* limit, const int stride_con, + Node* loop_entry) { + // Eagerly call transform() on the Cmp and Bool node to common them up if possible. This is required in order to + // successfully find a dominated test with the If node below. + Node* cmp_limit; + Node* bol; + if (stride_con > 0) { + cmp_limit = _igvn.transform(new (C) CmpINode(init_trip, limit)); + bol = _igvn.transform(new (C) BoolNode(cmp_limit, BoolTest::lt)); + } else { + cmp_limit = _igvn.transform(new (C) CmpINode(init_trip, limit)); + bol = _igvn.transform(new (C) BoolNode(cmp_limit, BoolTest::gt)); + } + + // Check if there is already a dominating init < limit check. If so, we do not need a Loop Limit Check Predicate. + IfNode* iff = new (C) IfNode(loop_entry, bol, PROB_MIN, COUNT_UNKNOWN); + // Also add fake IfProj nodes in order to call transform() on the newly created IfNode. + IfFalseNode* if_false = new (C) IfFalseNode(iff); + IfTrueNode* if_true = new (C) IfTrueNode(iff); + Node* dominated_iff = _igvn.transform(iff); + // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node). + const bool found_dominating_test = dominated_iff != NULL && dominated_iff->Opcode() == Op_ConI; + + // Kill the If with its projections again in the next IGVN round by cutting it off from the graph. + _igvn.replace_input_of(iff, 0, C->top()); + _igvn.replace_input_of(iff, 1, C->top()); + return found_dominating_test; +} + //----------------------exact_limit------------------------------------------- Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) { assert(loop->_head->is_CountedLoop(), ""); diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.hpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.hpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.hpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/loopnode.hpp 2024-01-11 01:53:23.000000000 +0000 @@ -896,6 +896,10 @@ // Create a new if above the uncommon_trap_if_pattern for the predicate to be promoted ProjNode* create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry, Deoptimization::DeoptReason reason); + void insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol); + bool has_dominating_loop_limit_check(Node* init_trip, Node* limit, int stride_con, + Node* loop_entry); + void register_control(Node* n, IdealLoopTree *loop, Node* pred); // Clone loop predicates to cloned loops (peeled, unswitched) diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/phaseX.hpp openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/phaseX.hpp --- openjdk-8-8u392-ga/=unpacked-tar2=/src/share/vm/opto/phaseX.hpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/src/share/vm/opto/phaseX.hpp 2024-01-11 01:53:23.000000000 +0000 @@ -433,9 +433,6 @@ protected: - // Idealize new Node 'n' with respect to its inputs and its value - virtual Node *transform( Node *a_node ); - // Warm up hash table, type table and initial worklist void init_worklist( Node *a_root ); @@ -449,6 +446,9 @@ PhaseIterGVN( PhaseGVN *gvn ); // Used after Parser PhaseIterGVN( PhaseIterGVN *igvn, const char *dummy ); // Used after +VerifyOpto + // Idealize new Node 'n' with respect to its inputs and its value + virtual Node *transform( Node *a_node ); + virtual PhaseIterGVN *is_IterGVN() { return this; } Unique_Node_List _worklist; // Iterative worklist diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/test/TEST.ROOT openjdk-8-8u402-ga/=unpacked-tar2=/test/TEST.ROOT --- openjdk-8-8u392-ga/=unpacked-tar2=/test/TEST.ROOT 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/test/TEST.ROOT 2024-01-11 01:53:23.000000000 +0000 @@ -37,3 +37,7 @@ requires.properties=sun.arch.data.model \ vm.flavor \ vm.bits + +# Path to libraries in the topmost test directory. This is needed so @library +# does not need ../../ notation to reach them +external.lib.roots = ../../ diff -Nru openjdk-8-8u392-ga/=unpacked-tar2=/test/runtime/memory/ReserveMemory.java openjdk-8-8u402-ga/=unpacked-tar2=/test/runtime/memory/ReserveMemory.java --- openjdk-8-8u392-ga/=unpacked-tar2=/test/runtime/memory/ReserveMemory.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar2=/test/runtime/memory/ReserveMemory.java 2024-01-11 01:53:23.000000000 +0000 @@ -21,10 +21,12 @@ * questions. */ +// Aix commits on touch, so this test won't work. /* * @test * @key regression * @bug 8012015 + * @requires !(os.family == "aix") * @summary Make sure reserved (but uncommitted) memory is not accessible * @library /testlibrary /testlibrary/whitebox * @build ReserveMemory @@ -37,14 +39,6 @@ import sun.hotspot.WhiteBox; public class ReserveMemory { - private static boolean isWindows() { - return System.getProperty("os.name").toLowerCase().startsWith("win"); - } - - private static boolean isOsx() { - return System.getProperty("os.name").toLowerCase().startsWith("mac"); - } - public static void main(String args[]) throws Exception { if (args.length > 0) { WhiteBox.getWhiteBox().readReservedMemory(); @@ -61,9 +55,9 @@ "test"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); - if (isWindows()) { + if (Platform.isWindows()) { output.shouldContain("EXCEPTION_ACCESS_VIOLATION"); - } else if (isOsx()) { + } else if (Platform.isOSX()) { output.shouldContain("SIGBUS"); } else { output.shouldContain("SIGSEGV"); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/README openjdk-8-8u402-ga/=unpacked-tar3=/README --- openjdk-8-8u392-ga/=unpacked-tar3=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -README: - This file should be located at the top of the jdk Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - -Simple Build Instructions: - - 1. Download and install a JDK 6 from - http://java.sun.com/javase/downloads/index.jsp - Set the environment variable ALT_BOOTDIR to the location of this JDK 6. - - 2. Either download and install the latest JDK7 from - http://download.java.net/openjdk/jdk7/, or build your own complete - OpenJDK7 by using the top level Makefile in the OpenJDK Mercurial forest. - Set the environment variable ALT_JDK_IMPORT_PATH to the location of - this latest JDK7 or OpenJDK7 build. - - 3. Check the sanity of doing a build with the current machine: - cd make && gnumake sanity - See README-builds.html if you run into problems. - - 4. Do a partial build of the jdk: - cd make && gnumake all - - 5. Construct the images: - cd make && gnumake images - The resulting JDK image should be found in build/*/j2sdk-image - - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/CompileLaunchers.gmk openjdk-8-8u402-ga/=unpacked-tar3=/make/CompileLaunchers.gmk --- openjdk-8-8u392-ga/=unpacked-tar3=/make/CompileLaunchers.gmk 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/CompileLaunchers.gmk 2024-01-11 01:53:23.000000000 +0000 @@ -281,10 +281,17 @@ $(eval $(call SetupLauncher,jarsigner, \ -DJAVA_ARGS='{ "-J-ms8m"$(COMMA) "sun.security.tools.jarsigner.Main"$(COMMA) }')) +# On s390 zero, run javac with larger stack +ifeq ($(OPENJDK_TARGET_CPU), s390x) +JAVAC_ARGS := '{ "-J-ms8m"$(COMMA) "-J-Xss3m"$(COMMA) "com.sun.tools.javac.Main"$(COMMA) }' +else +JAVAC_ARGS := '{ "-J-ms8m"$(COMMA) "com.sun.tools.javac.Main"$(COMMA) }' +endif + $(eval $(call SetupLauncher,javac, \ -DEXPAND_CLASSPATH_WILDCARDS \ -DNEVER_ACT_AS_SERVER_CLASS_MACHINE \ - -DJAVA_ARGS='{ "-J-ms8m"$(COMMA) "com.sun.tools.javac.Main"$(COMMA) }')) + -DJAVA_ARGS=$(JAVAC_ARGS))) ifeq ($(ENABLE_SJAVAC), yes) $(eval $(call SetupLauncher,sjavac, \ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicertcseccrootg5 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicertcseccrootg5 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicertcseccrootg5 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicertcseccrootg5 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,21 @@ +Owner: CN=DigiCert CS ECC P384 Root G5, O="DigiCert, Inc.", C=US +Issuer: CN=DigiCert CS ECC P384 Root G5, O="DigiCert, Inc.", C=US +Serial number: 3698fe712d519f3ced0fdb7b1643011 +Valid from: Fri Jan 15 00:00:00 GMT 2021 until: Sun Jan 14 23:59:59 GMT 2046 +Signature algorithm name: SHA384withECDSA +Subject Public Key Algorithm: 384-bit EC (secp384r1) key +Version: 3 +-----BEGIN CERTIFICATE----- +MIICFjCCAZ2gAwIBAgIQA2mP5xLVGfPO0P23sWQwETAKBggqhkjOPQQDAzBNMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMTHERp +Z2lDZXJ0IENTIEVDQyBQMzg0IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcNNDYw +MTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIElu +Yy4xJTAjBgNVBAMTHERpZ2lDZXJ0IENTIEVDQyBQMzg0IFJvb3QgRzUwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAAR/FK2Ftpf9AiE1TWDoOJOTmz0FEG2v0/7v+rv7c5nz +7DISjcdouIveiaKIVHeNuyF+M5VWlgno1YyhBLibbhkAYuhCKKZYN4QZVSZ7Mzdn +8ppyraGurgBCPBx+uHqeIZyjQjBAMB0GA1UdDgQWBBTwjJhxOThlwjobphdmHcjt +Zd6SNjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AwNnADBkAjAjb+EAGSZQ5EYgZYs3p8/rBuHMMskqoewyDXOiHgIcNWEqTmmrOXft +l4jAfWvqid0CMEPx0VijdT6Gm7ZVEYsX9z3+CmnFf07GdRtalMvqERHGCCKI3tB6 +oqV56OMhp80Tsw== +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicertcsrsarootg5 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicertcsrsarootg5 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicertcsrsarootg5 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicertcsrsarootg5 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,38 @@ +Owner: CN=DigiCert CS RSA4096 Root G5, O="DigiCert, Inc.", C=US +Issuer: CN=DigiCert CS RSA4096 Root G5, O="DigiCert, Inc.", C=US +Serial number: 6cee131be6d55c807f7c0c7fb44e620 +Valid from: Fri Jan 15 00:00:00 GMT 2021 until: Sun Jan 14 23:59:59 GMT 2046 +Signature algorithm name: SHA384withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIQBs7hMb5tVcgH98DH+0TmIDANBgkqhkiG9w0BAQwFADBM +MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJDAiBgNVBAMT +G0RpZ2lDZXJ0IENTIFJTQTQwOTYgUm9vdCBHNTAeFw0yMTAxMTUwMDAwMDBaFw00 +NjAxMTQyMzU5NTlaMEwxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5EaWdpQ2VydCwg +SW5jLjEkMCIGA1UEAxMbRGlnaUNlcnQgQ1MgUlNBNDA5NiBSb290IEc1MIICIjAN +BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtjNzgNhiA3AULBEcOV58rnyDhh3+ +Ji9MJK2L6oNfqbw9W/wLmEwCRzDs4v7s6DRbZl6/O9cspiX/jFmz3+rafCnZRlBy +CB1u0RsK3R/NmYn6Dw9zxOGcHXUyzW+X2ipqlbJsyQnQ6gt7fRcGSZnv1t7gyFPU +rsZ38Ya7Ixy4wN9Z94590e+C5iaLWji1/3XVstlPCfM3iFDaEaSKFBTRUwQAffNq +RBj+UHAyBxyomg46HcUKH24LJmm3PKJXcCyG+kxulalYQ7msEtb/P+3XQxdrTM6e +xJCr//oQUJqjkFfW54wQrp8WGs81HX/Xdu2KnDWnKLinXSH8MDfd3ggZTxXG56ba +kEeO95RTTI5TAr79meXqhtCvAwLTm6qT8asojiAB/0z7zLcpQPWHpBITBR9DbtdR +UJ84tCDtFwkSj8y5Ga+fzb5pEdOvVRBtF4Z5llLGsgCd5a84sDX0iGuPDgQ9fO6v +zdNqEErGzYbKIj2hSlz7Dv+I31xip8C5HtmsbH44N/53kyXChYpPtTcGWgaBFPHO +lJ2ZkeoyWs5nPW4EZq0MTy2jLvee9Xid9wr9fo/jQopVlrzxnzct/J5flf6MGBv8 +jv1LkK/XA2gSY6zik6eiywTlT2TOA/rGFJ/Zi+jM1GKMa+QALBmfGgbGMYFU+1Mk +mq9Vmbqdda64wt0CAwEAAaNCMEAwHQYDVR0OBBYEFGgBk7HSSkBCaZRGLBxaiKkl +tEdPMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB +DAUAA4ICAQCS/O64AnkXAlF9IcVJZ6ek8agkOOsMaOpaQmuc9HPBaUotszcFUEKY +kp4GeSwuBpn2798roM2zkgGDtaDLJ7U8IxqYSaLsLZmlWUOs0rGT1lfXHLyT1sZA +4bNvGVW3E9flQzOktavL2sExZA101iztw41u67uvGUdhYS3A9AW5b3jcOvdCQGVT +kb2ZDZOSVKapN1krm8uZxrw99wSE8JQzHQ+CWjnLLkXDKBmjspuYyPwxa2CP9umG +KLzgPH10XRaJW2kkxxCLxEu7Nk/UWT/DsKSRmfgu0UoBnfWIEu+/WhFqWU9Za1pn +84+0Ew/A2C89KHKqGX8RfWpbn5XnX7eUT/E+oVr/Lcyd3yd3jzJzHGcKdvP6XLG/ +vB29DCibsscXZwszD8O9Ntz7ukILq+2Ew2LWhBapsQdrqW7uxs/msEQpwvCzYYAq +i2/SFFwlh1Rk86RMwaH4p2vq/uo6/HnbDo/cxvPJ1Gze6YOhjh0i7Mk6sgB73Dun +Qhp/3IupET2Op8Agb10JXUNE5o9mzKlbB/Hvm3oOs1ThlP0OLMaT11X9cZg1uAlK +/8YpKCz2Ui3bFBiSJ+IWfozK1GG+goeR65g3P79fXXc/NKwbOEOraHKZMh46Ghml +ozhMI9ej58zVKpIXkAtaS70WvfuGauKJmezkoFUYyaMIHxPgMghy0A== +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicerttlseccrootg5 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicerttlseccrootg5 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicerttlseccrootg5 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicerttlseccrootg5 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,21 @@ +Owner: CN=DigiCert TLS ECC P384 Root G5, O="DigiCert, Inc.", C=US +Issuer: CN=DigiCert TLS ECC P384 Root G5, O="DigiCert, Inc.", C=US +Serial number: 9e09365acf7d9c8b93e1c0b042a2ef3 +Valid from: Fri Jan 15 00:00:00 GMT 2021 until: Sun Jan 14 23:59:59 GMT 2046 +Signature algorithm name: SHA384withECDSA +Subject Public Key Algorithm: 384-bit EC (secp384r1) key +Version: 3 +-----BEGIN CERTIFICATE----- +MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp +Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2 +MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ +bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS +7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp +0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS +B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ +LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4 +DXZDjC5Ty3zfDBeWUA== +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicerttlsrsarootg5 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicerttlsrsarootg5 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/digicerttlsrsarootg5 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/digicerttlsrsarootg5 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,38 @@ +Owner: CN=DigiCert TLS RSA4096 Root G5, O="DigiCert, Inc.", C=US +Issuer: CN=DigiCert TLS RSA4096 Root G5, O="DigiCert, Inc.", C=US +Serial number: 8f9b478a8fa7eda6a333789de7ccf8a +Valid from: Fri Jan 15 00:00:00 GMT 2021 until: Sun Jan 14 23:59:59 GMT 2046 +Signature algorithm name: SHA384withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN +MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT +HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN +NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs +IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+ +ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0 +2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp +wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM +pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD +nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po +sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx +Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd +Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX +KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe +XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL +tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv +TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN +AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw +GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H +PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF +O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ +REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik +AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv +/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+ +p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw +MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF +qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK +ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+ +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsigneccrootcag3 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsigneccrootcag3 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsigneccrootcag3 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsigneccrootcag3 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,22 @@ +Owner: CN=emSign ECC Root CA - G3, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign ECC Root CA - G3, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 3cf607a968700eda8b84 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA384withECDSA +Subject Public Key Algorithm: 384-bit EC (secp384r1) key +Version: 3 +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag1 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag1 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag1 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag1 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,29 @@ +Owner: CN=emSign Root CA - G1, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign Root CA - G1, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 31f5e4620c6c58edd6d8 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA256withRSA +Subject Public Key Algorithm: 2048-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag2 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag2 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag2 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/emsignrootcag2 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,39 @@ +Owner: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 864dbf0fe35ed77d8ed8 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA384withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIFlTCCA32gAwIBAgILAIZNvw/jXtd9jtgwDQYJKoZIhvcNAQEMBQAwZzELMAkG +A1UEBhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEg +VGVjaG5vbG9naWVzIExpbWl0ZWQxHDAaBgNVBAMTE2VtU2lnbiBSb290IENBIC0g +RzIwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBnMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBHMjCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMNwGIWW2kHfHK+sXTNwxF07K+IV +ySTuyFM2r1v002wUfcdT+zs5OM5QbMYFFnedXQI6gCFLsjKrcaej48Zt37OyEb3i +aPs7CsP4kAyTwzKH9aZe6gXYHrJq40/ZVMNcQVI2PcIp40B/SAN2gUZ+ZaUtIOvV +jEx26/ebNaXRIsthlkOG/caB+QRwDw1tl7338Zlv0M2oTBUy4B3e7dGP5pgXH71M +jqHPCoNo+xv9f0NTBT+hUDa8h8wUtcGQq9CDeJTpjWcD2bP2AMdVG6oVpMAUeUzo +cCyglvtFdUMjggxBbw4qhau1HXPG8Ot9hwL7ZMi8tkTzrvUIxxb8G9LF/7kKeCE7 +tGZaVzDTnXuifl3msR4ErHsQ4P7lVu2AIjIAhrAXoedDidb7pMcf7TABdrYUT1Jo +G/AiK+J9jO6GTjeADD4LMDSBZhHMuBK/PJ/g0kGBt+/C1L+/HURzQhJkMlRnM6Rv +XoCtfKopSlns5trZmTi971Wjbn88QXP61lGpBCUPwCjs7rpOYvSUJtI+lcbF+37q +kIqOXYkVT3cupDSpw+H89kFtj5GKY+Xny4LxY+3IvDIRiyd6ky1DPj713DI0yqve +EpsIr3A0PdwuyUI7CS1jg0NnGFT6Xxyr0xB+VDt83FJYW8v16k2pbaQ4kVxA3aXd +X9dZYyVR1S59KM75AgMBAAGjQjBAMB0GA1UdDgQWBBTt7E1FYRgo57MjKBEcTaUn +DV7s9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B +AQwFAAOCAgEACFC/ilQg8KTCVBxFJW/sazomkS0kNYbEIZg4B3obqwsJ7SX98z8Z +gfzBpz0nYClwwJjWbFN1R2zY8pCEot6/dgmA8Vbq0GxhwPM5YN/SZquNyRIxO3cU +dlAcwf+vSezdVCf9wOzvSAF3q0a5ljvbdbNJNpfScQVp7UUd5sBsZk8jXO1KQ/go +/Vf/GDPnrIFmxpAIGE3sgnO8lAv9FzUaAeuv7HWe47xN9J7+bQzF93yHuIXACPTL +pQHhg2zMv5C7BAbuDHfbj1Cu294Z832yhSfBcziWGskOvl3es2EcHytbS9c9P+0z +Mpka7zGC1FHrvLb/FoduH86TeZt0QjZ6pcplNzoaxDnDvzTJ6CC2Eny+qH/APFCu +VUv5/wjwF+HPm8Pup2ARj9cEp92+0qcerfHacNq5hMeGZdbA/dzdUR/5z5zXdxAk +nl8mcfGb0eMNSTXQmmB/i4AecNnr72uYjzlaXUGYN7Nrb6XouG0pnh0/BBtWWp0U +ShIPpWEAqs7RJBj6+1ZUYXZ4ObrCw962DxhN2p19Hxw9LtuUUcLqqTPrFXYvwO4t +ouj7KJnAkaTUfXGdEaFVtFig1EA30WzJY2X1vAQ7hVnniCjgaXAGqjsU6sklNM9n +xDx5rFCCCEtj9Kh8UHjGK2QqgP5kwgttjOApQMaCoezMfK4KD7WpOXU= +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/letsencryptisrgx2 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/letsencryptisrgx2 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/letsencryptisrgx2 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/letsencryptisrgx2 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,21 @@ +Owner: CN=ISRG Root X2, O=Internet Security Research Group, C=US +Issuer: CN=ISRG Root X2, O=Internet Security Research Group, C=US +Serial number: 41d29dd172eaeea780c12c6ce92f8752 +Valid from: Fri Sep 04 00:00:00 GMT 2020 until: Mon Sep 17 16:00:00 GMT 2040 +Signature algorithm name: SHA384withECDSA +Subject Public Key Algorithm: 384-bit EC (secp384r1) key +Version: 3 +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/teliarootcav2 openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/teliarootcav2 --- openjdk-8-8u392-ga/=unpacked-tar3=/make/data/cacerts/teliarootcav2 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/make/data/cacerts/teliarootcav2 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,39 @@ +Owner: CN=Telia Root CA v2, O=Telia Finland Oyj, C=FI +Issuer: CN=Telia Root CA v2, O=Telia Finland Oyj, C=FI +Serial number: 1675f27d6fe7ae3e4acbe095b059e +Valid from: Thu Nov 29 11:55:54 GMT 2018 until: Sun Nov 29 11:55:54 GMT 2043 +Signature algorithm name: SHA256withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx +CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE +AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1 +NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ +MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq +AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9 +vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9 +lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD +n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT +7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o +6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC +TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6 +WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R +DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI +pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj +YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy +rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ +8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi +0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM +A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS +SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K +TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF +6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er +3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt +Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT +VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW +ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA +rBPuUBQemMc= +-----END CERTIFICATE----- diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/com/sun/crypto/provider/RSACipher.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/com/sun/crypto/provider/RSACipher.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/com/sun/crypto/provider/RSACipher.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/com/sun/crypto/provider/RSACipher.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,6 +98,7 @@ // cipher parameter for OAEP padding and TLS RSA premaster secret private AlgorithmParameterSpec spec = null; + private boolean forTlsPremasterSecret = false; // buffer for the data private byte[] buffer; @@ -290,6 +291,7 @@ } spec = params; + forTlsPremasterSecret = true; this.random = random; // for TLS RSA premaster secret } int blockType = (mode <= MODE_DECRYPT) ? RSAPadding.PAD_BLOCKTYPE_2 @@ -353,21 +355,38 @@ switch (mode) { case MODE_SIGN: paddingCopy = padding.pad(buffer, 0, bufOfs); - result = RSACore.rsa(paddingCopy, privateKey, true); + if (paddingCopy != null) { + result = RSACore.rsa(paddingCopy, privateKey, true); + } else { + throw new BadPaddingException("Padding error in signing"); + } break; case MODE_VERIFY: byte[] verifyBuffer = RSACore.convert(buffer, 0, bufOfs); paddingCopy = RSACore.rsa(verifyBuffer, publicKey); result = padding.unpad(paddingCopy); + if (result == null) { + throw new BadPaddingException + ("Padding error in verification"); + } break; case MODE_ENCRYPT: paddingCopy = padding.pad(buffer, 0, bufOfs); - result = RSACore.rsa(paddingCopy, publicKey); + if (paddingCopy != null) { + result = RSACore.rsa(paddingCopy, publicKey); + } else { + throw new BadPaddingException + ("Padding error in encryption"); + } break; case MODE_DECRYPT: byte[] decryptBuffer = RSACore.convert(buffer, 0, bufOfs); paddingCopy = RSACore.rsa(decryptBuffer, privateKey, false); result = padding.unpad(paddingCopy); + if (result == null && !forTlsPremasterSecret) { + throw new BadPaddingException + ("Padding error in decryption"); + } break; default: throw new AssertionError("Internal error"); @@ -376,9 +395,9 @@ } finally { Arrays.fill(buffer, 0, bufOfs, (byte)0); bufOfs = 0; - if (paddingCopy != null // will not happen + if (paddingCopy != null && paddingCopy != buffer // already cleaned - && paddingCopy != result) { // DO NOT CLEAN, THIS IS RESULT! + && paddingCopy != result) { // DO NOT CLEAN, THIS IS RESULT Arrays.fill(paddingCopy, (byte)0); } } @@ -452,26 +471,22 @@ boolean isTlsRsaPremasterSecret = algorithm.equals("TlsRsaPremasterSecret"); - Exception failover = null; byte[] encoded = null; update(wrappedKey, 0, wrappedKey.length); try { encoded = doFinal(); - } catch (BadPaddingException e) { - if (isTlsRsaPremasterSecret) { - failover = e; - } else { - throw new InvalidKeyException("Unwrapping failed", e); - } - } catch (IllegalBlockSizeException e) { - // should not occur, handled with length check above + } catch (BadPaddingException | IllegalBlockSizeException e) { + // BadPaddingException cannot happen for TLS RSA unwrap. + // In that case, padding error is indicated by returning null. + // IllegalBlockSizeException cannot happen in any case, + // because of the length check above. throw new InvalidKeyException("Unwrapping failed", e); } try { if (isTlsRsaPremasterSecret) { - if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) { + if (!forTlsPremasterSecret) { throw new IllegalStateException( "No TlsRsaPremasterSecretParameterSpec specified"); } @@ -480,7 +495,7 @@ encoded = KeyUtil.checkTlsPreMasterSecretKey( ((TlsRsaPremasterSecretParameterSpec) spec).getClientVersion(), ((TlsRsaPremasterSecretParameterSpec) spec).getServerVersion(), - random, encoded, (failover != null)); + random, encoded, encoded == null); } return ConstructKeys.constructKey(encoded, algorithm, type); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/com/sun/media/sound/JARSoundbankReader.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/com/sun/media/sound/JARSoundbankReader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/com/sun/media/sound/JARSoundbankReader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/com/sun/media/sound/JARSoundbankReader.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; +import java.security.AccessController; import java.util.ArrayList; import java.util.Objects; import javax.sound.midi.InvalidMidiDataException; @@ -38,6 +39,7 @@ import javax.sound.midi.spi.SoundbankReader; import sun.reflect.misc.ReflectUtil; +import sun.security.action.GetBooleanAction; /** * JarSoundbankReader is used to read soundbank object from jar files. @@ -46,12 +48,15 @@ */ public final class JARSoundbankReader extends SoundbankReader { - /* - * Name of the system property that enables the Jar soundbank loading - * true if jar sound bank is allowed to be loaded - * default is false + /** + * Value of the system property that enables the Jar soundbank loading + * {@code true} if jar sound bank is allowed to be loaded default is + * {@code false}. */ - private final static String JAR_SOUNDBANK_ENABLED = "jdk.sound.jarsoundbank"; + @SuppressWarnings("removal") + private static final boolean JAR_SOUNDBANK_ENABLED = + AccessController.doPrivileged( + new GetBooleanAction("jdk.sound.jarsoundbank")); private static boolean isZIP(URL url) { boolean ok = false; @@ -77,7 +82,7 @@ public Soundbank getSoundbank(URL url) throws InvalidMidiDataException, IOException { Objects.requireNonNull(url); - if (!Boolean.getBoolean(JAR_SOUNDBANK_ENABLED) || !isZIP(url)) + if (!JAR_SOUNDBANK_ENABLED || !isZIP(url)) return null; ArrayList soundbanks = new ArrayList(); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/java/util/jar/JarFile.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/java/util/jar/JarFile.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/java/util/jar/JarFile.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/java/util/jar/JarFile.java 2024-01-11 01:53:23.000000000 +0000 @@ -436,7 +436,9 @@ throw new IOException("Unsupported size: " + uncompressedSize + " for JarEntry " + ze.getName() + ". Allowed max size: " + - SignatureFileVerifier.MAX_SIG_FILE_SIZE + " bytes"); + SignatureFileVerifier.MAX_SIG_FILE_SIZE + " bytes. " + + "You can use the jdk.jar.maxSignatureFileSize " + + "system property to increase the default value."); } int len = (int)uncompressedSize; byte[] b = IOUtils.readAllBytes(is); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/javax/security/auth/kerberos/package-info.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/javax/security/auth/kerberos/package-info.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/javax/security/auth/kerberos/package-info.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/javax/security/auth/kerberos/package-info.java 2024-01-11 01:53:23.000000000 +0000 @@ -48,6 +48,12 @@ * {@code /lib/security} and failing that, in an OS-specific * location.

* + * The {@code krb5.conf} file is formatted in the Windows INI file style, + * which contains a series of relations grouped into different sections. + * Each relation contains a key and a value, the value can be an arbitrary + * string or a boolean value. A boolean value can be one of "true", "false", + * "yes", or "no", case-insensitive.

+ * * @since JDK1.4 */ package javax.security.auth.kerberos; diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java 2024-01-11 01:53:23.000000000 +0000 @@ -312,7 +312,6 @@ } signature.initSign((PrivateKey)key); LOG.debug("Signature provider: {}", signature.getProvider()); - LOG.debug("Signing with key: {}", key); LOG.debug("JCA Algorithm: {}", getJCAAlgorithm()); try (SignerOutputStream outputStream = new SignerOutputStream(signature)) { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/Config.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/Config.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/Config.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/Config.java 2024-01-11 01:53:23.000000000 +0000 @@ -450,23 +450,6 @@ } /** - * Gets the boolean value for the specified keys. - * @param keys the keys - * @return the boolean value, false is returned if it cannot be - * found or the value is not "true" (case insensitive). - * @throw IllegalArgumentException if any of the keys is illegal - * @see #get(java.lang.String[]) - */ - public boolean getBooleanValue(String... keys) { - String val = get(keys); - if (val != null && val.equalsIgnoreCase("true")) { - return true; - } else { - return false; - } - } - - /** * Parses a string to an integer. The convertible strings include the * string representations of positive integers, negative integers, and * hex decimal integers. Valid inputs are, e.g., -1234, +1234, @@ -474,7 +457,7 @@ * * @param input the String to be converted to an Integer. * @return an numeric value represented by the string - * @exception NumberFormationException if the String does not contain a + * @exception NumberFormatException if the String does not contain a * parsable integer. */ private int parseIntValue(String input) throws NumberFormatException { @@ -1060,20 +1043,13 @@ * use addresses if "no_addresses" or "noaddresses" is set to false */ public boolean useAddresses() { - boolean useAddr = false; - // use addresses if "no_addresses" is set to false - String value = get("libdefaults", "no_addresses"); - useAddr = (value != null && value.equalsIgnoreCase("false")); - if (useAddr == false) { - // use addresses if "noaddresses" is set to false - value = get("libdefaults", "noaddresses"); - useAddr = (value != null && value.equalsIgnoreCase("false")); - } - return useAddr; + return getBooleanObject("libdefaults", "no_addresses") == Boolean.FALSE || + getBooleanObject("libdefaults", "noaddresses") == Boolean.FALSE; } /** - * Check if need to use DNS to locate Kerberos services + * Check if need to use DNS to locate Kerberos services for name. If not + * defined, check dns_fallback, whose default value is true. */ private boolean useDNS(String name, boolean defaultValue) { Boolean value = getBooleanObject("libdefaults", name); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/KDCOptions.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/KDCOptions.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/KDCOptions.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/KDCOptions.java 2024-01-11 01:53:23.000000000 +0000 @@ -301,14 +301,14 @@ if ((options & KDC_OPT_RENEWABLE_OK) == KDC_OPT_RENEWABLE_OK) { set(RENEWABLE_OK, true); } else { - if (config.getBooleanValue("libdefaults", "renewable")) { + if (config.getBooleanObject("libdefaults", "renewable") == Boolean.TRUE) { set(RENEWABLE_OK, true); } } if ((options & KDC_OPT_PROXIABLE) == KDC_OPT_PROXIABLE) { set(PROXIABLE, true); } else { - if (config.getBooleanValue("libdefaults", "proxiable")) { + if (config.getBooleanObject("libdefaults", "proxiable") == Boolean.TRUE) { set(PROXIABLE, true); } } @@ -316,7 +316,7 @@ if ((options & KDC_OPT_FORWARDABLE) == KDC_OPT_FORWARDABLE) { set(FORWARDABLE, true); } else { - if (config.getBooleanValue("libdefaults", "forwardable")) { + if (config.getBooleanObject("libdefaults", "forwardable") == Boolean.TRUE) { set(FORWARDABLE, true); } } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/crypto/EType.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/crypto/EType.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/crypto/EType.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/krb5/internal/crypto/EType.java 2024-01-11 01:53:23.000000000 +0000 @@ -58,8 +58,8 @@ boolean allowed = false; try { Config cfg = Config.getInstance(); - String temp = cfg.get("libdefaults", "allow_weak_crypto"); - if (temp != null && temp.equals("true")) allowed = true; + allowed = cfg.getBooleanObject("libdefaults", "allow_weak_crypto") + == Boolean.TRUE; } catch (Exception exc) { if (DEBUG) { System.out.println ("Exception in getting allow_weak_crypto, " + diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/pkcs11/P11Signature.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/pkcs11/P11Signature.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/pkcs11/P11Signature.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/pkcs11/P11Signature.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -728,9 +728,12 @@ int len = (p11Key.length() + 7) >> 3; RSAPadding padding = RSAPadding.getInstance (RSAPadding.PAD_BLOCKTYPE_1, len); - byte[] padded = padding.pad(data); - return padded; - } catch (GeneralSecurityException e) { + byte[] result = padding.pad(data); + if (result == null) { + throw new ProviderException("Error padding data"); + } + return result; + } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new ProviderException(e); } } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java 2024-01-11 01:53:23.000000000 +0000 @@ -336,8 +336,11 @@ } } + // Thread-local gate to prevent recursive provider lookups + private static ThreadLocal gate = new ThreadLocal<>(); + /** - * Download Certificates from the given AIA and add them to the + * Download certificates from the given AIA and add them to the * specified Collection. */ // cs.getCertificates(caSelector) returns a collection of X509Certificate's @@ -349,32 +352,47 @@ if (Builder.USE_AIA == false) { return false; } + List adList = aiaExt.getAccessDescriptions(); if (adList == null || adList.isEmpty()) { return false; } - boolean add = false; - for (AccessDescription ad : adList) { - CertStore cs = URICertStore.getInstance(ad); - if (cs != null) { - try { - if (certs.addAll((Collection) - cs.getCertificates(caSelector))) { - add = true; - if (!searchAllCertStores) { - return true; + if (gate.get() != null) { + // Avoid recursive fetching of certificates + if (debug != null) { + debug.println("Recursive fetching of certs via the AIA " + + "extension detected"); + } + return false; + } + + gate.set(gate); + try { + boolean add = false; + for (AccessDescription ad : adList) { + CertStore cs = URICertStore.getInstance(ad); + if (cs != null) { + try { + if (certs.addAll((Collection) + cs.getCertificates(caSelector))) { + add = true; + if (!searchAllCertStores) { + return true; + } + } + } catch (CertStoreException cse) { + if (debug != null) { + debug.println("exception getting certs from CertStore:"); + cse.printStackTrace(); } - } - } catch (CertStoreException cse) { - if (debug != null) { - debug.println("exception getting certs from CertStore:"); - cse.printStackTrace(); } } } + return add; + } finally { + gate.set(null); } - return add; } /** diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSAPadding.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSAPadding.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSAPadding.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSAPadding.java 2024-01-11 01:53:23.000000000 +0000 @@ -30,7 +30,6 @@ import java.security.*; import java.security.spec.*; -import javax.crypto.BadPaddingException; import javax.crypto.spec.PSource; import javax.crypto.spec.OAEPParameterSpec; @@ -236,24 +235,22 @@ } /** - * Pad the data and return the padded block. + * Pad the data and return the result or null if error occurred. */ - public byte[] pad(byte[] data) throws BadPaddingException { + public byte[] pad(byte[] data) { return pad(data, 0, data.length); } /** - * Pad the data and return the padded block. + * Pad the data and return the result or null if error occurred. */ - public byte[] pad(byte[] data, int ofs, int len) - throws BadPaddingException { + public byte[] pad(byte[] data, int ofs, int len) { if (len > maxDataSize) { - throw new BadPaddingException("Data must be shorter than " - + (maxDataSize + 1) + " bytes but received " - + len + " bytes."); + return null; } switch (type) { case PAD_NONE: + // assert len == paddedSize and data.length - ofs > len? return RSACore.convert(data, ofs, len); case PAD_BLOCKTYPE_1: case PAD_BLOCKTYPE_2: @@ -266,31 +263,30 @@ } /** - * Unpad the padded block and return the data. + * Unpad the padded block and return the result or null if error occurred. */ - public byte[] unpad(byte[] padded) throws BadPaddingException { - if (padded.length != paddedSize) { - throw new BadPaddingException("Decryption error." + - "The padded array length (" + padded.length + - ") is not the specified padded size (" + paddedSize + ")"); - } - switch (type) { - case PAD_NONE: - return padded; - case PAD_BLOCKTYPE_1: - case PAD_BLOCKTYPE_2: - return unpadV15(padded); - case PAD_OAEP_MGF1: - return unpadOAEP(padded); - default: - throw new AssertionError(); + public byte[] unpad(byte[] padded) { + if (padded.length == paddedSize) { + switch (type) { + case PAD_NONE: + return padded; + case PAD_BLOCKTYPE_1: + case PAD_BLOCKTYPE_2: + return unpadV15(padded); + case PAD_OAEP_MGF1: + return unpadOAEP(padded); + default: + throw new AssertionError(); + } + } else { + return null; } } /** * PKCS#1 v1.5 padding (blocktype 1 and 2). */ - private byte[] padV15(byte[] data, int ofs, int len) throws BadPaddingException { + private byte[] padV15(byte[] data, int ofs, int len) { byte[] padded = new byte[paddedSize]; System.arraycopy(data, ofs, padded, paddedSize - len, len); int psSize = paddedSize - 3 - len; @@ -328,10 +324,10 @@ /** * PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)). - * + * Return the result or null if error occurred. * Note that we want to make it a constant-time operation */ - private byte[] unpadV15(byte[] padded) throws BadPaddingException { + private byte[] unpadV15(byte[] padded) { int k = 0; boolean bp = false; @@ -367,10 +363,8 @@ byte[] data = new byte[n]; System.arraycopy(padded, p, data, 0, n); - BadPaddingException bpe = new BadPaddingException("Decryption error"); - if (bp) { - throw bpe; + return null; } else { return data; } @@ -379,8 +373,9 @@ /** * PKCS#1 v2.0 OAEP padding (MGF1). * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002) + * Return the result or null if error occurred. */ - private byte[] padOAEP(byte[] M, int ofs, int len) throws BadPaddingException { + private byte[] padOAEP(byte[] M, int ofs, int len) { if (random == null) { random = JCAUtil.getSecureRandom(); } @@ -429,8 +424,9 @@ /** * PKCS#1 v2.1 OAEP unpadding (MGF1). + * Return the result or null if error occurred. */ - private byte[] unpadOAEP(byte[] padded) throws BadPaddingException { + private byte[] unpadOAEP(byte[] padded) { byte[] EM = padded; boolean bp = false; int hLen = lHash.length; @@ -486,12 +482,6 @@ byte [] m = new byte[EM.length - mStart]; System.arraycopy(EM, mStart, m, 0, m.length); - BadPaddingException bpe = new BadPaddingException("Decryption error"); - - if (bp) { - throw bpe; - } else { - return m; - } + return (bp? null : m); } } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSASignature.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSASignature.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSASignature.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/rsa/RSASignature.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -189,13 +189,15 @@ try { byte[] encoded = encodeSignature(digestOID, digest); byte[] padded = padding.pad(encoded); - byte[] encrypted = RSACore.rsa(padded, privateKey, true); - return encrypted; + if (padded != null) { + return RSACore.rsa(padded, privateKey, true); + } } catch (GeneralSecurityException e) { throw new SignatureException("Could not sign data", e); } catch (IOException e) { throw new SignatureException("Could not encode data", e); } + throw new SignatureException("Could not sign data"); } // verify the data and return the result. See JCA doc @@ -206,21 +208,30 @@ } if (sigBytes.length != RSACore.getByteLength(publicKey)) { - throw new SignatureException("Signature length not correct: got " + + throw new SignatureException("Bad signature length: got " + sigBytes.length + " but was expecting " + RSACore.getByteLength(publicKey)); } - byte[] digest = getDigestValue(); + try { + // https://www.rfc-editor.org/rfc/rfc8017.html#section-8.2.2 + // Step 4 suggests comparing the encoded message byte[] decrypted = RSACore.rsa(sigBytes, publicKey); - byte[] unpadded = padding.unpad(decrypted); - byte[] decodedDigest = decodeSignature(digestOID, unpadded); - return MessageDigest.isEqual(digest, decodedDigest); + + byte[] digest = getDigestValue(); + + byte[] encoded = encodeSignature(digestOID, digest); + byte[] padded = padding.pad(encoded); + if (MessageDigest.isEqual(padded, decrypted)) { + return true; + } + + // Some vendors might omit the NULL params in digest algorithm + // identifier. Try again. + encoded = encodeSignatureWithoutNULL(digestOID, digest); + padded = padding.pad(encoded); + return MessageDigest.isEqual(padded, decrypted); } catch (javax.crypto.BadPaddingException e) { - // occurs if the app has used the wrong RSA public key - // or if sigBytes is invalid - // return false rather than propagating the exception for - // compatibility/ease of use return false; } catch (IOException e) { throw new SignatureException("Signature encoding error", e); @@ -242,27 +253,19 @@ } /** - * Decode the signature data. Verify that the object identifier matches - * and return the message digest. + * Encode the digest without the NULL params, return the to-be-signed data. + * This is only used by SunRsaSign. */ - public static byte[] decodeSignature(ObjectIdentifier oid, byte[] sig) + static byte[] encodeSignatureWithoutNULL(ObjectIdentifier oid, byte[] digest) throws IOException { - // Enforce strict DER checking for signatures - DerInputStream in = new DerInputStream(sig, 0, sig.length, false); - DerValue[] values = in.getSequence(2); - if ((values.length != 2) || (in.available() != 0)) { - throw new IOException("SEQUENCE length error"); - } - AlgorithmId algId = AlgorithmId.parse(values[0]); - if (algId.getOID().equals((Object)oid) == false) { - throw new IOException("ObjectIdentifier mismatch: " - + algId.getOID()); - } - if (algId.getEncodedParams() != null) { - throw new IOException("Unexpected AlgorithmId parameters"); - } - byte[] digest = values[1].getOctetString(); - return digest; + DerOutputStream out = new DerOutputStream(); + DerOutputStream oidout = new DerOutputStream(); + oidout.putOID(oid); + out.write(DerValue.tag_Sequence, oidout); + out.putOctetString(digest); + DerValue result = + new DerValue(DerValue.tag_Sequence, out.toByteArray()); + return result.toByteArray(); } // set parameter, not supported. See JCA doc diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java 2024-01-11 01:53:23.000000000 +0000 @@ -27,6 +27,7 @@ import sun.security.validator.Validator; +import java.lang.ref.SoftReference; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.security.AlgorithmParameters; @@ -55,6 +56,7 @@ import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.regex.Matcher; @@ -99,6 +101,8 @@ private final List disabledAlgorithms; private final Constraints algorithmConstraints; + private volatile SoftReference> cacheRef = + new SoftReference<>(null); public static DisabledAlgorithmConstraints certPathConstraints() { return CertPathHolder.CONSTRAINTS; @@ -158,7 +162,10 @@ @Override public final boolean permits(Set primitives, String algorithm, AlgorithmParameters parameters) { - if (!checkAlgorithm(disabledAlgorithms, algorithm, decomposer)) { + if (algorithm == null || algorithm.isEmpty()) { + throw new IllegalArgumentException("No algorithm name specified"); + } + if (!cachedCheckAlgorithm(algorithm)) { return false; } @@ -242,7 +249,7 @@ // Check if named curves in the key are disabled. for (Key key : cp.getKeys()) { for (String curve : getNamedCurveFromKey(key)) { - if (!checkAlgorithm(disabledAlgorithms, curve, decomposer)) { + if (!cachedCheckAlgorithm(curve)) { throw new CertPathValidatorException( "Algorithm constraints check failed on disabled " + "algorithm: " + curve, @@ -950,6 +957,25 @@ } } + private boolean cachedCheckAlgorithm(String algorithm) { + Map cache; + if ((cache = cacheRef.get()) == null) { + synchronized (this) { + if ((cache = cacheRef.get()) == null) { + cache = new ConcurrentHashMap<>(); + cacheRef = new SoftReference<>(cache); + } + } + } + Boolean result = cache.get(algorithm); + if (result != null) { + return result; + } + result = checkAlgorithm(disabledAlgorithms, algorithm, decomposer); + cache.put(algorithm, result); + return result; + } + /* * This constraint is used for the complete disabling of the algorithm. */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/KeyUtil.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/KeyUtil.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/KeyUtil.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/KeyUtil.java 2024-01-11 01:53:23.000000000 +0000 @@ -253,13 +253,14 @@ * contains the lower of that suggested by the client in the client * hello and the highest supported by the server. * @param encoded the encoded key in its "RAW" encoding format - * @param isFailover whether or not the previous decryption of the - * encrypted PreMasterSecret message run into problem + * @param failure true if encoded is incorrect according to previous checks * @return the polished PreMasterSecret key in its "RAW" encoding format */ public static byte[] checkTlsPreMasterSecretKey( int clientVersion, int serverVersion, SecureRandom random, - byte[] encoded, boolean isFailOver) { + byte[] encoded, boolean failure) { + + byte[] tmp; if (random == null) { random = JCAUtil.getSecureRandom(); @@ -267,30 +268,38 @@ byte[] replacer = new byte[48]; random.nextBytes(replacer); - if (!isFailOver && (encoded != null)) { - // check the length - if (encoded.length != 48) { - // private, don't need to clone the byte array. - return replacer; - } - - int encodedVersion = - ((encoded[0] & 0xFF) << 8) | (encoded[1] & 0xFF); - if (clientVersion != encodedVersion) { - if (clientVersion > 0x0301 || // 0x0301: TLSv1 - serverVersion != encodedVersion) { - encoded = replacer; - } // Otherwise, For compatibility, we maintain the behavior - // that the version in pre_master_secret can be the - // negotiated version for TLS v1.0 and SSL v3.0. - } + if (failure) { + tmp = replacer; + } else { + tmp = encoded; + } + if (tmp == null) { + encoded = replacer; + } else { + encoded = tmp; + } + // check the length + if (encoded.length != 48) { // private, don't need to clone the byte array. - return encoded; + tmp = replacer; + } else { + tmp = encoded; } - // private, don't need to clone the byte array. - return replacer; + int encodedVersion = + ((tmp[0] & 0xFF) << 8) | (tmp[1] & 0xFF); + int check1 = 0; + int check2 = 0; + int check3 = 0; + if (clientVersion != encodedVersion) check1 = 1; + if (clientVersion > 0x0301) check2 = 1; + if (serverVersion != encodedVersion) check3 = 1; + if ((check1 & (check2 | check3)) == 1) { + return replacer; + } else { + return tmp; + } } /** diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/SignatureFileVerifier.java openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/SignatureFileVerifier.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/classes/sun/security/util/SignatureFileVerifier.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/classes/sun/security/util/SignatureFileVerifier.java 2024-01-11 01:53:23.000000000 +0000 @@ -855,16 +855,16 @@ * the maximum allowed number of bytes for the signature-related files * in a JAR file. */ - Integer tmp = AccessController.doPrivileged(new GetIntegerAction( - "jdk.jar.maxSignatureFileSize", 8000000)); + int tmp = AccessController.doPrivileged(new GetIntegerAction( + "jdk.jar.maxSignatureFileSize", 16000000)); if (tmp < 0 || tmp > MAX_ARRAY_SIZE) { if (debug != null) { - debug.println("Default signature file size 8000000 bytes " + - "is used as the specified size for the " + - "jdk.jar.maxSignatureFileSize system property " + + debug.println("The default signature file size of 16000000 bytes " + + "will be used for the jdk.jar.maxSignatureFileSize " + + "system property since the specified value " + "is out of range: " + tmp); } - tmp = 8000000; + tmp = 16000000; } return tmp; } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/share/native/common/check_code.c openjdk-8-8u402-ga/=unpacked-tar3=/src/share/native/common/check_code.c --- openjdk-8-8u392-ga/=unpacked-tar3=/src/share/native/common/check_code.c 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/share/native/common/check_code.c 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,6 +84,7 @@ #include #include #include +#include #include "jni.h" #include "jvm.h" @@ -1202,7 +1203,7 @@ } } if (opcode == JVM_OPC_tableswitch) { - keys = _ck_ntohl(lpc[2]) - _ck_ntohl(lpc[1]) + 1; + keys = _ck_ntohl(lpc[2]) - _ck_ntohl(lpc[1]) + 1; delta = 1; } else { keys = _ck_ntohl(lpc[1]); /* number of pairs */ @@ -1682,11 +1683,13 @@ switch (instruction) { case JVM_OPC_tableswitch: { int *lpc = (int *)UCALIGN(iptr + 1); - int index; if (lpc + 2 >= (int *)end) { return -1; /* do not read pass the end */ } - index = _ck_ntohl(lpc[2]) - _ck_ntohl(lpc[1]); + int64_t low = _ck_ntohl(lpc[1]); + int64_t high = _ck_ntohl(lpc[2]); + int64_t index = high - low; + // The value of low must be less than or equal to high - i.e. index >= 0 if ((index < 0) || (index > 65535)) { return -1; /* illegal */ } else { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_GraphicsEnv.c openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_GraphicsEnv.c --- openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_GraphicsEnv.c 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_GraphicsEnv.c 2024-01-11 01:53:23.000000000 +0000 @@ -205,6 +205,8 @@ visualList = XGetVisualInfo(awt_display, mask, vinfo, &visualsMatched); if (visualList) { + int id = -1; + VisualID defaultVisual = XVisualIDFromVisual(DefaultVisual(awt_display, vinfo->screen)); defaultConfig = ZALLOC(_AwtGraphicsConfigData); for (i = 0; i < visualsMatched; i++) { memcpy(&defaultConfig->awt_visInfo, &visualList[i], sizeof(XVisualInfo)); @@ -213,20 +215,31 @@ /* we can't use awtJNI_CreateColorData here, because it'll pull, SystemColor, which in turn will cause toolkit to be reinitialized */ if (awtCreateX11Colormap(defaultConfig)) { - /* Allocate white and black pixels for this visual */ - color.flags = DoRed | DoGreen | DoBlue; - color.red = color.green = color.blue = 0x0000; - XAllocColor(awt_display, defaultConfig->awt_cmap, &color); - x11Screens[visualList[i].screen].blackpixel = color.pixel; - color.flags = DoRed | DoGreen | DoBlue; - color.red = color.green = color.blue = 0xffff; - XAllocColor(awt_display, defaultConfig->awt_cmap, &color); - x11Screens[visualList[i].screen].whitepixel = color.pixel; - - XFree(visualList); - return defaultConfig; + if (visualList[i].visualid == defaultVisual) { + id = i; + break; + } else if (-1 == id) { + // Keep 1st match for fallback + id = i; + } } } + if (-1 != id) { + memcpy(&defaultConfig->awt_visInfo, &visualList[id], sizeof(XVisualInfo)); + defaultConfig->awt_depth = visualList[id].depth; + /* Allocate white and black pixels for this visual */ + color.flags = DoRed | DoGreen | DoBlue; + color.red = color.green = color.blue = 0x0000; + XAllocColor(awt_display, defaultConfig->awt_cmap, &color); + x11Screens[visualList[id].screen].blackpixel = color.pixel; + color.flags = DoRed | DoGreen | DoBlue; + color.red = color.green = color.blue = 0xffff; + XAllocColor(awt_display, defaultConfig->awt_cmap, &color); + x11Screens[visualList[id].screen].whitepixel = color.pixel; + + XFree(visualList); + return defaultConfig; + } XFree(visualList); free((void *)defaultConfig); } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_InputMethod.c openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_InputMethod.c --- openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_InputMethod.c 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/awt/awt_InputMethod.c 2024-01-11 01:53:23.000000000 +0000 @@ -676,9 +676,10 @@ return NULL; } statusWindow->w = status; - //12-point font + //12, 13-point fonts statusWindow->fontset = XCreateFontSet(dpy, - "-*-*-medium-r-normal-*-*-120-*-*-*-*", + "-*-*-medium-r-normal-*-*-120-*-*-*-*," \ + "-*-*-medium-r-normal-*-*-130-*-*-*-*", &mclr, &mccr, &dsr); /* In case we didn't find the font set, release the list of missing characters */ if (mccr > 0) { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c --- openjdk-8-8u392-ga/=unpacked-tar3=/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c 2024-01-11 01:53:23.000000000 +0000 @@ -29,6 +29,7 @@ #include "jlong.h" #include +#include #include #include #include diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/windows/classes/sun/security/mscapi/CRSACipher.java openjdk-8-8u402-ga/=unpacked-tar3=/src/windows/classes/sun/security/mscapi/CRSACipher.java --- openjdk-8-8u392-ga/=unpacked-tar3=/src/windows/classes/sun/security/mscapi/CRSACipher.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/windows/classes/sun/security/mscapi/CRSACipher.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.security.Key; import java.security.interfaces.*; import java.security.spec.*; +import java.util.Arrays; import javax.crypto.*; import javax.crypto.spec.*; @@ -61,6 +62,9 @@ */ public final class CRSACipher extends CipherSpi { + private static final int ERROR_INVALID_PARAMETER = 0x57; + private static final int NTE_INVALID_PARAMETER = 0x80090027; + // constant for an empty byte array private final static byte[] B0 = new byte[0]; @@ -101,6 +105,8 @@ // cipher parameter for TLS RSA premaster secret private AlgorithmParameterSpec spec = null; + private boolean forTlsPremasterSecret = false; + // the source of randomness private SecureRandom random; @@ -171,6 +177,9 @@ } spec = params; this.random = random; // for TLS RSA premaster secret + this.forTlsPremasterSecret = true; + } else { + this.forTlsPremasterSecret = false; } init(opmode, key); } @@ -277,8 +286,7 @@ } // internal doFinal() method. Here we perform the actual RSA operation - private byte[] doFinal() throws BadPaddingException, - IllegalBlockSizeException { + private byte[] doFinal() throws IllegalBlockSizeException { if (bufOfs > buffer.length) { throw new IllegalBlockSizeException("Data must not be longer " + "than " + (buffer.length - paddingLength) + " bytes"); @@ -307,7 +315,7 @@ throw new AssertionError("Internal error"); } - } catch (KeyException e) { + } catch (KeyException | BadPaddingException e) { throw new ProviderException(e); } finally { @@ -330,14 +338,14 @@ // see JCE spec protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen) - throws BadPaddingException, IllegalBlockSizeException { + throws IllegalBlockSizeException { update(in, inOfs, inLen); return doFinal(); } // see JCE spec protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out, - int outOfs) throws ShortBufferException, BadPaddingException, + int outOfs) throws ShortBufferException, IllegalBlockSizeException { if (outputSize > out.length - outOfs) { throw new ShortBufferException @@ -353,6 +361,7 @@ // see JCE spec protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException { + byte[] encoded = key.getEncoded(); // TODO - unextractable key if ((encoded == null) || (encoded.length == 0)) { throw new InvalidKeyException("Could not obtain encoded key"); @@ -361,12 +370,7 @@ throw new InvalidKeyException("Key is too long for wrapping"); } update(encoded, 0, encoded.length); - try { - return doFinal(); - } catch (BadPaddingException e) { - // should not occur - throw new InvalidKeyException("Wrapping failed", e); - } + return doFinal(); } // see JCE spec @@ -387,31 +391,31 @@ update(wrappedKey, 0, wrappedKey.length); try { encoded = doFinal(); - } catch (BadPaddingException e) { - if (isTlsRsaPremasterSecret) { - failover = e; - } else { - throw new InvalidKeyException("Unwrapping failed", e); - } } catch (IllegalBlockSizeException e) { // should not occur, handled with length check above throw new InvalidKeyException("Unwrapping failed", e); } - if (isTlsRsaPremasterSecret) { - if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) { - throw new IllegalStateException( - "No TlsRsaPremasterSecretParameterSpec specified"); + try { + if (isTlsRsaPremasterSecret) { + if (!forTlsPremasterSecret) { + throw new IllegalStateException( + "No TlsRsaPremasterSecretParameterSpec specified"); + } + + // polish the TLS premaster secret + encoded = KeyUtil.checkTlsPreMasterSecretKey( + ((TlsRsaPremasterSecretParameterSpec) spec).getClientVersion(), + ((TlsRsaPremasterSecretParameterSpec) spec).getServerVersion(), + random, encoded, encoded == null); } - // polish the TLS premaster secret - encoded = KeyUtil.checkTlsPreMasterSecretKey( - ((TlsRsaPremasterSecretParameterSpec)spec).getClientVersion(), - ((TlsRsaPremasterSecretParameterSpec)spec).getServerVersion(), - random, encoded, (failover != null)); + return constructKey(encoded, algorithm, type); + } finally { + if (encoded != null) { + Arrays.fill(encoded, (byte) 0); + } } - - return constructKey(encoded, algorithm, type); } // see JCE spec @@ -495,7 +499,23 @@ * Encrypt/decrypt a data buffer using Microsoft Crypto API with HCRYPTKEY. * It expects and returns ciphertext data in big-endian form. */ - private native static byte[] encryptDecrypt(byte[] data, int dataSize, - long hCryptKey, boolean doEncrypt) throws KeyException; + private byte[] encryptDecrypt(byte[] data, int dataSize, + long hCryptKey, boolean doEncrypt) throws KeyException, BadPaddingException { + int[] returnStatus = new int[1]; + byte[] result= encryptDecrypt(returnStatus, data, dataSize, hCryptKey, doEncrypt); + if ((returnStatus[0] == ERROR_INVALID_PARAMETER) || (returnStatus[0] == NTE_INVALID_PARAMETER)) { + if (forTlsPremasterSecret) { + result = null; + } else { + throw new BadPaddingException("Error " + returnStatus[0] + " returned by MSCAPI"); + } + } else if (returnStatus[0] != 0) { + throw new KeyException("Error " + returnStatus[0] + " returned by MSCAPI"); + } + + return result; + } + private static native byte[] encryptDecrypt(int[] returnStatus, byte[] data, int dataSize, + long key, boolean doEncrypt) throws KeyException; } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/src/windows/native/sun/security/mscapi/security.cpp openjdk-8-8u402-ga/=unpacked-tar3=/src/windows/native/sun/security/mscapi/security.cpp --- openjdk-8-8u392-ga/=unpacked-tar3=/src/windows/native/sun/security/mscapi/security.cpp 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/src/windows/native/sun/security/mscapi/security.cpp 2024-01-11 01:53:23.000000000 +0000 @@ -1832,18 +1832,25 @@ /* * Class: sun_security_mscapi_CRSACipher * Method: encryptDecrypt - * Signature: ([BIJZ)[B + * Signature: ([I[BIJZ)[B */ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CRSACipher_encryptDecrypt - (JNIEnv *env, jclass clazz, jbyteArray jData, jint jDataSize, jlong hKey, + (JNIEnv *env, jclass clazz, jintArray jResultStatus, jbyteArray jData, jint jDataSize, jlong hKey, jboolean doEncrypt) { jbyteArray result = NULL; jbyte* pData = NULL; + jbyte* resultData = NULL; DWORD dwDataLen = jDataSize; DWORD dwBufLen = env->GetArrayLength(jData); DWORD i; BYTE tmp; + BOOL success; + DWORD ss = ERROR_SUCCESS; + DWORD lastError = ERROR_SUCCESS; + DWORD resultLen = 0; + DWORD pmsLen = 48; + jbyte pmsArr[48] = {0}; __try { @@ -1870,6 +1877,8 @@ pData[i] = pData[dwBufLen - i -1]; pData[dwBufLen - i - 1] = tmp; } + resultData = pData; + resultLen = dwBufLen; } else { // convert to little-endian for (i = 0; i < dwBufLen / 2; i++) { @@ -1879,21 +1888,28 @@ } // decrypt - if (! ::CryptDecrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, //deprecated - &dwBufLen)) { - - ThrowException(env, KEY_EXCEPTION, GetLastError()); - __leave; + success = ::CryptDecrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, //deprecated + &dwBufLen); + lastError = GetLastError(); + if (success) { + ss = ERROR_SUCCESS; + resultData = pData; + resultLen = dwBufLen; + } else { + ss = lastError; + resultData = pmsArr; + resultLen = pmsLen; } + env->SetIntArrayRegion(jResultStatus, 0, 1, (jint*) &ss); } - // Create new byte array - if ((result = env->NewByteArray(dwBufLen)) == NULL) { + // Create new byte array + if ((result = env->NewByteArray(resultLen)) == NULL) { __leave; } // Copy data from native buffer to Java buffer - env->SetByteArrayRegion(result, 0, dwBufLen, (jbyte*) pData); + env->SetByteArrayRegion(result, 0, resultLen, (jbyte*) resultData); } __finally { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/TEST.ROOT openjdk-8-8u402-ga/=unpacked-tar3=/test/TEST.ROOT --- openjdk-8-8u392-ga/=unpacked-tar3=/test/TEST.ROOT 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/TEST.ROOT 2024-01-11 01:53:23.000000000 +0000 @@ -25,3 +25,7 @@ # Group definitions groups=TEST.groups [closed/TEST.groups] + +# Path to libraries in the topmost test directory. This is needed so @library +# does not need ../../ notation to reach them +external.lib.roots = ../../ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/com/sun/management/OperatingSystemMXBean/GetCommittedVirtualMemorySize.java openjdk-8-8u402-ga/=unpacked-tar3=/test/com/sun/management/OperatingSystemMXBean/GetCommittedVirtualMemorySize.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/com/sun/management/OperatingSystemMXBean/GetCommittedVirtualMemorySize.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/com/sun/management/OperatingSystemMXBean/GetCommittedVirtualMemorySize.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,8 +56,7 @@ // Careful with these values. private static final long MIN_SIZE_FOR_PASS = 1; - // Max size for pass dynamically determined below - private static long max_size_for_pass = Long.MAX_VALUE; + private static long MAX_SIZE_FOR_PASS = Long.MAX_VALUE; private static boolean trace = false; @@ -66,16 +65,6 @@ trace = true; } - // 4934082: On Linux, VM size *can* be larger than total swap - // size. Linux might not reserve swap memory immediately when - // a page is mmaped. This means that the reported committed - // memory size can grow beyond the swap limit. - long max_size = mbean.getTotalSwapSpaceSize() + - mbean.getTotalPhysicalMemorySize(); - - if (max_size > 0) { - max_size_for_pass = max_size; - } long size = mbean.getCommittedVirtualMemorySize(); if (size == -1) { System.out.println("getCommittedVirtualMemorySize() is not supported"); @@ -87,11 +76,11 @@ size); } - if (size < MIN_SIZE_FOR_PASS || size > max_size_for_pass) { + if (size < MIN_SIZE_FOR_PASS || size > MAX_SIZE_FOR_PASS) { throw new RuntimeException("Committed virtual memory size " + "illegal value: " + size + " bytes " + "(MIN = " + MIN_SIZE_FOR_PASS + "; " + - "MAX = " + max_size_for_pass + ")"); + "MAX = " + MAX_SIZE_FOR_PASS + ")"); } System.out.println("Test passed."); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/java/awt/color/ICC_ColorSpace/SimpleSRGBConversionQualityTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/java/awt/color/ICC_ColorSpace/SimpleSRGBConversionQualityTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/java/awt/color/ICC_ColorSpace/SimpleSRGBConversionQualityTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/java/awt/color/ICC_ColorSpace/SimpleSRGBConversionQualityTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,51 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.color.ColorSpace; + +/** + * @test + * @bug 6528710 + * @summary Verifies sRGB-ColorSpace to sRGB-ColorSpace conversion quality + */ +public final class SimpleSRGBConversionQualityTest { + + public static void main(String[] args) { + ColorSpace cspace = ColorSpace.getInstance(ColorSpace.CS_sRGB); + float fvalue[] = {1.0f, 1.0f, 1.0f}; + + Color c = new Color(cspace, fvalue, 1.0f); + if (c.getRed() != 255 || c.getGreen() != 255 || c.getBlue() != 255) { + throw new RuntimeException("Wrong color: " + c); + } + + float frgbvalue[] = cspace.toRGB(fvalue); + for (int i = 0; i < 3; ++i) { + if (frgbvalue[i] != 1.0f) { + System.err.println(fvalue[i] + " -> " + frgbvalue[i]); + throw new RuntimeException("Wrong value"); + } + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/java/lang/ProcessBuilder/Basic.java openjdk-8-8u402-ga/=unpacked-tar3=/test/java/lang/ProcessBuilder/Basic.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/java/lang/ProcessBuilder/Basic.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/java/lang/ProcessBuilder/Basic.java 2024-01-11 01:53:23.000000000 +0000 @@ -62,6 +62,10 @@ /* used for AIX only */ static final String libpath = System.getenv("LIBPATH"); + /* Used for regex String matching for long error messages */ + static final String PERMISSION_DENIED_ERROR_MSG = "(Permission denied|error=13)"; + static final String NO_SUCH_FILE_ERROR_MSG = "(No such file|error=2)"; + /** * Returns the number of milliseconds since time given by * startNanoTime, which must have been previously returned from a @@ -295,7 +299,7 @@ } catch (IOException e) { String m = e.getMessage(); if (EnglishUnix.is() && - ! matches(m, "Permission denied")) + ! matches(m, PERMISSION_DENIED_ERROR_MSG)) unexpected(e); } catch (Throwable t) { unexpected(t); } } @@ -403,7 +407,7 @@ } catch (IOException e) { String m = e.getMessage(); if (EnglishUnix.is() && - ! matches(m, "No such file")) + ! matches(m, NO_SUCH_FILE_ERROR_MSG)) unexpected(e); } catch (Throwable t) { unexpected(t); } @@ -416,7 +420,7 @@ } catch (IOException e) { String m = e.getMessage(); if (EnglishUnix.is() && - ! matches(m, "No such file")) + ! matches(m, NO_SUCH_FILE_ERROR_MSG)) unexpected(e); } catch (Throwable t) { unexpected(t); } @@ -1854,7 +1858,7 @@ } catch (IOException e) { String m = e.getMessage(); if (EnglishUnix.is() && - ! matches(m, "No such file or directory")) + ! matches(m, NO_SUCH_FILE_ERROR_MSG)) unexpected(e); } catch (Throwable t) { unexpected(t); } @@ -1871,7 +1875,7 @@ Pattern p = Pattern.compile(programName); if (! matches(m, programName) || (EnglishUnix.is() - && ! matches(m, "No such file or directory"))) + && ! matches(m, NO_SUCH_FILE_ERROR_MSG))) unexpected(e); } catch (Throwable t) { unexpected(t); } @@ -1887,7 +1891,7 @@ String m = e.getMessage(); if (! matches(m, "in directory") || (EnglishUnix.is() && - ! matches(m, "No such file or directory"))) + ! matches(m, NO_SUCH_FILE_ERROR_MSG))) unexpected(e); } catch (Throwable t) { unexpected(t); } @@ -2122,7 +2126,7 @@ new File("./emptyCommand").delete(); String m = e.getMessage(); if (EnglishUnix.is() && - ! matches(m, "Permission denied")) + ! matches(m, PERMISSION_DENIED_ERROR_MSG)) unexpected(e); } catch (Throwable t) { unexpected(t); } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/JoinLeave.java openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/JoinLeave.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/JoinLeave.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/JoinLeave.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,13 +21,15 @@ * questions. */ -/* +/** * @test * @bug 4091811 4148753 4102731 * @summary Test java.net.MulticastSocket joinGroup and leaveGroup - * @library /lib/testlibrary - * @build jdk.testlibrary.NetworkConfiguration + * @library /test/lib + * @build jdk.test.lib.NetworkConfiguration + * jdk.test.lib.Platform * @run main JoinLeave + * @run main/othervm -Djava.net.preferIPv4Stack=true JoinLeave */ import java.io.IOException; @@ -35,11 +37,11 @@ import java.net.InetAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; -import jdk.testlibrary.NetworkConfiguration; +import jdk.test.lib.NetworkConfiguration; public class JoinLeave { - public static void main(String args[]) throws IOException { + public static void main(String args[]) throws IOException { InetAddress ip4Group = InetAddress.getByName("224.80.80.80"); InetAddress ip6Group = InetAddress.getByName("ff02::a"); @@ -48,8 +50,7 @@ nc.ip6MulticastInterfaces().forEach(nic -> joinLeave(ip6Group, nic)); } - static void joinLeave(InetAddress group, NetworkInterface nif) - { + static void joinLeave(InetAddress group, NetworkInterface nif) { System.out.println("Joining:" + group + " on " + nif); try (MulticastSocket soc = new MulticastSocket()) { soc.setNetworkInterface(nif); diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/SetGetNetworkInterfaceTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/SetGetNetworkInterfaceTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/SetGetNetworkInterfaceTest.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/SetGetNetworkInterfaceTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,105 +21,50 @@ * questions. */ - -/* - * @test - * @bug 6458027 - * @summary Disabling IPv6 on a specific network interface causes problems. - * - */ - import java.io.IOException; -import java.net.InetAddress; +import java.io.UncheckedIOException; import java.net.MulticastSocket; import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Arrays; -import java.util.Enumeration; +import jdk.test.lib.NetworkConfiguration; -public class SetGetNetworkInterfaceTest { +/** + * @test + * @bug 6458027 + * @summary Disabling IPv6 on a specific network interface causes problems. + * @library /test/lib + * @build jdk.test.lib.NetworkConfiguration + * jdk.test.lib.Platform + * @run main SetGetNetworkInterfaceTest + * @run main/othervm -Djava.net.preferIPv4Stack=true SetGetNetworkInterfaceTest +*/ +public class SetGetNetworkInterfaceTest { public static void main(String[] args) throws Exception { - - boolean passed = true; - try { - MulticastSocket ms = new MulticastSocket(); - Enumeration networkInterfaces = NetworkInterface - .getNetworkInterfaces(); - while (networkInterfaces.hasMoreElements()) { - NetworkInterface netIf = networkInterfaces.nextElement(); - if (isNetworkInterfaceTestable(netIf)) { - printNetIfDetails(netIf); - ms.setNetworkInterface(netIf); - NetworkInterface msNetIf = ms.getNetworkInterface(); - if (netIf.equals(msNetIf)) { - System.out.println(" OK"); - } else { - System.out.println("FAILED!!!"); - printNetIfDetails(msNetIf); - passed = false; - } - System.out.println("------------------"); - } - } + NetworkConfiguration nc = NetworkConfiguration.probe(); + try (MulticastSocket ms = new MulticastSocket()) { + nc.multicastInterfaces(true).forEach(nif -> setGetNetworkInterface(ms, nif)); } catch (IOException e) { e.printStackTrace(); - passed = false; } - if (!passed) { - throw new RuntimeException("Test Fail"); - } - System.out.println("Test passed "); - } - - private static boolean isNetworkInterfaceTestable(NetworkInterface netIf) throws Exception { - System.out.println("checking netif == " + netIf.getName()); - return (netIf.isUp() && netIf.supportsMulticast() && isIpAddrAvailable(netIf)); + System.out.println("Test passed."); } - private static boolean isIpAddrAvailable (NetworkInterface netIf) { - boolean ipAddrAvailable = false; - byte[] nullIpAddr = {'0', '0', '0', '0'}; - byte[] testIpAddr = null; - - Enumeration ipAddresses = netIf.getInetAddresses(); - while (ipAddresses.hasMoreElements()) { - InetAddress testAddr = ipAddresses.nextElement(); - testIpAddr = testAddr.getAddress(); - if ((testIpAddr != null) && (!Arrays.equals(testIpAddr, nullIpAddr))) { - ipAddrAvailable = true; - break; + static void setGetNetworkInterface(MulticastSocket ms, NetworkInterface nif) { + try { + System.out.println(NetworkConfiguration.interfaceInformation(nif)); + ms.setNetworkInterface(nif); + NetworkInterface msNetIf = ms.getNetworkInterface(); + if (nif.equals(msNetIf)) { + System.out.println(" OK"); } else { - System.out.println("ignore netif " + netIf.getName()); - } - } - return ipAddrAvailable; - } - - private static void printNetIfDetails(NetworkInterface ni) - throws SocketException { - System.out.println("Name " + ni.getName() + " index " + ni.getIndex()); - Enumeration en = ni.getInetAddresses(); - while (en.hasMoreElements()) { - System.out.println(" InetAdress: " + en.nextElement()); - } - System.out.println("HardwareAddress: " + createMacAddrString(ni)); - System.out.println("loopback: " + ni.isLoopback() + "; pointToPoint: " - + ni.isPointToPoint() + "; virtual: " + ni.isVirtual() - + "; MTU: " + ni.getMTU()); - } - - private static String createMacAddrString(NetworkInterface netIf) - throws SocketException { - byte[] macAddr = netIf.getHardwareAddress(); - StringBuilder sb = new StringBuilder(); - if (macAddr != null) { - for (int i = 0; i < macAddr.length; i++) { - sb.append(String.format("%02X%s", macAddr[i], - (i < macAddr.length - 1) ? "-" : "")); + System.out.println("FAILED!!!"); + System.out.println(NetworkConfiguration.interfaceInformation(msNetIf)); + throw new RuntimeException("Test Fail"); } + System.out.println("------------------"); + } catch (IOException e) { + throw new UncheckedIOException(e); } - return sb.toString(); } } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/Test.java openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/Test.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/java/net/MulticastSocket/Test.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/java/net/MulticastSocket/Test.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,21 +21,31 @@ * questions. */ -/* +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.net.SocketTimeoutException; + +import jdk.test.lib.NetworkConfiguration; + +/** * @test * @bug 4488458 * @summary IPv4 and IPv6 multicasting broken on Linux + * @library /test/lib + * @build jdk.test.lib.NetworkConfiguration + * jdk.test.lib.Platform + * @run main Test + * @run main/othervm -Djava.net.preferIPv4Stack=true Test */ -import java.net.*; -import java.io.IOException; -import java.util.Enumeration; - public class Test { static int count = 0; static int failures = 0; - void doTest(String address) throws Exception { + void doTest(String address) throws IOException { boolean failed = false; InetAddress ia = InetAddress.getByName(address); @@ -61,7 +71,7 @@ /* packets should be received */ - for (int j=0; j<2; j++) { + for (int j = 0; j < 2; j++) { p.setAddress(ia); p.setPort(port); @@ -123,59 +133,26 @@ } } - void allTests() throws Exception { + void allTests() throws IOException { + NetworkConfiguration nc = NetworkConfiguration.probe(); - /* - * Assume machine has IPv4 address - */ + // unconditionally test IPv4 address doTest("224.80.80.80"); - /* - * Check if IPv6 is enabled and the scope of the addresses - */ - boolean has_ipv6 = false; - boolean has_siteaddress = false; - boolean has_linklocaladdress = false; - boolean has_globaladdress = false; - - Enumeration nifs = NetworkInterface.getNetworkInterfaces(); - while (nifs.hasMoreElements()) { - NetworkInterface ni = (NetworkInterface)nifs.nextElement(); - Enumeration addrs = ni.getInetAddresses(); - - while (addrs.hasMoreElements()) { - InetAddress ia = (InetAddress)addrs.nextElement(); - - if (ia instanceof Inet6Address) { - has_ipv6 = true; - if (ia.isLinkLocalAddress()) has_linklocaladdress = true; - if (ia.isSiteLocalAddress()) has_siteaddress = true; - - if (!ia.isLinkLocalAddress() && - !ia.isSiteLocalAddress() && - !ia.isLoopbackAddress()) { - has_globaladdress = true; - } - } - } - } - - /* - * If IPv6 is enabled perform multicast tests with various scopes - */ - if (has_ipv6) { + // If IPv6 is enabled perform multicast tests with various scopes + if (nc.hasTestableIPv6Address()) { doTest("ff01::a"); } - if (has_linklocaladdress) { + if (nc.hasLinkLocalAddress()) { doTest("ff02::a"); } - if (has_siteaddress) { + if (nc.hasSiteLocalAddress()) { doTest("ff05::a"); } - if (has_globaladdress) { + if (nc.has_globaladdress()) { doTest("ff0e::a"); } } @@ -186,7 +163,7 @@ if (args.length == 0) { t.allTests(); } else { - for (int i=0; i= 8) - * @library /lib / + * @library /test/lib / * @key jfr * @run main/othervm/timeout=30 -XX:+FlightRecorder -XX:StartFlightRecording JFRSecurityTestSuite * @author Martin Balao (mbalao@redhat.com) diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestBadOptionValues.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestBadOptionValues.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestBadOptionValues.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestBadOptionValues.java 2024-01-11 01:53:23.000000000 +0000 @@ -35,7 +35,7 @@ * @key jfr * * - * @library /lib / + * @library /test/lib / * * diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestDumpOnExit.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestDumpOnExit.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestDumpOnExit.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestDumpOnExit.java 2024-01-11 01:53:23.000000000 +0000 @@ -43,7 +43,7 @@ * @summary Start a FlightRecording with dumponexit. Verify dump exists. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.startupargs.TestDumpOnExit */ public class TestDumpOnExit { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMemoryOptions.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMemoryOptions.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMemoryOptions.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMemoryOptions.java 2024-01-11 01:53:23.000000000 +0000 @@ -38,7 +38,7 @@ * @test * @key jfr * - * @library /lib / + * @library /test/lib / * * @run main/timeout=900 jdk.jfr.startupargs.TestMemoryOptions */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMultipleStartupRecordings.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMultipleStartupRecordings.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMultipleStartupRecordings.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestMultipleStartupRecordings.java 2024-01-11 01:53:23.000000000 +0000 @@ -34,7 +34,7 @@ * @key jfr * * - * @library /lib / + * @library /test/lib / * * @run main jdk.jfr.startupargs.TestMultipleStartupRecordings */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestOldObjectQueueSize.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestOldObjectQueueSize.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestOldObjectQueueSize.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestOldObjectQueueSize.java 2024-01-11 01:53:23.000000000 +0000 @@ -39,7 +39,7 @@ * @summary Test -XX:FlightRecorderOptions=old-object-queue-size * * - * @library /lib / + * @library /test/lib / * @key jfr * * @run main/othervm -XX:TLABSize=2k -XX:-FastTLABRefill -XX:FlightRecorderOptions=old-object-queue-size=0 jdk.jfr.startupargs.TestOldObjectQueueSize off diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPath.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPath.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPath.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPath.java 2024-01-11 01:53:23.000000000 +0000 @@ -36,7 +36,7 @@ * @summary Set repository path. Verify recording created in repo. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=TestStartRecording,settings=profile -XX:FlightRecorderOptions=repository=./repo jdk.jfr.startupargs.TestRepositoryPath */ public class TestRepositoryPath { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPathLong.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPathLong.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPathLong.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRepositoryPathLong.java 2024-01-11 01:53:23.000000000 +0000 @@ -36,7 +36,7 @@ * @summary Set repository path. Verify recording created in repo. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=myrec,settings=profile -XX:FlightRecorderOptions=repository=./subdirectory/subdirectory1/subdirectory2/subdirectory3/subdirectory4/subdirectory5/subdirectory6/subdirectory7/subdirectory8/subdirectory9/subdirectory10/subdirectory11/subdirectory12/subdirectory13/subdirectory14/subdirectory15 jdk.jfr.startupargs.TestRepositoryPathLong */ public class TestRepositoryPathLong { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransform.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransform.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransform.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransform.java 2024-01-11 01:53:23.000000000 +0000 @@ -36,7 +36,7 @@ * @test * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:FlightRecorderOptions=retransform=false jdk.jfr.startupargs.TestRetransform * @run main/othervm -XX:FlightRecorderOptions=retransform=true jdk.jfr.startupargs.TestRetransform */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransformUsingLog.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransformUsingLog.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransformUsingLog.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestRetransformUsingLog.java 2024-01-11 01:53:23.000000000 +0000 @@ -38,7 +38,7 @@ * @test * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.startupargs.TestRetransformUsingLog */ public class TestRetransformUsingLog { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelay.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelay.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelay.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelay.java 2024-01-11 01:53:23.000000000 +0000 @@ -38,7 +38,7 @@ * @summary Start a recording with delay. Verify recording starts later. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=TestStartDelay,delay=5000s jdk.jfr.startupargs.TestStartDelay */ public class TestStartDelay { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelayRunning.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelayRunning.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelayRunning.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDelayRunning.java 2024-01-11 01:53:23.000000000 +0000 @@ -37,7 +37,7 @@ * @summary Verify that a recopding with a delay is started. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=TestStartDelay,delay=1s jdk.jfr.startupargs.TestStartDelayRunning */ public class TestStartDelayRunning { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDuration.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDuration.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDuration.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartDuration.java 2024-01-11 01:53:23.000000000 +0000 @@ -39,7 +39,7 @@ * @summary Start a recording with duration. Verify recording stops. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main jdk.jfr.startupargs.TestStartDuration */ public class TestStartDuration { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartMaxAgeSize.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartMaxAgeSize.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartMaxAgeSize.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartMaxAgeSize.java 2024-01-11 01:53:23.000000000 +0000 @@ -37,7 +37,7 @@ * @summary Start a recording with delay. Verify recording starts later. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=TestStartMaxAgeSize,maxage=10s,maxsize=1000000 jdk.jfr.startupargs.TestStartMaxAgeSize */ public class TestStartMaxAgeSize { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartName.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartName.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartName.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartName.java 2024-01-11 01:53:23.000000000 +0000 @@ -34,7 +34,7 @@ * @test * @key jfr * - * @library /lib / + * @library /test/lib / * @run main jdk.jfr.startupargs.TestStartName */ public class TestStartName { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartNoSettings.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartNoSettings.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartNoSettings.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartNoSettings.java 2024-01-11 01:53:23.000000000 +0000 @@ -35,7 +35,7 @@ * @test * @summary Start a FlightRecording without any settings (not even default). * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.startupargs.TestStartNoSettings * -XX:StartFlightRecording=settings=none */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartRecording.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartRecording.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartRecording.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/startupargs/TestStartRecording.java 2024-01-11 01:53:23.000000000 +0000 @@ -37,7 +37,7 @@ * @summary Start a recording with -XX:StartFlightRecording. Dump recording with jcmd. * @key jfr * - * @library /lib / + * @library /test/lib / * @run main/othervm -XX:StartFlightRecording=name=TestStartRecording,settings=profile jdk.jfr.startupargs.TestStartRecording */ public class TestStartRecording { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestAssemble.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestAssemble.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestAssemble.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestAssemble.java 2024-01-11 01:53:23.000000000 +0000 @@ -45,7 +45,7 @@ * @test * @summary Test jfr reconstruct * @key jfr - * @library /lib / + * @library /test/lib / * @modules jdk.jfr/jdk.jfr.internal * @run main/othervm jdk.jfr.tool.TestAssemble */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestDisassemble.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestDisassemble.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestDisassemble.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestDisassemble.java 2024-01-11 01:53:23.000000000 +0000 @@ -42,7 +42,7 @@ * @test * @summary Test jfr split * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.tool.TestDisassemble */ public class TestDisassemble { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestHelp.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestHelp.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestHelp.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestHelp.java 2024-01-11 01:53:23.000000000 +0000 @@ -31,7 +31,7 @@ * @test * @summary Test help * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.tool.TestHelp */ public class TestHelp { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestMetadata.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestMetadata.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestMetadata.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestMetadata.java 2024-01-11 01:53:23.000000000 +0000 @@ -35,7 +35,7 @@ * @test * @summary Test jfr info * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.tool.TestMetadata */ public class TestMetadata { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrint.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrint.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrint.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrint.java 2024-01-11 01:53:23.000000000 +0000 @@ -36,7 +36,7 @@ * @test * @summary Test jfr print * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.tool.TestPrint */ public class TestPrint { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintDefault.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintDefault.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintDefault.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintDefault.java 2024-01-11 01:53:23.000000000 +0000 @@ -34,7 +34,7 @@ * @key jfr * @summary Tests print --json * - * @library /lib / + * @library /test/lib / * @modules java.scripting * jdk.jfr * diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintJSON.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintJSON.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintJSON.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintJSON.java 2024-01-11 01:53:23.000000000 +0000 @@ -49,7 +49,7 @@ * @key jfr * @summary Tests print --json * - * @library /lib / + * @library /test/lib / * @modules jdk.scripting.nashorn * jdk.jfr * diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintXML.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintXML.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintXML.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestPrintXML.java 2024-01-11 01:53:23.000000000 +0000 @@ -64,7 +64,7 @@ * @key jfr * @summary Tests print --xml * - * @library /lib / + * @library /test/lib / * @modules java.scripting java.xml jdk.jfr * * @run main/othervm jdk.jfr.tool.TestPrintXML diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestSummary.java openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestSummary.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestSummary.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/jfr/tool/TestSummary.java 2024-01-11 01:53:23.000000000 +0000 @@ -35,7 +35,7 @@ * @test * @summary Test jfr info * @key jfr - * @library /lib / + * @library /test/lib / * @run main/othervm jdk.jfr.tool.TestSummary */ public class TestSummary { diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/tools/launcher/JliLaunchTest.sh openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/tools/launcher/JliLaunchTest.sh --- openjdk-8-8u392-ga/=unpacked-tar3=/test/jdk/tools/launcher/JliLaunchTest.sh 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/jdk/tools/launcher/JliLaunchTest.sh 2024-01-11 01:53:23.000000000 +0000 @@ -2,7 +2,7 @@ # @test JliLaunchTest.sh # @bug 8238225 -# @library /lib +# @library /test/lib # @build JliLaunchTest # @run shell JliLaunchTest.sh diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/ClassFileInstaller.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/ClassFileInstaller.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/ClassFileInstaller.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/ClassFileInstaller.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.ByteArrayInputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** - * Dump a class file for a class on the class path in the current directory, or - * in the specified JAR file. This class is usually used when you build a class - * from a test library, but want to use this class in a sub-process. - * - * For example, to build the following library class: - * test/lib/sun/hotspot/WhiteBox.java - * - * You would use the following tags: - * - * @library /test/lib - * @build sun.hotspot.WhiteBox - * - * JTREG would build the class file under - * ${JTWork}/classes/test/lib/sun/hotspot/WhiteBox.class - * - * With you run your main test class using "@run main MyMainClass", JTREG would setup the - * -classpath to include "${JTWork}/classes/test/lib/", so MyMainClass would be able to - * load the WhiteBox class. - * - * However, if you run a sub process, and do not wish to use the exact same -classpath, - * You can use ClassFileInstaller to ensure that WhiteBox is available in the current - * directory of your test: - * - * @run main ClassFileInstaller sun.hotspot.WhiteBox - * - * Or, you can use the -jar option to store the class in the specified JAR file. If a relative - * path name is given, the JAR file would be relative to the current directory of - * - * @run main ClassFileInstaller -jar myjar.jar sun.hotspot.WhiteBox - */ -public class ClassFileInstaller { - /** - * You can enable debug tracing of ClassFileInstaller by running JTREG with - * jtreg -DClassFileInstaller.debug=true ... - */ - public static boolean DEBUG = Boolean.getBoolean("ClassFileInstaller.debug"); - - /** - * @param args The names of the classes to dump - * @throws Exception - */ - public static void main(String... args) throws Exception { - if (args.length > 1 && args[0].equals("-jar")) { - if (args.length < 2) { - throw new RuntimeException("Usage: ClassFileInstaller \n" + - "where possible options include:\n" + - " -jar Write to the JAR file "); - } - writeJar(args[1], null, args, 2, args.length); - } else { - if (DEBUG) { - System.out.println("ClassFileInstaller: Writing to " + System.getProperty("user.dir")); - } - for (String arg : args) { - writeClassToDisk(arg); - } - } - } - - public static class Manifest { - private InputStream in; - - private Manifest(InputStream in) { - this.in = in; - } - - static Manifest fromSourceFile(String fileName) throws Exception { - String pathName = System.getProperty("test.src") + File.separator + fileName; - return new Manifest(new FileInputStream(pathName)); - } - - // Example: - // String manifest = "Premain-Class: RedefineClassHelper\n" + - // "Can-Redefine-Classes: true\n"; - // ClassFileInstaller.writeJar("redefineagent.jar", - // ClassFileInstaller.Manifest.fromString(manifest), - // "RedefineClassHelper"); - static Manifest fromString(String manifest) throws Exception { - return new Manifest(new ByteArrayInputStream(manifest.getBytes())); - } - - public InputStream getInputStream() { - return in; - } - } - - private static void writeJar(String jarFile, Manifest manifest, String classes[], int from, int to) throws Exception { - if (DEBUG) { - System.out.println("ClassFileInstaller: Writing to " + getJarPath(jarFile)); - } - - (new File(jarFile)).delete(); - FileOutputStream fos = new FileOutputStream(jarFile); - ZipOutputStream zos = new ZipOutputStream(fos); - - // The manifest must be the first or second entry. See comments in JarInputStream - // constructor and JDK-5046178. - if (manifest != null) { - writeToDisk(zos, "META-INF/MANIFEST.MF", manifest.getInputStream()); - } - - for (int i=from; i 0) { - pathName = prependPath + "/" + pathName; - } - writeToDisk(zos, pathName, is); - } - - public static void writeClassToDisk(String className, byte[] bytecode) throws Exception { - writeClassToDisk(null, className, bytecode); - } - private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode) throws Exception { - writeClassToDisk(zos, className, bytecode, ""); - } - - public static void writeClassToDisk(String className, byte[] bytecode, String prependPath) throws Exception { - writeClassToDisk(null, className, bytecode, prependPath); - } - private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode, String prependPath) throws Exception { - // Convert dotted class name to a path to a class file - String pathName = className.replace('.', '/').concat(".class"); - if (prependPath.length() > 0) { - pathName = prependPath + "/" + pathName; - } - writeToDisk(zos, pathName, new ByteArrayInputStream(bytecode)); - } - - private static void writeToDisk(ZipOutputStream zos, String pathName, InputStream is) throws Exception { - if (DEBUG) { - System.out.println("ClassFileInstaller: Writing " + pathName); - } - if (zos != null) { - ZipEntry ze = new ZipEntry(pathName); - zos.putNextEntry(ze); - byte[] buf = new byte[1024]; - int len; - while ((len = is.read(buf))>0){ - zos.write(buf, 0, len); - } - } else { - // Create the class file's package directory - Path p = Paths.get(pathName); - if (pathName.contains("/")) { - Files.createDirectories(p.getParent()); - } - // Create the class file - Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING); - } - is.close(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/RedefineClassHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/RedefineClassHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/RedefineClassHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/RedefineClassHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.PrintWriter; -import java.lang.instrument.*; -import jdk.test.lib.compiler.InMemoryJavaCompiler; - -/* - * Helper class to write tests that redefine classes. - * When main method is run, it will create a redefineagent.jar that can be used - * with the -javaagent option to support redefining classes in jtreg tests. - * - * See sample test in test/testlibrary_tests/RedefineClassTest.java - */ -public class RedefineClassHelper { - - public static Instrumentation instrumentation; - public static void premain(String agentArgs, Instrumentation inst) { - instrumentation = inst; - } - - /** - * Redefine a class - * - * @param clazz Class to redefine - * @param javacode String with the new java code for the class to be redefined - */ - public static void redefineClass(Class clazz, String javacode) throws Exception { - byte[] bytecode = InMemoryJavaCompiler.compile(clazz.getName(), javacode); - redefineClass(clazz, bytecode); - } - - /** - * Redefine a class - * - * @param clazz Class to redefine - * @param bytecode byte[] with the new class - */ - public static void redefineClass(Class clazz, byte[] bytecode) throws Exception { - instrumentation.redefineClasses(new ClassDefinition(clazz, bytecode)); - } - - /** - * Main method to be invoked before test to create the redefineagent.jar - */ - public static void main(String[] args) throws Exception { - ClassFileInstaller.main("RedefineClassHelper"); - - PrintWriter pw = new PrintWriter("MANIFEST.MF"); - pw.println("Premain-Class: RedefineClassHelper"); - pw.println("Can-Redefine-Classes: true"); - pw.close(); - - sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); - if (!jarTool.run(new String[] { "-cmf", "MANIFEST.MF", "redefineagent.jar", "RedefineClassHelper.class" })) { - throw new Exception("jar operation failed"); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Asserts.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Asserts.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Asserts.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Asserts.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,620 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.Objects; - -/** - * Asserts that can be used for verifying assumptions in tests. - * - * An assertion will throw a {@link RuntimeException} if the assertion isn't true. - * All the asserts can be imported into a test by using a static import: - * - *
- * {@code
- * import static jdk.testlibrary.Asserts.*;
- * }
- *
- * Always provide a message describing the assumption if the line number of the
- * failing assertion isn't enough to understand why the assumption failed. For
- * example, if the assertion is in a loop or in a method that is called
- * multiple times, then the line number won't provide enough context to
- * understand the failure.
- * 
- */ -public class Asserts { - - /** - * Shorthand for {@link #assertLessThan(Comparable, Comparable)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertLessThan(Comparable, Comparable) - */ - public static > void assertLT(T lhs, T rhs) { - assertLessThan(lhs, rhs); - } - - /** - * Shorthand for {@link #assertLessThan(Comparable, Comparable, String)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertLessThan(Comparable, Comparable, String) - */ - public static > void assertLT(T lhs, T rhs, String msg) { - assertLessThan(lhs, rhs, msg); - } - - /** - * Calls {@link #assertLessThan(Comparable, Comparable, String)} with a default message. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertLessThan(Comparable, Comparable, String) - */ - public static > void assertLessThan(T lhs, T rhs) { - assertLessThan(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is less than {@code rhs}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static >void assertLessThan(T lhs, T rhs, String msg) { - if (!(compare(lhs, rhs, msg) < 0)) { - msg = Objects.toString(msg, "assertLessThan") - + ": expected that " + Objects.toString(lhs) - + " < " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Shorthand for {@link #assertLessThanOrEqual(Comparable, Comparable)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertLessThanOrEqual(Comparable, Comparable) - */ - public static > void assertLTE(T lhs, T rhs) { - assertLessThanOrEqual(lhs, rhs); - } - - /** - * Shorthand for {@link #assertLessThanOrEqual(Comparable, Comparable, String)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertLessThanOrEqual(Comparable, Comparable, String) - */ - public static > void assertLTE(T lhs, T rhs, String msg) { - assertLessThanOrEqual(lhs, rhs, msg); - } - - /** - * Calls {@link #assertLessThanOrEqual(Comparable, Comparable, String)} with a default message. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertLessThanOrEqual(Comparable, Comparable, String) - */ - public static > void assertLessThanOrEqual(T lhs, T rhs) { - assertLessThanOrEqual(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is less than or equal to {@code rhs}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static > void assertLessThanOrEqual(T lhs, T rhs, String msg) { - if (!(compare(lhs, rhs, msg) <= 0)) { - msg = Objects.toString(msg, "assertLessThanOrEqual") - + ": expected that " + Objects.toString(lhs) - + " <= " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Shorthand for {@link #assertEquals(Object, Object)}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertEquals(Object, Object) - */ - public static void assertEQ(Object lhs, Object rhs) { - assertEquals(lhs, rhs); - } - - /** - * Shorthand for {@link #assertEquals(Object, Object, String)}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertEquals(Object, Object, String) - */ - public static void assertEQ(Object lhs, Object rhs, String msg) { - assertEquals(lhs, rhs, msg); - } - - /** - * Calls {@link #assertEquals(java.lang.Object, java.lang.Object, java.lang.String)} with a default message. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertEquals(Object, Object, String) - */ - public static void assertEquals(Object lhs, Object rhs) { - assertEquals(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is equal to {@code rhs}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertEquals(Object lhs, Object rhs, String msg) { - if ((lhs != rhs) && ((lhs == null) || !(lhs.equals(rhs)))) { - msg = Objects.toString(msg, "assertEquals") - + ": expected " + Objects.toString(lhs) - + " to equal " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Calls {@link #assertSame(java.lang.Object, java.lang.Object, java.lang.String)} with a default message. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertSame(Object, Object, String) - */ - public static void assertSame(Object lhs, Object rhs) { - assertSame(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is the same as {@code rhs}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertSame(Object lhs, Object rhs, String msg) { - if (lhs != rhs) { - msg = Objects.toString(msg, "assertSame") - + ": expected " + Objects.toString(lhs) - + " to equal " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Shorthand for {@link #assertGreaterThanOrEqual(Comparable, Comparable)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertGreaterThanOrEqual(Comparable, Comparable) - */ - public static > void assertGTE(T lhs, T rhs) { - assertGreaterThanOrEqual(lhs, rhs); - } - - /** - * Shorthand for {@link #assertGreaterThanOrEqual(Comparable, Comparable, String)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertGreaterThanOrEqual(Comparable, Comparable, String) - */ - public static > void assertGTE(T lhs, T rhs, String msg) { - assertGreaterThanOrEqual(lhs, rhs, msg); - } - - /** - * Calls {@link #assertGreaterThanOrEqual(Comparable, Comparable, String)} with a default message. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertGreaterThanOrEqual(Comparable, Comparable, String) - */ - public static > void assertGreaterThanOrEqual(T lhs, T rhs) { - assertGreaterThanOrEqual(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is greater than or equal to {@code rhs}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static > void assertGreaterThanOrEqual(T lhs, T rhs, String msg) { - if (!(compare(lhs, rhs, msg) >= 0)) { - msg = Objects.toString(msg, "assertGreaterThanOrEqual") - + ": expected " + Objects.toString(lhs) - + " >= " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Shorthand for {@link #assertGreaterThan(Comparable, Comparable)}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertGreaterThan(Comparable, Comparable) - */ - public static > void assertGT(T lhs, T rhs) { - assertGreaterThan(lhs, rhs); - } - - /** - * Shorthand for {@link #assertGreaterThan(Comparable, Comparable, String)}. - * - * @param a type - * @param lhs the left hand value - * @param rhs the right hand value - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertGreaterThan(Comparable, Comparable, String) - */ - public static > void assertGT(T lhs, T rhs, String msg) { - assertGreaterThan(lhs, rhs, msg); - } - - /** - * Calls {@link #assertGreaterThan(Comparable, Comparable, String)} with a default message. - * - * @param a type - * @param lhs the left hand value - * @param rhs the right hand value - * @see #assertGreaterThan(Comparable, Comparable, String) - */ - public static > void assertGreaterThan(T lhs, T rhs) { - assertGreaterThan(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is greater than {@code rhs}. - * - * @param a type - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static > void assertGreaterThan(T lhs, T rhs, String msg) { - if (!(compare(lhs, rhs, msg) > 0)) { - msg = Objects.toString(msg, "assertGreaterThan") - + ": expected " + Objects.toString(lhs) - + " > " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Shorthand for {@link #assertNotEquals(Object, Object)}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertNotEquals(Object, Object) - */ - public static void assertNE(Object lhs, Object rhs) { - assertNotEquals(lhs, rhs); - } - - /** - * Shorthand for {@link #assertNotEquals(Object, Object, String)}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @see #assertNotEquals(Object, Object, String) - */ - public static void assertNE(Object lhs, Object rhs, String msg) { - assertNotEquals(lhs, rhs, msg); - } - - /** - * Calls {@link #assertNotEquals(Object, Object, String)} with a default message. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @see #assertNotEquals(Object, Object, String) - */ - public static void assertNotEquals(Object lhs, Object rhs) { - assertNotEquals(lhs, rhs, null); - } - - /** - * Asserts that {@code lhs} is not equal to {@code rhs}. - * - * @param lhs The left hand side of the comparison. - * @param rhs The right hand side of the comparison. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertNotEquals(Object lhs, Object rhs, String msg) { - if ((lhs == rhs) || (lhs != null && lhs.equals(rhs))) { - msg = Objects.toString(msg, "assertNotEquals") - + ": expected " + Objects.toString(lhs) - + " to not equal " + Objects.toString(rhs); - fail(msg); - } - } - - /** - * Calls {@link #assertNull(Object, String)} with a default message. - * - * @param o The reference assumed to be null. - * @see #assertNull(Object, String) - */ - public static void assertNull(Object o) { - assertNull(o, null); - } - - /** - * Asserts that {@code o} is null. - * - * @param o The reference assumed to be null. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertNull(Object o, String msg) { - assertEquals(o, null, msg); - } - - /** - * Calls {@link #assertNotNull(Object, String)} with a default message. - * - * @param o The reference assumed not to be null, - * @see #assertNotNull(Object, String) - */ - public static void assertNotNull(Object o) { - assertNotNull(o, null); - } - - /** - * Asserts that {@code o} is not null. - * - * @param o The reference assumed not to be null, - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertNotNull(Object o, String msg) { - assertNotEquals(o, null, msg); - } - - /** - * Calls {@link #assertFalse(boolean, String)} with a default message. - * - * @param value The value assumed to be false. - * @see #assertFalse(boolean, String) - */ - public static void assertFalse(boolean value) { - assertFalse(value, null); - } - - /** - * Asserts that {@code value} is {@code false}. - * - * @param value The value assumed to be false. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertFalse(boolean value, String msg) { - if (value) { - msg = Objects.toString(msg, "assertFalse") - + ": expected false, was true"; - fail(msg); - } - } - - /** - * Calls {@link #assertTrue(boolean, String)} with a default message. - * - * @param value The value assumed to be true. - * @see #assertTrue(boolean, String) - */ - public static void assertTrue(boolean value) { - assertTrue(value, null); - } - - /** - * Asserts that {@code value} is {@code true}. - * - * @param value The value assumed to be true. - * @param msg A description of the assumption; {@code null} for a default message. - * @throws RuntimeException if the assertion is not true. - */ - public static void assertTrue(boolean value, String msg) { - if (!value) { - msg = Objects.toString(msg, "assertTrue") - + ": expected true, was false"; - fail(msg); - } - } - - private static > int compare(T lhs, T rhs, String msg) { - if (lhs == null || rhs == null) { - fail(lhs, rhs, msg + ": values must be non-null:", ","); - } - return lhs.compareTo(rhs); - } - -/** - * Asserts that two strings are equal. - * - * If strings are not equals, then exception message - * will contain {@code msg} followed by list of mismatched lines. - * - * @param str1 First string to compare. - * @param str2 Second string to compare. - * @param msg A description of the assumption. - * @throws RuntimeException if strings are not equal. - */ - public static void assertStringsEqual(String str1, String str2, - String msg) { - String lineSeparator = System.getProperty("line.separator"); - String str1Lines[] = str1.split(lineSeparator); - String str2Lines[] = str2.split(lineSeparator); - - int minLength = Math.min(str1Lines.length, str2Lines.length); - String longestStringLines[] = ((str1Lines.length == minLength) ? - str2Lines : str1Lines); - - boolean stringsAreDifferent = false; - - StringBuilder messageBuilder = new StringBuilder(msg); - - messageBuilder.append("\n"); - - for (int line = 0; line < minLength; line++) { - if (!str1Lines[line].equals(str2Lines[line])) { - messageBuilder.append(String. - format("[line %d] '%s' differs " + - "from '%s'\n", - line, - str1Lines[line], - str2Lines[line])); - stringsAreDifferent = true; - } - } - - if (minLength < longestStringLines.length) { - String stringName = ((longestStringLines == str1Lines) ? - "first" : "second"); - messageBuilder.append(String.format("Only %s string contains " + - "following lines:\n", - stringName)); - stringsAreDifferent = true; - for(int line = minLength; line < longestStringLines.length; line++) { - messageBuilder.append(String. - format("[line %d] '%s'", line, - longestStringLines[line])); - } - } - - if (stringsAreDifferent) { - fail(messageBuilder.toString()); - } - } - - /** - * Returns a string formatted with a message and expected and actual values. - * @param lhs the actual value - * @param rhs the expected value - * @param message the actual value - * @param relation the asserted relationship between lhs and rhs - * @return a formatted string - */ - public static String format(Object lhs, Object rhs, String message, String relation) { - StringBuilder sb = new StringBuilder(80); - if (message != null) { - sb.append(message); - sb.append(' '); - } - sb.append("<"); - sb.append(Objects.toString(lhs)); - sb.append("> "); - sb.append(Objects.toString(relation, ",")); - sb.append(" <"); - sb.append(Objects.toString(rhs)); - sb.append(">"); - return sb.toString(); - } - - /** - * Fail reports a failure with message fail. - * - * @throws RuntimeException always - */ - public static void fail() { - fail("fail"); - } - - /** - * Fail reports a failure with a message. - * @param message for the failure - * @throws RuntimeException always - */ - public static void fail(String message) { - throw new RuntimeException(message); - } - - /** - * Fail reports a failure with a formatted message. - * - * @param lhs the actual value - * @param rhs the expected value - * @param message to be format before the expected and actual values - * @param relation the asserted relationship between lhs and rhs - * @throws RuntimeException always - */ - public static void fail(Object lhs, Object rhs, String message, String relation) { - throw new RuntimeException(format(lhs, rhs, message, relation)); - } - - /** - * Fail reports a failure with a message and a cause. - * @param message to be format before the expected and actual values - * @param cause the exception that caused this failure - * @throws RuntimeException always - */ - public static void fail(String message, Throwable cause) { - throw new RuntimeException(message, cause); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/BuildHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/BuildHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/BuildHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/BuildHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.File; -import java.io.FileReader; -import java.util.Properties; - -public class BuildHelper { - - /** - * Commercial builds should have the BUILD_TYPE set to commercial - * within the release file, found at the root of the JDK. - */ - public static boolean isCommercialBuild() throws Exception { - String buildType = getReleaseProperty("BUILD_TYPE","notFound"); - return buildType.equals("commercial"); - } - - - /** - * Return the value for property key, or defaultValue if no property not found. - * If present, double quotes are trimmed. - */ - public static String getReleaseProperty(String key, String defaultValue) throws Exception { - Properties properties = getReleaseProperties(); - String value = properties.getProperty(key, defaultValue); - return trimDoubleQuotes(value); - } - - /** - * Return the value for property key, or null if no property not found. - * If present, double quotes are trimmed. - */ - public static String getReleaseProperty(String key) throws Exception { - return getReleaseProperty(key, null); - } - - /** - * Get properties from the release file - */ - public static Properties getReleaseProperties() throws Exception { - Properties properties = new Properties(); - properties.load(new FileReader(getReleaseFile())); - return properties; - } - - /** - * Every JDK has a release file in its root. - * @return A handler to the release file. - */ - public static File getReleaseFile() throws Exception { - String jdkPath = getJDKRoot(); - File releaseFile = new File(jdkPath,"release"); - if ( ! releaseFile.canRead() ) { - throw new Exception("Release file is not readable, or it is absent: " + - releaseFile.getCanonicalPath()); - } - return releaseFile; - } - - /** - * Returns path to the JDK under test. - * This path is obtained through the test.jdk property, usually set by JTREG. - */ - public static String getJDKRoot() { - String jdkPath = System.getProperty("test.jdk"); - if (jdkPath == null) { - throw new RuntimeException("System property 'test.jdk' not set. This property is normally set by jtreg. " - + "When running test separately, set this property using '-Dtest.jdk=/path/to/jdk'."); - } - return jdkPath; - } - - /** - * Trim double quotes from the beginning and the end of the given string. - * @param original string to trim. - * @return a new trimmed string. - */ - public static String trimDoubleQuotes(String original) { - if (original == null) { return null; } - String trimmed = original.replaceAll("^\"+|\"+$", ""); - return trimmed; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/ByteCodeLoader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/ByteCodeLoader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/ByteCodeLoader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/ByteCodeLoader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.security.SecureClassLoader; - -/** - * {@code ByteCodeLoader} can be used for easy loading of byte code already - * present in memory. - * - * {@code InMemoryCompiler} can be used for compiling source code in a string - * into byte code, which then can be loaded with {@code ByteCodeLoader}. - * - * @see InMemoryCompiler - */ -public class ByteCodeLoader extends SecureClassLoader { - private final String className; - private final byte[] byteCode; - private volatile Class holder; - - /** - * Creates a new {@code ByteCodeLoader} ready to load a class with the - * given name and the given byte code. - * - * @param className The name of the class - * @param byteCode The byte code of the class - */ - public ByteCodeLoader(String className, byte[] byteCode) { - this.className = className; - this.byteCode = byteCode; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (!name.equals(className)) { - return super.loadClass(name); - } - if (holder == null) { - synchronized(this) { - if (holder == null) { - holder = findClass(name); - } - } - } - return holder; - } - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (!name.equals(className)) { - throw new ClassNotFoundException(name); - } - - return defineClass(name, byteCode, 0, byteCode.length); - } - - /** - * Utility method for creating a new {@code ByteCodeLoader} and then - * directly load the given byte code. - * - * @param className The name of the class - * @param byteCode The byte code for the class - * @throws ClassNotFoundException if the class can't be loaded - * @return A {@see Class} object representing the class - */ - public static Class load(String className, byte[] byteCode) throws ClassNotFoundException { - return new ByteCodeLoader(className, byteCode).loadClass(className); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Container.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Container.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Container.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Container.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2019, Red Hat Inc. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib; - -public class Container { - // Use this property to specify docker location on your system. - // E.g.: "/usr/local/bin/docker". We define this constant here so - // that it can be used in VMProps as well which checks docker support - // via this command - public static final String ENGINE_COMMAND = - System.getProperty("jdk.test.container.command", "docker"); -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Convert.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Convert.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Convert.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Convert.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.math.BigInteger; - -/** - * Utility class containing conversions between strings, arrays, and numeric - * values. - */ - -public class Convert { - - // Convert from a byte array to a hexadecimal representation as a string. - public static String byteArrayToHexString(byte[] arr) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < arr.length; ++i) { - byte curVal = arr[i]; - result.append(Character.forDigit(curVal >> 4 & 0xF, 16)); - result.append(Character.forDigit(curVal & 0xF, 16)); - } - return result.toString(); - } - - // Expand a single byte to a byte array - public static byte[] byteToByteArray(byte v, int length) { - byte[] result = new byte[length]; - result[0] = v; - return result; - } - - // Convert a hexadecimal string to a byte array - public static byte[] hexStringToByteArray(String str) { - byte[] result = new byte[str.length() / 2]; - for (int i = 0; i < result.length; i++) { - result[i] = (byte) Character.digit(str.charAt(2 * i), 16); - result[i] <<= 4; - result[i] += Character.digit(str.charAt(2 * i + 1), 16); - } - return result; - } - - /* - * Convert a hexadecimal string to the corresponding little-ending number - * as a BigInteger. The clearHighBit argument determines whether the most - * significant bit of the highest byte should be set to 0 in the result. - */ - public static - BigInteger hexStringToBigInteger(boolean clearHighBit, String str) { - BigInteger result = BigInteger.ZERO; - for (int i = 0; i < str.length() / 2; i++) { - int curVal = Character.digit(str.charAt(2 * i), 16); - curVal <<= 4; - curVal += Character.digit(str.charAt(2 * i + 1), 16); - if (clearHighBit && i == str.length() / 2 - 1) { - curVal &= 0x7F; - } - result = result.add(BigInteger.valueOf(curVal).shiftLeft(8 * i)); - } - return result; - } -} - - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/FileInstaller.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/FileInstaller.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/FileInstaller.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/FileInstaller.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; - -// !!! -// NOTE: this class is widely used. DO NOT depend on any other classes in any test library, or else -// you may see intermittent ClassNotFoundException as in JDK-8188828 -// !!! - -/** - * Copy a resource: file or directory recursively, using relative path(src and dst) - * which are applied to test source directory(src) and current directory(dst) - */ -public class FileInstaller { - public static final String TEST_SRC = System.getProperty("test.src", "").trim(); - - /** - * @param args source and destination - * @throws IOException if an I/O error occurs - */ - public static void main(String[] args) throws IOException { - if (args.length != 2) { - throw new IllegalArgumentException("Unexpected number of arguments for file copy"); - } - Path src = Paths.get(TEST_SRC, args[0]).toAbsolutePath().normalize(); - Path dst = Paths.get(args[1]).toAbsolutePath().normalize(); - if (src.toFile().exists()) { - System.out.printf("copying %s to %s%n", src, dst); - if (src.toFile().isDirectory()) { - // can't use Files::copy for dirs, as 'dst' might exist already - Files.walkFileTree(src, new CopyFileVisitor(src, dst)); - } else { - Path dstDir = dst.getParent(); - if (!dstDir.toFile().exists()) { - Files.createDirectories(dstDir); - } - Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); - } - } else { - throw new IOException("Can't find source " + src); - } - } - - private static class CopyFileVisitor extends SimpleFileVisitor { - private final Path copyFrom; - private final Path copyTo; - - public CopyFileVisitor(Path copyFrom, Path copyTo) { - this.copyFrom = copyFrom; - this.copyTo = copyTo; - } - - @Override - public FileVisitResult preVisitDirectory(Path file, - BasicFileAttributes attrs) throws IOException { - Path relativePath = copyFrom.relativize(file); - Path destination = copyTo.resolve(relativePath); - if (!destination.toFile().exists()) { - Files.createDirectories(destination); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - if (!file.toFile().isFile()) { - return FileVisitResult.CONTINUE; - } - Path relativePath = copyFrom.relativize(file); - Path destination = copyTo.resolve(relativePath); - Files.copy(file, destination, StandardCopyOption.COPY_ATTRIBUTES); - return FileVisitResult.CONTINUE; - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/InfiniteLoop.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/InfiniteLoop.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/InfiniteLoop.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/InfiniteLoop.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.Objects; - -/** - * Class which runs another Runnable in infinite loop with certain pauses - * between cycles. - */ -public class InfiniteLoop implements Runnable { - private final Runnable target; - private final long mills; - - - /** - * @param target a target to run in a loop - * @param mills the length of pause time in milliseconds - * @throws NullPointerException if target is null - * @throws IllegalArgumentException if the value of millis is negative - */ - public InfiniteLoop(Runnable target, long mills) { - Objects.requireNonNull(target); - if (mills < 0) { - throw new IllegalArgumentException("mills < 0"); - } - this.target = target; - this.mills = mills; - } - - @Override - public void run() { - try { - while (true) { - target.run(); - if (mills > 0) { - Thread.sleep(mills); - } - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new Error(e); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolFinder.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolFinder.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolFinder.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolFinder.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.FileNotFoundException; -import java.nio.file.Path; -import java.nio.file.Paths; - -public final class JDKToolFinder { - - private JDKToolFinder() { - } - - /** - * Returns the full path to an executable in jdk/bin based on System - * property {@code test.jdk} or {@code compile.jdk} (both are set by the jtreg test suite) - * - * @return Full path to an executable in jdk/bin - */ - public static String getJDKTool(String tool) { - - // First try to find the executable in test.jdk - try { - return getTool(tool, "test.jdk"); - } catch (FileNotFoundException e) { - - } - - // Now see if it's available in compile.jdk - try { - return getTool(tool, "compile.jdk"); - } catch (FileNotFoundException e) { - throw new RuntimeException("Failed to find " + tool + - ", looked in test.jdk (" + System.getProperty("test.jdk") + - ") and compile.jdk (" + System.getProperty("compile.jdk") + ")"); - } - } - - /** - * Returns the full path to an executable in jdk/bin based on System - * property {@code compile.jdk} - * - * @return Full path to an executable in jdk/bin - */ - public static String getCompileJDKTool(String tool) { - try { - return getTool(tool, "compile.jdk"); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - /** - * Returns the full path to an executable in jdk/bin based on System - * property {@code test.jdk} - * - * @return Full path to an executable in jdk/bin - */ - public static String getTestJDKTool(String tool) { - try { - return getTool(tool, "test.jdk"); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - private static String getTool(String tool, String property) throws FileNotFoundException { - String jdkPath = System.getProperty(property); - - if (jdkPath == null) { - throw new RuntimeException( - "System property '" + property + "' not set. This property is normally set by jtreg. " - + "When running test separately, set this property using '-D" + property + "=/path/to/jdk'."); - } - - Path toolName = Paths.get("bin", tool + (Platform.isWindows() ? ".exe" : "")); - - Path jdkTool = Paths.get(jdkPath, toolName.toString()); - if (!jdkTool.toFile().exists()) { - throw new FileNotFoundException("Could not find file " + jdkTool.toAbsolutePath()); - } - - return jdkTool.toAbsolutePath().toString(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolLauncher.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolLauncher.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolLauncher.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/JDKToolLauncher.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.ArrayList; -import java.util.List; - -/** - * A utility for constructing command lines for starting JDK tool processes. - * - * The JDKToolLauncher can in particular be combined with a - * java.lang.ProcessBuilder to easily run a JDK tool. For example, the following - * code run {@code jmap -heap} against a process with GC logging turned on for - * the {@code jmap} process: - * - *
- * {@code
- * JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
- *                                       .addVMArg("-XX:+PrintGC");
- *                                       .addVMArg("-XX:+PrintGCDetails")
- *                                       .addToolArg("-heap")
- *                                       .addToolArg(pid);
- * ProcessBuilder pb = new ProcessBuilder(jmap.getCommand());
- * Process p = pb.start();
- * }
- * 
- */ -public class JDKToolLauncher { - private final String executable; - private final List vmArgs = new ArrayList(); - private final List toolArgs = new ArrayList(); - - private JDKToolLauncher(String tool, boolean useCompilerJDK) { - if (useCompilerJDK) { - executable = JDKToolFinder.getJDKTool(tool); - } else { - executable = JDKToolFinder.getTestJDKTool(tool); - } - } - - /** - * Creates a new JDKToolLauncher for the specified tool. Using tools path - * from the compiler JDK. - * - * @param tool - * The name of the tool - * @return A new JDKToolLauncher - */ - public static JDKToolLauncher create(String tool) { - return new JDKToolLauncher(tool, true); - } - - /** - * Creates a new JDKToolLauncher for the specified tool in the Tested JDK. - * - * @param tool - * The name of the tool - * - * @return A new JDKToolLauncher - */ - public static JDKToolLauncher createUsingTestJDK(String tool) { - return new JDKToolLauncher(tool, false); - } - - /** - * Adds an argument to the JVM running the tool. - * - * The JVM arguments are passed to the underlying JVM running the tool. - * Arguments will automatically be prepended with "-J". - * - * Any platform specific arguments required for running the tool are - * automatically added. - * - * - * @param arg - * The argument to VM running the tool - * @return The JDKToolLauncher instance - */ - public JDKToolLauncher addVMArg(String arg) { - vmArgs.add(arg); - return this; - } - - /** - * Adds an argument to the tool. - * - * @param arg - * The argument to the tool - * @return The JDKToolLauncher instance - */ - public JDKToolLauncher addToolArg(String arg) { - toolArgs.add(arg); - return this; - } - - /** - * Returns the command that can be used for running the tool. - * - * @return An array whose elements are the arguments of the command. - */ - public String[] getCommand() { - List command = new ArrayList(); - command.add(executable); - // Add -J in front of all vmArgs - for (String arg : vmArgs) { - command.add("-J" + arg); - } - command.addAll(toolArgs); - return command.toArray(new String[command.size()]); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/LockFreeLogger.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/LockFreeLogger.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/LockFreeLogger.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/LockFreeLogger.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -/** - * A logger designed specifically to allow collecting ordered log messages - * in a multi-threaded environment without involving any kind of locking. - *

- * It is particularly useful in situations when one needs to assert various - * details about the tested thread state or the locks it hold while also wanting - * to produce diagnostic log messages. - *

- * The logger does not provide any guarantees about the completness of the - * logs written from different threads - it is up to the caller to make sure - * {@code toString()} method is called only when all the activity has ceased - * and the per-thread logs contain all the necessary data. - * - * @author Jaroslav Bachorik - **/ -public class LockFreeLogger { - private final AtomicInteger logCntr = new AtomicInteger(0); - private final Collection> allRecords = new ConcurrentLinkedQueue<>(); - private final ThreadLocal> records = ThreadLocal.withInitial(ConcurrentHashMap::new); - - public LockFreeLogger() { - allRecords.add(records.get()); - } - - /** - * Log a message - * @param format Message format - * @param params Message parameters - */ - public void log(String format, Object ... params) { - int id = logCntr.getAndIncrement(); - records.get().put(id, String.format(format, params)); - } - - /** - * Will generate an aggregated log of chronologically ordered messages. - *

- * Make sure that you call this method only when all the related threads - * have finished; otherwise you might get incomplete data. - * - * @return An aggregated log of chronologically ordered messages - */ - @Override - public String toString() { - return allRecords.stream() - .flatMap(m -> m.entrySet().stream()) - .sorted(Comparator.comparing(Map.Entry::getKey)) - .map(Map.Entry::getValue) - .collect(Collectors.joining()); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/NetworkConfiguration.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/NetworkConfiguration.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/NetworkConfiguration.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/NetworkConfiguration.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.PrintStream; -import java.io.UncheckedIOException; -import java.io.IOException; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import static java.net.NetworkInterface.getNetworkInterfaces; -import static java.util.Collections.list; - -/** - * Helper class for retrieving network interfaces and local addresses - * suitable for testing. - */ -public class NetworkConfiguration { - - private Map> ip4Interfaces; - private Map> ip6Interfaces; - - private NetworkConfiguration( - Map> ip4Interfaces, - Map> ip6Interfaces) { - this.ip4Interfaces = ip4Interfaces; - this.ip6Interfaces = ip6Interfaces; - } - - /** - * Returns a stream of interfaces suitable for functional tests. - */ - public Stream interfaces() { - return Stream.concat(ip4Interfaces(), ip6Interfaces()) - .distinct(); - } - - /** - * Returns a stream of interfaces suitable for IPv4 functional tests. - */ - public Stream ip4Interfaces() { - return ip4Interfaces.keySet() - .stream() - .filter(NetworkConfiguration::isNotExcludedInterface) - .filter(hasIp4Addresses); - } - - /** - * Returns a stream of interfaces suitable for IPv6 functional tests. - */ - public Stream ip6Interfaces() { - return ip6Interfaces.keySet() - .stream() - .filter(NetworkConfiguration::isNotExcludedInterface) - .filter(hasIp6Addresses); - } - - private static boolean isNotExcludedInterface(NetworkInterface nif) { - if (Platform.isOSX() && nif.getName().contains("awdl")) { - return false; - } - String dName = nif.getDisplayName(); - if (Platform.isWindows() && dName != null && dName.contains("Teredo")) { - return false; - } - return true; - } - - private final Predicate hasIp4Addresses = nif -> - ip4Interfaces.get(nif).stream().anyMatch(a -> !a.isAnyLocalAddress()); - - private final Predicate hasIp6Addresses = nif -> - ip6Interfaces.get(nif).stream().anyMatch(a -> !a.isAnyLocalAddress()); - - - /** - * Returns a stream of interfaces suitable for IPv4 multicast tests. - */ - public Stream ip4MulticastInterfaces() { - return ip4Interfaces().filter(supportsIp4Multicast); - } - - /** - * Returns a stream of interfaces suitable for IPv6 multicast tests. - */ - public Stream ip6MulticastInterfaces() { - return ip6Interfaces().filter(supportsIp6Multicast); - } - - private final Predicate supportsIp4Multicast = nif -> { - try { - if (!nif.supportsMulticast() || nif.isLoopback()) { - return false; - } - return hasIp4Addresses.test(nif); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }; - - private final Predicate supportsIp6Multicast = nif -> { - try { - if (!nif.supportsMulticast() || nif.isLoopback()) { - return false; - } - - return hasIp6Addresses.test(nif); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }; - - /** - * Returns all addresses on all "functional" interfaces. - */ - public Stream addresses(NetworkInterface nif) { - return Stream.concat(ip4Interfaces.get(nif).stream(), - ip6Interfaces.get(nif).stream()); - } - - /** - * Returns all IPv4 addresses on all "functional" interfaces. - */ - public Stream ip4Addresses() { - return ip4Interfaces().flatMap(this::ip4Addresses); - } - - /** - * Returns all IPv6 addresses on all "functional" interfaces. - */ - public Stream ip6Addresses() { - return ip6Interfaces().flatMap(this::ip6Addresses); - } - - /** - * Returns all IPv4 addresses the given interface. - */ - public Stream ip4Addresses(NetworkInterface nif) { - return ip4Interfaces.get(nif).stream(); - } - - /** - * Returns all IPv6 addresses for the given interface. - */ - public Stream ip6Addresses(NetworkInterface nif) { - return ip6Interfaces.get(nif).stream(); - } - - /** - * Return a NetworkConfiguration instance. - */ - public static NetworkConfiguration probe() throws IOException { - Map> ip4Interfaces = new HashMap<>(); - Map> ip6Interfaces = new HashMap<>(); - - List nifs = list(getNetworkInterfaces()); - for (NetworkInterface nif : nifs) { - // ignore interfaces that are down - if (!nif.isUp() || nif.isPointToPoint()) { - continue; - } - - List ip4Addresses = new LinkedList<>(); - List ip6Addresses = new LinkedList<>(); - ip4Interfaces.put(nif, ip4Addresses); - ip6Interfaces.put(nif, ip6Addresses); - for (InetAddress addr : list(nif.getInetAddresses())) { - if (addr instanceof Inet4Address) { - ip4Addresses.add((Inet4Address) addr); - } else if (addr instanceof Inet6Address) { - ip6Addresses.add((Inet6Address) addr); - } - } - } - return new NetworkConfiguration(ip4Interfaces, ip6Interfaces); - } - - @Override - public String toString() { - return interfaces().map(NetworkConfiguration::interfaceInformation) - .collect(Collectors.joining()); - } - - /** Returns detailed information for the given interface. */ - public static String interfaceInformation(NetworkInterface nif) { - StringBuilder sb = new StringBuilder(); - try { - sb.append("Display name: ") - .append(nif.getDisplayName()) - .append("\n"); - sb.append("Name: ") - .append(nif.getName()) - .append("\n"); - for (InetAddress inetAddress : list(nif.getInetAddresses())) { - sb.append("InetAddress: ") - .append(inetAddress) - .append("\n"); - } - sb.append("Up? ") - .append(nif.isUp()) - .append("\n"); - sb.append("Loopback? ") - .append(nif.isLoopback()) - .append("\n"); - sb.append("PointToPoint? ") - .append(nif.isPointToPoint()) - .append("\n"); - sb.append("Supports multicast? ") - .append(nif.supportsMulticast()) - .append("\n"); - sb.append("Virtual? ") - .append(nif.isVirtual()) - .append("\n"); - sb.append("Hardware address: ") - .append(Arrays.toString(nif.getHardwareAddress())) - .append("\n"); - sb.append("MTU: ") - .append(nif.getMTU()) - .append("\n"); - sb.append("Index: ") - .append(nif.getIndex()) - .append("\n"); - sb.append("\n"); - return sb.toString(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - /** Prints all the system interface information to the give stream. */ - public static void printSystemConfiguration(PrintStream out) { - try { - out.println("*** all system network interface configuration ***"); - for (NetworkInterface nif : list(getNetworkInterfaces())) { - out.print(interfaceInformation(nif)); - } - out.println("*** end ***"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Platform.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Platform.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Platform.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Platform.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,378 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -public class Platform { - public static final String vmName = System.getProperty("java.vm.name"); - public static final String vmInfo = System.getProperty("java.vm.info"); - private static final String osVersion = System.getProperty("os.version"); - private static String[] osVersionTokens; - private static int osVersionMajor = -1; - private static int osVersionMinor = -1; - private static final String osName = System.getProperty("os.name"); - private static final String dataModel = System.getProperty("sun.arch.data.model"); - private static final String vmVersion = System.getProperty("java.vm.version"); - private static final String jdkDebug = System.getProperty("jdk.debug"); - private static final String osArch = System.getProperty("os.arch"); - private static final String userName = System.getProperty("user.name"); - private static final String compiler = System.getProperty("sun.management.compiler"); - - public static boolean isClient() { - return vmName.endsWith(" Client VM"); - } - - public static boolean isServer() { - return vmName.endsWith(" Server VM"); - } - - public static boolean isGraal() { - return vmName.endsWith(" Graal VM"); - } - - public static boolean isZero() { - return vmName.endsWith(" Zero VM"); - } - - public static boolean isMinimal() { - return vmName.endsWith(" Minimal VM"); - } - - public static boolean isEmbedded() { - return vmName.contains("Embedded"); - } - - public static boolean isEmulatedClient() { - return vmInfo.contains(" emulated-client"); - } - - public static boolean isTieredSupported() { - return compiler.contains("Tiered Compilers"); - } - - public static boolean isInt() { - return vmInfo.contains("interpreted"); - } - - public static boolean isMixed() { - return vmInfo.contains("mixed"); - } - - public static boolean isComp() { - return vmInfo.contains("compiled"); - } - - public static boolean is32bit() { - return dataModel.equals("32"); - } - - public static boolean is64bit() { - return dataModel.equals("64"); - } - - public static boolean isAix() { - return isOs("aix"); - } - - public static boolean isLinux() { - return isOs("linux"); - } - - public static boolean isOSX() { - return isOs("mac"); - } - - public static boolean isSolaris() { - return isOs("sunos"); - } - - public static boolean isWindows() { - return isOs("win"); - } - - private static boolean isOs(String osname) { - return osName.toLowerCase().startsWith(osname.toLowerCase()); - } - - public static String getOsName() { - return osName; - } - - // Os version support. - private static void init_version() { - osVersionTokens = osVersion.split("\\."); - try { - if (osVersionTokens.length > 0) { - osVersionMajor = Integer.parseInt(osVersionTokens[0]); - if (osVersionTokens.length > 1) { - osVersionMinor = Integer.parseInt(osVersionTokens[1]); - } - } - } catch (NumberFormatException e) { - osVersionMajor = osVersionMinor = 0; - } - } - - public static String getOsVersion() { - return osVersion; - } - - // Returns major version number from os.version system property. - // E.g. 5 on Solaris 10 and 3 on SLES 11.3 (for the linux kernel version). - public static int getOsVersionMajor() { - if (osVersionMajor == -1) init_version(); - return osVersionMajor; - } - - // Returns minor version number from os.version system property. - // E.g. 10 on Solaris 10 and 0 on SLES 11.3 (for the linux kernel version). - public static int getOsVersionMinor() { - if (osVersionMinor == -1) init_version(); - return osVersionMinor; - } - - /** - * Compares the platform version with the supplied version. The - * version must be of the form a[.b[.c[.d...]]] where a, b, c, d, ... - * are decimal integers. - * - * @throws NullPointerException if the parameter is null - * @throws NumberFormatException if there is an error parsing either - * version as split into component strings - * @return -1, 0, or 1 according to whether the platform version is - * less than, equal to, or greater than the supplied version - */ - public static int compareOsVersion(String version) { - if (osVersionTokens == null) init_version(); - - Objects.requireNonNull(version); - - List s1 = Arrays - .stream(osVersionTokens) - .map(Integer::valueOf) - .collect(Collectors.toList()); - List s2 = Arrays - .stream(version.split("\\.")) - .map(Integer::valueOf) - .collect(Collectors.toList()); - - int count = Math.max(s1.size(), s2.size()); - for (int i = 0; i < count; i++) { - int i1 = i < s1.size() ? s1.get(i) : 0; - int i2 = i < s2.size() ? s2.get(i) : 0; - if (i1 > i2) { - return 1; - } else if (i2 > i1) { - return -1; - } - } - - return 0; - } - - public static boolean isDebugBuild() { - return (jdkDebug.toLowerCase().contains("debug")); - } - - public static boolean isSlowDebugBuild() { - return (jdkDebug.toLowerCase().equals("slowdebug")); - } - - public static boolean isFastDebugBuild() { - return (jdkDebug.toLowerCase().equals("fastdebug")); - } - - public static String getVMVersion() { - return vmVersion; - } - - public static boolean isAArch64() { - return isArch("aarch64"); - } - - public static boolean isARM() { - return isArch("arm.*"); - } - - public static boolean isPPC() { - return isArch("ppc.*"); - } - - // Returns true for IBM z System running linux. - public static boolean isS390x() { - return isArch("s390.*") || isArch("s/390.*") || isArch("zArch_64"); - } - - // Returns true for sparc and sparcv9. - public static boolean isSparc() { - return isArch("sparc.*"); - } - - public static boolean isX64() { - // On OSX it's 'x86_64' and on other (Linux, Windows and Solaris) platforms it's 'amd64' - return isArch("(amd64)|(x86_64)"); - } - - public static boolean isX86() { - // On Linux it's 'i386', Windows 'x86' without '_64' suffix. - return isArch("(i386)|(x86(?!_64))"); - } - - public static String getOsArch() { - return osArch; - } - - /** - * Return a boolean for whether SA and jhsdb are ported/available - * on this platform. - */ - public static boolean hasSA() { - if (isAix()) { - return false; // SA not implemented. - } else if (isLinux()) { - if (isS390x()) { - return false; // SA not implemented. - } - } - // Other platforms expected to work: - return true; - } - - /** - * Return a boolean for whether we expect to be able to attach - * the SA to our own processes on this system. This requires - * that SA is ported/available on this platform. - */ - public static boolean shouldSAAttach() throws IOException { - if (!hasSA()) return false; - if (isLinux()) { - return canPtraceAttachLinux(); - } else if (isOSX()) { - return canAttachOSX(); - } else { - // Other platforms expected to work: - return true; - } - } - - /** - * On Linux, first check the SELinux boolean "deny_ptrace" and return false - * as we expect to be denied if that is "1". Then expect permission to attach - * if we are root, so return true. Then return false for an expected denial - * if "ptrace_scope" is 1, and true otherwise. - */ - private static boolean canPtraceAttachLinux() throws IOException { - // SELinux deny_ptrace: - File deny_ptrace = new File("/sys/fs/selinux/booleans/deny_ptrace"); - if (deny_ptrace.exists()) { - try (RandomAccessFile file = new RandomAccessFile(deny_ptrace, "r")) { - if (file.readByte() != '0') { - return false; - } - } - } - - // YAMA enhanced security ptrace_scope: - // 0 - a process can PTRACE_ATTACH to any other process running under the same uid - // 1 - restricted ptrace: a process must be a children of the inferior or user is root - // 2 - only processes with CAP_SYS_PTRACE may use ptrace or user is root - // 3 - no attach: no processes may use ptrace with PTRACE_ATTACH - File ptrace_scope = new File("/proc/sys/kernel/yama/ptrace_scope"); - if (ptrace_scope.exists()) { - try (RandomAccessFile file = new RandomAccessFile(ptrace_scope, "r")) { - byte yama_scope = file.readByte(); - if (yama_scope == '3') { - return false; - } - - if (!userName.equals("root") && yama_scope != '0') { - return false; - } - } - } - // Otherwise expect to be permitted: - return true; - } - - /** - * On OSX, expect permission to attach only if we are root. - */ - private static boolean canAttachOSX() { - return userName.equals("root"); - } - - private static boolean isArch(String archnameRE) { - return Pattern.compile(archnameRE, Pattern.CASE_INSENSITIVE) - .matcher(osArch) - .matches(); - } - - /** - * Returns file extension of shared library, e.g. "so" on linux, "dll" on windows. - * @return file extension - */ - public static String sharedLibraryExt() { - if (isWindows()) { - return "dll"; - } else if (isOSX()) { - return "dylib"; - } else { - return "so"; - } - } - - /* - * Returns name of system variable containing paths to shared native libraries. - */ - public static String sharedLibraryPathVariableName() { - if (isWindows()) { - return "PATH"; - } else if (isOSX()) { - return "DYLD_LIBRARY_PATH"; - } else if (isAix()) { - return "LIBPATH"; - } else { - return "LD_LIBRARY_PATH"; - } - } - - /* - * This should match the #if condition in ClassListParser::load_class_from_source(). - */ - public static boolean areCustomLoadersSupportedForCDS() { - boolean isLinux = Platform.isLinux(); - boolean is64 = Platform.is64bit(); - boolean isSolaris = Platform.isSolaris(); - - return (is64 && (isLinux || isSolaris)); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/RandomFactory.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/RandomFactory.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/RandomFactory.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/RandomFactory.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.Random; -import java.util.SplittableRandom; - -/** - * Factory class which generates and prints to STDOUT a long-valued seed - * for use in initializing a PRNG. An instance of {@code Random} or - * {@code SplittableRandom} may likewise be obtained. - */ -public class RandomFactory { - /** - * Attempt to obtain the seed from the value of the "seed" property. - * @return The seed or {@code null} if the "seed" property was not set or - * could not be parsed. - */ - private static Long getSystemSeed() { - Long seed = null; - try { - // note that Long.valueOf(null) also throws a - // NumberFormatException so if the property is undefined this - // will still work correctly - seed = Long.valueOf(System.getProperty("seed")); - } catch (NumberFormatException e) { - // do nothing: seed is still null - } - - return seed; - } - - /** - * Obtain a seed from an independent PRNG. - * - * @return A random seed. - */ - private static long getRandomSeed() { - return new Random().nextLong(); - } - - /** - * Obtain and print to STDOUT a seed appropriate for initializing a PRNG. - * If the system property "seed" is set and has value which may be correctly - * parsed it is used, otherwise a seed is generated using an independent - * PRNG. - * - * @return The seed. - */ - public static long getSeed() { - Long seed = getSystemSeed(); - if (seed == null) { - seed = getRandomSeed(); - } - System.out.println("Seed from RandomFactory = "+seed+"L"); - return seed; - } - - /** - * Obtain and print to STDOUT a seed and use it to initialize a new - * {@code Random} instance which is returned. If the system - * property "seed" is set and has value which may be correctly parsed it - * is used, otherwise a seed is generated using an independent PRNG. - * - * @return The {@code Random} instance. - */ - public static Random getRandom() { - return new Random(getSeed()); - } - - /** - * Obtain and print to STDOUT a seed and use it to initialize a new - * {@code SplittableRandom} instance which is returned. If the system - * property "seed" is set and has value which may be correctly parsed it - * is used, otherwise a seed is generated using an independent PRNG. - * - * @return The {@code SplittableRandom} instance. - */ - public static SplittableRandom getSplittableRandom() { - return new SplittableRandom(getSeed()); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SecurityTools.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SecurityTools.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SecurityTools.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SecurityTools.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - -public class SecurityTools { - - public static final String RESPONSE_FILE = "security_tools_response.txt"; - - private static ProcessBuilder getProcessBuilder(String tool, List args) { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK(tool) - .addVMArg("-Duser.language=en") - .addVMArg("-Duser.country=US"); - if (!Platform.isWindows()) { - launcher.addVMArg("-Djava.security.egd=file:/dev/./urandom"); - } - for (String arg : args) { - if (arg.startsWith("-J")) { - launcher.addVMArg(arg.substring(2)); - } else { - launcher.addToolArg(arg); - } - } - return new ProcessBuilder(launcher.getCommand()); - } - - // keytool - - public static OutputAnalyzer keytool(List args) - throws Exception { - - ProcessBuilder pb = getProcessBuilder("keytool", args); - - Path p = Paths.get(RESPONSE_FILE); - if (!Files.exists(p)) { - Files.createFile(p); - } - pb.redirectInput(ProcessBuilder.Redirect.from(new File(RESPONSE_FILE))); - - try { - return execute(pb); - } finally { - Files.delete(p); - } - } - - // Only call this if there is no white space in every argument - public static OutputAnalyzer keytool(String args) throws Exception { - return keytool(args.split("\\s+")); - } - - public static OutputAnalyzer keytool(String... args) throws Exception { - return keytool(List.of(args)); - } - - public static void setResponse(String... responses) throws IOException { - String text; - if (responses.length > 0) { - text = Stream.of(responses).collect( - Collectors.joining("\n", "", "\n")); - } else { - text = ""; - } - Files.write(Paths.get(RESPONSE_FILE), text.getBytes()); - } - - // jarsigner - - public static OutputAnalyzer jarsigner(List args) - throws Exception { - return execute(getProcessBuilder("jarsigner", args)); - } - - private static OutputAnalyzer execute(ProcessBuilder pb) throws Exception { - try { - OutputAnalyzer oa = ProcessTools.executeCommand(pb); - System.out.println("Exit value: " + oa.getExitValue()); - return oa; - } catch (Throwable t) { - if (t instanceof Exception) { - throw (Exception) t; - } else { - throw new Exception(t); - } - } - } - - // Only call this if there is no white space in every argument - public static OutputAnalyzer jarsigner(String args) throws Exception { - - return jarsigner(args.split("\\s+")); - } - - public static OutputAnalyzer jarsigner(String... args) throws Exception { - return jarsigner(List.of(args)); - } -} - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SigTestUtil.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SigTestUtil.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SigTestUtil.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/SigTestUtil.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.security.*; -import java.security.spec.*; -import java.util.*; - -/* - * Utility class used by various Signature related regression tests for - * common functions such as generating the list of to-be-tested algorithms - * based on key size, etc. Currently, this is mostly needed by RSA - * signatures. - */ -public class SigTestUtil { - - public enum SignatureType { - RSA("RSA"), - RSASSA_PSS("RSASSA-PSS") - ; - - private String keyAlg; - - SignatureType(String keyAlg) { - this.keyAlg = keyAlg; - } - @Override - public String toString() { - return keyAlg; - } - } - - // collection of all supported digest algorithms - // note that the entries are ordered by required key sizes - private static final String[] DIGEST_ALGS = { - "SHA-512", - "SHA-384", - "SHA-256", - "SHA-512/256", - "SHA-224", - "SHA-512/224", - "SHA-1", - "MD2", "MD5" // these aren't supported by RSA PSS - }; - - // indice for message digest algorithms lookup - // may need to be adjusted if new algorithms are added - private static final int PKCS1_5_INDEX_768 = 0; - private static final int PKCS1_5_INDEX_512 = 2; - private static final int PKCS1_5_INDEX_END = DIGEST_ALGS.length; - private static final int PSS_INDEX_2048 = 0; - private static final int PSS_INDEX_1024 = 1; - private static final int PSS_INDEX_768 = 2; - private static final int PSS_INDEX_512 = 4; - private static final int PSS_INDEX_END = 7; - - public static Iterable getDigestAlgorithms(SignatureType type, - int keysize) throws RuntimeException { - - // initialize to all, then trim based on key size - List result = new ArrayList<>(Arrays.asList(DIGEST_ALGS)); - int index = 0; - switch (type) { - case RSA: - if (keysize >= 768) { - index = PKCS1_5_INDEX_768; - } else if (keysize >= 512) { - index = PKCS1_5_INDEX_512; - } else { - throw new RuntimeException("Keysize too small: " + keysize); - } - result = result.subList(index, PKCS1_5_INDEX_END); - break; - case RSASSA_PSS: - if (keysize >= 2048) { - index = PSS_INDEX_2048; - } else if (keysize >= 1024) { - index = PSS_INDEX_1024; - } else if (keysize >= 768) { - index = PSS_INDEX_768; - } else if (keysize >= 512) { - index = PSS_INDEX_512; - } else { - throw new RuntimeException("Keysize too small: " + keysize); - } - result = result.subList(index, PSS_INDEX_END); - break; - default: - // XXX maybe just return result instead of error out? - throw new RuntimeException("Unsupported signature type: " + type); - } - return result; - } - - public static AlgorithmParameterSpec generateDefaultParameter( - SignatureType type, String mdAlg) throws RuntimeException { - // only RSASSA-PSS signature uses parameters - switch (type) { - case RSASSA_PSS: - try { - MessageDigest md = MessageDigest.getInstance(mdAlg); - return new PSSParameterSpec(mdAlg, "MGF1", - new MGF1ParameterSpec(mdAlg), md.getDigestLength(), - PSSParameterSpec.TRAILER_FIELD_BC); - } catch (Exception e) { - throw new RuntimeException(e); - } - default: - return null; - } - } - - public static String generateSigAlg(SignatureType type, - String mdAlg) throws RuntimeException { - switch (type) { - case RSA: - int idx = mdAlg.indexOf("-"); - if (idx != -1) { - mdAlg = mdAlg.substring(0, idx) + mdAlg.substring(idx+1); - } - return mdAlg + "with" + type.toString(); - case RSASSA_PSS: - return type.toString(); - default: - throw new RuntimeException("Unsupported signature type " + type ); - } - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/TimeLimitedRunner.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/TimeLimitedRunner.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/TimeLimitedRunner.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/TimeLimitedRunner.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.util.Objects; -import java.util.concurrent.Callable; - -/** - * Auxiliary class to run target w/ given timeout. - */ -public class TimeLimitedRunner implements Callable { - private final long stoptime; - private final long timeout; - private final double factor; - private final Callable target; - - /** - * @param timeout a timeout. zero means no time limitation - * @param factor a multiplier used to estimate next iteration time - * @param target a target to run - * @throws NullPointerException if target is null - * @throws IllegalArgumentException if timeout is negative or - factor isn't positive - */ - public TimeLimitedRunner(long timeout, double factor, - Callable target) { - Objects.requireNonNull(target, "target must not be null"); - if (timeout < 0) { - throw new IllegalArgumentException("timeout[" + timeout + "] < 0"); - } - if (factor <= 0d) { - throw new IllegalArgumentException("factor[" + factor + "] <= 0"); - } - this.stoptime = System.currentTimeMillis() + timeout; - this.timeout = timeout; - this.factor = factor; - this.target = target; - } - - /** - * Runs @{linkplan target} while it returns true and timeout isn't exceeded - */ - @Override - public Void call() throws Exception { - long maxDuration = 0L; - long iterStart = System.currentTimeMillis(); - if (timeout != 0 && iterStart > stoptime) { - return null; - } - while (target.call()) { - if (timeout != 0) { - long iterDuration = System.currentTimeMillis() - iterStart; - maxDuration = Math.max(maxDuration, iterDuration); - iterStart = System.currentTimeMillis(); - if (iterStart + (maxDuration * factor) > stoptime) { - System.out.println("Not enough time to continue execution. " - + "Interrupted."); - break; - } - } - } - return null; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Utils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Utils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Utils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/Utils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,832 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib; - -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.ServerSocket; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.UnknownHostException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.FileAttribute; -import java.nio.channels.SocketChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import java.util.Random; -import java.util.function.BooleanSupplier; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static jdk.test.lib.Asserts.assertTrue; -import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.process.OutputAnalyzer; - -/** - * Common library for various test helper functions. - */ -public final class Utils { - - /** - * Returns the value of 'test.class.path' system property. - */ - public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); - - /** - * Returns the sequence used by operating system to separate lines. - */ - public static final String NEW_LINE = System.getProperty("line.separator"); - - /** - * Returns the value of 'test.vm.opts' system property. - */ - public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); - - /** - * Returns the value of 'test.java.opts' system property. - */ - public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); - - /** - * Returns the value of 'test.src' system property. - */ - public static final String TEST_SRC = System.getProperty("test.src", "").trim(); - - /* - * Returns the value of 'test.jdk' system property - */ - public static final String TEST_JDK = System.getProperty("test.jdk"); - - /* - * Returns the value of 'compile.jdk' system property - */ - public static final String COMPILE_JDK= System.getProperty("compile.jdk", TEST_JDK); - - /** - * Returns the value of 'test.classes' system property - */ - public static final String TEST_CLASSES = System.getProperty("test.classes", "."); - /** - * Defines property name for seed value. - */ - public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; - - /* (non-javadoc) - * Random generator with (or without) predefined seed. Depends on - * "jdk.test.lib.random.seed" property value. - */ - private static volatile Random RANDOM_GENERATOR; - - /** - * Contains the seed value used for {@link java.util.Random} creation. - */ - public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong()); - /** - * Returns the value of 'test.timeout.factor' system property - * converted to {@code double}. - */ - public static final double TIMEOUT_FACTOR; - static { - String toFactor = System.getProperty("test.timeout.factor", "1.0"); - TIMEOUT_FACTOR = Double.parseDouble(toFactor); - } - - /** - * Returns the value of JTREG default test timeout in milliseconds - * converted to {@code long}. - */ - public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); - - private Utils() { - // Private constructor to prevent class instantiation - } - - /** - * Returns the list of VM options. - * - * @return List of VM options - */ - public static List getVmOptions() { - return Arrays.asList(safeSplitString(VM_OPTIONS)); - } - - /** - * Returns the list of VM options with -J prefix. - * - * @return The list of VM options with -J prefix - */ - public static List getForwardVmOptions() { - String[] opts = safeSplitString(VM_OPTIONS); - for (int i = 0; i < opts.length; i++) { - opts[i] = "-J" + opts[i]; - } - return Arrays.asList(opts); - } - - /** - * Returns the default JTReg arguments for a jvm running a test. - * This is the combination of JTReg arguments test.vm.opts and test.java.opts. - * @return An array of options, or an empty array if no options. - */ - public static String[] getTestJavaOpts() { - List opts = new ArrayList(); - Collections.addAll(opts, safeSplitString(VM_OPTIONS)); - Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); - return opts.toArray(new String[0]); - } - - /** - * Combines given arguments with default JTReg arguments for a jvm running a test. - * This is the combination of JTReg arguments test.vm.opts and test.java.opts - * @return The combination of JTReg test java options and user args. - */ - public static String[] addTestJavaOpts(String... userArgs) { - List opts = new ArrayList(); - Collections.addAll(opts, getTestJavaOpts()); - Collections.addAll(opts, userArgs); - return opts.toArray(new String[0]); - } - - /** - * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". - * Removes any options matching: -XX:(+/-)Use*GC - * Used when a test need to set its own GC version. Then any - * GC specified by the framework must first be removed. - * @return A copy of given opts with all GC options removed. - */ - private static final Pattern useGcPattern = Pattern.compile( - "(?:\\-XX\\:[\\+\\-]Use.+GC)" - + "|(?:\\-Xconcgc)"); - public static List removeGcOpts(List opts) { - List optsWithoutGC = new ArrayList(); - for (String opt : opts) { - if (useGcPattern.matcher(opt).matches()) { - System.out.println("removeGcOpts: removed " + opt); - } else { - optsWithoutGC.add(opt); - } - } - return optsWithoutGC; - } - - /** - * Returns the default JTReg arguments for a jvm running a test without - * options that matches regular expressions in {@code filters}. - * This is the combination of JTReg arguments test.vm.opts and test.java.opts. - * @param filters Regular expressions used to filter out options. - * @return An array of options, or an empty array if no options. - */ - public static String[] getFilteredTestJavaOpts(String... filters) { - String options[] = getTestJavaOpts(); - - if (filters.length == 0) { - return options; - } - - List filteredOptions = new ArrayList(options.length); - Pattern patterns[] = new Pattern[filters.length]; - for (int i = 0; i < filters.length; i++) { - patterns[i] = Pattern.compile(filters[i]); - } - - for (String option : options) { - boolean matched = false; - for (int i = 0; i < patterns.length && !matched; i++) { - Matcher matcher = patterns[i].matcher(option); - matched = matcher.find(); - } - if (!matched) { - filteredOptions.add(option); - } - } - - return filteredOptions.toArray(new String[filteredOptions.size()]); - } - - /** - * Splits a string by white space. - * Works like String.split(), but returns an empty array - * if the string is null or empty. - */ - private static String[] safeSplitString(String s) { - if (s == null || s.trim().isEmpty()) { - return new String[] {}; - } - return s.trim().split("\\s+"); - } - - /** - * @return The full command line for the ProcessBuilder. - */ - public static String getCommandLine(ProcessBuilder pb) { - StringBuilder cmd = new StringBuilder(); - for (String s : pb.command()) { - cmd.append(s).append(" "); - } - return cmd.toString(); - } - - /** - * Returns the socket address of an endpoint that refuses connections. The - * endpoint is an InetSocketAddress where the address is the loopback address - * and the port is a system port (1-1023 range). - * This method is a better choice than getFreePort for tests that need - * an endpoint that refuses connections. - */ - public static InetSocketAddress refusingEndpoint() { - InetAddress lb = InetAddress.getLoopbackAddress(); - int port = 1; - while (port < 1024) { - InetSocketAddress sa = new InetSocketAddress(lb, port); - try { - SocketChannel.open(sa).close(); - } catch (IOException ioe) { - return sa; - } - port++; - } - throw new RuntimeException("Unable to find system port that is refusing connections"); - } - - /** - * Returns the free port on the local host. - * - * @return The port number - * @throws IOException if an I/O error occurs when opening the socket - */ - public static int getFreePort() throws IOException { - try (ServerSocket serverSocket = - new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { - return serverSocket.getLocalPort(); - } - } - - /** - * Returns the name of the local host. - * - * @return The host name - * @throws UnknownHostException if IP address of a host could not be determined - */ - public static String getHostname() throws UnknownHostException { - InetAddress inetAddress = InetAddress.getLocalHost(); - String hostName = inetAddress.getHostName(); - - assertTrue((hostName != null && !hostName.isEmpty()), - "Cannot get hostname"); - - return hostName; - } - - /** - * Uses "jcmd -l" to search for a jvm pid. This function will wait - * forever (until jtreg timeout) for the pid to be found. - * @param key Regular expression to search for - * @return The found pid. - */ - public static int waitForJvmPid(String key) throws Throwable { - final long iterationSleepMillis = 250; - System.out.println("waitForJvmPid: Waiting for key '" + key + "'"); - System.out.flush(); - while (true) { - int pid = tryFindJvmPid(key); - if (pid >= 0) { - return pid; - } - Thread.sleep(iterationSleepMillis); - } - } - - /** - * Searches for a jvm pid in the output from "jcmd -l". - * - * Example output from jcmd is: - * 12498 sun.tools.jcmd.JCmd -l - * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar - * - * @param key A regular expression to search for. - * @return The found pid, or -1 if not found. - * @throws Exception If multiple matching jvms are found. - */ - public static int tryFindJvmPid(String key) throws Throwable { - OutputAnalyzer output = null; - try { - JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd"); - jcmdLauncher.addToolArg("-l"); - output = ProcessTools.executeProcess(jcmdLauncher.getCommand()); - output.shouldHaveExitValue(0); - - // Search for a line starting with numbers (pid), follwed by the key. - Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n"); - Matcher matcher = pattern.matcher(output.getStdout()); - - int pid = -1; - if (matcher.find()) { - pid = Integer.parseInt(matcher.group(1)); - System.out.println("findJvmPid.pid: " + pid); - if (matcher.find()) { - throw new Exception("Found multiple JVM pids for key: " + key); - } - } - return pid; - } catch (Throwable t) { - System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t)); - throw t; - } - } - - /** - * Adjusts the provided timeout value for the TIMEOUT_FACTOR - * @param tOut the timeout value to be adjusted - * @return The timeout value adjusted for the value of "test.timeout.factor" - * system property - */ - public static long adjustTimeout(long tOut) { - return Math.round(tOut * Utils.TIMEOUT_FACTOR); - } - - /** - * Return the contents of the named file as a single String, - * or null if not found. - * @param filename name of the file to read - * @return String contents of file, or null if file not found. - * @throws IOException - * if an I/O error occurs reading from the file or a malformed or - * unmappable byte sequence is read - */ - public static String fileAsString(String filename) throws IOException { - Path filePath = Paths.get(filename); - if (!Files.exists(filePath)) return null; - return new String(Files.readAllBytes(filePath)); - } - - private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - - /** - * Returns hex view of byte array - * - * @param bytes byte array to process - * @return space separated hexadecimal string representation of bytes - */ - public static String toHexString(byte[] bytes) { - char[] hexView = new char[bytes.length * 3 - 1]; - for (int i = 0; i < bytes.length - 1; i++) { - hexView[i * 3] = hexArray[(bytes[i] >> 4) & 0x0F]; - hexView[i * 3 + 1] = hexArray[bytes[i] & 0x0F]; - hexView[i * 3 + 2] = ' '; - } - hexView[hexView.length - 2] = hexArray[(bytes[bytes.length - 1] >> 4) & 0x0F]; - hexView[hexView.length - 1] = hexArray[bytes[bytes.length - 1] & 0x0F]; - return new String(hexView); - } - - /** - * Returns byte array of hex view - * - * @param hex hexadecimal string representation - * @return byte array - */ - public static byte[] toByteArray(String hex) { - int length = hex.length(); - byte[] bytes = new byte[length / 2]; - for (int i = 0; i < length; i += 2) { - bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) - + Character.digit(hex.charAt(i + 1), 16)); - } - return bytes; - } - - /** - * Returns {@link java.util.Random} generator initialized with particular seed. - * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME} - * In case no seed is provided, the method uses a random number. - * The used seed printed to stdout. - * @return {@link java.util.Random} generator with particular seed. - */ - public static Random getRandomInstance() { - if (RANDOM_GENERATOR == null) { - synchronized (Utils.class) { - if (RANDOM_GENERATOR == null) { - RANDOM_GENERATOR = new Random(SEED); - System.out.printf("For random generator using seed: %d%n", SEED); - System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); - } - } - } - return RANDOM_GENERATOR; - } - - /** - * Returns random element of non empty collection - * - * @param a type of collection element - * @param collection collection of elements - * @return random element of collection - * @throws IllegalArgumentException if collection is empty - */ - public static T getRandomElement(Collection collection) - throws IllegalArgumentException { - if (collection.isEmpty()) { - throw new IllegalArgumentException("Empty collection"); - } - Random random = getRandomInstance(); - int elementIndex = 1 + random.nextInt(collection.size() - 1); - Iterator iterator = collection.iterator(); - while (--elementIndex != 0) { - iterator.next(); - } - return iterator.next(); - } - - /** - * Returns random element of non empty array - * - * @param a type of array element - * @param array array of elements - * @return random element of array - * @throws IllegalArgumentException if array is empty - */ - public static T getRandomElement(T[] array) - throws IllegalArgumentException { - if (array == null || array.length == 0) { - throw new IllegalArgumentException("Empty or null array"); - } - Random random = getRandomInstance(); - return array[random.nextInt(array.length)]; - } - - /** - * Wait for condition to be true - * - * @param condition, a condition to wait for - */ - public static final void waitForCondition(BooleanSupplier condition) { - waitForCondition(condition, -1L, 100L); - } - - /** - * Wait until timeout for condition to be true - * - * @param condition, a condition to wait for - * @param timeout a time in milliseconds to wait for condition to be true - * specifying -1 will wait forever - * @return condition value, to determine if wait was successful - */ - public static final boolean waitForCondition(BooleanSupplier condition, - long timeout) { - return waitForCondition(condition, timeout, 100L); - } - - /** - * Wait until timeout for condition to be true for specified time - * - * @param condition, a condition to wait for - * @param timeout a time in milliseconds to wait for condition to be true, - * specifying -1 will wait forever - * @param sleepTime a time to sleep value in milliseconds - * @return condition value, to determine if wait was successful - */ - public static final boolean waitForCondition(BooleanSupplier condition, - long timeout, long sleepTime) { - long startTime = System.currentTimeMillis(); - while (!(condition.getAsBoolean() || (timeout != -1L - && ((System.currentTimeMillis() - startTime) > timeout)))) { - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new Error(e); - } - } - return condition.getAsBoolean(); - } - - /** - * Interface same as java.lang.Runnable but with - * method {@code run()} able to throw any Throwable. - */ - public static interface ThrowingRunnable { - void run() throws Throwable; - } - - /** - * Filters out an exception that may be thrown by the given - * test according to the given filter. - * - * @param test - method that is invoked and checked for exception. - * @param filter - function that checks if the thrown exception matches - * criteria given in the filter's implementation. - * @return - exception that matches the filter if it has been thrown or - * {@code null} otherwise. - * @throws Throwable - if test has thrown an exception that does not - * match the filter. - */ - public static Throwable filterException(ThrowingRunnable test, - Function filter) throws Throwable { - try { - test.run(); - } catch (Throwable t) { - if (filter.apply(t)) { - return t; - } else { - throw t; - } - } - return null; - } - - /** - * Ensures a requested class is loaded - * @param aClass class to load - */ - public static void ensureClassIsLoaded(Class aClass) { - if (aClass == null) { - throw new Error("Requested null class"); - } - try { - Class.forName(aClass.getName(), /* initialize = */ true, - ClassLoader.getSystemClassLoader()); - } catch (ClassNotFoundException e) { - throw new Error("Class not found", e); - } - } - /** - * @param parent a class loader to be the parent for the returned one - * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg - * property and with the given parent - */ - public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { - URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) - .map(Paths::get) - .map(Path::toUri) - .map(x -> { - try { - return x.toURL(); - } catch (MalformedURLException ex) { - throw new Error("Test issue. JTREG property" - + " 'test.class.path'" - + " is not defined correctly", ex); - } - }).toArray(URL[]::new); - return new URLClassLoader(urls, parent); - } - - /** - * Runs runnable and checks that it throws expected exception. If exceptionException is null it means - * that we expect no exception to be thrown. - * @param runnable what we run - * @param expectedException expected exception - */ - public static void runAndCheckException(ThrowingRunnable runnable, Class expectedException) { - runAndCheckException(runnable, t -> { - if (t == null) { - if (expectedException != null) { - throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); - } - } else { - String message = "Got unexpected exception " + t.getClass().getSimpleName(); - if (expectedException == null) { - throw new AssertionError(message, t); - } else if (!expectedException.isAssignableFrom(t.getClass())) { - message += " instead of " + expectedException.getSimpleName(); - throw new AssertionError(message, t); - } - } - }); - } - - /** - * Runs runnable and makes some checks to ensure that it throws expected exception. - * @param runnable what we run - * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise - */ - public static void runAndCheckException(ThrowingRunnable runnable, Consumer checkException) { - Throwable throwable = null; - try { - runnable.run(); - } catch (Throwable t) { - throwable = t; - } - checkException.accept(throwable); - } - - /** - * Converts to VM type signature - * - * @param type Java type to convert - * @return string representation of VM type - */ - public static String toJVMTypeSignature(Class type) { - if (type.isPrimitive()) { - if (type == boolean.class) { - return "Z"; - } else if (type == byte.class) { - return "B"; - } else if (type == char.class) { - return "C"; - } else if (type == double.class) { - return "D"; - } else if (type == float.class) { - return "F"; - } else if (type == int.class) { - return "I"; - } else if (type == long.class) { - return "J"; - } else if (type == short.class) { - return "S"; - } else if (type == void.class) { - return "V"; - } else { - throw new Error("Unsupported type: " + type); - } - } - String result = type.getName().replaceAll("\\.", "/"); - if (!type.isArray()) { - return "L" + result + ";"; - } - return result; - } - - public static Object[] getNullValues(Class... types) { - Object[] result = new Object[types.length]; - int i = 0; - for (Class type : types) { - result[i++] = NULL_VALUES.get(type); - } - return result; - } - private static Map, Object> NULL_VALUES = new HashMap<>(); - static { - NULL_VALUES.put(boolean.class, false); - NULL_VALUES.put(byte.class, (byte) 0); - NULL_VALUES.put(short.class, (short) 0); - NULL_VALUES.put(char.class, '\0'); - NULL_VALUES.put(int.class, 0); - NULL_VALUES.put(long.class, 0L); - NULL_VALUES.put(float.class, 0.0f); - NULL_VALUES.put(double.class, 0.0d); - } - - /** - * Returns mandatory property value - * @param propName is a name of property to request - * @return a String with requested property value - */ - public static String getMandatoryProperty(String propName) { - Objects.requireNonNull(propName, "Requested null property"); - String prop = System.getProperty(propName); - Objects.requireNonNull(prop, - String.format("A mandatory property '%s' isn't set", propName)); - return prop; - } - - /* - * Run uname with specified arguments. - */ - public static OutputAnalyzer uname(String... args) throws Throwable { - String[] cmds = new String[args.length + 1]; - cmds[0] = "uname"; - System.arraycopy(args, 0, cmds, 1, args.length); - return ProcessTools.executeCommand(cmds); - } - - /* - * Returns the system distro. - */ - public static String distro() { - try { - return uname("-v").asLines().get(0); - } catch (Throwable t) { - throw new RuntimeException("Failed to determine distro.", t); - } - } - - // This method is intended to be called from a jtreg test. - // It will identify the name of the test by means of stack walking. - // It can handle both jtreg tests and a testng tests wrapped inside jtreg tests. - // For jtreg tests the name of the test will be searched by stack-walking - // until the method main() is found; the class containing that method is the - // main test class and will be returned as the name of the test. - // Special handling is used for testng tests. - public static String getTestName() { - String result = null; - // If we are using testng, then we should be able to load the "Test" annotation. - Class testClassAnnotation; - - try { - testClassAnnotation = Class.forName("org.testng.annotations.Test"); - } catch (ClassNotFoundException e) { - testClassAnnotation = null; - } - - StackTraceElement[] elms = (new Throwable()).getStackTrace(); - for (StackTraceElement n: elms) { - String className = n.getClassName(); - - // If this is a "main" method, then use its class name, but only - // if we are not using testng. - if (testClassAnnotation == null && "main".equals(n.getMethodName())) { - result = className; - break; - } - - // If this is a testng test, the test will have no "main" method. We can - // detect a testng test class by looking for the org.testng.annotations.Test - // annotation. If present, then use the name of this class. - if (testClassAnnotation != null) { - try { - Class c = Class.forName(className); - if (c.isAnnotationPresent(testClassAnnotation)) { - result = className; - break; - } - } catch (ClassNotFoundException e) { - throw new RuntimeException("Unexpected exception: " + e, e); - } - } - } - - if (result == null) { - throw new RuntimeException("Couldn't find main test class in stack trace"); - } - - return result; - } - - /** - * Creates an empty file in "user.dir" if the property set. - *

- * This method is meant as a replacement for {@code Files#createTempFile(String, String, FileAttribute...)} - * that doesn't leave files behind in /tmp directory of the test machine - *

- * If the property "user.dir" is not set, "." will be used. - * - * @param prefix - * @param suffix - * @param attrs - * @return the path to the newly created file that did not exist before this - * method was invoked - * @throws IOException - * - * @see {@link Files#createTempFile(String, String, FileAttribute...)} - */ - public static Path createTempFile(String prefix, String suffix, FileAttribute... attrs) throws IOException { - Path dir = Paths.get(System.getProperty("user.dir", ".")); - return Files.createTempFile(dir, prefix, suffix); - } - - /** - * Creates an empty directory in "user.dir" or "." - *

- * This method is meant as a replacement for {@code Files#createTempDirectory(String, String, FileAttribute...)} - * that doesn't leave files behind in /tmp directory of the test machine - *

- * If the property "user.dir" is not set, "." will be used. - * - * @param prefix - * @param attrs - * @return the path to the newly created directory - * @throws IOException - * - * @see {@link Files#createTempDirectory(String, String, FileAttribute...)} - */ - public static Path createTempDirectory(String prefix, FileAttribute... attrs) throws IOException { - Path dir = Paths.get(System.getProperty("user.dir", ".")); - return Files.createTempDirectory(dir, prefix); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredApp.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredApp.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredApp.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredApp.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,518 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.apps; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.StringReader; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.FileTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.UUID; - -import jdk.test.lib.Utils; -import jdk.test.lib.process.OutputBuffer; -import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.process.StreamPumper; - -/** - * This is a framework to launch an app that could be synchronized with caller - * to make further attach actions reliable across supported platforms - - * Caller example: - * SmartTestApp a = SmartTestApp.startApp(cmd); - * // do something - * a.stopApp(); - * - * or fine grained control - * - * a = new SmartTestApp("MyLock.lck"); - * a.createLock(); - * a.runApp(); - * a.waitAppReady(); - * // do something - * a.deleteLock(); - * a.waitAppTerminate(); - * - * Then you can work with app output and process object - * - * output = a.getAppOutput(); - * process = a.getProcess(); - * - */ -public class LingeredApp { - - private static final long spinDelay = 1000; - - private long lockCreationTime; - private ByteArrayOutputStream stderrBuffer; - private ByteArrayOutputStream stdoutBuffer; - private Thread outPumperThread; - private Thread errPumperThread; - - protected Process appProcess; - protected OutputBuffer output; - protected static final int appWaitTime = 100; - protected final String lockFileName; - - /** - * Create LingeredApp object on caller side. Lock file have be a valid filename - * at writable location - * - * @param lockFileName - the name of lock file - */ - public LingeredApp(String lockFileName) { - this.lockFileName = lockFileName; - } - - public LingeredApp() { - final String lockName = UUID.randomUUID().toString() + ".lck"; - this.lockFileName = lockName; - } - - /** - * - * @return name of lock file - */ - public String getLockFileName() { - return this.lockFileName; - } - - /** - * - * @return name of testapp - */ - public String getAppName() { - return this.getClass().getName(); - } - - /** - * - * @return pid of java process running testapp - */ - public long getPid() { - if (appProcess == null) { - throw new RuntimeException("Process is not alive"); - } - return appProcess.pid(); - } - - /** - * - * @return process object - */ - public Process getProcess() { - return appProcess; - } - - /** - * - * @return OutputBuffer object for the LingeredApp's output. Can only be called - * after LingeredApp has exited. - */ - public OutputBuffer getOutput() { - if (appProcess.isAlive()) { - throw new RuntimeException("Process is still alive. Can't get its output."); - } - if (output == null) { - output = new OutputBuffer(stdoutBuffer.toString(), stderrBuffer.toString()); - } - return output; - } - - /* - * Capture all stdout and stderr output from the LingeredApp so it can be returned - * to the driver app later. This code is modeled after ProcessTools.getOutput(). - */ - private void startOutputPumpers() { - stderrBuffer = new ByteArrayOutputStream(); - stdoutBuffer = new ByteArrayOutputStream(); - StreamPumper outPumper = new StreamPumper(appProcess.getInputStream(), stdoutBuffer); - StreamPumper errPumper = new StreamPumper(appProcess.getErrorStream(), stderrBuffer); - outPumperThread = new Thread(outPumper); - errPumperThread = new Thread(errPumper); - - outPumperThread.setDaemon(true); - errPumperThread.setDaemon(true); - - outPumperThread.start(); - errPumperThread.start(); - } - - /** - * - * @return application output as List. Empty List if application produced no output - */ - public List getAppOutput() { - if (appProcess.isAlive()) { - throw new RuntimeException("Process is still alive. Can't get its output."); - } - BufferedReader bufReader = new BufferedReader(new StringReader(output.getStdout())); - return bufReader.lines().collect(Collectors.toList()); - } - - /* Make sure all part of the app use the same method to get dates, - as different methods could produce different results - */ - private static long epoch() { - return new Date().getTime(); - } - - private static long lastModified(String fileName) throws IOException { - Path path = Paths.get(fileName); - BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); - return attr.lastModifiedTime().toMillis(); - } - - private static void setLastModified(String fileName, long newTime) throws IOException { - Path path = Paths.get(fileName); - FileTime fileTime = FileTime.fromMillis(newTime); - Files.setLastModifiedTime(path, fileTime); - } - - /** - * create lock - * - * @throws IOException - */ - public void createLock() throws IOException { - Path path = Paths.get(lockFileName); - // Files.deleteIfExists(path); - Files.createFile(path); - lockCreationTime = lastModified(lockFileName); - } - - /** - * Delete lock - * - * @throws IOException - */ - public void deleteLock() throws IOException { - try { - Path path = Paths.get(lockFileName); - Files.delete(path); - } catch (NoSuchFileException ex) { - // Lock already deleted. Ignore error - } - } - - public void waitAppTerminate() { - // This code is modeled after tail end of ProcessTools.getOutput(). - try { - // If the app hangs, we don't want to wait for the to test timeout. - if (!appProcess.waitFor(Utils.adjustTimeout(appWaitTime), TimeUnit.SECONDS)) { - appProcess.destroy(); - appProcess.waitFor(); - } - outPumperThread.join(); - errPumperThread.join(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - // pass - } - } - - /** - * The app touches the lock file when it's started - * wait while it happens. Caller have to delete lock on wait error. - * - * @param timeout - * @throws java.io.IOException - */ - public void waitAppReady(long timeout) throws IOException { - long here = epoch(); - while (true) { - long epoch = epoch(); - if (epoch - here > (timeout * 1000)) { - throw new IOException("App waiting timeout"); - } - - // Live process should touch lock file every second - long lm = lastModified(lockFileName); - if (lm > lockCreationTime) { - break; - } - - // Make sure process didn't already exit - if (!appProcess.isAlive()) { - throw new IOException("App exited unexpectedly with " + appProcess.exitValue()); - } - - try { - Thread.sleep(spinDelay); - } catch (InterruptedException ex) { - // pass - } - } - } - - /** - * Analyze an environment and prepare a command line to - * run the app, app name should be added explicitly - */ - public List runAppPrepare(List vmArguments) { - // We should always use testjava or throw an exception, - // so we can't use JDKToolFinder.getJDKTool("java"); - // that falls back to compile java on error - String jdkPath = System.getProperty("test.jdk"); - if (jdkPath == null) { - // we are not under jtreg, try env - Map env = System.getenv(); - jdkPath = env.get("TESTJAVA"); - } - - if (jdkPath == null) { - throw new RuntimeException("Can't determine jdk path neither test.jdk property no TESTJAVA env are set"); - } - - String osname = System.getProperty("os.name"); - String javapath = jdkPath + ((osname.startsWith("window")) ? "/bin/java.exe" : "/bin/java"); - - List cmd = new ArrayList(); - cmd.add(javapath); - - if (vmArguments == null) { - // Propagate test.vm.options to LingeredApp, filter out possible empty options - String testVmOpts[] = System.getProperty("test.vm.opts","").split("\\s+"); - for (String s : testVmOpts) { - if (!s.equals("")) { - cmd.add(s); - } - } - } else { - // Lets user manage LingeredApp options - cmd.addAll(vmArguments); - } - - // Make sure we set correct classpath to run the app - cmd.add("-cp"); - String classpath = System.getProperty("test.class.path"); - cmd.add((classpath == null) ? "." : classpath); - - return cmd; - } - - /** - * Assemble command line to a printable string - */ - public void printCommandLine(List cmd) { - // A bit of verbosity - StringBuilder cmdLine = new StringBuilder(); - for (String strCmd : cmd) { - cmdLine.append("'").append(strCmd).append("' "); - } - - System.err.println("Command line: [" + cmdLine.toString() + "]"); - } - - /** - * Run the app. - * - * @param vmArguments - * @throws IOException - */ - public void runApp(List vmArguments) - throws IOException { - - List cmd = runAppPrepare(vmArguments); - - cmd.add(this.getAppName()); - cmd.add(lockFileName); - - printCommandLine(cmd); - - ProcessBuilder pb = new ProcessBuilder(cmd); - // ProcessBuilder.start can throw IOException - appProcess = pb.start(); - - startOutputPumpers(); - } - - private void finishApp() { - OutputBuffer output = getOutput(); - String msg = - " LingeredApp stdout: [" + output.getStdout() + "];\n" + - " LingeredApp stderr: [" + output.getStderr() + "]\n" + - " LingeredApp exitValue = " + appProcess.exitValue(); - - System.err.println(msg); - } - - /** - * Delete lock file that signals app to terminate, then - * wait until app is actually terminated. - * @throws IOException - */ - public void stopApp() throws IOException { - deleteLock(); - // The startApp() of the derived app can throw - // an exception before the LA actually starts - if (appProcess != null) { - waitAppTerminate(); - int exitcode = appProcess.exitValue(); - if (exitcode != 0) { - throw new IOException("LingeredApp terminated with non-zero exit code " + exitcode); - } - } - finishApp(); - } - - /** - * High level interface for test writers - */ - /** - * Factory method that creates LingeredApp object with ready to use application - * lock name is autogenerated - * @param cmd - vm options, could be null to auto add testvm.options - * @return LingeredApp object - * @throws IOException - */ - public static LingeredApp startApp(List cmd) throws IOException { - LingeredApp a = new LingeredApp(); - a.createLock(); - try { - a.runApp(cmd); - a.waitAppReady(appWaitTime); - } catch (Exception ex) { - a.deleteLock(); - System.err.println("LingeredApp failed to start: " + ex); - a.finishApp(); - throw ex; - } - - return a; - } - - /** - * Factory method that starts pre-created LingeredApp - * lock name is autogenerated - * @param cmd - vm options, could be null to auto add testvm.options - * @param theApp - app to start - * @return LingeredApp object - * @throws IOException - */ - - public static void startApp(List cmd, LingeredApp theApp) throws IOException { - theApp.createLock(); - try { - theApp.runApp(cmd); - theApp.waitAppReady(appWaitTime); - } catch (Exception ex) { - theApp.deleteLock(); - throw ex; - } - } - - public static LingeredApp startApp() throws IOException { - return startApp(null); - } - - public static void stopApp(LingeredApp app) throws IOException { - if (app != null) { - // LingeredApp can throw an exception during the intialization, - // make sure we don't have cascade NPE - app.stopApp(); - } - } - - /** - * LastModified time might not work correctly in some cases it might - * cause later failures - */ - - public static boolean isLastModifiedWorking() { - boolean sane = true; - try { - long lm = lastModified("."); - if (lm == 0) { - System.err.println("SANITY Warning! The lastModifiedTime() doesn't work on this system, it returns 0"); - sane = false; - } - - long now = epoch(); - if (lm > now) { - System.err.println("SANITY Warning! The Clock is wrong on this system lastModifiedTime() > getTime()"); - sane = false; - } - - setLastModified(".", epoch()); - long lm1 = lastModified("."); - if (lm1 <= lm) { - System.err.println("SANITY Warning! The setLastModified doesn't work on this system"); - sane = false; - } - } - catch(IOException e) { - System.err.println("SANITY Warning! IOException during sanity check " + e); - sane = false; - } - - return sane; - } - - /** - * This part is the application it self - */ - public static void main(String args[]) { - - if (args.length != 1) { - System.err.println("Lock file name is not specified"); - System.exit(7); - } - - String theLockFileName = args[0]; - - try { - Path path = Paths.get(theLockFileName); - - while (Files.exists(path)) { - // Touch the lock to indicate our readiness - setLastModified(theLockFileName, epoch()); - Thread.sleep(spinDelay); - } - } catch (NoSuchFileException ex) { - // Lock deleted while we are setting last modified time. - // Ignore error and lets the app exits - } catch (Exception ex) { - System.err.println("LingeredApp ERROR: " + ex); - // Leave exit_code = 1 to Java launcher - System.exit(3); - } - - System.exit(0); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredAppWithDeadlock.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredAppWithDeadlock.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredAppWithDeadlock.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/apps/LingeredAppWithDeadlock.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.apps; - -import java.util.concurrent.Phaser; - -public class LingeredAppWithDeadlock extends LingeredApp { - - private static final Object Lock1 = new Object(); - private static final Object Lock2 = new Object(); - - private static volatile int reachCount = 0; - - private static final Phaser p = new Phaser(2); - - private static class ThreadOne extends Thread { - public void run() { - // wait Lock2 is locked - p.arriveAndAwaitAdvance(); - synchronized (Lock1) { - // signal Lock1 is locked - p.arriveAndAwaitAdvance(); - synchronized (Lock2) { - reachCount += 1; - } - } - } - } - - private static class ThreadTwo extends Thread { - public void run() { - synchronized (Lock2) { - // signal Lock2 is locked - p.arriveAndAwaitAdvance(); - // wait Lock1 is locked - p.arriveAndAwaitAdvance(); - synchronized (Lock1) { - reachCount += 1; - } - } - } - } - - public static void main(String args[]) { - if (args.length != 1) { - System.err.println("Lock file name is not specified"); - System.exit(7); - } - - // Run two theads that should come to deadlock - new ThreadOne().start(); - new ThreadTwo().start(); - - if (reachCount > 0) { - // Not able to deadlock, exiting - System.exit(3); - } - - LingeredApp.main(args); - } - } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/Artifact.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/Artifact.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/Artifact.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/Artifact.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.lang.annotation.*; - -@Target(ElementType.TYPE) -@Repeatable(ArtifactContainer.class) -@Retention(RetentionPolicy.RUNTIME) -public @interface Artifact { - String organization(); - String name(); - String revision(); - String extension(); - String classifier() default ""; - boolean unpack() default true; -} - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.lang.annotation.*; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface ArtifactContainer { - Artifact[] value(); -} - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.io.FileNotFoundException; -import java.nio.file.Path; - -public interface ArtifactManager { - public Path resolve(Artifact artifact) throws ArtifactResolverException; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.io.FileNotFoundException; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; - -public class ArtifactResolver { - public static Map resolve(Class klass) throws ArtifactResolverException { - ArtifactManager manager = new DefaultArtifactManager(); - try { - String managerName = System.getProperty("jdk.test.lib.artifacts.artifactmanager"); - if (managerName != null) { - manager = (ArtifactManager) Class.forName(managerName).newInstance(); - } else { - manager = JibArtifactManager.newInstance(); - } - } catch (Exception e) { - // If we end up here, we'll use the DefaultArtifactManager - } - - ArtifactContainer artifactContainer = klass.getAnnotation(ArtifactContainer.class); - HashMap locations = new HashMap<>(); - Artifact[] artifacts; - - if (artifactContainer == null) { - artifacts = new Artifact[]{klass.getAnnotation(Artifact.class)}; - } else { - artifacts = artifactContainer.value(); - } - for (Artifact artifact : artifacts) { - locations.put(artifactName(artifact), manager.resolve(artifact)); - } - - return locations; - } - - private static String artifactName(Artifact artifact) { - // Format of the artifact name is .-(-) - String name = String.format("%s.%s-%s", artifact.organization(), artifact.name(), artifact.revision()); - if (artifact.classifier().length() != 0) { - name = name +"-" + artifact.classifier(); - } - return name; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -package jdk.test.lib.artifacts; - -/** - * Thrown by the ArtifactResolver when failing to resolve an Artifact. - */ -public class ArtifactResolverException extends Exception { - - public ArtifactResolverException(String message) { - super(message); - } - - public ArtifactResolverException(String message, Throwable cause) { - super(message, cause); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.io.FileNotFoundException; -import java.nio.file.Path; -import java.nio.file.Paths; - -public class DefaultArtifactManager implements ArtifactManager { - @Override - public Path resolve(Artifact artifact) throws ArtifactResolverException { - String name = artifact.name(); - String location = System.getProperty(artifactProperty(name)); - if (location == null) { - throw new ArtifactResolverException("Couldn't automatically resolve dependency for " + name - + " , revision " + artifact.revision() + "\n" + - "Please specify the location using " + artifactProperty(name)); - } - return Paths.get(location); - } - - private static String artifactProperty(String name) { - return "jdk.test.lib.artifacts." + name; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.artifacts; - -import java.io.FileNotFoundException; -import java.lang.reflect.Method; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; - -public class JibArtifactManager implements ArtifactManager { - private static final String JIB_SERVICE_FACTORY = "com.oracle.jib.api.JibServiceFactory"; - private static String jibVersion = "1.0"; - private Object installerObject; - - private JibArtifactManager(Object o) { - installerObject = o; - } - - public static JibArtifactManager newInstance() throws ClassNotFoundException { - try { - Class jibServiceFactory = Class.forName(JIB_SERVICE_FACTORY); - Object jibArtifactInstaller = jibServiceFactory.getMethod("createJibArtifactInstaller").invoke(null); - return new JibArtifactManager(jibArtifactInstaller); - } catch (Exception e) { - throw new ClassNotFoundException(JIB_SERVICE_FACTORY, e); - } - } - - private Path download(String jibVersion, HashMap artifactDescription) throws Exception { - return invokeInstallerMethod("download", jibVersion, artifactDescription); - } - - private Path install(String jibVersion, HashMap artifactDescription) throws Exception { - return invokeInstallerMethod("install", jibVersion, artifactDescription); - } - - private Path invokeInstallerMethod(String methodName, String jibVersion, HashMap artifactDescription) throws Exception { - Method m = Class.forName("com.oracle.jib.api.JibArtifactInstaller").getMethod(methodName, String.class, Map.class); - return (Path)m.invoke(installerObject, jibVersion, artifactDescription); - } - - @Override - public Path resolve(Artifact artifact) throws ArtifactResolverException { - Path path; - // Use the DefaultArtifactManager to enable users to override locations - try { - ArtifactManager manager = new DefaultArtifactManager(); - path = manager.resolve(artifact); - } catch (ArtifactResolverException e) { - // Location hasn't been overridden, continue to automatically try to resolve the dependency - try { - HashMap artifactDescription = new HashMap<>(); - artifactDescription.put("module", artifact.name()); - artifactDescription.put("organization", artifact.organization()); - artifactDescription.put("ext", artifact.extension()); - artifactDescription.put("revision", artifact.revision()); - if (artifact.classifier().length() > 0) { - artifactDescription.put("classifier", artifact.classifier()); - } - - path = download(jibVersion, artifactDescription); - if (artifact.unpack()) { - path = install(jibVersion, artifactDescription); - } - } catch (Exception e2) { - throw new ArtifactResolverException("Failed to resolve the artifact " + artifact, e2); - } - } - return path; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSOptions.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSOptions.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSOptions.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSOptions.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.cds; - -import java.util.ArrayList; - -// This class represents options used -// during creation of CDS archive and/or running JVM with a CDS archive -public class CDSOptions { - public String xShareMode = "on"; - public String archiveName; - public ArrayList prefix = new ArrayList(); - public ArrayList suffix = new ArrayList(); - - // Indicate whether to append "-version" when using CDS Archive. - // Most of tests will use '-version' - public boolean useVersion = true; - - - public CDSOptions() { - } - - - public CDSOptions addPrefix(String... prefix) { - for (String s : prefix) this.prefix.add(s); - return this; - } - - - public CDSOptions addSuffix(String... suffix) { - for (String s : suffix) this.suffix.add(s); - return this; - } - - public CDSOptions setXShareMode(String mode) { - this.xShareMode = mode; - return this; - } - - - public CDSOptions setArchiveName(String name) { - this.archiveName = name; - return this; - } - - - public CDSOptions setUseVersion(boolean use) { - this.useVersion = use; - return this; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSTestUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSTestUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSTestUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cds/CDSTestUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,585 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.cds; - -import java.io.IOException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import jdk.test.lib.Utils; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - - -// This class contains common test utilities for testing CDS -public class CDSTestUtils { - public interface Checker { - public void check(OutputAnalyzer output) throws Exception; - } - - /* - * INTRODUCTION - * - * When testing various CDS functionalities, we need to launch JVM processes - * using a "launch method" (such as TestCommon.run), and analyze the results of these - * processes. - * - * While typical jtreg tests would use OutputAnalyzer in such cases, due to the - * complexity of CDS failure modes, we have added the CDSTestUtils.Result class - * to make the analysis more convenient and less error prone. - * - * A Java process can end in one of the following 4 states: - * - * 1: Unexpected error - such as JVM crashing. In this case, the "launch method" - * will throw a RuntimeException. - * 2: Mapping Failure - this happens when the OS (intermittently) fails to map the - * CDS archive, normally caused by Address Space Layout Randomization. - * We usually treat this as "pass". - * 3: Normal Exit - the JVM process has finished without crashing, and the exit code is 0. - * 4: Abnormal Exit - the JVM process has finished without crashing, and the exit code is not 0. - * - * In most test cases, we need to check the JVM process's output in cases 3 and 4. However, we need - * to make sure that our test code is not confused by case 2. - * - * For example, a JVM process is expected to print the string "Hi" and exit with 0. With the old - * CDSTestUtils.runWithArchive API, the test may be written as this: - * - * OutputAnalyzer out = CDSTestUtils.runWithArchive(args); - * out.shouldContain("Hi"); - * - * However, if the JVM process fails with mapping failure, the string "Hi" will not be in the output, - * and your test case will fail intermittently. - * - * Instead, the test case should be written as - * - * CCDSTestUtils.run(args).assertNormalExit("Hi"); - * - * EXAMPLES/HOWTO - * - * 1. For simple substring matching: - * - * CCDSTestUtils.run(args).assertNormalExit("Hi"); - * CCDSTestUtils.run(args).assertNormalExit("a", "b", "x"); - * CCDSTestUtils.run(args).assertAbnormalExit("failure 1", "failure2"); - * - * 2. For more complex output matching: using Lambda expressions - * - * CCDSTestUtils.run(args) - * .assertNormalExit(output -> output.shouldNotContain("this should not be printed"); - * CCDSTestUtils.run(args) - * .assertAbnormalExit(output -> { - * output.shouldNotContain("this should not be printed"); - * output.shouldHaveExitValue(123); - * }); - * - * 3. Chaining several checks: - * - * CCDSTestUtils.run(args) - * .assertNormalExit(output -> output.shouldNotContain("this should not be printed") - * .assertNormalExit("should have this", "should have that"); - * - * 4. [Rare use case] if a test sometimes exit normally, and sometimes abnormally: - * - * CCDSTestUtils.run(args) - * .ifNormalExit("ths string is printed when exiting with 0") - * .ifAbNormalExit("ths string is printed when exiting with 1"); - * - * NOTE: you usually don't want to write your test case like this -- it should always - * exit with the same exit code. (But I kept this API because some existing test cases - * behave this way -- need to revisit). - */ - public static class Result { - private final OutputAnalyzer output; - private final CDSOptions options; - private final boolean hasMappingFailure; - private final boolean hasAbnormalExit; - private final boolean hasNormalExit; - private final String CDS_DISABLED = "warning: CDS is disabled when the"; - - public Result(CDSOptions opts, OutputAnalyzer out) throws Exception { - options = opts; - output = out; - hasMappingFailure = CDSTestUtils.checkCommonExecExceptions(output); - hasAbnormalExit = (!hasMappingFailure) && (output.getExitValue() != 0); - hasNormalExit = (!hasMappingFailure) && (output.getExitValue() == 0); - - if (hasNormalExit) { - if ("on".equals(options.xShareMode) && - output.getStderr().contains("java version") && - !output.getStderr().contains(CDS_DISABLED)) { - // "-showversion" is always passed in the command-line by the execXXX methods. - // During normal exit, we require that the VM to show that sharing was enabled. - output.shouldContain("sharing"); - } - } - } - - public Result assertNormalExit(Checker checker) throws Exception { - if (!hasMappingFailure) { - checker.check(output); - output.shouldHaveExitValue(0); - } - return this; - } - - public Result assertAbnormalExit(Checker checker) throws Exception { - if (!hasMappingFailure) { - checker.check(output); - output.shouldNotHaveExitValue(0); - } - return this; - } - - // When {--limit-modules, --patch-module, and/or --upgrade-module-path} - // are specified, CDS is silently disabled for both -Xshare:auto and -Xshare:on. - public Result assertSilentlyDisabledCDS(Checker checker) throws Exception { - if (hasMappingFailure) { - throw new RuntimeException("Unexpected mapping failure"); - } - // this comes from a JVM warning message. - output.shouldContain(CDS_DISABLED); - - checker.check(output); - return this; - } - - public Result assertSilentlyDisabledCDS(int exitCode, String... matches) throws Exception { - return assertSilentlyDisabledCDS((out) -> { - out.shouldHaveExitValue(exitCode); - checkMatches(out, matches); - }); - } - - public Result ifNormalExit(Checker checker) throws Exception { - if (hasNormalExit) { - checker.check(output); - } - return this; - } - - public Result ifAbnormalExit(Checker checker) throws Exception { - if (hasAbnormalExit) { - checker.check(output); - } - return this; - } - - public Result ifNoMappingFailure(Checker checker) throws Exception { - if (!hasMappingFailure) { - checker.check(output); - } - return this; - } - - - public Result assertNormalExit(String... matches) throws Exception { - if (!hasMappingFailure) { - checkMatches(output, matches); - output.shouldHaveExitValue(0); - } - return this; - } - - public Result assertAbnormalExit(String... matches) throws Exception { - if (!hasMappingFailure) { - checkMatches(output, matches); - output.shouldNotHaveExitValue(0); - } - - return this; - } - } - - // Specify this property to copy sdandard output of the child test process to - // the parent/main stdout of the test. - // By default such output is logged into a file, and is copied into the main stdout. - public static final boolean CopyChildStdoutToMainStdout = - Boolean.valueOf(System.getProperty("test.cds.copy.child.stdout", "true")); - - // This property is passed to child test processes - public static final String TestTimeoutFactor = System.getProperty("test.timeout.factor", "1.0"); - - public static final String UnableToMapMsg = - "Unable to map shared archive: test did not complete; assumed PASS"; - - // Create bootstrap CDS archive, - // use extra JVM command line args as a prefix. - // For CDS tests specifying prefix makes more sense than specifying suffix, since - // normally there are no classes or arguments to classes, just "-version" - // To specify suffix explicitly use CDSOptions.addSuffix() - public static OutputAnalyzer createArchive(String... cliPrefix) - throws Exception { - return createArchive((new CDSOptions()).addPrefix(cliPrefix)); - } - - // Create bootstrap CDS archive - public static OutputAnalyzer createArchive(CDSOptions opts) - throws Exception { - - startNewArchiveName(); - - ArrayList cmd = new ArrayList(); - - for (String p : opts.prefix) cmd.add(p); - - cmd.add("-Xshare:dump"); - cmd.add("-Xlog:cds,cds+hashtables"); - if (opts.archiveName == null) - opts.archiveName = getDefaultArchiveName(); - cmd.add("-XX:SharedArchiveFile=./" + opts.archiveName); - - for (String s : opts.suffix) cmd.add(s); - - String[] cmdLine = cmd.toArray(new String[cmd.size()]); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine); - return executeAndLog(pb, "dump"); - } - - - // check result of 'dump-the-archive' operation, that is "-Xshare:dump" - public static OutputAnalyzer checkDump(OutputAnalyzer output, String... extraMatches) - throws Exception { - - output.shouldContain("Loading classes to share"); - output.shouldHaveExitValue(0); - - for (String match : extraMatches) { - output.shouldContain(match); - } - - return output; - } - - - // A commonly used convenience methods to create an archive and check the results - // Creates an archive and checks for errors - public static OutputAnalyzer createArchiveAndCheck(CDSOptions opts) - throws Exception { - return checkDump(createArchive(opts)); - } - - - public static OutputAnalyzer createArchiveAndCheck(String... cliPrefix) - throws Exception { - return checkDump(createArchive(cliPrefix)); - } - - - // This method should be used to check the output of child VM for common exceptions. - // Most of CDS tests deal with child VM processes for creating and using the archive. - // However exceptions that occur in the child process do not automatically propagate - // to the parent process. This mechanism aims to improve the propagation - // of exceptions and common errors. - // Exception e argument - an exception to be re-thrown if none of the common - // exceptions match. Pass null if you wish not to re-throw any exception. - public static boolean checkCommonExecExceptions(OutputAnalyzer output, Exception e) - throws Exception { - if (output.getStdout().contains("http://bugreport.java.com/bugreport/crash.jsp")) { - throw new RuntimeException("Hotspot crashed"); - } - if (output.getStdout().contains("TEST FAILED")) { - throw new RuntimeException("Test Failed"); - } - if (output.getOutput().contains("shared class paths mismatch")) { -// throw new RuntimeException("shared class paths mismatch"); - } - if (output.getOutput().contains("Unable to unmap shared space")) { - throw new RuntimeException("Unable to unmap shared space"); - } - - // Special case -- sometimes Xshare:on fails because it failed to map - // at given address. This behavior is platform-specific, machine config-specific - // and can be random (see ASLR). - if (isUnableToMap(output)) { - System.out.println(UnableToMapMsg); - return true; - } - - if (e != null) { - throw e; - } - return false; - } - - public static boolean checkCommonExecExceptions(OutputAnalyzer output) throws Exception { - return checkCommonExecExceptions(output, null); - } - - - // Check the output for indication that mapping of the archive failed. - // Performance note: this check seems to be rather costly - searching the entire - // output stream of a child process for multiple strings. However, it is necessary - // to detect this condition, a failure to map an archive, since this is not a real - // failure of the test or VM operation, and results in a test being "skipped". - // Suggestions to improve: - // 1. VM can designate a special exit code for such condition. - // 2. VM can print a single distinct string indicating failure to map an archive, - // instead of utilizing multiple messages. - // These are suggestions to improve testibility of the VM. However, implementing them - // could also improve usability in the field. - public static boolean isUnableToMap(OutputAnalyzer output) { - String outStr = output.getOutput(); - if ((output.getExitValue() == 1) && ( - outStr.contains("Unable to reserve shared space at required address") || - outStr.contains("Unable to map ReadOnly shared space at required address") || - outStr.contains("Unable to map ReadWrite shared space at required address") || - outStr.contains("Unable to map MiscData shared space at required address") || - outStr.contains("Unable to map MiscCode shared space at required address") || - outStr.contains("Unable to map OptionalData shared space at required address") || - outStr.contains("Could not allocate metaspace at a compatible address") || - outStr.contains("UseSharedSpaces: Unable to allocate region, range is not within java heap") )) - { - return true; - } - - return false; - } - - public static Result run(String... cliPrefix) throws Exception { - CDSOptions opts = new CDSOptions(); - opts.setArchiveName(getDefaultArchiveName()); - opts.addPrefix(cliPrefix); - return new Result(opts, runWithArchive(opts)); - } - - public static Result run(CDSOptions opts) throws Exception { - return new Result(opts, runWithArchive(opts)); - } - - // Execute JVM with CDS archive, specify command line args suffix - public static OutputAnalyzer runWithArchive(String... cliPrefix) - throws Exception { - - return runWithArchive( (new CDSOptions()) - .setArchiveName(getDefaultArchiveName()) - .addPrefix(cliPrefix) ); - } - - - // Execute JVM with CDS archive, specify CDSOptions - public static OutputAnalyzer runWithArchive(CDSOptions opts) - throws Exception { - - ArrayList cmd = new ArrayList(); - - for (String p : opts.prefix) cmd.add(p); - - cmd.add("-Xshare:" + opts.xShareMode); - cmd.add("-Dtest.timeout.factor=" + TestTimeoutFactor); - - if (opts.archiveName == null) - opts.archiveName = getDefaultArchiveName(); - cmd.add("-XX:SharedArchiveFile=" + opts.archiveName); - - if (opts.useVersion) - cmd.add("-version"); - - for (String s : opts.suffix) cmd.add(s); - - String[] cmdLine = cmd.toArray(new String[cmd.size()]); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine); - return executeAndLog(pb, "exec"); - } - - - // A commonly used convenience methods to create an archive and check the results - // Creates an archive and checks for errors - public static OutputAnalyzer runWithArchiveAndCheck(CDSOptions opts) throws Exception { - return checkExec(runWithArchive(opts)); - } - - - public static OutputAnalyzer runWithArchiveAndCheck(String... cliPrefix) throws Exception { - return checkExec(runWithArchive(cliPrefix)); - } - - - public static OutputAnalyzer checkExec(OutputAnalyzer output, - String... extraMatches) throws Exception { - CDSOptions opts = new CDSOptions(); - return checkExec(output, opts, extraMatches); - } - - - // check result of 'exec' operation, that is when JVM is run using the archive - public static OutputAnalyzer checkExec(OutputAnalyzer output, CDSOptions opts, - String... extraMatches) throws Exception { - try { - if ("on".equals(opts.xShareMode)) { - output.shouldContain("sharing"); - } - output.shouldHaveExitValue(0); - } catch (RuntimeException e) { - checkCommonExecExceptions(output, e); - return output; - } - - checkMatches(output, extraMatches); - return output; - } - - - public static OutputAnalyzer checkExecExpectError(OutputAnalyzer output, - int expectedExitValue, - String... extraMatches) throws Exception { - if (isUnableToMap(output)) { - System.out.println(UnableToMapMsg); - return output; - } - - output.shouldHaveExitValue(expectedExitValue); - checkMatches(output, extraMatches); - return output; - } - - public static OutputAnalyzer checkMatches(OutputAnalyzer output, - String... matches) throws Exception { - for (String match : matches) { - output.shouldContain(match); - } - return output; - } - - - // get the file object for the test artifact - public static File getTestArtifact(String name, boolean checkExistence) { - File dir = new File(System.getProperty("test.classes", ".")); - File file = new File(dir, name); - - if (checkExistence && !file.exists()) { - throw new RuntimeException("Cannot find " + file.getPath()); - } - - return file; - } - - - // create file containing the specified class list - public static File makeClassList(String classes[]) - throws Exception { - return makeClassList(getTestName() + "-", classes); - } - - // create file containing the specified class list - public static File makeClassList(String testCaseName, String classes[]) - throws Exception { - - File classList = getTestArtifact(testCaseName + "test.classlist", false); - FileOutputStream fos = new FileOutputStream(classList); - PrintStream ps = new PrintStream(fos); - - addToClassList(ps, classes); - - ps.close(); - fos.close(); - - return classList; - } - - - public static void addToClassList(PrintStream ps, String classes[]) - throws IOException - { - if (classes != null) { - for (String s : classes) { - ps.println(s); - } - } - } - - - // Optimization for getting a test name. - // Test name does not change during execution of the test, - // but getTestName() uses stack walking hence it is expensive. - // Therefore cache it and reuse it. - private static String testName; - public static String getTestName() { - if (testName == null) { - testName = Utils.getTestName(); - } - return testName; - } - - private static final SimpleDateFormat timeStampFormat = - new SimpleDateFormat("HH'h'mm'm'ss's'SSS"); - - private static String defaultArchiveName; - - // Call this method to start new archive with new unique name - public static void startNewArchiveName() { - defaultArchiveName = getTestName() + - timeStampFormat.format(new Date()) + ".jsa"; - } - - public static String getDefaultArchiveName() { - return defaultArchiveName; - } - - - // ===================== FILE ACCESS convenience methods - public static File getOutputFile(String name) { - File dir = new File(System.getProperty("test.classes", ".")); - return new File(dir, getTestName() + "-" + name); - } - - - public static File getOutputSourceFile(String name) { - File dir = new File(System.getProperty("test.classes", ".")); - return new File(dir, name); - } - - - public static File getSourceFile(String name) { - File dir = new File(System.getProperty("test.src", ".")); - return new File(dir, name); - } - - - // ============================= Logging - public static OutputAnalyzer executeAndLog(ProcessBuilder pb, String logName) throws Exception { - long started = System.currentTimeMillis(); - OutputAnalyzer output = new OutputAnalyzer(pb.start()); - - writeFile(getOutputFile(logName + ".stdout"), output.getStdout()); - writeFile(getOutputFile(logName + ".stderr"), output.getStderr()); - System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]"); - System.out.println("[STDERR]\n" + output.getStderr()); - - if (CopyChildStdoutToMainStdout) - System.out.println("[STDOUT]\n" + output.getStdout()); - - return output; - } - - - private static void writeFile(File file, String content) throws Exception { - FileOutputStream fos = new FileOutputStream(file); - PrintStream ps = new PrintStream(fos); - ps.print(content); - ps.close(); - fos.close(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.classloader; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.FileInputStream; - -public class ClassLoadUtils { - - private ClassLoadUtils() { - } - - /** - * Get filename of class file from classpath for given class name. - * - * @param className class name - * @return filename or null if not found - */ - public static String getClassPath(String className) { - String fileName = className.replace(".", File.separator) + ".class"; - String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); - File target = null; - int i; - for (i = 0; i < classPath.length; ++i) { - target = new File(classPath[i] + File.separator + fileName); - System.out.println("Try: " + target); - if (target.exists()) { - break; - } - } - if (i != classPath.length) { - return classPath[i]; - } - return null; - } - - /** - * Get filename of class file from classpath for given class name. - * - * @param className class name - * @return filename or null if not found - */ - public static String getClassPathFileName(String className) { - String fileName = className.replace(".", File.separator) + ".class"; - String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); - File target = null; - int i; - for (i = 0; i < classPath.length; ++i) { - target = new File(classPath[i] + File.separator + fileName); - System.out.println("Try: " + target); - if (target.exists()) { - break; - } - } - if (i != classPath.length) { - try { - return target.getCanonicalPath(); - } catch (IOException e) { - return null; - } - } - return null; - } - - public static String getRedefineClassFileName(String dir, String className) { - String fileName = getClassPathFileName(className); - if (fileName == null) { - return null; - } - if (fileName.contains("classes")) { - return fileName.replace("classes", dir); - } else { - String classPath = getClassPath(className); - if (classPath != null) { - return classPath + File.separator + "newclass" + File.separator + className.replace(".", File.separator) + ".class"; - } else { - return null; - } - } - } - - /** - * Get filename of class file which is to be redefined. - */ - public static String getRedefineClassFileName(String className) { - return getRedefineClassFileName("newclass", className); - } - - /** - * Read whole file. - * - * @param file file - * @return contents of file as byte array - */ - public static byte[] readFile(File file) throws IOException { - InputStream in = new FileInputStream(file); - long countl = file.length(); - if (countl > Integer.MAX_VALUE) { - throw new IOException("File is too huge"); - } - int count = (int) countl; - byte[] buffer = new byte[count]; - int n = 0; - try { - while (n < count) { - int k = in.read(buffer, n, count - n); - if (k < 0) { - throw new IOException("Unexpected EOF"); - } - n += k; - } - } finally { - in.close(); - } - return buffer; - } - - /** - * Read whole file. - * - * @param name file name - * @return contents of file as byte array - */ - public static byte[] readFile(String name) throws IOException { - return readFile(new File(name)); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.classloader; - -import java.util.function.Predicate; -/** - * A classloader, which using target classloader in case provided condition - * for class name is met, and using parent otherwise - */ -public class FilterClassLoader extends ClassLoader { - - private final ClassLoader target; - private final Predicate condition; - - public FilterClassLoader(ClassLoader target, ClassLoader parent, - Predicate condition) { - super(parent); - this.condition = condition; - this.target = target; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (condition.test(name)) { - return target.loadClass(name); - } - return super.loadClass(name); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.classloader; - -import java.io.*; -import java.util.*; - -/** - * Classloader that generates classes on the fly. - * - * This classloader can load classes with name starting with 'Class'. It will - * use TemplateClass as template and will replace class name in the bytecode of - * template class. It can be used for example to detect memory leaks in class - * loading or to quickly fill Metaspace. - */ -class TemplateClass { -} - -public class GeneratingClassLoader extends ClassLoader { - - public synchronized Class loadClass(String name) throws ClassNotFoundException { - return loadClass(name, false); - } - - public synchronized Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - Class c = findLoadedClass(name); - if (c != null) { - return c; - } - if (!name.startsWith(PREFIX)) { - return super.loadClass(name, resolve); - } - if (name.length() != templateClassName.length()) { - throw new ClassNotFoundException("Only can load classes with name.length() = " + getNameLength() + " got: '" + name + "' length: " + name.length()); - } - byte[] bytecode = getPatchedByteCode(name); - c = defineClass(name, bytecode, 0, bytecode.length); - if (resolve) { - resolveClass(c); - } - return c; - } - - /** - * Create generating class loader that will use class file for given class - * from classpath as template. - */ - public GeneratingClassLoader(String templateClassName) { - this.templateClassName = templateClassName; - classPath = System.getProperty("java.class.path").split(File.pathSeparator); - try { - templateClassNameBytes = templateClassName.getBytes(encoding); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - /** - * Create generating class loader that will use class file for - * nsk.share.classload.TemplateClass as template. - */ - public GeneratingClassLoader() { - this(TemplateClass.class.getName()); - } - - public int getNameLength() { - return templateClassName.length(); - } - - String getPrefix() { - return PREFIX; - } - - public String getClassName(int number) { - StringBuffer sb = new StringBuffer(); - sb.append(PREFIX); - sb.append(number); - int n = templateClassName.length() - sb.length(); - for (int i = 0; i < n; ++i) { - sb.append("_"); - } - return sb.toString(); - } - - private byte[] getPatchedByteCode(String name) throws ClassNotFoundException { - try { - byte[] bytecode = getByteCode(); - String fname = name.replace(".", File.separator); - byte[] replaceBytes = fname.getBytes(encoding); - for (int offset : offsets) { - for (int i = 0; i < replaceBytes.length; ++i) { - bytecode[offset + i] = replaceBytes[i]; - } - } - return bytecode; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - private byte[] getByteCode() throws ClassNotFoundException { - if (bytecode == null) { - readByteCode(); - } - if (offsets == null) { - getOffsets(bytecode); - if (offsets == null) { - throw new RuntimeException("Class name not found in template class file"); - } - } - return (byte[]) bytecode.clone(); - } - - private void readByteCode() throws ClassNotFoundException { - String fname = templateClassName.replace(".", File.separator) + ".class"; - File target = null; - for (int i = 0; i < classPath.length; ++i) { - target = new File(classPath[i] + File.separator + fname); - if (target.exists()) { - break; - } - } - - if (target == null || !target.exists()) { - throw new ClassNotFoundException("File not found: " + target); - } - try { - bytecode = ClassLoadUtils.readFile(target); - } catch (IOException e) { - throw new ClassNotFoundException(templateClassName, e); - } - } - - private void getOffsets(byte[] bytecode) { - List offsets = new ArrayList(); - if (this.offsets == null) { - String pname = templateClassName.replace(".", "/"); - try { - byte[] pnameb = pname.getBytes(encoding); - int i = 0; - while (true) { - while (i < bytecode.length) { - int j = 0; - while (j < pnameb.length && bytecode[i + j] == pnameb[j]) { - ++j; - } - if (j == pnameb.length) { - break; - } - i++; - } - if (i == bytecode.length) { - break; - } - offsets.add(new Integer(i)); - i++; - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - this.offsets = new int[offsets.size()]; - for (int i = 0; i < offsets.size(); ++i) { - this.offsets[i] = offsets.get(i).intValue(); - } - } - } - - public static final String DEFAULT_CLASSNAME = TemplateClass.class.getName(); - static final String PREFIX = "Class"; - - private final String[] classPath; - private byte[] bytecode; - private int[] offsets; - private final String encoding = "UTF8"; - private final String templateClassName; - private final byte[] templateClassNameBytes; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.classloader; - -import java.net.URL; -import java.net.URLClassLoader; - -/** - * An url classloader, which trying to load class from provided URL[] first, - * and using parent classloader in case it failed - */ -public class ParentLastURLClassLoader extends URLClassLoader { - - public ParentLastURLClassLoader(URL urls[], ClassLoader parent) { - super(urls, parent); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - try { - Class c = findClass(name); - if (c != null) { - return c; - } - } catch (ClassNotFoundException e) { - // ignore - } - return super.loadClass(name); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli; - -import jdk.test.lib.cli.predicate.CPUSpecificPredicate; - -/** - * Base class for command line options tests that - * requires specific CPU arch or specific CPU features. - */ -public abstract class CPUSpecificCommandLineOptionTest - extends CommandLineOptionTest { - /** - * Creates new CPU specific test instance that does not - * require any CPU features. - * - * @param cpuArchPattern Regular expression that should - * match os.arch. - */ - public CPUSpecificCommandLineOptionTest(String cpuArchPattern) { - this(cpuArchPattern, null, null); - } - - /** - * Creates new CPU specific test instance that does not - * require from CPU support of {@code supportedCPUFeatures} features - * and no support of {@code unsupportedCPUFeatures}. - * - * @param cpuArchPattern Regular expression that should - * match os.arch. - * @param supportedCPUFeatures Array with names of features that - * should be supported by CPU. If {@code null}, - * then no features have to be supported. - * @param unsupportedCPUFeatures Array with names of features that - * should not be supported by CPU. - * If {@code null}, then CPU may support any - * features. - */ - public CPUSpecificCommandLineOptionTest(String cpuArchPattern, - String supportedCPUFeatures[], String unsupportedCPUFeatures[]) { - super(new CPUSpecificPredicate(cpuArchPattern, supportedCPUFeatures, - unsupportedCPUFeatures)); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,545 +0,0 @@ -/* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli; - -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; -import java.util.function.BooleanSupplier; - -import jdk.test.lib.management.InputArguments; -import jdk.test.lib.process.ExitCode; -import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.Platform; -import jdk.test.lib.Utils; - -/** - * Base class for command line option tests. - */ -public abstract class CommandLineOptionTest { - public static final String UNLOCK_DIAGNOSTIC_VM_OPTIONS - = "-XX:+UnlockDiagnosticVMOptions"; - public static final String UNLOCK_EXPERIMENTAL_VM_OPTIONS - = "-XX:+UnlockExperimentalVMOptions"; - protected static final String UNRECOGNIZED_OPTION_ERROR_FORMAT - = "Unrecognized VM option '[+-]?%s(=.*)?'"; - protected static final String EXPERIMENTAL_OPTION_ERROR_FORMAT - = "VM option '%s' is experimental and must be enabled via " - + "-XX:\\+UnlockExperimentalVMOptions."; - protected static final String DIAGNOSTIC_OPTION_ERROR_FORMAT - = " VM option '%s' is diagnostic and must be enabled via " - + "-XX:\\+UnlockDiagnosticVMOptions."; - private static final String PRINT_FLAGS_FINAL_FORMAT = "%s\\s*:?=\\s*%s"; - - /** - * Verifies that JVM startup behavior matches our expectations. - * - * @param option an option that should be passed to JVM - * @param expectedMessages an array of patterns that should occur - * in JVM output. If {@code null} then - * JVM output could be empty. - * @param unexpectedMessages an array of patterns that should not - * occur in JVM output. If {@code null} then - * JVM output could be empty. - * @param exitErrorMessage message that will be shown if exit code is not - * as expected. - * @param wrongWarningMessage message that will be shown if warning - * messages are not as expected. - * @param exitCode expected exit code. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyJVMStartup(String option, - String expectedMessages[], String unexpectedMessages[], - String exitErrorMessage, String wrongWarningMessage, - ExitCode exitCode) throws Throwable { - CommandLineOptionTest.verifyJVMStartup(expectedMessages, - unexpectedMessages, exitErrorMessage, - wrongWarningMessage, exitCode, false, option); - } - - /** - * Verifies that JVM startup behavior matches our expectations. - * - * @param expectedMessages an array of patterns that should occur - * in JVM output. If {@code null} then - * JVM output could be empty. - * @param unexpectedMessages an array of patterns that should not - * occur in JVM output. If {@code null} then - * JVM output could be empty. - * @param exitErrorMessage message that will be shown if exit code is not - * as expected. - * @param wrongWarningMessage message that will be shown if warning - * messages are not as expected. - * @param exitCode expected exit code. - * @param addTestVMOptions if {@code true} then test VM options will be - * passed to VM. - * @param options options that should be passed to VM in addition to mode - * flag. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyJVMStartup(String expectedMessages[], - String unexpectedMessages[], String exitErrorMessage, - String wrongWarningMessage, ExitCode exitCode, - boolean addTestVMOptions, String... options) - throws Throwable { - List finalOptions = new ArrayList<>(); - if (addTestVMOptions) { - Collections.addAll(finalOptions, InputArguments.getVmInputArgs()); - Collections.addAll(finalOptions, Utils.getTestJavaOpts()); - } - Collections.addAll(finalOptions, options); - finalOptions.add("-version"); - - ProcessBuilder processBuilder - = ProcessTools.createJavaProcessBuilder(finalOptions.toArray( - new String[finalOptions.size()])); - OutputAnalyzer outputAnalyzer - = new OutputAnalyzer(processBuilder.start()); - - try { - outputAnalyzer.shouldHaveExitValue(exitCode.value); - } catch (RuntimeException e) { - String errorMessage = String.format( - "JVM process should have exit value '%d'.%n%s", - exitCode.value, exitErrorMessage); - throw new AssertionError(errorMessage, e); - } - - verifyOutput(expectedMessages, unexpectedMessages, - wrongWarningMessage, outputAnalyzer); - } - - /** - * Verifies that JVM startup behavior matches our expectations. - * - * @param expectedMessages an array of patterns that should occur in JVM - * output. If {@code null} then - * JVM output could be empty. - * @param unexpectedMessages an array of patterns that should not occur - * in JVM output. If {@code null} then - * JVM output could be empty. - * @param wrongWarningMessage message that will be shown if messages are - * not as expected. - * @param outputAnalyzer OutputAnalyzer instance - * @throws AssertionError if verification fails. - */ - public static void verifyOutput(String[] expectedMessages, - String[] unexpectedMessages, String wrongWarningMessage, - OutputAnalyzer outputAnalyzer) { - if (expectedMessages != null) { - for (String expectedMessage : expectedMessages) { - try { - outputAnalyzer.shouldMatch(expectedMessage); - } catch (RuntimeException e) { - String errorMessage = String.format( - "Expected message not found: '%s'.%n%s", - expectedMessage, wrongWarningMessage); - throw new AssertionError(errorMessage, e); - } - } - } - - if (unexpectedMessages != null) { - for (String unexpectedMessage : unexpectedMessages) { - try { - outputAnalyzer.shouldNotMatch(unexpectedMessage); - } catch (RuntimeException e) { - String errorMessage = String.format( - "Unexpected message found: '%s'.%n%s", - unexpectedMessage, wrongWarningMessage); - throw new AssertionError(errorMessage, e); - } - } - } - } - - /** - * Verifies that JVM startup behavior matches our expectations when type - * of newly started VM is the same as the type of current. - * - * @param expectedMessages an array of patterns that should occur - * in JVM output. If {@code null} then - * JVM output could be empty. - * @param unexpectedMessages an array of patterns that should not - * occur in JVM output. If {@code null} then - * JVM output could be empty. - * @param exitErrorMessage Message that will be shown if exit value is not - * as expected. - * @param wrongWarningMessage message that will be shown if warning - * messages are not as expected. - * @param exitCode expected exit code. - * @param options options that should be passed to VM in addition to mode - * flag. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifySameJVMStartup(String expectedMessages[], - String unexpectedMessages[], String exitErrorMessage, - String wrongWarningMessage, ExitCode exitCode, String... options) - throws Throwable { - List finalOptions = new ArrayList<>(); - finalOptions.add(CommandLineOptionTest.getVMTypeOption()); - String extraFlagForEmulated = CommandLineOptionTest.getVMTypeOptionForEmulated(); - if (extraFlagForEmulated != null) { - finalOptions.add(extraFlagForEmulated); - } - Collections.addAll(finalOptions, options); - - CommandLineOptionTest.verifyJVMStartup(expectedMessages, - unexpectedMessages, exitErrorMessage, - wrongWarningMessage, exitCode, false, - finalOptions.toArray(new String[finalOptions.size()])); - } - - /** - * Verifies that value of specified JVM option is the same as - * expected value. - * This method filter out option with {@code optionName} - * name from test java options. - * - * @param optionName a name of tested option. - * @param expectedValue expected value of tested option. - * @param optionErrorString message will be shown if option value is not as - * expected. - * @param additionalVMOpts additional options that should be - * passed to JVM. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyOptionValue(String optionName, - String expectedValue, String optionErrorString, - String... additionalVMOpts) throws Throwable { - verifyOptionValue(optionName, expectedValue, optionErrorString, - true, additionalVMOpts); - } - - /** - * Verifies that value of specified JVM option is the same as - * expected value. - * This method filter out option with {@code optionName} - * name from test java options. - * - * @param optionName a name of tested option. - * @param expectedValue expected value of tested option. - * @param addTestVmOptions if {@code true}, then test VM options - * will be used. - * @param optionErrorString message will be shown if option value is not as - * expected. - * @param additionalVMOpts additional options that should be - * passed to JVM. - * @throws Throwable if verification fails or some other issues - * occur. - */ - public static void verifyOptionValue(String optionName, - String expectedValue, String optionErrorString, - boolean addTestVmOptions, String... additionalVMOpts) - throws Throwable { - List vmOpts = new ArrayList<>(); - - if (addTestVmOptions) { - Collections.addAll(vmOpts, - Utils.getFilteredTestJavaOpts(optionName)); - } - Collections.addAll(vmOpts, additionalVMOpts); - Collections.addAll(vmOpts, "-XX:+PrintFlagsFinal", "-version"); - - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( - vmOpts.toArray(new String[vmOpts.size()])); - - OutputAnalyzer outputAnalyzer - = new OutputAnalyzer(processBuilder.start()); - - try { - outputAnalyzer.shouldHaveExitValue(0); - } catch (RuntimeException e) { - String errorMessage = String.format( - "JVM should start with option '%s' without errors.", - optionName); - throw new AssertionError(errorMessage, e); - } - verifyOptionValue(optionName, expectedValue, optionErrorString, - outputAnalyzer); - } - - /** - * Verifies that value of specified JVM option is the same as - * expected value. - * - * @param optionName a name of tested option. - * @param expectedValue expected value of tested option. - * @param optionErrorString message will be shown if option value is not - * as expected. - * @param outputAnalyzer OutputAnalyzer instance - * @throws AssertionError if verification fails - */ - public static void verifyOptionValue(String optionName, - String expectedValue, String optionErrorString, - OutputAnalyzer outputAnalyzer) { - try { - outputAnalyzer.shouldMatch(String.format( - CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT, - optionName, expectedValue)); - } catch (RuntimeException e) { - String errorMessage = String.format( - "Option '%s' is expected to have '%s' value%n%s", - optionName, expectedValue, - optionErrorString); - throw new AssertionError(errorMessage, e); - } - } - - /** - * Start VM with given options and values. - * Generates command line option flags from - * {@code optionNames} and {@code optionValues}. - * - * @param optionNames names of options to pass in - * @param optionValues values of option - * @param additionalVMOpts additional options that should be - * passed to JVM. - * @return output from vm process - */ - public static OutputAnalyzer startVMWithOptions(String[] optionNames, - String[] optionValues, - String... additionalVMOpts) throws Throwable { - List vmOpts = new ArrayList<>(); - if (optionNames == null || optionValues == null || optionNames.length != optionValues.length) { - throw new IllegalArgumentException("optionNames and/or optionValues"); - } - - for (int i = 0; i < optionNames.length; i++) { - vmOpts.add(prepareFlag(optionNames[i], optionValues[i])); - } - Collections.addAll(vmOpts, additionalVMOpts); - Collections.addAll(vmOpts, "-version"); - - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( - vmOpts.toArray(new String[vmOpts.size()])); - - return new OutputAnalyzer(processBuilder.start()); - } - - /** - * Verifies from the output that values of specified JVM options were the same as - * expected values. - * - * @param outputAnalyzer search output for expect options and values. - * @param optionNames names of tested options. - * @param expectedValues expected values of tested options. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyOptionValuesFromOutput(OutputAnalyzer outputAnalyzer, - String[] optionNames, - String[] expectedValues) throws Throwable { - outputAnalyzer.shouldHaveExitValue(0); - for (int i = 0; i < optionNames.length; i++) { - outputAnalyzer.shouldMatch(String.format( - CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT, - optionNames[i], expectedValues[i])); - } - } - - /** - * Verifies that value of specified JVM options are the same as - * expected values. - * Generates command line option flags from - * {@code optionNames} and {@code expectedValues}. - * - * @param optionNames names of tested options. - * @param expectedValues expected values of tested options. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyOptionValues(String[] optionNames, - String[] expectedValues) throws Throwable { - OutputAnalyzer outputAnalyzer = startVMWithOptions(optionNames, expectedValues, "-XX:+PrintFlagsFinal"); - verifyOptionValuesFromOutput(outputAnalyzer, optionNames, expectedValues); - } - - /** - * Verifies that value of specified JVM when type of newly started VM - * is the same as the type of current. - * This method filter out option with {@code optionName} - * name from test java options. - * Only mode flag will be passed to VM in addition to - * {@code additionalVMOpts} - * - * @param optionName name of tested option. - * @param expectedValue expected value of tested option. - * @param optionErrorString message to show if option has another value - * @param additionalVMOpts additional options that should be - * passed to JVM. - * @throws Throwable if verification fails or some other issues occur. - */ - public static void verifyOptionValueForSameVM(String optionName, - String expectedValue, String optionErrorString, - String... additionalVMOpts) throws Throwable { - List finalOptions = new ArrayList<>(); - finalOptions.add(CommandLineOptionTest.getVMTypeOption()); - String extraFlagForEmulated = CommandLineOptionTest.getVMTypeOptionForEmulated(); - if (extraFlagForEmulated != null) { - finalOptions.add(extraFlagForEmulated); - } - Collections.addAll(finalOptions, additionalVMOpts); - - CommandLineOptionTest.verifyOptionValue(optionName, expectedValue, - optionErrorString, false, - finalOptions.toArray(new String[finalOptions.size()])); - } - - /** - * Prepares boolean command line flag with name {@code name} according - * to it's {@code value}. - * - * @param name the name of option to be prepared - * @param value the value of option - * @return prepared command line flag - */ - public static String prepareBooleanFlag(String name, boolean value) { - return String.format("-XX:%c%s", (value ? '+' : '-'), name); - } - - /** - * Prepares numeric command line flag with name {@code name} by setting - * it's value to {@code value}. - * - * @param name the name of option to be prepared - * @param value the value of option - * @return prepared command line flag - */ - public static String prepareNumericFlag(String name, Number value) { - return String.format("-XX:%s=%s", name, value.toString()); - } - - /** - * Prepares generic command line flag with name {@code name} by setting - * it's value to {@code value}. - * - * @param name the name of option to be prepared - * @param value the value of option ("+" or "-" can be used instead of "true" or "false") - * @return prepared command line flag - */ - public static String prepareFlag(String name, String value) { - if (value.equals("+") || value.equalsIgnoreCase("true")) { - return "-XX:+" + name; - } else if (value.equals("-") || value.equalsIgnoreCase("false")) { - return "-XX:-" + name; - } else { - return "-XX:" + name + "=" + value; - } - } - - /** - * Returns message that should occur in VM output if option - * {@code optionName} if unrecognized. - * - * @param optionName the name of option for which message should be returned - * @return message saying that option {@code optionName} is unrecognized - */ - public static String getUnrecognizedOptionErrorMessage(String optionName) { - return String.format( - CommandLineOptionTest.UNRECOGNIZED_OPTION_ERROR_FORMAT, - optionName); - } - - /** - * Returns message that should occur in VM output if option - * {@code optionName} is experimental and - * -XX:+UnlockExperimentalVMOptions was not passed to VM. - * - * @param optionName the name of option for which message should be returned - * @return message saying that option {@code optionName} is experimental - */ - public static String getExperimentalOptionErrorMessage(String optionName) { - return String.format( - CommandLineOptionTest.EXPERIMENTAL_OPTION_ERROR_FORMAT, - optionName); - } - - /** - * Returns message that should occur in VM output if option - * {@code optionName} is diagnostic and -XX:+UnlockDiagnosticVMOptions - * was not passed to VM. - * - * @param optionName the name of option for which message should be returned - * @return message saying that option {@code optionName} is diganostic - */ - public static String getDiagnosticOptionErrorMessage(String optionName) { - return String.format( - CommandLineOptionTest.DIAGNOSTIC_OPTION_ERROR_FORMAT, - optionName); - } - - /** - * @return option required to start a new VM with the same type as current. - * @throws RuntimeException when VM type is unknown. - */ - private static String getVMTypeOption() { - if (Platform.isServer()) { - return "-server"; - } else if (Platform.isClient()) { - return "-client"; - } else if (Platform.isMinimal()) { - return "-minimal"; - } else if (Platform.isGraal()) { - return "-graal"; - } - throw new RuntimeException("Unknown VM mode."); - } - - /** - * @return addtional VMoptions(Emulated related) required to start a new VM with the same type as current. - */ - private static String getVMTypeOptionForEmulated() { - if (Platform.isServer() && !Platform.isEmulatedClient()) { - return "-XX:-NeverActAsServerClassMachine"; - } else if (Platform.isEmulatedClient()) { - return "-XX:+NeverActAsServerClassMachine"; - } - return null; - } - - private final BooleanSupplier predicate; - - /** - * Constructs new CommandLineOptionTest that will be executed only if - * predicate {@code predicate} return {@code true}. - * @param predicate a predicate responsible for test's preconditions check. - */ - public CommandLineOptionTest(BooleanSupplier predicate) { - this.predicate = predicate; - } - - /** - * Runs command line option test. - */ - public final void test() throws Throwable { - if (predicate.getAsBoolean()) { - runTestCases(); - } - } - - /** - * @throws Throwable if some issue happened during test cases execution. - */ - protected abstract void runTestCases() throws Throwable; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli.predicate; - -import java.util.function.BooleanSupplier; - -public class AndPredicate implements BooleanSupplier { - private final BooleanSupplier a; - private final BooleanSupplier b; - private final BooleanSupplier c; - - public AndPredicate(BooleanSupplier a, BooleanSupplier b) { - this.a = a; - this.b = b; - this.c = () -> true; // Boolean.TRUE::booleanValue - } - - public AndPredicate(BooleanSupplier a, BooleanSupplier b, BooleanSupplier c) { - this.a = a; - this.b = b; - this.c = c; - } - - @Override - public boolean getAsBoolean() { - return a.getAsBoolean() && b.getAsBoolean() && c.getAsBoolean(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli.predicate; - -import jdk.test.lib.Platform; -import sun.hotspot.cpuinfo.CPUInfo; - -import java.util.function.BooleanSupplier; - -public class CPUSpecificPredicate implements BooleanSupplier { - private final String cpuArchPattern; - private final String supportedCPUFeatures[]; - private final String unsupportedCPUFeatures[]; - - public CPUSpecificPredicate(String cpuArchPattern, - String supportedCPUFeatures[], - String unsupportedCPUFeatures[]) { - this.cpuArchPattern = cpuArchPattern; - this.supportedCPUFeatures = supportedCPUFeatures; - this.unsupportedCPUFeatures = unsupportedCPUFeatures; - } - - @Override - public boolean getAsBoolean() { - if (!Platform.getOsArch().matches(cpuArchPattern)) { - System.out.println("CPU arch " + Platform.getOsArch() + " does not match " + cpuArchPattern); - return false; - } - - if (supportedCPUFeatures != null) { - for (String feature : supportedCPUFeatures) { - if (!CPUInfo.hasFeature(feature)) { - System.out.println("CPU does not support " + feature - + " feature"); - return false; - } - } - } - - if (unsupportedCPUFeatures != null) { - for (String feature : unsupportedCPUFeatures) { - if (CPUInfo.hasFeature(feature)) { - System.out.println("CPU support " + feature + " feature"); - return false; - } - } - } - return true; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli.predicate; - -import java.util.function.BooleanSupplier; - -public class NotPredicate implements BooleanSupplier { - private final BooleanSupplier s; - - public NotPredicate(BooleanSupplier s) { - this.s = s; - } - - @Override - public boolean getAsBoolean() { - return !s.getAsBoolean(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.cli.predicate; - -import java.util.function.BooleanSupplier; - -public class OrPredicate implements BooleanSupplier { - private final BooleanSupplier a; - private final BooleanSupplier b; - - public OrPredicate(BooleanSupplier a, BooleanSupplier b) { - this.a = a; - this.b = b; - } - - @Override - public boolean getAsBoolean() { - return a.getAsBoolean() || b.getAsBoolean(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/CompilerUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/CompilerUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/CompilerUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/CompilerUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.compiler; - -import javax.tools.JavaCompiler; -import javax.tools.StandardJavaFileManager; -import javax.tools.StandardLocation; -import javax.tools.ToolProvider; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -/** - * This class consists exclusively of static utility methods for invoking the - * java compiler. - */ -public final class CompilerUtils { - private CompilerUtils() { } - - /** - * Compile all the java sources in {@code /**} to - * {@code /**}. The destination directory will be created if - * it doesn't exist. - * - * Equivalent to calling {@code compile(source, destination, true, options);}. - * - * All warnings/errors emitted by the compiler are output to System.out/err. - * - * @param source Path to the source directory - * @param destination Path to the destination directory - * @param options Any options to pass to the compiler - * - * @return true if the compilation is successful - * - * @throws IOException - * if there is an I/O error scanning the source tree or - * creating the destination directory - * @throws UnsupportedOperationException - * if there is no system java compiler - */ - public static boolean compile(Path source, Path destination, String... options) - throws IOException - { - return compile(source, destination, true, options); - } - - /** - * Compile all the java sources in {@code } and optionally its - * subdirectories, to - * {@code }. The destination directory will be created if - * it doesn't exist. - * - * All warnings/errors emitted by the compiler are output to System.out/err. - * - * @param source Path to the source directory - * @param destination Path to the destination directory - * @param recurse If {@code true} recurse into any {@code source} subdirectories - * to compile all java source files; else only compile those directly in - * {@code source}. - * @param options Any options to pass to the compiler - * - * @return true if the compilation is successful - * - * @throws IOException - * if there is an I/O error scanning the source tree or - * creating the destination directory - * @throws UnsupportedOperationException - * if there is no system java compiler - */ - - public static boolean compile(Path source, Path destination, boolean recurse, String... options) - throws IOException - { - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - if (compiler == null) { - // no compiler available - throw new UnsupportedOperationException("Unable to get system java compiler. " - + "Perhaps, jdk.compiler module is not available."); - } - StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null); - - List sources - = Files.find(source, (recurse ? Integer.MAX_VALUE : 1), - (file, attrs) -> (file.toString().endsWith(".java"))) - .collect(Collectors.toList()); - - Files.createDirectories(destination); - jfm.setLocation(StandardLocation.CLASS_PATH, Collections.emptyList()); - jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, - Collections.singletonList(destination)); - - List opts = Arrays.asList(options); - JavaCompiler.CompilationTask task - = compiler.getTask(null, jfm, null, opts, null, - jfm.getJavaFileObjectsFromPaths(sources)); - - return task.call(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/InMemoryJavaCompiler.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/InMemoryJavaCompiler.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/InMemoryJavaCompiler.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/InMemoryJavaCompiler.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.compiler; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.tools.ForwardingJavaFileManager; -import javax.tools.FileObject; -import javax.tools.JavaCompiler; -import javax.tools.JavaCompiler.CompilationTask; -import javax.tools.JavaFileObject; -import javax.tools.JavaFileObject.Kind; -import javax.tools.SimpleJavaFileObject; -import javax.tools.StandardLocation; -import javax.tools.ToolProvider; - -/** - * {@code InMemoryJavaCompiler} can be used for compiling a {@link - * CharSequence} to a {@code byte[]}. - * - * The compiler will not use the file system at all, instead using a {@link - * ByteArrayOutputStream} for storing the byte code. For the source code, any - * kind of {@link CharSequence} can be used, e.g. {@link String}, {@link - * StringBuffer} or {@link StringBuilder}. - * - * The {@code InMemoryCompiler} can easily be used together with a {@code - * ByteClassLoader} to easily compile and load source code in a {@link String}: - * - *

- * {@code
- * import jdk.test.lib.compiler.InMemoryJavaCompiler;
- * import jdk.test.lib.ByteClassLoader;
- *
- * class Example {
- *     public static void main(String[] args) {
- *         String className = "Foo";
- *         String sourceCode = "public class " + className + " {" +
- *                             "    public void bar() {" +
- *                             "        System.out.println("Hello from bar!");" +
- *                             "    }" +
- *                             "}";
- *         byte[] byteCode = InMemoryJavaCompiler.compile(className, sourceCode);
- *         Class fooClass = ByteClassLoader.load(className, byteCode);
- *     }
- * }
- * }
- * 
- */ -public class InMemoryJavaCompiler { - private static class MemoryJavaFileObject extends SimpleJavaFileObject { - private final String className; - private final CharSequence sourceCode; - private final ByteArrayOutputStream byteCode; - - public MemoryJavaFileObject(String className, CharSequence sourceCode) { - super(URI.create("string:///" + className.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE); - this.className = className; - this.sourceCode = sourceCode; - this.byteCode = new ByteArrayOutputStream(); - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return sourceCode; - } - - @Override - public OutputStream openOutputStream() throws IOException { - return byteCode; - } - - public byte[] getByteCode() { - return byteCode.toByteArray(); - } - - public String getClassName() { - return className; - } - } - - private static class FileManagerWrapper extends ForwardingJavaFileManager { - private static final Location PATCH_LOCATION = new Location() { - @Override - public String getName() { - return "patch module location"; - } - - @Override - public boolean isOutputLocation() { - return false; - } - }; - private final MemoryJavaFileObject file; - private final String moduleOverride; - - public FileManagerWrapper(MemoryJavaFileObject file, String moduleOverride) { - super(getCompiler().getStandardFileManager(null, null, null)); - this.file = file; - this.moduleOverride = moduleOverride; - } - - @Override - public JavaFileObject getJavaFileForOutput(Location location, String className, - Kind kind, FileObject sibling) - throws IOException { - if (!file.getClassName().equals(className)) { - throw new IOException("Expected class with name " + file.getClassName() + - ", but got " + className); - } - return file; - } - - @Override - public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException { - if (fo == file && moduleOverride != null) { - return PATCH_LOCATION; - } - return super.getLocationForModule(location, fo); - } - - @Override - public String inferModuleName(Location location) throws IOException { - if (location == PATCH_LOCATION) { - return moduleOverride; - } - return super.inferModuleName(location); - } - - @Override - public boolean hasLocation(Location location) { - return super.hasLocation(location) || location == StandardLocation.PATCH_MODULE_PATH; - } - - } - - /** - * Compiles the class with the given name and source code. - * - * @param className The name of the class - * @param sourceCode The source code for the class with name {@code className} - * @param options additional command line options - * @throws RuntimeException if the compilation did not succeed - * @return The resulting byte code from the compilation - */ - public static byte[] compile(String className, CharSequence sourceCode, String... options) { - MemoryJavaFileObject file = new MemoryJavaFileObject(className, sourceCode); - CompilationTask task = getCompilationTask(file, options); - - if(!task.call()) { - throw new RuntimeException("Could not compile " + className + " with source code " + sourceCode); - } - - return file.getByteCode(); - } - - private static JavaCompiler getCompiler() { - return ToolProvider.getSystemJavaCompiler(); - } - - private static CompilationTask getCompilationTask(MemoryJavaFileObject file, String... options) { - List opts = new ArrayList<>(); - String moduleOverride = null; - for (String opt : options) { - if (opt.startsWith("--patch-module=")) { - moduleOverride = opt.substring("--patch-module=".length()); - } else { - opts.add(opt); - } - } - return getCompiler().getTask(null, new FileManagerWrapper(file, moduleOverride), null, opts, null, Arrays.asList(file)); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/ModuleInfoMaker.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/ModuleInfoMaker.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/ModuleInfoMaker.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/compiler/ModuleInfoMaker.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.compiler; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -/** - * Utility class for creating test modules. - */ -public class ModuleInfoMaker { - private static final String MODULE_INFO_JAVA = "module-info.java"; - private static final Pattern MODULE_PATTERN = - Pattern.compile("module\\s+((?:\\w+\\.)*)"); - private static final Pattern PACKAGE_PATTERN = - Pattern.compile("package\\s+(((?:\\w+\\.)*)(?:\\w+))"); - private static final Pattern CLASS_PATTERN = - Pattern.compile("(?:public\\s+)?(?:class|enum|interface)\\s+(\\w+)"); - - private final Path dir; - - public ModuleInfoMaker(Path dir) { - this.dir = dir; - } - - /** - * Create java source files of the given module - */ - public void writeJavaFiles(String module, String moduleInfoJava, String... contents) - throws IOException - { - Path msrc = dir.resolve(module); - new JavaSource(moduleInfoJava).write(msrc); - for (String c : contents) { - new JavaSource(c).write(msrc); - } - } - - /** - * Compile the module to the given destination. - */ - public void compile(String module, Path dest, String... options) - throws IOException - { - Path msrc = dir.resolve(module); - String[] args = - Stream.concat(Arrays.stream(options), - Stream.of("--module-source-path", - dir.toString())).toArray(String[]::new); - if (!CompilerUtils.compile(msrc, dest, args)) { - throw new Error("Fail to compile " + module); - } - } - - static class JavaSource { - final String source; - JavaSource(String source) { - this.source = source; - } - - /** - * Writes the source code to a file in a specified directory. - * @param dir the directory - * @throws IOException if there is a problem writing the file - */ - public void write(Path dir) throws IOException { - Path file = dir.resolve(getJavaFileNameFromSource(source)); - Files.createDirectories(file.getParent()); - try (BufferedWriter out = Files.newBufferedWriter(file)) { - out.write(source.replace("\n", System.lineSeparator())); - } - } - - /** - * Extracts the Java file name from the class declaration. - * This method is intended for simple files and uses regular expressions, - * so comments matching the pattern can make the method fail. - */ - static String getJavaFileNameFromSource(String source) { - String packageName = null; - - Matcher matcher = MODULE_PATTERN.matcher(source); - if (matcher.find()) - return MODULE_INFO_JAVA; - - matcher = PACKAGE_PATTERN.matcher(source); - if (matcher.find()) - packageName = matcher.group(1).replace(".", "/"); - - matcher = CLASS_PATTERN.matcher(source); - if (matcher.find()) { - String className = matcher.group(1) + ".java"; - return (packageName == null) ? className : packageName + "/" + className; - } else if (packageName != null) { - return packageName + "/package-info.java"; - } else { - throw new Error("Could not extract the java class " + - "name from the provided source"); - } - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.cgroup; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import jdk.test.lib.Asserts; - - -// A simple CPU sets reader and parser -public class CPUSetsReader { - public static String PROC_SELF_STATUS_PATH = "/proc/self/status"; - - // Test the parser - public static void test() { - assertParse("0-7", "0,1,2,3,4,5,6,7"); - assertParse("1,3,6", "1,3,6"); - assertParse("0,2-4,6,10-11", "0,2,3,4,6,10,11"); - assertParse("0", "0"); - } - - - private static void assertParse(String cpuSet, String expectedResult) { - Asserts.assertEquals(listToString(parseCpuSet(cpuSet)), expectedResult); - } - - public static int getNumCpus() { - String path = "/proc/cpuinfo"; - try (Stream stream = Files.lines(Paths.get(path))) { - return (int) stream.filter(line -> line.startsWith("processor")).count(); - } catch (IOException e) { - return 0; - } - } - - - public static String readFromProcStatus(String setType) { - String path = PROC_SELF_STATUS_PATH; - Optional o = Optional.empty(); - - System.out.println("readFromProcStatus() entering for: " + setType); - - try (Stream stream = Files.lines(Paths.get(path))) { - o = stream - .filter(line -> line.contains(setType)) - .findFirst(); - } catch (IOException e) { - return null; - } - - if (!o.isPresent()) { - return null; // entry not found - } - - String[] parts = o.get().replaceAll("\\s", "").split(":"); - - // Should be 2 parts, before and after ":" - Asserts.assertEquals(parts.length, 2); - - String result = parts[1]; - System.out.println("readFromProcStatus() returning: " + result); - return result; - } - - - public static List parseCpuSet(String value) { - ArrayList result = new ArrayList(); - - try { - String[] commaSeparated = value.split(","); - - for (String item : commaSeparated) { - if (item.contains("-")) { - addRange(result, item); - } else { - result.add(Integer.parseInt(item)); - } - } - } catch (Exception e) { - System.err.println("Exception in getMaxCpuSets(): " + e); - return null; - } - - return result; - } - - private static void addRange(ArrayList list, String s) { - String[] range = s.split("-"); - if (range.length != 2) { - throw new RuntimeException("Range should only contain two items, but contains " - + range.length + " items"); - } - - int min = Integer.parseInt(range[0]); - int max = Integer.parseInt(range[1]); - - if (min >= max) { - String msg = String.format("min is greater or equals to max, min = %d, max = %d", - min, max); - throw new RuntimeException(msg); - } - - for (int i = min; i <= max; i++) { - list.add(i); - } - } - - - // Convert list of integers to string with comma-separated values - public static String listToString(List list) { - return listToString(list, Integer.MAX_VALUE); - } - - // Convert list of integers to a string with comma-separated values; - // include up to maxCount. - public static String listToString(List list, int maxCount) { - return list.stream() - .limit(maxCount) - .map(Object::toString) - .collect(Collectors.joining(",")); - } - - public static String numberToString(int num) { - return IntStream.range(0, num).boxed().map(Object::toString).collect(Collectors.joining(",")); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2020, Red Hat Inc. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.cgroup; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -interface CgroupMetricsTester { - - public static final double ERROR_MARGIN = 0.1; - public static final String EMPTY_STR = ""; - - public void testMemorySubsystem(); - public void testCpuAccounting(); - public void testCpuSchedulingMetrics(); - public void testCpuSets(); - public void testCpuConsumption() throws IOException, InterruptedException; - public void testMemoryUsage() throws Exception; - public void testMisc(); - - public static long convertStringToLong(String strval, long initialVal, long overflowRetval) { - long retval = initialVal; - if (strval == null) return retval; - - try { - retval = Long.parseLong(strval); - } catch (NumberFormatException e) { - // For some properties (e.g. memory.limit_in_bytes) we may overflow the range of signed long. - // In this case, return Long.MAX_VALUE - BigInteger b = new BigInteger(strval); - if (b.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { - return overflowRetval; - } - } - return retval; - } - - public static boolean compareWithErrorMargin(long oldVal, long newVal) { - return Math.abs(oldVal - newVal) <= Math.abs(oldVal * ERROR_MARGIN); - } - - public static boolean compareWithErrorMargin(double oldVal, double newVal) { - return Math.abs(oldVal - newVal) <= Math.abs(oldVal * ERROR_MARGIN); - } - - public static void fail(String controller, String metric, long oldVal, long testVal) { - throw new RuntimeException("Test failed for - " + controller + ":" - + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); - } - - public static void fail(String controller, String metric, String oldVal, String testVal) { - throw new RuntimeException("Test failed for - " + controller + ":" - + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); - } - - public static void fail(String controller, String metric, double oldVal, double testVal) { - throw new RuntimeException("Test failed for - " + controller + ":" - + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); - } - - public static void fail(String controller, String metric, boolean oldVal, boolean testVal) { - throw new RuntimeException("Test failed for - " + controller + ":" - + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); - } - - public static void warn(String controller, String metric, long oldVal, long testVal) { - System.err.println("Warning - " + controller + ":" + metric - + ", expected [" + oldVal + "], got [" + testVal + "]"); - } - - public static Integer[] convertCpuSetsToArray(String cpusstr) { - if (cpusstr == null || EMPTY_STR.equals(cpusstr)) { - return null; - } - // Parse range string in the format 1,2-6,7 - Integer[] cpuSets = Stream.of(cpusstr.split(",")).flatMap(a -> { - if (a.contains("-")) { - String[] range = a.split("-"); - return IntStream.rangeClosed(Integer.parseInt(range[0]), - Integer.parseInt(range[1])).boxed(); - } else { - return Stream.of(Integer.parseInt(a)); - } - }).toArray(Integer[]::new); - return cpuSets; - } - - public static Integer[] boxedArrayOrNull(int[] primitiveArray) { - if (primitiveArray == null) { - return null; - } - return Arrays.stream(primitiveArray).boxed().toArray(Integer[]::new); - } - - public static Integer[] sortAllowNull(Integer[] array) { - if (array == null) { - return null; - } - Arrays.sort(array); - return array; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2020, Red Hat Inc. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -package jdk.test.lib.containers.cgroup; - -import java.util.Objects; - -import jdk.internal.platform.Metrics; - -/** - * Cgroup version agnostic metrics tester - * - */ -public class MetricsTester { - - private static final String CGROUP_V1 = "cgroupv1"; - private static final String CGROUP_V2 = "cgroupv2"; - - private static CgroupMetricsTester createInstance(Metrics m) { - Objects.requireNonNull(m); - if (CGROUP_V1.equals(m.getProvider())) { - MetricsTesterCgroupV1 t = new MetricsTesterCgroupV1(); - t.setup(); - return t; - } else if (CGROUP_V2.equals(m.getProvider())) { - return new MetricsTesterCgroupV2(); - } else { - System.err.println("WARNING: Metrics provider, '" + m.getProvider() - + "' is unknown!"); - return null; - } - } - - public void testAll(Metrics m) throws Exception { - CgroupMetricsTester tester = createInstance(m); - tester.testCpuAccounting(); - tester.testCpuConsumption(); - tester.testCpuSchedulingMetrics(); - tester.testCpuSets(); - tester.testMemorySubsystem(); - tester.testMemoryUsage(); - tester.testMisc(); - } - - public static void main(String[] args) throws Exception { - Metrics m = Metrics.systemMetrics(); - // If cgroups is not configured, report success - if (m == null) { - System.out.println("TEST PASSED!!!"); - return; - } - - MetricsTester metricsTester = new MetricsTester(); - metricsTester.testAll(m); - System.out.println("TEST PASSED!!!"); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,579 +0,0 @@ -/* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.cgroup; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.LongStream; -import java.util.stream.Stream; - -import jdk.internal.platform.CgroupSubsystem; -import jdk.internal.platform.CgroupV1Metrics; -import jdk.internal.platform.Metrics; -import jdk.test.lib.Asserts; - -public class MetricsTesterCgroupV1 implements CgroupMetricsTester { - - // Aliased for readability - private static final long RETVAL_UNAVAILABLE = CgroupSubsystem.LONG_RETVAL_UNLIMITED; - private static long unlimited_minimum = 0x7FFFFFFFFF000000L; - long startSysVal; - long startUserVal; - long startUsage; - long startPerCpu[]; - - enum Controller { - MEMORY("memory"), - CPUSET("cpuset"), - CPU("cpu"), - CPUACCT("cpuacct"), - BLKIO("blkio"); - - private String value; - - Controller(String value) { - this.value = value; - } - - public String value() { - return value; - } - } - - private static final Set allowedSubSystems = - Stream.of(Controller.values()).map(Controller::value).collect(Collectors.toSet()); - - private static final Map subSystemPaths = new HashMap<>(); - - private static void setPath(String[] line) { - String cgroupPath = line[2]; - String[] subSystems = line[1].split(","); - - for (String subSystem : subSystems) { - if (allowedSubSystems.contains(subSystem)) { - String[] paths = subSystemPaths.get(subSystem); - String finalPath = ""; - String root = paths[0]; - String mountPoint = paths[1]; - if (root != null && cgroupPath != null) { - if (root.equals("/")) { - if (!cgroupPath.equals("/")) { - finalPath = mountPoint + cgroupPath; - } else { - finalPath = mountPoint; - } - } else { - if (root.equals(cgroupPath)) { - finalPath = mountPoint; - } else { - if (cgroupPath.startsWith(root)) { - if (cgroupPath.length() > root.length()) { - String cgroupSubstr = cgroupPath.substring(root.length()); - finalPath = mountPoint + cgroupSubstr; - } - } - } - } - } - subSystemPaths.put(subSystem, new String[]{finalPath, mountPoint}); - } - } - } - - private static void createSubsystems(String[] line) { - if (line.length < 5) return; - Path p = Paths.get(line[4]); - String subsystemName = p.getFileName().toString(); - if (subsystemName != null) { - for (String subSystem : subsystemName.split(",")) { - if (allowedSubSystems.contains(subSystem)) { - subSystemPaths.put(subSystem, new String[]{line[3], line[4]}); - } - } - } - } - - public void setup() { - Metrics metrics = Metrics.systemMetrics(); - // Initialize CPU usage metrics before we do any testing. - startSysVal = metrics.getCpuSystemUsage(); - startUserVal = metrics.getCpuUserUsage(); - startUsage = metrics.getCpuUsage(); - startPerCpu = metrics.getPerCpuUsage(); - - try { - Stream lines = Files.lines(Paths.get("/proc/self/mountinfo")); - lines.filter(line -> line.contains(" - cgroup cgroup ")) - .map(line -> line.split(" ")) - .forEach(MetricsTesterCgroupV1::createSubsystems); - lines.close(); - - lines = Files.lines(Paths.get("/proc/self/cgroup")); - lines.map(line -> line.split(":")) - .filter(line -> (line.length >= 3)) - .forEach(MetricsTesterCgroupV1::setPath); - lines.close(); - } catch (IOException e) { - } - } - - private static String getFileContents(Controller subSystem, String fileName) { - String fname = subSystemPaths.get(subSystem.value())[0] + File.separator + fileName; - try { - return new Scanner(new File(fname)).useDelimiter("\\Z").next(); - } catch (FileNotFoundException e) { - System.err.println("Unable to open : " + fname); - return null; - } - } - - private static long getLongValueFromFile(Controller subSystem, String fileName) { - String data = getFileContents(subSystem, fileName); - return (data == null || data.isEmpty()) ? RETVAL_UNAVAILABLE : convertStringToLong(data); - } - - private static long convertStringToLong(String strval) { - return CgroupMetricsTester.convertStringToLong(strval, RETVAL_UNAVAILABLE, Long.MAX_VALUE); - } - - private static long getLongValueFromFile(Controller subSystem, String metric, String subMetric) { - String stats = getFileContents(subSystem, metric); - String[] tokens = stats.split("[\\r\\n]+"); - for (int i = 0; i < tokens.length; i++) { - if (tokens[i].startsWith(subMetric)) { - String strval = tokens[i].split("\\s+")[1]; - return convertStringToLong(strval); - } - } - return RETVAL_UNAVAILABLE; - } - - private static double getDoubleValueFromFile(Controller subSystem, String fileName) { - String data = getFileContents(subSystem, fileName); - return data == null || data.isEmpty() ? RETVAL_UNAVAILABLE : Double.parseDouble(data); - } - - private static void fail(Controller system, String metric, long oldVal, long testVal) { - CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); - } - - private static void fail(Controller system, String metric, String oldVal, String testVal) { - CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); - } - - private static void fail(Controller system, String metric, double oldVal, double testVal) { - CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); - } - - private static void fail(Controller system, String metric, boolean oldVal, boolean testVal) { - CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); - } - - private static void warn(Controller system, String metric, long oldVal, long testVal) { - CgroupMetricsTester.warn(system.value, metric, oldVal, testVal); - } - - private Long[] boxedArrayOrNull(long[] primitiveArray) { - if (primitiveArray == null) { - return null; - } - return LongStream.of(primitiveArray).boxed().toArray(Long[]::new); - } - - public void testMemorySubsystem() { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - - // User Memory - long oldVal = metrics.getMemoryFailCount(); - long newVal = getLongValueFromFile(Controller.MEMORY, "memory.failcnt"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.failcnt", oldVal, newVal); - } - - oldVal = metrics.getMemoryLimit(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.limit_in_bytes"); - newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.limit_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getMemoryMaxUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.max_usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.max_usage_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getMemoryUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.usage_in_bytes", oldVal, newVal); - } - - // Kernel memory - oldVal = metrics.getKernelMemoryFailCount(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.failcnt"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.failcnt", oldVal, newVal); - } - - oldVal = metrics.getKernelMemoryLimit(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.limit_in_bytes"); - newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.limit_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getKernelMemoryMaxUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.max_usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.max_usage_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getKernelMemoryUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.usage_in_bytes", oldVal, newVal); - } - - //TCP Memory - oldVal = metrics.getTcpMemoryFailCount(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.failcnt"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.tcp.failcnt", oldVal, newVal); - } - - oldVal = metrics.getTcpMemoryLimit(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.limit_in_bytes"); - newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED: newVal; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.tcp.limit_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getTcpMemoryMaxUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.max_usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.tcp.max_usage_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getTcpMemoryUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.kmem.tcp.usage_in_bytes", oldVal, newVal); - } - - // Memory and Swap - // Skip swap tests if no swap is configured. - if (metrics.getMemoryAndSwapLimit() > metrics.getMemoryLimit()) { - oldVal = metrics.getMemoryAndSwapFailCount(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.failcnt"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.memsw.failcnt", oldVal, newVal); - } - - oldVal = metrics.getMemoryAndSwapLimit(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.limit_in_bytes"); - newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.memsw.limit_in_bytes", oldVal, newVal); - } - - oldVal = metrics.getMemoryAndSwapMaxUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.max_usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.memsw.max_usage_in_bytes", oldVal, newVal); - } - - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.memsw.usage_in_bytes", oldVal, newVal); - oldVal = metrics.getMemoryAndSwapUsage(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.usage_in_bytes"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.memsw.usage_in_bytes", oldVal, newVal); - } - } - } - - oldVal = metrics.getMemorySoftLimit(); - newVal = getLongValueFromFile(Controller.MEMORY, "memory.soft_limit_in_bytes"); - newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.MEMORY, "memory.soft_limit_in_bytes", oldVal, newVal); - } - - boolean oomKillEnabled = metrics.isMemoryOOMKillEnabled(); - boolean newOomKillEnabled = getLongValueFromFile(Controller.MEMORY, - "memory.oom_control", "oom_kill_disable") == 0L ? true : false; - if (oomKillEnabled != newOomKillEnabled) { - throw new RuntimeException("Test failed for - " + Controller.MEMORY.value + ":" - + "memory.oom_control:oom_kill_disable" + ", expected [" - + oomKillEnabled + "], got [" + newOomKillEnabled + "]"); - } - } - - public void testCpuAccounting() { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - long oldVal = metrics.getCpuUsage(); - long newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.usage"); - - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn(Controller.CPUACCT, "cpuacct.usage", oldVal, newVal); - } - - String newValsStr = getFileContents(Controller.CPUACCT, "cpuacct.usage_percpu"); - Long[] newVals = null; - if (newValsStr != null) { - newVals = Stream.of(newValsStr - .split("\\s+")) - .map(Long::parseLong) - .toArray(Long[]::new); - } - Long[] oldVals = boxedArrayOrNull(metrics.getPerCpuUsage()); - if (oldVals != null) { - for (int i = 0; i < oldVals.length; i++) { - if (!CgroupMetricsTester.compareWithErrorMargin(oldVals[i], newVals[i])) { - warn(Controller.CPUACCT, "cpuacct.usage_percpu", oldVals[i], newVals[i]); - } - } - } else { - Asserts.assertNull(newVals, Controller.CPUACCT.value() + "cpuacct.usage_percpu not both null"); - } - - oldVal = metrics.getCpuUserUsage(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.stat", "user"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn(Controller.CPUACCT, "cpuacct.usage - user", oldVal, newVal); - } - - oldVal = metrics.getCpuSystemUsage(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.stat", "system"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn(Controller.CPUACCT, "cpuacct.usage - system", oldVal, newVal); - } - } - - public void testCpuSchedulingMetrics() { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - long oldVal = metrics.getCpuPeriod(); - long newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.cfs_period_us"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.cfs_period_us", oldVal, newVal); - } - - oldVal = metrics.getCpuQuota(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.cfs_quota_us"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.cfs_quota_us", oldVal, newVal); - } - - oldVal = metrics.getCpuShares(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.shares"); - if (newVal == 0 || newVal == 1024) newVal = -1; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.shares", oldVal, newVal); - } - - oldVal = metrics.getCpuNumPeriods(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "nr_periods"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.stat - nr_periods", oldVal, newVal); - } - - oldVal = metrics.getCpuNumThrottled(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "nr_throttled"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.stat - nr_throttled", oldVal, newVal); - } - - oldVal = metrics.getCpuThrottledTime(); - newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "throttled_time"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.CPUACCT, "cpu.stat - throttled_time", oldVal, newVal); - } - } - - public void testCpuSets() { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - Integer[] oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetCpus()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - - String cpusstr = getFileContents(Controller.CPUSET, "cpuset.cpus"); - // Parse range string in the format 1,2-6,7 - Integer[] newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail(Controller.CPUSET, "cpuset.cpus", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - int [] cpuSets = metrics.getEffectiveCpuSetCpus(); - - oldVal = CgroupMetricsTester.boxedArrayOrNull(cpuSets); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getFileContents(Controller.CPUSET, "cpuset.effective_cpus"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail(Controller.CPUSET, "cpuset.effective_cpus", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetMems()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getFileContents(Controller.CPUSET, "cpuset.mems"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail(Controller.CPUSET, "cpuset.mems", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - int [] cpuSetMems = metrics.getEffectiveCpuSetMems(); - - oldVal = CgroupMetricsTester.boxedArrayOrNull(cpuSetMems); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getFileContents(Controller.CPUSET, "cpuset.effective_mems"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail(Controller.CPUSET, "cpuset.effective_mems", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - double oldValue = metrics.getCpuSetMemoryPressure(); - double newValue = getDoubleValueFromFile(Controller.CPUSET, "cpuset.memory_pressure"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldValue, newValue)) { - fail(Controller.CPUSET, "cpuset.memory_pressure", oldValue, newValue); - } - - boolean oldV = metrics.isCpuSetMemoryPressureEnabled(); - boolean newV = getLongValueFromFile(Controller.CPUSET, - "cpuset.memory_pressure_enabled") == 1 ? true : false; - if (oldV != newV) { - fail(Controller.CPUSET, "cpuset.memory_pressure_enabled", oldV, newV); - } - } - - private void testBlkIO() { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - long oldVal = metrics.getBlkIOServiceCount(); - long newVal = getLongValueFromFile(Controller.BLKIO, - "blkio.throttle.io_service_bytes", "Total"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.BLKIO, "blkio.throttle.io_service_bytes - Total", - oldVal, newVal); - } - - oldVal = metrics.getBlkIOServiced(); - newVal = getLongValueFromFile(Controller.BLKIO, "blkio.throttle.io_serviced", "Total"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail(Controller.BLKIO, "blkio.throttle.io_serviced - Total", oldVal, newVal); - } - } - - public void testCpuConsumption() throws IOException, InterruptedException { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - // make system call - long newSysVal = metrics.getCpuSystemUsage(); - long newUserVal = metrics.getCpuUserUsage(); - long newUsage = metrics.getCpuUsage(); - long[] newPerCpu = metrics.getPerCpuUsage(); - - // system/user CPU usage counters may be slowly increasing. - // allow for equal values for a pass - if (newSysVal < startSysVal) { - fail(Controller.CPU, "getCpuSystemUsage", newSysVal, startSysVal); - } - - // system/user CPU usage counters may be slowly increasing. - // allow for equal values for a pass - if (newUserVal < startUserVal) { - fail(Controller.CPU, "getCpuUserUsage", newUserVal, startUserVal); - } - - if (newUsage <= startUsage) { - fail(Controller.CPU, "getCpuUsage", newUsage, startUsage); - } - - if (startPerCpu != null) { - boolean success = false; - for (int i = 0; i < startPerCpu.length; i++) { - if (newPerCpu[i] > startPerCpu[i]) { - success = true; - break; - } - } - if (!success) { - fail(Controller.CPU, "getPerCpuUsage", Arrays.toString(newPerCpu), - Arrays.toString(startPerCpu)); - } - } else { - Asserts.assertNull(newPerCpu, Controller.CPU.value() + " getPerCpuUsage not both null"); - } - - } - - public void testMemoryUsage() throws Exception { - CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); - long memoryMaxUsage = metrics.getMemoryMaxUsage(); - long memoryUsage = metrics.getMemoryUsage(); - long newMemoryMaxUsage = 0, newMemoryUsage = 0; - - // allocate memory in a loop and check more than once for new values - // otherwise we might see seldom the effect of decreasing new memory values - // e.g. because the system could free up memory - byte[][] bytes = new byte[32][]; - for (int i = 0; i < 32; i++) { - bytes[i] = new byte[8*1024*1024]; - newMemoryUsage = metrics.getMemoryUsage(); - if (newMemoryUsage > memoryUsage) { - break; - } - } - newMemoryMaxUsage = metrics.getMemoryMaxUsage(); - - if (newMemoryMaxUsage < memoryMaxUsage) { - fail(Controller.MEMORY, "getMemoryMaxUsage", memoryMaxUsage, - newMemoryMaxUsage); - } - - if (newMemoryUsage < memoryUsage) { - fail(Controller.MEMORY, "getMemoryUsage", memoryUsage, newMemoryUsage); - } - } - - @Override - public void testMisc() { - testBlkIO(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,484 +0,0 @@ -/* - * Copyright (c) 2020, Red Hat Inc. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.cgroup; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import jdk.internal.platform.Metrics; - -public class MetricsTesterCgroupV2 implements CgroupMetricsTester { - - private static final long UNLIMITED = -1; - private static final long NOT_AVAILABLE = -1; - private static final UnifiedController UNIFIED = new UnifiedController(); - private static final String MAX = "max"; - private static final int PER_CPU_SHARES = 1024; - - private final long startSysVal; - private final long startUserVal; - private final long startUsage; - - static class UnifiedController { - - private static final String NAME = "unified"; - private final String path; - - UnifiedController() { - path = constructPath(); - } - - String getPath() { - return path; - } - - private static String constructPath() { - String mountPath; - String cgroupPath; - try { - List fifthTokens = Files.lines(Paths.get("/proc/self/mountinfo")) - .filter( l -> l.contains("- cgroup2")) - .map(UnifiedController::splitAndMountPath) - .collect(Collectors.toList()); - if (fifthTokens.size() != 1) { - throw new AssertionError("Expected only one cgroup2 line"); - } - mountPath = fifthTokens.get(0); - - List cgroupPaths = Files.lines(Paths.get("/proc/self/cgroup")) - .filter( l -> l.startsWith("0:")) - .map(UnifiedController::splitAndCgroupPath) - .collect(Collectors.toList()); - if (cgroupPaths.size() != 1) { - throw new AssertionError("Expected only one unified controller line"); - } - cgroupPath = cgroupPaths.get(0); - return Paths.get(mountPath, cgroupPath).toString(); - } catch (IOException e) { - return null; - } - } - - public static String splitAndMountPath(String input) { - String[] tokens = input.split("\\s+"); - return tokens[4]; // fifth entry is the mount path - } - - public static String splitAndCgroupPath(String input) { - String[] tokens = input.split(":"); - return tokens[2]; - } - } - - private long getLongLimitValueFromFile(String file) { - String strVal = getStringVal(file); - if (MAX.equals(strVal)) { - return UNLIMITED; - } - return convertStringToLong(strVal); - } - - public MetricsTesterCgroupV2() { - Metrics metrics = Metrics.systemMetrics(); - // Initialize CPU usage metrics before we do any testing. - startSysVal = metrics.getCpuSystemUsage(); - startUserVal = metrics.getCpuUserUsage(); - startUsage = metrics.getCpuUsage(); - } - - private long getLongValueFromFile(String file) { - return convertStringToLong(getStringVal(file)); - } - - private long getLongValueEntryFromFile(String file, String metric) { - Path filePath = Paths.get(UNIFIED.getPath(), file); - try { - String strVal = Files.lines(filePath).filter(l -> l.startsWith(metric)).collect(Collectors.joining()); - if (strVal.isEmpty()) { - // sometimes the match for the metric does not exist, e.g. cpu.stat's nr_periods iff the controller - // is not enabled - return UNLIMITED; - } - String[] keyValues = strVal.split("\\s+"); - String value = keyValues[1]; - return convertStringToLong(value); - } catch (IOException e) { - return NOT_AVAILABLE; - } - } - - private String getStringVal(String file) { - Path filePath = Paths.get(UNIFIED.getPath(), file); - try { - return Files.lines(filePath).collect(Collectors.joining()); - } catch (IOException e) { - return null; - } - } - - private void fail(String metric, long oldVal, long newVal) { - CgroupMetricsTester.fail(UnifiedController.NAME, metric, oldVal, newVal); - } - - private void fail(String metric, String oldVal, String newVal) { - CgroupMetricsTester.fail(UnifiedController.NAME, metric, oldVal, newVal); - } - - private void warn(String metric, long oldVal, long newVal) { - CgroupMetricsTester.warn(UnifiedController.NAME, metric, oldVal, newVal); - } - - private long getCpuShares(String file) { - long rawVal = getLongValueFromFile(file); - if (rawVal == NOT_AVAILABLE || rawVal == 100) { - return UNLIMITED; - } - int shares = (int)rawVal; - // CPU shares (OCI) value needs to get translated into - // a proper Cgroups v2 value. See: - // https://github.com/containers/crun/blob/master/crun.1.md#cpu-controller - // - // Use the inverse of (x == OCI value, y == cgroupsv2 value): - // ((262142 * y - 1)/9999) + 2 = x - // - int x = 262142 * shares - 1; - double frac = x/9999.0; - x = ((int)frac) + 2; - if ( x <= PER_CPU_SHARES ) { - return PER_CPU_SHARES; // mimic cgroups v1 - } - int f = x/PER_CPU_SHARES; - int lower_multiple = f * PER_CPU_SHARES; - int upper_multiple = (f + 1) * PER_CPU_SHARES; - int distance_lower = Math.max(lower_multiple, x) - Math.min(lower_multiple, x); - int distance_upper = Math.max(upper_multiple, x) - Math.min(upper_multiple, x); - x = distance_lower <= distance_upper ? lower_multiple : upper_multiple; - return x; - } - - private long getCpuMaxValueFromFile(String file) { - return getCpuValueFromFile(file, 0 /* $MAX index */); - } - - private long getCpuPeriodValueFromFile(String file) { - return getCpuValueFromFile(file, 1 /* $PERIOD index */); - } - - private long getCpuValueFromFile(String file, int index) { - String maxPeriod = getStringVal(file); - if (maxPeriod == null) { - return UNLIMITED; - } - String[] tokens = maxPeriod.split("\\s+"); - String val = tokens[index]; - if (MAX.equals(val)) { - return UNLIMITED; - } - return convertStringToLong(val); - } - - private long convertStringToLong(String val) { - return CgroupMetricsTester.convertStringToLong(val, NOT_AVAILABLE, UNLIMITED); - } - - private long nanosOrUnlimited(long micros) { - if (micros < 0) { - return UNLIMITED; - } - return TimeUnit.MICROSECONDS.toNanos(micros); - } - - @Override - public void testMemorySubsystem() { - Metrics metrics = Metrics.systemMetrics(); - - // User Memory - long oldVal = metrics.getMemoryFailCount(); - long newVal = getLongValueEntryFromFile("memory.events", "max"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.events[max]", oldVal, newVal); - } - - oldVal = metrics.getMemoryLimit(); - newVal = getLongLimitValueFromFile("memory.max"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.max", oldVal, newVal); - } - - oldVal = metrics.getMemoryUsage(); - newVal = getLongValueFromFile("memory.current"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.current", oldVal, newVal); - } - - oldVal = metrics.getTcpMemoryUsage(); - newVal = getLongValueEntryFromFile("memory.stat", "sock"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.stat[sock]", oldVal, newVal); - } - - long memAndSwapLimit = metrics.getMemoryAndSwapLimit(); - long memLimit = metrics.getMemoryLimit(); - // Only test swap memory limits if we can. On systems with swapaccount=0 - // we cannot, as swap limits are disabled. - if (memAndSwapLimit <= memLimit) { - System.out.println("No swap memory limits, test case(s) skipped"); - } else { - oldVal = memAndSwapLimit; - long valSwap = getLongLimitValueFromFile("memory.swap.max"); - long valMemory = getLongLimitValueFromFile("memory.max"); - if (valSwap == UNLIMITED) { - newVal = valSwap; - } else { - assert valMemory >= 0; - newVal = valSwap + valMemory; - } - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.swap.max", oldVal, newVal); - } - - oldVal = metrics.getMemoryAndSwapUsage(); - long swapUsage = getLongValueFromFile("memory.swap.current"); - long memUsage = getLongValueFromFile("memory.current"); - newVal = swapUsage + memUsage; - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.swap.current", oldVal, newVal); - } - } - - oldVal = metrics.getMemorySoftLimit(); - newVal = getLongLimitValueFromFile("memory.low"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("memory.low", oldVal, newVal); - } - - } - - @Override - public void testCpuAccounting() { - Metrics metrics = Metrics.systemMetrics(); - long oldVal = metrics.getCpuUsage(); - long newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "usage_usec")); - - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn("cpu.stat[usage_usec]", oldVal, newVal); - } - - oldVal = metrics.getCpuUserUsage(); - newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "user_usec")); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn("cpu.stat[user_usec]", oldVal, newVal); - } - - oldVal = metrics.getCpuSystemUsage(); - newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "system_usec")); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - warn("cpu.stat[system_usec]", oldVal, newVal); - } - } - - @Override - public void testCpuSchedulingMetrics() { - Metrics metrics = Metrics.systemMetrics(); - long oldVal = metrics.getCpuPeriod(); - long newVal = getCpuPeriodValueFromFile("cpu.max"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.max[$PERIOD]", oldVal, newVal); - } - - oldVal = metrics.getCpuQuota(); - newVal = getCpuMaxValueFromFile("cpu.max"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.max[$MAX]", oldVal, newVal); - } - - oldVal = metrics.getCpuShares(); - newVal = getCpuShares("cpu.weight"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.weight", oldVal, newVal); - } - - oldVal = metrics.getCpuNumPeriods(); - newVal = getLongValueEntryFromFile("cpu.stat", "nr_periods"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.stat[nr_periods]", oldVal, newVal); - } - - oldVal = metrics.getCpuNumThrottled(); - newVal = getLongValueEntryFromFile("cpu.stat", "nr_throttled"); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.stat[nr_throttled]", oldVal, newVal); - } - - oldVal = metrics.getCpuThrottledTime(); - newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "throttled_usec")); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("cpu.stat[throttled_usec]", oldVal, newVal); - } - } - - @Override - public void testCpuSets() { - Metrics metrics = Metrics.systemMetrics(); - Integer[] oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetCpus()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - - String cpusstr = getStringVal("cpuset.cpus"); - // Parse range string in the format 1,2-6,7 - Integer[] newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail("cpuset.cpus", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getEffectiveCpuSetCpus()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getStringVal("cpuset.cpus.effective"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail("cpuset.cpus.effective", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetMems()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getStringVal("cpuset.mems"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail("cpuset.mems", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - - oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getEffectiveCpuSetMems()); - oldVal = CgroupMetricsTester.sortAllowNull(oldVal); - cpusstr = getStringVal("cpuset.mems.effective"); - newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); - newVal = CgroupMetricsTester.sortAllowNull(newVal); - if (!Arrays.equals(oldVal, newVal)) { - fail("cpuset.mems.effective", Arrays.toString(oldVal), - Arrays.toString(newVal)); - } - } - - @Override - public void testCpuConsumption() { - Metrics metrics = Metrics.systemMetrics(); - // make system call - long newSysVal = metrics.getCpuSystemUsage(); - long newUserVal = metrics.getCpuUserUsage(); - long newUsage = metrics.getCpuUsage(); - - // system/user CPU usage counters may be slowly increasing. - // allow for equal values for a pass - if (newSysVal < startSysVal) { - fail("getCpuSystemUsage", newSysVal, startSysVal); - } - - // system/user CPU usage counters may be slowly increasing. - // allow for equal values for a pass - if (newUserVal < startUserVal) { - fail("getCpuUserUsage", newUserVal, startUserVal); - } - - if (newUsage <= startUsage) { - fail("getCpuUsage", newUsage, startUsage); - } - } - - @Override - public void testMemoryUsage() { - Metrics metrics = Metrics.systemMetrics(); - long memoryUsage = metrics.getMemoryUsage(); - long newMemoryUsage = 0; - - // allocate memory in a loop and check more than once for new values - // otherwise we might occasionally see the effect of decreasing new memory - // values. For example because the system could free up memory - byte[][] bytes = new byte[32][]; - for (int i = 0; i < 32; i++) { - bytes[i] = new byte[8*1024*1024]; - newMemoryUsage = metrics.getMemoryUsage(); - if (newMemoryUsage > memoryUsage) { - break; - } - } - - if (newMemoryUsage < memoryUsage) { - fail("getMemoryUsage", memoryUsage, newMemoryUsage); - } - } - - @Override - public void testMisc() { - testIOStat(); - } - - private void testIOStat() { - Metrics metrics = Metrics.systemMetrics(); - long oldVal = metrics.getBlkIOServiceCount(); - long newVal = getIoStatAccumulate(new String[] { "rios", "wios" }); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("io.stat->rios/wios: ", oldVal, newVal); - } - - oldVal = metrics.getBlkIOServiced(); - newVal = getIoStatAccumulate(new String[] { "rbytes", "wbytes" }); - if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { - fail("io.stat->rbytes/wbytes: ", oldVal, newVal); - } - } - - private long getIoStatAccumulate(String[] matchNames) { - try { - return Files.lines(Paths.get(UNIFIED.getPath(), "io.stat")) - .map(line -> { - long accumulator = 0; - String[] tokens = line.split("\\s+"); - for (String t: tokens) { - String[] keyVal = t.split("="); - if (keyVal.length != 2) { - continue; - } - for (String match: matchNames) { - if (match.equals(keyVal[0])) { - accumulator += Long.parseLong(keyVal[1]); - } - } - } - return accumulator; - }).collect(Collectors.summingLong(e -> e)); - } catch (IOException e) { - return NOT_AVAILABLE; - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/Common.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/Common.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/Common.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/Common.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.docker; - -/* - * Methods and definitions common to docker tests container in this directory - */ - -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Paths; -import jdk.test.lib.containers.docker.DockerRunOptions; -import jdk.test.lib.containers.docker.DockerTestUtils; -import jdk.test.lib.Utils; -import jdk.test.lib.process.OutputAnalyzer; - - -public class Common { - public static final String imageNameAndTag = "jdk-internal:test"; - - public static String imageName(String suffix) { - return imageNameAndTag + "-" + suffix; - } - - - public static void prepareWhiteBox() throws Exception { - Files.copy(Paths.get(new File("whitebox.jar").getAbsolutePath()), - Paths.get(Utils.TEST_CLASSES, "whitebox.jar")); - } - - - // create simple commonly used options - public static DockerRunOptions newOpts(String imageNameAndTag) { - return new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version") - .addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo"); - } - - - // create commonly used options with class to be launched inside container - public static DockerRunOptions newOpts(String imageNameAndTag, String testClass) { - DockerRunOptions opts = - new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", testClass); - opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/"); - opts.addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo"); - opts.addJavaOpts("-cp", "/test-classes/"); - return opts; - } - - - public static DockerRunOptions addWhiteBoxOpts(DockerRunOptions opts) { - opts.addJavaOpts("-Xbootclasspath/a:/test-classes/whitebox.jar", - "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI"); - return opts; - } - - - // most common type of run and checks - public static OutputAnalyzer run(DockerRunOptions opts) throws Exception { - return DockerTestUtils.dockerRunJava(opts) - .shouldHaveExitValue(0).shouldContain("Initializing Container Support"); - } - - - // log beginning of a test case - public static void logNewTestCase(String msg) { - System.out.println("========== NEW TEST CASE: " + msg); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.docker; - -import java.util.ArrayList; -import java.util.Collections; - - -// This class represents options for running java inside docker containers -// in test environment. -public class DockerRunOptions { - public String imageNameAndTag; - public ArrayList dockerOpts = new ArrayList(); - public String command; // normally a full path to java - public ArrayList javaOpts = new ArrayList(); - public String classToRun; // class or "-version" - public ArrayList classParams = new ArrayList(); - - public boolean tty = true; - public boolean removeContainerAfterUse = true; - public boolean appendTestJavaOptions = true; - public boolean retainChildStdout = false; - - /** - * Convenience constructor for most common use cases in testing. - * @param imageNameAndTag a string representing name and tag for the - * docker image to run, as "name:tag" - * @param javaCmd a java command to run (e.g. /jdk/bin/java) - * @param classToRun a class to run, or "-version" - * @param javaOpts java options to use - * - * @return Default docker run options - */ - public DockerRunOptions(String imageNameAndTag, String javaCmd, - String classToRun, String... javaOpts) { - this.imageNameAndTag = imageNameAndTag; - this.command = javaCmd; - this.classToRun = classToRun; - this.addJavaOpts(javaOpts); - } - - public DockerRunOptions addDockerOpts(String... opts) { - Collections.addAll(dockerOpts, opts); - return this; - } - - public DockerRunOptions addJavaOpts(String... opts) { - Collections.addAll(javaOpts, opts); - return this; - } - - public DockerRunOptions addClassOptions(String... opts) { - Collections.addAll(classParams,opts); - return this; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,302 +0,0 @@ -/* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.docker; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.FileVisitResult; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import jdk.test.lib.Container; -import jdk.test.lib.Utils; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - - -public class DockerTestUtils { - private static final String FS = File.separator; - private static boolean isDockerEngineAvailable = false; - private static boolean wasDockerEngineChecked = false; - - // Set this property to true to retain image after test. By default - // images are removed after test execution completes. - // Retaining the image can be useful for diagnostics and image inspection. - // E.g.: start image interactively: docker run -it . - public static final boolean RETAIN_IMAGE_AFTER_TEST = - Boolean.getBoolean("jdk.test.docker.retain.image"); - - // Path to a JDK under test. - // This may be useful when developing tests on non-Linux platforms. - public static final String JDK_UNDER_TEST = - System.getProperty("jdk.test.docker.jdk", Utils.TEST_JDK); - - - /** - * Optimized check of whether the docker engine is available in a given - * environment. Checks only once, then remembers the result in a singleton. - * - * @return true if docker engine is available - * @throws Exception - */ - public static boolean isDockerEngineAvailable() throws Exception { - if (wasDockerEngineChecked) - return isDockerEngineAvailable; - - isDockerEngineAvailable = isDockerEngineAvailableCheck(); - wasDockerEngineChecked = true; - return isDockerEngineAvailable; - } - - - /** - * Convenience method, will check if docker engine is available and usable; - * will print the appropriate message when not available. - * - * @return true if docker engine is available - * @throws Exception - */ - public static boolean canTestDocker() throws Exception { - if (isDockerEngineAvailable()) { - return true; - } else { - System.out.println("Docker engine is not available on this system"); - System.out.println("This test is SKIPPED"); - return false; - } - } - - - /** - * Simple check - is docker engine available, accessible and usable. - * Run basic docker command: 'docker ps' - list docker instances. - * If docker engine is available and accesible then true is returned - * and we can proceed with testing docker. - * - * @return true if docker engine is available and usable - * @throws Exception - */ - private static boolean isDockerEngineAvailableCheck() throws Exception { - try { - execute(Container.ENGINE_COMMAND, "ps") - .shouldHaveExitValue(0) - .shouldContain("CONTAINER") - .shouldContain("IMAGE"); - } catch (Exception e) { - return false; - } - return true; - } - - - /** - * Build a docker image that contains JDK under test. - * The jdk will be placed under the "/jdk/" folder inside the docker file system. - * - * @param imageName name of the image to be created, including version tag - * @param dockerfile name of the dockerfile residing in the test source; - * we check for a platform specific dockerfile as well - * and use this one in case it exists - * @param buildDirName name of the docker build/staging directory, which will - * be created in the jtreg's scratch folder - * @throws Exception - */ - public static void - buildJdkDockerImage(String imageName, String dockerfile, String buildDirName) - throws Exception { - - Path buildDir = Paths.get(".", buildDirName); - if (Files.exists(buildDir)) { - throw new RuntimeException("The docker build directory already exists: " + buildDir); - } - - Path jdkSrcDir = Paths.get(JDK_UNDER_TEST); - Path jdkDstDir = buildDir.resolve("jdk"); - - Files.createDirectories(jdkDstDir); - - // Copy JDK-under-test tree to the docker build directory. - // This step is required for building a docker image. - Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir)); - buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir); - } - - - /** - * Build a docker image based on given docker file and docker build directory. - * - * @param imageName name of the image to be created, including version tag - * @param dockerfile path to the Dockerfile to be used for building the docker - * image. The specified dockerfile will be copied to the docker build - * directory as 'Dockerfile' - * @param buildDir build directory; it should already contain all the content - * needed to build the docker image. - * @throws Exception - */ - public static void - buildDockerImage(String imageName, Path dockerfile, Path buildDir) throws Exception { - - generateDockerFile(buildDir.resolve("Dockerfile"), - DockerfileConfig.getBaseImageName(), - DockerfileConfig.getBaseImageVersion()); - - // Build the docker - execute(Container.ENGINE_COMMAND, "build", "--no-cache", "--tag", imageName, buildDir.toString()) - .shouldHaveExitValue(0); - } - - - /** - * Run Java inside the docker image with specified parameters and options. - * - * @param DockerRunOptions optins for running docker - * - * @return output of the run command - * @throws Exception - */ - public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception { - ArrayList cmd = new ArrayList<>(); - - cmd.add(Container.ENGINE_COMMAND); - cmd.add("run"); - if (opts.tty) - cmd.add("--tty=true"); - if (opts.removeContainerAfterUse) - cmd.add("--rm"); - - cmd.addAll(opts.dockerOpts); - cmd.add(opts.imageNameAndTag); - cmd.add(opts.command); - - cmd.addAll(opts.javaOpts); - if (opts.appendTestJavaOptions) { - Collections.addAll(cmd, Utils.getTestJavaOpts()); - } - - cmd.add(opts.classToRun); - cmd.addAll(opts.classParams); - - return execute(cmd); - } - - - /** - * Remove docker image - * - * @param DockerRunOptions optins for running docker - * @throws Exception - */ - public static void removeDockerImage(String imageNameAndTag) throws Exception { - execute(Container.ENGINE_COMMAND, "rmi", "--force", imageNameAndTag); - } - - - - /** - * Convenience method - express command as sequence of strings - * - * @param command to execute - * @return The output from the process - * @throws Exception - */ - public static OutputAnalyzer execute(List command) throws Exception { - return execute(command.toArray(new String[command.size()])); - } - - - /** - * Execute a specified command in a process, report diagnostic info. - * - * @param command to be executed - * @return The output from the process - * @throws Exception - */ - public static OutputAnalyzer execute(String... command) throws Exception { - - ProcessBuilder pb = new ProcessBuilder(command); - System.out.println("[COMMAND]\n" + Utils.getCommandLine(pb)); - - long started = System.currentTimeMillis(); - OutputAnalyzer output = new OutputAnalyzer(pb.start()); - - System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]"); - System.out.println("[STDERR]\n" + output.getStderr()); - System.out.println("[STDOUT]\n" + output.getStdout()); - - return output; - } - - - private static void generateDockerFile(Path dockerfile, String baseImage, - String baseImageVersion) throws Exception { - String template = - "FROM %s:%s\n" + - "COPY /jdk /jdk\n" + - "ENV JAVA_HOME=/jdk\n" + - "CMD [\"/bin/bash\"]\n"; - String dockerFileStr = String.format(template, baseImage, baseImageVersion); - Files.write(dockerfile, dockerFileStr.getBytes(StandardCharsets.UTF_8)); - } - - - private static class CopyFileVisitor extends SimpleFileVisitor { - private final Path src; - private final Path dst; - - public CopyFileVisitor(Path src, Path dst) { - this.src = src; - this.dst = dst; - } - - - @Override - public FileVisitResult preVisitDirectory(Path file, - BasicFileAttributes attrs) throws IOException { - Path dstDir = dst.resolve(src.relativize(file)); - if (!dstDir.toFile().exists()) { - Files.createDirectories(dstDir); - } - return FileVisitResult.CONTINUE; - } - - - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - if (!file.toFile().isFile()) { - return FileVisitResult.CONTINUE; - } - Path dstFile = dst.resolve(src.relativize(file)); - Files.copy(file, dstFile, StandardCopyOption.COPY_ATTRIBUTES); - return FileVisitResult.CONTINUE; - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.containers.docker; - -import jdk.test.lib.Platform; - -// Use the following properties to specify docker base image at test execution time: -// Image name: jdk.test.docker.image.name -// Image version: jdk.test.docker.image.version -// Usage: -// jtreg -Djdk.test.docker.image.name= -Djdk.test.docker.image.version= test/hotspot/jtreg/runtime/containers/docker/ -// E.g.: -// jtreg -Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest test/hotspot/jtreg/runtime/containers/docker/ -// Using make: -// make test TEST="test/hotspot/jtreg/runtime/containers/docker" JTREG="JAVA_OPTIONS=-Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest" -// Note: base image version should not be an empty string. Use "latest" to get the latest version. - -public class DockerfileConfig { - static String getBaseImageName() { - String name = System.getProperty("jdk.test.docker.image.name"); - if (name != null) { - System.out.println("DockerfileConfig: using custom image name: " + name); - return name; - } - - switch (Platform.getOsArch()) { - case "aarch64": - return "arm64v8/ubuntu"; - case "ppc64le": - return "ppc64le/ubuntu"; - case "s390x": - return "s390x/ubuntu"; - default: - return "oraclelinux"; - } - } - - static String getBaseImageVersion() { - String version = System.getProperty("jdk.test.docker.image.version"); - if (version != null) { - System.out.println("DockerfileConfig: using custom image version: " + version); - return version; - } - - switch (Platform.getOsArch()) { - case "aarch64": - case "ppc64le": - case "s390x": - return "latest"; - default: - return "7.6"; - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import jdk.test.lib.process.OutputAnalyzer; - -/** - * Abstract base class for Diagnostic Command executors - */ -public abstract class CommandExecutor { - - /** - * Execute a diagnostic command - * - * @param cmd The diagnostic command to execute - * @return an {@link jdk.testlibrary.OutputAnalyzer} encapsulating the output of the command - * @throws CommandExecutorException if there is an exception on the "calling side" while trying to execute the - * Diagnostic Command. Exceptions thrown on the remote side are available as textual representations in - * stderr, regardless of the specific executor used. - */ - public final OutputAnalyzer execute(String cmd) throws CommandExecutorException { - return execute(cmd, false); - } - - /** - * Execute a diagnostic command - * - * @param cmd The diagnostic command to execute - * @param silent Do not print the command output - * @return an {@link jdk.testlibrary.OutputAnalyzer} encapsulating the output of the command - * @throws CommandExecutorException if there is an exception on the "calling side" while trying to execute the - * Diagnostic Command. Exceptions thrown on the remote side are available as textual representations in - * stderr, regardless of the specific executor used. - */ - public final OutputAnalyzer execute(String cmd, boolean silent) throws CommandExecutorException { - if (!silent) { - System.out.printf("Running DCMD '%s' through '%s'%n", cmd, this.getClass().getSimpleName()); - } - - OutputAnalyzer oa = executeImpl(cmd); - - if (!silent) { - System.out.println("---------------- stdout ----------------"); - System.out.println(oa.getStdout()); - System.out.println("---------------- stderr ----------------"); - System.out.println(oa.getStderr()); - System.out.println("----------------------------------------"); - System.out.println(); - } - return oa; - } - - protected abstract OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -/** - * CommandExecutorException encapsulates exceptions thrown (on the "calling side") from the execution of Diagnostic - * Commands - */ -public class CommandExecutorException extends RuntimeException { - private static final long serialVersionUID = -7039597746579144280L; - - public CommandExecutorException(String message, Throwable e) { - super(message, e); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.List; - -/** - * Executes Diagnostic Commands on the target VM (specified by pid) using the jcmd tool and its ability to read - * Diagnostic Commands from a file. - */ -public class FileJcmdExecutor extends PidJcmdExecutor { - - /** - * Instantiates a new FileJcmdExecutor targeting the current VM - */ - public FileJcmdExecutor() { - super(); - } - - /** - * Instantiates a new FileJcmdExecutor targeting the VM indicated by the given pid - * - * @param target Pid of the target VM - */ - public FileJcmdExecutor(String target) { - super(target); - } - - protected List createCommandLine(String cmd) throws CommandExecutorException { - File cmdFile = createTempFile(); - writeCommandToTemporaryFile(cmd, cmdFile); - - return Arrays.asList(jcmdBinary, Long.toString(pid), - "-f", cmdFile.getAbsolutePath()); - } - - private void writeCommandToTemporaryFile(String cmd, File cmdFile) { - try (PrintWriter pw = new PrintWriter(cmdFile)) { - pw.println(cmd); - } catch (IOException e) { - String message = "Could not write to file: " + cmdFile.getAbsolutePath(); - throw new CommandExecutorException(message, e); - } - } - - private File createTempFile() { - try { - File cmdFile = File.createTempFile("input", "jcmd"); - cmdFile.deleteOnExit(); - return cmdFile; - } catch (IOException e) { - throw new CommandExecutorException("Could not create temporary file", e); - } - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import jdk.test.lib.process.OutputAnalyzer; - -import javax.management.*; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; - -import java.lang.management.ManagementFactory; - -import java.util.HashMap; - -/** - * Executes Diagnostic Commands on the target VM (specified by a host/port combination or a full JMX Service URL) using - * the JMX interface. If the target is not the current VM, the JMX Remote interface must be enabled beforehand. - */ -public class JMXExecutor extends CommandExecutor { - - private final MBeanServerConnection mbs; - - /** - * Instantiates a new JMXExecutor targeting the current VM - */ - public JMXExecutor() { - super(); - mbs = ManagementFactory.getPlatformMBeanServer(); - } - - /** - * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX - * Service URL - * - * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM - */ - public JMXExecutor(String target) { - String urlStr; - - if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) { - /* Matches "hostname:port" */ - urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target); - } else if (target.startsWith("service:")) { - urlStr = target; - } else { - throw new IllegalArgumentException("Could not recognize target string: " + target); - } - - try { - JMXServiceURL url = new JMXServiceURL(urlStr); - JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>()); - mbs = c.getMBeanServerConnection(); - } catch (IOException e) { - throw new CommandExecutorException("Could not initiate connection to target: " + target, e); - } - } - - protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException { - String stdout = ""; - String stderr = ""; - - String[] cmdParts = cmd.split(" ", 2); - String operation = commandToMethodName(cmdParts[0]); - Object[] dcmdArgs = produceArguments(cmdParts); - String[] signature = {String[].class.getName()}; - - ObjectName beanName = getMBeanName(); - - try { - stdout = (String) mbs.invoke(beanName, operation, dcmdArgs, signature); - } - - /* Failures on the "local" side, the one invoking the command. */ - catch (ReflectionException e) { - Throwable cause = e.getCause(); - if (cause instanceof NoSuchMethodException) { - /* We want JMXExecutor to match the behavior of the other CommandExecutors */ - String message = "Unknown diagnostic command: " + operation; - stderr = exceptionTraceAsString(new IllegalArgumentException(message, e)); - } else { - rethrowExecutorException(operation, dcmdArgs, e); - } - } - - /* Failures on the "local" side, the one invoking the command. */ - catch (InstanceNotFoundException | IOException e) { - rethrowExecutorException(operation, dcmdArgs, e); - } - - /* Failures on the remote side, the one executing the invoked command. */ - catch (MBeanException e) { - stdout = exceptionTraceAsString(e); - } - - return new OutputAnalyzer(stdout, stderr); - } - - private void rethrowExecutorException(String operation, Object[] dcmdArgs, - Exception e) throws CommandExecutorException { - String message = String.format("Could not invoke: %s %s", operation, - String.join(" ", (String[]) dcmdArgs[0])); - throw new CommandExecutorException(message, e); - } - - private ObjectName getMBeanName() throws CommandExecutorException { - String MBeanName = "com.sun.management:type=DiagnosticCommand"; - - try { - return new ObjectName(MBeanName); - } catch (MalformedObjectNameException e) { - String message = "MBean not found: " + MBeanName; - throw new CommandExecutorException(message, e); - } - } - - private Object[] produceArguments(String[] cmdParts) { - Object[] dcmdArgs = {new String[0]}; /* Default: No arguments */ - - if (cmdParts.length == 2) { - dcmdArgs[0] = cmdParts[1].split(" "); - } - return dcmdArgs; - } - - /** - * Convert from diagnostic command to MBean method name - * - * Examples: - * help --> help - * VM.version --> vmVersion - * VM.command_line --> vmCommandLine - */ - private static String commandToMethodName(String cmd) { - String operation = ""; - boolean up = false; /* First letter is to be lower case */ - - /* - * If a '.' or '_' is encountered it is not copied, - * instead the next character will be converted to upper case - */ - for (char c : cmd.toCharArray()) { - if (('.' == c) || ('_' == c)) { - up = true; - } else if (up) { - operation = operation.concat(Character.toString(c).toUpperCase()); - up = false; - } else { - operation = operation.concat(Character.toString(c).toLowerCase()); - } - } - - return operation; - } - - private static String exceptionTraceAsString(Throwable cause) { - StringWriter sw = new StringWriter(); - cause.printStackTrace(new PrintWriter(sw)); - return sw.toString(); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import jdk.test.lib.JDKToolFinder; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - -import java.util.List; - -/** - * Base class for Diagnostic Command Executors using the jcmd tool - */ -public abstract class JcmdExecutor extends CommandExecutor { - protected String jcmdBinary; - - protected abstract List createCommandLine(String cmd) throws CommandExecutorException; - - protected JcmdExecutor() { - jcmdBinary = JDKToolFinder.getJDKTool("jcmd"); - } - - protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException { - List commandLine = createCommandLine(cmd); - - try { - System.out.printf("Executing command '%s'%n", commandLine); - OutputAnalyzer output = ProcessTools.executeProcess(new ProcessBuilder(commandLine)); - System.out.printf("Command returned with exit code %d%n", output.getExitValue()); - - return output; - } catch (Exception e) { - String message = String.format("Caught exception while executing '%s'", commandLine); - throw new CommandExecutorException(message, e); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import java.util.Arrays; -import java.util.List; - -/** - * Executes Diagnostic Commands on the target VM (specified by main class) using the jcmd tool - */ -public class MainClassJcmdExecutor extends JcmdExecutor { - private final String mainClass; - - /** - * Instantiates a new MainClassJcmdExecutor targeting the current VM - */ - public MainClassJcmdExecutor() { - super(); - mainClass = System.getProperty("sun.java.command").split(" ")[0]; - } - - /** - * Instantiates a new MainClassJcmdExecutor targeting the VM indicated by the given main class - * - * @param target Main class of the target VM - */ - public MainClassJcmdExecutor(String target) { - super(); - mainClass = target; - } - - protected List createCommandLine(String cmd) throws CommandExecutorException { - return Arrays.asList(jcmdBinary, mainClass, cmd); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.dcmd; - -import jdk.test.lib.process.ProcessTools; - -import java.util.Arrays; -import java.util.List; - -/** - * Executes Diagnostic Commands on the target VM (specified by pid) using the jcmd tool - */ -public class PidJcmdExecutor extends JcmdExecutor { - protected final long pid; - - /** - * Instantiates a new PidJcmdExecutor targeting the current VM - */ - public PidJcmdExecutor() { - super(); - try { - pid = ProcessTools.getProcessId(); - } catch (Exception e) { - throw new CommandExecutorException("Could not determine own pid", e); - } - } - - /** - * Instantiates a new PidJcmdExecutor targeting the VM indicated by the given pid - * - * @param target Pid of the target VM - */ - public PidJcmdExecutor(String target) { - super(); - pid = Long.valueOf(target); - } - - protected List createCommandLine(String cmd) throws CommandExecutorException { - return Arrays.asList(jcmdBinary, Long.toString(pid), cmd); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/HprofParser.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/HprofParser.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/HprofParser.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/HprofParser.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.hprof; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; - -import jdk.test.lib.hprof.model.Snapshot; -import jdk.test.lib.hprof.parser.Reader; - -/** - * Helper class to parse a java heap dump file. - */ -public class HprofParser { - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.out.println("No arguments supplied"); - } - File dump = new File(args[0]); - if (!dump.exists() || !dump.isFile()) { - throw new RuntimeException("The dump file does not exist or not a file"); - } - parse(dump); - } - - /** - * @see #parse(File, boolean, boolean, boolean) - */ - public static File parse(File dump) throws Exception { - return parse(dump, false, true, true); - } - - /** - * @see #parse(File, boolean, boolean, boolean) - */ - public static File parseWithDebugInfo(File dump) throws Exception { - return parse(dump, true, true, true); - } - - /** - * Parse a java heap dump file - * - * @param dump Heap dump file to parse - * @param debug Turn on/off debug file parsing - * @param callStack Turn on/off tracking of object allocation call stack - * @param calculateRefs Turn on/off tracking object allocation call stack - * @throws Exception - * @return File containing output from the parser - */ - public static File parse(File dump, boolean debug, boolean callStack, boolean calculateRefs) throws Exception { - File out = new File("hprof." + System.currentTimeMillis() + ".out"); - if (out.exists()) { - out.delete(); - } - - PrintStream psSystemOut = System.out; - try (PrintStream psHprof = new PrintStream(new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath())))) { - System.setOut(psHprof); - - int debugLevel = debug ? 2 : 0; - try (Snapshot snapshot = Reader.readFile(dump.getAbsolutePath(), callStack, debugLevel)) { - System.out.println("Snapshot read, resolving..."); - snapshot.resolve(calculateRefs); - System.out.println("Snapshot resolved."); - } - } finally { - System.setOut(psSystemOut); - } - - return out; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/README openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/README --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -The jhat tool has been removed. jhat hprof file parser/validator -are needed for tests. The old packages for jhat were moved here: -com.sun.tools.hat.internal.model -> jdk.test.lib.hprof.model -com.sun.tools.hat.internal.parser -> jdk.test.lib.hprof.parser -com.sun.tools.hat.internal.util -> jdk.test.lib.hprof.util - -jhat was added in JDK 6 and its original implementation was from -java.net HAT project [1]. jhat is an experimental, unsupported tool. -There hasn't been much update to jhat tool in the JDK. In addition, -there are several better heap dump visualizer/analyzer emerged since -JDK 5/6 serviceability support. - -[1] https://java.net/projects/hat diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * A visitor for a JavaThing. @see JavaObject#visitReferencedObjects() - * - */ - - -abstract public class AbstractJavaHeapObjectVisitor - implements JavaHeapObjectVisitor { - abstract public void visit(JavaHeapObject other); - - /** - * Should the given field be excluded from the set of things visited? - * @return true if it should. - */ - public boolean exclude(JavaClass clazz, JavaField f) { - return false; - } - - /** - * @return true iff exclude might ever return true - */ - public boolean mightExclude() { - return false; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Primitive array type codes as defined by VM specification. - * - */ -public interface ArrayTypeCodes { - // Typecodes for array elements. - // Refer to newarray instruction in VM Spec. - public static final int T_BOOLEAN = 4; - public static final int T_CHAR = 5; - public static final int T_FLOAT = 6; - public static final int T_DOUBLE = 7; - public static final int T_BYTE = 8; - public static final int T_SHORT = 9; - public static final int T_INT = 10; - public static final int T_LONG = 11; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * This is used to represent values that the program doesn't really understand. - * This includes the null vlaue, and unresolved references (which shouldn't - * happen in well-formed hprof files). - * - * - * @author Bill Foote - */ - - - - -public class HackJavaValue extends JavaValue { - - private String value; - private long size; - - public HackJavaValue(String value, long size) { - this.value = value; - this.size = size; - } - - public String toString() { - return value; - } - - @Override - public long getSize() { - return size; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a boolean (i.e. a boolean field in an instance). - * - * @author Bill Foote - */ - - -public class JavaBoolean extends JavaValue { - - boolean value; - - public JavaBoolean(boolean value) { - this.value = value; - } - - public String toString() { - return "" + value; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaByte.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaByte.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaByte.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaByte.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents an byte (i.e. a byte field in an instance). - * - * @author Bill Foote - */ - - -public class JavaByte extends JavaValue { - - byte value; - - public JavaByte(byte value) { - this.value = value; - } - - public String toString() { - return "0x" + Integer.toString(((int) value) & 0xff, 16); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaChar.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaChar.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaChar.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaChar.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a char (i.e. a char field in an instance). - * - * @author Bill Foote - */ - - -public class JavaChar extends JavaValue { - - char value; - - public JavaChar(char value) { - this.value = value; - } - - public String toString() { - return "" + value; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaClass.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaClass.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaClass.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaClass.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,504 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.util.Vector; -import java.util.Enumeration; -import jdk.test.lib.hprof.util.CompositeEnumeration; -import jdk.test.lib.hprof.parser.ReadBuffer; - -/** - * - * @author Bill Foote - */ - - -public class JavaClass extends JavaHeapObject { - // my id - private long id; - // my name - private String name; - - // These are JavaObjectRef before resolve - private JavaThing superclass; - private JavaThing loader; - private JavaThing signers; - private JavaThing protectionDomain; - - // non-static fields - private JavaField[] fields; - // static fields - private JavaStatic[] statics; - - private static final JavaClass[] EMPTY_CLASS_ARRAY = new JavaClass[0]; - // my subclasses - private JavaClass[] subclasses = EMPTY_CLASS_ARRAY; - - // my instances - private Vector instances = new Vector(); - - // Who I belong to. Set on resolve. - private Snapshot mySnapshot; - - // Size of an instance, including VM overhead - private int instanceSize; - // Total number of fields including inherited ones - private int totalNumFields; - - - public JavaClass(long id, String name, long superclassId, long loaderId, - long signersId, long protDomainId, - JavaField[] fields, JavaStatic[] statics, - int instanceSize) { - this.id = id; - this.name = name; - this.superclass = new JavaObjectRef(superclassId); - this.loader = new JavaObjectRef(loaderId); - this.signers = new JavaObjectRef(signersId); - this.protectionDomain = new JavaObjectRef(protDomainId); - this.fields = fields; - this.statics = statics; - this.instanceSize = instanceSize; - } - - public JavaClass(String name, long superclassId, long loaderId, - long signersId, long protDomainId, - JavaField[] fields, JavaStatic[] statics, - int instanceSize) { - this(-1L, name, superclassId, loaderId, signersId, - protDomainId, fields, statics, instanceSize); - } - - public final JavaClass getClazz() { - return mySnapshot.getJavaLangClass(); - } - - public final int getIdentifierSize() { - return mySnapshot.getIdentifierSize(); - } - - public final int getMinimumObjectSize() { - return mySnapshot.getMinimumObjectSize(); - } - - public void resolve(Snapshot snapshot) { - if (mySnapshot != null) { - return; - } - mySnapshot = snapshot; - resolveSuperclass(snapshot); - if (superclass != null) { - ((JavaClass) superclass).addSubclass(this); - } - - loader = loader.dereference(snapshot, null); - signers = signers.dereference(snapshot, null); - protectionDomain = protectionDomain.dereference(snapshot, null); - - for (int i = 0; i < statics.length; i++) { - statics[i].resolve(this, snapshot); - } - snapshot.getJavaLangClass().addInstance(this); - super.resolve(snapshot); - return; - } - - /** - * Resolve our superclass. This might be called well before - * all instances are available (like when reading deferred - * instances in a 1.2 dump file :-) Calling this is sufficient - * to be able to explore this class' fields. - */ - public void resolveSuperclass(Snapshot snapshot) { - if (superclass == null) { - // We must be java.lang.Object, so we have no superclass. - } else { - totalNumFields = fields.length; - superclass = superclass.dereference(snapshot, null); - if (superclass == snapshot.getNullThing()) { - superclass = null; - } else { - try { - JavaClass sc = (JavaClass) superclass; - sc.resolveSuperclass(snapshot); - totalNumFields += sc.totalNumFields; - } catch (ClassCastException ex) { - System.out.println("Warning! Superclass of " + name + " is " + superclass); - superclass = null; - } - } - } - } - - public boolean isString() { - return mySnapshot.getJavaLangString() == this; - } - - public boolean isClassLoader() { - return mySnapshot.getJavaLangClassLoader().isAssignableFrom(this); - } - - /** - * Get a numbered field from this class - */ - public JavaField getField(int i) { - if (i < 0 || i >= fields.length) { - throw new Error("No field " + i + " for " + name); - } - return fields[i]; - } - - /** - * Get the total number of fields that are part of an instance of - * this class. That is, include superclasses. - */ - public int getNumFieldsForInstance() { - return totalNumFields; - } - - /** - * Get a numbered field from all the fields that are part of instance - * of this class. That is, include superclasses. - */ - public JavaField getFieldForInstance(int i) { - if (superclass != null) { - JavaClass sc = (JavaClass) superclass; - if (i < sc.totalNumFields) { - return sc.getFieldForInstance(i); - } - i -= sc.totalNumFields; - } - return getField(i); - } - - /** - * Get the class responsible for field i, where i is a field number that - * could be passed into getFieldForInstance. - * - * @see JavaClass.getFieldForInstance() - */ - public JavaClass getClassForField(int i) { - if (superclass != null) { - JavaClass sc = (JavaClass) superclass; - if (i < sc.totalNumFields) { - return sc.getClassForField(i); - } - } - return this; - } - - public long getId() { - return id; - } - - public String getName() { - return name; - } - - public boolean isArray() { - return name.indexOf('[') != -1; - } - - public Enumeration getInstances(boolean includeSubclasses) { - if (includeSubclasses) { - Enumeration res = instances.elements(); - for (int i = 0; i < subclasses.length; i++) { - res = new CompositeEnumeration(res, - subclasses[i].getInstances(true)); - } - return res; - } else { - return instances.elements(); - } - } - - /** - * @return a count of the instances of this class - */ - public int getInstancesCount(boolean includeSubclasses) { - int result = instances.size(); - if (includeSubclasses) { - for (int i = 0; i < subclasses.length; i++) { - result += subclasses[i].getInstancesCount(includeSubclasses); - } - } - return result; - } - - public JavaClass[] getSubclasses() { - return subclasses; - } - - /** - * This can only safely be called after resolve() - */ - public JavaClass getSuperclass() { - return (JavaClass) superclass; - } - - /** - * This can only safely be called after resolve() - */ - public JavaThing getLoader() { - return loader; - } - - /** - * This can only safely be called after resolve() - */ - public boolean isBootstrap() { - return loader == mySnapshot.getNullThing(); - } - - /** - * This can only safely be called after resolve() - */ - public JavaThing getSigners() { - return signers; - } - - /** - * This can only safely be called after resolve() - */ - public JavaThing getProtectionDomain() { - return protectionDomain; - } - - public JavaField[] getFields() { - return fields; - } - - /** - * Includes superclass fields - */ - public JavaField[] getFieldsForInstance() { - Vector v = new Vector(); - addFields(v); - JavaField[] result = new JavaField[v.size()]; - for (int i = 0; i < v.size(); i++) { - result[i] = v.elementAt(i); - } - return result; - } - - - public JavaStatic[] getStatics() { - return statics; - } - - // returns value of static field of given name - public JavaThing getStaticField(String name) { - for (int i = 0; i < statics.length; i++) { - JavaStatic s = statics[i]; - if (s.getField().getName().equals(name)) { - return s.getValue(); - } - } - return null; - } - - public String toString() { - return "class " + name; - } - - public int compareTo(JavaThing other) { - if (other instanceof JavaClass) { - return name.compareTo(((JavaClass) other).name); - } - return super.compareTo(other); - } - - - /** - * @return true iff a variable of type this is assignable from an instance - * of other - */ - public boolean isAssignableFrom(JavaClass other) { - if (this == other) { - return true; - } else if (other == null) { - return false; - } else { - return isAssignableFrom((JavaClass) other.superclass); - // Trivial tail recursion: I have faith in javac. - } - } - - /** - * Describe the reference that this thing has to target. This will only - * be called if target is in the array returned by getChildrenForRootset. - */ - public String describeReferenceTo(JavaThing target, Snapshot ss) { - for (int i = 0; i < statics.length; i++) { - JavaField f = statics[i].getField(); - if (f.hasId()) { - JavaThing other = statics[i].getValue(); - if (other == target) { - return "static field " + f.getName(); - } - } - } - return super.describeReferenceTo(target, ss); - } - - /** - * @return the size of an instance of this class. Gives 0 for an array - * type. - */ - public int getInstanceSize() { - return instanceSize + mySnapshot.getMinimumObjectSize(); - } - - - /** - * @return The size of all instances of this class. Correctly handles - * arrays. - */ - public long getTotalInstanceSize() { - int count = instances.size(); - if (count == 0 || !isArray()) { - return count * instanceSize; - } - - // array class and non-zero count, we have to - // get the size of each instance and sum it - long result = 0; - for (int i = 0; i < count; i++) { - JavaThing t = (JavaThing) instances.elementAt(i); - result += t.getSize(); - } - return result; - } - - /** - * @return the size of this object - */ - @Override - public long getSize() { - JavaClass cl = mySnapshot.getJavaLangClass(); - if (cl == null) { - return 0; - } else { - return cl.getInstanceSize(); - } - } - - public void visitReferencedObjects(JavaHeapObjectVisitor v) { - super.visitReferencedObjects(v); - JavaHeapObject sc = getSuperclass(); - if (sc != null) v.visit(getSuperclass()); - - JavaThing other; - other = getLoader(); - if (other instanceof JavaHeapObject) { - v.visit((JavaHeapObject)other); - } - other = getSigners(); - if (other instanceof JavaHeapObject) { - v.visit((JavaHeapObject)other); - } - other = getProtectionDomain(); - if (other instanceof JavaHeapObject) { - v.visit((JavaHeapObject)other); - } - - for (int i = 0; i < statics.length; i++) { - JavaField f = statics[i].getField(); - if (!v.exclude(this, f) && f.hasId()) { - other = statics[i].getValue(); - if (other instanceof JavaHeapObject) { - v.visit((JavaHeapObject) other); - } - } - } - } - - // package-privates below this point - final ReadBuffer getReadBuffer() { - return mySnapshot.getReadBuffer(); - } - - final void setNew(JavaHeapObject obj, boolean flag) { - mySnapshot.setNew(obj, flag); - } - - final boolean isNew(JavaHeapObject obj) { - return mySnapshot.isNew(obj); - } - - final StackTrace getSiteTrace(JavaHeapObject obj) { - return mySnapshot.getSiteTrace(obj); - } - - final void addReferenceFromRoot(Root root, JavaHeapObject obj) { - mySnapshot.addReferenceFromRoot(root, obj); - } - - final Root getRoot(JavaHeapObject obj) { - return mySnapshot.getRoot(obj); - } - - final Snapshot getSnapshot() { - return mySnapshot; - } - - void addInstance(JavaHeapObject inst) { - instances.addElement(inst); - } - - // Internals only below this point - private void addFields(Vector v) { - if (superclass != null) { - ((JavaClass) superclass).addFields(v); - } - for (int i = 0; i < fields.length; i++) { - v.addElement(fields[i]); - } - } - - private void addSubclassInstances(Vector v) { - for (int i = 0; i < subclasses.length; i++) { - subclasses[i].addSubclassInstances(v); - } - for (int i = 0; i < instances.size(); i++) { - v.addElement(instances.elementAt(i)); - } - } - - private void addSubclass(JavaClass sub) { - JavaClass newValue[] = new JavaClass[subclasses.length + 1]; - System.arraycopy(subclasses, 0, newValue, 0, subclasses.length); - newValue[subclasses.length] = sub; - subclasses = newValue; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a double (i.e. a double field in an instance). - * - * @author Bill Foote - */ - - -public class JavaDouble extends JavaValue { - - double value; - - public JavaDouble(double value) { - this.value = value; - } - - public String toString() { - return Double.toString(value); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaField.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaField.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaField.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaField.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - - -/** - * - * @author Bill Foote - */ - -public class JavaField { - - private String name; - private String signature; - - public JavaField(String name, String signature) { - this.name = name; - this.signature = signature; - } - - - /** - * @return true if the type of this field is something that has an ID. - * int fields, for exampe, don't. - */ - public boolean hasId() { - char ch = signature.charAt(0); - return (ch == '[' || ch == 'L'); - } - - public String getName() { - return name; - } - - public String getSignature() { - return signature; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a float (i.e. a float field in an instance). - * - * @author Bill Foote - */ - - -public class JavaFloat extends JavaValue { - - float value; - - public JavaFloat(float value) { - this.value = value; - } - - public String toString() { - return Float.toString(value); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,207 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import jdk.test.lib.hprof.util.Misc; - - -/** - * - * @author Bill Foote - */ - -/** - * Represents an object that's allocated out of the Java heap. It occupies - * memory in the VM, and is the sort of thing that in a JDK 1.1 VM had - * a handle. It can be a - * JavaClass, a JavaObjectArray, a JavaValueArray or a JavaObject. - */ - -public abstract class JavaHeapObject extends JavaThing { - - // - // Who we refer to. This is heavily optimized for space, because it's - // well worth trading a bit of speed for less swapping. - // referers and referersLen go through two phases: Building and - // resolved. When building, referers might have duplicates, but can - // be appended to. When resolved, referers has no duplicates or - // empty slots. - // - private JavaThing[] referers = null; - private int referersLen = 0; // -1 when resolved - - public abstract JavaClass getClazz(); - public abstract long getSize(); - public abstract long getId(); - - /** - * Do any initialization this thing needs after its data is read in. - * Subclasses that override this should call super.resolve(). - */ - public void resolve(Snapshot snapshot) { - StackTrace trace = snapshot.getSiteTrace(this); - if (trace != null) { - trace.resolve(snapshot); - } - } - - // - // Eliminate duplicates from referers, and size the array exactly. - // This sets us up to answer queries. See the comments around the - // referers data member for details. - // - void setupReferers() { - if (referersLen > 1) { - // Copy referers to map, screening out duplicates - Map map = new HashMap(); - for (int i = 0; i < referersLen; i++) { - if (map.get(referers[i]) == null) { - map.put(referers[i], referers[i]); - } - } - - // Now copy into the array - referers = new JavaThing[map.size()]; - map.keySet().toArray(referers); - } - referersLen = -1; - } - - - /** - * @return the id of this thing as hex string - */ - public String getIdString() { - return Misc.toHex(getId()); - } - - public String toString() { - return getClazz().getName() + "@" + getIdString(); - } - - /** - * @return the StackTrace of the point of allocation of this object, - * or null if unknown - */ - public StackTrace getAllocatedFrom() { - return getClazz().getSiteTrace(this); - } - - public boolean isNew() { - return getClazz().isNew(this); - } - - void setNew(boolean flag) { - getClazz().setNew(this, flag); - } - - /** - * Tell the visitor about all of the objects we refer to - */ - public void visitReferencedObjects(JavaHeapObjectVisitor v) { - v.visit(getClazz()); - } - - void addReferenceFrom(JavaHeapObject other) { - if (referersLen == 0) { - referers = new JavaThing[1]; // It was null - } else if (referersLen == referers.length) { - JavaThing[] copy = new JavaThing[(3 * (referersLen + 1)) / 2]; - System.arraycopy(referers, 0, copy, 0, referersLen); - referers = copy; - } - referers[referersLen++] = other; - // We just append to referers here. Measurements have shown that - // around 10% to 30% are duplicates, so it's better to just append - // blindly and screen out all the duplicates at once. - } - - void addReferenceFromRoot(Root r) { - getClazz().addReferenceFromRoot(r, this); - } - - /** - * If the rootset includes this object, return a Root describing one - * of the reasons why. - */ - public Root getRoot() { - return getClazz().getRoot(this); - } - - /** - * Tell who refers to us. - * - * @return an Enumeration of JavaHeapObject instances - */ - public Enumeration getReferers() { - if (referersLen != -1) { - throw new RuntimeException("not resolved: " + getIdString()); - } - return new Enumeration() { - - private int num = 0; - - public boolean hasMoreElements() { - return referers != null && num < referers.length; - } - - public JavaThing nextElement() { - return referers[num++]; - } - }; - } - - /** - * Given other, which the caller promises is in referers, determines if - * the reference is only a weak reference. - */ - public boolean refersOnlyWeaklyTo(Snapshot ss, JavaThing other) { - return false; - } - - /** - * Describe the reference that this thing has to target. This will only - * be called if target is in the array returned by getChildrenForRootset. - */ - public String describeReferenceTo(JavaThing target, Snapshot ss) { - return "??"; - } - - public boolean isHeapAllocated() { - return true; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * A visitor for a JavaThing. @see JavaObject#visitReferencedObjects() - * - * @author Bill Foote - */ - - -public interface JavaHeapObjectVisitor { - public void visit(JavaHeapObject other); - - /** - * Should the given field be excluded from the set of things visited? - * @return true if it should. - */ - public boolean exclude(JavaClass clazz, JavaField f); - - /** - * @return true iff exclude might ever return true - */ - public boolean mightExclude(); -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaInt.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaInt.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaInt.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaInt.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents an integer (i.e. an int field in an instance). - * - * @author Bill Foote - */ - - -public class JavaInt extends JavaValue { - - int value; - - public JavaInt(int value) { - this.value = value; - } - - public String toString() { - return "" + value; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,168 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.io.IOException; -import jdk.test.lib.hprof.parser.ReadBuffer; - -/* - * Base class for lazily read Java heap objects. - */ -public abstract class JavaLazyReadObject extends JavaHeapObject { - - // file offset from which this object data starts - private final long offset; - - protected JavaLazyReadObject(long offset) { - this.offset = offset; - } - - @Override - public final long getSize() { - return getValueLength() + getClazz().getMinimumObjectSize(); - } - - protected final long getOffset() { - return offset; - } - - protected ReadBuffer buf() { - return getClazz().getReadBuffer(); - } - - protected int idSize() { - return getClazz().getIdentifierSize(); - } - - // return the length of the data for this object - protected final long getValueLength() { - try { - return readValueLength(); - } catch (IOException exp) { - System.err.println("lazy read failed at offset " + offset); - exp.printStackTrace(); - return 0; - } - } - - // get this object's content as byte array - protected final JavaThing[] getValue() { - try { - return readValue(); - } catch (IOException exp) { - System.err.println("lazy read failed at offset " + offset); - exp.printStackTrace(); - return Snapshot.EMPTY_JAVATHING_ARRAY; - } - } - - // get ID of this object - public final long getId() { - try { - if (idSize() == 4) { - return ((long)buf().getInt(offset)) & Snapshot.SMALL_ID_MASK; - } else { - return buf().getLong(offset); - } - } catch (IOException exp) { - System.err.println("lazy read failed at offset " + offset); - exp.printStackTrace(); - return -1; - } - } - - protected abstract long readValueLength() throws IOException; - protected abstract JavaThing[] readValue() throws IOException; - - // make Integer or Long for given object ID - protected static Number makeId(long id) { - if ((id & ~Snapshot.SMALL_ID_MASK) == 0) { - return (int)id; - } else { - return id; - } - } - - // get ID as long value from Number - protected static long getIdValue(Number num) { - long id = num.longValue(); - if (num instanceof Integer) { - id &= Snapshot.SMALL_ID_MASK; - } - return id; - } - - // read object ID from given index from given byte array - protected final long objectIdAt(long offset) throws IOException { - if (idSize() == 4) { - return ((long)intAt(offset)) & Snapshot.SMALL_ID_MASK; - } else { - return longAt(offset); - } - } - - // utility methods to read primitive types from byte array - protected byte byteAt(long offset) throws IOException { - return buf().getByte(offset); - } - - protected boolean booleanAt(long offset) throws IOException { - return byteAt(offset) == 0 ? false : true; - } - - protected char charAt(long offset) throws IOException { - return buf().getChar(offset); - } - - protected short shortAt(long offset) throws IOException { - return buf().getShort(offset); - } - - protected int intAt(long offset) throws IOException { - return buf().getInt(offset); - } - - protected long longAt(long offset) throws IOException { - return buf().getLong(offset); - } - - protected float floatAt(long offset) throws IOException { - int val = intAt(offset); - return Float.intBitsToFloat(val); - } - - protected double doubleAt(long offset) throws IOException { - long val = longAt(offset); - return Double.longBitsToDouble(val); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLong.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLong.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLong.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaLong.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a long (i.e. a long field in an instance). - * - * @author Bill Foote - */ - - -public class JavaLong extends JavaValue { - - long value; - - public JavaLong(long value) { - this.value = value; - } - - public String toString() { - return Long.toString(value); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObject.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObject.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObject.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObject.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,333 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.io.IOException; -import jdk.test.lib.hprof.parser.ReadBuffer; - -/** - * Represents Java instance - * - * @author Bill Foote - */ -public class JavaObject extends JavaLazyReadObject { - - private Object clazz; // Number before resolve - // JavaClass after resolve - /** - * Construct a new JavaObject. - * - * @param classID id of the class object - * @param offset The offset of field data - */ - public JavaObject(long classID, long offset) { - super(offset); - this.clazz = makeId(classID); - } - - public void resolve(Snapshot snapshot) { - if (clazz instanceof JavaClass) { - return; - } - if (clazz instanceof Number) { - long classID = getIdValue((Number)clazz); - clazz = snapshot.findThing(classID); - if (! (clazz instanceof JavaClass)) { - warn("Class " + Long.toHexString(classID) + " not found, " + - "adding fake class!"); - int length; - ReadBuffer buf = snapshot.getReadBuffer(); - int idSize = snapshot.getIdentifierSize(); - long lenOffset = getOffset() + 2*idSize + 4; - try { - length = buf.getInt(lenOffset); - } catch (IOException exp) { - throw new RuntimeException(exp); - } - clazz = snapshot.addFakeInstanceClass(classID, length); - } - } else { - throw new InternalError("should not reach here"); - } - - JavaClass cl = (JavaClass) clazz; - cl.resolve(snapshot); - - // while resolving, parse fields in verbose mode. - // but, getFields calls parseFields in non-verbose mode - // to avoid printing warnings repeatedly. - parseFields(true); - - cl.addInstance(this); - super.resolve(snapshot); - } - - /** - * Are we the same type as other? We are iff our clazz is the - * same type as other's. - */ - public boolean isSameTypeAs(JavaThing other) { - if (!(other instanceof JavaObject)) { - return false; - } - JavaObject oo = (JavaObject) other; - return getClazz().equals(oo.getClazz()); - } - - /** - * Return our JavaClass object. This may only be called after resolve. - */ - public JavaClass getClazz() { - return (JavaClass) clazz; - } - - public JavaThing[] getFields() { - // pass false to verbose mode so that dereference - // warnings are not printed. - return parseFields(false); - } - - // returns the value of field of given name - public JavaThing getField(String name) { - JavaThing[] flds = getFields(); - JavaField[] instFields = getClazz().getFieldsForInstance(); - for (int i = 0; i < instFields.length; i++) { - if (instFields[i].getName().equals(name)) { - return flds[i]; - } - } - return null; - } - - public int compareTo(JavaThing other) { - if (other instanceof JavaObject) { - JavaObject oo = (JavaObject) other; - return getClazz().getName().compareTo(oo.getClazz().getName()); - } - return super.compareTo(other); - } - - public void visitReferencedObjects(JavaHeapObjectVisitor v) { - super.visitReferencedObjects(v); - JavaThing[] flds = getFields(); - for (int i = 0; i < flds.length; i++) { - if (flds[i] != null) { - if (v.mightExclude() - && v.exclude(getClazz().getClassForField(i), - getClazz().getFieldForInstance(i))) - { - // skip it - } else if (flds[i] instanceof JavaHeapObject) { - v.visit((JavaHeapObject) flds[i]); - } - } - } - } - - public boolean refersOnlyWeaklyTo(Snapshot ss, JavaThing other) { - if (ss.getWeakReferenceClass() != null) { - final int referentFieldIndex = ss.getReferentFieldIndex(); - if (ss.getWeakReferenceClass().isAssignableFrom(getClazz())) { - // - // REMIND: This introduces a dependency on the JDK - // implementation that is undesirable. - JavaThing[] flds = getFields(); - for (int i = 0; i < flds.length; i++) { - if (i != referentFieldIndex && flds[i] == other) { - return false; - } - } - return true; - } - } - return false; - } - - /** - * Describe the reference that this thing has to target. This will only - * be called if target is in the array returned by getChildrenForRootset. - */ - public String describeReferenceTo(JavaThing target, Snapshot ss) { - JavaThing[] flds = getFields(); - for (int i = 0; i < flds.length; i++) { - if (flds[i] == target) { - JavaField f = getClazz().getFieldForInstance(i); - return "field " + f.getName(); - } - } - return super.describeReferenceTo(target, ss); - } - - public String toString() { - if (getClazz().isString()) { - JavaThing value = getField("value"); - if (value instanceof JavaValueArray) { - return ((JavaValueArray)value).valueString(); - } else { - return "null"; - } - } else { - return super.toString(); - } - } - - // Internals only below this point - - /* - * Java instance record (HPROF_GC_INSTANCE_DUMP) looks as below: - * - * object ID - * stack trace serial number (int) - * class ID - * data length (int) - * byte[length] - */ - @Override - protected final long readValueLength() throws IOException { - long lengthOffset = getOffset() + 2 * idSize() + 4; - return buf().getInt(lengthOffset); - } - - @Override - protected final JavaThing[] readValue() throws IOException { - return parseFields(false); - } - - private long dataStartOffset() { - return getOffset() + idSize() + 4 + idSize() + 4; - } - - private JavaThing[] parseFields(boolean verbose) { - JavaClass cl = getClazz(); - int target = cl.getNumFieldsForInstance(); - JavaField[] fields = cl.getFields(); - JavaThing[] fieldValues = new JavaThing[target]; - Snapshot snapshot = cl.getSnapshot(); - int fieldNo = 0; - // In the dump file, the fields are stored in this order: - // fields of most derived class (immediate class) are stored - // first and then the super class and so on. In this object, - // fields are stored in the reverse ("natural") order. i.e., - // fields of most super class are stored first. - - // target variable is used to compensate for the fact that - // the dump file starts field values from the leaf working - // upwards in the inheritance hierarchy, whereas JavaObject - // starts with the top of the inheritance hierarchy and works down. - target -= fields.length; - JavaClass currClass = cl; - long offset = dataStartOffset(); - for (int i = 0; i < fieldValues.length; i++, fieldNo++) { - while (fieldNo >= fields.length) { - currClass = currClass.getSuperclass(); - fields = currClass.getFields(); - fieldNo = 0; - target -= fields.length; - } - JavaField f = fields[fieldNo]; - char sig = f.getSignature().charAt(0); - try { - switch (sig) { - case 'L': - case '[': { - long id = objectIdAt(offset); - offset += idSize(); - JavaObjectRef ref = new JavaObjectRef(id); - fieldValues[target+fieldNo] = ref.dereference(snapshot, f, verbose); - break; - } - case 'Z': { - byte value = byteAt(offset); - offset++; - fieldValues[target+fieldNo] = new JavaBoolean(value != 0); - break; - } - case 'B': { - byte value = byteAt(offset); - offset++; - fieldValues[target+fieldNo] = new JavaByte(value); - break; - } - case 'S': { - short value = shortAt(offset); - offset += 2; - fieldValues[target+fieldNo] = new JavaShort(value); - break; - } - case 'C': { - char value = charAt(offset); - offset += 2; - fieldValues[target+fieldNo] = new JavaChar(value); - break; - } - case 'I': { - int value = intAt(offset); - offset += 4; - fieldValues[target+fieldNo] = new JavaInt(value); - break; - } - case 'J': { - long value = longAt(offset); - offset += 8; - fieldValues[target+fieldNo] = new JavaLong(value); - break; - } - case 'F': { - float value = floatAt(offset); - offset += 4; - fieldValues[target+fieldNo] = new JavaFloat(value); - break; - } - case 'D': { - double value = doubleAt(offset); - offset += 8; - fieldValues[target+fieldNo] = new JavaDouble(value); - break; - } - default: - throw new RuntimeException("invalid signature: " + sig); - - } - } catch (IOException exp) { - System.err.println("lazy read failed at offset " + offset); - exp.printStackTrace(); - return Snapshot.EMPTY_JAVATHING_ARRAY; - } - } - return fieldValues; - } - - private void warn(String msg) { - System.out.println("WARNING: " + msg); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.io.IOException; -import jdk.test.lib.hprof.parser.ReadBuffer; - -/** - * @author Bill Foote - */ -public class JavaObjectArray extends JavaLazyReadObject { - - private Object clazz; // Long before resolve, the class after resolve - - public JavaObjectArray(long classID, long offset) { - super(offset); - this.clazz = makeId(classID); - } - - public JavaClass getClazz() { - return (JavaClass) clazz; - } - - public void resolve(Snapshot snapshot) { - if (clazz instanceof JavaClass) { - return; - } - long classID = getIdValue((Number)clazz); - if (snapshot.isNewStyleArrayClass()) { - // Modern heap dumps do this - JavaThing t = snapshot.findThing(classID); - if (t instanceof JavaClass) { - clazz = (JavaClass) t; - } - } - if (!(clazz instanceof JavaClass)) { - JavaThing t = snapshot.findThing(classID); - if (t != null && t instanceof JavaClass) { - JavaClass el = (JavaClass) t; - String nm = el.getName(); - if (!nm.startsWith("[")) { - nm = "L" + el.getName() + ";"; - } - clazz = snapshot.getArrayClass(nm); - } - } - - if (!(clazz instanceof JavaClass)) { - clazz = snapshot.getOtherArrayType(); - } - ((JavaClass)clazz).addInstance(this); - super.resolve(snapshot); - } - - public JavaThing[] getValues() { - return getElements(); - } - - public JavaThing[] getElements() { - return getValue(); - } - - public int compareTo(JavaThing other) { - if (other instanceof JavaObjectArray) { - return 0; - } - return super.compareTo(other); - } - - public int getLength() { - return (int)(getValueLength() / idSize()); - } - - public void visitReferencedObjects(JavaHeapObjectVisitor v) { - super.visitReferencedObjects(v); - JavaThing[] elements = getElements(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] != null && elements[i] instanceof JavaHeapObject) { - v.visit((JavaHeapObject) elements[i]); - } - } - } - - /** - * Describe the reference that this thing has to target. This will only - * be called if target is in the array returned by getChildrenForRootset. - */ - public String describeReferenceTo(JavaThing target, Snapshot ss) { - JavaThing[] elements = getElements(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] == target) { - return "Element " + i + " of " + this; - } - } - return super.describeReferenceTo(target, ss); - } - - /* - * Java object array record (HPROF_GC_OBJ_ARRAY_DUMP) - * looks as below: - * - * object ID - * stack trace serial number (int) - * array length (int) - * array class ID - * array element IDs - */ - @Override - protected final long readValueLength() throws IOException { - long offset = getOffset() + idSize() + 4; - // length of the array in elements - long len = buf().getInt(offset); - // byte length of array - return len * idSize(); - } - - private long dataStartOffset() { - return getOffset() + idSize() + 4 + 4 + idSize(); - } - - @Override - protected final JavaThing[] readValue() throws IOException { - Snapshot snapshot = getClazz().getSnapshot(); - int len = getLength(); - long offset = dataStartOffset(); - - JavaThing[] res = new JavaThing[len]; - for (int i = 0; i < len; i++) { - long id = objectIdAt(offset); - res[i] = snapshot.findThing(id); - offset += idSize(); - } - return res; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import jdk.test.lib.hprof.util.Misc; - -/** - * A forward reference to an object. This is an intermediate representation - * for a JavaThing, when we have the thing's ID, but we might not have read - * the thing yet. - * - * @author Bill Foote - */ -public class JavaObjectRef extends JavaThing { - private long id; - - public JavaObjectRef(long id) { - this.id = id; - } - - public long getId() { - return id; - } - - public boolean isHeapAllocated() { - return true; - } - - public JavaThing dereference(Snapshot snapshot, JavaField field) { - return dereference(snapshot, field, true); - } - - public JavaThing dereference(Snapshot snapshot, JavaField field, boolean verbose) { - if (field != null && !field.hasId()) { - // If this happens, we must be a field that represents an int. - // (This only happens with .bod-style files) - return new JavaLong(id); - } - if (id == 0) { - return snapshot.getNullThing(); - } - JavaThing result = snapshot.findThing(id); - if (result == null) { - if (!snapshot.getUnresolvedObjectsOK() && verbose) { - String msg = "WARNING: Failed to resolve object id " - + Misc.toHex(id); - if (field != null) { - msg += " for field " + field.getName() - + " (signature " + field.getSignature() + ")"; - } - System.out.println(msg); - // Thread.dumpStack(); - } - result = new HackJavaValue("Unresolved object " - + Misc.toHex(id), 0); - } - return result; - } - - @Override - public long getSize() { - return 0; - } - - public String toString() { - return "Unresolved object " + Misc.toHex(id); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaShort.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaShort.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaShort.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaShort.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a short (i.e. a short field in an instance). - * - * @author Bill Foote - */ - - -public class JavaShort extends JavaValue { - - short value; - - public JavaShort(short value) { - this.value = value; - } - - public String toString() { - return "" + value; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * - * @author Bill Foote - */ - -/** - * Represents the value of a static field of a JavaClass - */ - -public class JavaStatic { - - private JavaField field; - private JavaThing value; - - public JavaStatic(JavaField field, JavaThing value) { - this.field = field; - this.value = value; - } - - public void resolve(JavaClass clazz, Snapshot snapshot) { - long id = -1; - if (value instanceof JavaObjectRef) { - id = ((JavaObjectRef)value).getId(); - } - value = value.dereference(snapshot, field); - if (value.isHeapAllocated() && - clazz.getLoader() == snapshot.getNullThing()) { - // static fields are only roots if they are in classes - // loaded by the root classloader. - JavaHeapObject ho = (JavaHeapObject) value; - String s = "Static reference from " + clazz.getName() - + "." + field.getName(); - snapshot.addRoot(new Root(id, clazz.getId(), - Root.JAVA_STATIC, s)); - } - } - - public JavaField getField() { - return field; - } - - public JavaThing getValue() { - return value; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaThing.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaThing.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaThing.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaThing.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.util.Enumeration; -import java.util.Hashtable; - - -/** - * - * @author Bill Foote - */ - - -/** - * Represents a java "Thing". A thing is anything that can be the value of - * a field. This includes JavaHeapObject, JavaObjectRef, and JavaValue. - */ - -public abstract class JavaThing { - - protected JavaThing() { - } - - /** - * If this is a forward reference, figure out what it really - * refers to. - * - * @param snapshot The snapshot this is for - * @param field The field this thing represents. If null, it is - * assumed this thing is an object (and never a value). - */ - public JavaThing dereference(Snapshot shapshot, JavaField field) { - return this; - } - - - /** - * Are we the same type as other? - * - * @see JavaObject.isSameTypeAs() - */ - public boolean isSameTypeAs(JavaThing other) { - return getClass() == other.getClass(); - } - /** - * @return true iff this represents a heap-allocated object - */ - abstract public boolean isHeapAllocated(); - - /** - * @return the size of this object, in bytes, including VM overhead - */ - abstract public long getSize(); - - /** - * @return a human-readable string representation of this thing - */ - abstract public String toString(); - - /** - * Compare our string representation to other's - * @see java.lang.String.compareTo() - */ - public int compareTo(JavaThing other) { - return toString().compareTo(other.toString()); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValue.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValue.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValue.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValue.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Abstract base class for all value types (ints, longs, floats, etc.) - * - * @author Bill Foote - */ - - - - -public abstract class JavaValue extends JavaThing { - - protected JavaValue() { - } - - public boolean isHeapAllocated() { - return false; - } - - abstract public String toString(); - - @Override - public long getSize() { - // The size of a value is already accounted for in the class - // that has the data member. - return 0; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,354 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import jdk.test.lib.hprof.parser.ReadBuffer; -import java.io.IOException; - -/** - * An array of values, that is, an array of ints, boolean, floats or the like. - * - * @author Bill Foote - */ -public class JavaValueArray extends JavaLazyReadObject - /*imports*/ implements ArrayTypeCodes { - - private static String arrayTypeName(byte sig) { - switch (sig) { - case 'B': - return "byte[]"; - case 'Z': - return "boolean[]"; - case 'C': - return "char[]"; - case 'S': - return "short[]"; - case 'I': - return "int[]"; - case 'F': - return "float[]"; - case 'J': - return "long[]"; - case 'D': - return "double[]"; - default: - throw new RuntimeException("invalid array element sig: " + sig); - } - } - - private static int elementSize(byte type) { - switch (type) { - case T_BYTE: - case T_BOOLEAN: - return 1; - case T_CHAR: - case T_SHORT: - return 2; - case T_INT: - case T_FLOAT: - return 4; - case T_LONG: - case T_DOUBLE: - return 8; - default: - throw new RuntimeException("invalid array element type: " + type); - } - } - - /* - * Java primitive array record (HPROF_GC_PRIM_ARRAY_DUMP) looks - * as below: - * - * object ID - * stack trace serial number (int) - * number of elements (int) - * element type (byte) - * array data - */ - @Override - protected final long readValueLength() throws IOException { - long offset = getOffset() + idSize() + 4; - // length of the array in elements - long len = buf().getInt(offset); - // byte length of array - return len * elementSize(getElementType()); - } - - private long dataStartOffset() { - return getOffset() + idSize() + 4 + 4 + 1; - } - - - @Override - protected final JavaThing[] readValue() throws IOException { - int len = getLength(); - long offset = dataStartOffset(); - - JavaThing[] res = new JavaThing[len]; - synchronized (buf()) { - switch (getElementType()) { - case 'Z': { - for (int i = 0; i < len; i++) { - res[i] = new JavaBoolean(booleanAt(offset)); - offset += 1; - } - return res; - } - case 'B': { - for (int i = 0; i < len; i++) { - res[i] = new JavaByte(byteAt(offset)); - offset += 1; - } - return res; - } - case 'C': { - for (int i = 0; i < len; i++) { - res[i] = new JavaChar(charAt(offset)); - offset += 2; - } - return res; - } - case 'S': { - for (int i = 0; i < len; i++) { - res[i] = new JavaShort(shortAt(offset)); - offset += 2; - } - return res; - } - case 'I': { - for (int i = 0; i < len; i++) { - res[i] = new JavaInt(intAt(offset)); - offset += 4; - } - return res; - } - case 'J': { - for (int i = 0; i < len; i++) { - res[i] = new JavaLong(longAt(offset)); - offset += 8; - } - return res; - } - case 'F': { - for (int i = 0; i < len; i++) { - res[i] = new JavaFloat(floatAt(offset)); - offset += 4; - } - return res; - } - case 'D': { - for (int i = 0; i < len; i++) { - res[i] = new JavaDouble(doubleAt(offset)); - offset += 8; - } - return res; - } - default: { - throw new RuntimeException("unknown primitive type?"); - } - } - } - } - - // JavaClass set only after resolve. - private JavaClass clazz; - - // This field contains elementSignature byte and - // divider to be used to calculate length. Note that - // length of content byte[] is not same as array length. - // Actual array length is (byte[].length / divider) - private int data; - - // First 8 bits of data is used for element signature - private static final int SIGNATURE_MASK = 0x0FF; - - // Next 8 bits of data is used for length divider - private static final int LENGTH_DIVIDER_MASK = 0x0FF00; - - // Number of bits to shift to get length divider - private static final int LENGTH_DIVIDER_SHIFT = 8; - - public JavaValueArray(byte elementSignature, long offset) { - super(offset); - this.data = (elementSignature & SIGNATURE_MASK); - } - - public JavaClass getClazz() { - return clazz; - } - - public void visitReferencedObjects(JavaHeapObjectVisitor v) { - super.visitReferencedObjects(v); - } - - public void resolve(Snapshot snapshot) { - if (clazz instanceof JavaClass) { - return; - } - byte elementSig = getElementType(); - clazz = snapshot.findClass(arrayTypeName(elementSig)); - if (clazz == null) { - clazz = snapshot.getArrayClass("" + ((char) elementSig)); - } - getClazz().addInstance(this); - super.resolve(snapshot); - } - - public int getLength() { - int divider = (data & LENGTH_DIVIDER_MASK) >>> LENGTH_DIVIDER_SHIFT; - if (divider == 0) { - byte elementSignature = getElementType(); - switch (elementSignature) { - case 'B': - case 'Z': - divider = 1; - break; - case 'C': - case 'S': - divider = 2; - break; - case 'I': - case 'F': - divider = 4; - break; - case 'J': - case 'D': - divider = 8; - break; - default: - throw new RuntimeException("unknown primitive type: " + - elementSignature); - } - data |= (divider << LENGTH_DIVIDER_SHIFT); - } - return (int)(getValueLength() / divider); - } - - public JavaThing[] getElements() { - return getValue(); - } - - public byte getElementType() { - return (byte) (data & SIGNATURE_MASK); - } - - private void checkIndex(int index) { - if (index < 0 || index >= getLength()) { - throw new ArrayIndexOutOfBoundsException(index); - } - } - - private void requireType(char type) { - if (getElementType() != type) { - throw new RuntimeException("not of type : " + type); - } - } - - public String valueString() { - return valueString(true); - } - - public String valueString(boolean bigLimit) { - // Char arrays deserve special treatment - StringBuilder result; - JavaThing[] things = getValue(); - byte elementSignature = getElementType(); - if (elementSignature == 'C') { - result = new StringBuilder(); - for (int i = 0; i < things.length; i++) { - result.append(things[i]); - } - } else { - int limit = 8; - if (bigLimit) { - limit = 1000; - } - result = new StringBuilder("{"); - for (int i = 0; i < things.length; i++) { - if (i > 0) { - result.append(", "); - } - if (i >= limit) { - result.append("... "); - break; - } - switch (elementSignature) { - case 'Z': { - boolean val = ((JavaBoolean)things[i]).value; - if (val) { - result.append("true"); - } else { - result.append("false"); - } - break; - } - case 'B': { - byte val = ((JavaByte)things[i]).value; - result.append("0x").append(Integer.toString(val, 16)); - break; - } - case 'S': { - short val = ((JavaShort)things[i]).value; - result.append(val); - break; - } - case 'I': { - int val = ((JavaInt)things[i]).value; - result.append(val); - break; - } - case 'J': { // long - long val = ((JavaLong)things[i]).value; - result.append(val); - break; - } - case 'F': { - float val = ((JavaFloat)things[i]).value; - result.append(val); - break; - } - case 'D': { // double - double val = ((JavaDouble)things[i]).value; - result.append(val); - break; - } - default: { - throw new RuntimeException("unknown primitive type?"); - } - } - } - result.append('}'); - } - return result.toString(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - - -/** - * This represents a set of data members that should be excluded from the - * reachable objects query. This is useful to exclude observers from the - * transitive closure of objects reachable from a given object, allowing - * some kind of real determination of the "size" of that object. - * - */ - -public interface ReachableExcludes { - /** - * @return true iff the given field is on the hitlist of excluded - * fields. - */ - public boolean isExcluded(String fieldName); -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.BufferedReader; -import java.io.IOException; - -import java.util.Hashtable; - -/** - * This represents a set of data members that should be excluded from the - * reachable objects query. - * This is useful to exclude observers from the - * transitive closure of objects reachable from a given object, allowing - * some kind of real determination of the "size" of that object. - * - * @author Bill Foote - */ -public class ReachableExcludesImpl implements ReachableExcludes { - - private File excludesFile; - private long lastModified; - private Hashtable methods; // Used as a bag - - /** - * Create a new ReachableExcludesImpl over the given file. The file will be - * re-read whenever the timestamp changes. - */ - public ReachableExcludesImpl(File excludesFile) { - this.excludesFile = excludesFile; - readFile(); - } - - private void readFileIfNeeded() { - if (excludesFile.lastModified() != lastModified) { - synchronized(this) { - if (excludesFile.lastModified() != lastModified) { - readFile(); - } - } - } - } - - private void readFile() { - long lm = excludesFile.lastModified(); - Hashtable m = new Hashtable(); - - try (BufferedReader r = new BufferedReader(new InputStreamReader( - new FileInputStream(excludesFile)))) { - String method; - while ((method = r.readLine()) != null) { - m.put(method, method); - } - lastModified = lm; - methods = m; // We want this to be atomic - } catch (IOException ex) { - System.out.println("Error reading " + excludesFile + ": " + ex); - } - } - - /** - * @return true iff the given field is on the histlist of excluded - * fields. - */ - public boolean isExcluded(String fieldName) { - readFileIfNeeded(); - return methods.get(fieldName) != null; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.util.Vector; -import java.util.Hashtable; -import java.util.Enumeration; - -import jdk.test.lib.hprof.util.ArraySorter; -import jdk.test.lib.hprof.util.Comparer; - -/** - * @author A. Sundararajan - */ - -public class ReachableObjects { - public ReachableObjects(JavaHeapObject root, - final ReachableExcludes excludes) { - this.root = root; - - final Hashtable bag = new Hashtable(); - final Hashtable fieldsExcluded = new Hashtable(); //Bag - final Hashtable fieldsUsed = new Hashtable(); // Bag - JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() { - public void visit(JavaHeapObject t) { - // Size is zero for things like integer fields - if (t != null && t.getSize() > 0 && bag.get(t) == null) { - bag.put(t, t); - t.visitReferencedObjects(this); - } - } - - public boolean mightExclude() { - return excludes != null; - } - - public boolean exclude(JavaClass clazz, JavaField f) { - if (excludes == null) { - return false; - } - String nm = clazz.getName() + "." + f.getName(); - if (excludes.isExcluded(nm)) { - fieldsExcluded.put(nm, nm); - return true; - } else { - fieldsUsed.put(nm, nm); - return false; - } - } - }; - // Put the closure of root and all objects reachable from root into - // bag (depth first), but don't include root: - visitor.visit(root); - bag.remove(root); - - // Now grab the elements into a vector, and sort it in decreasing size - JavaThing[] things = new JavaThing[bag.size()]; - int i = 0; - for (Enumeration e = bag.elements(); e.hasMoreElements(); ) { - things[i++] = (JavaThing) e.nextElement(); - } - ArraySorter.sort(things, new Comparer() { - public int compare(Object lhs, Object rhs) { - JavaThing left = (JavaThing) lhs; - JavaThing right = (JavaThing) rhs; - long diff = right.getSize() - left.getSize(); - if (diff != 0) { - return Long.signum(diff); - } - return left.compareTo(right); - } - }); - this.reachables = things; - - this.totalSize = root.getSize(); - for (i = 0; i < things.length; i++) { - this.totalSize += things[i].getSize(); - } - - excludedFields = getElements(fieldsExcluded); - usedFields = getElements(fieldsUsed); - } - - public JavaHeapObject getRoot() { - return root; - } - - public JavaThing[] getReachables() { - return reachables; - } - - public long getTotalSize() { - return totalSize; - } - - public String[] getExcludedFields() { - return excludedFields; - } - - public String[] getUsedFields() { - return usedFields; - } - - private String[] getElements(Hashtable ht) { - Object[] keys = ht.keySet().toArray(); - int len = keys.length; - String[] res = new String[len]; - System.arraycopy(keys, 0, res, 0, len); - ArraySorter.sortArrayOfStrings(res); - return res; - } - - private JavaHeapObject root; - private JavaThing[] reachables; - private String[] excludedFields; - private String[] usedFields; - private long totalSize; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * Represents a chain of references to some target object - * - * @author Bill Foote - */ - -public class ReferenceChain { - - JavaHeapObject obj; // Object referred to - ReferenceChain next; // Next in chain - - public ReferenceChain(JavaHeapObject obj, ReferenceChain next) { - this.obj = obj; - this.next = next; - } - - public JavaHeapObject getObj() { - return obj; - } - - public ReferenceChain getNext() { - return next; - } - - public int getDepth() { - int count = 1; - ReferenceChain tmp = next; - while (tmp != null) { - count++; - tmp = tmp.next; - } - return count; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Root.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Root.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Root.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Root.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,174 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import jdk.test.lib.hprof.util.Misc; - -/** - * - * @author Bill Foote - */ - - -/** - * Represents a member of the rootset, that is, one of the objects that - * the GC starts from when marking reachable objects. - */ - -public class Root { - - private long id; // ID of the JavaThing we refer to - private long refererId; // Thread or Class responsible for this, or 0 - private int index = -1; // Index in Snapshot.roots - private int type; - private String description; - private JavaHeapObject referer = null; - private StackTrace stackTrace = null; - - // Values for type. Higher values are more interesting -- see getType(). - // See also getTypeName() - public final static int INVALID_TYPE = 0; - public final static int UNKNOWN = 1; - public final static int SYSTEM_CLASS = 2; - - public final static int NATIVE_LOCAL = 3; - public final static int NATIVE_STATIC = 4; - public final static int THREAD_BLOCK = 5; - public final static int BUSY_MONITOR = 6; - public final static int JAVA_LOCAL = 7; - public final static int NATIVE_STACK = 8; - public final static int JAVA_STATIC = 9; - - - public Root(long id, long refererId, int type, String description) { - this(id, refererId, type, description, null); - } - - - public Root(long id, long refererId, int type, String description, - StackTrace stackTrace) { - this.id = id; - this.refererId = refererId; - this.type = type; - this.description = description; - this.stackTrace = stackTrace; - } - - public long getId() { - return id; - } - - public String getIdString() { - return Misc.toHex(id); - } - - public String getDescription() { - if ("".equals(description)) { - return getTypeName() + " Reference"; - } else { - return description; - } - } - - /** - * Return type. We guarantee that more interesting roots will have - * a type that is numerically higher. - */ - public int getType() { - return type; - } - - public String getTypeName() { - switch(type) { - case INVALID_TYPE: return "Invalid (?!?)"; - case UNKNOWN: return "Unknown"; - case SYSTEM_CLASS: return "System Class"; - case NATIVE_LOCAL: return "JNI Local"; - case NATIVE_STATIC: return "JNI Global"; - case THREAD_BLOCK: return "Thread Block"; - case BUSY_MONITOR: return "Busy Monitor"; - case JAVA_LOCAL: return "Java Local"; - case NATIVE_STACK: return "Native Stack (possibly Java local)"; - case JAVA_STATIC: return "Java Static"; - default: return "??"; - } - } - - /** - * Given two Root instances, return the one that is most interesting. - */ - public Root mostInteresting(Root other) { - if (other.type > this.type) { - return other; - } else { - return this; - } - } - - /** - * Get the object that's responsible for this root, if there is one. - * This will be null, a Thread object, or a Class object. - */ - public JavaHeapObject getReferer() { - return referer; - } - - /** - * @return the stack trace responsible for this root, or null if there - * is none. - */ - public StackTrace getStackTrace() { - return stackTrace; - } - - /** - * @return The index of this root in Snapshot.roots - */ - public int getIndex() { - return index; - } - - void resolve(Snapshot ss) { - if (refererId != 0) { - referer = ss.findThing(refererId); - } - if (stackTrace != null) { - stackTrace.resolve(ss); - } - } - - void setIndex(int i) { - index = i; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Snapshot.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Snapshot.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Snapshot.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/Snapshot.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,635 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -import java.lang.ref.SoftReference; -import java.util.*; - -import jdk.test.lib.hprof.parser.ReadBuffer; -import jdk.test.lib.hprof.util.Misc; - -/** - * - * @author Bill Foote - */ - -/** - * Represents a snapshot of the Java objects in the VM at one instant. - * This is the top-level "model" object read out of a single .hprof or .bod - * file. - */ - -public class Snapshot implements AutoCloseable { - - public static final long SMALL_ID_MASK = 0x0FFFFFFFFL; - public static final JavaThing[] EMPTY_JAVATHING_ARRAY = new JavaThing[0]; - - private static final JavaField[] EMPTY_FIELD_ARRAY = new JavaField[0]; - private static final JavaStatic[] EMPTY_STATIC_ARRAY = new JavaStatic[0]; - - // all heap objects - private Hashtable heapObjects = - new Hashtable(); - - private Hashtable fakeClasses = - new Hashtable(); - - // all Roots in this Snapshot - private Vector roots = new Vector(); - - // name-to-class map - private Map classes = - new TreeMap(); - - // new objects relative to a baseline - lazily initialized - private volatile Map newObjects; - - // allocation site traces for all objects - lazily initialized - private volatile Map siteTraces; - - // object-to-Root map for all objects - private Map rootsMap = - new HashMap(); - - // soft cache of finalizeable objects - lazily initialized - private SoftReference> finalizablesCache; - - // represents null reference - private JavaThing nullThing; - - // java.lang.ref.Reference class - private JavaClass weakReferenceClass; - // index of 'referent' field in java.lang.ref.Reference class - private int referentFieldIndex; - - // java.lang.Class class - private JavaClass javaLangClass; - // java.lang.String class - private JavaClass javaLangString; - // java.lang.ClassLoader class - private JavaClass javaLangClassLoader; - - // unknown "other" array class - private volatile JavaClass otherArrayType; - // Stuff to exclude from reachable query - private ReachableExcludes reachableExcludes; - // the underlying heap dump buffer - private ReadBuffer readBuf; - - // True iff some heap objects have isNew set - private boolean hasNewSet; - private boolean unresolvedObjectsOK; - - // whether object array instances have new style class or - // old style (element) class. - private boolean newStyleArrayClass; - - // object id size in the heap dump - private int identifierSize = 4; - - // minimum object size - accounts for object header in - // most Java virtual machines - we assume 2 identifierSize - // (which is true for Sun's hotspot JVM). - private int minimumObjectSize; - - public Snapshot(ReadBuffer buf) { - nullThing = new HackJavaValue("", 0); - readBuf = buf; - } - - public void setSiteTrace(JavaHeapObject obj, StackTrace trace) { - if (trace != null && trace.getFrames().length != 0) { - initSiteTraces(); - siteTraces.put(obj, trace); - } - } - - public StackTrace getSiteTrace(JavaHeapObject obj) { - if (siteTraces != null) { - return siteTraces.get(obj); - } else { - return null; - } - } - - public void setNewStyleArrayClass(boolean value) { - newStyleArrayClass = value; - } - - public boolean isNewStyleArrayClass() { - return newStyleArrayClass; - } - - public void setIdentifierSize(int size) { - identifierSize = size; - minimumObjectSize = 2 * size; - } - - public int getIdentifierSize() { - return identifierSize; - } - - public int getMinimumObjectSize() { - return minimumObjectSize; - } - - public void addHeapObject(long id, JavaHeapObject ho) { - heapObjects.put(makeId(id), ho); - } - - public void addRoot(Root r) { - r.setIndex(roots.size()); - roots.addElement(r); - } - - public void addClass(long id, JavaClass c) { - addHeapObject(id, c); - putInClassesMap(c); - } - - JavaClass addFakeInstanceClass(long classID, int instSize) { - // Create a fake class name based on ID. - String name = "unknown-class<@" + Misc.toHex(classID) + ">"; - - // Create fake fields convering the given instance size. - // Create as many as int type fields and for the left over - // size create byte type fields. - int numInts = instSize / 4; - int numBytes = instSize % 4; - JavaField[] fields = new JavaField[numInts + numBytes]; - int i; - for (i = 0; i < numInts; i++) { - fields[i] = new JavaField("unknown-field-" + i, "I"); - } - for (i = 0; i < numBytes; i++) { - fields[i + numInts] = new JavaField("unknown-field-" + - i + numInts, "B"); - } - - // Create fake instance class - JavaClass c = new JavaClass(name, 0, 0, 0, 0, fields, - EMPTY_STATIC_ARRAY, instSize); - // Add the class - addFakeClass(makeId(classID), c); - return c; - } - - - /** - * @return true iff it's possible that some JavaThing instances might - * isNew set - * - * @see JavaThing.isNew() - */ - public boolean getHasNewSet() { - return hasNewSet; - } - - // - // Used in the body of resolve() - // - private static class MyVisitor extends AbstractJavaHeapObjectVisitor { - JavaHeapObject t; - public void visit(JavaHeapObject other) { - other.addReferenceFrom(t); - } - } - - // To show heap parsing progress, we print a '.' after this limit - private static final int DOT_LIMIT = 5000; - - /** - * Called after reading complete, to initialize the structure - */ - public void resolve(boolean calculateRefs) { - System.out.println("Resolving " + heapObjects.size() + " objects..."); - - // First, resolve the classes. All classes must be resolved before - // we try any objects, because the objects use classes in their - // resolution. - javaLangClass = findClass("java.lang.Class"); - if (javaLangClass == null) { - System.out.println("WARNING: hprof file does not include java.lang.Class!"); - javaLangClass = new JavaClass("java.lang.Class", 0, 0, 0, 0, - EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); - addFakeClass(javaLangClass); - } - javaLangString = findClass("java.lang.String"); - if (javaLangString == null) { - System.out.println("WARNING: hprof file does not include java.lang.String!"); - javaLangString = new JavaClass("java.lang.String", 0, 0, 0, 0, - EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); - addFakeClass(javaLangString); - } - javaLangClassLoader = findClass("java.lang.ClassLoader"); - if (javaLangClassLoader == null) { - System.out.println("WARNING: hprof file does not include java.lang.ClassLoader!"); - javaLangClassLoader = new JavaClass("java.lang.ClassLoader", 0, 0, 0, 0, - EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); - addFakeClass(javaLangClassLoader); - } - - for (JavaHeapObject t : heapObjects.values()) { - if (t instanceof JavaClass) { - t.resolve(this); - } - } - - // Now, resolve everything else. - for (JavaHeapObject t : heapObjects.values()) { - if (!(t instanceof JavaClass)) { - t.resolve(this); - } - } - - heapObjects.putAll(fakeClasses); - fakeClasses.clear(); - - weakReferenceClass = findClass("java.lang.ref.Reference"); - referentFieldIndex = 0; - if (weakReferenceClass != null) { - JavaField[] fields = weakReferenceClass.getFieldsForInstance(); - for (int i = 0; i < fields.length; i++) { - if ("referent".equals(fields[i].getName())) { - referentFieldIndex = i; - break; - } - } - } - - if (calculateRefs) { - calculateReferencesToObjects(); - System.out.print("Eliminating duplicate references"); - System.out.flush(); - // This println refers to the *next* step - } - int count = 0; - for (JavaHeapObject t : heapObjects.values()) { - t.setupReferers(); - ++count; - if (calculateRefs && count % DOT_LIMIT == 0) { - System.out.print("."); - System.out.flush(); - } - } - if (calculateRefs) { - System.out.println(""); - } - - // to ensure that Iterator.remove() on getClasses() - // result will throw exception.. - classes = Collections.unmodifiableMap(classes); - } - - private void calculateReferencesToObjects() { - System.out.print("Chasing references, expect " - + (heapObjects.size() / DOT_LIMIT) + " dots"); - System.out.flush(); - int count = 0; - MyVisitor visitor = new MyVisitor(); - for (JavaHeapObject t : heapObjects.values()) { - visitor.t = t; - // call addReferenceFrom(t) on all objects t references: - t.visitReferencedObjects(visitor); - ++count; - if (count % DOT_LIMIT == 0) { - System.out.print("."); - System.out.flush(); - } - } - System.out.println(); - for (Root r : roots) { - r.resolve(this); - JavaHeapObject t = findThing(r.getId()); - if (t != null) { - t.addReferenceFromRoot(r); - } - } - } - - public void markNewRelativeTo(Snapshot baseline) { - hasNewSet = true; - for (JavaHeapObject t : heapObjects.values()) { - boolean isNew; - long thingID = t.getId(); - if (thingID == 0L || thingID == -1L) { - isNew = false; - } else { - JavaThing other = baseline.findThing(t.getId()); - if (other == null) { - isNew = true; - } else { - isNew = !t.isSameTypeAs(other); - } - } - t.setNew(isNew); - } - } - - public Enumeration getThings() { - return heapObjects.elements(); - } - - - public JavaHeapObject findThing(long id) { - Number idObj = makeId(id); - JavaHeapObject jho = heapObjects.get(idObj); - return jho != null? jho : fakeClasses.get(idObj); - } - - public JavaHeapObject findThing(String id) { - return findThing(Misc.parseHex(id)); - } - - public JavaClass findClass(String name) { - if (name.startsWith("0x")) { - return (JavaClass) findThing(name); - } else { - return classes.get(name); - } - } - - /** - * Return an Iterator of all of the classes in this snapshot. - **/ - public Iterator getClasses() { - // note that because classes is a TreeMap - // classes are already sorted by name - return classes.values().iterator(); - } - - public JavaClass[] getClassesArray() { - JavaClass[] res = new JavaClass[classes.size()]; - classes.values().toArray(res); - return res; - } - - public synchronized Enumeration getFinalizerObjects() { - Vector obj; - if (finalizablesCache != null && - (obj = finalizablesCache.get()) != null) { - return obj.elements(); - } - - JavaClass clazz = findClass("java.lang.ref.Finalizer"); - JavaObject queue = (JavaObject) clazz.getStaticField("queue"); - JavaThing tmp = queue.getField("head"); - Vector finalizables = new Vector(); - if (tmp != getNullThing()) { - JavaObject head = (JavaObject) tmp; - while (true) { - JavaHeapObject referent = (JavaHeapObject) head.getField("referent"); - JavaThing next = head.getField("next"); - if (next == getNullThing() || next.equals(head)) { - break; - } - head = (JavaObject) next; - finalizables.add(referent); - } - } - finalizablesCache = new SoftReference>(finalizables); - return finalizables.elements(); - } - - public Enumeration getRoots() { - return roots.elements(); - } - - public Root[] getRootsArray() { - Root[] res = new Root[roots.size()]; - roots.toArray(res); - return res; - } - - public Root getRootAt(int i) { - return roots.elementAt(i); - } - - public ReferenceChain[] - rootsetReferencesTo(JavaHeapObject target, boolean includeWeak) { - Vector fifo = new Vector(); // This is slow... A real fifo would help - // Must be a fifo to go breadth-first - Hashtable visited = new Hashtable(); - // Objects are added here right after being added to fifo. - Vector result = new Vector(); - visited.put(target, target); - fifo.addElement(new ReferenceChain(target, null)); - - while (fifo.size() > 0) { - ReferenceChain chain = fifo.elementAt(0); - fifo.removeElementAt(0); - JavaHeapObject curr = chain.getObj(); - if (curr.getRoot() != null) { - result.addElement(chain); - // Even though curr is in the rootset, we want to explore its - // referers, because they might be more interesting. - } - Enumeration referers = curr.getReferers(); - while (referers.hasMoreElements()) { - JavaHeapObject t = (JavaHeapObject) referers.nextElement(); - if (t != null && !visited.containsKey(t)) { - if (includeWeak || !t.refersOnlyWeaklyTo(this, curr)) { - visited.put(t, t); - fifo.addElement(new ReferenceChain(t, chain)); - } - } - } - } - - ReferenceChain[] realResult = new ReferenceChain[result.size()]; - for (int i = 0; i < result.size(); i++) { - realResult[i] = result.elementAt(i); - } - return realResult; - } - - public boolean getUnresolvedObjectsOK() { - return unresolvedObjectsOK; - } - - public void setUnresolvedObjectsOK(boolean v) { - unresolvedObjectsOK = v; - } - - public JavaClass getWeakReferenceClass() { - return weakReferenceClass; - } - - public int getReferentFieldIndex() { - return referentFieldIndex; - } - - public JavaThing getNullThing() { - return nullThing; - } - - public void setReachableExcludes(ReachableExcludes e) { - reachableExcludes = e; - } - - public ReachableExcludes getReachableExcludes() { - return reachableExcludes; - } - - // package privates - void addReferenceFromRoot(Root r, JavaHeapObject obj) { - Root root = rootsMap.get(obj); - if (root == null) { - rootsMap.put(obj, r); - } else { - rootsMap.put(obj, root.mostInteresting(r)); - } - } - - Root getRoot(JavaHeapObject obj) { - return rootsMap.get(obj); - } - - JavaClass getJavaLangClass() { - return javaLangClass; - } - - JavaClass getJavaLangString() { - return javaLangString; - } - - JavaClass getJavaLangClassLoader() { - return javaLangClassLoader; - } - - JavaClass getOtherArrayType() { - if (otherArrayType == null) { - synchronized(this) { - if (otherArrayType == null) { - addFakeClass(new JavaClass("[", 0, 0, 0, 0, - EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, - 0)); - otherArrayType = findClass("["); - } - } - } - return otherArrayType; - } - - JavaClass getArrayClass(String elementSignature) { - JavaClass clazz; - synchronized(classes) { - clazz = findClass("[" + elementSignature); - if (clazz == null) { - clazz = new JavaClass("[" + elementSignature, 0, 0, 0, 0, - EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); - addFakeClass(clazz); - // This is needed because the JDK only creates Class structures - // for array element types, not the arrays themselves. For - // analysis, though, we need to pretend that there's a - // JavaClass for the array type, too. - } - } - return clazz; - } - - ReadBuffer getReadBuffer() { - return readBuf; - } - - void setNew(JavaHeapObject obj, boolean isNew) { - initNewObjects(); - if (isNew) { - newObjects.put(obj, Boolean.TRUE); - } - } - - boolean isNew(JavaHeapObject obj) { - if (newObjects != null) { - return newObjects.get(obj) != null; - } else { - return false; - } - } - - // Internals only below this point - private Number makeId(long id) { - if (identifierSize == 4) { - return (int)id; - } else { - return id; - } - } - - private void putInClassesMap(JavaClass c) { - String name = c.getName(); - if (classes.containsKey(name)) { - // more than one class can have the same name - // if so, create a unique name by appending - // - and id string to it. - name += "-" + c.getIdString(); - } - classes.put(c.getName(), c); - } - - private void addFakeClass(JavaClass c) { - putInClassesMap(c); - c.resolve(this); - } - - private void addFakeClass(Number id, JavaClass c) { - fakeClasses.put(id, c); - addFakeClass(c); - } - - private synchronized void initNewObjects() { - if (newObjects == null) { - synchronized (this) { - if (newObjects == null) { - newObjects = new HashMap(); - } - } - } - } - - private synchronized void initSiteTraces() { - if (siteTraces == null) { - synchronized (this) { - if (siteTraces == null) { - siteTraces = new HashMap(); - } - } - } - } - - @Override - public void close() throws Exception { - readBuf.close(); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackFrame.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackFrame.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackFrame.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackFrame.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,101 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * - * @author Bill Foote - */ - - -/** - * Represents a stack frame. - */ - -public class StackFrame { - - // - // Values for the lineNumber data member. These are the same - // as the values used in the JDK 1.2 heap dump file. - // - public final static int LINE_NUMBER_UNKNOWN = -1; - public final static int LINE_NUMBER_COMPILED = -2; - public final static int LINE_NUMBER_NATIVE = -3; - - private String methodName; - private String methodSignature; - private String className; - private String sourceFileName; - private int lineNumber; - - public StackFrame(String methodName, String methodSignature, - String className, String sourceFileName, int lineNumber) { - this.methodName = methodName; - this.methodSignature = methodSignature; - this.className = className; - this.sourceFileName = sourceFileName; - this.lineNumber = lineNumber; - } - - public void resolve(Snapshot snapshot) { - } - - public String getMethodName() { - return methodName; - } - - public String getMethodSignature() { - return methodSignature; - } - - public String getClassName() { - return className; - } - - public String getSourceFileName() { - return sourceFileName; - } - - public String getLineNumber() { - switch(lineNumber) { - case LINE_NUMBER_UNKNOWN: - return "(unknown)"; - case LINE_NUMBER_COMPILED: - return "(compiled method)"; - case LINE_NUMBER_NATIVE: - return "(native method)"; - default: - return Integer.toString(lineNumber, 10); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackTrace.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackTrace.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackTrace.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/model/StackTrace.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.model; - -/** - * - * @author Bill Foote - */ - - -/** - * Represents a stack trace, that is, an ordered collection of stack frames. - */ - -public class StackTrace { - - private StackFrame[] frames; - - public StackTrace(StackFrame[] frames) { - this.frames = frames; - } - - /** - * @param depth. The minimum reasonable depth is 1. - * - * @return a (possibly new) StackTrace that is limited to depth. - */ - public StackTrace traceForDepth(int depth) { - if (depth >= frames.length) { - return this; - } else { - StackFrame[] f = new StackFrame[depth]; - System.arraycopy(frames, 0, f, 0, depth); - return new StackTrace(f); - } - } - - public void resolve(Snapshot snapshot) { - for (int i = 0; i < frames.length; i++) { - frames[i].resolve(snapshot); - } - } - - public StackFrame[] getFrames() { - return frames; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.IOException; -import java.io.RandomAccessFile; - -/** - * Implementation of ReadBuffer using a RandomAccessFile - * - * @author A. Sundararajan - */ -class FileReadBuffer implements ReadBuffer { - // underlying file to read - private RandomAccessFile file; - - FileReadBuffer(RandomAccessFile file) { - this.file = file; - } - - private void seek(long pos) throws IOException { - file.getChannel().position(pos); - } - - public synchronized void get(long pos, byte[] buf) throws IOException { - seek(pos); - file.read(buf); - } - - @Override - public synchronized char getChar(long pos) throws IOException { - seek(pos); - return file.readChar(); - } - - @Override - public synchronized byte getByte(long pos) throws IOException { - seek(pos); - return (byte) file.read(); - } - - @Override - public synchronized short getShort(long pos) throws IOException { - seek(pos); - return file.readShort(); - } - - @Override - public synchronized int getInt(long pos) throws IOException { - seek(pos); - return file.readInt(); - } - - @Override - public synchronized long getLong(long pos) throws IOException { - seek(pos); - return file.readLong(); - } - - @Override - public void close() throws Exception { - file.close(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,926 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.*; -import java.util.Date; -import java.util.Hashtable; -import java.util.Map; -import jdk.test.lib.hprof.model.ArrayTypeCodes; -import jdk.test.lib.hprof.model.*; - -/** - * Object that's used to read a hprof file. - * - * @author Bill Foote - */ - -public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes { - - final static int MAGIC_NUMBER = 0x4a415641; - // That's "JAVA", the first part of "JAVA PROFILE ..." - private final static String[] VERSIONS = { - " PROFILE 1.0\0", - " PROFILE 1.0.1\0", - " PROFILE 1.0.2\0", - }; - - private final static int VERSION_JDK12BETA3 = 0; - private final static int VERSION_JDK12BETA4 = 1; - private final static int VERSION_JDK6 = 2; - // These version numbers are indices into VERSIONS. The instance data - // member version is set to one of these, and it drives decisions when - // reading the file. - // - // Version 1.0.1 added HPROF_GC_PRIM_ARRAY_DUMP, which requires no - // version-sensitive parsing. - // - // Version 1.0.1 changed the type of a constant pool entry from a signature - // to a typecode. - // - // Version 1.0.2 added HPROF_HEAP_DUMP_SEGMENT and HPROF_HEAP_DUMP_END - // to allow a large heap to be dumped as a sequence of heap dump segments. - // - // The HPROF agent in J2SE 1.2 through to 5.0 generate a version 1.0.1 - // file. In Java SE 6.0 the version is either 1.0.1 or 1.0.2 depending on - // the size of the heap (normally it will be 1.0.1 but for multi-GB - // heaps the heap dump will not fit in a HPROF_HEAP_DUMP record so the - // dump is generated as version 1.0.2). - - // - // Record types: - // - static final int HPROF_UTF8 = 0x01; - static final int HPROF_LOAD_CLASS = 0x02; - static final int HPROF_UNLOAD_CLASS = 0x03; - static final int HPROF_FRAME = 0x04; - static final int HPROF_TRACE = 0x05; - static final int HPROF_ALLOC_SITES = 0x06; - static final int HPROF_HEAP_SUMMARY = 0x07; - - static final int HPROF_START_THREAD = 0x0a; - static final int HPROF_END_THREAD = 0x0b; - - static final int HPROF_HEAP_DUMP = 0x0c; - - static final int HPROF_CPU_SAMPLES = 0x0d; - static final int HPROF_CONTROL_SETTINGS = 0x0e; - static final int HPROF_LOCKSTATS_WAIT_TIME = 0x10; - static final int HPROF_LOCKSTATS_HOLD_TIME = 0x11; - - static final int HPROF_GC_ROOT_UNKNOWN = 0xff; - static final int HPROF_GC_ROOT_JNI_GLOBAL = 0x01; - static final int HPROF_GC_ROOT_JNI_LOCAL = 0x02; - static final int HPROF_GC_ROOT_JAVA_FRAME = 0x03; - static final int HPROF_GC_ROOT_NATIVE_STACK = 0x04; - static final int HPROF_GC_ROOT_STICKY_CLASS = 0x05; - static final int HPROF_GC_ROOT_THREAD_BLOCK = 0x06; - static final int HPROF_GC_ROOT_MONITOR_USED = 0x07; - static final int HPROF_GC_ROOT_THREAD_OBJ = 0x08; - - static final int HPROF_GC_CLASS_DUMP = 0x20; - static final int HPROF_GC_INSTANCE_DUMP = 0x21; - static final int HPROF_GC_OBJ_ARRAY_DUMP = 0x22; - static final int HPROF_GC_PRIM_ARRAY_DUMP = 0x23; - - static final int HPROF_HEAP_DUMP_SEGMENT = 0x1c; - static final int HPROF_HEAP_DUMP_END = 0x2c; - - private final static int T_CLASS = 2; - - private int version; // The version of .hprof being read - - private int debugLevel; - private long currPos; // Current position in the file - - private int dumpsToSkip; - private boolean callStack; // If true, read the call stack of objects - - private int identifierSize; // Size, in bytes, of identifiers. - private Hashtable names; - - // Hashtable, used to map the thread sequence number - // (aka "serial number") to the thread object ID for - // HPROF_GC_ROOT_THREAD_OBJ. ThreadObject is a trivial inner class, - // at the end of this file. - private Hashtable threadObjects; - - // Hashtable, maps class object ID to class name - // (with / converted to .) - private Hashtable classNameFromObjectID; - - // Hashtable, maps class serial # to class object ID - private Hashtable classNameFromSerialNo; - - // Hashtable maps stack frame ID to StackFrame. - // Null if we're not tracking them. - private Hashtable stackFrames; - - // Hashtable maps stack frame ID to StackTrace - // Null if we're not tracking them. - private Hashtable stackTraces; - - private Snapshot snapshot; - - public static boolean verifyMagicNumber(int numberRead) { - return (numberRead == MAGIC_NUMBER); - } - - public HprofReader(String fileName, PositionDataInputStream in, - int dumpNumber, boolean callStack, int debugLevel) - throws IOException { - super(in); - RandomAccessFile file = new RandomAccessFile(fileName, "r"); - this.snapshot = new Snapshot(MappedReadBuffer.create(file)); - this.dumpsToSkip = dumpNumber - 1; - this.callStack = callStack; - this.debugLevel = debugLevel; - names = new Hashtable(); - threadObjects = new Hashtable(43); - classNameFromObjectID = new Hashtable(); - if (callStack) { - stackFrames = new Hashtable(43); - stackTraces = new Hashtable(43); - classNameFromSerialNo = new Hashtable(); - } - } - - public Snapshot read() throws IOException { - currPos = 4; // 4 because of the magic number - version = readVersionHeader(); - identifierSize = in.readInt(); - snapshot.setIdentifierSize(identifierSize); - if (version >= VERSION_JDK12BETA4) { - snapshot.setNewStyleArrayClass(true); - } else { - snapshot.setNewStyleArrayClass(false); - } - - currPos += 4; - if (identifierSize != 4 && identifierSize != 8) { - throw new IOException("I'm sorry, but I can't deal with an identifier size of " + identifierSize + ". I can only deal with 4 or 8."); - } - System.out.println("Dump file created " + (new Date(in.readLong()))); - currPos += 8; - - for (;;) { - int type; - try { - type = in.readUnsignedByte(); - } catch (EOFException ignored) { - break; - } - in.readInt(); // Timestamp of this record - // Length of record: readInt() will return negative value for record - // length >2GB. so store 32bit value in long to keep it unsigned. - long length = in.readInt() & 0xffffffffL; - if (debugLevel > 0) { - System.out.println("Read record type " + type - + ", length " + length - + " at position " + toHex(currPos)); - } - if (length < 0) { - throw new IOException("Bad record length of " + length - + " at byte " + toHex(currPos+5) - + " of file."); - } - currPos += 9 + length; - switch (type) { - case HPROF_UTF8: { - long id = readID(); - byte[] chars = new byte[(int)length - identifierSize]; - in.readFully(chars); - names.put(id, new String(chars)); - break; - } - case HPROF_LOAD_CLASS: { - int serialNo = in.readInt(); // Not used - long classID = readID(); - int stackTraceSerialNo = in.readInt(); - long classNameID = readID(); - Long classIdI = classID; - String nm = getNameFromID(classNameID).replace('/', '.'); - classNameFromObjectID.put(classIdI, nm); - if (classNameFromSerialNo != null) { - classNameFromSerialNo.put(serialNo, nm); - } - break; - } - - case HPROF_HEAP_DUMP: { - if (dumpsToSkip <= 0) { - try { - readHeapDump(length, currPos); - } catch (EOFException exp) { - handleEOF(exp, snapshot); - } - if (debugLevel > 0) { - System.out.println(" Finished processing instances in heap dump."); - } - return snapshot; - } else { - dumpsToSkip--; - skipBytes(length); - } - break; - } - - case HPROF_HEAP_DUMP_END: { - if (version >= VERSION_JDK6) { - if (dumpsToSkip <= 0) { - skipBytes(length); // should be no-op - return snapshot; - } else { - // skip this dump (of the end record for a sequence of dump segments) - dumpsToSkip--; - } - } else { - // HPROF_HEAP_DUMP_END only recognized in >= 1.0.2 - warn("Ignoring unrecognized record type " + type); - } - skipBytes(length); // should be no-op - break; - } - - case HPROF_HEAP_DUMP_SEGMENT: { - if (version >= VERSION_JDK6) { - if (dumpsToSkip <= 0) { - try { - // read the dump segment - readHeapDump(length, currPos); - } catch (EOFException exp) { - handleEOF(exp, snapshot); - } - } else { - // all segments comprising the heap dump will be skipped - skipBytes(length); - } - } else { - // HPROF_HEAP_DUMP_SEGMENT only recognized in >= 1.0.2 - warn("Ignoring unrecognized record type " + type); - skipBytes(length); - } - break; - } - - case HPROF_FRAME: { - if (stackFrames == null) { - skipBytes(length); - } else { - long id = readID(); - String methodName = getNameFromID(readID()); - String methodSig = getNameFromID(readID()); - String sourceFile = getNameFromID(readID()); - int classSer = in.readInt(); - String className = classNameFromSerialNo.get(classSer); - int lineNumber = in.readInt(); - if (lineNumber < StackFrame.LINE_NUMBER_NATIVE) { - warn("Weird stack frame line number: " + lineNumber); - lineNumber = StackFrame.LINE_NUMBER_UNKNOWN; - } - stackFrames.put(id, - new StackFrame(methodName, methodSig, - className, sourceFile, - lineNumber)); - } - break; - } - case HPROF_TRACE: { - if (stackTraces == null) { - skipBytes(length); - } else { - int serialNo = in.readInt(); - int threadSeq = in.readInt(); // Not used - StackFrame[] frames = new StackFrame[in.readInt()]; - for (int i = 0; i < frames.length; i++) { - long fid = readID(); - frames[i] = stackFrames.get(fid); - if (frames[i] == null) { - throw new IOException("Stack frame " + toHex(fid) + " not found"); - } - } - stackTraces.put(serialNo, - new StackTrace(frames)); - } - break; - } - case HPROF_UNLOAD_CLASS: - case HPROF_ALLOC_SITES: - case HPROF_START_THREAD: - case HPROF_END_THREAD: - case HPROF_HEAP_SUMMARY: - case HPROF_CPU_SAMPLES: - case HPROF_CONTROL_SETTINGS: - case HPROF_LOCKSTATS_WAIT_TIME: - case HPROF_LOCKSTATS_HOLD_TIME: - { - // Ignore these record types - skipBytes(length); - break; - } - default: { - skipBytes(length); - warn("Ignoring unrecognized record type " + type); - } - } - } - - return snapshot; - } - - public String printStackTraces() { - StringBuffer output = new StringBuffer(); - for (Map.Entry entry : stackTraces.entrySet()) { - StackFrame[] frames = entry.getValue().getFrames(); - output.append("SerialNo " + entry.getKey() + "\n"); - for (int i = 0; i < frames.length; i++) { - output.append(" " + frames[i].getClassName() + "." + frames[i].getMethodName() - + frames[i].getMethodSignature() + " (" + frames[i].getSourceFileName() - + ":" + frames[i].getLineNumber() + ")" + "\n"); - } - } - - System.out.println(output); - return output.toString(); - } - - private void skipBytes(long length) throws IOException { - while (length > 0) { - long skipped = in.skip(length); - if (skipped == 0) { - // EOF or other problem, throw exception - throw new EOFException("Couldn't skip enough bytes"); - } - length -= skipped; - } - } - - private int readVersionHeader() throws IOException { - int candidatesLeft = VERSIONS.length; - boolean[] matched = new boolean[VERSIONS.length]; - for (int i = 0; i < candidatesLeft; i++) { - matched[i] = true; - } - - int pos = 0; - while (candidatesLeft > 0) { - char c = (char) in.readByte(); - currPos++; - for (int i = 0; i < VERSIONS.length; i++) { - if (matched[i]) { - if (c != VERSIONS[i].charAt(pos)) { // Not matched - matched[i] = false; - --candidatesLeft; - } else if (pos == VERSIONS[i].length() - 1) { // Full match - return i; - } - } - } - ++pos; - } - throw new IOException("Version string not recognized at byte " + (pos+3)); - } - - private void readHeapDump(long bytesLeft, long posAtEnd) throws IOException { - while (bytesLeft > 0) { - int type = in.readUnsignedByte(); - if (debugLevel > 0) { - System.out.println(" Read heap sub-record type " + type - + " at position " - + toHex(posAtEnd - bytesLeft)); - } - bytesLeft--; - switch(type) { - case HPROF_GC_ROOT_UNKNOWN: { - long id = readID(); - bytesLeft -= identifierSize; - snapshot.addRoot(new Root(id, 0, Root.UNKNOWN, "")); - break; - } - case HPROF_GC_ROOT_THREAD_OBJ: { - long id = readID(); - int threadSeq = in.readInt(); - int stackSeq = in.readInt(); - bytesLeft -= identifierSize + 8; - threadObjects.put(threadSeq, - new ThreadObject(id, stackSeq)); - break; - } - case HPROF_GC_ROOT_JNI_GLOBAL: { - long id = readID(); - long globalRefId = readID(); // Ignored, for now - bytesLeft -= 2*identifierSize; - snapshot.addRoot(new Root(id, 0, Root.NATIVE_STATIC, "")); - break; - } - case HPROF_GC_ROOT_JNI_LOCAL: { - long id = readID(); - int threadSeq = in.readInt(); - int depth = in.readInt(); - bytesLeft -= identifierSize + 8; - ThreadObject to = getThreadObjectFromSequence(threadSeq); - StackTrace st = getStackTraceFromSerial(to.stackSeq); - if (st != null) { - st = st.traceForDepth(depth+1); - } - snapshot.addRoot(new Root(id, to.threadId, - Root.NATIVE_LOCAL, "", st)); - break; - } - case HPROF_GC_ROOT_JAVA_FRAME: { - long id = readID(); - int threadSeq = in.readInt(); - int depth = in.readInt(); - bytesLeft -= identifierSize + 8; - ThreadObject to = getThreadObjectFromSequence(threadSeq); - StackTrace st = getStackTraceFromSerial(to.stackSeq); - if (st != null) { - st = st.traceForDepth(depth+1); - } - snapshot.addRoot(new Root(id, to.threadId, - Root.JAVA_LOCAL, "", st)); - break; - } - case HPROF_GC_ROOT_NATIVE_STACK: { - long id = readID(); - int threadSeq = in.readInt(); - bytesLeft -= identifierSize + 4; - ThreadObject to = getThreadObjectFromSequence(threadSeq); - StackTrace st = getStackTraceFromSerial(to.stackSeq); - snapshot.addRoot(new Root(id, to.threadId, - Root.NATIVE_STACK, "", st)); - break; - } - case HPROF_GC_ROOT_STICKY_CLASS: { - long id = readID(); - bytesLeft -= identifierSize; - snapshot.addRoot(new Root(id, 0, Root.SYSTEM_CLASS, "")); - break; - } - case HPROF_GC_ROOT_THREAD_BLOCK: { - long id = readID(); - int threadSeq = in.readInt(); - bytesLeft -= identifierSize + 4; - ThreadObject to = getThreadObjectFromSequence(threadSeq); - StackTrace st = getStackTraceFromSerial(to.stackSeq); - snapshot.addRoot(new Root(id, to.threadId, - Root.THREAD_BLOCK, "", st)); - break; - } - case HPROF_GC_ROOT_MONITOR_USED: { - long id = readID(); - bytesLeft -= identifierSize; - snapshot.addRoot(new Root(id, 0, Root.BUSY_MONITOR, "")); - break; - } - case HPROF_GC_CLASS_DUMP: { - int bytesRead = readClass(); - bytesLeft -= bytesRead; - break; - } - case HPROF_GC_INSTANCE_DUMP: { - int bytesRead = readInstance(); - bytesLeft -= bytesRead; - break; - } - case HPROF_GC_OBJ_ARRAY_DUMP: { - long bytesRead = readArray(false); - bytesLeft -= bytesRead; - break; - } - case HPROF_GC_PRIM_ARRAY_DUMP: { - long bytesRead = readArray(true); - bytesLeft -= bytesRead; - break; - } - default: { - throw new IOException("Unrecognized heap dump sub-record type: " + type); - } - } - } - if (bytesLeft != 0) { - warn("Error reading heap dump or heap dump segment: Byte count is " + bytesLeft + " instead of 0"); - skipBytes(bytesLeft); - } - if (debugLevel > 0) { - System.out.println(" Finished heap sub-records."); - } - } - - private long readID() throws IOException { - return (identifierSize == 4)? - (Snapshot.SMALL_ID_MASK & (long)in.readInt()) : in.readLong(); - } - - // - // Read a java value. If result is non-null, it's expected to be an - // array of one element. We use it to fake multiple return values. - // @returns the number of bytes read - // - private int readValue(JavaThing[] resultArr) throws IOException { - byte type = in.readByte(); - return 1 + readValueForType(type, resultArr); - } - - private int readValueForType(byte type, JavaThing[] resultArr) - throws IOException { - if (version >= VERSION_JDK12BETA4) { - type = signatureFromTypeId(type); - } - return readValueForTypeSignature(type, resultArr); - } - - private int readValueForTypeSignature(byte type, JavaThing[] resultArr) - throws IOException { - switch (type) { - case '[': - case 'L': { - long id = readID(); - if (resultArr != null) { - resultArr[0] = new JavaObjectRef(id); - } - return identifierSize; - } - case 'Z': { - int b = in.readByte(); - if (b != 0 && b != 1) { - warn("Illegal boolean value read"); - } - if (resultArr != null) { - resultArr[0] = new JavaBoolean(b != 0); - } - return 1; - } - case 'B': { - byte b = in.readByte(); - if (resultArr != null) { - resultArr[0] = new JavaByte(b); - } - return 1; - } - case 'S': { - short s = in.readShort(); - if (resultArr != null) { - resultArr[0] = new JavaShort(s); - } - return 2; - } - case 'C': { - char ch = in.readChar(); - if (resultArr != null) { - resultArr[0] = new JavaChar(ch); - } - return 2; - } - case 'I': { - int val = in.readInt(); - if (resultArr != null) { - resultArr[0] = new JavaInt(val); - } - return 4; - } - case 'J': { - long val = in.readLong(); - if (resultArr != null) { - resultArr[0] = new JavaLong(val); - } - return 8; - } - case 'F': { - float val = in.readFloat(); - if (resultArr != null) { - resultArr[0] = new JavaFloat(val); - } - return 4; - } - case 'D': { - double val = in.readDouble(); - if (resultArr != null) { - resultArr[0] = new JavaDouble(val); - } - return 8; - } - default: { - throw new IOException("Bad value signature: " + type); - } - } - } - - private ThreadObject getThreadObjectFromSequence(int threadSeq) - throws IOException { - ThreadObject to = threadObjects.get(threadSeq); - if (to == null) { - throw new IOException("Thread " + threadSeq + - " not found for JNI local ref"); - } - return to; - } - - private String getNameFromID(long id) throws IOException { - return getNameFromID(Long.valueOf(id)); - } - - private String getNameFromID(Long id) throws IOException { - if (id.longValue() == 0L) { - return ""; - } - String result = names.get(id); - if (result == null) { - warn("Name not found at " + toHex(id.longValue())); - return "unresolved name " + toHex(id.longValue()); - } - return result; - } - - private StackTrace getStackTraceFromSerial(int ser) throws IOException { - if (stackTraces == null) { - return null; - } - StackTrace result = stackTraces.get(ser); - if (result == null) { - warn("Stack trace not found for serial # " + ser); - } - return result; - } - - // - // Handle a HPROF_GC_CLASS_DUMP - // Return number of bytes read - // - private int readClass() throws IOException { - long id = readID(); - StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); - long superId = readID(); - long classLoaderId = readID(); - long signersId = readID(); - long protDomainId = readID(); - long reserved1 = readID(); - long reserved2 = readID(); - int instanceSize = in.readInt(); - int bytesRead = 7 * identifierSize + 8; - - int numConstPoolEntries = in.readUnsignedShort(); - bytesRead += 2; - for (int i = 0; i < numConstPoolEntries; i++) { - int index = in.readUnsignedShort(); // unused - bytesRead += 2; - bytesRead += readValue(null); // We ignore the values - } - - int numStatics = in.readUnsignedShort(); - bytesRead += 2; - JavaThing[] valueBin = new JavaThing[1]; - JavaStatic[] statics = new JavaStatic[numStatics]; - for (int i = 0; i < numStatics; i++) { - long nameId = readID(); - bytesRead += identifierSize; - byte type = in.readByte(); - bytesRead++; - bytesRead += readValueForType(type, valueBin); - String fieldName = getNameFromID(nameId); - if (version >= VERSION_JDK12BETA4) { - type = signatureFromTypeId(type); - } - String signature = "" + ((char) type); - JavaField f = new JavaField(fieldName, signature); - statics[i] = new JavaStatic(f, valueBin[0]); - } - - int numFields = in.readUnsignedShort(); - bytesRead += 2; - JavaField[] fields = new JavaField[numFields]; - for (int i = 0; i < numFields; i++) { - long nameId = readID(); - bytesRead += identifierSize; - byte type = in.readByte(); - bytesRead++; - String fieldName = getNameFromID(nameId); - if (version >= VERSION_JDK12BETA4) { - type = signatureFromTypeId(type); - } - String signature = "" + ((char) type); - fields[i] = new JavaField(fieldName, signature); - } - String name = classNameFromObjectID.get(id); - if (name == null) { - warn("Class name not found for " + toHex(id)); - name = "unknown-name@" + toHex(id); - } - JavaClass c = new JavaClass(id, name, superId, classLoaderId, signersId, - protDomainId, fields, statics, - instanceSize); - snapshot.addClass(id, c); - snapshot.setSiteTrace(c, stackTrace); - - return bytesRead; - } - - private String toHex(long addr) { - return jdk.test.lib.hprof.util.Misc.toHex(addr); - } - - // - // Handle a HPROF_GC_INSTANCE_DUMP - // Return number of bytes read - // - private int readInstance() throws IOException { - long start = in.position(); - long id = readID(); - StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); - long classID = readID(); - JavaClass searchedClass = snapshot.findClass( - "0x" + Long.toHexString(classID)); - if (searchedClass == null) { - throw new IOException( - "Class Record for 0x" + Long.toHexString(classID) + " not found"); - } - int bytesFollowing = in.readInt(); - int bytesRead = (2 * identifierSize) + 8 + bytesFollowing; - JavaObject jobj = new JavaObject(classID, start); - skipBytes(bytesFollowing); - snapshot.addHeapObject(id, jobj); - snapshot.setSiteTrace(jobj, stackTrace); - return bytesRead; - } - - // - // Handle a HPROF_GC_OBJ_ARRAY_DUMP or HPROF_GC_PRIM_ARRAY_DUMP - // Return number of bytes read - // - private long readArray(boolean isPrimitive) throws IOException { - long start = in.position(); - long id = readID(); - StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); - int num = in.readInt(); - long bytesRead = identifierSize + 8; - long elementClassID; - if (isPrimitive) { - elementClassID = in.readByte(); - bytesRead++; - } else { - elementClassID = readID(); - bytesRead += identifierSize; - } - - // Check for primitive arrays: - byte primitiveSignature = 0x00; - int elSize = 0; - if (isPrimitive || version < VERSION_JDK12BETA4) { - switch ((int)elementClassID) { - case T_BOOLEAN: { - primitiveSignature = (byte) 'Z'; - elSize = 1; - break; - } - case T_CHAR: { - primitiveSignature = (byte) 'C'; - elSize = 2; - break; - } - case T_FLOAT: { - primitiveSignature = (byte) 'F'; - elSize = 4; - break; - } - case T_DOUBLE: { - primitiveSignature = (byte) 'D'; - elSize = 8; - break; - } - case T_BYTE: { - primitiveSignature = (byte) 'B'; - elSize = 1; - break; - } - case T_SHORT: { - primitiveSignature = (byte) 'S'; - elSize = 2; - break; - } - case T_INT: { - primitiveSignature = (byte) 'I'; - elSize = 4; - break; - } - case T_LONG: { - primitiveSignature = (byte) 'J'; - elSize = 8; - break; - } - } - if (version >= VERSION_JDK12BETA4 && primitiveSignature == 0x00) { - throw new IOException("Unrecognized typecode: " - + elementClassID); - } - } - if (primitiveSignature != 0x00) { - long size = elSize * (long)num; - bytesRead += size; - JavaValueArray va = new JavaValueArray(primitiveSignature, start); - skipBytes(size); - snapshot.addHeapObject(id, va); - snapshot.setSiteTrace(va, stackTrace); - } else { - long sz = (long)num * identifierSize; - bytesRead += sz; - JavaObjectArray arr = new JavaObjectArray(elementClassID, start); - skipBytes(sz); - snapshot.addHeapObject(id, arr); - snapshot.setSiteTrace(arr, stackTrace); - } - return bytesRead; - } - - private byte signatureFromTypeId(byte typeId) throws IOException { - switch (typeId) { - case T_CLASS: { - return (byte) 'L'; - } - case T_BOOLEAN: { - return (byte) 'Z'; - } - case T_CHAR: { - return (byte) 'C'; - } - case T_FLOAT: { - return (byte) 'F'; - } - case T_DOUBLE: { - return (byte) 'D'; - } - case T_BYTE: { - return (byte) 'B'; - } - case T_SHORT: { - return (byte) 'S'; - } - case T_INT: { - return (byte) 'I'; - } - case T_LONG: { - return (byte) 'J'; - } - default: { - throw new IOException("Invalid type id of " + typeId); - } - } - } - - private void handleEOF(EOFException exp, Snapshot snapshot) { - if (debugLevel > 0) { - exp.printStackTrace(); - } - warn("Unexpected EOF. Will miss information..."); - // we have EOF, we have to tolerate missing references - snapshot.setUnresolvedObjectsOK(true); - } - - private void warn(String msg) { - System.out.println("WARNING: " + msg); - } - - // - // A trivial data-holder class for HPROF_GC_ROOT_THREAD_OBJ. - // - private class ThreadObject { - - long threadId; - int stackSeq; - - ThreadObject(long threadId, int stackSeq) { - this.threadId = threadId; - this.stackSeq = stackSeq; - } - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,136 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; - -/** - * Implementation of ReadBuffer using mapped file buffer - * - * @author A. Sundararajan - */ -class MappedReadBuffer implements ReadBuffer { - private MappedByteBuffer buf; - private RandomAccessFile file; - - MappedReadBuffer(RandomAccessFile file, MappedByteBuffer buf) { - this.file = file; - this.buf = buf; - } - - /** - * Factory method to create correct ReadBuffer for a given file. - * - * The initial purpose of this method was to choose how to read hprof file for parsing - * depending on the size of the file and the system property 'jhat.disableFileMap': - * "If file size is more than 2 GB and when file mapping is configured (default), - * use mapped file reader". - * - * However, it has been discovered a problem with this approach. - * Creating java.nio.MappedByteBuffer from inside the test leads to hprof file - * is locked on Windows until test process dies since there is no good way to - * release this resource. - * - * java.nio.MappedByteBuffer will be used only if 'jhat.enableFileMap' is set to true. - * Per default 'jhat.enableFileMap' is not set. - */ - static ReadBuffer create(RandomAccessFile file) throws IOException { - if (canUseFileMap()) { - MappedByteBuffer buf; - try { - FileChannel ch = file.getChannel(); - long size = ch.size(); - buf = ch.map(FileChannel.MapMode.READ_ONLY, 0, size); - ch.close(); - return new MappedReadBuffer(file, buf); - } catch (IOException exp) { - exp.printStackTrace(); - System.err.println("File mapping failed, will use direct read"); - // fall through - } - } // else fall through - return new FileReadBuffer(file); - } - - /** - * Set system property 'jhat.enableFileMap' to 'true' to enable file mapping. - */ - private static boolean canUseFileMap() { - String prop = System.getProperty("jhat.enableFileMap"); - return prop != null && prop.equals("true"); - } - - private void seek(long pos) throws IOException { - assert pos <= Integer.MAX_VALUE : "position overflow"; - buf.position((int)pos); - } - - @Override - public synchronized char getChar(long pos) throws IOException { - seek(pos); - return buf.getChar(); - } - - @Override - public synchronized byte getByte(long pos) throws IOException { - seek(pos); - return buf.get(); - } - - @Override - public synchronized short getShort(long pos) throws IOException { - seek(pos); - return buf.getShort(); - } - - @Override - public synchronized int getInt(long pos) throws IOException { - seek(pos); - return buf.getInt(); - } - - @Override - public synchronized long getLong(long pos) throws IOException { - seek(pos); - return buf.getLong(); - } - - @Override - public void close() throws Exception { - file.close(); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.DataInputStream; -import java.io.InputStream; - -/** - * A DataInputStream that keeps track of total bytes read - * (in effect 'position' in stream) so far. - * - */ -public class PositionDataInputStream extends DataInputStream { - public PositionDataInputStream(InputStream in) { - super(in instanceof PositionInputStream? - in : new PositionInputStream(in)); - } - - public boolean markSupported() { - return false; - } - - public void mark(int readLimit) { - throw new UnsupportedOperationException("mark"); - } - - public void reset() { - throw new UnsupportedOperationException("reset"); - } - - public long position() { - return ((PositionInputStream)in).position(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * InputStream that keeps track of total bytes read (in effect - * 'position' in stream) from the input stream. - * - */ -public class PositionInputStream extends FilterInputStream { - private long position = 0L; - - public PositionInputStream(InputStream in) { - super(in); - } - - public int read() throws IOException { - int res = super.read(); - if (res != -1) position++; - return res; - } - - public int read(byte[] b, int off, int len) throws IOException { - int res = super.read(b, off, len); - if (res != -1) position += res; - return res; - } - - public long skip(long n) throws IOException { - long res = super.skip(n); - position += res; - return res; - } - - public boolean markSupported() { - return false; - } - - public void mark(int readLimit) { - throw new UnsupportedOperationException("mark"); - } - - public void reset() { - throw new UnsupportedOperationException("reset"); - } - - public long position() { - return position; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.IOException; - -/** - * Positionable read only buffer - * - * @author A. Sundararajan - */ -public interface ReadBuffer extends AutoCloseable { - public char getChar(long pos) throws IOException; - public byte getByte(long pos) throws IOException; - public short getShort(long pos) throws IOException; - public int getInt(long pos) throws IOException; - public long getLong(long pos) throws IOException; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/Reader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/Reader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/Reader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/parser/Reader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,135 +0,0 @@ -/* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.parser; - -import java.io.*; -import jdk.test.lib.hprof.model.*; - -/** - * Abstract base class for reading object dump files. A reader need not be - * thread-safe. - * - * @author Bill Foote - */ - - -public abstract class Reader { - protected PositionDataInputStream in; - - protected Reader(PositionDataInputStream in) { - this.in = in; - } - - /** - * Read a snapshot from a data input stream. It is assumed that the magic - * number has already been read. - */ - abstract public Snapshot read() throws IOException; - - /** - * Read a snapshot from a file. - * - * @param heapFile The name of a file containing a heap dump - * @param callStack If true, read the call stack of allocaation sites - */ - public static Snapshot readFile(String heapFile, boolean callStack, - int debugLevel) - throws IOException { - int dumpNumber = 1; - int pos = heapFile.lastIndexOf('#'); - if (pos > -1) { - String num = heapFile.substring(pos+1, heapFile.length()); - try { - dumpNumber = Integer.parseInt(num, 10); - } catch (java.lang.NumberFormatException ex) { - String msg = "In file name \"" + heapFile - + "\", a dump number was " - + "expected after the :, but \"" - + num + "\" was found instead."; - System.err.println(msg); - throw new IOException(msg); - } - heapFile = heapFile.substring(0, pos); - } - try (PositionDataInputStream in = new PositionDataInputStream( - new BufferedInputStream(new FileInputStream(heapFile)))) { - int i = in.readInt(); - if (i == HprofReader.MAGIC_NUMBER) { - Reader r - = new HprofReader(heapFile, in, dumpNumber, - callStack, debugLevel); - return r.read(); - } else { - throw new IOException("Unrecognized magic number: " + i); - } - } - } - - /** - * Get Stack Traces from a Hprof file. - * - * @param heapFile The name of a file containing a heap dump - */ - public static String getStack(String heapFile, int debugLevel) - throws IOException { - int dumpNumber = 1; - int pos = heapFile.lastIndexOf('#'); - if (pos > -1) { - String num = heapFile.substring(pos+1, heapFile.length()); - try { - dumpNumber = Integer.parseInt(num, 10); - } catch (java.lang.NumberFormatException ex) { - String msg = "In file name \"" + heapFile - + "\", a dump number was " - + "expected after the :, but \"" - + num + "\" was found instead."; - System.err.println(msg); - throw new IOException(msg); - } - heapFile = heapFile.substring(0, pos); - } - try (PositionDataInputStream in = new PositionDataInputStream( - new BufferedInputStream(new FileInputStream(heapFile)))) { - int i = in.readInt(); - if (i == HprofReader.MAGIC_NUMBER) { - HprofReader r - = new HprofReader(heapFile, in, dumpNumber, - true, debugLevel); - r.read(); - return r.printStackTraces(); - } else { - throw new IOException("Unrecognized magic number: " + i); - } - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,147 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.util; -import java.util.*; - -/** - * A singleton utility class that sorts an array of objects. - *

- * Use: - *

- *
- *  Stuff[] arr = ...;
- *  ArraySorter.sort(arr, new Comparer() {
- *      public int compare(Object lhs, Object rhs) {
- *          return ((String) lhs).compareTo((String) rhs);
- *      }
- *  });
- * 
- * - * @author Bill Foote - */ - -public class ArraySorter { - - /** - * Sort the given array, using c for comparison - **/ - static public void sort(Object[] arr, Comparer c) { - quickSort(arr, c, 0, arr.length-1); - } - - - /** - * Sort an array of strings, using String.compareTo() - **/ - static public void sortArrayOfStrings(Object[] arr) { - sort(arr, new Comparer() { - public int compare(Object lhs, Object rhs) { - return ((String) lhs).compareTo((String) rhs); - } - }); - } - - - static private void swap(Object[] arr, int a, int b) { - Object tmp = arr[a]; - arr[a] = arr[b]; - arr[b] = tmp; - } - - // - // Sorts arr between from and to, inclusive. This is a quick, off-the-top- - // of-my-head quicksort: I haven't put any thought into optimizing it. - // I _did_ put thought into making sure it's safe (it will always - // terminate). Worst-case it's O(n^2), but it will usually run in - // in O(n log n). It's well-behaved if the list is already sorted, - // or nearly so. - // - static private void quickSort(Object[] arr, Comparer c, int from, int to) { - if (to <= from) - return; - int mid = (from + to) / 2; - if (mid != from) - swap(arr, mid, from); - Object pivot = arr[from]; // Simple-minded, but reasonable - int highestBelowPivot = from - 1; - int low = from+1; - int high = to; - // We now move low and high toward each other, maintaining the - // invariants: - // arr[i] <= pivot for all i < low - // arr[i] > pivot for all i > high - // As long as these invariants hold, and every iteration makes - // progress, we are safe. - while (low <= high) { - int cmp = c.compare(arr[low], pivot); - if (cmp <= 0) { // arr[low] <= pivot - if (cmp < 0) { - highestBelowPivot = low; - } - low++; - } else { - int c2; - for (;;) { - // arr[high] > pivot: - c2 = c.compare(arr[high], pivot); - if (c2 > 0) { - high--; - if (low > high) { - break; - } - } else { - break; - } - } - // At this point, low is never == high, BTW - if (low <= high) { - swap(arr, low, high); - if (c2 < 0) { - highestBelowPivot = low; - } - low++; - high--; - } - } - } - // At this point, low == high+1 - // Now we just need to sort from from..highestBelowPivot - // and from high+1..to - if (highestBelowPivot > from) { - // pivot == pivot, so ensure algorithm terminates - swap(arr, from, highestBelowPivot); - quickSort(arr, c, from, highestBelowPivot-1); - } - quickSort(arr, c, high+1, to); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Comparer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Comparer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Comparer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Comparer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.util; - -/** - * Base class for comparison of two objects. - * @see VectorSorter - * - * @author Bill Foote - */ - -abstract public class Comparer { - - /** - * @return a number <, == or > 0 depending on lhs compared to rhs - * @see java.lang.String.compareTo - **/ - abstract public int compare(Object lhs, Object rhs); -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.util; - -import java.util.Enumeration; -import java.util.NoSuchElementException; -import jdk.test.lib.hprof.model.JavaHeapObject; - -public class CompositeEnumeration implements Enumeration { - Enumeration e1; - Enumeration e2; - - public CompositeEnumeration(Enumeration e1, Enumeration e2) { - this.e1 = e1; - this.e2 = e2; - } - - public boolean hasMoreElements() { - return e1.hasMoreElements() || e2.hasMoreElements(); - } - - public JavaHeapObject nextElement() { - if (e1.hasMoreElements()) { - return e1.nextElement(); - } - - if (e2.hasMoreElements()) { - return e2.nextElement(); - } - - throw new NoSuchElementException(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Misc.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Misc.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Misc.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/Misc.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.util; -import java.util.*; - -/** - * Miscellaneous functions I couldn't think of a good place to put. - * - * @author Bill Foote - */ - - -public class Misc { - - private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - public final static String toHex(int addr) { - char[] buf = new char[8]; - int i = 0; - for (int s = 28; s >= 0; s -= 4) { - buf[i++] = digits[(addr >> s) & 0xf]; - } - return "0x" + new String(buf); - } - - public final static String toHex(long addr) { - return "0x" + Long.toHexString(addr); - } - - public final static long parseHex(String value) { - long result = 0; - if (value.length() < 2 || value.charAt(0) != '0' || - value.charAt(1) != 'x') { - return -1L; - } - for(int i = 2; i < value.length(); i++) { - result *= 16; - char ch = value.charAt(i); - if (ch >= '0' && ch <= '9') { - result += (ch - '0'); - } else if (ch >= 'a' && ch <= 'f') { - result += (ch - 'a') + 10; - } else if (ch >= 'A' && ch <= 'F') { - result += (ch - 'A') + 10; - } else { - throw new NumberFormatException("" + ch - + " is not a valid hex digit"); - } - } - return result; - } - - public static String encodeHtml(String str) { - final int len = str.length(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < len; i++) { - char ch = str.charAt(i); - if (ch == '<') { - sb.append("<"); - } else if (ch == '>') { - sb.append(">"); - } else if (ch == '"') { - sb.append("""); - } else if (ch == '\'') { - sb.append("'"); - } else if (ch == '&') { - sb.append("&"); - } else if (ch < ' ') { - sb.append("&#").append((int)ch).append(';'); - } else { - int c = (ch & 0xFFFF); - if (c > 127) { - sb.append("&#").append(c).append(';'); - } else { - sb.append(ch); - } - } - } - return sb.toString(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -/* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - * The Original Code is HAT. The Initial Developer of the - * Original Code is Bill Foote, with contributions from others - * at JavaSoft/Sun. - */ - -package jdk.test.lib.hprof.util; -import java.util.*; - -/** - * A singleton utility class that sorts a vector. - *

- * Use: - *

- *
- *  Vector v =   ;
- *  VectorSorter.sort(v, new Comparer() {
- *      public int compare(Object lhs, Object rhs) {
- *          return ((String) lhs).compareTo((String) rhs);
- *      }
- *  });
- * 
- * - * @author Bill Foote - */ - - -public class VectorSorter { - - /** - * Sort the given vector, using c for comparison - **/ - static public void sort(Vector v, Comparer c) { - quickSort(v, c, 0, v.size()-1); - } - - - /** - * Sort a vector of strings, using String.compareTo() - **/ - static public void sortVectorOfStrings(Vector v) { - sort(v, new Comparer() { - public int compare(Object lhs, Object rhs) { - return ((String) lhs).compareTo((String) rhs); - } - }); - } - - - static private void swap(Vector v, int a, int b) { - Object tmp = v.elementAt(a); - v.setElementAt(v.elementAt(b), a); - v.setElementAt(tmp, b); - } - - // - // Sorts v between from and to, inclusive. This is a quick, off-the-top- - // of-my-head quicksort: I haven't put any thought into optimizing it. - // I _did_ put thought into making sure it's safe (it will always - // terminate). Worst-case it's O(n^2), but it will usually run in - // in O(n log n). It's well-behaved if the list is already sorted, - // or nearly so. - // - static private void quickSort(Vector v, Comparer c, int from, int to) { - if (to <= from) - return; - int mid = (from + to) / 2; - if (mid != from) - swap(v, mid, from); - Object pivot = v.elementAt(from); - // Simple-minded, but reasonable - int highestBelowPivot = from - 1; - int low = from+1; - int high = to; - // We now move low and high toward eachother, maintaining the - // invariants: - // v[i] <= pivot for all i < low - // v[i] > pivot for all i > high - // As long as these invariants hold, and every iteration makes - // progress, we are safe. - while (low <= high) { - int cmp = c.compare(v.elementAt(low), pivot); - if (cmp <= 0) { // v[low] <= pivot - if (cmp < 0) { - highestBelowPivot = low; - } - low++; - } else { - int c2; - for (;;) { - c2 = c.compare(v.elementAt(high), pivot); - // v[high] > pivot: - if (c2 > 0) { - high--; - if (low > high) { - break; - } - } else { - break; - } - } - // At this point, low is never == high - if (low <= high) { - swap(v, low, high); - if (c2 < 0) { - highestBelowPivot = low; - } - low++; - high--; - } - } - } - // Now we just need to sort from from..highestBelowPivot - // and from high+1..to - if (highestBelowPivot > from) { - // pivot == pivot, so ensure algorithm terminates - swap(v, from, highestBelowPivot); - quickSort(v, c, from, highestBelowPivot-1); - } - quickSort(v, c, high+1, to); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - - -/** - * Helper class for running applications with enabled JFR recording - */ -public class AppExecutorHelper { - - /** - * Executes an application with enabled JFR and writes collected events - * to the given output file. - * Which events to track and other parameters are taken from the setting .jfc file. - * - * @param setting JFR settings file(optional) - * @param jfrFilename JFR resulting recording filename(optional) - * @param additionalVMFlags additional VM flags passed to the java(optional) - * @param className name of the class to execute - * @param classArguments arguments passed to the class(optional) - * @return output analyzer for executed application - */ - public static OutputAnalyzer executeAndRecord(String settings, String jfrFilename, String[] additionalVmFlags, - String className, String... classArguments) throws Exception { - List arguments = new ArrayList<>(); - String baseStartFlightRecording = "-XX:StartFlightRecording"; - String additionalStartFlightRecording = ""; - - if (additionalVmFlags != null) { - Collections.addAll(arguments, additionalVmFlags); - } - - if (settings != null & jfrFilename != null) { - additionalStartFlightRecording = String.format("=settings=%s,filename=%s", settings, jfrFilename); - } else if (settings != null) { - additionalStartFlightRecording = String.format("=settings=%s", settings); - } else if (jfrFilename != null) { - additionalStartFlightRecording = String.format("=filename=%s", jfrFilename); - } - arguments.add(baseStartFlightRecording + additionalStartFlightRecording); - - arguments.add(className); - if (classArguments.length > 0) { - Collections.addAll(arguments, classArguments); - } - - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, arguments.toArray(new String[0])); - return ProcessTools.executeProcess(pb); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/CommonHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/CommonHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/CommonHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/CommonHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import static jdk.test.lib.Asserts.assertEquals; -import static jdk.test.lib.Asserts.fail; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import jdk.jfr.Recording; -import jdk.jfr.RecordingState; -import jdk.jfr.consumer.RecordedEvent; -import jdk.jfr.consumer.RecordingFile; -import jdk.test.lib.Asserts; -import jdk.test.lib.Utils; - - -/** - * Common helper class. - */ -public final class CommonHelper { - - private static RecordedEvent timeStampCounterEvent; - - public static void verifyException(VoidFunction f, String msg, Class expectedException) throws Throwable { - try { - f.run(); - } catch (Throwable t) { - if (expectedException.isAssignableFrom(t.getClass())) { - return; - } - t.printStackTrace(); - assertEquals(t.getClass(), expectedException, "Wrong exception class"); - } - fail("Missing Exception for: " + msg); - } - - public static Recording verifyExists(long recId, List recordings) { - for (Recording r : recordings) { - if (recId == r.getId()) { - return r; - } - } - Asserts.fail("Recording not found, id=" + recId); - return null; - } - - - public static void waitForRecordingState(Recording r, RecordingState expectedState) throws Exception { - while (r.getState() != expectedState) { - Thread.sleep(20); - } - } - - public static void verifyRecordingState(Recording r, RecordingState expectedState) throws Exception { - assertEquals(expectedState, r.getState(), "Wrong state"); - } - - public static boolean hasFastTimeEnabled() throws Exception { - return getTimeStampCounterEvent().getValue("fastTimeEnabled"); - } - - private synchronized static RecordedEvent getTimeStampCounterEvent() throws IOException, Exception { - if (timeStampCounterEvent == null) { - try (Recording r = new Recording()) { - r.enable(EventNames.CPUTimeStampCounter); - r.start(); - r.stop(); - Path p = Utils.createTempFile("timestamo", ".jfr"); - r.dump(p); - List events = RecordingFile.readAllEvents(p); - Files.deleteIfExists(p); - if (events.isEmpty()) { - throw new Exception("Could not locate CPUTimeStampCounter event"); - } - timeStampCounterEvent = events.get(0); - } - } - return timeStampCounterEvent; - } - - public static void waitForSystemCurrentMillisToChange() { - long t = System.currentTimeMillis(); - while (t == System.currentTimeMillis()) { - try { - Thread.sleep(2); - } catch (InterruptedException e) { - throw new Error("Sleep interupted", e); - } - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventField.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventField.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventField.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventField.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import jdk.jfr.ValueDescriptor; -import jdk.jfr.consumer.RecordedObject; -import jdk.test.lib.Asserts; - - -public final class EventField { - public final RecordedObject event; - public final ValueDescriptor desc; - - public EventField(RecordedObject event, ValueDescriptor valueDescriptor) { - this.event = event; - this.desc = valueDescriptor; - } - - @SuppressWarnings("unchecked") - public > boolean isEqual(T value) { - return value == (T)getValue(); - } - - @SuppressWarnings("unchecked") - public > EventField equal(T value) { - doAssert(()-> Asserts.assertEquals((T)getValue(), value, getErrMsg("Value not equal to " + value))); - return this; - } - - @SuppressWarnings("unchecked") - public > EventField notEqual(T value) { - doAssert(()-> Asserts.assertNotEquals((T)getValue(), value, getErrMsg("Value equal to " + value))); - return this; - } - - @SuppressWarnings("unchecked") - public > EventField above(T value) { - doAssert(()-> Asserts.assertGreaterThan((T)getValue(), value, getErrMsg("Value not above " + value))); - return this; - } - - @SuppressWarnings("unchecked") - public > EventField below(T value) { - doAssert(()-> Asserts.assertLessThan((T)getValue(), value, getErrMsg("Value not below " + value))); - return this; - } - - @SuppressWarnings("unchecked") - public > EventField atLeast(T value) { - doAssert(()-> Asserts.assertGreaterThanOrEqual((T)getValue(), value, getErrMsg("Value not atLeast" + value))); - return this; - } - - @SuppressWarnings("unchecked") - public > EventField atMost(T value) { - doAssert(()-> Asserts.assertLessThanOrEqual((T)getValue(), value, getErrMsg("Value not atMost " + value))); - return this; - } - - public > EventField instring(String part) { - final String value = getValue(); - doAssert(()-> Asserts.assertTrue(value.contains(part), getErrMsg("Value does not contain '" + part +"'"))); - return this; - } - - @SuppressWarnings("unchecked") - public T getValue() { - return (T)event.getValue(desc.getName()); - } - - public EventField notNull() { - doAssert(()-> Asserts.assertNotNull(getValue(), getErrMsg("Field is null"))); - return this; - } - - public EventField isNull() { - doAssert(()-> Asserts.assertNull(getValue(), getErrMsg("Field is not null"))); - return this; - } - - public EventField notEmpty() { - notNull(); - final String s = getValue(); - doAssert(()-> Asserts.assertFalse(s.isEmpty(), getErrMsg("Field is empty"))); - return this; - } - - private void doAssert(AssertFunction f) { - try { - f.doAssert(); - } catch (RuntimeException e) { - System.out.printf("Error: %s%nFailed event:%n%s%n", e.getMessage(), event.toString()); - throw e; - } - } - - public EventField containsAny(String... allowed) { - final String value = getValue(); - final List allowedValues = Arrays.asList(allowed); - boolean contains = false; - for(String allowedValue : allowed) { - if (value.contains(allowedValue)) { - contains = true; - } - } - if (!contains) { - doAssert(()-> Asserts.fail(getErrMsg(String.format("Value not in (%s)", - allowedValues.stream().collect(Collectors.joining(", ")))))); - } - return this; - } - - private String getErrMsg(String msg) { - final String name = desc.getName(); - final Object value = event.getValue(name); - return String.format("%s, field='%s', value='%s'", msg, name, value); - } - - @FunctionalInterface - public interface AssertFunction { - void doAssert(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventNames.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventNames.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventNames.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventNames.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import jdk.jfr.EventType; - -/** - * Contains id for events that are shipped with the JDK. - * - */ -public class EventNames { - - public final static String PREFIX = "jdk."; - private static final String GC_CATEGORY = "GC"; - - // JVM Configuration - public final static String JVMInformation = PREFIX + "JVMInformation"; - public final static String InitialSystemProperty = PREFIX + "InitialSystemProperty"; - public final static String IntFlag = PREFIX + "IntFlag"; - public final static String UnsignedIntFlag = PREFIX + "UnsignedIntFlag"; - public final static String LongFlag = PREFIX + "LongFlag"; - public final static String UnsignedLongFlag = PREFIX + "UnsignedLongFlag"; - public final static String DoubleFlag = PREFIX + "DoubleFlag"; - public final static String BooleanFlag = PREFIX + "BooleanFlag"; - public final static String StringFlag = PREFIX + "StringFlag"; - public final static String IntFlagChanged = PREFIX + "IntFlagChanged"; - public final static String UnsignedIntFlagChanged = PREFIX + "UnsignedIntFlagChanged"; - public final static String LongFlagChanged = PREFIX + "LongFlagChanged"; - public final static String UnsignedLongFlagChanged = PREFIX + "UnsignedLongFlagChanged"; - public final static String DoubleFlagChanged = PREFIX + "DoubleFlagChanged"; - public final static String BooleanFlagChanged = PREFIX + "BooleanFlagChanged"; - public final static String StringFlagChanged = PREFIX + "StringFlagChanged"; - - // Runtime - public final static String ThreadStart = PREFIX + "ThreadStart"; - public final static String ThreadEnd = PREFIX + "ThreadEnd"; - public final static String ThreadSleep = PREFIX + "ThreadSleep"; - public final static String ThreadPark = PREFIX + "ThreadPark"; - public final static String JavaMonitorEnter = PREFIX + "JavaMonitorEnter"; - public final static String JavaMonitorWait = PREFIX + "JavaMonitorWait"; - public final static String JavaMonitorInflate = PREFIX + "JavaMonitorInflate"; - public final static String ClassLoad = PREFIX + "ClassLoad"; - public final static String ClassDefine = PREFIX + "ClassDefine"; - public final static String ClassUnload = PREFIX + "ClassUnload"; - public final static String SafepointBegin = PREFIX + "SafepointBegin"; - public final static String SafepointStateSynchronization = PREFIX + "SafepointStateSynchronization"; - public final static String SafepointWaitBlocked = PREFIX + "SafepointWaitBlocked"; - public final static String SafepointCleanup = PREFIX + "SafepointCleanup"; - public final static String SafepointCleanupTask = PREFIX + "SafepointCleanupTask"; - public final static String SafepointEnd = PREFIX + "SafepointEnd"; - public final static String ExecuteVMOperation = PREFIX + "ExecuteVMOperation"; - public final static String Shutdown = PREFIX + "Shutdown"; - public final static String JavaThreadStatistics = PREFIX + "JavaThreadStatistics"; - public final static String ClassLoadingStatistics = PREFIX + "ClassLoadingStatistics"; - public final static String ClassLoaderStatistics = PREFIX + "ClassLoaderStatistics"; - public final static String ThreadAllocationStatistics = PREFIX + "ThreadAllocationStatistics"; - public final static String ExecutionSample = PREFIX + "ExecutionSample"; - public final static String NativeMethodSample = PREFIX + "NativeMethodSample"; - public final static String ThreadDump = PREFIX + "ThreadDump"; - public final static String OldObjectSample = PREFIX + "OldObjectSample"; - public final static String BiasedLockRevocation = PREFIX + "BiasedLockRevocation"; - public final static String BiasedLockSelfRevocation = PREFIX + "BiasedLockSelfRevocation"; - public final static String BiasedLockClassRevocation = PREFIX + "BiasedLockClassRevocation"; - // This event is hard to test - public final static String ReservedStackActivation = PREFIX + "ReservedStackActivation"; - - // GC - public final static String GCHeapSummary = PREFIX + "GCHeapSummary"; - public final static String MetaspaceSummary = PREFIX + "MetaspaceSummary"; - public final static String MetaspaceGCThreshold = PREFIX + "MetaspaceGCThreshold"; - public final static String MetaspaceAllocationFailure = PREFIX + "MetaspaceAllocationFailure"; - public final static String MetaspaceOOM = PREFIX + "MetaspaceOOM"; - public final static String MetaspaceChunkFreeListSummary = PREFIX + "MetaspaceChunkFreeListSummary"; - public final static String PSHeapSummary = PREFIX + "PSHeapSummary"; - public final static String G1HeapSummary = PREFIX + "G1HeapSummary"; - public final static String G1HeapRegionInformation = PREFIX + "G1HeapRegionInformation"; - public final static String G1HeapRegionTypeChange = PREFIX + "G1HeapRegionTypeChange"; - public final static String TenuringDistribution = PREFIX + "TenuringDistribution"; - public final static String GarbageCollection = PREFIX + "GarbageCollection"; - public final static String ParallelOldGarbageCollection = PREFIX + "ParallelOldGarbageCollection"; - public final static String ParallelOldCollection = ParallelOldGarbageCollection; - public final static String YoungGarbageCollection = PREFIX + "YoungGarbageCollection"; - public final static String OldGarbageCollection = PREFIX + "OldGarbageCollection"; - public final static String G1GarbageCollection = PREFIX + "G1GarbageCollection"; - public final static String G1MMU = PREFIX + "G1MMU"; - public final static String EvacuationInformation = PREFIX + "EvacuationInformation"; - public final static String GCReferenceStatistics = PREFIX + "GCReferenceStatistics"; - public final static String ObjectCountAfterGC = PREFIX + "ObjectCountAfterGC"; - public final static String PromoteObjectInNewPLAB = PREFIX + "PromoteObjectInNewPLAB"; - public final static String PromoteObjectOutsidePLAB = PREFIX + "PromoteObjectOutsidePLAB"; - public final static String PromotionFailed = PREFIX + "PromotionFailed"; - public final static String EvacuationFailed = PREFIX + "EvacuationFailed"; - public final static String ConcurrentModeFailure = PREFIX + "ConcurrentModeFailure"; - public final static String GCPhasePause = PREFIX + "GCPhasePause"; - public final static String GCPhasePauseLevel1 = PREFIX + "GCPhasePauseLevel1"; - public final static String GCPhasePauseLevel2 = PREFIX + "GCPhasePauseLevel2"; - public final static String GCPhasePauseLevel3 = PREFIX + "GCPhasePauseLevel3"; - public final static String GCPhasePauseLevel4 = PREFIX + "GCPhasePauseLevel4"; - public final static String ObjectCount = PREFIX + "ObjectCount"; - public final static String GCConfiguration = PREFIX + "GCConfiguration"; - public final static String GCSurvivorConfiguration = PREFIX + "GCSurvivorConfiguration"; - public final static String GCTLABConfiguration = PREFIX + "GCTLABConfiguration"; - public final static String GCHeapConfiguration = PREFIX + "GCHeapConfiguration"; - public final static String YoungGenerationConfiguration = PREFIX + "YoungGenerationConfiguration"; - public final static String G1AdaptiveIHOP = PREFIX + "G1AdaptiveIHOP"; - public final static String G1EvacuationYoungStatistics = PREFIX + "G1EvacuationYoungStatistics"; - public final static String G1EvacuationOldStatistics = PREFIX + "G1EvacuationOldStatistics"; - public final static String G1BasicIHOP = PREFIX + "G1BasicIHOP"; - public final static String AllocationRequiringGC = PREFIX + "AllocationRequiringGC"; - public final static String GCPhaseConcurrent = PREFIX + "GCPhaseConcurrent"; - - // Compiler - public final static String Compilation = PREFIX + "Compilation"; - public final static String CompilerPhase = PREFIX + "CompilerPhase"; - public final static String CompilationFailure = PREFIX + "CompilationFailure"; - public final static String CompilerInlining = PREFIX + "CompilerInlining"; - public final static String CompilerStatistics = PREFIX + "CompilerStatistics"; - public final static String CompilerConfiguration = PREFIX + "CompilerConfiguration"; - public final static String CodeCacheStatistics = PREFIX + "CodeCacheStatistics"; - public final static String CodeCacheConfiguration = PREFIX + "CodeCacheConfiguration"; - public final static String CodeSweeperStatistics = PREFIX + "CodeSweeperStatistics"; - public final static String CodeSweeperConfiguration = PREFIX + "CodeSweeperConfiguration"; - public final static String SweepCodeCache = PREFIX + "SweepCodeCache"; - public final static String CodeCacheFull = PREFIX + "CodeCacheFull"; - public final static String ObjectAllocationInNewTLAB = PREFIX + "ObjectAllocationInNewTLAB"; - public final static String ObjectAllocationOutsideTLAB = PREFIX + "ObjectAllocationOutsideTLAB"; - - // OS - public final static String OSInformation = PREFIX + "OSInformation"; - public final static String CPUInformation = PREFIX + "CPUInformation"; - public final static String CPULoad = PREFIX + "CPULoad"; - public final static String ThreadCPULoad = PREFIX + "ThreadCPULoad"; - public final static String SystemProcess = PREFIX + "SystemProcess"; - public final static String ThreadContextSwitchRate = PREFIX + "ThreadContextSwitchRate"; - public final static String InitialEnvironmentVariable = PREFIX + "InitialEnvironmentVariable"; - public final static String NativeLibrary = PREFIX + "NativeLibrary"; - public final static String PhysicalMemory = PREFIX + "PhysicalMemory"; - public final static String NetworkUtilization = PREFIX + "NetworkUtilization"; - - // JDK - public static final String FileForce = PREFIX + "FileForce"; - public static final String FileRead = PREFIX + "FileRead"; - public static final String FileWrite = PREFIX + "FileWrite"; - public static final String SocketRead = PREFIX + "SocketRead"; - public static final String SocketWrite = PREFIX + "SocketWrite"; - public final static String ExceptionStatistics = PREFIX + "ExceptionStatistics"; - public final static String JavaExceptionThrow = PREFIX + "JavaExceptionThrow"; - public final static String JavaErrorThrow = PREFIX + "JavaErrorThrow"; - - // Flight Recorder - public final static String DumpReason = PREFIX + "DumpReason"; - public final static String DataLoss = PREFIX + "DataLoss"; - public final static String CPUTimeStampCounter = PREFIX + "CPUTimeStampCounter"; - public final static String ActiveRecording = PREFIX + "ActiveRecording"; - public final static String ActiveSetting = PREFIX + "ActiveSetting"; - - public static boolean isGcEvent(EventType et) { - return et.getCategoryNames().contains(GC_CATEGORY); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import java.util.ArrayList; -import java.util.List; - -import jdk.jfr.AnnotationElement; -import jdk.jfr.Name; -import jdk.jfr.ValueDescriptor; - -public final class EventTypePrototype { - private final List fields; - private final List annotations; - private final String name; - - public EventTypePrototype(String name, List as, List fields) { - this.annotations = new ArrayList<>(as); - this.annotations.add(new AnnotationElement(Name.class, name)); - this.fields = fields; - this.name = name; - } - - public EventTypePrototype(String name) { - this(name, new ArrayList<>(), new ArrayList<>()); - } - - public int getFieldIndex(String key) { - int index = 0; - for (ValueDescriptor f : fields) { - if (f.getName().equals(key)) { - return index; - } - index++; - } - throw new NoSuchFieldError(key); - } - - public void addField(ValueDescriptor fieldDescriptor) { - fields.add(fieldDescriptor); - } - - public void addAnnotation(AnnotationElement annotation) { - annotations.add(annotation); - } - - public List getFields() { - return fields; - } - - public List getAnnotations() { - return annotations; - } - - public String getName() { - return name; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventVerifier.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventVerifier.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventVerifier.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/EventVerifier.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import jdk.jfr.consumer.RecordedEvent; - -public abstract class EventVerifier { - protected final RecordedEvent event; - - public EventVerifier(RecordedEvent event) { - this.event = event; - } - - public > void verifyEquals(String name, T value) { - Events.assertField(event, name).equal(value); - } - - public void verifyContains(String name, String value) { - Events.assertField(event, name).containsAny(value); - } - - protected long gigabytes(int num) { - return num * 1024L * 1024L * 1024L; - } - - protected long megabytes(int num) { - return num * 1024L * 1024L; - } - - public abstract void verify() throws Exception; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Events.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Events.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Events.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Events.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,390 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import static jdk.test.lib.Asserts.assertEquals; -import static jdk.test.lib.Asserts.assertFalse; -import static jdk.test.lib.Asserts.assertNotNull; -import static jdk.test.lib.Asserts.assertTrue; -import static jdk.test.lib.Asserts.fail; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.lang.management.ManagementFactory; - -import jdk.jfr.AnnotationElement; -import jdk.jfr.EventType; -import jdk.jfr.Recording; -import jdk.jfr.SettingDescriptor; -import jdk.jfr.Timespan; -import jdk.jfr.Timestamp; -import jdk.jfr.ValueDescriptor; -import jdk.jfr.consumer.RecordingFile; -import jdk.test.lib.Asserts; -import jdk.jfr.consumer.RecordedClass; -import jdk.jfr.consumer.RecordedEvent; -import jdk.jfr.consumer.RecordedObject; -import jdk.jfr.consumer.RecordedThread; -import jdk.jfr.consumer.RecordedThreadGroup; - - -/** - * Helper class to verify RecordedEvent content - */ -public class Events { - - public static EventField assertField(RecordedEvent event, String name) { - String[] partNames = name.split("\\."); - RecordedObject struct = event; - try { - for (int i=0; i valueDescriptors = struct.getFields(); - for (ValueDescriptor d : valueDescriptors) { - if (name.equals(d.getName())) { - return d; - } - } - System.out.printf("Failed struct:%s", struct.toString()); - fail(String.format("Field %s not in struct", name)); - return null; - } - - public static void hasEvents(List events) { - assertFalse(events.isEmpty(), "No events"); - } - - public static void hasEvents(RecordingFile file) { - assertTrue(file.hasMoreEvents(), "No events"); - } - - public static void assertEventThread(RecordedEvent event) { - RecordedThread eventThread = event.getThread(); - if (eventThread == null) { - System.out.printf("Failed event:%n%s%n", event.toString()); - fail("No thread in event"); - } - } - - public static void assertJavaMethod(RecordedEvent event) { - assertField(event, "method.name").notEmpty(); - assertField(event, "method.descriptor").notEmpty(); - assertField(event, "method.modifiers").atLeast(0); - assertField(event, "method.hidden"); - assertField(event, "method.type.name").notEmpty(); - assertField(event, "method.type.modifiers").atLeast(0); - } - - public static void assertEventThread(RecordedEvent event, Thread thread) { - assertThread(event.getThread(), thread); - } - - public static void assertEventThread(RecordedEvent event, String structName, Thread thread) { - assertThread(assertField(event, structName).notNull().getValue(), thread); - } - - public static void assertDuration(RecordedEvent event, String name, Duration duration) { - assertEquals(event.getDuration(name), duration); - } - - public static void assertInstant(RecordedEvent event, String name, Instant instant) { - assertEquals(event.getInstant(name), instant); - } - - public static void assertMissingValue(RecordedEvent event, String name) { - ValueDescriptor v = event.getEventType().getField(name); - if (v.getAnnotation(Timespan.class) != null) { - Duration d = event.getDuration(name); - assertTrue(d.getSeconds() == Long.MIN_VALUE && d.getNano() == 0); - return; - } - if (v.getAnnotation(Timestamp.class) != null) { - Instant instant = event.getInstant(name); - assertTrue(instant.equals(Instant.MIN)); - return; - } - if (v.getTypeName().equals("double")) { - double d = event.getDouble(name); - assertTrue(Double.isNaN(d) || d == Double.NEGATIVE_INFINITY); - return; - } - if (v.getTypeName().equals("float")) { - float f = event.getFloat(name); - assertTrue(Float.isNaN(f) || f == Float.NEGATIVE_INFINITY); - return; - } - if (v.getTypeName().equals("int")) { - int i = event.getInt(name); - assertTrue(i == Integer.MIN_VALUE); - return; - } - if (v.getTypeName().equals("long")) { - assertEquals(event.getLong(name), Long.MIN_VALUE); - return; - } - Object o = event.getValue(name); - Asserts.assertNull(o); - } - - private static void assertThread(RecordedThread eventThread, Thread thread) { - assertNotNull(eventThread, "Thread in event was null"); - assertEquals(eventThread.getJavaThreadId(), thread.getId(), "Wrong thread id"); - assertEquals(eventThread.getJavaName(), thread.getName(), "Wrong thread name"); - - ThreadGroup threadGroup = thread.getThreadGroup(); - RecordedThreadGroup eventThreadGroup = eventThread.getThreadGroup(); - assertNotNull(eventThreadGroup, "eventThreadGroup was null"); - - // Iterate and check all threadGroups - while (eventThreadGroup != null) { - final String groupName = eventThreadGroup.getName(); - if (threadGroup != null) { - assertEquals(groupName, threadGroup.getName(), "Wrong threadGroup name"); - threadGroup = threadGroup.getParent(); - } else { - assertNotNull(groupName, "threadGroup name was null"); - assertFalse(groupName.isEmpty(), "threadGroup name was empty"); - } - eventThreadGroup = eventThreadGroup.getParent(); - } - } - - public static boolean hasField(RecordedEvent event, String name) { - return event.getFields().stream().map(vd -> vd.getName()).anyMatch(s -> s.equals(name)); - } - - public static boolean isEventType(RecordedEvent event, String typeName) { - return typeName.equals(event.getEventType().getName()); - } - - - /** - * Creates a list of events from a recording. - * - * @param recording recording, not {@code null} - * @return an a list, not null - * @throws IOException if an event set could not be created due to I/O - * errors. - */ - public static List fromRecording(Recording recording) throws IOException { - return RecordingFile.readAllEvents(makeCopy(recording)); - } - - public static RecordingFile copyTo(Recording r) throws IOException { - return new RecordingFile(makeCopy(r)); - } - - private static String getProcessId(final String fallback) { - // Note: may fail in some JVM implementations - // therefore fallback has to be provided - - // something like '@', at least in SUN / Oracle JVMs - final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); - - final int index = jvmName.indexOf('@'); - - if (index < 1) { - // part before '@' empty (index = 0) / '@' not found (index = -1) - return fallback; - } - - try { - return Long.toString(Long.parseLong(jvmName.substring(0, index))); - } catch (NumberFormatException e) { - // ignore - } - return fallback; - } - - private static Path makeCopy(Recording recording) throws IOException { - Path p = recording.getDestination(); - if (p == null) { - File directory = new File("."); - // FIXME: Must come up with a way to give human-readable name - // this will at least not clash when running parallel. - //ProcessHandle h = ProcessHandle.current(); - //p = new File(directory.getAbsolutePath(), "recording-" + recording.getId() + "-pid" + h.pid() + ".jfr").toPath(); - p = new File(directory.getAbsolutePath(), "recording-" + recording.getId() + "-pid" + getProcessId("666") + ".jfr").toPath(); - recording.dump(p); - } - return p; - } - - public static void hasAnnotation(ValueDescriptor field, Class annotationClass) throws Exception { - AnnotationElement a = getAnnotation(field, annotationClass); - if (a == null) { - throw new Exception("Expected " + annotationClass.getSimpleName() + " on field " + field.getName()); - } - } - - public static void assertAnnotation(ValueDescriptor field, Class annotationClass, String value) throws Exception { - AnnotationElement a = getAnnotation(field, annotationClass); - Object v = a.getValue("value"); - if (!v.equals(value)) { - throw new Exception("Expected " + annotationClass.getSimpleName() + " on field " + field.getName() + " to have value " + value + ", but got " + v); - } - } - - // candidate for moving into API - public static AnnotationElement getAnnotation(ValueDescriptor v, Class clazz) throws Exception { - for (AnnotationElement a : v.getAnnotationElements()) { - if (a.getTypeName().equals(clazz.getName())) { - return a; - } - } - - throw new Exception("Could not find annotation " + clazz.getName()); - } - - // candidate for moving into API - public static AnnotationElement getAnnotationByName(EventType t, String name) throws Exception { - for (AnnotationElement a : t.getAnnotationElements()) { - if (a.getTypeName().equals(name)) { - return a; - } - } - throw new Exception("Could not find annotation '" + name + " in type " + t.getName()); - } - - // candidate for moving into API - public static SettingDescriptor getSetting(EventType type, String name) { - for (SettingDescriptor s : type.getSettingDescriptors()) { - if (s.getName().equals(name)) { - return s; - } - } - throw new IllegalArgumentException("Could not setting with name " + name); - } - - public static void hasEvent(Recording r, String name) throws IOException { - List events = fromRecording(r); - Events.hasEvents(events); - Events.hasEvent(events, name); - } - - public static void hasEvent(List events, String name) throws IOException { - if (!containsEvent(events, name)) { - Asserts.fail("Missing event " + name + " in recording " + events.toString()); - } - } - - public static void hasNotEvent(List events, String name) throws IOException { - if (containsEvent(events, name)) { - Asserts.fail("Rercording should not contain event " + name + " " + events.toString()); - } - } - - private static boolean containsEvent(List events, String name) { - for (RecordedEvent event : events) { - if (event.getEventType().getName().equals(name)) { - return true; - } - } - return false; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/FileHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/FileHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/FileHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/FileHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import java.io.File; -import java.io.IOException; -import java.nio.file.AccessDeniedException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - -import jdk.jfr.consumer.RecordedEvent; -import jdk.jfr.consumer.RecordingFile; -import jdk.test.lib.Asserts; - -/** - * Common helper class. - */ -public class FileHelper { - - public static Path getDest(String subPath) throws IOException { - Path path = Paths.get(subPath + "/test.jfr"); - Path parent = path.getParent(); - if (parent == null) { - throw new IOException("No parent cound be found for path " + subPath); - } - Files.createDirectories(parent); - return path; - } - - public static Path createLongDir(Path root) throws IOException { - final int minPathLength = 400; - StringBuilder buff = new StringBuilder(); - buff.append(root.toString()); - while (buff.length() < minPathLength) { - buff.append("/veryLongPath012345678901234567890123456789"); - } - Path path = Paths.get(buff.toString()); - System.out.println("long dir=" + path); - Files.createDirectories(path); - return path; - } - - public static Path getDestReadOnly(String subPath) throws IOException { - final Path path = getDest(subPath); - Path parent = path.getParent(); - if (parent == null) { - throw new IOException("No parent cound be found for path " + subPath); - } - parent.toFile().setReadOnly(); - return path; - } - - public static Path createReadOnlyFile(Path path) throws IOException { - final Path createdPath = Files.createFile(path); - createdPath.toFile().setReadOnly(); - return createdPath; - } - - public static Path createReadOnlyDir(Path path) throws IOException { - final Path createdPath = Files.createDirectories(path); - createdPath.toFile().setReadOnly(); - return createdPath; - } - - public static Path getDestNotExist() { - return Paths.get(".", "thisDirDoesNotExist/test.jfr"); - } - - public static boolean isReadOnlyPath(Path path) throws IOException { - // Files.isWritable(path) can not really be trusted. At least not on Windows. - // If path is a directory, we try to create a new file in it. - if (Files.isDirectory(path)) { - try { - Path f = Files.createFile(Paths.get(path.toString(), "dummyFileToCheckReadOnly")); - System.out.printf("Dir is not read-only, created %s, exists=%b%n", f, Files.exists(f)); - return false; - } catch (AccessDeniedException e) { - System.out.printf("'%s' verified read-only by %s%n", path, e.toString()); - return true; - } - } else { - boolean isReadOnly = !Files.isWritable(path); - System.out.format("isReadOnly '%s': %b%n", path, isReadOnly); - return isReadOnly; - } - } - - public static void verifyRecording(File file) throws Exception { - Asserts.assertTrue(file.exists(), file.getAbsolutePath() + " does not exist"); - Asserts.assertTrue(file.isFile(), file.getAbsolutePath() + " is not a file"); - Asserts.assertGreaterThan(file.length(), 0L, "Size of recording is 0."); - List events = RecordingFile.readAllEvents(file.toPath()); - for (RecordedEvent event : events) { - System.out.printf("First event in recording '%s':%n%s", file.getName(), event); - return; - } - Asserts.fail("No events in file " + file.getName()); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/GCHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/GCHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/GCHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/GCHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,468 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import static jdk.test.lib.Asserts.assertEquals; -import static jdk.test.lib.Asserts.assertNotEquals; -import static jdk.test.lib.Asserts.assertNotNull; -import static jdk.test.lib.Asserts.assertNull; -import static jdk.test.lib.Asserts.fail; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.lang.management.GarbageCollectorMXBean; -import java.lang.management.ManagementFactory; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import jdk.jfr.ValueDescriptor; -import jdk.jfr.consumer.RecordedEvent; - -/** - * Mixed helper classes to test GC events. - */ -public class GCHelper { - public static final String event_garbage_collection = EventNames.GarbageCollection; - public static final String event_young_garbage_collection = EventNames.YoungGarbageCollection; - public static final String event_old_garbage_collection = EventNames.OldGarbageCollection; - public static final String event_parold_garbage_collection = EventNames.ParallelOldCollection; - public static final String event_g1_garbage_collection = EventNames.G1GarbageCollection; - public static final String event_heap_summary = EventNames.GCHeapSummary; - public static final String event_heap_ps_summary = EventNames.PSHeapSummary; - public static final String event_heap_metaspace_summary = EventNames.MetaspaceSummary; - public static final String event_reference_statistics = EventNames.GCReferenceStatistics; - public static final String event_phases_pause = EventNames.GCPhasePause; - public static final String event_phases_level_1 = EventNames.GCPhasePauseLevel1; - public static final String event_phases_level_2 = EventNames.GCPhasePauseLevel2; - public static final String event_phases_level_3 = EventNames.GCPhasePauseLevel3; - - public static final String gcG1New = "G1New"; - public static final String gcParNew = "ParNew"; - public static final String gcDefNew = "DefNew"; - public static final String gcParallelScavenge = "ParallelScavenge"; - public static final String gcG1Old = "G1Old"; - public static final String gcG1Full = "G1Full"; - public static final String gcConcurrentMarkSweep = "ConcurrentMarkSweep"; - public static final String gcSerialOld = "SerialOld"; - public static final String gcPSMarkSweep = "PSMarkSweep"; - public static final String gcParallelOld = "ParallelOld"; - public static final String pauseLevelEvent = "GCPhasePauseLevel"; - - private static final List g1HeapRegionTypes; - private static PrintStream defaultErrorLog = null; - - public static int getGcId(RecordedEvent event) { - return Events.assertField(event, "gcId").getValue(); - } - - public static boolean isGcEvent(RecordedEvent event) { - for (ValueDescriptor v : event.getFields()) { - if ("gcId".equals(v.getName())) { - return true; - } - } - return false; - } - -// public static String getEventDesc(RecordedEvent event) { -// final String path = event.getEventType().getName(); -// if (!isGcEvent(event)) { -// return path; -// } -// if (event_garbage_collection.equals(path)) { -// String name = Events.assertField(event, "name").getValue(); -// String cause = Events.assertField(event, "cause").getValue(); -// return String.format("path=%s, gcId=%d, endTime=%d, name=%s, cause=%s, startTime=%d", -// path, getGcId(event), event.getEndTime(), name, cause, event.getStartTime()); -// } else { -// return String.format("path=%s, gcId=%d, endTime=%d", path, getGcId(event), event.getEndTime()); -// } -// } - - public static RecordedEvent getConfigEvent(List events) throws Exception { - for (RecordedEvent event : events) { - if (EventNames.GCConfiguration.equals(event.getEventType().getName())) { - return event; - } - } - fail("Could not find event " + EventNames.GCConfiguration); - return null; - } - - public static void callSystemGc(int num, boolean withGarbage) { - for (int i = 0; i < num; i++) { - if (withGarbage) { - makeGarbage(); - } - System.gc(); - } - } - - private static void makeGarbage() { - Object[] garbage = new Object[1024]; - for (int i = 0; i < 1024; i++) { - garbage[i] = new Object(); - } - } - - // Removes gcEvents with lowest and highest gcID. This is used to filter out - // any incomplete GCs if the recording started/stopped in the middle of a GC. - // We also filters out events without gcId. Those events are not needed. - public static List removeFirstAndLastGC(List events) { - int minGcId = Integer.MAX_VALUE; - int maxGcId = Integer.MIN_VALUE; - // Find min/max gcId - for (RecordedEvent event : events) { - if (Events.hasField(event, "gcId")) { - int gcId = Events.assertField(event, "gcId").getValue(); - minGcId = Math.min(gcId, minGcId); - maxGcId = Math.max(gcId, maxGcId); - } - } - - // Add all events except those with gcId = min/max gcId - List filteredEvents = new ArrayList<>(); - for (RecordedEvent event : events) { - if (Events.hasField(event, "gcId")) { - int gcId = Events.assertField(event, "gcId").getValue(); - if (gcId != minGcId && gcId != maxGcId) { - filteredEvents.add(event); - } - } - } - return filteredEvents; - } - - public static Map beanCollectorTypes = new HashMap<>(); - public static Set collectorOverrides = new HashSet<>(); - public static Map requiredEvents = new HashMap<>(); - - static { - // young GarbageCollectionMXBeans. - beanCollectorTypes.put("G1 Young Generation", true); - beanCollectorTypes.put("Copy", true); - beanCollectorTypes.put("PS Scavenge", true); - beanCollectorTypes.put("ParNew", true); - - // old GarbageCollectionMXBeans. - beanCollectorTypes.put("G1 Old Generation", false); - beanCollectorTypes.put("ConcurrentMarkSweep", false); - beanCollectorTypes.put("PS MarkSweep", false); - beanCollectorTypes.put("MarkSweepCompact", false); - - // List of expected collector overrides. "A.B" means that collector A may use collector B. - collectorOverrides.add("G1Old.G1Full"); - collectorOverrides.add("G1Old.SerialOld"); - collectorOverrides.add("ConcurrentMarkSweep.SerialOld"); - collectorOverrides.add("SerialOld.PSMarkSweep"); - - requiredEvents.put(gcG1New, new String[] {event_heap_summary, event_young_garbage_collection}); - requiredEvents.put(gcParNew, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); - requiredEvents.put(gcDefNew, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); - requiredEvents.put(gcParallelScavenge, new String[] {event_heap_summary, event_heap_ps_summary, event_heap_metaspace_summary, event_reference_statistics, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); - requiredEvents.put(gcG1Old, new String[] {event_heap_summary, event_old_garbage_collection}); - requiredEvents.put(gcG1Full, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_old_garbage_collection}); - requiredEvents.put(gcConcurrentMarkSweep, new String[] {event_phases_pause, event_phases_level_1, event_old_garbage_collection}); - requiredEvents.put(gcSerialOld, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_old_garbage_collection}); - requiredEvents.put(gcParallelOld, new String[] {event_heap_summary, event_heap_ps_summary, event_heap_metaspace_summary, event_reference_statistics, event_phases_pause, event_phases_level_1, event_old_garbage_collection, event_parold_garbage_collection}); - - String[] g1HeapRegionTypeLiterals = new String[] { - "Free", - "Eden", - "Survivor", - "Starts Humongous", - "Continues Humongous", - "Old", - "Archive" - }; - - g1HeapRegionTypes = Collections.unmodifiableList(Arrays.asList(g1HeapRegionTypeLiterals)); - } - - /** - * Contains all GC events belonging to the same GC (same gcId). - */ - public static class GcBatch { - private List events = new ArrayList<>(); - - public int getGcId() { - if (events.isEmpty()) { - return -1; - } - return GCHelper.getGcId(events.get(0)); - } - - public String getName() { - RecordedEvent endEvent = getEndEvent(); - String name = endEvent == null ? null : Events.assertField(endEvent, "name").getValue(); - return name == null ? "null" : name; - } - - public RecordedEvent getEndEvent() { - return getEvent(event_garbage_collection); - } - - public boolean addEvent(RecordedEvent event) { - if (!events.isEmpty()) { - assertEquals(getGcId(), GCHelper.getGcId(event), "Wrong gcId in event. Error in test code."); - } - boolean isEndEvent = event_garbage_collection.equals(event.getEventType().getName()); - if (isEndEvent) { - // Verify that we have not already got a garbage_collection event with this gcId. - assertNull(getEndEvent(), String.format("Multiple %s for gcId %d", event_garbage_collection, getGcId())); - } - events.add(event); - return isEndEvent; - } - - public boolean isYoungCollection() { - boolean isYoung = containsEvent(event_young_garbage_collection); - boolean isOld = containsEvent(event_old_garbage_collection); - assertNotEquals(isYoung, isOld, "isYoung and isOld was same for batch: " + toString()); - return isYoung; - } - - public int getEventCount() { - return events.size(); - } - - public RecordedEvent getEvent(int index) { - return events.get(index); - } - - public List getEvents() { - return events; - } - - public RecordedEvent getEvent(String eventPath) { - for (RecordedEvent event : events) { - if (eventPath.equals(event.getEventType().getName())) { - return event; - } - } - return null; - } - - public boolean containsEvent(String eventPath) { - return getEvent(eventPath) != null; - } - - public String toString() { - RecordedEvent endEvent = getEndEvent(); - Instant startTime = Instant.EPOCH; - String cause = "?"; - String name = "?"; - if (endEvent != null) { - name = getName(); - startTime = endEvent.getStartTime(); - cause = Events.assertField(endEvent, "cause").getValue(); - } - return String.format("GcEvent: gcId=%d, method=%s, cause=%s, startTime=%s", - getGcId(), name, cause, startTime); - } - - public String getLog() { - StringBuilder sb = new StringBuilder(); - sb.append(this.toString() + System.getProperty("line.separator")); - for (RecordedEvent event : events) { - sb.append(String.format("event: %s%n", event)); - } - return sb.toString(); - } - - // Group all events info batches. - public static List createFromEvents(List events) throws Exception { - Stack openGcIds = new Stack<>(); - List batches = new ArrayList<>(); - GcBatch currBatch = null; - - for (RecordedEvent event : events) { - if (!isGcEvent(event)) { - continue; - } - int gcId = GCHelper.getGcId(event); - if (currBatch == null || currBatch.getGcId() != gcId) { - currBatch = null; - // Search for existing batch - for (GcBatch loopBatch : batches) { - if (gcId == loopBatch.getGcId()) { - currBatch = loopBatch; - break; - } - } - if (currBatch == null) { - // No existing batch. Create new. - currBatch = new GcBatch(); - batches.add(currBatch); - openGcIds.push(new Integer(gcId)); - } - } - boolean isEndEvent = currBatch.addEvent(event); - if (isEndEvent) { - openGcIds.pop(); - } - } - // Verify that all start_garbage_collection events have received a corresponding "garbage_collection" event. - for (GcBatch batch : batches) { - if (batch.getEndEvent() == null) { - System.out.println(batch.getLog()); - } - assertNotNull(batch.getEndEvent(), "GcBatch has no end event"); - } - return batches; - } - } - - /** - * Contains number of collections and sum pause time for young and old collections. - */ - public static class CollectionSummary { - public long collectionCountOld; - public long collectionCountYoung; - public long collectionTimeOld; - public long collectionTimeYoung; - private Set names = new HashSet<>(); - - public void add(String collectorName, boolean isYoung, long count, long time) { - if (isYoung) { - collectionCountYoung += count; - collectionTimeYoung += time; - } else { - collectionCountOld += count; - collectionTimeOld += time; - } - if (!names.contains(collectorName)) { - names.add(collectorName); - } - } - - public long sum() { - return collectionCountOld + collectionCountYoung; - } - - public CollectionSummary calcDelta(CollectionSummary prev) { - CollectionSummary delta = new CollectionSummary(); - delta.collectionCountOld = this.collectionCountOld - prev.collectionCountOld; - delta.collectionTimeOld = this.collectionTimeOld - prev.collectionTimeOld; - delta.collectionCountYoung = this.collectionCountYoung - prev.collectionCountYoung; - delta.collectionTimeYoung = this.collectionTimeYoung - prev.collectionTimeYoung; - delta.names.addAll(this.names); - delta.names.addAll(prev.names); - return delta; - } - - public static CollectionSummary createFromMxBeans() { - CollectionSummary summary = new CollectionSummary(); - List gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); - for (int c=0; c batches) { - CollectionSummary summary = new CollectionSummary(); - for (GcBatch batch : batches) { - RecordedEvent endEvent = batch.getEndEvent(); - assertNotNull(endEvent, "No end event in batch with gcId " + batch.getGcId()); - String name = batch.getName(); - summary.add(name, batch.isYoungCollection(), 1, Events.assertField(endEvent, "sumOfPauses").getValue()); - } - return summary; - } - - public String toString() { - StringBuilder collectorNames = new StringBuilder(); - for (String s : names) { - if (collectorNames.length() > 0) { - collectorNames.append(", "); - } - collectorNames.append(s); - } - return String.format("CollectionSummary: young.collections=%d, young.time=%d, old.collections=%d, old.time=%d, collectors=(%s)", - collectionCountYoung, collectionTimeYoung, collectionCountOld, collectionTimeOld, collectorNames); - } - } - - public static PrintStream getDefaultErrorLog() { - if (defaultErrorLog == null) { - try { - defaultErrorLog = new PrintStream(new FileOutputStream("error.log", true)); - } catch (IOException e) { - e.printStackTrace(); - defaultErrorLog = System.err; - } - } - return defaultErrorLog; - } - - public static void log(Object msg) { - log(msg, System.err); - log(msg, getDefaultErrorLog()); - } - - public static void log(Object msg, PrintStream ps) { - ps.println(msg); - } - - public static boolean isValidG1HeapRegionType(final String type) { - return g1HeapRegionTypes.contains(type); - } - - /** - * Helper function to align heap size up. - * - * @param value - * @param alignment - * @return aligned value - */ - public static long alignUp(long value, long alignment) { - return (value + alignment - 1) & ~(alignment - 1); - } - - /** - * Helper function to align heap size down. - * - * @param value - * @param alignment - * @return aligned value - */ - public static long alignDown(long value, long alignment) { - return value & ~(alignment - 1); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/RecurseThread.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/RecurseThread.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/RecurseThread.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/RecurseThread.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import jdk.test.lib.Asserts; - -public class RecurseThread extends Thread { - - public int totalDepth; - public long dummy = 0; // Just to make sure the optimizer does not remove the test code. - private volatile boolean timeToQuit = false; - private volatile boolean isInRunLoop = false; - - public RecurseThread(int totalDepth) { - this.totalDepth = totalDepth; - } - - @Override - public void run() { - // totalDepth includes functions run() and recurse() and runloop(). - // Remove 3 from totalDepth when recursing. - final int minDepth = 3; - Asserts.assertGreaterThanOrEqual(totalDepth, minDepth, "totalDepth too small"); - int recurseDepth = totalDepth - minDepth; - - // We want the last function before runloop() to be recurseA(). - boolean startWithRecurseA = (totalDepth % 2) != 0; - dummy = startWithRecurseA ? recurseA(recurseDepth) : recurseB(recurseDepth); - } - - public void quit() { - timeToQuit = true; - } - - public boolean isInRunLoop() { - return isInRunLoop; - } - - private long recurseA(int depth) { - if (depth == 0) { - return recurseEnd(); - } else { - return recurseB(depth - 1); - } - } - - private long recurseB(int depth) { - if (depth == 0) { - return recurseEnd(); - } else { - return recurseA(depth - 1); - } - } - - // Test expects this function to be at the top of the stack. - // We should not call other functions from here. - private long recurseEnd() { - isInRunLoop = true; - long[] dummyTable = new long[] { 0, 2, 4, 8, 16 }; - long dummyTotal = 0; - while (!timeToQuit) { - dummyTotal = 0; - for (int i = 0; i < 5; ++i) { - dummyTotal += dummyTable[i]; - } - } - return dummyTotal; - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEvent.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEvent.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEvent.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEvent.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import jdk.jfr.Event; - -public class SimpleEvent extends Event { - public int id; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import jdk.jfr.Recording; -import jdk.jfr.consumer.RecordedEvent; -import jdk.test.lib.Asserts; - -public class SimpleEventHelper { - - public static void enable(Recording r, boolean isEnabled) { - if (isEnabled) { - r.enable(SimpleEvent.class).withThreshold(Duration.ofMillis(0)).withoutStackTrace(); - } else { - r.disable(SimpleEvent.class); - } - } - - public static SimpleEvent createEvent(int id) { - SimpleEvent event = new SimpleEvent(); - event.begin(); - event.id = id; - event.end(); - event.commit(); - return event; - } - - public static void verifyEvents(Recording r, int ... ids) throws Exception { - List eventIds = new ArrayList<>(); - for (RecordedEvent event : Events.fromRecording(r)) { - if (Events.isEventType(event, SimpleEvent.class.getName())) { - int id = Events.assertField(event, "id").getValue(); - System.out.printf("recording %s: event.id=%d%n", r.getName(), id); - eventIds.add(id); - } - } - Asserts.assertEquals(eventIds.size(), ids.length, "Wrong number of events"); - for (int i = 0; i < ids.length; ++i) { - Asserts.assertEquals(eventIds.get(i).intValue(), ids[i], "Wrong id in event"); - } - } - - public static void verifyContains(List events, int ... ids) throws Exception { - Set missingIds = new HashSet<>(); - for (int id : ids) { - missingIds.add(id); - } - for (RecordedEvent event : getSimpleEvents(events)) { - int id = Events.assertField(event, "id").getValue(); - System.out.printf("event.id=%d%n", id); - missingIds.remove(new Integer(id)); - } - if (!missingIds.isEmpty()) { - missingIds.forEach(id -> System.out.println("Missing MyEvent with id " + id)); - Asserts.fail("Missing some MyEvent events"); - } - } - - public static void verifyNotContains(List events, int ... ids) throws Exception { - for (RecordedEvent event : getSimpleEvents(events)) { - int eventId = Events.assertField(event, "id").getValue(); - System.out.printf("event.id=%d%n", eventId); - for (int id : ids) { - Events.assertField(event, "id").notEqual(id); - } - } - } - - public static List getSimpleEvents(List events) { - List myEvents = new ArrayList<>(); - for (RecordedEvent event : events) { - if (Events.isEventType(event, SimpleEvent.class.getName())) { - myEvents.add(event); - } - } - return myEvents; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleSetting.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleSetting.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleSetting.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/SimpleSetting.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import java.util.Set; - -import jdk.jfr.SettingControl; - -public class SimpleSetting extends SettingControl { - - @Override - public String combine(Set settingValue) { - return "none"; - } - - @Override - public void setValue(String value) { - } - - @Override - public String getValue() { - return "none"; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Stressor.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Stressor.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Stressor.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/Stressor.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.test.lib.jfr; - -import java.util.ArrayList; -import java.util.List; - -/** - * Class to help run multiple threads executing some task - * - * - * @since 1.9 - */ -public class Stressor { - public static void execute(int numberOfThreads, Thread.UncaughtExceptionHandler eh, Runnable task) throws Exception { - List threads = new ArrayList<>(); - for (int n = 0; n < numberOfThreads; ++n) { - Thread t = new Thread(task); - t.setUncaughtExceptionHandler(eh); - threads.add(t); - t.start(); - } - for (Thread t : threads) { - t.join(); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/TestClassLoader.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/TestClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/TestClassLoader.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/TestClassLoader.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Custom class loader which will try to load the class via getResourceAsStream(). - * If there are any errors, the parent class loader will be used instead. - */ -public class TestClassLoader extends ClassLoader { - static public final String CLASS_LOADER_NAME = "jdk/test/lib/jfr/TestClassLoader";// XXX since JDK 9 "JFR TestClassLoader"; - - public TestClassLoader() { - //super(CLASS_LOADER_NAME, ClassLoader.getSystemClassLoader()); - super(ClassLoader.getSystemClassLoader()); - } - - public Class loadClass(String name) throws ClassNotFoundException { - - InputStream is = null; - DataInputStream dis = null; - try { - String resourceName = name.replace('.', '/') + ".class"; - is = getResourceAsStream(resourceName); - if (is != null) { - int i = is.available(); - byte buf[] = new byte[i]; - dis = new DataInputStream(is); - dis.readFully(buf); - dis.close(); - return defineClass(name, buf, 0, buf.length); - } - } catch (SecurityException e) { - // This error will happen quite often (for example when loading - // "java.lang..."). - // Ignore this error and use parent class loader. - } catch (IOException e) { - // Unexpected error. Use parent class loader. - e.printStackTrace(); - } finally { - if (dis != null) { - try { - dis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return super.loadClass(name); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/VoidFunction.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/VoidFunction.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/VoidFunction.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/jfr/VoidFunction.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.jfr; - -@FunctionalInterface -public interface VoidFunction { - void run() throws Throwable; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/DynamicVMOption.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/DynamicVMOption.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/DynamicVMOption.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/DynamicVMOption.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.management; - -import com.sun.management.HotSpotDiagnosticMXBean; -import java.lang.management.ManagementFactory; - -/** - * A utility class to work with VM options which could be altered during - * execution. - * - * This class is a wrapper around {@code com.sun.management.VMOption}. - * It provides more convenient interface to read/write the values. - * - */ -public class DynamicVMOption { - - private final HotSpotDiagnosticMXBean mxBean; - - /** - * VM option name, like "MinHeapFreeRatio". - */ - public final String name; - - /** - * Creates an instance of DynamicVMOption. - * - * @param name the VM option name - */ - public DynamicVMOption(String name) { - this.name = name; - mxBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); - } - - /** - * Sets a new value for the option. - * Trying to set not applicable value will cause IllegalArgumentException. - * Behavior with null is undefined, most likely NPE will be thrown. - * - * @param newValue the value to be set - * @see #getValue() - * @throws IllegalArgumentException if newValue is not applicable to the option - */ - public final void setValue(String newValue) { - mxBean.setVMOption(name, newValue); - } - - /** - * Returns the value of option. - * - * @return the current option value - * @see #setValue(java.lang.String) - */ - public final String getValue() { - return mxBean.getVMOption(name).getValue(); - } - - /** - * Returns true, if option is writable, false otherwise. - * - * @return true, if option is writable, false otherwise - */ - public final boolean isWriteable() { - return mxBean.getVMOption(name).isWriteable(); - } - - /** - * Checks if the given value is applicable for the option. - * - * This method tries to set the option to the new value. If no exception - * has been thrown the value is treated as valid. - * - * Calling this method will not change the option value. After an attempt - * to set a new value, the option will be restored to its previous value. - * - * @param value the value to verify - * @return true if option could be set to the given value - */ - public boolean isValidValue(String value) { - boolean isValid = true; - String oldValue = getValue(); - try { - setValue(value); - } catch (NullPointerException e) { - if (value == null) { - isValid = false; - } - } catch (IllegalArgumentException e) { - isValid = false; - } finally { - setValue(oldValue); - } - return isValid; - } - - /** - * Returns the value of the given VM option as String. - * - * This is a simple shortcut for {@code new DynamicVMOption(name).getValue()} - * - * @param name the name of VM option - * @return value as a string - * @see #getValue() - */ - public static String getString(String name) { - return new DynamicVMOption(name).getValue(); - } - - /** - * Returns the value of the given option as int. - * - * @param name the name of VM option - * @return value parsed as integer - * @see #getString(java.lang.String) - * - */ - public static int getInt(String name) { - return Integer.parseInt(getString(name)); - } - - /** - * Sets the VM option to a new value. - * - * This is a simple shortcut for {@code new DynamicVMOption(name).setValue(value)} - * - * @param name the name of VM option - * @param value the value to be set - * @see #setValue(java.lang.String) - */ - public static void setString(String name, String value) { - new DynamicVMOption(name).setValue(value); - } - - /** - * Sets the VM option value to a new integer value. - * - * @param name the name of VM option - * @param value the integer value to be set - * @see #setString(java.lang.String, java.lang.String) - */ - public static void setInt(String name, int value) { - new DynamicVMOption(name).setValue(Integer.toString(value)); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/InputArguments.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/InputArguments.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/InputArguments.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/InputArguments.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.management; - -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.util.List; - -public class InputArguments { - /** - * Gets the array of strings containing input arguments passed to the VM - * - * @return arguments - */ - public static String[] getVmInputArgs() { - RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); - List args = runtime.getInputArguments(); - return args.toArray(new String[args.size()]); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.management; - -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; - -/** - * A few utility methods to use ThreadMXBean. - */ -public final class ThreadMXBeanTool { - - /** - * Waits until {@link Thread} is in the certain {@link Thread.State} - * and blocking on {@code object}. - * - * @param state The thread state - * @param object The object to block on - */ - public static void waitUntilBlockingOnObject(Thread thread, Thread.State state, Object object) - throws InterruptedException { - String want = object == null ? null : object.getClass().getName() + '@' - + Integer.toHexString(System.identityHashCode(object)); - ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); - while (thread.isAlive()) { - ThreadInfo ti = tmx.getThreadInfo(thread.getId()); - if (ti.getThreadState() == state - && (want == null || want.equals(ti.getLockName()))) { - return; - } - Thread.sleep(1); - } - } - - /** - * Waits until {@link Thread} is in native. - */ - public static void waitUntilInNative(Thread thread) throws InterruptedException { - ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); - while (thread.isAlive()) { - ThreadInfo ti = tmx.getThreadInfo(thread.getId()); - if (ti.isInNative()) { - return; - } - Thread.sleep(1); - } - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ExitCode.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ExitCode.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ExitCode.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ExitCode.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.process; - -/** - * Exit code values that could be returned by the JVM. - */ -public enum ExitCode { - OK(0), - FAIL(1), - CRASH(134); - - public final int value; - - ExitCode(int value) { - this.value = value; - } -} - diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputAnalyzer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputAnalyzer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputAnalyzer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputAnalyzer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,557 +0,0 @@ -/* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.process; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class OutputAnalyzer { - - private final String stdout; - private final String stderr; - private final int exitValue; - - /** - * Create an OutputAnalyzer, a utility class for verifying output and exit - * value from a Process - * - * @param process Process to analyze - * @throws IOException If an I/O error occurs. - */ - public OutputAnalyzer(Process process) throws IOException { - OutputBuffer output = ProcessTools.getOutput(process); - exitValue = process.exitValue(); - this.stdout = output.getStdout(); - this.stderr = output.getStderr(); - } - - /** - * Create an OutputAnalyzer, a utility class for verifying output - * - * @param buf String buffer to analyze - */ - public OutputAnalyzer(String buf) { - this(buf, buf); - } - - /** - * Create an OutputAnalyzer, a utility class for verifying output - * - * @param stdout stdout buffer to analyze - * @param stderr stderr buffer to analyze - */ - public OutputAnalyzer(String stdout, String stderr) { - this.stdout = stdout; - this.stderr = stderr; - exitValue = -1; - } - - /** - * Verify that the stdout contents of output buffer is empty - * - * @throws RuntimeException - * If stdout was not empty - */ - public void stdoutShouldBeEmpty() { - if (!getStdout().isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stdout was not empty"); - } - } - - /** - * Verify that the stderr contents of output buffer is empty - * - * @throws RuntimeException - * If stderr was not empty - */ - public void stderrShouldBeEmpty() { - if (!getStderr().isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stderr was not empty"); - } - } - - /** - * Verify that the stderr contents of output buffer is empty, - * after filtering out the Hotspot warning messages - * - * @throws RuntimeException - * If stderr was not empty - */ - public void stderrShouldBeEmptyIgnoreVMWarnings() { - if (!getStderr().replaceAll(jvmwarningmsg + "\\R", "").isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stderr was not empty"); - } - } - - /** - * Verify that the stdout contents of output buffer is not empty - * - * @throws RuntimeException - * If stdout was empty - */ - public void stdoutShouldNotBeEmpty() { - if (getStdout().isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stdout was empty"); - } - } - - /** - * Verify that the stderr contents of output buffer is not empty - * - * @throws RuntimeException - * If stderr was empty - */ - public void stderrShouldNotBeEmpty() { - if (getStderr().isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stderr was empty"); - } - } - - /** - * Verify that the stdout and stderr contents of output buffer contains the string - * - * @param expectedString String that buffer should contain - * @throws RuntimeException If the string was not found - */ - public OutputAnalyzer shouldContain(String expectedString) { - if (!stdout.contains(expectedString) && !stderr.contains(expectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + expectedString + "' missing from stdout/stderr \n"); - } - return this; - } - - /** - * Verify that the stdout contents of output buffer contains the string - * - * @param expectedString String that buffer should contain - * @throws RuntimeException If the string was not found - */ - public OutputAnalyzer stdoutShouldContain(String expectedString) { - if (!stdout.contains(expectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + expectedString + "' missing from stdout \n"); - } - return this; - } - - /** - * Verify that the stderr contents of output buffer contains the string - * - * @param expectedString String that buffer should contain - * @throws RuntimeException If the string was not found - */ - public OutputAnalyzer stderrShouldContain(String expectedString) { - if (!stderr.contains(expectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + expectedString + "' missing from stderr \n"); - } - return this; - } - - /** - * Verify that the stdout and stderr contents of output buffer does not contain the string - * - * @param expectedString String that the buffer should not contain - * @throws RuntimeException If the string was found - */ - public OutputAnalyzer shouldNotContain(String notExpectedString) { - if (stdout.contains(notExpectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + notExpectedString + "' found in stdout \n"); - } - if (stderr.contains(notExpectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + notExpectedString + "' found in stderr \n"); - } - return this; - } - - /** - * Verify that the stdout and stderr contents of output buffer are empty - * - * @throws RuntimeException If the stdout and stderr are not empty - */ - public OutputAnalyzer shouldBeEmpty() { - if (!stdout.isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stdout was not empty"); - } - if (!stderr.isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stderr was not empty"); - } - return this; - } - - /** - * Verify that the stdout contents of output buffer does not contain the string - * - * @param expectedString String that the buffer should not contain - * @throws RuntimeException If the string was found - */ - public OutputAnalyzer stdoutShouldNotContain(String notExpectedString) { - if (stdout.contains(notExpectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + notExpectedString + "' found in stdout \n"); - } - return this; - } - - /** - * Verify that the stderr contents of output buffer does not contain the string - * - * @param expectedString String that the buffer should not contain - * @throws RuntimeException If the string was found - */ - public OutputAnalyzer stderrShouldNotContain(String notExpectedString) { - if (stderr.contains(notExpectedString)) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + notExpectedString + "' found in stderr \n"); - } - return this; - } - - /** - * Verify that the stdout and stderr contents of output buffer matches - * the pattern - * - * @param pattern - * @throws RuntimeException If the pattern was not found - */ - public OutputAnalyzer shouldMatch(String pattern) { - Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); - Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - if (!stdoutMatcher.find() && !stderrMatcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' missing from stdout/stderr \n"); - } - return this; - } - - /** - * Verify that the stdout contents of output buffer matches the - * pattern - * - * @param pattern - * @throws RuntimeException If the pattern was not found - */ - public OutputAnalyzer stdoutShouldMatch(String pattern) { - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); - if (!matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' missing from stdout \n"); - } - return this; - } - - /** - * Verify that the stderr contents of output buffer matches the - * pattern - * - * @param pattern - * @throws RuntimeException If the pattern was not found - */ - public OutputAnalyzer stderrShouldMatch(String pattern) { - - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - if (!matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' missing from stderr \n"); - } - return this; - } - - /** - * Verify that the stdout and stderr contents of output buffer does not - * match the pattern - * - * @param pattern - * @throws RuntimeException If the pattern was found - */ - public OutputAnalyzer shouldNotMatch(String pattern) { - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); - if (matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' found in stdout: '" + matcher.group() + "' \n"); - } - matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - if (matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' found in stderr: '" + matcher.group() + "' \n"); - } - return this; - } - - /** - * Verify that the stdout contents of output buffer does not match the - * pattern - * - * @param pattern - * @throws RuntimeException If the pattern was found - */ - public OutputAnalyzer stdoutShouldNotMatch(String pattern) { - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); - if (matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' found in stdout \n"); - } - return this; - } - - /** - * Verify that the stderr contents of output buffer does not match the - * pattern - * - * @param pattern - * @throws RuntimeException If the pattern was found - */ - public OutputAnalyzer stderrShouldNotMatch(String pattern) { - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - if (matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' found in stderr \n"); - } - return this; - } - - /** - * Get the captured group of the first string matching the pattern. - * stderr is searched before stdout. - * - * @param pattern The multi-line pattern to match - * @param group The group to capture - * @return The matched string or null if no match was found - */ - public String firstMatch(String pattern, int group) { - Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); - if (stderrMatcher.find()) { - return stderrMatcher.group(group); - } - if (stdoutMatcher.find()) { - return stdoutMatcher.group(group); - } - return null; - } - - /** - * Get the first string matching the pattern. - * stderr is searched before stdout. - * - * @param pattern The multi-line pattern to match - * @return The matched string or null if no match was found - */ - public String firstMatch(String pattern) { - return firstMatch(pattern, 0); - } - - /** - * Verify the exit value of the process - * - * @param expectedExitValue Expected exit value from process - * @throws RuntimeException If the exit value from the process did not match the expected value - */ - public OutputAnalyzer shouldHaveExitValue(int expectedExitValue) { - if (getExitValue() != expectedExitValue) { - reportDiagnosticSummary(); - throw new RuntimeException("Expected to get exit value of [" - + expectedExitValue + "]\n"); - } - return this; - } - - /** - * Verify the exit value of the process - * - * @param notExpectedExitValue Unexpected exit value from process - * @throws RuntimeException If the exit value from the process did match the expected value - */ - public OutputAnalyzer shouldNotHaveExitValue(int notExpectedExitValue) { - if (getExitValue() == notExpectedExitValue) { - reportDiagnosticSummary(); - throw new RuntimeException("Unexpected to get exit value of [" - + notExpectedExitValue + "]\n"); - } - return this; - } - - - /** - * Report summary that will help to diagnose the problem - * Currently includes: - * - standard input produced by the process under test - * - standard output - * - exit code - * Note: the command line is printed by the ProcessTools - */ - public void reportDiagnosticSummary() { - String msg = - " stdout: [" + stdout + "];\n" + - " stderr: [" + stderr + "]\n" + - " exitValue = " + getExitValue() + "\n"; - - System.err.println(msg); - } - - /** - * Print the stdout buffer to the given {@code PrintStream}. - * - * @return this OutputAnalyzer - */ - public OutputAnalyzer outputTo(PrintStream out) { - out.println(getStdout()); - return this; - } - - /** - * Print the stderr buffer to the given {@code PrintStream}. - * - * @return this OutputAnalyzer - */ - public OutputAnalyzer errorTo(PrintStream out) { - out.println(getStderr()); - return this; - } - - /** - * Get the contents of the output buffer (stdout and stderr) - * - * @return Content of the output buffer - */ - public String getOutput() { - return stdout + stderr; - } - - /** - * Get the contents of the stdout buffer - * - * @return Content of the stdout buffer - */ - public String getStdout() { - return stdout; - } - - /** - * Get the contents of the stderr buffer - * - * @return Content of the stderr buffer - */ - public String getStderr() { - return stderr; - } - - /** - * Get the process exit value - * - * @return Process exit value - */ - public int getExitValue() { - return exitValue; - } - - /** - * Get the contents of the output buffer (stdout and stderr) as list of strings. - * Output will be split by newlines. - * - * @return Contents of the output buffer as list of strings - */ - public List asLines() { - return asLines(getOutput()); - } - - private List asLines(String buffer) { - return Arrays.asList(buffer.split("(\\r\\n|\\n|\\r)")); - } - - - private static final String jvmwarningmsg = ".* VM warning:.*"; - - /** - * Verifies that the stdout and stderr contents of output buffer are empty, after - * filtering out the HotSpot warning messages. - * - * @throws RuntimeException If the stdout and stderr are not empty - */ - public OutputAnalyzer shouldBeEmptyIgnoreVMWarnings() { - if (!stdout.isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stdout was not empty"); - } - if (!stderr.replaceAll(jvmwarningmsg + "\\R", "").isEmpty()) { - reportDiagnosticSummary(); - throw new RuntimeException("stderr was not empty"); - } - return this; - } - - /** - * Verify that the stderr contents of output buffer matches the pattern, - * after filtering out the Hotespot warning messages - * - * @param pattern - * @throws RuntimeException If the pattern was not found - */ - public OutputAnalyzer stderrShouldMatchIgnoreVMWarnings(String pattern) { - String stderr = this.stderr.replaceAll(jvmwarningmsg + "\\R", ""); - Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); - if (!matcher.find()) { - reportDiagnosticSummary(); - throw new RuntimeException("'" + pattern - + "' missing from stderr \n"); - } - return this; - } - - /** - * Returns the contents of the output buffer (stdout and stderr), without those - * JVM warning msgs, as list of strings. Output is split by newlines. - * - * @return Contents of the output buffer as list of strings - */ - public List asLinesWithoutVMWarnings() { - return Arrays.asList(getOutput().split("\\R")) - .stream() - .filter(Pattern.compile(jvmwarningmsg).asPredicate().negate()) - .collect(Collectors.toList()); - } - -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputBuffer.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputBuffer.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/OutputBuffer.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.process; - -public class OutputBuffer { - private final String stdout; - private final String stderr; - - /** - * Create an OutputBuffer, a class for storing and managing stdout and stderr - * results separately - * - * @param stdout stdout result - * @param stderr stderr result - */ - public OutputBuffer(String stdout, String stderr) { - this.stdout = stdout; - this.stderr = stderr; - } - - /** - * Returns the stdout result - * - * @return stdout result - */ - public String getStdout() { - return stdout; - } - - /** - * Returns the stderr result - * - * @return stderr result - */ - public String getStderr() { - return stderr; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ProcessTools.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ProcessTools.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ProcessTools.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/ProcessTools.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,596 +0,0 @@ -/* - * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.process; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.CountDownLatch; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Predicate; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.lang.management.ManagementFactory; - -import jdk.test.lib.JDKToolFinder; -import jdk.test.lib.Utils; - -public final class ProcessTools { - private static final class LineForwarder extends StreamPumper.LinePump { - private final PrintStream ps; - private final String prefix; - LineForwarder(String prefix, PrintStream os) { - this.ps = os; - this.prefix = prefix; - } - @Override - protected void processLine(String line) { - ps.println("[" + prefix + "] " + line); - } - } - - private ProcessTools() { - } - - /** - * Pumps stdout and stderr from running the process into a String. - * - * @param processBuilder ProcessBuilder to run. - * @return Output from process. - * @throws IOException If an I/O error occurs. - */ - public static OutputBuffer getOutput(ProcessBuilder processBuilder) throws IOException { - return getOutput(processBuilder.start()); - } - - /** - * Pumps stdout and stderr the running process into a String. - * - * @param process Process to pump. - * @return Output from process. - * @throws IOException If an I/O error occurs. - */ - public static OutputBuffer getOutput(Process process) throws IOException { - ByteArrayOutputStream stderrBuffer = new ByteArrayOutputStream(); - ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream(); - StreamPumper outPumper = new StreamPumper(process.getInputStream(), stdoutBuffer); - StreamPumper errPumper = new StreamPumper(process.getErrorStream(), stderrBuffer); - Thread outPumperThread = new Thread(outPumper); - Thread errPumperThread = new Thread(errPumper); - - outPumperThread.setDaemon(true); - errPumperThread.setDaemon(true); - - outPumperThread.start(); - errPumperThread.start(); - - try { - process.waitFor(); - outPumperThread.join(); - errPumperThread.join(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return null; - } - - return new OutputBuffer(stdoutBuffer.toString(), stderrBuffer.toString()); - } - - /** - *

Starts a process from its builder.

- * The default redirects of STDOUT and STDERR are started - * @param name The process name - * @param processBuilder The process builder - * @return Returns the initialized process - * @throws IOException - */ - public static Process startProcess(String name, - ProcessBuilder processBuilder) - throws IOException { - return startProcess(name, processBuilder, (Consumer)null); - } - - /** - *

Starts a process from its builder.

- * The default redirects of STDOUT and STDERR are started - *

It is possible to monitor the in-streams via the provided {@code consumer} - * @param name The process name - * @param consumer {@linkplain Consumer} instance to process the in-streams - * @param processBuilder The process builder - * @return Returns the initialized process - * @throws IOException - */ - @SuppressWarnings("overloads") - public static Process startProcess(String name, - ProcessBuilder processBuilder, - Consumer consumer) - throws IOException { - try { - return startProcess(name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS); - } catch (InterruptedException | TimeoutException e) { - // will never happen - throw new RuntimeException(e); - } - } - - /** - *

Starts a process from its builder.

- * The default redirects of STDOUT and STDERR are started - *

- * It is possible to wait for the process to get to a warmed-up state - * via {@linkplain Predicate} condition on the STDOUT - *

- * @param name The process name - * @param processBuilder The process builder - * @param linePredicate The {@linkplain Predicate} to use on the STDOUT - * Used to determine the moment the target app is - * properly warmed-up. - * It can be null - in that case the warmup is skipped. - * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever - * @param unit The timeout {@linkplain TimeUnit} - * @return Returns the initialized {@linkplain Process} - * @throws IOException - * @throws InterruptedException - * @throws TimeoutException - */ - public static Process startProcess(String name, - ProcessBuilder processBuilder, - final Predicate linePredicate, - long timeout, - TimeUnit unit) - throws IOException, InterruptedException, TimeoutException { - return startProcess(name, processBuilder, null, linePredicate, timeout, unit); - } - - /** - *

Starts a process from its builder.

- * The default redirects of STDOUT and STDERR are started - *

- * It is possible to wait for the process to get to a warmed-up state - * via {@linkplain Predicate} condition on the STDOUT and monitor the - * in-streams via the provided {@linkplain Consumer} - *

- * @param name The process name - * @param processBuilder The process builder - * @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to - * @param linePredicate The {@linkplain Predicate} to use on the STDOUT - * Used to determine the moment the target app is - * properly warmed-up. - * It can be null - in that case the warmup is skipped. - * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever - * @param unit The timeout {@linkplain TimeUnit} - * @return Returns the initialized {@linkplain Process} - * @throws IOException - * @throws InterruptedException - * @throws TimeoutException - */ - public static Process startProcess(String name, - ProcessBuilder processBuilder, - final Consumer lineConsumer, - final Predicate linePredicate, - long timeout, - TimeUnit unit) - throws IOException, InterruptedException, TimeoutException { - System.out.println("["+name+"]:" + processBuilder.command().stream().collect(Collectors.joining(" "))); - Process p = processBuilder.start(); - StreamPumper stdout = new StreamPumper(p.getInputStream()); - StreamPumper stderr = new StreamPumper(p.getErrorStream()); - - stdout.addPump(new LineForwarder(name, System.out)); - stderr.addPump(new LineForwarder(name, System.err)); - if (lineConsumer != null) { - StreamPumper.LinePump pump = new StreamPumper.LinePump() { - @Override - protected void processLine(String line) { - lineConsumer.accept(line); - } - }; - stdout.addPump(pump); - stderr.addPump(pump); - } - - - CountDownLatch latch = new CountDownLatch(1); - if (linePredicate != null) { - StreamPumper.LinePump pump = new StreamPumper.LinePump() { - @Override - protected void processLine(String line) { - if (latch.getCount() > 0 && linePredicate.test(line)) { - latch.countDown(); - } - } - }; - stdout.addPump(pump); - stderr.addPump(pump); - } else { - latch.countDown(); - } - final Future stdoutTask = stdout.process(); - final Future stderrTask = stderr.process(); - - try { - if (timeout > -1) { - if (timeout == 0) { - latch.await(); - } else { - if (!latch.await(Utils.adjustTimeout(timeout), unit)) { - throw new TimeoutException(); - } - } - } - } catch (TimeoutException | InterruptedException e) { - System.err.println("Failed to start a process (thread dump follows)"); - for(Map.Entry s : Thread.getAllStackTraces().entrySet()) { - printStack(s.getKey(), s.getValue()); - } - - if (p.isAlive()) { - p.destroyForcibly(); - } - - stdoutTask.cancel(true); - stderrTask.cancel(true); - throw e; - } - - return new ProcessImpl(p, stdoutTask, stderrTask); - } - - /** - *

Starts a process from its builder.

- * The default redirects of STDOUT and STDERR are started - *

- * It is possible to wait for the process to get to a warmed-up state - * via {@linkplain Predicate} condition on the STDOUT. The warm-up will - * wait indefinitely. - *

- * @param name The process name - * @param processBuilder The process builder - * @param linePredicate The {@linkplain Predicate} to use on the STDOUT - * Used to determine the moment the target app is - * properly warmed-up. - * It can be null - in that case the warmup is skipped. - * @return Returns the initialized {@linkplain Process} - * @throws IOException - * @throws InterruptedException - * @throws TimeoutException - */ - @SuppressWarnings("overloads") - public static Process startProcess(String name, - ProcessBuilder processBuilder, - final Predicate linePredicate) - throws IOException, InterruptedException, TimeoutException { - return startProcess(name, processBuilder, linePredicate, 0, TimeUnit.SECONDS); - } - - /** - * Get the process id of the current running Java process - * - * @return Process id - */ - public static long getProcessId() throws Exception { - final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); - - final int index = jvmName.indexOf('@'); - - if (index < 1) { - // part before '@' empty (index = 0) / '@' not found (index = -1) - return 42; - } - - try { - return Long.parseLong(jvmName.substring(0, index)); - } catch (NumberFormatException e) { - // ignore - } - return 42; - } - - - - /** - * Create ProcessBuilder using the java launcher from the jdk to be tested and - * with any platform specific arguments prepended - */ - public static ProcessBuilder createJavaProcessBuilder(String... command) { - return createJavaProcessBuilder(false, command); - } - - /** - * Create ProcessBuilder using the java launcher from the jdk to be tested, - * and with any platform specific arguments prepended. - * - * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts - * to the java arguments. - * @param command Arguments to pass to the java command. - * @return The ProcessBuilder instance representing the java command. - */ - public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) { - String javapath = JDKToolFinder.getJDKTool("java"); - - ArrayList args = new ArrayList<>(); - args.add(javapath); - - args.add("-cp"); - args.add(System.getProperty("java.class.path")); - - if (addTestVmAndJavaOptions) { - Collections.addAll(args, Utils.getTestJavaOpts()); - } - - Collections.addAll(args, command); - - // Reporting - StringBuilder cmdLine = new StringBuilder(); - for (String cmd : args) - cmdLine.append(cmd).append(' '); - System.out.println("Command line: [" + cmdLine.toString() + "]"); - - return new ProcessBuilder(args.toArray(new String[args.size()])); - } - - private static void printStack(Thread t, StackTraceElement[] stack) { - System.out.println("\t" + t + - " stack: (length = " + stack.length + ")"); - if (t != null) { - for (StackTraceElement stack1 : stack) { - System.out.println("\t" + stack1); - } - System.out.println(); - } - } - - /** - * Executes a test jvm process, waits for it to finish and returns the process output. - * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. - * The java from the test.jdk is used to execute the command. - * - * The command line will be like: - * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds - * - * The jvm process will have exited before this method returns. - * - * @param cmds User specified arguments. - * @return The output from the process. - */ - public static OutputAnalyzer executeTestJvm(String... cmds) throws Exception { - ProcessBuilder pb = createJavaProcessBuilder(Utils.addTestJavaOpts(cmds)); - return executeProcess(pb); - } - - /** - * @see #executeTestJvm(String...) - * @param cmds User specified arguments. - * @return The output from the process. - */ - public static OutputAnalyzer executeTestJava(String... cmds) throws Exception { - return executeTestJvm(cmds); - } - - /** - * Executes a process, waits for it to finish and returns the process output. - * The process will have exited before this method returns. - * @param pb The ProcessBuilder to execute. - * @return The {@linkplain OutputAnalyzer} instance wrapping the process. - */ - public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Exception { - OutputAnalyzer output = null; - Process p = null; - boolean failed = false; - try { - p = pb.start(); - output = new OutputAnalyzer(p); - p.waitFor(); - - return output; - } catch (Throwable t) { - if (p != null) { - p.destroyForcibly().waitFor(); - } - - failed = true; - System.out.println("executeProcess() failed: " + t); - throw t; - } finally { - if (failed) { - System.err.println(getProcessLog(pb, output)); - } - } - } - - /** - * Executes a process, waits for it to finish and returns the process output. - * - * The process will have exited before this method returns. - * - * @param cmds The command line to execute. - * @return The output from the process. - */ - public static OutputAnalyzer executeProcess(String... cmds) throws Throwable { - return executeProcess(new ProcessBuilder(cmds)); - } - - /** - * Used to log command line, stdout, stderr and exit code from an executed process. - * @param pb The executed process. - * @param output The output from the process. - */ - public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) { - String stderr = output == null ? "null" : output.getStderr(); - String stdout = output == null ? "null" : output.getStdout(); - String exitValue = output == null ? "null": Integer.toString(output.getExitValue()); - StringBuilder logMsg = new StringBuilder(); - final String nl = System.getProperty("line.separator"); - logMsg.append("--- ProcessLog ---" + nl); - logMsg.append("cmd: " + getCommandLine(pb) + nl); - logMsg.append("exitvalue: " + exitValue + nl); - logMsg.append("stderr: " + stderr + nl); - logMsg.append("stdout: " + stdout + nl); - - return logMsg.toString(); - } - - /** - * @return The full command line for the ProcessBuilder. - */ - public static String getCommandLine(ProcessBuilder pb) { - if (pb == null) { - return "null"; - } - StringBuilder cmd = new StringBuilder(); - for (String s : pb.command()) { - cmd.append(s).append(" "); - } - return cmd.toString().trim(); - } - - /** - * Executes a process, waits for it to finish, prints the process output - * to stdout, and returns the process output. - * - * The process will have exited before this method returns. - * - * @param cmds The command line to execute. - * @return The {@linkplain OutputAnalyzer} instance wrapping the process. - */ - public static OutputAnalyzer executeCommand(String... cmds) - throws Throwable { - String cmdLine = Arrays.stream(cmds).collect(Collectors.joining(" ")); - System.out.println("Command line: [" + cmdLine + "]"); - OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds); - System.out.println(analyzer.getOutput()); - return analyzer; - } - - /** - * Executes a process, waits for it to finish, prints the process output - * to stdout and returns the process output. - * - * The process will have exited before this method returns. - * - * @param pb The ProcessBuilder to execute. - * @return The {@linkplain OutputAnalyzer} instance wrapping the process. - */ - public static OutputAnalyzer executeCommand(ProcessBuilder pb) - throws Throwable { - String cmdLine = pb.command().stream().collect(Collectors.joining(" ")); - System.out.println("Command line: [" + cmdLine + "]"); - OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); - System.out.println(analyzer.getOutput()); - return analyzer; - } - - private static class ProcessImpl extends Process { - - private final Process p; - private final Future stdoutTask; - private final Future stderrTask; - - public ProcessImpl(Process p, Future stdoutTask, Future stderrTask) { - this.p = p; - this.stdoutTask = stdoutTask; - this.stderrTask = stderrTask; - } - - @Override - public OutputStream getOutputStream() { - return p.getOutputStream(); - } - - @Override - public InputStream getInputStream() { - return p.getInputStream(); - } - - @Override - public InputStream getErrorStream() { - return p.getErrorStream(); - } - - @Override - public int waitFor() throws InterruptedException { - int rslt = p.waitFor(); - waitForStreams(); - return rslt; - } - - @Override - public int exitValue() { - return p.exitValue(); - } - - @Override - public void destroy() { - p.destroy(); - } - - public long pid() { - try { - return ProcessTools.getProcessId(); - } catch (Exception e) { - //shit happens, ignore - } - return 42; - } - - @Override - public boolean isAlive() { - return p.isAlive(); - } - - @Override - public Process destroyForcibly() { - return p.destroyForcibly(); - } - - @Override - public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { - boolean rslt = p.waitFor(timeout, unit); - if (rslt) { - waitForStreams(); - } - return rslt; - } - - private void waitForStreams() throws InterruptedException { - try { - stdoutTask.get(); - } catch (ExecutionException e) { - } - try { - stderrTask.get(); - } catch (ExecutionException e) { - } - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/StreamPumper.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/StreamPumper.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/StreamPumper.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/process/StreamPumper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.process; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; -import java.util.concurrent.atomic.AtomicBoolean; - -public final class StreamPumper implements Runnable { - - private static final int BUF_SIZE = 256; - - /** - * Pump will be called by the StreamPumper to process the incoming data - */ - abstract public static class Pump { - abstract void register(StreamPumper d); - } - - /** - * OutputStream -> Pump adapter - */ - final public static class StreamPump extends Pump { - private final OutputStream out; - public StreamPump(OutputStream out) { - this.out = out; - } - - @Override - void register(StreamPumper sp) { - sp.addOutputStream(out); - } - } - - /** - * Used to process the incoming data line-by-line - */ - abstract public static class LinePump extends Pump { - @Override - final void register(StreamPumper sp) { - sp.addLineProcessor(this); - } - - abstract protected void processLine(String line); - } - - private final InputStream in; - private final Set outStreams = new HashSet<>(); - private final Set linePumps = new HashSet<>(); - - private final AtomicBoolean processing = new AtomicBoolean(false); - private final FutureTask processingTask = new FutureTask<>(this, null); - - public StreamPumper(InputStream in) { - this.in = in; - } - - /** - * Create a StreamPumper that reads from in and writes to out. - * - * @param in The stream to read from. - * @param out The stream to write to. - */ - public StreamPumper(InputStream in, OutputStream out) { - this(in); - this.addOutputStream(out); - } - - /** - * Implements Thread.run(). Continuously read from {@code in} and write to - * {@code out} until {@code in} has reached end of stream. Abort on - * interruption. Abort on IOExceptions. - */ - @Override - public void run() { - try (BufferedInputStream is = new BufferedInputStream(in)) { - ByteArrayOutputStream lineBos = new ByteArrayOutputStream(); - byte[] buf = new byte[BUF_SIZE]; - int len = 0; - int linelen = 0; - - while ((len = is.read(buf)) > 0 && !Thread.interrupted()) { - for(OutputStream out : outStreams) { - out.write(buf, 0, len); - } - if (!linePumps.isEmpty()) { - int i = 0; - int lastcrlf = -1; - while (i < len) { - if (buf[i] == '\n' || buf[i] == '\r') { - int bufLinelen = i - lastcrlf - 1; - if (bufLinelen > 0) { - lineBos.write(buf, lastcrlf + 1, bufLinelen); - } - linelen += bufLinelen; - - if (linelen > 0) { - lineBos.flush(); - final String line = lineBos.toString(); - linePumps.stream().forEach((lp) -> { - lp.processLine(line); - }); - lineBos.reset(); - linelen = 0; - } - lastcrlf = i; - } - - i++; - } - if (lastcrlf == -1) { - lineBos.write(buf, 0, len); - linelen += len; - } else if (lastcrlf < len - 1) { - lineBos.write(buf, lastcrlf + 1, len - lastcrlf - 1); - linelen += len - lastcrlf - 1; - } - } - } - - } catch (IOException e) { - e.printStackTrace(); - } finally { - for(OutputStream out : outStreams) { - try { - out.flush(); - } catch (IOException e) {} - } - try { - in.close(); - } catch (IOException e) {} - } - } - - final void addOutputStream(OutputStream out) { - outStreams.add(out); - } - - final void addLineProcessor(LinePump lp) { - linePumps.add(lp); - } - - final public StreamPumper addPump(Pump ... pump) { - if (processing.get()) { - throw new IllegalStateException("Can not modify pumper while " + - "processing is in progress"); - } - for(Pump p : pump) { - p.register(this); - } - return this; - } - - final public Future process() { - if (!processing.compareAndSet(false, true)) { - throw new IllegalStateException("Can not re-run the processing"); - } - Thread t = new Thread(new Runnable() { - @Override - public void run() { - processingTask.run(); - } - }); - t.setDaemon(true); - t.start(); - - return processingTask; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/TestThread.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/TestThread.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/TestThread.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/TestThread.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.thread; - -import java.util.concurrent.TimeoutException; - -/** - * Thread which catches exceptions thrown during the execution - * and stores them for later analysis. - * - *
- * {@code
- * TestThread thread = new TestThread(new XRun() {
- *      public void run() {
- *      // do something
- *      }
- * });
- * thread.start();
- * // do something
- * Throwable uncaught = thread.getUncaught();
- * }
- * 
- */ -public class TestThread extends Thread { - - private final Runnable runnable; - private volatile Throwable uncaught; - - /** - * Returns {@link Runnable} the thread has been created with. - * - * @return The object whose {@code run} method is called - */ - public Runnable getRunnable() { - return runnable; - } - - /** - * Creates a new {@code TestThread} object. - * - * @param target The object whose {@code run} method is called - * @param name The thread name - */ - public TestThread(Runnable target, String name) { - super(target, name); - this.runnable = target; - } - - /** - * Creates a new {@code TestThread} object. - * - * @param target The object whose {@code run} method is called - */ - public TestThread(Runnable target) { - super(target); - this.runnable = target; - } - - /** - * Creates a new {@code TestThread} object. - * - * @param group The thread group - * @param target The object whose {@code run} method is called - * @param name The thread name - * @param stackSize Stack size - */ - public TestThread(ThreadGroup group, Runnable target, String name, - long stackSize) { - super(group, target, name, stackSize); - this.runnable = target; - } - - /** - * Creates a new {@code TestThread} object. - * - * @param group The thread group - * @param target The object whose {@code run} method is called - * @param name The thread name - */ - public TestThread(ThreadGroup group, Runnable target, String name) { - super(group, target, name); - this.runnable = target; - } - - /** - * Creates a new {@code TestThread} object. - * - * @param group The thread group - * @param target The object whose {@code run} method is called - */ - public TestThread(ThreadGroup group, Runnable target) { - super(group, target); - this.runnable = target; - } - - /** - * The thread executor. - */ - @Override - public void run() { - try { - super.run(); - } catch (Throwable t) { - uncaught = t; - } - } - - /** - * Returns exception caught during the execution. - * - * @return {@link Throwable} - */ - public Throwable getUncaught() { - return uncaught; - } - - /** - * Waits for {@link TestThread} to die - * and throws exception caught during the execution. - * - * @throws InterruptedException - * @throws Throwable - */ - public void joinAndThrow() throws InterruptedException, Throwable { - join(); - if (uncaught != null) { - throw uncaught; - } - } - - /** - * Waits during {@code timeout} for {@link TestThread} to die - * and throws exception caught during the execution. - * - * @param timeout The time to wait in milliseconds - * @throws InterruptedException - * @throws Throwable - */ - public void joinAndThrow(long timeout) throws InterruptedException, - Throwable { - join(timeout); - if (isAlive()) { - throw new TimeoutException(); - } - if (uncaught != null) { - throw uncaught; - } - } - - /** - * Waits for {@link TestThread} to die - * and returns exception caught during the execution. - * - * @return Exception caught during the execution - * @throws InterruptedException - */ - public Throwable joinAndReturn() throws InterruptedException { - join(); - if (uncaught != null) { - return uncaught; - } - return null; - } - - /** - * Waits during {@code timeout} for {@link TestThread} to die - * and returns exception caught during the execution. - * - * @param timeout The time to wait in milliseconds - * @return Exception caught during the execution - * @throws InterruptedException - */ - public Throwable joinAndReturn(long timeout) throws InterruptedException { - join(timeout); - if (isAlive()) { - return new TimeoutException(); - } - if (uncaught != null) { - return uncaught; - } - return null; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/XRun.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/XRun.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/XRun.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/thread/XRun.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.thread; - -/** - * This type serves no other purpose than to simply allow automatically running - * something in a thread, and have all exceptions propagated to - * RuntimeExceptions, which are thrown up to thread, which in turn should - * probably be a {@link TestThread} to they are stored. - */ -public abstract class XRun implements Runnable { - - /** - * Invokes {@code xrun()} and throws all exceptions caught in it - * up to the thread. - */ - public final void run() { - try { - xrun(); - } catch (Error e) { - throw e; - } catch (RuntimeException e) { - throw e; - } catch (Throwable e) { - throw new RuntimeException(e); - } - } - - /** - * Override this method to implement what to run in the thread. - * - * @throws Throwable - */ - protected abstract void xrun() throws Throwable; -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/JarUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/JarUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/JarUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/JarUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.util; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.InvalidPathException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; - -/** - * Common library for various test jar file utility functions. - */ -public final class JarUtils { - - /** - * Create jar file with specified files. If a specified file does not exist, - * a new jar entry will be created with the file name itself as the content. - */ - public static void createJar(String dest, String... files) - throws IOException { - try (JarOutputStream jos = new JarOutputStream( - new FileOutputStream(dest), new Manifest())) { - for (String file : files) { - System.out.println(String.format("Adding %s to %s", - file, dest)); - - // add an archive entry, and write a file - jos.putNextEntry(new JarEntry(file)); - try (FileInputStream fis = new FileInputStream(file)) { - fis.transferTo(jos); - } catch (FileNotFoundException e) { - jos.write(file.getBytes()); - } - } - } - System.out.println(); - } - - /** - * Add or remove specified files to existing jar file. If a specified file - * to be updated or added does not exist, the jar entry will be created - * with the file name itself as the content. - * - * @param src the original jar file name - * @param dest the new jar file name - * @param files the files to update. The list is broken into 2 groups - * by a "-" string. The files before in the 1st group will - * be either updated or added. The files in the 2nd group - * will be removed. If no "-" exists, all files belong to - * the 1st group. - */ - public static void updateJar(String src, String dest, String... files) - throws IOException { - Map changes = new HashMap<>(); - boolean update = true; - for (String file : files) { - if (file.equals("-")) { - update = false; - } else if (update) { - try { - Path p = Paths.get(file); - if (Files.exists(p)) { - changes.put(file, p); - } else { - changes.put(file, file); - } - } catch (InvalidPathException e) { - // Fallback if file not a valid Path. - changes.put(file, file); - } - } else { - changes.put(file, Boolean.FALSE); - } - } - updateJar(src, dest, changes); - } - - /** - * Update content of a jar file. - * - * @param src the original jar file name - * @param dest the new jar file name - * @param changes a map of changes, key is jar entry name, value is content. - * Value can be Path, byte[] or String. If key exists in - * src but value is Boolean FALSE. The entry is removed. - * Existing entries in src not a key is unmodified. - * @throws IOException - */ - public static void updateJar(String src, String dest, - Map changes) - throws IOException { - - // What if input changes is immutable? - changes = new HashMap<>(changes); - - System.out.printf("Creating %s from %s...\n", dest, src); - try (JarOutputStream jos = new JarOutputStream( - new FileOutputStream(dest))) { - - try (JarFile srcJarFile = new JarFile(src)) { - Enumeration entries = srcJarFile.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - String name = entry.getName(); - if (changes.containsKey(name)) { - System.out.println(String.format("- Update %s", name)); - updateEntry(jos, name, changes.get(name)); - changes.remove(name); - } else { - System.out.println(String.format("- Copy %s", name)); - jos.putNextEntry(entry); - srcJarFile.getInputStream(entry).transferTo(jos); - } - } - } - for (Map.Entry e : changes.entrySet()) { - System.out.println(String.format("- Add %s", e.getKey())); - updateEntry(jos, e.getKey(), e.getValue()); - } - } - System.out.println(); - } - - private static void updateEntry(JarOutputStream jos, String name, Object content) - throws IOException { - if (content instanceof Boolean) { - if (((Boolean) content).booleanValue()) { - throw new RuntimeException("Boolean value must be FALSE"); - } - } else { - jos.putNextEntry(new JarEntry(name)); - if (content instanceof Path) { - Files.newInputStream((Path) content).transferTo(jos); - } else if (content instanceof byte[]) { - jos.write((byte[]) content); - } else if (content instanceof String) { - jos.write(((String) content).getBytes()); - } else { - throw new RuntimeException("Unknown type " + content.getClass()); - } - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Pair.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Pair.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Pair.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Pair.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.util; - -import java.util.Objects; - -/** - * Pair - a two element tuple - * - * @param first type - * @param second type - */ -public class Pair { - public final F first; - public final S second; - - public Pair(F first, S second) { - this.first = first; - this.second = second; - } - - @Override - public String toString() { - return "(" + first + ":" + second + ")"; - } - - @Override - public boolean equals(Object other) { - if (other instanceof Pair) { - Pair otherPair = (Pair) other; - return Objects.equals(first, otherPair.first) && - Objects.equals(second, otherPair.second); - } - return false; - } - - @Override - public int hashCode() { - if (first == null) { - return (second == null) ? 0 : second.hashCode(); - } else if (second == null) { - return first.hashCode(); - } else { - return first.hashCode() * 17 + second.hashCode(); - } - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/SerializationUtils.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/SerializationUtils.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/SerializationUtils.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/SerializationUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -/** - * Common library for various test serialization utility functions. - */ -public final class SerializationUtils { - /** - * Serialize an object into byte array. - */ - public static byte[] serialize(Object obj) throws IOException { - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - try (ObjectOutputStream out = new ObjectOutputStream(bs)) { - out.writeObject(obj); - } - return bs.toByteArray(); - } - - /** - * Deserialize an object from byte array. - */ - public static Object deserialize(byte[] ba) throws IOException, ClassNotFoundException { - try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(ba))) { - return in.readObject(); - } - } - private SerializationUtils() {} -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Triple.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Triple.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Triple.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/jdk/test/lib/util/Triple.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.test.lib.util; - -import java.util.Objects; - -/** - * Triple - a three element tuple - * - * @param first element type - * @param second element type - * @param third element type - */ -public class Triple { - private final Pair> container; - - /** - * Constructor - * - * @param first first element of the triple - * @param second second element of the triple - * @param third third element of the triple - */ - public Triple(F first, S second, T third) { - container = new Pair<>(first, new Pair<>(second, third)); - } - - /** - * Gets first element of the triple - */ - public F getFirst() { - return container.first; - } - - /** - * Gets second element of the triple - */ - public S getSecond() { - return container.second.first; - } - - /** - * Gets third element of the triple - */ - public T getThird() { - return container.second.second; - } - - @Override - public int hashCode() { - return container.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Triple) { - Triple objTriple = (Triple) obj; - return Objects.equals(container.first, objTriple.container.first) - && Objects.equals(container.second, - objTriple.container.second); - } - return false; - } - - @Override - public String toString() { - return "(" + getFirst() + " : " + getSecond() + " : " + getThird() + ")"; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/WhiteBox.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/WhiteBox.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/WhiteBox.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/WhiteBox.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,450 +0,0 @@ -/* - * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot; - -import java.lang.management.MemoryUsage; -import java.lang.reflect.Executable; -import java.util.Arrays; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.security.BasicPermission; -import java.util.Objects; -import java.net.URL; - -import sun.hotspot.parser.DiagnosticCommand; - -public class WhiteBox { - @SuppressWarnings("serial") - public static class WhiteBoxPermission extends BasicPermission { - public WhiteBoxPermission(String s) { - super(s); - } - } - - private WhiteBox() {} - private static final WhiteBox instance = new WhiteBox(); - private static native void registerNatives(); - - /** - * Returns the singleton WhiteBox instance. - * - * The returned WhiteBox object should be carefully guarded - * by the caller, since it can be used to read and write data - * at arbitrary memory addresses. It must never be passed to - * untrusted code. - */ - public synchronized static WhiteBox getWhiteBox() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new WhiteBoxPermission("getInstance")); - } - return instance; - } - - static { - registerNatives(); - } - - // Get the maximum heap size supporting COOPs - public native long getCompressedOopsMaxHeapSize(); - // Arguments - public native void printHeapSizes(); - - // Memory - public native long getObjectAddress(Object o); - public native int getHeapOopSize(); - public native int getVMPageSize(); - public native long getVMAllocationGranularity(); - public native long getVMLargePageSize(); - public native long getHeapSpaceAlignment(); - public native long getHeapAlignment(); - - public native boolean isObjectInOldGen(Object o); - public native long getObjectSize(Object o); - - public native boolean classKnownToNotExist(ClassLoader loader, String name); - public native URL[] getLookupCacheURLs(ClassLoader loader); - public native int[] getLookupCacheMatches(ClassLoader loader, String name); - - // Runtime - // Make sure class name is in the correct format - public boolean isClassAlive(String name) { - return isClassAlive0(name.replace('.', '/')); - } - private native boolean isClassAlive0(String name); - - public native boolean isMonitorInflated(Object obj); - - public native void forceSafepoint(); - - private native long getConstantPool0(Class aClass); - public long getConstantPool(Class aClass) { - Objects.requireNonNull(aClass); - return getConstantPool0(aClass); - } - - private native int getConstantPoolCacheIndexTag0(); - public int getConstantPoolCacheIndexTag() { - return getConstantPoolCacheIndexTag0(); - } - - private native int getConstantPoolCacheLength0(Class aClass); - public int getConstantPoolCacheLength(Class aClass) { - Objects.requireNonNull(aClass); - return getConstantPoolCacheLength0(aClass); - } - - private native int remapInstructionOperandFromCPCache0(Class aClass, int index); - public int remapInstructionOperandFromCPCache(Class aClass, int index) { - Objects.requireNonNull(aClass); - return remapInstructionOperandFromCPCache0(aClass, index); - } - - private native int encodeConstantPoolIndyIndex0(int index); - public int encodeConstantPoolIndyIndex(int index) { - return encodeConstantPoolIndyIndex0(index); - } - - // JVMTI - public native void addToBootstrapClassLoaderSearch(String segment); - public native void addToSystemClassLoaderSearch(String segment); - - // G1 - public native boolean g1InConcurrentMark(); - public native boolean g1IsHumongous(Object o); - public native boolean g1BelongsToHumongousRegion(long adr); - public native boolean g1BelongsToFreeRegion(long adr); - public native long g1NumMaxRegions(); - public native long g1NumFreeRegions(); - public native int g1RegionSize(); - public native MemoryUsage g1AuxiliaryMemoryUsage(); - public native Object[] parseCommandLine(String commandline, DiagnosticCommand[] args); - - // Parallel GC - public native long psVirtualSpaceAlignment(); - public native long psHeapGenerationAlignment(); - - /** - * Enumerates old regions with liveness less than specified and produces some statistics - * @param liveness percent of region's liveness (live_objects / total_region_size * 100). - * @return long[3] array where long[0] - total count of old regions - * long[1] - total memory of old regions - * long[2] - lowest estimation of total memory of old regions to be freed (non-full - * regions are not included) - */ - public native long[] g1GetMixedGCInfo(int liveness); - - // NMT - public native long NMTMalloc(long size); - public native void NMTFree(long mem); - public native long NMTReserveMemory(long size); - public native long NMTAttemptReserveMemoryAt(long addr, long size); - public native void NMTCommitMemory(long addr, long size); - public native void NMTUncommitMemory(long addr, long size); - public native void NMTReleaseMemory(long addr, long size); - public native long NMTMallocWithPseudoStack(long size, int index); - public native long NMTMallocWithPseudoStackAndType(long size, int index, int type); - public native boolean NMTIsDetailSupported(); - public native boolean NMTChangeTrackingLevel(); - public native int NMTGetHashSize(); - - // Compiler - public native int matchesMethod(Executable method, String pattern); - public native int matchesInline(Executable method, String pattern); - public native boolean shouldPrintAssembly(Executable method, int comp_level); - public native int deoptimizeFrames(boolean makeNotEntrant); - public native void deoptimizeAll(); - - public boolean isMethodCompiled(Executable method) { - return isMethodCompiled(method, false /*not osr*/); - } - public native boolean isMethodCompiled(Executable method, boolean isOsr); - public boolean isMethodCompilable(Executable method) { - return isMethodCompilable(method, -2 /*any*/); - } - public boolean isMethodCompilable(Executable method, int compLevel) { - return isMethodCompilable(method, compLevel, false /*not osr*/); - } - public native boolean isMethodCompilable(Executable method, int compLevel, boolean isOsr); - - public native boolean isMethodQueuedForCompilation(Executable method); - - // Determine if the compiler corresponding to the compilation level 'compLevel' - // and to the compilation context 'compilation_context' provides an intrinsic - // for the method 'method'. An intrinsic is available for method 'method' if: - // - the intrinsic is enabled (by using the appropriate command-line flag) and - // - the platform on which the VM is running provides the instructions necessary - // for the compiler to generate the intrinsic code. - // - // The compilation context is related to using the DisableIntrinsic flag on a - // per-method level, see hotspot/src/share/vm/compiler/abstractCompiler.hpp - // for more details. - public boolean isIntrinsicAvailable(Executable method, - Executable compilationContext, - int compLevel) { - Objects.requireNonNull(method); - return isIntrinsicAvailable0(method, compilationContext, compLevel); - } - // If usage of the DisableIntrinsic flag is not expected (or the usage can be ignored), - // use the below method that does not require the compilation context as argument. - public boolean isIntrinsicAvailable(Executable method, int compLevel) { - return isIntrinsicAvailable(method, null, compLevel); - } - private native boolean isIntrinsicAvailable0(Executable method, - Executable compilationContext, - int compLevel); - public int deoptimizeMethod(Executable method) { - return deoptimizeMethod(method, false /*not osr*/); - } - public native int deoptimizeMethod(Executable method, boolean isOsr); - public void makeMethodNotCompilable(Executable method) { - makeMethodNotCompilable(method, -2 /*any*/); - } - public void makeMethodNotCompilable(Executable method, int compLevel) { - makeMethodNotCompilable(method, compLevel, false /*not osr*/); - } - public native void makeMethodNotCompilable(Executable method, int compLevel, boolean isOsr); - public int getMethodCompilationLevel(Executable method) { - return getMethodCompilationLevel(method, false /*not ost*/); - } - public native int getMethodCompilationLevel(Executable method, boolean isOsr); - public native boolean testSetDontInlineMethod(Executable method, boolean value); - public int getCompileQueuesSize() { - return getCompileQueueSize(-2 /*any*/); - } - public native int getCompileQueueSize(int compLevel); - public native boolean testSetForceInlineMethod(Executable method, boolean value); - - public boolean enqueueMethodForCompilation(Executable method, int compLevel) { - return enqueueMethodForCompilation(method, compLevel, -1 /*InvocationEntryBci*/); - } - private native boolean enqueueMethodForCompilation0(Executable method, int compLevel, int entry_bci); - public boolean enqueueMethodForCompilation(Executable method, int compLevel, int entry_bci) { - Objects.requireNonNull(method); - return enqueueMethodForCompilation0(method, compLevel, entry_bci); - } - private native boolean enqueueInitializerForCompilation0(Class aClass, int compLevel); - public boolean enqueueInitializerForCompilation(Class aClass, int compLevel) { - Objects.requireNonNull(aClass); - return enqueueInitializerForCompilation0(aClass, compLevel); - } - public native void clearMethodState(Executable method); - public native void markMethodProfiled(Executable method); - public native void lockCompilation(); - public native void unlockCompilation(); - public native int getMethodEntryBci(Executable method); - public native Object[] getNMethod(Executable method, boolean isOsr); - public native long allocateCodeBlob(int size, int type); - public long allocateCodeBlob(long size, int type) { - int intSize = (int) size; - if ((long) intSize != size || size < 0) { - throw new IllegalArgumentException( - "size argument has illegal value " + size); - } - return allocateCodeBlob( intSize, type); - } - public native void freeCodeBlob(long addr); - public native Object[] getCodeHeapEntries(int type); - public native int getCompilationActivityMode(); - private native long getMethodData0(Executable method); - public long getMethodData(Executable method) { - Objects.requireNonNull(method); - return getMethodData0(method); - } - public native Object[] getCodeBlob(long addr); - - private native void clearInlineCaches0(boolean preserve_static_stubs); - public void clearInlineCaches() { - clearInlineCaches0(false); - } - public void clearInlineCaches(boolean preserve_static_stubs) { - clearInlineCaches0(preserve_static_stubs); - } - - // Intered strings - public native boolean isInStringTable(String str); - - // Memory - public native void readReservedMemory(); - public native long allocateMetaspace(ClassLoader classLoader, long size); - public native void freeMetaspace(ClassLoader classLoader, long addr, long size); - public native long incMetaspaceCapacityUntilGC(long increment); - public native long metaspaceCapacityUntilGC(); - public native boolean metaspaceShouldConcurrentCollect(); - public native long metaspaceReserveAlignment(); - - // Don't use these methods directly - // Use sun.hotspot.gc.GC class instead. - public native boolean isGCSupported(int name); - public native boolean isGCSelected(int name); - public native boolean isGCSelectedErgonomically(); - - // Force Young GC - public native void youngGC(); - - // Force Full GC - public native void fullGC(); - - // Returns true if the current GC supports control of its concurrent - // phase via requestConcurrentGCPhase(). If false, a request will - // always fail. - public native boolean supportsConcurrentGCPhaseControl(); - - // Returns an array of concurrent phase names provided by this - // collector. These are the names recognized by - // requestConcurrentGCPhase(). - public native String[] getConcurrentGCPhases(); - - // Attempt to put the collector into the indicated concurrent phase, - // and attempt to remain in that state until a new request is made. - // - // Returns immediately if already in the requested phase. - // Otherwise, waits until the phase is reached. - // - // Throws IllegalStateException if unsupported by the current collector. - // Throws NullPointerException if phase is null. - // Throws IllegalArgumentException if phase is not valid for the current collector. - public void requestConcurrentGCPhase(String phase) { - if (!supportsConcurrentGCPhaseControl()) { - throw new IllegalStateException("Concurrent GC phase control not supported"); - } else if (phase == null) { - throw new NullPointerException("null phase"); - } else if (!requestConcurrentGCPhase0(phase)) { - throw new IllegalArgumentException("Unknown concurrent GC phase: " + phase); - } - } - - // Helper for requestConcurrentGCPhase(). Returns true if request - // succeeded, false if the phase is invalid. - private native boolean requestConcurrentGCPhase0(String phase); - - // Method tries to start concurrent mark cycle. - // It returns false if CM Thread is always in concurrent cycle. - public native boolean g1StartConcMarkCycle(); - - // Tests on ReservedSpace/VirtualSpace classes - public native int stressVirtualSpaceResize(long reservedSpaceSize, long magnitude, long iterations); - public native void runMemoryUnitTests(); - public native void readFromNoaccessArea(); - public native long getThreadStackSize(); - public native long getThreadRemainingStackSize(); - - // CPU features - public native String getCPUFeatures(); - - // VM flags - public native boolean isConstantVMFlag(String name); - public native boolean isLockedVMFlag(String name); - public native void setBooleanVMFlag(String name, boolean value); - public native void setIntVMFlag(String name, long value); - public native void setUintVMFlag(String name, long value); - public native void setIntxVMFlag(String name, long value); - public native void setUintxVMFlag(String name, long value); - public native void setUint64VMFlag(String name, long value); - public native void setSizeTVMFlag(String name, long value); - public native void setStringVMFlag(String name, String value); - public native void setDoubleVMFlag(String name, double value); - public native Boolean getBooleanVMFlag(String name); - public native Long getIntVMFlag(String name); - public native Long getUintVMFlag(String name); - public native Long getIntxVMFlag(String name); - public native Long getUintxVMFlag(String name); - public native Long getUint64VMFlag(String name); - public native Long getSizeTVMFlag(String name); - public native String getStringVMFlag(String name); - public native Double getDoubleVMFlag(String name); - private final List> flagsGetters = Arrays.asList( - this::getBooleanVMFlag, this::getIntVMFlag, this::getUintVMFlag, - this::getIntxVMFlag, this::getUintxVMFlag, this::getUint64VMFlag, - this::getSizeTVMFlag, this::getStringVMFlag, this::getDoubleVMFlag); - - public Object getVMFlag(String name) { - return flagsGetters.stream() - .map(f -> f.apply(name)) - .filter(x -> x != null) - .findAny() - .orElse(null); - } - - // Jigsaw - public native void DefineModule(Object module, boolean is_open, String version, - String location, Object[] packages); - public native void AddModuleExports(Object from_module, String pkg, Object to_module); - public native void AddReadsModule(Object from_module, Object source_module); - public native void AddModuleExportsToAllUnnamed(Object module, String pkg); - public native void AddModuleExportsToAll(Object module, String pkg); - - public native int getOffsetForName0(String name); - public int getOffsetForName(String name) throws Exception { - int offset = getOffsetForName0(name); - if (offset == -1) { - throw new RuntimeException(name + " not found"); - } - return offset; - } - public native Boolean getMethodBooleanOption(Executable method, String name); - public native Long getMethodIntxOption(Executable method, String name); - public native Long getMethodUintxOption(Executable method, String name); - public native Double getMethodDoubleOption(Executable method, String name); - public native String getMethodStringOption(Executable method, String name); - private final List> methodOptionGetters - = Arrays.asList(this::getMethodBooleanOption, this::getMethodIntxOption, - this::getMethodUintxOption, this::getMethodDoubleOption, - this::getMethodStringOption); - - public Object getMethodOption(Executable method, String name) { - return methodOptionGetters.stream() - .map(f -> f.apply(method, name)) - .filter(x -> x != null) - .findAny() - .orElse(null); - } - - // Safepoint Checking - public native void assertMatchingSafepointCalls(boolean mutexSafepointValue, boolean attemptedNoSafepointValue); - - // Sharing & archiving - public native boolean isShared(Object o); - public native boolean isSharedClass(Class c); - public native boolean areSharedStringsIgnored(); - public native boolean isCDSIncludedInVmBuild(); - public native boolean isJFRIncludedInVmBuild(); - public native boolean isJavaHeapArchiveSupported(); - public native Object getResolvedReferences(Class c); - public native boolean areOpenArchiveHeapObjectsMapped(); - - // Handshakes - public native int handshakeWalkStack(Thread t, boolean all_threads); - - // Returns true on linux if library has the noexecstack flag set. - public native boolean checkLibSpecifiesNoexecstack(String libfilename); - - // Container testing - public native boolean isContainerized(); - public native void printOsInfo(); - - // Decoder - public native void disableElfSectionCache(); -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/BlobType.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/BlobType.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/BlobType.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/BlobType.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.code; - -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryPoolMXBean; -import java.util.EnumSet; - -import sun.hotspot.WhiteBox; - -public enum BlobType { - // All types (No code cache segmentation) - All(0, "CodeCache", "Code Cache", "ReservedCodeCacheSize"); - - public final int id; - public final String sizeOptionName; - public final String beanName; - public final String name; - - private BlobType(int id, String name, String beanName, String sizeOptionName) { - this.id = id; - this.name = name; - this.beanName = beanName; - this.sizeOptionName = sizeOptionName; - } - - public MemoryPoolMXBean getMemoryPool() { - for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) { - String name = bean.getName(); - if (beanName.equals(name)) { - return bean; - } - } - return null; - } - - public boolean allowTypeWhenOverflow(BlobType type) { - return type == this; - } - - public static EnumSet getAvailable() { - return EnumSet.of(All); - } - - public long getSize() { - return WhiteBox.getWhiteBox().getUintxVMFlag(sizeOptionName); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/CodeBlob.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/CodeBlob.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/CodeBlob.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/CodeBlob.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.code; - -import sun.hotspot.WhiteBox; - -public class CodeBlob { - private static final WhiteBox WB = WhiteBox.getWhiteBox(); - public static CodeBlob[] getCodeBlobs(BlobType type) { - Object[] obj = WB.getCodeHeapEntries(type.id); - if (obj == null) { - return null; - } - CodeBlob[] result = new CodeBlob[obj.length]; - for (int i = 0, n = result.length; i < n; ++i) { - result[i] = new CodeBlob((Object[]) obj[i]); - } - return result; - } - public static CodeBlob getCodeBlob(long addr) { - Object[] obj = WB.getCodeBlob(addr); - if (obj == null) { - return null; - } - return new CodeBlob(obj); - } - protected CodeBlob(Object[] obj) { - assert obj.length == 4; - name = (String) obj[0]; - size = (Integer) obj[1]; - int blob_type_index = (Integer) obj[2]; - if (blob_type_index == -1) { // AOT - code_blob_type = null; - } else { - code_blob_type = BlobType.values()[blob_type_index]; - assert code_blob_type.id == (Integer) obj[2]; - } - address = (Long) obj[3]; - } - public final String name; - public final int size; - public final BlobType code_blob_type; - public final long address; - @Override - public String toString() { - return "CodeBlob{" - + "name=" + name - + ", size=" + size - + ", code_blob_type=" + code_blob_type - + ", address=" + address - + '}'; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/Compiler.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/Compiler.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/Compiler.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/Compiler.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.code; - -import sun.hotspot.WhiteBox; - -/** - * API to obtain information about enabled JIT compilers - * retrieved from the VM with the WhiteBox API. - */ -public class Compiler { - - private static final WhiteBox WB = WhiteBox.getWhiteBox(); - - /** - * Check if Graal is used as JIT compiler. - * - * Graal is enabled if following conditions are true: - * - we are not in Interpreter mode - * - UseJVMCICompiler flag is true - * - jvmci.Compiler variable is equal to 'graal' - * - TieredCompilation is not used or TieredStopAtLevel is greater than 3 - * No need to check client mode because it set UseJVMCICompiler to false. - * - * @return true if Graal is used as JIT compiler. - */ - public static boolean isGraalEnabled() { - Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); - if (useCompiler == null || !useCompiler) { - return false; - } - Boolean useJvmciComp = WB.getBooleanVMFlag("UseJVMCICompiler"); - if (useJvmciComp == null || !useJvmciComp) { - return false; - } - // This check might be redundant but let's keep it for now. - String jvmciCompiler = System.getProperty("jvmci.Compiler"); - if (jvmciCompiler == null || !jvmciCompiler.equals("graal")) { - return false; - } - - Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); - Long compLevel = WB.getIntxVMFlag("TieredStopAtLevel"); - // if TieredCompilation is enabled and compilation level is <= 3 then no Graal is used - if (tieredCompilation != null && tieredCompilation && - compLevel != null && compLevel <= 3) { - return false; - } - return true; - } - - /** - * Check if C2 is used as JIT compiler. - * - * C2 is enabled if following conditions are true: - * - we are not in Interpreter mode - * - we are in Server compilation mode - * - TieredCompilation is not used or TieredStopAtLevel is greater than 3 - * - Graal is not used - * - * @return true if C2 is used as JIT compiler. - */ - public static boolean isC2Enabled() { - Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); - if (useCompiler == null || !useCompiler) { - return false; - } - Boolean serverMode = WB.getBooleanVMFlag("ProfileInterpreter"); - if (serverMode == null || !serverMode) { - return false; - } - - Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); - Long compLevel = WB.getIntxVMFlag("TieredStopAtLevel"); - // if TieredCompilation is enabled and compilation level is <= 3 then no Graal is used - if (tieredCompilation != null && tieredCompilation && - compLevel != null && compLevel <= 3) { - return false; - } - - if (isGraalEnabled()) { - return false; - } - - return true; - } - - /* - * Check if C1 is used as JIT compiler. - * - * C1 is enabled if following conditions are true: - * - we are not in Interpreter mode - * - we are not in Server compilation mode - * - TieredCompilation is used in Server mode - * - * @return true if C1 is used as JIT compiler. - */ - public static boolean isC1Enabled() { - Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); - if (useCompiler == null || !useCompiler) { - return false; - } - Boolean serverMode = WB.getBooleanVMFlag("ProfileInterpreter"); - if (serverMode == null || !serverMode) { - return true; // Client mode - } - - Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); - // C1 is not used in server mode if TieredCompilation is off. - if (tieredCompilation != null && !tieredCompilation) { - return false; - } - return true; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/NMethod.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/NMethod.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/NMethod.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/code/NMethod.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.code; - -import java.lang.reflect.Executable; -import sun.hotspot.WhiteBox; - -public class NMethod extends CodeBlob { - private static final WhiteBox wb = WhiteBox.getWhiteBox(); - public static NMethod get(Executable method, boolean isOsr) { - Object[] obj = wb.getNMethod(method, isOsr); - return obj == null ? null : new NMethod(obj); - } - private NMethod(Object[] obj) { - super((Object[])obj[0]); - assert obj.length == 5; - comp_level = (Integer) obj[1]; - insts = (byte[]) obj[2]; - compile_id = (Integer) obj[3]; - entry_point = (Long) obj[4]; - } - public final byte[] insts; - public final int comp_level; - public final int compile_id; - public final long entry_point; - - @Override - public String toString() { - return "NMethod{" - + super.toString() - + ", insts=" + insts - + ", comp_level=" + comp_level - + ", compile_id=" + compile_id - + ", entry_point=" + entry_point - + '}'; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.cpuinfo; - -import java.util.List; -import java.util.Arrays; -import java.util.Collections; -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import sun.hotspot.WhiteBox; - -/** - * Information about CPU on test box. - * - * CPUInfo uses WhiteBox to gather information, - * so WhiteBox class should be added to bootclasspath - * and option -XX:+WhiteBoxAPI should be explicitly - * specified on command line. - */ -public class CPUInfo { - - private static final List features; - private static final String additionalCPUInfo; - - static { - WhiteBox wb = WhiteBox.getWhiteBox(); - - Pattern additionalCPUInfoRE = - Pattern.compile("([^(]*\\([^)]*\\)[^,]*),\\s*"); - - String cpuFeaturesString = wb.getCPUFeatures(); - Matcher matcher = additionalCPUInfoRE.matcher(cpuFeaturesString); - if (matcher.find()) { - additionalCPUInfo = matcher.group(1); - } else { - additionalCPUInfo = ""; - } - String splittedFeatures[] = matcher.replaceAll("").split("(, )| "); - - features = Collections.unmodifiableList(Arrays. - asList(splittedFeatures)); - } - - /** - * Get additional information about CPU. - * For example, on X86 in will be family/model/stepping - * and number of cores. - * - * @return additional CPU info - */ - public static String getAdditionalCPUInfo() { - return additionalCPUInfo; - } - - /** - * Get all known features supported by CPU. - * - * @return unmodifiable list with names of all known features - * supported by CPU. - */ - public static List getFeatures() { - return features; - } - - /** - * Check if some feature is supported by CPU. - * - * @param feature Name of feature to be tested. - * @return true if tested feature is supported by CPU. - */ - public static boolean hasFeature(String feature) { - return features.contains(feature.toLowerCase()); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/gc/GC.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/gc/GC.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/gc/GC.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/gc/GC.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.gc; - -import sun.hotspot.WhiteBox; - -/** - * API to obtain information about selected and supported Garbage Collectors - * retrieved from the VM with the WhiteBox API. - */ -public enum GC { - /* - * Enum values much match CollectedHeap::Name - */ - Serial(1), - Parallel(2), - ConcMarkSweep(3), - G1(4), - Epsilon(5), - Z(6); - - private static final WhiteBox WB = WhiteBox.getWhiteBox(); - - private final int name; - - private GC(int name) { - this.name = name; - } - - /** - * @return true if this GC is supported by the VM - */ - public boolean isSupported() { - return WB.isGCSupported(name); - } - - /** - * @return true if this GC is currently selected/used - */ - public boolean isSelected() { - return WB.isGCSelected(name); - } - - /** - * @return true if GC was selected ergonomically, as opposed - * to being explicitly specified on the command line - */ - public static boolean isSelectedErgonomically() { - return WB.isGCSelectedErgonomically(); - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/parser/DiagnosticCommand.java openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/parser/DiagnosticCommand.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/lib/sun/hotspot/parser/DiagnosticCommand.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/lib/sun/hotspot/parser/DiagnosticCommand.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.hotspot.parser; - -public class DiagnosticCommand { - - public enum DiagnosticArgumentType { - JLONG, BOOLEAN, STRING, NANOTIME, STRINGARRAY, MEMORYSIZE - } - - private String name; - private String desc; - private DiagnosticArgumentType type; - private boolean mandatory; - private String defaultValue; - private boolean argument; - - public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type, - boolean mandatory, String defaultValue) { - this(name, desc, type, false, mandatory, defaultValue); - } - - public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type, - boolean argument, boolean mandatory, String defaultValue) { - this.name = name; - this.desc = desc; - this.type = type; - this.mandatory = mandatory; - this.defaultValue = defaultValue; - this.argument = argument; - } - - public String getName() { - return name; - } - - public String getDesc() { - return desc; - } - - public DiagnosticArgumentType getType() { - return type; - } - - public boolean isMandatory() { - return mandatory; - } - - public boolean isArgument() { - return argument; - } - - public String getDefaultValue() { - return defaultValue; - } -} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/AmazonCA.java openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/AmazonCA.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/AmazonCA.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/AmazonCA.java 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,291 +51,325 @@ public static void main(String[] args) throws Exception { ValidatePathWithParams pathValidator = new ValidatePathWithParams(null); - boolean ocspEnabled = false; if (args.length >= 1 && "CRL".equalsIgnoreCase(args[0])) { pathValidator.enableCRLCheck(); } else { // OCSP check by default pathValidator.enableOCSPCheck(); - ocspEnabled = true; } - new AmazonCA_1().runTest(pathValidator, ocspEnabled); - new AmazonCA_2().runTest(pathValidator, ocspEnabled); - new AmazonCA_3().runTest(pathValidator, ocspEnabled); - new AmazonCA_4().runTest(pathValidator, ocspEnabled); + new AmazonCA_1().runTest(pathValidator); + new AmazonCA_2().runTest(pathValidator); + new AmazonCA_3().runTest(pathValidator); + new AmazonCA_4().runTest(pathValidator); } } class AmazonCA_1 { - // Owner: CN=Amazon, OU=Server CA 1A, O=Amazon, C=US + // Owner: CN=Amazon RSA 2048 M02, O=Amazon, C=US // Issuer: CN=Amazon Root CA 1, O=Amazon, C=US - // Serial number: 67f9457508c648c09ca652e71791830e72592 - // Valid from: Wed Oct 21 17:00:00 PDT 2015 until: Sat Oct 18 17:00:00 PDT 2025 - private static final String INT = "-----BEGIN CERTIFICATE-----\n" + - "MIIERzCCAy+gAwIBAgITBn+UV1CMZIwJymUucXkYMOclkjANBgkqhkiG9w0BAQsF\n" + + // Serial number: 773124a4bcbd44ec7b53beaf194842d3a0fa1 + // Valid from: Tue Aug 23 15:25:30 PDT 2022 until: Fri Aug 23 15:25:30 PDT 2030 + private static final String INT_VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIEXjCCA0agAwIBAgITB3MSSkvL1E7HtTvq8ZSELToPoTANBgkqhkiG9w0BAQsF\n" + + "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" + + "b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjUzMFoXDTMwMDgyMzIyMjUzMFowPDEL\n" + + "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT\n" + + "QSAyMDQ4IE0wMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALtDGMZa\n" + + "qHneKei1by6+pUPPLljTB143Si6VpEWPc6mSkFhZb/6qrkZyoHlQLbDYnI2D7hD0\n" + + "sdzEqfnuAjIsuXQLG3A8TvX6V3oFNBFVe8NlLJHvBseKY88saLwufxkZVwk74g4n\n" + + "WlNMXzla9Y5F3wwRHwMVH443xGz6UtGSZSqQ94eFx5X7Tlqt8whi8qCaKdZ5rNak\n" + + "+r9nUThOeClqFd4oXych//Rc7Y0eX1KNWHYSI1Nk31mYgiK3JvH063g+K9tHA63Z\n" + + "eTgKgndlh+WI+zv7i44HepRZjA1FYwYZ9Vv/9UkC5Yz8/yU65fgjaE+wVHM4e/Yy\n" + + "C2osrPWE7gJ+dXMCAwEAAaOCAVowggFWMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYD\n" + + "VR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNV\n" + + "HQ4EFgQUwDFSzVpQw4J8dHHOy+mc+XrrguIwHwYDVR0jBBgwFoAUhBjMhTTsvAyU\n" + + "lC4IWZzHshBOCggwewYIKwYBBQUHAQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8v\n" + + "b2NzcC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDov\n" + + "L2NydC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8E\n" + + "ODA2MDSgMqAwhi5odHRwOi8vY3JsLnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jv\n" + + "b3RjYTEuY3JsMBMGA1UdIAQMMAowCAYGZ4EMAQIBMA0GCSqGSIb3DQEBCwUAA4IB\n" + + "AQAtTi6Fs0Azfi+iwm7jrz+CSxHH+uHl7Law3MQSXVtR8RV53PtR6r/6gNpqlzdo\n" + + "Zq4FKbADi1v9Bun8RY8D51uedRfjsbeodizeBB8nXmeyD33Ep7VATj4ozcd31YFV\n" + + "fgRhvTSxNrrTlNpWkUk0m3BMPv8sg381HhA6uEYokE5q9uws/3YkKqRiEz3TsaWm\n" + + "JqIRZhMbgAfp7O7FUwFIb7UIspogZSKxPIWJpxiPo3TcBambbVtQOcNRWz5qCQdD\n" + + "slI2yayq0n2TXoHyNCLEH8rpsJRVILFsg0jc7BaFrMnF462+ajSehgj12IidNeRN\n" + + "4zl+EoNaWdpnWndvSpAEkq2P\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=Amazon RSA 2048 M01, O=Amazon, C=US + // Issuer: CN=Amazon Root CA 1, O=Amazon, C=US + // Serial number: 77312380b9d6688a33b1ed9bf9ccda68e0e0f + // Valid from: Tue Aug 23 15:21:28 PDT 2022 until: Fri Aug 23 15:21:28 PDT 2030 + private static final String INT_REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIEXjCCA0agAwIBAgITB3MSOAudZoijOx7Zv5zNpo4ODzANBgkqhkiG9w0BAQsF\n" + "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" + - "b24gUm9vdCBDQSAxMB4XDTE1MTAyMjAwMDAwMFoXDTI1MTAxOTAwMDAwMFowRjEL\n" + - "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENB\n" + - "IDFBMQ8wDQYDVQQDEwZBbWF6b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n" + - "AoIBAQCeQM3XCsIZunv8bSJxOqkc/ed87uL76FDB7teBNThDRB+1J7aITuadbNfH\n" + - "5ZfZykrdZ1qQLKxP6DwHOmJr9u2b4IxjUX9qUMuq4B02ghD2g6yU3YivEosZ7fpo\n" + - "srD2TBN29JpgPGrOrpOE+ArZuIpBjdKFinemu6fTDD0NCeQlfyHXd1NOYyfYRLTa\n" + - "xlpDqr/2M41BgSkWQfSPHHyRWNQgWBiGsIQaS8TK0g8OWi1ov78+2K9DWT+AHgXW\n" + - "AanjZK91GfygPXJYSlAGxSiBAwH/KhAMifhaoFYAbH0Yuohmd85B45G2xVsop4TM\n" + - "Dsl007U7qnS7sdJ4jYGzEvva/a95AgMBAAGjggE5MIIBNTASBgNVHRMBAf8ECDAG\n" + - "AQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUYtRCXoZwdWqQvMa40k1g\n" + - "wjS6UTowHwYDVR0jBBgwFoAUhBjMhTTsvAyUlC4IWZzHshBOCggwewYIKwYBBQUH\n" + - "AQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5yb290Y2ExLmFtYXpvbnRy\n" + - "dXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDovL2NydC5yb290Y2ExLmFtYXpvbnRy\n" + - "dXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3Js\n" + - "LnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jvb3RjYTEuY3JsMBEGA1UdIAQKMAgw\n" + - "BgYEVR0gADANBgkqhkiG9w0BAQsFAAOCAQEAMHbSWHRFMzGNIE0qhN6gnRahTrTU\n" + - "CDPwe7l9/q0IA+QBlrpUHnlAreetYeH1jB8uF3qXXzy22gpBU7NqulTkqSPByT1J\n" + - "xOhpT2FpO5R3VAdMPdWfSEgtrED0jkmyUQrR1T+/A+nBLdJZeQcl+OqLgeY790JM\n" + - "JJTsJnnI6FBWeTGhcDI4Y+n3KS3QCVePeWI7jx1dhrHcXH+QDX8Ywe31hV7YENdr\n" + - "HDpUXrjK6eHN8gazy8G6pndXHFwHp4auiZbJbYAk/q1peOTRagD2JojcLkm+i3cD\n" + - "843t4By6YT/PVlePU2PCWejkrJQnKQAPOov7IA8kuO2RDWuzE/zF6Hotdg==\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=good.sca1a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 1A, O=Amazon, C=US - // Serial number: 703e4e4bbd78e2b6db5634f36c4ee944cb1a4 - // Valid from: Mon Jul 29 16:53:36 PDT 2019 until: Sat Aug 29 16:53:36 PDT 2020 + "b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjEyOFoXDTMwMDgyMzIyMjEyOFowPDEL\n" + + "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT\n" + + "QSAyMDQ4IE0wMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOtxLKnL\n" + + "H4gokjIwr4pXD3i3NyWVVYesZ1yX0yLI2qIUZ2t88Gfa4gMqs1YSXca1R/lnCKeT\n" + + "epWSGA+0+fkQNpp/L4C2T7oTTsddUx7g3ZYzByDTlrwS5HRQQqEFE3O1T5tEJP4t\n" + + "f+28IoXsNiEzl3UGzicYgtzj2cWCB41eJgEmJmcf2T8TzzK6a614ZPyq/w4CPAff\n" + + "nAV4coz96nW3AyiE2uhuB4zQUIXvgVSycW7sbWLvj5TDXunEpNCRwC4kkZjK7rol\n" + + "jtT2cbb7W2s4Bkg3R42G3PLqBvt2N32e/0JOTViCk8/iccJ4sXqrS1uUN4iB5Nmv\n" + + "JK74csVl+0u0UecCAwEAAaOCAVowggFWMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYD\n" + + "VR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNV\n" + + "HQ4EFgQUgbgOY4qJEhjl+js7UJWf5uWQE4UwHwYDVR0jBBgwFoAUhBjMhTTsvAyU\n" + + "lC4IWZzHshBOCggwewYIKwYBBQUHAQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8v\n" + + "b2NzcC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDov\n" + + "L2NydC5yb290Y2ExLmFtYXpvbnRydXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8E\n" + + "ODA2MDSgMqAwhi5odHRwOi8vY3JsLnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jv\n" + + "b3RjYTEuY3JsMBMGA1UdIAQMMAowCAYGZ4EMAQIBMA0GCSqGSIb3DQEBCwUAA4IB\n" + + "AQCtAN4CBSMuBjJitGuxlBbkEUDeK/pZwTXv4KqPK0G50fOHOQAd8j21p0cMBgbG\n" + + "kfMHVwLU7b0XwZCav0h1ogdPMN1KakK1DT0VwA/+hFvGPJnMV1Kx2G4S1ZaSk0uU\n" + + "5QfoiYIIano01J5k4T2HapKQmmOhS/iPtuo00wW+IMLeBuKMn3OLn005hcrOGTad\n" + + "hcmeyfhQP7Z+iKHvyoQGi1C0ClymHETx/chhQGDyYSWqB/THwnN15AwLQo0E5V9E\n" + + "SJlbe4mBlqeInUsNYugExNf+tOiybcrswBy8OFsd34XOW3rjSUtsuafd9AWySa3h\n" + + "xRRrwszrzX/WWGm6wyB+f7C4\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=valid.rootca1.demo.amazontrust.com + // Issuer: CN=Amazon RSA 2048 M02, O=Amazon, C=US + // Serial number: 60c6e837b2e7586d8464eb34f4a85fe + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + - "MIIFEzCCA/ugAwIBAgITBwPk5LvXjitttWNPNsTulEyxpDANBgkqhkiG9w0BAQsF\n" + - "ADBGMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2\n" + - "ZXIgQ0EgMUExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTA3MjkyMzUzMzZaFw0yMDA4\n" + - "MjkyMzUzMzZaMIHaMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwC\n" + - "AQITCERlbGF3YXJlMR0wGwYDVQQPExRQcml2YXRlIE9yZ2FuaXphdGlvbjEQMA4G\n" + - "A1UEBRMHNTg0Njc0MzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24x\n" + - "EDAOBgNVBAcTB1NlYXR0bGUxHjAcBgNVBAoTFUFtYXpvbiBUcnVzdCBTZXJ2aWNl\n" + - "czEjMCEGA1UEAxMaZ29vZC5zY2ExYS5hbWF6b250cnVzdC5jb20wggEiMA0GCSqG\n" + - "SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDQyuJ83c2Zf9k29f6iLqd8nJSuHSk1v+SS\n" + - "0sYyG8tjscfCC1HcOdNj37vtiNN65sXh/e/kBKH9wvzhCLOJbBqVKRHOZuHdJEpH\n" + - "35R6C/PbcV/tp49g6mNmBe+lcmm/cwwCtYvkL0rgL/OKB0liFhhRIqy2TPg08op/\n" + - "RlY2DdbgBA2B3g7wdMo0hK3SO56/QUccUtLRm43km9Yd4E3U+CEUyDd0Bmc/YbPa\n" + - "htuXVsXJwiwlwooomujIIENhFw3htdcsu2apRj8EYUrKL8Mvvn+h16gDyobj0f01\n" + - "jWXlUgmH2lzUzca5eGuphfvmWN/ME/yqC2mMvWGnWySycqtT8VdJAgMBAAGjggFj\n" + - "MIIBXzAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0OBBYEFFENOZBwFkjVdQX0iK32c77z\n" + - "SUl6MB8GA1UdIwQYMBaAFGLUQl6GcHVqkLzGuNJNYMI0ulE6MB0GA1UdJQQWMBQG\n" + - "CCsGAQUFBwMBBggrBgEFBQcDAjB1BggrBgEFBQcBAQRpMGcwLQYIKwYBBQUHMAGG\n" + - "IWh0dHA6Ly9vY3NwLnNjYTFhLmFtYXpvbnRydXN0LmNvbTA2BggrBgEFBQcwAoYq\n" + - "aHR0cDovL2NydC5zY2ExYS5hbWF6b250cnVzdC5jb20vc2NhMWEuY2VyMCUGA1Ud\n" + - "EQQeMByCGmdvb2Quc2NhMWEuYW1hem9udHJ1c3QuY29tMFAGA1UdIARJMEcwDQYL\n" + - "YIZIAYb9bgEHGAMwNgYFZ4EMAQEwLTArBggrBgEFBQcCARYfaHR0cHM6Ly93d3cu\n" + - "YW1hem9udHJ1c3QuY29tL2NwczANBgkqhkiG9w0BAQsFAAOCAQEAmn7z6Ub1sL77\n" + - "wyUEaCq/Odqm+2RtYYMJ1MeW6nTXTfAgZ/iLx/6hStafd9AK9gHiTCggBpj6KgnF\n" + - "UsGMDeX879jP675fH6SEk710QPDhIrfAzwE0pF/eUNsd7pLwne32zHX0ouCoAt4d\n" + - "KwBCZkKNUkdj4U+bpOJzvtcTP9JlzziLp9IFRjjQh3xKgfblx57CmRJbqH3fT5JJ\n" + - "IAIDVTz3ZUcqhPTFAnNsO1oNBEyrO5X9rwCiSy7aRijY/11R75mIIvyA9zyd9ss1\n" + - "kvrrER0GWMTDvC84FZD2vhkXgPTFrB1Dn9f3QgO5APT9GCFY5hdpqqPEXOSdRzQo\n" + - "h9j4OQAqtA==\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=revoked.sca1a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=PrivateOrganization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 1A, O=Amazon, C=US - // Serial number: 6f1d774ad5e7b6d251d217661782bbdb6f37d - // Valid from: Mon Jan 28 15:34:38 PST 2019 until: Thu Apr 28 16:34:38 PDT 2022 + "MIIGKDCCBRCgAwIBAgIQBgxug3sudYbYRk6zT0qF/jANBgkqhkiG9w0BAQsFADA8\n" + + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRwwGgYDVQQDExNBbWF6b24g\n" + + "UlNBIDIwNDggTTAyMB4XDTIzMDUxMDAwMDAwMFoXDTI0MDYwNzIzNTk1OVowLTEr\n" + + "MCkGA1UEAxMidmFsaWQucm9vdGNhMS5kZW1vLmFtYXpvbnRydXN0LmNvbTCCASIw\n" + + "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3hA+omhUcO8nYO8/+dkpbYz8WI\n" + + "1ms7Y7JA2pPFfp2N/aWcf6m5ORm1BkyGLOttjTu318Qpa9eahQ1Pi3RNe3BtqjD9\n" + + "jcHncpwAFMsXy1beZA7sZ7AA4vKltA3t6yrU5ruTLUGQwUndeIBBSTW5QpdT9I/p\n" + + "EM7d+Miwre63kofbJ1lVPAJvN/udMVqGWNF8V5qscklUUHoSKA3FWWsiCyIgnthg\n" + + "G3u6R1KH66Qionp0ho/ttvrBCI0C/bdrdH+wybFv8oFFvAW2U9xn2Azt47/2kHHm\n" + + "tTRjrgufhDbcz/MLR6hwBXAJuwVvJZmSqe7B4IILFexu6wjxZfyqVm2FMr8CAwEA\n" + + "AaOCAzMwggMvMB8GA1UdIwQYMBaAFMAxUs1aUMOCfHRxzsvpnPl664LiMB0GA1Ud\n" + + "DgQWBBSkrnsTnjwYhDRAeLy/9FXm/7hApDBlBgNVHREEXjBcgiJ2YWxpZC5yb290\n" + + "Y2ExLmRlbW8uYW1hem9udHJ1c3QuY29tghpnb29kLnNjYTBhLmFtYXpvbnRydXN0\n" + + "LmNvbYIaZ29vZC5zY2ExYS5hbWF6b250cnVzdC5jb20wDgYDVR0PAQH/BAQDAgWg\n" + + "MB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjA7BgNVHR8ENDAyMDCgLqAs\n" + + "hipodHRwOi8vY3JsLnIybTAyLmFtYXpvbnRydXN0LmNvbS9yMm0wMi5jcmwwEwYD\n" + + "VR0gBAwwCjAIBgZngQwBAgEwdQYIKwYBBQUHAQEEaTBnMC0GCCsGAQUFBzABhiFo\n" + + "dHRwOi8vb2NzcC5yMm0wMi5hbWF6b250cnVzdC5jb20wNgYIKwYBBQUHMAKGKmh0\n" + + "dHA6Ly9jcnQucjJtMDIuYW1hem9udHJ1c3QuY29tL3IybTAyLmNlcjAMBgNVHRMB\n" + + "Af8EAjAAMIIBfgYKKwYBBAHWeQIEAgSCAW4EggFqAWgAdgDuzdBk1dsazsVct520\n" + + "zROiModGfLzs3sNRSFlGcR+1mwAAAYgHvXWVAAAEAwBHMEUCICAs74qT1f9ufSr5\n" + + "PgQqtQFiXBbmbb3i4xwVV78USU5NAiEA/iJEfnTG+hZZaHYv2wVbg6tUY8fQgIhI\n" + + "2rbl6PrD9FIAdgBIsONr2qZHNA/lagL6nTDrHFIBy1bdLIHZu7+rOdiEcwAAAYgH\n" + + "vXWWAAAEAwBHMEUCIQDf2nWyee/5+vSgk/O8P0BFvXYu89cyAugZHyd919BdAgIg\n" + + "UnGGpQtZmWnPMmdgpzI7jrCLuC370Tn0i7Aktdzj2X8AdgDatr9rP7W2Ip+bwrtc\n" + + "a+hwkXFsu1GEhTS9pD0wSNf7qwAAAYgHvXVpAAAEAwBHMEUCIGN6cT+6uwDospXe\n" + + "gMa8b38oXouXUT66X2gOiJ0SoRyQAiEAjDMu2vEll5tRpUvU8cD4gR2xV4hqoDxx\n" + + "Q+QGW+PvJxcwDQYJKoZIhvcNAQELBQADggEBACtxC3LlQvULeI3lt7ZYFSWndEhm\n" + + "tNUotoeKSXJXdoIpqSr10bzMPX9SHvemgOUtzP3JNqWPHw1uW9YFyeDE6yWj/B13\n" + + "Xj1hv1cqYIwyaOZBerU/9PT5PaCn20AC9DHbc7iBv+zs+DYiqlAFJ1GVaprwLul4\n" + + "8wp3gnC3Hjb8NykydCo6vw0AJ2UzjpjiTyVZ93jITzLOiboOUa1gQGnojzWlYaet\n" + + "sXe+RDylBp/Wuj1ZS7v/etltzYm5GanPi4y/p7Ta3Uky6std/GM6XbPRdBEFboFR\n" + + "B2IP0divd9c74Q+tLgpsAz5yXm9LtYPMcEPC2YRN2PgBg67c5+A7eIOluuw=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=revoked.rootca1.demo.amazontrust.com + // Issuer: CN=Amazon RSA 2048 M01, O=Amazon, C=US + // Serial number: e1023665b1268d788cc25bf69a9d05e + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + - "MIIE2zCCA8OgAwIBAgITBvHXdK1ee20lHSF2YXgrvbbzfTANBgkqhkiG9w0BAQsF\n" + - "ADBGMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2\n" + - "ZXIgQ0EgMUExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTAxMjgyMzM0MzhaFw0yMjA0\n" + - "MjgyMzM0MzhaMIHcMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwC\n" + - "AQITCERlbGF3YXJlMRwwGgYDVQQPExNQcml2YXRlT3JnYW5pemF0aW9uMRAwDgYD\n" + - "VQQFEwc1ODQ2NzQzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ\n" + - "MA4GA1UEBxMHU2VhdHRsZTEeMBwGA1UEChMVQW1hem9uIFRydXN0IFNlcnZpY2Vz\n" + - "MSYwJAYDVQQDEx1yZXZva2VkLnNjYTFhLmFtYXpvbnRydXN0LmNvbTCCASIwDQYJ\n" + - "KoZIhvcNAQEBBQADggEPADCCAQoCggEBANUoHop9sW+QlgVsdtacioraTAWHcSTd\n" + - "MNkOkOEMgJIFPyfdcDvW/H2NvpdYeIQqzaCgT2kcsONWTZTPJMirCPnzl1ohHOZU\n" + - "uTnOVkamGxvNmQCURLBXmlCMRTCI5RY3CuYntFFbSPAnbumsF+K/gKqcE6ME53Bw\n" + - "PAwn4qwavB0i5Ib7Jk8XYzxSYXC9l8QLxt6fshPJRlecpXzfmVFvMAm3IbaLcpuv\n" + - "AtD+8I2KwjNtBPRPNYeFsWxwsgUGAyHEGa61oTGUqqAXu5YmPfyK+YTOJdoofsh4\n" + - "Tf3K7AKxnPWuvY3RNTs1pzEVwJYZqSsNwbgyKJJ4+0Xe4iP7qB8SYf8CAwEAAaOC\n" + - "ASkwggElMA4GA1UdDwEB/wQEAwIFoDAdBgNVHQ4EFgQUGHreoz+LP/Wr+RKzuexO\n" + - "V8ICtmEwHwYDVR0jBBgwFoAUYtRCXoZwdWqQvMa40k1gwjS6UTowHQYDVR0lBBYw\n" + - "FAYIKwYBBQUHAwEGCCsGAQUFBwMCMHUGCCsGAQUFBwEBBGkwZzAtBggrBgEFBQcw\n" + - "AYYhaHR0cDovL29jc3Auc2NhMWEuYW1hem9udHJ1c3QuY29tMDYGCCsGAQUFBzAC\n" + - "hipodHRwOi8vY3J0LnNjYTFhLmFtYXpvbnRydXN0LmNvbS9zY2ExYS5jZXIwKAYD\n" + - "VR0RBCEwH4IdcmV2b2tlZC5zY2ExYS5hbWF6b250cnVzdC5jb20wEwYDVR0gBAww\n" + - "CjAIBgZngQwBAgEwDQYJKoZIhvcNAQELBQADggEBABSbe1UCLL7Qay6XK5wD8B5a\n" + - "wvR1XG3UrggpVIz/w5cutEm/yE71hzE0gag/3YPbNYEnaLbJH+9jz4YW9wd/cEPj\n" + - "xSK5PErAQjCd+aA4LKN1xqkSysgYknl0y47hJBXGnWf+hxvBBHeSoUzM0KIC21pC\n" + - "ZyXrmfaPCQAz13ruYIYdQaETqXGVORmKbf/a+Zn18/tfQt0LeeCYVoSopbXWQvcJ\n" + - "gUMtdIqYQmb8aVj0pdZXwKl4yZ2DtlS3Z9MpWNgQNlhRPmiYlu28y2yTtZ9SwD6m\n" + - "2f+cwc19aJrDT4Y280px+jRU7dIE6oZVJU+yBRVIZYpUFAB7extCMVxnTkCf8Dk=\n" + - "-----END CERTIFICATE-----"; - - public void runTest(ValidatePathWithParams pathValidator, boolean ocspEnabled) throws Exception { - // EE certificates don't have CRLDP extension - if (!ocspEnabled){ - pathValidator.validate(new String[]{INT}, - ValidatePathWithParams.Status.GOOD, null, System.out); + "MIIGMjCCBRqgAwIBAgIQDhAjZlsSaNeIzCW/aanQXjANBgkqhkiG9w0BAQsFADA8\n" + + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRwwGgYDVQQDExNBbWF6b24g\n" + + "UlNBIDIwNDggTTAxMB4XDTIzMDUxMDAwMDAwMFoXDTI0MDYwNzIzNTk1OVowLzEt\n" + + "MCsGA1UEAxMkcmV2b2tlZC5yb290Y2ExLmRlbW8uYW1hem9udHJ1c3QuY29tMIIB\n" + + "IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxSPd1PWACxZohFCAJT1JWuXK\n" + + "GY29wZZ9yY0zoiq6+qYiUIU0crktytUNNI1ZpW/3qXpEw2ZQkM6WF1LshXtwGwrA\n" + + "zJwSeX1L9T5rOKhoBvoFeqfX7xu4VBM1/fDGt5X+NRFfD9Op9UfK5OsnL05TYach\n" + + "rdnfOA5wKGvMgFiN5CeOD0AtumXSuAnTZC85ojJTHjPF+hqV893WvrrUxLyyxtvh\n" + + "lq/WttFOjhfQu2IkfyDAFiH939uzUi0WSTAdsbsHuko5mDTDnOfMRbaaWZu0At01\n" + + "EgaIPeK+kGdi7EYwVndIwTKLeQ4mjIM8aj8Heg/y2hZ0kOmfCUZdUmJFlNoCIQID\n" + + "AQABo4IDOzCCAzcwHwYDVR0jBBgwFoAUgbgOY4qJEhjl+js7UJWf5uWQE4UwHQYD\n" + + "VR0OBBYEFMeBhIOkuWUY4DYqFrfgbD2eUeFtMG0GA1UdEQRmMGSCJHJldm9rZWQu\n" + + "cm9vdGNhMS5kZW1vLmFtYXpvbnRydXN0LmNvbYIdcmV2b2tlZC5zY2EwYS5hbWF6\n" + + "b250cnVzdC5jb22CHXJldm9rZWQuc2NhMWEuYW1hem9udHJ1c3QuY29tMA4GA1Ud\n" + + "DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwOwYDVR0f\n" + + "BDQwMjAwoC6gLIYqaHR0cDovL2NybC5yMm0wMS5hbWF6b250cnVzdC5jb20vcjJt\n" + + "MDEuY3JsMBMGA1UdIAQMMAowCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAtBggr\n" + + "BgEFBQcwAYYhaHR0cDovL29jc3AucjJtMDEuYW1hem9udHJ1c3QuY29tMDYGCCsG\n" + + "AQUFBzAChipodHRwOi8vY3J0LnIybTAxLmFtYXpvbnRydXN0LmNvbS9yMm0wMS5j\n" + + "ZXIwDAYDVR0TAQH/BAIwADCCAX4GCisGAQQB1nkCBAIEggFuBIIBagFoAHYA7s3Q\n" + + "ZNXbGs7FXLedtM0TojKHRny87N7DUUhZRnEftZsAAAGIB72TggAABAMARzBFAiAZ\n" + + "naLbRHRuaRrE304GSuWX/79MU/e+SSlr0cNJ0kNNaAIhAPnz9HayL4txhkTEZiMs\n" + + "nttNnNqD17I0J17JLVOF4i/4AHYASLDja9qmRzQP5WoC+p0w6xxSActW3SyB2bu/\n" + + "qznYhHMAAAGIB72TmwAABAMARzBFAiEAgEqT7CYGQ/u36/3YcxBH78QfknI9kgcY\n" + + "sgJLkurUF6cCIFZZ/b803+ek6o+bmdV/uVx2UlskAyyolZ2okBAb6IscAHYA2ra/\n" + + "az+1tiKfm8K7XGvocJFxbLtRhIU0vaQ9MEjX+6sAAAGIB72TbQAABAMARzBFAiEA\n" + + "6z2RSoK263hvYF71rj1d0TpC70/6zagSRR4glHOT6IACICYvaMAnrCNSTSiZ20Wz\n" + + "Ju5roTippO3BWKhQYrTKZuu4MA0GCSqGSIb3DQEBCwUAA4IBAQB4S1JGulFpMIaP\n" + + "NtLUJmjWz8eexQdWLDVF+H8dd6xpZgpiYtig/Ynphzuk1IIF8DkT3CeK/9vrezgI\n" + + "igNjneN9B4eIuzi/rJzIKeUwpZ2k5D+36Ab4esseoc+TopmNerw8hidt2g818jER\n" + + "D71ppSMakeQFPGe/Hs2/cVa/G1DNVcU2XAut45yRZ/+xsZ0/mcBDVsG9P5uGCN5O\n" + + "7SAp4J959WnKDqgVuU9WowPE5IjmS9BAv2gjniFYdDV2yksyf7+8edHd1KfSVX06\n" + + "pLx6CuCVZGJFG4Q2Aa1YAh1Wvt9hqWeXXpNRO2/wChL5rhT4GajsrGepsk4bjxYX\n" + + "Wf2iZ8mX\n" + + "-----END CERTIFICATE-----"; - return; - } + public void runTest(ValidatePathWithParams pathValidator) throws Exception { // Validate valid - pathValidator.validate(new String[]{VALID, INT}, + pathValidator.validate(new String[]{VALID, INT_VALID}, ValidatePathWithParams.Status.GOOD, null, System.out); // Validate Revoked - pathValidator.validate(new String[]{REVOKED, INT}, + pathValidator.validate(new String[]{REVOKED, INT_REVOKED}, ValidatePathWithParams.Status.REVOKED, - "Mon Jan 28 15:35:56 PST 2019", System.out); + "Mon May 15 13:36:57 PDT 2023", System.out); } } class AmazonCA_2 { - // Owner: CN=Amazon, OU=Server CA 2A, O=Amazon, C=US + // Owner: CN=Amazon RSA 4096 M02, O=Amazon, C=US // Issuer: CN=Amazon Root CA 2, O=Amazon, C=US - // Serial number: 67f945755f187a91f8163f3e624620177ff38 - // Valid from: Wed Oct 21 17:00:00 PDT 2015 until: Sat Oct 18 17:00:00 PDT 2025 + // Serial number: 773125b0c34c3c940299a9f04a39e5a52ccd9 + // Valid from: Tue Aug 23 15:29:13 PDT 2022 until: Fri Aug 23 15:29:13 PDT 2030 private static final String INT = "-----BEGIN CERTIFICATE-----\n" + - "MIIGRzCCBC+gAwIBAgITBn+UV1Xxh6kfgWPz5iRiAXf/ODANBgkqhkiG9w0BAQwF\n" + + "MIIGXjCCBEagAwIBAgITB3MSWww0w8lAKZqfBKOeWlLM2TANBgkqhkiG9w0BAQwF\n" + "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" + - "b24gUm9vdCBDQSAyMB4XDTE1MTAyMjAwMDAwMFoXDTI1MTAxOTAwMDAwMFowRjEL\n" + - "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENB\n" + - "IDJBMQ8wDQYDVQQDEwZBbWF6b24wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\n" + - "AoICAQC0P8hSLewmrZ41CCPBQytZs5NBFMq5ztbnMf+kZUp9S25LPfjNW3zgC/6E\n" + - "qCTWNVMMHhq7ez9IQJk48qbfBTLlZkuKnUWbA9vowrDfcxUN0mRE4B/TJbveXyTf\n" + - "vE91iDlqDrERecE9D8sdjzURrtHTp27lZdRkXFvfEVCq4hl3sHkzjodisaQthLp1\n" + - "gLsiA7vKt+8zcL4Aeq52UyYb8r4/jdZ3KaQp8O/T4VwDCRKm8ey3kttpJWaflci7\n" + - "eRzNjY7gE3NMANVXCeQwOBfH2GjINFCObmPsqiBuoAnsv2k5aQLNoU1OZk08ClXm\n" + - "mEZ2rI5qZUTX1HuefBJnpMkPugFCw8afaHnB13SkLE7wxX8SZRdDIe5WiwyDL1tR\n" + - "2+8lpz4JsMoFopHmD3GaHyjbN+hkOqHgLltwewOsiyM0u3CZphypN2KeD+1FLjnY\n" + - "TgdIAd1FRgK2ZXDDrEdjnsSEfShKf0l4mFPSBs9E3U6sLmubDRXKLLLpa/dF4eKu\n" + - "LEKS1bXYT28iM6D5gSCnzho5G4d18jQD/slmc5XmRo5Pig0RyBwDaLuxeIZuiJ0A\n" + - "J6YFhffbrLYF5dEQl0cU+t3VBK5u/o1WkWXsZawU038lWn/AXerodT/pAcrtWA4E\n" + - "NQEN09WEKMhZVPhqdwhF/Gusr04mQtKt7T2v6UMQvtVglv5E7wIDAQABo4IBOTCC\n" + - "ATUwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYE\n" + - "FNpDStD8AcBLv1gnjHbNCoHzlC70MB8GA1UdIwQYMBaAFLAM8Eww9AVYAkj9M+VS\n" + - "r0uE42ZSMHsGCCsGAQUFBwEBBG8wbTAvBggrBgEFBQcwAYYjaHR0cDovL29jc3Au\n" + - "cm9vdGNhMi5hbWF6b250cnVzdC5jb20wOgYIKwYBBQUHMAKGLmh0dHA6Ly9jcnQu\n" + - "cm9vdGNhMi5hbWF6b250cnVzdC5jb20vcm9vdGNhMi5jZXIwPwYDVR0fBDgwNjA0\n" + - "oDKgMIYuaHR0cDovL2NybC5yb290Y2EyLmFtYXpvbnRydXN0LmNvbS9yb290Y2Ey\n" + - "LmNybDARBgNVHSAECjAIMAYGBFUdIAAwDQYJKoZIhvcNAQEMBQADggIBAEO5W+iF\n" + - "yChjDyyrmiwFupVWQ0Xy2ReFNQiZq7XKVHvsLQe01moSLnxcBxioOPBKt1KkZO7w\n" + - "Gcbmke0+7AxLaG/F5NPnzRtK1/pRhXQ0XdU8pVh/1/h4GoqRlZ/eN0JDarUhZPkV\n" + - "kSr96LUYDTxcsAidF7zkzWfmtcJg/Aw8mi14xKVEa6aVyKu54c8kKkdlt0WaigOv\n" + - "Z/xYhxp24AfoFKaIraDNdsD8q2N7eDYeN4WGLzNSlil+iFjzflI9mq1hTuI/ZNjV\n" + - "rbvob6FUQ8Cc524gMjbpZCNuZ1gfXzwwhGp0AnQF6CJsWF9uwPpZEVFnnnfiWH3M\n" + - "oup41EvBhqaAqOlny0sm5pI82nRUCAE3DLkJ1+eAtdQaYblZQkQrRyTuPmJEm+5y\n" + - "QwdDVw6uHc5OsSj/tyhh8zJ2Xq3zgh3dMONGjJEysxGaCoIb+61PWwMy2dIarVwI\n" + - "r+c+AY+3PrhgBspNdWZ87JzNHii7ksdjUSVGTTy1vGXgPYrv0lp0IMnKaZP58xiw\n" + - "rDx7uTlQuPVWNOZvCaT3ZcoxTsNKNscIUe+WJjWx5hdzpv/oksDPY5ltZ0j3hlDS\n" + - "D+Itk95/cNJVRM/0HpxI1SX9MTZtOSJoEDdUtOpVaOuBAvEK4gvTzdt0r5L+fuI6\n" + - "o5LAuRo/LO1xVRH49KFRoaznzU3Ch9+kbPb3\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=good.sca2a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 2A, O=Amazon, C=US - // Serial number: 703e4e70616c90d611fd04a5ecc635665184e - // Valid from: Mon Jul 29 16:54:06 PDT 2019 until: Sat Aug 29 16:54:06 PDT 2020 + "b24gUm9vdCBDQSAyMB4XDTIyMDgyMzIyMjkxM1oXDTMwMDgyMzIyMjkxM1owPDEL\n" + + "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT\n" + + "QSA0MDk2IE0wMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMGMl/pZ\n" + + "1OsxHY9gw/YfdON4mmrANkPwi7z2djHA5ELt/vRI3Su0le6OoipLf03iyoCnYy4Y\n" + + "rpfTbhyDriE8NJpps2ODJ5W1h0rz6FM1Q5Jt35wfk+4CEfATBTegHVlUJ0rJgzK5\n" + + "Yl/jrk12ZsC4ZeRn54shszcK6bHj4LZIHXhrYIIfetBMMD8V7hlhd54AclEWutUV\n" + + "eBEjkSCzDSk+pQKIjCL0crqvRSPvUNry/BV65zfGmceSYxpcLmV7k7Spwpo+1z8w\n" + + "+Odfnx2vsm7olPldfaThqk6fXBtInORl4Ef32xF3VDT13UeXtQPolFhnp8UOci64\n" + + "bW+R8tbtGpUXIA8Dhr8SgYPH6NW4jhUD4+AG8yer8ctA1Hl9tq+6tYr26q3yuCLu\n" + + "5rwJdfMG634fWIRXSj+GJi8SfAdGtPyXwu5799NWesV4vUkrkSXdIBK4TQCuK+jx\n" + + "aJ5Y+Zo2l3GFsWyMPNORLjoQXbjF6KAyjTyICLq9VzoQKhyx4Ll2CNrQv8CxqtDC\n" + + "GvXi9kREJYAF6lscOB0xglAAF5lndcaNkVHEVOMdg9ZZtdJywHWm8Qed1Wty2qr+\n" + + "hmA7booWQNRE12nW1niC5D4cP2ykPK9HSgb7xWdUF32VidUc9tNKM6xKjSd/R/tP\n" + + "p+XAybNSwEooPt3/OvyhpVRjLuWoqqbClTKdAgMBAAGjggFaMIIBVjASBgNVHRMB\n" + + "Af8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcD\n" + + "AQYIKwYBBQUHAwIwHQYDVR0OBBYEFJ5xHxodk6nZLY7MSFM/A1TznuZmMB8GA1Ud\n" + + "IwQYMBaAFLAM8Eww9AVYAkj9M+VSr0uE42ZSMHsGCCsGAQUFBwEBBG8wbTAvBggr\n" + + "BgEFBQcwAYYjaHR0cDovL29jc3Aucm9vdGNhMi5hbWF6b250cnVzdC5jb20wOgYI\n" + + "KwYBBQUHMAKGLmh0dHA6Ly9jcnQucm9vdGNhMi5hbWF6b250cnVzdC5jb20vcm9v\n" + + "dGNhMi5jZXIwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC5yb290Y2EyLmFt\n" + + "YXpvbnRydXN0LmNvbS9yb290Y2EyLmNybDATBgNVHSAEDDAKMAgGBmeBDAECATAN\n" + + "BgkqhkiG9w0BAQwFAAOCAgEAl1GgKXOn0j1MWT1KJVSewQ28SGbie3UwZj1dMsjJ\n" + + "amCrQPn2ngSNbLm9+ulFiBDU8xKR9Zx3tZps55IUKWLUPkfMC+vkV7asDBqqzzE0\n" + + "F/MkekgPfOjx1V9S6Wfg3sSg+9KcluurXFElruqKfOm4cqmkV776X1G+AaaQ7mlU\n" + + "giCYi6NqRQSyhn8zrKkNnbO6QL5a9ICC47kiZYRAR/hRvZOt11QUK5tCMXJXo0iO\n" + + "4XKkMu+jdnehP1kh4xuZhYznIgKK6MJIITFI/Jj89U4SOPncyuS94sUuE2EqvvO/\n" + + "t81qeoey6wThz5iRbU/0CvDFnTMgebWGUZ2UZJ+az/rb3KYXGfVWasLIonkvYT7z\n" + + "vHOGNAA9oQ8TTgPOmPfSVyfpplKtO/aybWp5QSH2csIwuvw5dkmpkc42iD57XHob\n" + + "5LbMJg99z3vQBmod/ipmOpND95/BeA2mllBZgZ53S0nvDXDzbzR9Fd81PAz9Qruo\n" + + "dOJKcD6plKQjZjkLzNh1v/RoCFO8kiJGE4UBMTM8FUk0DXH4bALII4wwmDelrSUu\n" + + "lKvDTDxZvPF4dbEXICNPd51EMGPgETxwboOV+bzWFVI0IWQ8PhZ2VuMPDk2taOMp\n" + + "NsuLtlYc2twPb9r/Hvgv7G6+ItpBHZwOVt1oI3pHbjMp7P3pOZSPr6G1WkNy9mX8\n" + + "rVc=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=valid.rootca2.demo.amazontrust.com + // Issuer: CN=Amazon RSA 4096 M02, O=Amazon, C=US + // Serial number: 662f7646d76193cbb76946d111e49fa + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + - "MIIHEzCCBPugAwIBAgITBwPk5wYWyQ1hH9BKXsxjVmUYTjANBgkqhkiG9w0BAQwF\n" + - "ADBGMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2\n" + - "ZXIgQ0EgMkExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTA3MjkyMzU0MDZaFw0yMDA4\n" + - "MjkyMzU0MDZaMIHaMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwC\n" + - "AQITCERlbGF3YXJlMR0wGwYDVQQPExRQcml2YXRlIE9yZ2FuaXphdGlvbjEQMA4G\n" + - "A1UEBRMHNTg0Njc0MzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24x\n" + - "EDAOBgNVBAcTB1NlYXR0bGUxHjAcBgNVBAoTFUFtYXpvbiBUcnVzdCBTZXJ2aWNl\n" + - "czEjMCEGA1UEAxMaZ29vZC5zY2EyYS5hbWF6b250cnVzdC5jb20wggIiMA0GCSqG\n" + - "SIb3DQEBAQUAA4ICDwAwggIKAoICAQC+XjOB3ZCFX+b9y9reP+e6EAQz4ytiMSqU\n" + - "O4s5MyYLkY6n4BIZHmgWeQ2IgW1VrH8ho+Iu3UsTiuhd3/L/q/w+T0OJfcrWngTs\n" + - "uVcIuvUr32ObPeeWbg/m/lkN7hqH1jY62iybYVrFXiLo1+0G92PUazcyNvyA20+G\n" + - "HsvGG5jlArWNgRLdc8KUXxvnDUxx5vu4jeHEZnqSwuulV1h9ve0UutkmoK0Sk7Rz\n" + - "HMxYK0LmUT5OvcNQSkUi5nLi+M1FxnYYgsELwSiKSSEDfEdgxooMAiVTgw51Q/DB\n" + - "lTOjAIDL3K3J0yGfIG3bwLvE1qz2Z5yWn8f3JibIah7LrC4PiZDDLHFM6V9l+YqU\n" + - "RqimJ5BltSyAx7bxQNZ1AW3Lxvvm894i4k6/Vdf1CDovRuTMPCDAQmKA/A/AQ7TN\n" + - "q3bBimX6UyuJu0I8RyvAYKzFhOOqe4vXrbndTbje/jnzTNQPeIIcuRa9cgXTOrbw\n" + - "86FTUKj6AZXihRWjKWsQpDwdgE0tQETZ3ynCXfbBKfFmn0MSjeX0CEEAZdYHR8EV\n" + - "F271Yt7UJjS/FP702aHTOWk7zFbIRfFQODvBhn0I8p/Stk2sDq4/YsbXVZOe3+ad\n" + - "YavoiODGSAH6ZcZzULumgK9eii0koAOPB/xqXnkcTS63gEHOKjLQl3hqdVZRCugv\n" + - "1CwUXLvoSwIDAQABo4IBYzCCAV8wDgYDVR0PAQH/BAQDAgWgMB0GA1UdDgQWBBTa\n" + - "j6dHgPdOxTGLcwaNDeaMnlSxNjAfBgNVHSMEGDAWgBTaQ0rQ/AHAS79YJ4x2zQqB\n" + - "85Qu9DAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwdQYIKwYBBQUHAQEE\n" + - "aTBnMC0GCCsGAQUFBzABhiFodHRwOi8vb2NzcC5zY2EyYS5hbWF6b250cnVzdC5j\n" + - "b20wNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQuc2NhMmEuYW1hem9udHJ1c3QuY29t\n" + - "L3NjYTJhLmNlcjAlBgNVHREEHjAcghpnb29kLnNjYTJhLmFtYXpvbnRydXN0LmNv\n" + - "bTBQBgNVHSAESTBHMA0GC2CGSAGG/W4BBxgDMDYGBWeBDAEBMC0wKwYIKwYBBQUH\n" + - "AgEWH2h0dHBzOi8vd3d3LmFtYXpvbnRydXN0LmNvbS9jcHMwDQYJKoZIhvcNAQEM\n" + - "BQADggIBAE6RwZAZvN0i9ygwzqoX9DhSPtvZ3xIO0G0Bhgjkb986+p8XJstU3gEM\n" + - "8P2i1J/YthXCnRGedm+Odxx+31G6xIYfP5S5g7HyRGkj/aXNXy4s3KjH8HJgOY9N\n" + - "ra3XfC05OKq5FpyZQDZ+hxCdLrH3Gs+UxREbu+LuIKUpI7nMVEjn9XynKyOdKN21\n" + - "Kq5VsuI0fDWCYvUN1M+lI/LgE5HbNJVQJs+dB7g1/kaOeaLia7Wk1ys+uRzB58rp\n" + - "FKAoLk++HWTfNDkbN8vKRfHhJ/xhI9ju3TWcci6EyFVAym1C62UkJNI0KHgQ+zc7\n" + - "nl1tv/ytj8N/eJoysyp23lJ5qrVetlQORfgXryGkWBMYBvYF8zbBb/f+UXHDKVWt\n" + - "9l1lL6HQGY/tTo253pj6/FgDD35bZdjLQeUVmbnz679S5oUmoH5ZtSdnpUTghU3p\n" + - "bae9adBFY9S1pm50Q3ckRVBAwNqNmI0KKUh14Ms8KSAUHg19NvGsBonqwOT2rdbv\n" + - "xZ47N6c2eCl/cjMvzre0v0NoUO+3og2GHeAoOwVos6480YDbMqp739tOFPxBcsII\n" + - "6SjpDVh+14dkSW6kEKeaCFLR+eChqutri1VQbQ49nmADQWw9Al8vBytSnPv0YN6W\n" + - "XfIE1Qj7YmHu/UuoeKVsqDqoP/no29+96dtfd4afJqlIoyZUqXpt\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=revoked.sca2a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=PrivateOrganization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - //Issuer: CN=Amazon, OU=Server CA 2A, O=Amazon, C=US - //Serial number: 6f1d782c0aa2f4866b7b522c279b939b92369 - //Valid from: Mon Jan 28 15:37:45 PST 2019 until: Thu Apr 28 16:37:45 PDT 2022 + "MIIICzCCBfOgAwIBAgIQBmL3ZG12GTy7dpRtER5J+jANBgkqhkiG9w0BAQwFADA8\n" + + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRwwGgYDVQQDExNBbWF6b24g\n" + + "UlNBIDQwOTYgTTAyMB4XDTIzMDUxMDAwMDAwMFoXDTI0MDYwNzIzNTk1OVowLTEr\n" + + "MCkGA1UEAxMidmFsaWQucm9vdGNhMi5kZW1vLmFtYXpvbnRydXN0LmNvbTCCAiIw\n" + + "DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAON5EbEKoBiujI7Ja8mLZLJbaY7f\n" + + "RtoWIjU/F0l9ueWFogXmEaA1jWsl97F3WTHTyGKz6ChCjPMSyoXXpY+yoE90QUyX\n" + + "w35uWEhNrc40drMJkyN+QXitSrH346GCOKvpYVvu18UD4W8hDhg8vvbOQYhtmSf7\n" + + "Rfrs7/qUdXpzpvR9VjWktbQAzJT8fB/jFNjNQJTknynjGiYO5GF51+peOCLK6qw8\n" + + "9kKYEigR4K8/aWL283rC4xRxZqVioy433VG02l/Fwdv8o/vL9YYIqkyspCB9fpFw\n" + + "Q50yYrwEomxuOz7rXhmdfeNaFYuyTtOUSKff6p2oqO0S7pcLujUVMlO4dYBDELQF\n" + + "cabByNjwblviCtGKJMIzD6Thkgamp3iXQgcU498+P5r7N5CYbMmkJEdcuILg+bgJ\n" + + "/LUUTT+IMt2txYlO/ld3N0EHlgVt7rztW5mtm6Ba8jN7cLSh7ZWu6Fr1+oK7bl5T\n" + + "wPxSfqT5W3BwQKS3YptIoKEWUb+VNnS/dYx/7IspF9+z6kw4g+V2EY9M4ZYNakzM\n" + + "AI7KIj4thMFoWeYrJq0dUMZ297QCBPRdAwh9hhkq2LYi2x8tMUtcBnhb/q75sO+E\n" + + "icPqFVv7iMDZ/8Xep+0UoClF3JGmZW3UNtwcbi7Pn/OqtaMi7E8xnHUgc4ZchtXO\n" + + "v8VtVvDeZAlY5TjVAgMBAAGjggMWMIIDEjAfBgNVHSMEGDAWgBSecR8aHZOp2S2O\n" + + "zEhTPwNU857mZjAdBgNVHQ4EFgQUnGekBRKIZBYgCEajbpCMC24bp2owSQYDVR0R\n" + + "BEIwQIIidmFsaWQucm9vdGNhMi5kZW1vLmFtYXpvbnRydXN0LmNvbYIaZ29vZC5z\n" + + "Y2EyYS5hbWF6b250cnVzdC5jb20wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQG\n" + + "CCsGAQUFBwMBBggrBgEFBQcDAjA7BgNVHR8ENDAyMDCgLqAshipodHRwOi8vY3Js\n" + + "LnI0bTAyLmFtYXpvbnRydXN0LmNvbS9yNG0wMi5jcmwwEwYDVR0gBAwwCjAIBgZn\n" + + "gQwBAgEwdQYIKwYBBQUHAQEEaTBnMC0GCCsGAQUFBzABhiFodHRwOi8vb2NzcC5y\n" + + "NG0wMi5hbWF6b250cnVzdC5jb20wNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQucjRt\n" + + "MDIuYW1hem9udHJ1c3QuY29tL3I0bTAyLmNlcjAMBgNVHRMBAf8EAjAAMIIBfQYK\n" + + "KwYBBAHWeQIEAgSCAW0EggFpAWcAdgDuzdBk1dsazsVct520zROiModGfLzs3sNR\n" + + "SFlGcR+1mwAAAYgHvX9QAAAEAwBHMEUCIQD8qPPCLL2Grd+/YNALWqAq7LC7YBaa\n" + + "dNg5+6Q4kRDEqgIgEkf/UMsMNfTRaOZvoOgAK9/F0xX/CfdcUTjULhmoA+cAdQBI\n" + + "sONr2qZHNA/lagL6nTDrHFIBy1bdLIHZu7+rOdiEcwAAAYgHvX8UAAAEAwBGMEQC\n" + + "IBVFDtapMMWJOqyu8Cv6XEhFmbU8N33c2owed//pa80xAiAT9T6Wba3B9DFUmrL5\n" + + "cCGKLqciIEUPhPbvjCuUepelrAB2ANq2v2s/tbYin5vCu1xr6HCRcWy7UYSFNL2k\n" + + "PTBI1/urAAABiAe9ft8AAAQDAEcwRQIhAP2XDC/RlmVtH4WrfSwVosR/f/WXRhG5\n" + + "mk9Nwq+ZOIriAiAopPXSH7VwXa3bEAIiTwcV1l10QIDZaIPCU5olknU5CjANBgkq\n" + + "hkiG9w0BAQwFAAOCAgEAFuwMIJdP5rgz6cqOIj2EgF2OU8CUGi/wJ45BomXWv4Rv\n" + + "U5mOKB+jHOGZZC9dncjAMa44RwoF2I7/8Y3qLVaoNm46ObvvS+6UvzTcyQqXM7JU\n" + + "cSmdlf9DkspjKPDvMBokVrM4ak5AoxUjuru5qaia3nvbxq7XKO9/FGUaUaU8Xlsd\n" + + "V6Fo8VmNwFc88VCqOp8eI/IicHxMDLl8TKXMvr3CYh8A9nCeFGcV+4CL+7JF2t5K\n" + + "YvV5r074Wyk0QMlRVYMNDl0t+VAEoDJ7RRE+kEvplWcsX9S2wvr4HhkA4iChpwFm\n" + + "2UDTppHskSWyLsuNQvipn0zTzZ8RIxXd/ei0qCdhKmkV7x9cgbTiyXgaI7iJEtdo\n" + + "RvYNcXc2RmitWjY5Av8yJGOk0eYpCwRrBv6ughbtJe3NMrqUeTyrKidIEo9KnRSA\n" + + "rMokRbHunkroS97VkoK/9j9pNJki+qAH9XTLYWcm/5+cTSGRsN+escRgZwV6KWg/\n" + + "JQQe5LbwU2HHzNqWuk63GC/ngVlWXjaVFfbNVmYEKZFFazcZchesN1YyDu+WndOx\n" + + "+rTcuke2feOvQ4EnVviM0k85JZNiqPDH2iafAWyqZFUYTnb7XK3HhJflAniv/SLq\n" + + "DQfbJmtQtNHdJYgVmC1u2RT9gbJDIAj0ZI4vU2WVB5Hmd9F31un6jundEuG4+S4=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=revoked.rootca2.demo.amazontrust.com + // Issuer: CN=Amazon RSA 4096 M02, O=Amazon, C=US + // Serial number: 788baa8f47bc5b1c624424216240fd3 + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + - "MIIG2zCCBMOgAwIBAgITBvHXgsCqL0hmt7Uiwnm5ObkjaTANBgkqhkiG9w0BAQwF\n" + - "ADBGMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2\n" + - "ZXIgQ0EgMkExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTAxMjgyMzM3NDVaFw0yMjA0\n" + - "MjgyMzM3NDVaMIHcMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwC\n" + - "AQITCERlbGF3YXJlMRwwGgYDVQQPExNQcml2YXRlT3JnYW5pemF0aW9uMRAwDgYD\n" + - "VQQFEwc1ODQ2NzQzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ\n" + - "MA4GA1UEBxMHU2VhdHRsZTEeMBwGA1UEChMVQW1hem9uIFRydXN0IFNlcnZpY2Vz\n" + - "MSYwJAYDVQQDEx1yZXZva2VkLnNjYTJhLmFtYXpvbnRydXN0LmNvbTCCAiIwDQYJ\n" + - "KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKFm418X8hN1YTgD2XpMb4sp78mw8k3j\n" + - "Dq/vnpX48evVUzNpHpy4qRz/ZHBR4HUJO4lhfnX+CO0uRqqqx4F0JZRQB3KevaU8\n" + - "QGWHdJGhEddnurDhrgOUa+ZroqUnMCsTJfbyGtC6aiEXeu/eMhEUFkuBxJH1JtwD\n" + - "dQXMXuMjG07SVjOkhTkbMDzA/YbUqkDeOIybifDuvA5LEsl+kReY0b6RYFo2Tt/M\n" + - "dPhJD8q3Wsu+XCiCnbpcwlEVGxiD2RVRXJJ9o3ALGOxqU69V+lYS0kkwNHT7oV9J\n" + - "rhgt7iOCq0aoTAxu2j4FCp0JHNhGoW9pXoMXnmS6kK80hzLNYDxvKEaVaKkiYHw5\n" + - "CV0Vwii05ICa14nrStH/jcRNLyU+gp+6OeerPV3jpKWshGKWewF+2UiWU2WHTSrd\n" + - "Wis0/qEfFK/kSraAxpd+KavEEavKeudoMAHIxMACOk9E/fF5zhd2y4G1q1BdoRlR\n" + - "KP4GIV2v6qH6Ru2mNSuge9il6kDXxFNucrYKLDbAqkqalohkvDavcPoG9gZT3etv\n" + - "4IcgJriIWRxbJwKPpwJM+6wa6RpwoeJMuEp3ZBP7KDaQ8YX4rlf4zXLAsOKCNA9K\n" + - "OS/qYQ/I4g0E1WhfgEKClaLPS2u7jeVR6s1t4txGo4vq5Dkt17KTCew/WsX3rckf\n" + - "a2p5zvFcfpCNAgMBAAGjggEpMIIBJTAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0OBBYE\n" + - "FAF8N1wV8EoYFkMXH6tEnmR/7vI+MB8GA1UdIwQYMBaAFNpDStD8AcBLv1gnjHbN\n" + - "CoHzlC70MB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjB1BggrBgEFBQcB\n" + - "AQRpMGcwLQYIKwYBBQUHMAGGIWh0dHA6Ly9vY3NwLnNjYTJhLmFtYXpvbnRydXN0\n" + - "LmNvbTA2BggrBgEFBQcwAoYqaHR0cDovL2NydC5zY2EyYS5hbWF6b250cnVzdC5j\n" + - "b20vc2NhMmEuY2VyMCgGA1UdEQQhMB+CHXJldm9rZWQuc2NhMmEuYW1hem9udHJ1\n" + - "c3QuY29tMBMGA1UdIAQMMAowCAYGZ4EMAQIBMA0GCSqGSIb3DQEBDAUAA4ICAQBC\n" + - "VwR1NFk1IYIF4cjU7ML1aj8OIn+8mtakGQnuSJLK6ypSysINJBS48ZDdP6XZXvyD\n" + - "iTS0xEAPjAZHTqrABdNYmvJeL2RnN99DIwVzBpZp4NLTXbiSW7jb0Y5cEPDGJMOo\n" + - "SUAAM6fsiPRfz5vX4XVPznbcF2AwE/NVV+L3n9LVRt7qv2VqIEvLioR56Dq+5ofR\n" + - "4bw0BVlEYWF4Gsy7WDDTL1iLNBUwZTqBHwTv0fgDRiPqb/odmLQuRANwcJy8B8Zr\n" + - "s/yX4SeESaRdA82lAlQilksQitXS2qvQN06GEDOgUxYE6EabFdgklV5JypKqdOly\n" + - "vzpaDpF3z5W8Bj3D4fns1Kjrh1pPh5JRvg+616diKnQRt4X5q+EtmnXhDvIGMISI\n" + - "FuGwj57CNQ2x2MY2HHKWPrOccpQfEEvoSNR+ntYWrtSSttZq948O+zZBk1TXWuXV\n" + - "TVXllqTg8lp6d5cfKgvtHKgt98WkpPOcLVrNuVnMAIfDw6ar54dVKqrvkeEcF6mJ\n" + - "7oMKjJX/Vu9lYoGViBIfdeqcCPWSI8BpnCKaG7dTQO3Q1ObGmLdGBRlsRh+d+S5l\n" + - "Fq326ckbjx537e5/ai31lOR7OwVh9TDweKLqIACjs987C0EJSEfoOue25WRww2va\n" + - "iX9SrTPm4GxQ2OJgYwx0+HbezJXFN+dhaOFUavTSFw==\n" + - "-----END CERTIFICATE-----"; - - public void runTest(ValidatePathWithParams pathValidator, boolean ocspEnabled) throws Exception { - // EE certificates don't have CRLDP extension - if (!ocspEnabled){ - pathValidator.validate(new String[]{INT}, - ValidatePathWithParams.Status.GOOD, null, System.out); + "MIIIEjCCBfqgAwIBAgIQB4i6qPR7xbHGJEJCFiQP0zANBgkqhkiG9w0BAQwFADA8\n" + + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRwwGgYDVQQDExNBbWF6b24g\n" + + "UlNBIDQwOTYgTTAyMB4XDTIzMDUxMDAwMDAwMFoXDTI0MDYwNzIzNTk1OVowLzEt\n" + + "MCsGA1UEAxMkcmV2b2tlZC5yb290Y2EyLmRlbW8uYW1hem9udHJ1c3QuY29tMIIC\n" + + "IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAzJfddWdrWhA9dSJdmy23veN9\n" + + "oLvSqpM4YaXGZmPtKUmbFMLs2I3vCKrzflRKeOpl3MCc2hh6TH/3z+Q/fGugXLsY\n" + + "H8QcjSbiIOd15n+3dUFTLKaoWMyseMcWiOIVaN5rCDVXiAHdt1pc147wyFQIzqNK\n" + + "J/xiV1u9eT2MFue+4bd7kUNAcmI8M+SXruhto4jtAV8ugpTEChTDlyO/l8xmaM1Q\n" + + "HkijsHX7Aq72Q/3PH/U+wbJ9pmpTp4x2AEJoo45IGfB/NKDTrv5otLBuiP8Y0M7b\n" + + "K7irRPDFBqMNZw7S7p39SnC+V/WibJQk5Bo/8vcwDJX+WnDkw1QD/uXu3ugDzSDD\n" + + "iBDViMOdN+3K47s4x2kdssoh4WWScMlAVb4vyN7IA3J4TnwA/1uCWhw4LE1WvY7N\n" + + "etekhVP1eWF8IzNY0oo2u2ie79777xvBtmtp7RnvYLGv7I+xVhjH5qGNzn9fRCUm\n" + + "QDego5HAfJ0PLlMEagdW8asCak1WaC117adnibL6WPtFA2FD2i6gNalTvhXhK2Ex\n" + + "alGxrVd/BCseT3bMp783jqScJO1g6xRHu0Qx+RyrOGVvcKZa6Y0DcAc8psRpkHaO\n" + + "HZY+lE8O2CIxpAJlwSnD6BoDNo8sg1IqFNkECw3wqfeMPBcg38k6zjAxwRDcIx6U\n" + + "SwDl4d3sjrmy3gOFFXMCAwEAAaOCAxswggMXMB8GA1UdIwQYMBaAFJ5xHxodk6nZ\n" + + "LY7MSFM/A1TznuZmMB0GA1UdDgQWBBQXpWT7gMHO+HKoHM1gU1VQVnylRzBOBgNV\n" + + "HREERzBFgiRyZXZva2VkLnJvb3RjYTIuZGVtby5hbWF6b250cnVzdC5jb22CHXJl\n" + + "dm9rZWQuc2NhMmEuYW1hem9udHJ1c3QuY29tMA4GA1UdDwEB/wQEAwIFoDAdBgNV\n" + + "HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwOwYDVR0fBDQwMjAwoC6gLIYqaHR0\n" + + "cDovL2NybC5yNG0wMi5hbWF6b250cnVzdC5jb20vcjRtMDIuY3JsMBMGA1UdIAQM\n" + + "MAowCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAtBggrBgEFBQcwAYYhaHR0cDov\n" + + "L29jc3AucjRtMDIuYW1hem9udHJ1c3QuY29tMDYGCCsGAQUFBzAChipodHRwOi8v\n" + + "Y3J0LnI0bTAyLmFtYXpvbnRydXN0LmNvbS9yNG0wMi5jZXIwDAYDVR0TAQH/BAIw\n" + + "ADCCAX0GCisGAQQB1nkCBAIEggFtBIIBaQFnAHYA7s3QZNXbGs7FXLedtM0TojKH\n" + + "Rny87N7DUUhZRnEftZsAAAGIB72CzgAABAMARzBFAiEA2vPYIPfGJeynPaZHq/c0\n" + + "GGvyT6MpvFGMW0s0woLRT28CIEFbZbFSCnKugaqw9QDNi7vYmIF3Gyi3s6G2cCxY\n" + + "4RJXAHYASLDja9qmRzQP5WoC+p0w6xxSActW3SyB2bu/qznYhHMAAAGIB72DDgAA\n" + + "BAMARzBFAiAvfNcgtFEwk5C9dvMUYANbIAv0IOdF1new8Umn3cM+JwIhALbs/3L9\n" + + "0ndF7sRKDZmfronNruptFlrI528P5Qi2P528AHUA2ra/az+1tiKfm8K7XGvocJFx\n" + + "bLtRhIU0vaQ9MEjX+6sAAAGIB72CxQAABAMARjBEAiBKUns2FPbs0cThb6e7SnyL\n" + + "y4/qP3V1Q/ASt/ZDRTeEQQIgWSQO4Gsz32srtqYuTM9AsFd92WA44kJHincdcGVX\n" + + "XbIwDQYJKoZIhvcNAQEMBQADggIBAAnaNbn2wXylTCS7dtgB3rWdUf6hja1UDuvB\n" + + "uZEL2dUOvyXfVFLNxKdeWBPzqpwEBNNwPQXhoI97TXlyu2x60jLzQamoGoRQ3s0P\n" + + "NLhasLGEIQH/oYdMV/yp8EI8fUuRVE3xyw39FRqOrmsUFAnxNQmBO/09JM7sLcvS\n" + + "wwh14p9dFTTolJHgnL4ZEtmZxSddFG+GBSTJ/A7dVSmwIudwzd+goA6173BI6yeT\n" + + "hhQumLctQiOM7y1MzFeV8rL+oIpd2xuzyhKKT1EgvU6/wyt0Ib8QqsFsrXPnUOKk\n" + + "HAq3SeZyq35QUaTKoaH9L1iZMbSCG9Jm6FMb12SdAz53653tYvAiUS76oD8Jot13\n" + + "RZu5NUlWAVLLq0OaEtuGp0bh+cVtzVnCC9m1qa46YpY0SojpvSbakgQMMGIgDlT3\n" + + "wFE7tST4WlsDC1f/m+H9V5qz/j0U8D3eNNdowxPqx/JZq/sk9ZK5KyMFARrvM+fh\n" + + "YrVYjKt91mu7JaS4pPOyZmJ8OQ14EvrN7BXc7IkNrI1reeaRFe49k5DAETB8VmP5\n" + + "2F0SWou2KkgtJvU4Z7YjlZ2HNHnpjTK5KdPNpRSt7EUy2zn9NCNoyQhnws70FyXv\n" + + "oPFyG92lnUQOKaAUhVRwTr9fvnkdMOzSKg/spxi2Ogdzym5Jw68eguwi0dVqX2+9\n" + + "3zViP2aH\n" + + "-----END CERTIFICATE-----"; - return; - } + public void runTest(ValidatePathWithParams pathValidator) throws Exception { // Validate valid pathValidator.validate(new String[]{VALID, INT}, @@ -344,201 +378,228 @@ // Validate Revoked pathValidator.validate(new String[]{REVOKED, INT}, ValidatePathWithParams.Status.REVOKED, - "Mon Jan 28 15:38:57 PST 2019", System.out); + "Mon May 15 13:38:54 PDT 2023", System.out); } } class AmazonCA_3 { - // Owner: CN=Amazon, OU=Server CA 3A, O=Amazon, C=US + // Owner: CN=Amazon ECDSA 256 M02, O=Amazon, C=US // Issuer: CN=Amazon Root CA 3, O=Amazon, C=US - // Serial number: 67f945758fe55b9ee3f75831d47f07d226c8a - // Valid from: Wed Oct 21 17:00:00 PDT 2015 until: Sat Oct 18 17:00:00 PDT 2025 - private static final String INT = "-----BEGIN CERTIFICATE-----\n" + - "MIICuzCCAmGgAwIBAgITBn+UV1j+VbnuP3WDHUfwfSJsijAKBggqhkjOPQQDAjA5\n" + + // Serial number: 773126de2c2fafd2c47ad88b1566e0182046d + // Valid from: Tue Aug 23 15:33:24 PDT 2022 until: Fri Aug 23 15:33:24 PDT 2030 + private static final String INT_VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIC1DCCAnmgAwIBAgITB3MSbeLC+v0sR62IsVZuAYIEbTAKBggqhkjOPQQDAjA5\n" + + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\n" + + "Um9vdCBDQSAzMB4XDTIyMDgyMzIyMzMyNFoXDTMwMDgyMzIyMzMyNFowPTELMAkG\n" + + "A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEdMBsGA1UEAxMUQW1hem9uIEVDRFNB\n" + + "IDI1NiBNMDIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAS9vQLD4W/Kg4AnFRl8\n" + + "x/FUbLqtd5ICYjUijGsytF9hmgb/Dyk+Ebt4cw6rAlGbaiOLapSJKZiZr+UQdh3I\n" + + "QOr+o4IBWjCCAVYwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYw\n" + + "HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBS7eJrXaDMy\n" + + "nRq7bP2xNEwB3svQdTAfBgNVHSMEGDAWgBSrttvXBp43rDCGB5Fwx5zEGbF4wDB7\n" + + "BggrBgEFBQcBAQRvMG0wLwYIKwYBBQUHMAGGI2h0dHA6Ly9vY3NwLnJvb3RjYTMu\n" + + "YW1hem9udHJ1c3QuY29tMDoGCCsGAQUFBzAChi5odHRwOi8vY3J0LnJvb3RjYTMu\n" + + "YW1hem9udHJ1c3QuY29tL3Jvb3RjYTMuY2VyMD8GA1UdHwQ4MDYwNKAyoDCGLmh0\n" + + "dHA6Ly9jcmwucm9vdGNhMy5hbWF6b250cnVzdC5jb20vcm9vdGNhMy5jcmwwEwYD\n" + + "VR0gBAwwCjAIBgZngQwBAgEwCgYIKoZIzj0EAwIDSQAwRgIhAKSYEcDcp3kcPMzh\n" + + "OIYDWZOLu4InPod4fQhRTmc2zBAgAiEAmwdGE4AuNWhw9N8REhf82rJLNm7h9Myg\n" + + "TsR9Wu0bQYU=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=Amazon ECDSA 256 M01, O=Amazon, C=US + // Issuer: CN=Amazon Root CA 3, O=Amazon, C=US + // Serial number: 773126684d577c0fcf8d3a342bea86f94fc8f + // Valid from: Tue Aug 23 15:31:46 PDT 2022 until: Fri Aug 23 15:31:46 PDT 2030 + private static final String INT_REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIC0zCCAnmgAwIBAgITB3MSZoTVd8D8+NOjQr6ob5T8jzAKBggqhkjOPQQDAjA5\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\n" + - "Um9vdCBDQSAzMB4XDTE1MTAyMjAwMDAwMFoXDTI1MTAxOTAwMDAwMFowRjELMAkG\n" + - "A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENBIDNB\n" + - "MQ8wDQYDVQQDEwZBbWF6b24wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATYcYsK\n" + - "mYdR0Gj8Xz45E/lfcTTnXhg2EtAIYBIHyXv/ZQyyyCas1aptX/I5T1coT6XK181g\n" + - "nB8hADuKfWlNoIYRo4IBOTCCATUwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8B\n" + - "Af8EBAMCAYYwHQYDVR0OBBYEFATc4JXl6LlrlKHvjFsxHhN+VZfaMB8GA1UdIwQY\n" + - "MBaAFKu229cGnjesMIYHkXDHnMQZsXjAMHsGCCsGAQUFBwEBBG8wbTAvBggrBgEF\n" + - "BQcwAYYjaHR0cDovL29jc3Aucm9vdGNhMy5hbWF6b250cnVzdC5jb20wOgYIKwYB\n" + - "BQUHMAKGLmh0dHA6Ly9jcnQucm9vdGNhMy5hbWF6b250cnVzdC5jb20vcm9vdGNh\n" + - "My5jZXIwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC5yb290Y2EzLmFtYXpv\n" + - "bnRydXN0LmNvbS9yb290Y2EzLmNybDARBgNVHSAECjAIMAYGBFUdIAAwCgYIKoZI\n" + - "zj0EAwIDSAAwRQIgOl/vux0qfxNm05W3eofa9lKwz6oKvdu6g6Sc0UlwgRcCIQCS\n" + - "WSQ6F6JHLoeOWLyFFF658eNKEKbkEGMHz34gLX/N3g==\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=good.sca3a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 3A, O=Amazon, C=US - // Serial number: 703e4e9bbc2605f37967a0e95f31f4789a677 - // Valid from: Mon Jul 29 16:54:43 PDT 2019 until: Sat Aug 29 16:54:43 PDT 2020 + "Um9vdCBDQSAzMB4XDTIyMDgyMzIyMzE0NloXDTMwMDgyMzIyMzE0NlowPTELMAkG\n" + + "A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEdMBsGA1UEAxMUQW1hem9uIEVDRFNB\n" + + "IDI1NiBNMDEwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAT80w+2RwNHzyXmVUM/\n" + + "OUKBZpJkTzHyCKDl4sBrUfjzVjot/lNba9kYzMKSHYv95CUDoMaF2h2KAqx65uLQ\n" + + "Y8ago4IBWjCCAVYwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYw\n" + + "HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQWBBRPWfy8BhYo\n" + + "v6LI2wj7zxMkumlCXDAfBgNVHSMEGDAWgBSrttvXBp43rDCGB5Fwx5zEGbF4wDB7\n" + + "BggrBgEFBQcBAQRvMG0wLwYIKwYBBQUHMAGGI2h0dHA6Ly9vY3NwLnJvb3RjYTMu\n" + + "YW1hem9udHJ1c3QuY29tMDoGCCsGAQUFBzAChi5odHRwOi8vY3J0LnJvb3RjYTMu\n" + + "YW1hem9udHJ1c3QuY29tL3Jvb3RjYTMuY2VyMD8GA1UdHwQ4MDYwNKAyoDCGLmh0\n" + + "dHA6Ly9jcmwucm9vdGNhMy5hbWF6b250cnVzdC5jb20vcm9vdGNhMy5jcmwwEwYD\n" + + "VR0gBAwwCjAIBgZngQwBAgEwCgYIKoZIzj0EAwIDSAAwRQIhALRfxq3SQIhj5xA4\n" + + "S5UAY/KlKqayZDpnbBdCDH8Kqmf/AiAUVZddALefnqRe+ifxN2FUp461LL6/cgVM\n" + + "EH3Ty27f1Q==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=valid.rootca3.demo.amazontrust.com + // Issuer: CN=Amazon ECDSA 256 M02, O=Amazon, C=US + // Serial number: 8e2f14864fb28e4a1da0f15a5118cc8 + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + - "MIIDhzCCAy2gAwIBAgITBwPk6bvCYF83lnoOlfMfR4mmdzAKBggqhkjOPQQDAjBG\n" + - "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2ZXIg\n" + - "Q0EgM0ExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTA3MjkyMzU0NDNaFw0yMDA4Mjky\n" + - "MzU0NDNaMIHaMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQIT\n" + - "CERlbGF3YXJlMR0wGwYDVQQPExRQcml2YXRlIE9yZ2FuaXphdGlvbjEQMA4GA1UE\n" + - "BRMHNTg0Njc0MzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAO\n" + - "BgNVBAcTB1NlYXR0bGUxHjAcBgNVBAoTFUFtYXpvbiBUcnVzdCBTZXJ2aWNlczEj\n" + - "MCEGA1UEAxMaZ29vZC5zY2EzYS5hbWF6b250cnVzdC5jb20wWTATBgcqhkjOPQIB\n" + - "BggqhkjOPQMBBwNCAARl4yxf8XcvWR0LZ+YuBC0CpkwtU2NiMdlIM7eX0lxhQp53\n" + - "NpLlCrPRNzOWrjCJDdn21D0u7PrtN94UHLHOg9X0o4IBYzCCAV8wDgYDVR0PAQH/\n" + - "BAQDAgeAMB0GA1UdDgQWBBT2cHmOJFLWfg1Op7xAdAnqYcwaPzAfBgNVHSMEGDAW\n" + - "gBQE3OCV5ei5a5Sh74xbMR4TflWX2jAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB\n" + - "BQUHAwIwdQYIKwYBBQUHAQEEaTBnMC0GCCsGAQUFBzABhiFodHRwOi8vb2NzcC5z\n" + - "Y2EzYS5hbWF6b250cnVzdC5jb20wNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQuc2Nh\n" + - "M2EuYW1hem9udHJ1c3QuY29tL3NjYTNhLmNlcjAlBgNVHREEHjAcghpnb29kLnNj\n" + - "YTNhLmFtYXpvbnRydXN0LmNvbTBQBgNVHSAESTBHMA0GC2CGSAGG/W4BBxgDMDYG\n" + - "BWeBDAEBMC0wKwYIKwYBBQUHAgEWH2h0dHBzOi8vd3d3LmFtYXpvbnRydXN0LmNv\n" + - "bS9jcHMwCgYIKoZIzj0EAwIDSAAwRQIgURdcqJVr4PWNIkmWcSKmzgZ1i94hQpGe\n" + - "mWbE9osk4m0CIQDhxIguihwvDa5RsBwdM0aRDgGKLNHigGqJoKqgH0d2qg==\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=revoked.sca3a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=PrivateOrganization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 3A, O=Amazon, C=US - // Serial number: 6f1d78cf0ca64ce7f551a6f2a0715cc0e8b50 - // Valid from: Mon Jan 28 15:40:01 PST 2019 until: Thu Apr 28 16:40:01 PDT 2022 + "MIIEfjCCBCWgAwIBAgIQCOLxSGT7KOSh2g8VpRGMyDAKBggqhkjOPQQDAjA9MQsw\n" + + "CQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMR0wGwYDVQQDExRBbWF6b24gRUNE\n" + + "U0EgMjU2IE0wMjAeFw0yMzA1MTAwMDAwMDBaFw0yNDA2MDcyMzU5NTlaMC0xKzAp\n" + + "BgNVBAMTInZhbGlkLnJvb3RjYTMuZGVtby5hbWF6b250cnVzdC5jb20wWTATBgcq\n" + + "hkjOPQIBBggqhkjOPQMBBwNCAAQfWc7gBGBBBmseCb2XWWRQVhCUQDVml3mVgvj5\n" + + "RmnP1y5wpifUTFqu8ELdI7YGZ4JMSnetiKNmLtg5yhTEjzCQo4IDFTCCAxEwHwYD\n" + + "VR0jBBgwFoAUu3ia12gzMp0au2z9sTRMAd7L0HUwHQYDVR0OBBYEFHCE8orvZDUK\n" + + "5TI9MYadzxWR9CZGMEkGA1UdEQRCMECCInZhbGlkLnJvb3RjYTMuZGVtby5hbWF6\n" + + "b250cnVzdC5jb22CGmdvb2Quc2NhM2EuYW1hem9udHJ1c3QuY29tMA4GA1UdDwEB\n" + + "/wQEAwIHgDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwOwYDVR0fBDQw\n" + + "MjAwoC6gLIYqaHR0cDovL2NybC5lMm0wMi5hbWF6b250cnVzdC5jb20vZTJtMDIu\n" + + "Y3JsMBMGA1UdIAQMMAowCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAtBggrBgEF\n" + + "BQcwAYYhaHR0cDovL29jc3AuZTJtMDIuYW1hem9udHJ1c3QuY29tMDYGCCsGAQUF\n" + + "BzAChipodHRwOi8vY3J0LmUybTAyLmFtYXpvbnRydXN0LmNvbS9lMm0wMi5jZXIw\n" + + "DAYDVR0TAQH/BAIwADCCAXwGCisGAQQB1nkCBAIEggFsBIIBaAFmAHUA7s3QZNXb\n" + + "Gs7FXLedtM0TojKHRny87N7DUUhZRnEftZsAAAGIB71y/gAABAMARjBEAiAEAXIb\n" + + "aOVR26HgFaI+qoIasCb8w2sOqVxGAxf5iPgX6QIgdAlMjqeoihi1arnJpzN8Bqxy\n" + + "5ULMUO7GK3JEgcogJHMAdgBIsONr2qZHNA/lagL6nTDrHFIBy1bdLIHZu7+rOdiE\n" + + "cwAAAYgHvXLkAAAEAwBHMEUCIF7wDDmWxTHwBZM7Me8eOCM1aQ/g1c1rJg/I+NJa\n" + + "HkZYAiEA8p+IviuY5piHBELjUtVlZLiS9XSSMxpQNhUerqC/YFoAdQDatr9rP7W2\n" + + "Ip+bwrtca+hwkXFsu1GEhTS9pD0wSNf7qwAAAYgHvXKvAAAEAwBGMEQCIFLskZDs\n" + + "UG4+/88D/5/QbD9zT6ZmZlwXiPZ6H2YR/KiJAiBvi4vvNsb9KNAhJMgI2T2iCg9U\n" + + "CIru+US6y3ua7dKKDTAKBggqhkjOPQQDAgNHADBEAiAzvgzKV/kvBbKWCT1NNUBD\n" + + "AF9okIEcJx/ukFgzmYMwUQIgXeJeVf3izkxsgiEUSknwHsErLFs/cEme2PSRj2AW\n" + + "dYA=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=revoked.rootca3.demo.amazontrust.com + // Issuer: CN=Amazon ECDSA 256 M01, O=Amazon, C=US + // Serial number: c458bfaeedae16a5e61fe64773fc898 + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + - "MIIDTzCCAvWgAwIBAgITBvHXjPDKZM5/VRpvKgcVzA6LUDAKBggqhkjOPQQDAjBG\n" + - "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2ZXIg\n" + - "Q0EgM0ExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTAxMjgyMzQwMDFaFw0yMjA0Mjgy\n" + - "MzQwMDFaMIHcMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQIT\n" + - "CERlbGF3YXJlMRwwGgYDVQQPExNQcml2YXRlT3JnYW5pemF0aW9uMRAwDgYDVQQF\n" + - "Ewc1ODQ2NzQzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G\n" + - "A1UEBxMHU2VhdHRsZTEeMBwGA1UEChMVQW1hem9uIFRydXN0IFNlcnZpY2VzMSYw\n" + - "JAYDVQQDEx1yZXZva2VkLnNjYTNhLmFtYXpvbnRydXN0LmNvbTBZMBMGByqGSM49\n" + - "AgEGCCqGSM49AwEHA0IABJNl90Jq0wddpFj+JbLtmvGR/1geL5t1tvV406jGpYn2\n" + - "C5lAFjwASFy7pAnazZbfSkIDUU2i2XU0+7Cs+j1S/EOjggEpMIIBJTAOBgNVHQ8B\n" + - "Af8EBAMCB4AwHQYDVR0OBBYEFPhX3dYays5Sps0xTgouLkZzYLg4MB8GA1UdIwQY\n" + - "MBaAFATc4JXl6LlrlKHvjFsxHhN+VZfaMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggr\n" + - "BgEFBQcDAjB1BggrBgEFBQcBAQRpMGcwLQYIKwYBBQUHMAGGIWh0dHA6Ly9vY3Nw\n" + - "LnNjYTNhLmFtYXpvbnRydXN0LmNvbTA2BggrBgEFBQcwAoYqaHR0cDovL2NydC5z\n" + - "Y2EzYS5hbWF6b250cnVzdC5jb20vc2NhM2EuY2VyMCgGA1UdEQQhMB+CHXJldm9r\n" + - "ZWQuc2NhM2EuYW1hem9udHJ1c3QuY29tMBMGA1UdIAQMMAowCAYGZ4EMAQIBMAoG\n" + - "CCqGSM49BAMCA0gAMEUCICLb16/50S4fOAFafi5lagdx7q6EDPPm596g19eQDMXk\n" + - "AiEAksCMLypRB4t30FABlsEjhVCBIxay0iIer2OcCIrhfEI=\n" + - "-----END CERTIFICATE-----"; - - public void runTest(ValidatePathWithParams pathValidator, boolean ocspEnabled) throws Exception { - // EE certificates don't have CRLDP extension - if (!ocspEnabled){ - pathValidator.validate(new String[]{INT}, - ValidatePathWithParams.Status.GOOD, null, System.out); + "MIIEhzCCBC2gAwIBAgIQDEWL+u7a4WpeYf5kdz/ImDAKBggqhkjOPQQDAjA9MQsw\n" + + "CQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMR0wGwYDVQQDExRBbWF6b24gRUNE\n" + + "U0EgMjU2IE0wMTAeFw0yMzA1MTAwMDAwMDBaFw0yNDA2MDcyMzU5NTlaMC8xLTAr\n" + + "BgNVBAMTJHJldm9rZWQucm9vdGNhMy5kZW1vLmFtYXpvbnRydXN0LmNvbTBZMBMG\n" + + "ByqGSM49AgEGCCqGSM49AwEHA0IABAsSs5kW5TZlS0SDrMb9iUQAqEaKa12Fc6SN\n" + + "9UR6qtOFdW/1UuziDq3Hl5dqsAYZJkbJSPCIsD2HTP/EGTMKITCjggMbMIIDFzAf\n" + + "BgNVHSMEGDAWgBRPWfy8BhYov6LI2wj7zxMkumlCXDAdBgNVHQ4EFgQUeE55ET2e\n" + + "i8KbY7KHTxOuvCkRpTowTgYDVR0RBEcwRYIkcmV2b2tlZC5yb290Y2EzLmRlbW8u\n" + + "YW1hem9udHJ1c3QuY29tgh1yZXZva2VkLnNjYTNhLmFtYXpvbnRydXN0LmNvbTAO\n" + + "BgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMDsG\n" + + "A1UdHwQ0MDIwMKAuoCyGKmh0dHA6Ly9jcmwuZTJtMDEuYW1hem9udHJ1c3QuY29t\n" + + "L2UybTAxLmNybDATBgNVHSAEDDAKMAgGBmeBDAECATB1BggrBgEFBQcBAQRpMGcw\n" + + "LQYIKwYBBQUHMAGGIWh0dHA6Ly9vY3NwLmUybTAxLmFtYXpvbnRydXN0LmNvbTA2\n" + + "BggrBgEFBQcwAoYqaHR0cDovL2NydC5lMm0wMS5hbWF6b250cnVzdC5jb20vZTJt\n" + + "MDEuY2VyMAwGA1UdEwEB/wQCMAAwggF9BgorBgEEAdZ5AgQCBIIBbQSCAWkBZwB2\n" + + "AHb/iD8KtvuVUcJhzPWHujS0pM27KdxoQgqf5mdMWjp0AAABiAe9lQ8AAAQDAEcw\n" + + "RQIgZVFAX5WPZRBpEOqk620v4Rbzxh/3wrJ5QBMBJ0Mb8B0CIQC0oxFVLfs+PAv7\n" + + "25wawOu2VgDXG9lJAJtCwk3gN8BshQB2AEiw42vapkc0D+VqAvqdMOscUgHLVt0s\n" + + "gdm7v6s52IRzAAABiAe9lQ4AAAQDAEcwRQIhAIPVMj6IfjAUKeGYbpG9s0DRdWbc\n" + + "b8OzsOf+kRqk03NMAiB777hfoFCUMPrN0g8o5v6zp3T3qOhRnYY0TZN4q4NnMgB1\n" + + "ANq2v2s/tbYin5vCu1xr6HCRcWy7UYSFNL2kPTBI1/urAAABiAe9lN4AAAQDAEYw\n" + + "RAIgL0qoVbKLFD+Y3f/V6Rw+euZrPO6d1HEVPQGo7wLzkl8CIGHp3PQmmrEofl76\n" + + "4da7bY0L+csFW0sB8clN0KziMfe6MAoGCCqGSM49BAMCA0gAMEUCIQC+6VdX9X5g\n" + + "x3NSUmJ7py01Zxf26TNBv1ildxqesvZ/7wIgIrefriRzPiIFDHCUbdjk0VlmMwZR\n" + + "VzXXHINsGCiCKOs=\n" + + "-----END CERTIFICATE-----"; - return; - } + public void runTest(ValidatePathWithParams pathValidator) throws Exception { // Validate valid - pathValidator.validate(new String[]{VALID, INT}, + pathValidator.validate(new String[]{VALID, INT_VALID}, ValidatePathWithParams.Status.GOOD, null, System.out); // Validate Revoked - pathValidator.validate(new String[]{REVOKED, INT}, + pathValidator.validate(new String[]{REVOKED, INT_REVOKED}, ValidatePathWithParams.Status.REVOKED, - "Mon Jan 28 15:40:35 PST 2019", System.out); + "Mon May 15 13:41:22 PDT 2023", System.out); } } class AmazonCA_4 { - // Owner: CN=Amazon, OU=Server CA 4A, O=Amazon, C=US + // Owner: CN=Amazon ECDSA 384 M02, O=Amazon, C=US // Issuer: CN=Amazon Root CA 4, O=Amazon, C=US - // Serial number: 67f94575a8862a9072e3239c37ceba1274e18 - // Valid from: Wed Oct 21 17:00:00 PDT 2015 until: Sat Oct 18 17:00:00 PDT 2025 + // Serial number: 773127dfaa6b9e2b95538aa76dde4307f17c4 + // Valid from: Tue Aug 23 15:36:58 PDT 2022 until: Fri Aug 23 15:36:58 PDT 2030 private static final String INT = "-----BEGIN CERTIFICATE-----\n" + - "MIIC+TCCAn6gAwIBAgITBn+UV1qIYqkHLjI5w3zroSdOGDAKBggqhkjOPQQDAzA5\n" + + "MIIDETCCApagAwIBAgITB3MSffqmueK5VTiqdt3kMH8XxDAKBggqhkjOPQQDAzA5\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\n" + - "Um9vdCBDQSA0MB4XDTE1MTAyMjAwMDAwMFoXDTI1MTAxOTAwMDAwMFowRjELMAkG\n" + - "A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENBIDRB\n" + - "MQ8wDQYDVQQDEwZBbWF6b24wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASRP0kIW0Ha\n" + - "7+ORvEVhIS5gIgkH66X5W9vBRTX14oG/1elIyI6LbFZ+E5KAufL0XoWJGI1WbPRm\n" + - "HW246FKSzF0wOEZZyxEROz6tuaVsnXRHRE76roS/Wr064uJpKH+Lv+SjggE5MIIB\n" + - "NTASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU\n" + - "pSHN2+tTIZmqytlnQpQlsnv0wuMwHwYDVR0jBBgwFoAU0+zHOmVuzOHadppW+5zz\n" + - "hm1X5YEwewYIKwYBBQUHAQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5y\n" + - "b290Y2E0LmFtYXpvbnRydXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDovL2NydC5y\n" + - "b290Y2E0LmFtYXpvbnRydXN0LmNvbS9yb290Y2E0LmNlcjA/BgNVHR8EODA2MDSg\n" + - "MqAwhi5odHRwOi8vY3JsLnJvb3RjYTQuYW1hem9udHJ1c3QuY29tL3Jvb3RjYTQu\n" + - "Y3JsMBEGA1UdIAQKMAgwBgYEVR0gADAKBggqhkjOPQQDAwNpADBmAjEA59RAOBaj\n" + - "uh0rT/OOTWPEv6TBnb9XEadburBaXb8SSrR8il+NdkfS9WXRAzbwrG7LAjEA3ukD\n" + - "1HrQq+WXHBM5sIuViJI/Zh7MOjsc159Q+dn36PBqLRq03AXqE/lRjnv8C5nj\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=good.sca4a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 4A, O=Amazon, C=US - // Serial number: 703e4ec57c72d5669efbc98875c3f6bc3f934 - // Valid from: Mon Jul 29 16:55:17 PDT 2019 until: Sat Aug 29 16:55:17 PDT 2020 + "Um9vdCBDQSA0MB4XDTIyMDgyMzIyMzY1OFoXDTMwMDgyMzIyMzY1OFowPTELMAkG\n" + + "A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEdMBsGA1UEAxMUQW1hem9uIEVDRFNB\n" + + "IDM4NCBNMDIwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATNYzWQDXV0NoNmR0hJPwJq\n" + + "hjYOOS9z0B2Z7MQudxg5x3Vsib6N+tJkq8dljRq5o6K0bbh/kRVfoi9wfKhB03Yz\n" + + "gkerrwRCH7Z9gU5nbBY+Y5+EtImq4yOB0n7JQgQxWemjggFaMIIBVjASBgNVHRMB\n" + + "Af8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcD\n" + + "AQYIKwYBBQUHAwIwHQYDVR0OBBYEFKbZqzuHmTP/6Gj4i2GDbNCyuq+9MB8GA1Ud\n" + + "IwQYMBaAFNPsxzplbszh2naaVvuc84ZtV+WBMHsGCCsGAQUFBwEBBG8wbTAvBggr\n" + + "BgEFBQcwAYYjaHR0cDovL29jc3Aucm9vdGNhNC5hbWF6b250cnVzdC5jb20wOgYI\n" + + "KwYBBQUHMAKGLmh0dHA6Ly9jcnQucm9vdGNhNC5hbWF6b250cnVzdC5jb20vcm9v\n" + + "dGNhNC5jZXIwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC5yb290Y2E0LmFt\n" + + "YXpvbnRydXN0LmNvbS9yb290Y2E0LmNybDATBgNVHSAEDDAKMAgGBmeBDAECATAK\n" + + "BggqhkjOPQQDAwNpADBmAjEA2zCG6x0xMlgSXWEGLN8+1XN+OCYF5vj0Z1jtVy+A\n" + + "pdLlzuxNt9HBWn3hvqvO2W8KAjEApNdsZOCmk5uZBYiuCSBnDH3jyKhN6dWyuuHW\n" + + "9Wj7SxKnOU5+wYWZA0BQAv1KT62i\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=valid.rootca4.demo.amazontrust.com + // Issuer: CN=Amazon ECDSA 384 M02, O=Amazon, C=US + // Serial number: f579bed3369f1a147ea5d0e8e6532d3 + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + - "MIIDxTCCA0qgAwIBAgITBwPk7FfHLVZp77yYh1w/a8P5NDAKBggqhkjOPQQDAzBG\n" + - "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2ZXIg\n" + - "Q0EgNEExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTA3MjkyMzU1MTdaFw0yMDA4Mjky\n" + - "MzU1MTdaMIHaMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQIT\n" + - "CERlbGF3YXJlMR0wGwYDVQQPExRQcml2YXRlIE9yZ2FuaXphdGlvbjEQMA4GA1UE\n" + - "BRMHNTg0Njc0MzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAO\n" + - "BgNVBAcTB1NlYXR0bGUxHjAcBgNVBAoTFUFtYXpvbiBUcnVzdCBTZXJ2aWNlczEj\n" + - "MCEGA1UEAxMaZ29vZC5zY2E0YS5hbWF6b250cnVzdC5jb20wdjAQBgcqhkjOPQIB\n" + - "BgUrgQQAIgNiAAS9fqMYfOBsdXMSsPjqOlTgIGOlOQWA7Wg6XwVvHTr0+UN+XTeC\n" + - "yZN+XjLbEDQ0CF5eryRZ535sDpwh3qNe0lYFO1n1+2iDtDI1jhhLNYNxBpVnR2BU\n" + - "2l9EuRmgRbQpDCajggFjMIIBXzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFMd0\n" + - "itH5IcE6DpM1uTSBV/6DLmK7MB8GA1UdIwQYMBaAFKUhzdvrUyGZqsrZZ0KUJbJ7\n" + - "9MLjMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjB1BggrBgEFBQcBAQRp\n" + - "MGcwLQYIKwYBBQUHMAGGIWh0dHA6Ly9vY3NwLnNjYTRhLmFtYXpvbnRydXN0LmNv\n" + - "bTA2BggrBgEFBQcwAoYqaHR0cDovL2NydC5zY2E0YS5hbWF6b250cnVzdC5jb20v\n" + - "c2NhNGEuY2VyMCUGA1UdEQQeMByCGmdvb2Quc2NhNGEuYW1hem9udHJ1c3QuY29t\n" + - "MFAGA1UdIARJMEcwDQYLYIZIAYb9bgEHGAMwNgYFZ4EMAQEwLTArBggrBgEFBQcC\n" + - "ARYfaHR0cHM6Ly93d3cuYW1hem9udHJ1c3QuY29tL2NwczAKBggqhkjOPQQDAwNp\n" + - "ADBmAjEA2RBD1F+rnm394VkqA3ncysM3deoyfWqaoAO5923MNisswPnHfVqnfeXf\n" + - "ZwTAvVTBAjEAiiaPx9GRjEk8IBKvCSbTp9rPogVTN7zDDQGrwA83O0pRP7A0dxtT\n" + - "pn/0K5Sj8otp\n" + - "-----END CERTIFICATE-----"; - - // Owner: CN=revoked.sca4a.amazontrust.com, O=Amazon Trust Services, L=Seattle, ST=Washington, C=US, \ - // SERIALNUMBER=5846743, OID.2.5.4.15=PrivateOrganization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, \ - // OID.1.3.6.1.4.1.311.60.2.1.3=US - // Issuer: CN=Amazon, OU=Server CA 4A, O=Amazon, C=US - // Serial number: 6f1d79295c384a699d51c2d756bd46213b5b3 - // Valid from: Mon Jan 28 15:41:16 PST 2019 until: Thu Apr 28 16:41:16 PDT 2022 + "MIIEvjCCBESgAwIBAgIQD1eb7TNp8aFH6l0OjmUy0zAKBggqhkjOPQQDAzA9MQsw\n" + + "CQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMR0wGwYDVQQDExRBbWF6b24gRUNE\n" + + "U0EgMzg0IE0wMjAeFw0yMzA1MTAwMDAwMDBaFw0yNDA2MDcyMzU5NTlaMC0xKzAp\n" + + "BgNVBAMTInZhbGlkLnJvb3RjYTQuZGVtby5hbWF6b250cnVzdC5jb20wdjAQBgcq\n" + + "hkjOPQIBBgUrgQQAIgNiAAT6/95JFuvx5t9MVeRZmBtXq63Q2fXZnSwEy2U2F4Qc\n" + + "ejhDwcYfD2HmT6S6GrKqLNJMa5n2YOvet4LZpKJLFF+BQo6FJt5cXkzHHxZ1I4z3\n" + + "8pGU79CpCgFOFy6QUlF68NajggMXMIIDEzAfBgNVHSMEGDAWgBSm2as7h5kz/+ho\n" + + "+Ithg2zQsrqvvTAdBgNVHQ4EFgQUR/GnpQkrUsCj8jF6/JIE1Rs07zswSQYDVR0R\n" + + "BEIwQIIidmFsaWQucm9vdGNhNC5kZW1vLmFtYXpvbnRydXN0LmNvbYIaZ29vZC5z\n" + + "Y2E0YS5hbWF6b250cnVzdC5jb20wDgYDVR0PAQH/BAQDAgeAMB0GA1UdJQQWMBQG\n" + + "CCsGAQUFBwMBBggrBgEFBQcDAjA7BgNVHR8ENDAyMDCgLqAshipodHRwOi8vY3Js\n" + + "LmUzbTAyLmFtYXpvbnRydXN0LmNvbS9lM20wMi5jcmwwEwYDVR0gBAwwCjAIBgZn\n" + + "gQwBAgEwdQYIKwYBBQUHAQEEaTBnMC0GCCsGAQUFBzABhiFodHRwOi8vb2NzcC5l\n" + + "M20wMi5hbWF6b250cnVzdC5jb20wNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQuZTNt\n" + + "MDIuYW1hem9udHJ1c3QuY29tL2UzbTAyLmNlcjAMBgNVHRMBAf8EAjAAMIIBfgYK\n" + + "KwYBBAHWeQIEAgSCAW4EggFqAWgAdgDuzdBk1dsazsVct520zROiModGfLzs3sNR\n" + + "SFlGcR+1mwAAAYgHvZA9AAAEAwBHMEUCIQCmzmQOzunsuAg1GpIcNx0isG6ylbhP\n" + + "y9JP4UFclL2hdwIgBtTM89mE7QJDj7h7xr2eRPio1ehgmeYH1PHXxCqHIGYAdgBI\n" + + "sONr2qZHNA/lagL6nTDrHFIBy1bdLIHZu7+rOdiEcwAAAYgHvZB1AAAEAwBHMEUC\n" + + "IF9hbi82CLU5umfRze4NpX6u4jlT+N8KSaBe6UbhqjBZAiEAi2Y6PTt2+107LxtM\n" + + "oBpHprph7hQvGfjPE+p+rfM/X+EAdgDatr9rP7W2Ip+bwrtca+hwkXFsu1GEhTS9\n" + + "pD0wSNf7qwAAAYgHvZBeAAAEAwBHMEUCIAI+m4mVE3HtZOEMC5VI7m0nEPdPPJUq\n" + + "fxUKPpeIVmk5AiEA0scVJy7g3Fv+2nTVhbcwWCwn/Gvc+0txQrc529juflcwCgYI\n" + + "KoZIzj0EAwMDaAAwZQIxAKV837BpqlNHg35EsCCtrJPoQ6RuY9UoHm1O2CdsCXGR\n" + + "Z3kAnlgIV8A/waI6wQqfsQIwdCqaC+qN60JCnX09YKRD15eQjq1rN3w+llI+lEbS\n" + + "FSMsnoHJcqMZLo9s+4Rf0zS3\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=revoked.rootca4.demo.amazontrust.com + // Issuer: CN=Amazon ECDSA 384 M02, O=Amazon, C=US + // Serial number: 4a5d392936b4decb818b7fb106ebbd8 + // Valid from: Tue May 09 17:00:00 PDT 2023 until: Fri Jun 07 16:59:59 PDT 2024 private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + - "MIIDjTCCAxKgAwIBAgITBvHXkpXDhKaZ1RwtdWvUYhO1szAKBggqhkjOPQQDAzBG\n" + - "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRUwEwYDVQQLEwxTZXJ2ZXIg\n" + - "Q0EgNEExDzANBgNVBAMTBkFtYXpvbjAeFw0xOTAxMjgyMzQxMTZaFw0yMjA0Mjgy\n" + - "MzQxMTZaMIHcMRMwEQYLKwYBBAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQIT\n" + - "CERlbGF3YXJlMRwwGgYDVQQPExNQcml2YXRlT3JnYW5pemF0aW9uMRAwDgYDVQQF\n" + - "Ewc1ODQ2NzQzMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G\n" + - "A1UEBxMHU2VhdHRsZTEeMBwGA1UEChMVQW1hem9uIFRydXN0IFNlcnZpY2VzMSYw\n" + - "JAYDVQQDEx1yZXZva2VkLnNjYTRhLmFtYXpvbnRydXN0LmNvbTB2MBAGByqGSM49\n" + - "AgEGBSuBBAAiA2IABLuNpZTcNU3FElNP3Y/OeXIZcIMXkFTBi/n92fNwHfqUbEhH\n" + - "H+PovJ26eAGvb5a8bGc275MBFcVnWL0rCVgM+j9KAtBDCRJX3f7mo0D2VKcmtZKu\n" + - "jPxwGPy2kuqM505dGqOCASkwggElMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQU\n" + - "zUFIhn+hphzCKA2qgAdLztSBzJgwHwYDVR0jBBgwFoAUpSHN2+tTIZmqytlnQpQl\n" + - "snv0wuMwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMHUGCCsGAQUFBwEB\n" + - "BGkwZzAtBggrBgEFBQcwAYYhaHR0cDovL29jc3Auc2NhNGEuYW1hem9udHJ1c3Qu\n" + - "Y29tMDYGCCsGAQUFBzAChipodHRwOi8vY3J0LnNjYTRhLmFtYXpvbnRydXN0LmNv\n" + - "bS9zY2E0YS5jZXIwKAYDVR0RBCEwH4IdcmV2b2tlZC5zY2E0YS5hbWF6b250cnVz\n" + - "dC5jb20wEwYDVR0gBAwwCjAIBgZngQwBAgEwCgYIKoZIzj0EAwMDaQAwZgIxALDA\n" + - "klY3iKwyzwpwVtLfLxzQEl45xvE2VjBJvfJJ60KhJt7Ud0gt0zxkogh29+mpEQIx\n" + - "ANTG1mk8OJB41DU7ru1Pwc6ju8STw1FdwDp/Eliqhvnm2i0k4/F1bBHLta2mlC2V\n" + - "hg==\n" + - "-----END CERTIFICATE-----"; - - public void runTest(ValidatePathWithParams pathValidator, boolean ocspEnabled) throws Exception { - // EE certificates don't have CRLDP extension - if (!ocspEnabled){ - pathValidator.validate(new String[]{INT}, - ValidatePathWithParams.Status.GOOD, null, System.out); + "MIIExjCCBEygAwIBAgIQBKXTkpNrTey4GLf7EG672DAKBggqhkjOPQQDAzA9MQsw\n" + + "CQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMR0wGwYDVQQDExRBbWF6b24gRUNE\n" + + "U0EgMzg0IE0wMjAeFw0yMzA1MTAwMDAwMDBaFw0yNDA2MDcyMzU5NTlaMC8xLTAr\n" + + "BgNVBAMTJHJldm9rZWQucm9vdGNhNC5kZW1vLmFtYXpvbnRydXN0LmNvbTB2MBAG\n" + + "ByqGSM49AgEGBSuBBAAiA2IABFYfMbv5/vgqDunZj4ffJiuELtdwfEPXx9QlZnCm\n" + + "rBP3Z4/GvUVRVmyh5sYdnbCGCEClH/RxU6BC5SKv+TzhsFLEumhezanljnQXRAIL\n" + + "a1OGbP8zLLP6FuAD0cjY3P3adKOCAx0wggMZMB8GA1UdIwQYMBaAFKbZqzuHmTP/\n" + + "6Gj4i2GDbNCyuq+9MB0GA1UdDgQWBBSqnGV5pN/agPCtVdV37CP1z/DUqjBOBgNV\n" + + "HREERzBFgiRyZXZva2VkLnJvb3RjYTQuZGVtby5hbWF6b250cnVzdC5jb22CHXJl\n" + + "dm9rZWQuc2NhNGEuYW1hem9udHJ1c3QuY29tMA4GA1UdDwEB/wQEAwIHgDAdBgNV\n" + + "HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwOwYDVR0fBDQwMjAwoC6gLIYqaHR0\n" + + "cDovL2NybC5lM20wMi5hbWF6b250cnVzdC5jb20vZTNtMDIuY3JsMBMGA1UdIAQM\n" + + "MAowCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAtBggrBgEFBQcwAYYhaHR0cDov\n" + + "L29jc3AuZTNtMDIuYW1hem9udHJ1c3QuY29tMDYGCCsGAQUFBzAChipodHRwOi8v\n" + + "Y3J0LmUzbTAyLmFtYXpvbnRydXN0LmNvbS9lM20wMi5jZXIwDAYDVR0TAQH/BAIw\n" + + "ADCCAX8GCisGAQQB1nkCBAIEggFvBIIBawFpAHYAdv+IPwq2+5VRwmHM9Ye6NLSk\n" + + "zbsp3GhCCp/mZ0xaOnQAAAGIB72QJQAABAMARzBFAiA74zKrlL+y5rYwSLxBL8fs\n" + + "QYRYXF0s0sGoaSEeAg1DkgIhAPu8Z0TLIFoppmyiv+A5z6S+SG+v/kOsAYmQmiUO\n" + + "5scIAHcASLDja9qmRzQP5WoC+p0w6xxSActW3SyB2bu/qznYhHMAAAGIB72QJgAA\n" + + "BAMASDBGAiEAg+x7JBT3oIaZdnfgGN1G6SAiNUL7zR/tBhbWIG9tz94CIQDGwBiV\n" + + "Tslt11+W3ZaNsS7UtUIiB45YHUc4qKm5ry2fTAB2ANq2v2s/tbYin5vCu1xr6HCR\n" + + "cWy7UYSFNL2kPTBI1/urAAABiAe9kAgAAAQDAEcwRQIgPvKfSpMJKRocGk9+GNr3\n" + + "hUj8x8WySB//0X116TNgA0gCIQDhGRqxnEZmEFGEfj5GY9vjEfm0kKwcL0lCuwBu\n" + + "NZG4dzAKBggqhkjOPQQDAwNoADBlAjEA1PLdsrko3tDs50aAeEU9Gn+0CG8QKy7R\n" + + "fQaXBTjGETDgGJk/7zGNpGelKPr/UYV9AjASwdA32S8jIADxA8HrqiMsVYDFMnbU\n" + + "jLLwR6CTLtAcWtwVmoQ2x0usvTvN8YJBPoA=\n" + + "-----END CERTIFICATE-----"; - return; - } + public void runTest(ValidatePathWithParams pathValidator) throws Exception { // Validate valid pathValidator.validate(new String[]{VALID, INT}, @@ -547,6 +608,6 @@ // Validate Revoked pathValidator.validate(new String[]{REVOKED, INT}, ValidatePathWithParams.Status.REVOKED, - "Mon Jan 28 15:41:53 PST 2019", System.out); + "Mon May 15 13:42:48 PDT 2023", System.out); } } diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/DigicertCSRootG5.java openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/DigicertCSRootG5.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/DigicertCSRootG5.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/DigicertCSRootG5.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8318759 + * @summary Interoperability tests with Digicert CS Root G5 certificates + * @build ValidatePathWithParams + * @run main/othervm -Djava.security.debug=ocsp,certpath DigicertCSRootG5 OCSP + * @run main/othervm -Djava.security.debug=certpath DigicertCSRootG5 CRL + */ + +public class DigicertCSRootG5 { + + public static void main(String[] args) throws Exception { + + ValidatePathWithParams pathValidator = new ValidatePathWithParams(null); + + if (args.length >= 1 && "CRL".equalsIgnoreCase(args[0])) { + pathValidator.enableCRLCheck(); + } else { + // OCSP check by default + pathValidator.enableOCSPCheck(); + } + + new Digicert_CS_ECC().runTest(pathValidator); + new Digicert_CS_RSA().runTest(pathValidator); + } +} + +class Digicert_CS_ECC { + + // Owner: CN=DigiCert G5 CS ECC SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Issuer: CN=DigiCert CS ECC P384 Root G5, O="DigiCert, Inc.", C=US + // Serial number: d926818addd3c47758f0ace9379b2e7 + // Valid from: Wed Feb 10 16:00:00 PST 2021 until: Sun Feb 10 15:59:59 PST 2036 + private static final String INT = "-----BEGIN CERTIFICATE-----\n" + + "MIIDOTCCAsCgAwIBAgIQDZJoGK3dPEd1jwrOk3my5zAKBggqhkjOPQQDAzBNMQsw\n" + + "CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMTHERp\n" + + "Z2lDZXJ0IENTIEVDQyBQMzg0IFJvb3QgRzUwHhcNMjEwMjExMDAwMDAwWhcNMzYw\n" + + "MjEwMjM1OTU5WjBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIElu\n" + + "Yy4xKzApBgNVBAMTIkRpZ2lDZXJ0IEc1IENTIEVDQyBTSEEzODQgMjAyMSBDQTEw\n" + + "djAQBgcqhkjOPQIBBgUrgQQAIgNiAAS/zvKH4sLLu/zze3/+vHyfRE5OcO77TNw3\n" + + "MCMAlad2Y/ja50KTooGSmXhfwMXpbBTob7hsoxpvIU92W6DhFn9lg4pcKf5UHLEi\n" + + "0iDdHQ9w0hpFJiMABwK60nk+OwsGTZSjggFdMIIBWTASBgNVHRMBAf8ECDAGAQH/\n" + + "AgEAMB0GA1UdDgQWBBTXHcf6xvqCdCBFcTQSL1XVmEGSXjAfBgNVHSMEGDAWgBTw\n" + + "jJhxOThlwjobphdmHcjtZd6SNjAOBgNVHQ8BAf8EBAMCAYYwEwYDVR0lBAwwCgYI\n" + + "KwYBBQUHAwMweQYIKwYBBQUHAQEEbTBrMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz\n" + + "cC5kaWdpY2VydC5jb20wQwYIKwYBBQUHMAKGN2h0dHA6Ly9jYWNlcnRzLmRpZ2lj\n" + + "ZXJ0LmNvbS9EaWdpQ2VydENTRUNDUDM4NFJvb3RHNS5jcnQwRQYDVR0fBD4wPDA6\n" + + "oDigNoY0aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0Q1NFQ0NQMzg0\n" + + "Um9vdEc1LmNybDAcBgNVHSAEFTATMAcGBWeBDAEDMAgGBmeBDAEEATAKBggqhkjO\n" + + "PQQDAwNnADBkAjByCWijRCnJogZf94U5HG/5S4QFMxEOBSAyxECbFxgrXMKXh5qa\n" + + "7oS2F+hT2DPzxTwCMCIthK0X/14bxZvrNNiNSWzer2TDUyRw6HNIfnkHgqaGFQVA\n" + + "KyS5I77prv53stK0XQ==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN="Win The Customer, LLC", O="Win The Customer, LLC", L=Saratoga + // Springs, ST=Utah, C=US, SERIALNUMBER=9637546-0160, OID.2.5.4.15=Private + // Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Utah, OID.1.3.6.1.4.1.311.60.2.1.3=US + // Issuer: CN=DigiCert G5 CS ECC SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Serial number: b13737c3caf58eecb4359f441522133 + // Valid from: Wed Jan 25 16:00:00 PST 2023 until: Tue Jan 28 15:59:59 PST 2025 + private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIEEjCCA5mgAwIBAgIQCxNzfDyvWO7LQ1n0QVIhMzAKBggqhkjOPQQDAzBTMQsw\n" + + "CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xKzApBgNVBAMTIkRp\n" + + "Z2lDZXJ0IEc1IENTIEVDQyBTSEEzODQgMjAyMSBDQTEwHhcNMjMwMTI2MDAwMDAw\n" + + "WhcNMjUwMTI4MjM1OTU5WjCB2TETMBEGCysGAQQBgjc8AgEDEwJVUzEVMBMGCysG\n" + + "AQQBgjc8AgECEwRVdGFoMR0wGwYDVQQPDBRQcml2YXRlIE9yZ2FuaXphdGlvbjEV\n" + + "MBMGA1UEBRMMOTYzNzU0Ni0wMTYwMQswCQYDVQQGEwJVUzENMAsGA1UECBMEVXRh\n" + + "aDEZMBcGA1UEBxMQU2FyYXRvZ2EgU3ByaW5nczEeMBwGA1UEChMVV2luIFRoZSBD\n" + + "dXN0b21lciwgTExDMR4wHAYDVQQDExVXaW4gVGhlIEN1c3RvbWVyLCBMTEMwWTAT\n" + + "BgcqhkjOPQIBBggqhkjOPQMBBwNCAASyShgaH44RcHazlEEMpwRKY4YebnygI9hG\n" + + "wTMQE/VFG40k3tR8lnyjgxTzZbC0aCVavdv1eglDGejQ+6iD8nzgo4IBxjCCAcIw\n" + + "HwYDVR0jBBgwFoAU1x3H+sb6gnQgRXE0Ei9V1ZhBkl4wHQYDVR0OBBYEFLGgEWb9\n" + + "GF89JoXyan/FD/auNIVVMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEF\n" + + "BQcDAzCBjQYDVR0fBIGFMIGCMD+gPaA7hjlodHRwOi8vY3JsMy5kaWdpY2VydC5j\n" + + "b20vRGlnaUNlcnRHNUNTRUNDU0hBMzg0MjAyMUNBMS5jcmwwP6A9oDuGOWh0dHA6\n" + + "Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEc1Q1NFQ0NTSEEzODQyMDIxQ0Ex\n" + + "LmNybDA9BgNVHSAENjA0MDIGBWeBDAEDMCkwJwYIKwYBBQUHAgEWG2h0dHA6Ly93\n" + + "d3cuZGlnaWNlcnQuY29tL0NQUzB+BggrBgEFBQcBAQRyMHAwJAYIKwYBBQUHMAGG\n" + + "GGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBIBggrBgEFBQcwAoY8aHR0cDovL2Nh\n" + + "Y2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0RzVDU0VDQ1NIQTM4NDIwMjFDQTEu\n" + + "Y3J0MAwGA1UdEwEB/wQCMAAwCgYIKoZIzj0EAwMDZwAwZAIwLkWJc/eLxftorFCv\n" + + "ocOA1dfUFx7Al18d5Xsgpkx47kj2DWgQU+/bQEbbyPrKzYgCAjAP5ErLauJRC2to\n" + + "pPk/yXZYXsusmWVH7ozl9O5WR7+a3gVQ1zwVFWuqdjbq3zWWqJM=\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=Win the Customer LLC, O=Win the Customer LLC, L=Saratoga Springs, ST=Utah, C=US + // Issuer: CN=DigiCert G5 CS ECC SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Serial number: 201e51cb1ec8a56a1e8438c95adf024 + // Valid from: Sun Oct 22 17:00:00 PDT 2023 until: Tue Oct 22 16:59:59 PDT 2024 + private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIFdjCCBP2gAwIBAgIQAgHlHLHsilah6EOMla3wJDAKBggqhkjOPQQDAzBTMQsw\n" + + "CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xKzApBgNVBAMTIkRp\n" + + "Z2lDZXJ0IEc1IENTIEVDQyBTSEEzODQgMjAyMSBDQTEwHhcNMjMxMDIzMDAwMDAw\n" + + "WhcNMjQxMDIyMjM1OTU5WjB1MQswCQYDVQQGEwJVUzENMAsGA1UECBMEVXRhaDEZ\n" + + "MBcGA1UEBxMQU2FyYXRvZ2EgU3ByaW5nczEdMBsGA1UEChMUV2luIHRoZSBDdXN0\n" + + "b21lciBMTEMxHTAbBgNVBAMTFFdpbiB0aGUgQ3VzdG9tZXIgTExDMIICIjANBgkq\n" + + "hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0o+FWNSfYzJmz+XgA7SRAIQd1H1pYnzq\n" + + "dPyNJJsd1G/nqfeHk/ezEx8Wd7iMJjcPOvKSd14uniAC3ayi3XOKKeFqEw5g5m2/\n" + + "JTO3n8xy9DK5CN1ctpK5Zy+UppOXrtTdBZB74/qSaREOysIfRLnVR4fxNy39urtl\n" + + "TJf0lvzRU9V6BQ3zRjMOCQnY6sueAPoQpVgpCVXkr4obJCkI5arkIQHVpfrcScaJ\n" + + "IzLQ46xL8nxoXPcGhikRystJKdbzg/oCFt68x87uSviZMtkqTHQhzRCzpO5pdx/z\n" + + "g64XZP8fAzSrM/uJCETXxMmazK6ZVkgPu3X4GvjfTfulvcJdxZNMm877NOSICtbL\n" + + "dKoBpvIeKtuyxrvmoJUfNw4e+LLbAQOFznVy7UxkTzG1INPgd57zu3Sm3ALq/oJZ\n" + + "oKfheM4zo8UevYMKmoki+N+qMHcJplPF8C04/u8CNc1Jk8tKmjgof8ZsGbQCC2+l\n" + + "NKXzTUnPpza4mHBMU3Qdd4iV8oxd/9jQyE71h11ISakWSresbCyC6HSOVUh409A1\n" + + "Mhv9+aEbqBNhAHJIYrQSY1hb98CKLRS6cABKAzr+HdafiPCAN3cdLGgJ5TWTIiBj\n" + + "AcjyHseVU4jeLIQl7/4gZATjePzSy/bo62SZXWzCOFp6zzy8VGGavRmMobe193gn\n" + + "cz/17hmFvqECAwEAAaOCAcQwggHAMB8GA1UdIwQYMBaAFNcdx/rG+oJ0IEVxNBIv\n" + + "VdWYQZJeMB0GA1UdDgQWBBR5Hkdl3jgG88ixGc1wEwO6N9Rn2TA+BgNVHSAENzA1\n" + + "MDMGBmeBDAEEATApMCcGCCsGAQUFBwIBFhtodHRwOi8vd3d3LmRpZ2ljZXJ0LmNv\n" + + "bS9DUFMwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMIGNBgNV\n" + + "HR8EgYUwgYIwP6A9oDuGOWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2Vy\n" + + "dEc1Q1NFQ0NTSEEzODQyMDIxQ0ExLmNybDA/oD2gO4Y5aHR0cDovL2NybDQuZGln\n" + + "aWNlcnQuY29tL0RpZ2lDZXJ0RzVDU0VDQ1NIQTM4NDIwMjFDQTEuY3JsMH4GCCsG\n" + + "AQUFBwEBBHIwcDAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t\n" + + "MEgGCCsGAQUFBzAChjxodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl\n" + + "cnRHNUNTRUNDU0hBMzg0MjAyMUNBMS5jcnQwCQYDVR0TBAIwADAKBggqhkjOPQQD\n" + + "AwNnADBkAjA9aX3CSzCOZiHdC6JBF0nQwPLGNipPdHFMSbINmfpuHCC3Go4prf8M\n" + + "WCsWEQr2gQYCMErfcrU8zfxnQ9SxsmGJ8jkM3MDGvAr0CtzDwmWis32V60jAUFBQ\n" + + "lGm/Mdb5/EqKpw==\n" + + "-----END CERTIFICATE-----"; + + public void runTest(ValidatePathWithParams pathValidator) throws Exception { + // Validate valid + pathValidator.validate(new String[]{VALID, INT}, + ValidatePathWithParams.Status.GOOD, null, System.out); + + // Validate Revoked + pathValidator.validate(new String[]{REVOKED, INT}, + ValidatePathWithParams.Status.REVOKED, + "Mon Oct 23 14:48:38 PDT 2023", System.out); + } +} + +class Digicert_CS_RSA { + + // Owner: CN=DigiCert G5 CS RSA4096 SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Issuer: CN=DigiCert CS RSA4096 Root G5, O="DigiCert, Inc.", C=US + // Serial number: 10262e16224ca6dfef584f8c63048db + // Valid from: Wed Feb 10 16:00:00 PST 2021 until: Sun Feb 10 15:59:59 PST 2036 + private static final String INT = "-----BEGIN CERTIFICATE-----\n" + + "MIIGjDCCBHSgAwIBAgIQAQJi4WIkym3+9YT4xjBI2zANBgkqhkiG9w0BAQwFADBM\n" + + "MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJDAiBgNVBAMT\n" + + "G0RpZ2lDZXJ0IENTIFJTQTQwOTYgUm9vdCBHNTAeFw0yMTAyMTEwMDAwMDBaFw0z\n" + + "NjAyMTAyMzU5NTlaMFcxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5EaWdpQ2VydCwg\n" + + "SW5jLjEvMC0GA1UEAxMmRGlnaUNlcnQgRzUgQ1MgUlNBNDA5NiBTSEEzODQgMjAy\n" + + "MSBDQTEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC1GOMV0tdTLLBk\n" + + "Ylmccgb6bFa9By5zkuLg9NfFMl4y9P9f21C7N+mMA4fWgfjEs+7/3ByGLaB+7/Pi\n" + + "TT3qXpvBz4uVWob9xv3lkAsIpwh/TMJulijy3GdpAQBMdvW/+HFrbRJGaJ3MM9d1\n" + + "pC3CRPmFWyXUpxqhb0FbMPA8OlsZNjg9fd/zCLevSJlL6ZdjfZ/4FiF26OfO60V6\n" + + "bOuTnd8JbDuwPfMWLP6qEinlFr7V9mjcZc4dfUWH70y7M6av7R1Tc68YQjrtPwIA\n" + + "5pdEcG/VeBVplpne1uxuc61ucVgTpjwOTV6E2KrCe+OCG8/m4voN7T4GC1RfPH3n\n" + + "PlCNV6MeiCVwExPhJFxZ+eTvhVJe0W7mriYpEo2kNR4pnSUhiS92vF4lI3ToAdnH\n" + + "LV+yx0VdsPVwEO344rsVNQvP/hrCHefKm3HsirlazTKpiI9OgZlkXohHanp8IgMx\n" + + "2HvBE/6HcCq/5PiRaeSzvFfRuotLS/LMCXaQEGV9JNSd1omKeNyaDqs89cNbf0g7\n" + + "Tn1AhAxb/TDIkIAV/1bU1UFeq48ufRCRpPO145JQXL7hfdUIth3AkvFRqLPbTsCH\n" + + "v/PcnKScv/QCtoYRnYv5LwdIvYblC+yqe7a9CVARsaVsGBw45wBevcMR5fcdriET\n" + + "ZjRNmQ5gMBjm/ZlHlzyBgShH6U22TQIDAQABo4IBXTCCAVkwEgYDVR0TAQH/BAgw\n" + + "BgEB/wIBADAdBgNVHQ4EFgQUiRgH/z5tMBfJNa27i3GG5Z9mksMwHwYDVR0jBBgw\n" + + "FoAUaAGTsdJKQEJplEYsHFqIqSW0R08wDgYDVR0PAQH/BAQDAgGGMBMGA1UdJQQM\n" + + "MAoGCCsGAQUFBwMDMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcwAYYYaHR0cDov\n" + + "L29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8vY2FjZXJ0cy5k\n" + + "aWdpY2VydC5jb20vRGlnaUNlcnRDU1JTQTQwOTZSb290RzUuY3J0MEUGA1UdHwQ+\n" + + "MDwwOqA4oDaGNGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydENTUlNB\n" + + "NDA5NlJvb3RHNS5jcmwwHAYDVR0gBBUwEzAHBgVngQwBAzAIBgZngQwBBAEwDQYJ\n" + + "KoZIhvcNAQEMBQADggIBALBxItkM8LmHhbsnkykSN6+HnLj9/hUx9UUcym1Hwoii\n" + + "Bl9VCCpibLDJurx1w19KL5S6j2ggOMn/1zBugWMVhn6j12RzD4HUkfLqNBXzQmRc\n" + + "xZoXxspSgqpk+jd5iMtVSDBzlaF7s1feDh9qKa7O/7OB5KAiIO2VYFx1ia9ne3tV\n" + + "lY98G+3TnEdjo7r9lBi4KDGmDJv56h7Sb4WeVFlJ/8b4u9IHblq3ykQ/LyKuCYDf\n" + + "v2bnqlT+HY4mgU9ZA0WoO/L7V7m0sBrBYhpdM0pmxlqn6mpvWIHA2tC4rsTY2TXn\n" + + "ZlXbyJaMd5mvjRjvK0DF/2yoKC+us/1li2blLZKS9k0Z36/m4D7z5nVXkmUvRvE2\n" + + "70BhJ0NnM5lHtytTR+OgiaPapeiDy6AA+VbdnV7hhINGEhP7tF3IZPPfmKZN7/bN\n" + + "Qr7wuKZx/jO5sTBtblBaOU2+xric+MlTt2k3ilDnO3EzkZOp1JMWnNjAZciRa8Gy\n" + + "bYAXrsxY4vQnxgA7dj1/3KDB+pCRT7CTMOJJQu27OOv0MuNkb1E+8chPx/eFwfrN\n" + + "rft1Eiqp3Te0w4njDkzukP6EMhebcTp3POm0YhMZl8s1fTI6DCcHFwcMVywXiWwv\n" + + "QG+Td+dHlFT0P8jq/ecaMj6s8j69q36MER+QMyrxGAl3MHyEA7BBut1WCh9dsOnY\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN="Win The Customer, LLC", O="Win The Customer, LLC", L=Saratoga + // Springs, ST=Utah, C=US + // Issuer: CN=DigiCert G5 CS RSA4096 SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Serial number: bfec2fd49eeacb347ddbea5c1576083 + // Valid from: Fri Jun 23 17:00:00 PDT 2023 until: Wed Jun 26 16:59:59 PDT 2024 + private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIGqzCCBJOgAwIBAgIQC/7C/UnurLNH3b6lwVdggzANBgkqhkiG9w0BAQsFADBX" + + "MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xLzAtBgNVBAMT" + + "JkRpZ2lDZXJ0IEc1IENTIFJTQTQwOTYgU0hBMzg0IDIwMjEgQ0ExMB4XDTIzMDYy" + + "NDAwMDAwMFoXDTI0MDYyNjIzNTk1OVowdzELMAkGA1UEBhMCVVMxDTALBgNVBAgT" + + "BFV0YWgxGTAXBgNVBAcTEFNhcmF0b2dhIFNwcmluZ3MxHjAcBgNVBAoTFVdpbiBU" + + "aGUgQ3VzdG9tZXIsIExMQzEeMBwGA1UEAxMVV2luIFRoZSBDdXN0b21lciwgTExD" + + "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAsElsbtoNNIL5fCadUzW+" + + "aDl2LF0c6BRckZSuH1f88tFD5LDjuT+rdIxsjDS/dqedRiilJe40z/3973OZNaxs" + + "wxYCSHhUV9XimSHH0zQ2MpbupdA7aLDYM4tcypam1Zm9q6njLArBUgGVaKYBUZqW" + + "obVh+6aFBzj36u7EmPgLCJsre5oheo8+gOwfu+xVExceoHG+V7XTKhD6vhclS49B" + + "UIHgvpn+/BlB8kjf5M2XzmpfWg9aGq75gnd1ix4fU1BnA0A33cZPrFsi5cMh6NZd" + + "tI4WIpb5P8X17G3yRqNMM/noBvBrtpQHVLpN2C2NLg0YX1FjIK7bcBKFOnIG36ou" + + "vs+QesMyVOXeKKnt1ERBSqwrMjUuqN7W6YnXjoIp7xWxEdIdae+1fDK702zhGaYv" + + "b6pYGoJ7HQI/x7S6kF462qvXsf++yA5kxr2qNTSNY4ZggzEwubvu0PYRYjMHwIUn" + + "SV3ZlRAKXK2AO7GydecWr2QVRra4+myCznsil/rKasWTAgMBAAGjggHRMIIBzTAf" + + "BgNVHSMEGDAWgBSJGAf/Pm0wF8k1rbuLcYbln2aSwzAdBgNVHQ4EFgQUfr+syABm" + + "R7FB/f155oky+e5fLR8wDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF" + + "BwMDMIGVBgNVHR8EgY0wgYowQ6BBoD+GPWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNv" + + "bS9EaWdpQ2VydEc1Q1NSU0E0MDk2U0hBMzg0MjAyMUNBMS5jcmwwQ6BBoD+GPWh0" + + "dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEc1Q1NSU0E0MDk2U0hBMzg0" + + "MjAyMUNBMS5jcmwwPgYDVR0gBDcwNTAzBgZngQwBBAEwKTAnBggrBgEFBQcCARYb" + + "aHR0cDovL3d3dy5kaWdpY2VydC5jb20vQ1BTMIGCBggrBgEFBQcBAQR2MHQwJAYI" + + "KwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBMBggrBgEFBQcwAoZA" + + "aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0RzVDU1JTQTQwOTZT" + + "SEEzODQyMDIxQ0ExLmNydDAJBgNVHRMEAjAAMA0GCSqGSIb3DQEBCwUAA4ICAQCj" + + "HCYM2aGyHFpdWRkbxa+so37uyPDJ27wpn4oNhaSKKletB8Xr6rMa5JBJ1NUa2S9Q" + + "3CYvdH9pGjjThUJPR0Lg8DrZNkPtqyjQLQ86tYfjteoKe5SXTxZ0epXikRTXySFa" + + "NM1KOEf5CJq7OywLLXVxm+F2VEX2+PzLAtHxViGeN7AsZMbWGlp3VkymVITcKkP3" + + "vnsoF6Teacb019xxBDCLuhNG91rlzhG0YrJ3qMlPyStmzxqy+2UIlPwFeLRkBkRG" + + "K7Kxi2xvYbgdFP93kRbwJbp8d3x/JG3LpwAZv+NV0TY3jBj7ymGoGuiSV0nU9XPt" + + "yDm1FYYZAH2ykwo8YPZqAcu+EHvyxi1dgOM3ABfoLJfOIYJv2gxPx+KIKzn1wzBS" + + "kk1HMf8xbYXs40vF2Lrb7AQIyLa2ZskJTyfb0dyEyOq+vvVgLA9ZdwidzD1RnVf6" + + "vOb7KbMSBCLK+HGqHrW+hhSDi2vHvSit7Cn+q80ZmzRqvJ/+mVl+ppnjDC7nSLIa" + + "qeG0fvUz6SabPX7yV92D5ARrJJ3xgAvgmgWfuKBV7WlEGCmj0QTWZ0/AFBLzNcq7" + + "+0rgP0GM98MZpKa8pHZaS1A3uP1TFzamfVGdv0FVHXSkN5Kvg0iPh4Qz9TRiCkyE" + + "boJeU1LYdyTrP/+q3zQqsGa9xdQ50EovjWymbvWzCQ==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=Win the Customer LLC, O=Win the Customer LLC, L=Saratoga Springs, + // ST=Utah, C=US + // Issuer: CN=DigiCert G5 CS RSA4096 SHA384 2021 CA1, O="DigiCert, Inc.", C=US + // Serial number: f409d101094769abaf06f085f11ca4f + // Valid from: Sun Oct 22 17:00:00 PDT 2023 until: Tue Oct 22 16:59:59 PDT 2024 + private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIHKTCCBRGgAwIBAgIQD0CdEBCUdpq68G8IXxHKTzANBgkqhkiG9w0BAQsFADBX\n" + + "MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xLzAtBgNVBAMT\n" + + "JkRpZ2lDZXJ0IEc1IENTIFJTQTQwOTYgU0hBMzg0IDIwMjEgQ0ExMB4XDTIzMTAy\n" + + "MzAwMDAwMFoXDTI0MTAyMjIzNTk1OVowdTELMAkGA1UEBhMCVVMxDTALBgNVBAgT\n" + + "BFV0YWgxGTAXBgNVBAcTEFNhcmF0b2dhIFNwcmluZ3MxHTAbBgNVBAoTFFdpbiB0\n" + + "aGUgQ3VzdG9tZXIgTExDMR0wGwYDVQQDExRXaW4gdGhlIEN1c3RvbWVyIExMQzCC\n" + + "AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANKPhVjUn2MyZs/l4AO0kQCE\n" + + "HdR9aWJ86nT8jSSbHdRv56n3h5P3sxMfFne4jCY3DzrykndeLp4gAt2sot1ziinh\n" + + "ahMOYOZtvyUzt5/McvQyuQjdXLaSuWcvlKaTl67U3QWQe+P6kmkRDsrCH0S51UeH\n" + + "8Tct/bq7ZUyX9Jb80VPVegUN80YzDgkJ2OrLngD6EKVYKQlV5K+KGyQpCOWq5CEB\n" + + "1aX63EnGiSMy0OOsS/J8aFz3BoYpEcrLSSnW84P6AhbevMfO7kr4mTLZKkx0Ic0Q\n" + + "s6TuaXcf84OuF2T/HwM0qzP7iQhE18TJmsyumVZID7t1+Br43037pb3CXcWTTJvO\n" + + "+zTkiArWy3SqAabyHirbssa75qCVHzcOHviy2wEDhc51cu1MZE8xtSDT4Hee87t0\n" + + "ptwC6v6CWaCn4XjOM6PFHr2DCpqJIvjfqjB3CaZTxfAtOP7vAjXNSZPLSpo4KH/G\n" + + "bBm0AgtvpTSl801Jz6c2uJhwTFN0HXeIlfKMXf/Y0MhO9YddSEmpFkq3rGwsguh0\n" + + "jlVIeNPQNTIb/fmhG6gTYQBySGK0EmNYW/fAii0UunAASgM6/h3Wn4jwgDd3HSxo\n" + + "CeU1kyIgYwHI8h7HlVOI3iyEJe/+IGQE43j80sv26OtkmV1swjhaes88vFRhmr0Z\n" + + "jKG3tfd4J3M/9e4Zhb6hAgMBAAGjggHRMIIBzTAfBgNVHSMEGDAWgBSJGAf/Pm0w\n" + + "F8k1rbuLcYbln2aSwzAdBgNVHQ4EFgQUeR5HZd44BvPIsRnNcBMDujfUZ9kwPgYD\n" + + "VR0gBDcwNTAzBgZngQwBBAEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdp\n" + + "Y2VydC5jb20vQ1BTMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcD\n" + + "AzCBlQYDVR0fBIGNMIGKMEOgQaA/hj1odHRwOi8vY3JsMy5kaWdpY2VydC5jb20v\n" + + "RGlnaUNlcnRHNUNTUlNBNDA5NlNIQTM4NDIwMjFDQTEuY3JsMEOgQaA/hj1odHRw\n" + + "Oi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNlcnRHNUNTUlNBNDA5NlNIQTM4NDIw\n" + + "MjFDQTEuY3JsMIGCBggrBgEFBQcBAQR2MHQwJAYIKwYBBQUHMAGGGGh0dHA6Ly9v\n" + + "Y3NwLmRpZ2ljZXJ0LmNvbTBMBggrBgEFBQcwAoZAaHR0cDovL2NhY2VydHMuZGln\n" + + "aWNlcnQuY29tL0RpZ2lDZXJ0RzVDU1JTQTQwOTZTSEEzODQyMDIxQ0ExLmNydDAJ\n" + + "BgNVHRMEAjAAMA0GCSqGSIb3DQEBCwUAA4ICAQAKCH6ri6f507/j2ifF7VQbavWE\n" + + "Wn4T63PzJveL6/kedV7avhrQ/B6uHrez1xy/RH/MlL/B+TF6YTg+ILqtKR/PyJrg\n" + + "N+1RON0Eg3AEWWDtGl3KBYFlklz8Szo+xmXf5GYiqueejbxscH1BA0PU/5CgGkr6\n" + + "1Kk4OXqKqmpuPeQCxca1ARDD749E/2IFsDGC8kBCWepV62l0/xcDKWD5Zn+y4Tkh\n" + + "5+YJJ21D746sNDOsDNJ4DuqEYrXWUH6BlT5EDYelGqRCOdyTYUdDg+QcSFWnH7wR\n" + + "O+eIA3BLSw0x1Vh6DJRKm5H644sPVppaI1jVZDe+zBwp2e/j8XH7KDlp/WaRUhcU\n" + + "bjGg2Ss5TMbBjR6B4nMwjvqaCIFoAD6aFRYc80px/KY6KTSyOFF0FBQNuhSsUZQy\n" + + "p74aRjUraSu/RiJMA8A6OYGo1b7W9o/UOg0MB4WQkfwl+Mxh+58QKjLjZr9VVapW\n" + + "4yv0G/G6rT/pHrRiyBcT7Kt4xNFsmMFAN4BXL9WI9mkGDa4iwDmWVjIjAaiilaaC\n" + + "MIXwwm3eg/QBgWBUrwXf3YC+1HXkaFDZc5apQ5uaNJPjQo9nQ6xqfpnACXTJ/Lwm\n" + + "JBu4YlXPby5Vh6mWWSyVdbICrCD7BtGP8aSBPFGPEuPEjK32uyeoGWVwwSubVFPX\n" + + "ARhLX5oSFZUySvHgYg==\n" + + "-----END CERTIFICATE-----"; + + public void runTest(ValidatePathWithParams pathValidator) throws Exception { + // Validate valid + pathValidator.validate(new String[]{VALID, INT}, + ValidatePathWithParams.Status.GOOD, null, System.out); + + // Validate Revoked + pathValidator.validate(new String[]{REVOKED, INT}, + ValidatePathWithParams.Status.REVOKED, + "Mon Oct 23 14:44:23 PDT 2023", System.out); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8319187 + * @summary Interoperability tests with eMudhra emSign Root CA G2 CS root + * @build ValidatePathWithParams + * @run main/othervm -Djava.security.debug=certpath EmSignRootG2CA OCSP + * @run main/othervm -Djava.security.debug=certpath EmSignRootG2CA CRL + */ + +public class EmSignRootG2CA { + + // Owner: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Issuer: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: c084e666596139a1fa9b + // Valid from: Sun Feb 18 10:30:00 PST 2018 until: Fri Feb 18 10:30:00 PST 2033 + private static final String INT = "-----BEGIN CERTIFICATE-----\n" + + "MIIGeDCCBGCgAwIBAgILAMCE5mZZYTmh+pswDQYJKoZIhvcNAQEMBQAwZzELMAkG\n" + + "A1UEBhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEg\n" + + "VGVjaG5vbG9naWVzIExpbWl0ZWQxHDAaBgNVBAMTE2VtU2lnbiBSb290IENBIC0g\n" + + "RzIwHhcNMTgwMjE4MTgzMDAwWhcNMzMwMjE4MTgzMDAwWjBlMQswCQYDVQQGEwJJ\n" + + "TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s\n" + + "b2dpZXMgTGltaXRlZDEaMBgGA1UEAxMRZW1TaWduIENTIENBIC0gRzIwggIiMA0G\n" + + "CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDYYkv6Q9an5RylOJ6rkTAHT0cAwfYg\n" + + "ZsFKk/Hz/4VwWYsmzf+Z7M8i3CK3mnUcqgw0AIzrVLUwxiKAaL0qca+SbXwOk/7p\n" + + "Y/zwwLdg0OhHVGeeU3OTvkbsBpiLS08i7ids9FGrte6m1kqk+QSOY2F5AESxA4+F\n" + + "AKXGtzIImQd15m67C88AzzFsvszAAxSvVTqs4hb8BcRnUCzlAp7gMJSwwrrgTiEv\n" + + "6Ap6cFVT+n1oj6370sd5KBiRelLoqZtQx4njoNJkJlM30ftPNMGnqPLCloQ6koP/\n" + + "dAdpmwWB+F0/5d5UVmVPC3R/F8w7aX3fdSC8+M2E/ZXPVIYkEquLT7K2yXhRl3hn\n" + + "xwG6qqGp6TjvKvhiyac8qieu9YNG1R+PVFqejOFMohV2g0Z5MfwaruhUCNwHHeZs\n" + + "Dv/MVYMiHcV+5qU+MMzcKngb3RCmq0jzCb+MESomEMiAieCC15W7YC/LpgDHO0jY\n" + + "vV4AdLquUHfsOnhT2KD7mEg2PnL7JOwoQSFtuJYmM/coh+Y6CIoV3x+aV1bO7FDF\n" + + "ap33u36lE639oQj0tTqW3n1WcyNxhD0lwGlYIAjG8XnhRjtl6/MVVrGuyPWpB4TH\n" + + "u8CgNT0roENuq13RnHbBz2rLnndenHiMbxCyElGJBpZfXiF1H25KHUzvyzxt++L+\n" + + "hSfprX9BSXLpGQIDAQABo4IBJTCCASEwHwYDVR0jBBgwFoAU7exNRWEYKOezIygR\n" + + "HE2lJw1e7PQwHQYDVR0OBBYEFBWGyrZ0lhdIWDSCLM3S4XWer0S3MA4GA1UdDwEB\n" + + "/wQEAwIBBjATBgNVHSUEDDAKBggrBgEFBQcDAzA9BgNVHSAENjA0MDIGBFUdIAAw\n" + + "KjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnkuZW1zaWduLmNvbTASBgNV\n" + + "HRMBAf8ECDAGAQH/AgEAMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcwAYYWaHR0\n" + + "cDovL29jc3AuZW1zaWduLmNvbTAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js\n" + + "LmVtc2lnbi5jb20/Um9vdENBRzIuY3JsMA0GCSqGSIb3DQEBDAUAA4ICAQCDkogs\n" + + "d5Tv1zwsQdk15btzYK/oI1tEwvN6IpIM9rSqIrje8XnXKjHHmbHX6emHIR31bxuK\n" + + "7mY77XjrJMWp+71udC/DgDy4tfZTXIzEekI0XQfcui1UPC08Ysl0taQKTANwsAOV\n" + + "VSi7boSGqLet0qSmeKVyQ5/blbwx1NhjyLTyi66rVYf7fYdPV55X5TKUJdKDgiRI\n" + + "BomNVRcrrnHZtS8+t9CXxSXR35VAu2ube44Tl+dQHIWz9XwLxtYFwIPSEdqPpoAu\n" + + "5XEVo7evwMHQoY/MQj6Ywbw6tYh6bHu6C/qrp4oSyYXbz2ZWlHkz1oEXvefi7a9Z\n" + + "6mKnnaY3UYHq5AI+k6ojazVFbSTenb/TO/Z247gdhG7Wssshd6pgyqcTEa+FZz+F\n" + + "5ZZdoiIl8UJsTCPPg0xP9Ab0WE3BjCCqTPt+Czbd3cgBxiBS7KTQs/DnQRFuPCjC\n" + + "khbDtHsCN4aUoLM9OOw94/ZcoU0G5cg9mSvONBxUv9W7SIpJreXXMPXixcBKULoJ\n" + + "focui3s0yzGqTA9tSzQ4nmA9aXBCAAxrABlY/hk10ImeBa1SPjocRb/vuCaGp74T\n" + + "n8oADP42XudDnp8wlOKWxFJulhNi960Rev+5vZOPF/LGfS78GI6yzBjR49VJGhOP\n" + + "EJK8NSNmK3FNblQfOyFM7VE0uOGHOUwpMGVM2A==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=test, OU=test, O=test, L=test, ST=test, C=IN + // Issuer: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: 7c9ade672c0ad1b6 + // Valid from: Wed Aug 30 05:39:25 PDT 2023 until: Sat Aug 30 05:39:25 PDT 2025 + private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIGNjCCBB6gAwIBAgIIfJreZywK0bYwDQYJKoZIhvcNAQEMBQAwZTELMAkGA1UE\n" + + "BhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEgVGVj\n" + + "aG5vbG9naWVzIExpbWl0ZWQxGjAYBgNVBAMTEWVtU2lnbiBDUyBDQSAtIEcyMB4X\n" + + "DTIzMDgzMDEyMzkyNVoXDTI1MDgzMDEyMzkyNVowWDELMAkGA1UEBhMCSU4xDTAL\n" + + "BgNVBAgTBHRlc3QxDTALBgNVBAcTBHRlc3QxDTALBgNVBAoMBHRlc3QxDTALBgNV\n" + + "BAsTBHRlc3QxDTALBgNVBAMTBHRlc3QwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAw\n" + + "ggGKAoIBgQC04pOiSFbl7Bd4wFYXzzyukKh+EmwIq8xRGQDkuYH+C6Zao36VAV+k\n" + + "xGw7lmM3rf4YUcArgZYHfrxgPJNBbGrCi/YnEPYQTNwSrBAePUx1tt13LVBxHfNu\n" + + "cQQT+kqE7064WsYfmfr/uzJZemqVH7lG82DN23+8E/235AIh3lz/pn7T9ByLj7TV\n" + + "zWP40oT0UfQXQvWUpFevPONu/RksRP+NiKV3ji6/wYpvrfodzkrGxw2DPfOh4Iam\n" + + "j6bBH2rkTMToH853plsQGr2ji8OndePfvDdk+5c33Jz1knCNPZSlYQIIp8scyz4z\n" + + "jaUGdoC140FjEA1SMA2WzpRJoE7xjAidLv7jiV596/bTwrIM+IZhzBc8SKRmkdZ6\n" + + "lYjPYJHPqRosRtfxcQne3pY6F4s1aOUtuGJaQS/AJkkykZoOx27plWM5SjtmlrL+\n" + + "7g2/ihWT9CEagYuo44tqk9Tmp3P37+ADAmiXxP0zUxYIv77DSabdArrZ+AB5XUol\n" + + "V8sxE1V6h0UCAwEAAaOCAXUwggFxMB8GA1UdIwQYMBaAFBWGyrZ0lhdIWDSCLM3S\n" + + "4XWer0S3MB0GA1UdDgQWBBQ2k0TE2p46sYwI5M/a1XJ8M5Oc8DAOBgNVHQ8BAf8E\n" + + "BAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwMwNwYDVR0fBDAwLjAsoCqgKIYmaHR0\n" + + "cDovL2NybC5lbXNpZ24uY29tP2VtU2lnbkNTQ0FHMi5jcmwwTgYDVR0gBEcwRTA5\n" + + "BgsrBgEEAYOOIQEAATAqMCgGCCsGAQUFBwIBFhxodHRwOi8vcmVwb3NpdG9yeS5l\n" + + "bVNpZ24uY29tMAgGBmeBDAEEATBzBggrBgEFBQcBAQRnMGUwIgYIKwYBBQUHMAGG\n" + + "Fmh0dHA6Ly9vY3NwLmVtU2lnbi5jb20wPwYIKwYBBQUHMAKGM2h0dHA6Ly9yZXBv\n" + + "c2l0b3J5LmVtc2lnbi5jb20vY2VydHMvZW1TaWduQ1NDQUcyLmNydDAMBgNVHRMB\n" + + "Af8EAjAAMA0GCSqGSIb3DQEBDAUAA4ICAQBKLa7j8fNpcnWNv7NegrMKTRy7gycI\n" + + "qrMK848wISX6jl2wg6b275sWQHzQRxA6rbB76bF2HXLFcpITJPaz+vjetYOVQd4v\n" + + "l8iZN52OpN6Pwrheiz7JhdLiHisN+2NKMmF899bH7w1l2Sr/FQl5vqk41gwwWMen\n" + + "99Waf4Bp6p3lvBArK2BbabTs8+16xvmkHEK3d3l3Bu6qTEbQRgUI5XsVXmXXn8Pg\n" + + "IANliTEsbsN9CMWrJ56ciEujU7w2L+IBfvKhl10N1AQNHwpQzwfFyz2BUbACN75o\n" + + "feIUBarM3ssNzpnt7idgkCTwWVrdEL1NHyW967aEMWyVwaRrtkjFOW/0xuSr2rEI\n" + + "jBpPj5RPdP6ZEaqnmg5PIgSrJ8FBjx6JmvVgZH/XEl5MZ7PsvJFfIMun6RxXtGn7\n" + + "QP0+ipkRrI6USNFS84H53Q0WJhQWZUgd3cdm37wpFGvxOVEskIgJNW9SbOgiT9sB\n" + + "zTIy3ceOK2onmUkDM2Q2+Hbc7A4BmNIlW4fpYXvZlM7IXSl9U3Voks92Hi45azgz\n" + + "StWZv9+Ronmmp+b7JKCe7MZXIBHfj0JhAVNJiYTZ9BqkY2VRvuQPVUdKxske9fQ6\n" + + "ciFJ5a6RDOhce6pFloaQu39ci2XCY1N4mIR3vFzpmBNkttlEXviK07XNTv9cnQt6\n" + + "3CW5aMAsfTbmOw==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=test, OU=test, O=test, L=test, ST=test, C=IN + // Issuer: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: cf02dedd03d2f509 + // Valid from: Thu Oct 05 22:38:51 PDT 2023 until: Sun Oct 05 22:38:51 PDT 2025 + private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIGNzCCBB+gAwIBAgIJAM8C3t0D0vUJMA0GCSqGSIb3DQEBDAUAMGUxCzAJBgNV\n" + + "BAYTAklOMRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRl\n" + + "Y2hub2xvZ2llcyBMaW1pdGVkMRowGAYDVQQDExFlbVNpZ24gQ1MgQ0EgLSBHMjAe\n" + + "Fw0yMzEwMDYwNTM4NTFaFw0yNTEwMDYwNTM4NTFaMFgxCzAJBgNVBAYTAklOMQ0w\n" + + "CwYDVQQIEwR0ZXN0MQ0wCwYDVQQHEwR0ZXN0MQ0wCwYDVQQKDAR0ZXN0MQ0wCwYD\n" + + "VQQLEwR0ZXN0MQ0wCwYDVQQDEwR0ZXN0MIIBojANBgkqhkiG9w0BAQEFAAOCAY8A\n" + + "MIIBigKCAYEAmUSghjvjUvVgYguH2PMLwW4TwtYsNDpAuGPqux53lI9v9S5u4oAv\n" + + "m1Sa3MW7CeEnhHNAIFu/AKvNXSfkvnJpTozWstZMjd93DcNacteBG0fBKTkIq+5k\n" + + "A8qIBiXWk8NORlbjV5bXnoW2pO7wbrALDK3FGf2JAQjuYWXE1mlVk0+SJewUSN+F\n" + + "XTl63V3tcaqjxhoViY8/dCWc7pNTPgQ/f+Rmnm1bpE0hxVPpQ29+60lyoNtKiOWj\n" + + "InKRKBV8jYkR/xI13bKWguaxZnswpf2MrophQTvO9ivPHADWhZlNYYjYYEMl4tbi\n" + + "rG2EquJ7g8Jdo+aL3BggLv5gFkpfoEcaveNuUWy7ggUl7MNhvgDdWdoi6VY7R8Fi\n" + + "F52+JqPByGpHkZKi0wPa3BaI7guGGyCn3TMe66kNTMS4ADxHktqQlpNSaYYl/84G\n" + + "lnr2WxQt/W+sXoorlKc/Kh0ubbm6eDzPE8kkIDV2uIxUEgSL7SJQ95yf5XgRihoH\n" + + "KoBA45iR5vCtAgMBAAGjggF1MIIBcTAfBgNVHSMEGDAWgBQVhsq2dJYXSFg0gizN\n" + + "0uF1nq9EtzAdBgNVHQ4EFgQUDs5dk74eElzdEKdxIlkzISoWSFkwDgYDVR0PAQH/\n" + + "BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMDcGA1UdHwQwMC4wLKAqoCiGJmh0\n" + + "dHA6Ly9jcmwuZW1zaWduLmNvbT9lbVNpZ25DU0NBRzIuY3JsME4GA1UdIARHMEUw\n" + + "OQYLKwYBBAGDjiEBAAEwKjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnku\n" + + "ZW1TaWduLmNvbTAIBgZngQwBBAEwcwYIKwYBBQUHAQEEZzBlMCIGCCsGAQUFBzAB\n" + + "hhZodHRwOi8vb2NzcC5lbVNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVw\n" + + "b3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL2VtU2lnbkNTQ0FHMi5jcnQwDAYDVR0T\n" + + "AQH/BAIwADANBgkqhkiG9w0BAQwFAAOCAgEAGa2XSoRkoIkHHHGXrdzTBCf/+KgK\n" + + "FlHhqlBOk5rwLDX1sfNlmsaz10I69phE90Ac8Coa/xCrBaFrTYqRvmkY9gU19jkn\n" + + "FdVcwQEHNku7Ro/Z/mbyi+aTBzHMTy0Vl4HqVnQInjV891n64SerUuAB7wNVOOho\n" + + "GoBfpf6lzDzzuEmetFokHYv1tWGQqPF/dHLARQraUlQpWjsnOx0QcZ5cM79REONE\n" + + "y6uzXT2vaatT3ns8Mtx8zooq+t8pnZlXJqlrwNTcnPad9gSsVu6vfsnWhLhz0VLG\n" + + "sYPXcWIssLbBQW3v5z0l1Isj7vy2UFfbn8AmZ0PanPo3v3C2sk19DK+Zlc9xBAXc\n" + + "KKwc4m8le6QkP/EB2wUA7ey5Cf29hjNDJpZznquEaWl9aKbBRdJDKsK88IBJjzK0\n" + + "Gbpw9fYJ3txuGA7Q27gyaZAeGAIrFvOtRY0XFbr20qSh2GBBYN57+lBPh4UKqgy8\n" + + "Z2Kk/2jK9k+nm41JYCmwVZHg3Va9RRfW8FkeE95gAUFPDWjeV+GvcimCbcB3DwaZ\n" + + "9fy1qfV4xsduhC3ei6f7Ask8LbAEWaEIXmgK10YbIfhzomCyCzlA+E+gwkq/bmkv\n" + + "B8hh27KWA6IRt7URI51MZlh0e8fULyXlOZcoJA/IPX9RdePa2RHFuPSypBHjoN7z\n" + + "6bCML1XZ2xnHIAg=\n" + + "-----END CERTIFICATE-----"; + + public static void main(String[] args) throws Exception { + + ValidatePathWithParams pathValidator = new ValidatePathWithParams(null); + + if (args.length >= 1 && "CRL".equalsIgnoreCase(args[0])) { + pathValidator.enableCRLCheck(); + } else { + // OCSP check by default + pathValidator.enableOCSPCheck(); + } + + // Validate valid + pathValidator.validate(new String[]{VALID, INT}, + ValidatePathWithParams.Status.GOOD, null, System.out); + + // Validate Revoked + pathValidator.validate(new String[]{REVOKED, INT}, + ValidatePathWithParams.Status.REVOKED, + "Thu Oct 05 22:51:36 PDT 2023", System.out); + } +} \ No newline at end of file diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java 2024-01-11 01:53:23.000000000 +0000 @@ -30,7 +30,7 @@ * @test * @bug 6216082 * @summary Redirect problem with HttpsURLConnection using a proxy - * @library .. /lib + * @library .. /test/lib * @build jdk.test.lib.NetworkConfiguration * jdk.test.lib.Platform * HttpCallback TestHttpsServer ClosedChannelList diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ec/SignedObjectChain.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ec/SignedObjectChain.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ec/SignedObjectChain.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ec/SignedObjectChain.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 8050374 8146293 * @summary Verify a chain of signed objects - * @library /lib + * @library /test/lib * @compile ../../../java/security/SignedObject/Chain.java * @run main SignedObjectChain */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/krb5/config/YesNo.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/krb5/config/YesNo.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/krb5/config/YesNo.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/krb5/config/YesNo.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8029995 + * @summary accept yes/no for boolean krb5.conf settings + * @compile -XDignore.symbol.file YesNo.java + * @run main/othervm YesNo + */ +import sun.security.krb5.Config; +import sun.security.krb5.internal.crypto.EType; + +import java.util.Arrays; + +public class YesNo { + static Config config = null; + public static void main(String[] args) throws Exception { + System.setProperty("java.security.krb5.conf", + System.getProperty("test.src", ".") +"/yesno.conf"); + config = Config.getInstance(); + check("a", Boolean.TRUE); + check("b", Boolean.FALSE); + check("c", Boolean.TRUE); + check("d", Boolean.FALSE); + check("e", null); + check("f", null); + + if (!Arrays.stream(EType.getBuiltInDefaults()) + .anyMatch(n -> n < 4)) { + throw new Exception(); + } + } + + static void check(String k, Boolean expected) throws Exception { + Boolean result = config.getBooleanObject("libdefaults", k); + if (expected != result) { + throw new Exception("value for " + k + " is " + result); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/krb5/config/yesno.conf openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/krb5/config/yesno.conf --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/krb5/config/yesno.conf 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/krb5/config/yesno.conf 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,7 @@ +[libdefaults] +a = true +b = FALSE +c = YES +d = no +e = nothing +allow_weak_crypto = yes diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/lib/cacerts/VerifyCACerts.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/lib/cacerts/VerifyCACerts.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/lib/cacerts/VerifyCACerts.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/lib/cacerts/VerifyCACerts.java 2024-01-11 01:53:23.000000000 +0000 @@ -28,7 +28,7 @@ * 8209452 8209506 8210432 8195793 8216577 8222089 8222133 8222137 8222136 * 8223499 8225392 8232019 8234245 8233223 8225068 8225069 8243321 8243320 * 8243559 8225072 8258630 8259312 8256421 8225081 8225082 8225083 8245654 - * 8305975 8304760 8307134 8295894 8314960 + * 8305975 8304760 8307134 8295894 8314960 8317373 8317374 8318759 8319187 * @summary Check root CA entries in cacerts file */ import java.io.ByteArrayInputStream; @@ -54,12 +54,12 @@ + File.separator + "security" + File.separator + "cacerts"; // The numbers of certs now. - private static final int COUNT = 97; + private static final int COUNT = 106; // SHA-256 of cacerts, can be generated with // shasum -a 256 cacerts | sed -e 's/../&:/g' | tr '[:lower:]' '[:upper:]' | cut -c1-95 private static final String CHECKSUM - = "88:72:92:56:FF:E5:A3:E4:39:98:6D:18:0B:BA:CC:0B:66:CB:1D:6D:52:CE:D7:C8:AD:63:B7:F1:5F:02:24:52"; + = "61:5F:6D:C5:9C:A3:8A:65:3F:CB:F9:F5:26:04:23:F4:53:A6:8C:B3:8B:2B:0A:F0:66:7D:9E:67:B9:4D:AC:B7"; // map of cert alias to SHA-256 fingerprint @SuppressWarnings("serial") private static final Map FINGERPRINT_MAP @@ -151,6 +151,8 @@ "5D:56:49:9B:E4:D2:E0:8B:CF:CA:D0:8A:3E:38:72:3D:50:50:3B:DE:70:69:48:E4:2F:55:60:30:19:E5:28:AE"); put("letsencryptisrgx1 [jdk]", "96:BC:EC:06:26:49:76:F3:74:60:77:9A:CF:28:C5:A7:CF:E8:A3:C0:AA:E1:1A:8F:FC:EE:05:C0:BD:DF:08:C6"); + put("letsencryptisrgx2 [jdk]", + "69:72:9B:8E:15:A8:6E:FC:17:7A:57:AF:B7:17:1D:FC:64:AD:D2:8C:2F:CA:8C:F1:50:7E:34:45:3C:CB:14:70"); put("luxtrustglobalrootca [jdk]", "A1:B2:DB:EB:64:E7:06:C6:16:9E:3C:41:18:B2:3B:AA:09:01:8A:84:27:66:6D:8B:F0:E2:88:91:EC:05:19:50"); put("quovadisrootca [jdk]", @@ -165,6 +167,14 @@ "18:F1:FC:7F:20:5D:F8:AD:DD:EB:7F:E0:07:DD:57:E3:AF:37:5A:9C:4D:8D:73:54:6B:F4:F1:FE:D1:E1:8D:35"); put("quovadisrootca3g3 [jdk]", "88:EF:81:DE:20:2E:B0:18:45:2E:43:F8:64:72:5C:EA:5F:BD:1F:C2:D9:D2:05:73:07:09:C5:D8:B8:69:0F:46"); + put("digicertcseccrootg5 [jdk]", + "26:C5:6A:D2:20:8D:1E:9B:15:2F:66:85:3B:F4:79:7C:BE:B7:55:2C:1F:3F:47:72:51:E8:CB:1A:E7:E7:97:BF"); + put("digicertcsrsarootg5 [jdk]", + "73:53:B6:D6:C2:D6:DA:42:47:77:3F:3F:07:D0:75:DE:CB:51:34:21:2B:EA:D0:92:8E:F1:F4:61:15:26:09:41"); + put("digicerttlseccrootg5 [jdk]", + "01:8E:13:F0:77:25:32:CF:80:9B:D1:B1:72:81:86:72:83:FC:48:C6:E1:3B:E9:C6:98:12:85:4A:49:0C:1B:05"); + put("digicerttlsrsarootg5 [jdk]", + "37:1A:00:DC:05:33:B3:72:1A:7E:EB:40:E8:41:9E:70:79:9D:2B:0A:0F:2C:1D:80:69:31:65:F7:CE:C4:AD:75"); put("secomscrootca2 [jdk]", "51:3B:2C:EC:B8:10:D4:CD:E5:DD:85:39:1A:DF:C6:C2:DD:60:D8:7B:B7:36:D2:B5:21:48:4A:A4:7A:0E:BE:F6"); put("swisssigngoldg2ca [jdk]", @@ -259,6 +269,14 @@ "34:9D:FA:40:58:C5:E2:63:12:3B:39:8A:E7:95:57:3C:4E:13:13:C8:3F:E6:8F:93:55:6C:D5:E8:03:1B:3C:7D"); put("certignarootca [jdk]", "D4:8D:3D:23:EE:DB:50:A4:59:E5:51:97:60:1C:27:77:4B:9D:7B:18:C9:4D:5A:05:95:11:A1:02:50:B9:31:68"); + put("teliarootcav2 [jdk]", + "24:2B:69:74:2F:CB:1E:5B:2A:BF:98:89:8B:94:57:21:87:54:4E:5B:4D:99:11:78:65:73:62:1F:6A:74:B8:2C"); + put("emsignrootcag1 [jdk]", + "40:F6:AF:03:46:A9:9A:A1:CD:1D:55:5A:4E:9C:CE:62:C7:F9:63:46:03:EE:40:66:15:83:3D:C8:C8:D0:03:67"); + put("emsigneccrootcag3 [jdk]", + "86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B"); + put("emsignrootcag2 [jdk]", + "1A:A0:C2:70:9E:83:1B:D6:E3:B5:12:9A:00:BA:41:F7:EE:EF:02:08:72:F1:E6:50:4B:F0:F6:C3:F2:4F:3A:F3"); } }; diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/mscapi/SignedObjectChain.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/mscapi/SignedObjectChain.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/mscapi/SignedObjectChain.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/mscapi/SignedObjectChain.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 8050374 8146293 * @summary Verify a chain of signed objects - * @library /lib + * @library /test/lib * @compile ../../../java/security/SignedObject/Chain.java * @run main SignedObjectChain */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java 2024-01-11 01:53:23.000000000 +0000 @@ -31,7 +31,7 @@ * @bug 6405536 * @summary Verify that all ciphersuites work (incl. ECC using NSS crypto) * @author Andreas Sterbenz - * @library /lib .. ../../../../javax/net/ssl/TLSCommon + * @library /test/lib .. ../../../../javax/net/ssl/TLSCommon * @library ../../../../java/security/testlibrary * @run main/othervm -Djdk.tls.namedGroups="secp256r1,sect193r1" * ClientJSSEServerJSSE diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/EmptyPassword.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/EmptyPassword.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/EmptyPassword.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/EmptyPassword.java 2024-01-11 01:53:23.000000000 +0000 @@ -26,7 +26,7 @@ * @bug 8202299 * @modules java.base/sun.security.tools.keytool * java.base/sun.security.x509 - * @library /lib / + * @library /test/lib / * @summary Java Keystore fails to load PKCS12/PFX certificates created in WindowsServer2016 */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsPreferences.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsPreferences.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsPreferences.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsPreferences.java 2024-01-11 01:53:23.000000000 +0000 @@ -38,7 +38,7 @@ /* * @test * @bug 8076190 - * @library /lib/testlibrary /lib + * @library /lib/testlibrary /test/lib * @modules java.base/sun.security.pkcs * java.base/sun.security.x509 * java.base/sun.security.util diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsTest.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/pkcs12/ParamsTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -24,7 +24,7 @@ /* * @test * @bug 8076190 - * @library /lib/testlibrary /lib + * @library /lib/testlibrary /test/lib * @modules java.base/sun.security.pkcs * java.base/sun.security.x509 * java.base/sun.security.util diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/RSAPaddingCheck.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/RSAPaddingCheck.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/RSAPaddingCheck.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/RSAPaddingCheck.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8302017 + * @summary Ensure that RSAPadding class works as expected after refactoring + * @modules java.base/sun.security.rsa + */ +import java.util.Arrays; +import sun.security.rsa.RSAPadding; + +public class RSAPaddingCheck { + + private static int[] PADDING_TYPES = { + RSAPadding.PAD_BLOCKTYPE_1, + RSAPadding.PAD_BLOCKTYPE_2, + RSAPadding.PAD_NONE, + RSAPadding.PAD_OAEP_MGF1, + }; + + public static void main(String[] args) throws Exception { + int size = 2048 >> 3; + byte[] testData = "This is some random to-be-padded Data".getBytes(); + for (int type : PADDING_TYPES) { + byte[] data = (type == RSAPadding.PAD_NONE? + Arrays.copyOf(testData, size) : testData); + System.out.println("Testing PaddingType: " + type); + RSAPadding padding = RSAPadding.getInstance(type, size); + byte[] paddedData = padding.pad(data); + if (paddedData == null) { + throw new RuntimeException("Unexpected padding op failure!"); + } + + byte[] data2 = padding.unpad(paddedData); + if (data2 == null) { + throw new RuntimeException("Unexpected unpadding op failure!"); + } + if (!Arrays.equals(data, data2)) { + throw new RuntimeException("diff check failure!"); + } + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/SignatureTest.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/SignatureTest.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/SignatureTest.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/SignatureTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -38,7 +38,7 @@ * @summary Create a signature for RSA and get its signed data. re-initiate * the signature with the public key. The signature can be verified * by acquired signed data. - * @library /lib + * @library /test/lib * @key randomness * @library ../../../lib/testlibrary * @run main SignatureTest MD2withRSA 512 diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/SignedObjectChain.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/SignedObjectChain.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/SignedObjectChain.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/SignedObjectChain.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 8050374 8146293 * @summary Verify a chain of signed objects - * @library /lib + * @library /test/lib * @compile ../../../java/security/SignedObject/Chain.java * @run main SignedObjectChain */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/TestKeyPairGenerator.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/TestKeyPairGenerator.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/TestKeyPairGenerator.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/TestKeyPairGenerator.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 4853305 4865198 4888410 4963723 8146293 * @summary Verify that the RSA KeyPairGenerator works - * @library /lib + * @library /test/lib * @build jdk.test.lib.SigTestUtil * @run main TestKeyPairGenerator * @author Andreas Sterbenz diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/TestSignatures.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/TestSignatures.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/TestSignatures.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/TestSignatures.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 4853305 4963723 8146293 * @summary Test signing/verifying using all the signature algorithms - * @library /lib + * @library /test/lib * @build jdk.test.lib.SigTestUtil * @run main TestSignatures * @author Andreas Sterbenz diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/WithoutNULL.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/WithoutNULL.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/WithoutNULL.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/WithoutNULL.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8320597 + * @summary Verify RSA signature with omitted digest params (should be encoded as NULL) + * for backward compatibility + */ +import java.security.KeyFactory; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +public class WithoutNULL { + public static void main(String[] args) throws Exception { + + // A 1024-bit RSA public key + byte[] key = Base64.getMimeDecoder().decode( + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrfTrEm4KvdFSpGAM7InrFEzALTKdphT9fK6Gu" + + "eVjHtKsuCSEaULCdjhJvPpFK40ONr1JEC1Ywp1UYrfBBdKunnbDZqNZL1cFv+IzF4Yj6JO6pOeHi" + + "1Zpur1GaQRRlYTvzmyWY/AATQDh8JfKObNnDVwXeezFODUG8h5+XL1ZXZQIDAQAB"); + + // A SHA1withRSA signature on an empty input where the digestAlgorithm + // inside DigestInfo does not have a parameters field. + byte[] sig = Base64.getMimeDecoder().decode( + "D1FpiT44WEXlDfYK880bdorLO+e9qJVXZWiBgqs9dfK7lYQwyEt9dL23mbUAKm5TVEj2ZxtHkEvk" + + "b8oaWkxk069jDTM1RhllPJZkAjeQRbw4gkg4N6wKZz9B/jdSRMNJg/b9QdRYZOHOBxsEHMbUREPV" + + "DoCOLaxB8eIXX0EWkiE="); + + Signature s = Signature.getInstance("SHA1withRSA", "SunRsaSign"); + s.initVerify(KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(key))); + if (!s.verify(sig)) { + throw new RuntimeException("Does not verify"); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/pss/SignatureTestPSS.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/pss/SignatureTestPSS.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/rsa/pss/SignatureTestPSS.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/rsa/pss/SignatureTestPSS.java 2024-01-11 01:53:23.000000000 +0000 @@ -36,7 +36,7 @@ * @summary Create a signature for RSASSA-PSS and get its signed data. * re-initiate the signature with the public key. The signature * can be verified by acquired signed data. - * @library /lib + * @library /test/lib * @build jdk.test.lib.SigTestUtil * @run main SignatureTestPSS 512 * @run main SignatureTestPSS 768 diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java 2024-01-11 01:53:23.000000000 +0000 @@ -54,7 +54,7 @@ * @test * @bug 8165367 * @summary Verify the restrictions for certificate path on JSSE with custom trust store. - * @library /lib + * @library /test/lib * @build jdk.test.lib.Utils * jdk.test.lib.Asserts * jdk.test.lib.JDKToolFinder diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 7126889 * @summary Incorrect SSLEngine debug output - * @library /lib /lib/security + * @library /test/lib /lib/security * @run main DebugReportsOneExtraByte */ /* diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/rsa/SignedObjectChain.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/rsa/SignedObjectChain.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/ssl/rsa/SignedObjectChain.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/ssl/rsa/SignedObjectChain.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 8050374 8146293 * @summary Verify a chain of signed objects - * @library /lib + * @library /test/lib * @compile ../../../../java/security/SignedObject/Chain.java * @run main SignedObjectChain */ diff -Nru openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/util/DerInputBuffer/PaddedBitString.java openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/util/DerInputBuffer/PaddedBitString.java --- openjdk-8-8u392-ga/=unpacked-tar3=/test/sun/security/util/DerInputBuffer/PaddedBitString.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar3=/test/sun/security/util/DerInputBuffer/PaddedBitString.java 2024-01-11 01:53:23.000000000 +0000 @@ -25,7 +25,7 @@ * @test * @bug 4511556 * @summary Verify BitString value containing padding bits is accepted. - * @library /lib + * @library /test/lib */ import java.io.*; import java.math.BigInteger; diff -Nru openjdk-8-8u392-ga/=unpacked-tar4=/README openjdk-8-8u402-ga/=unpacked-tar4=/README --- openjdk-8-8u392-ga/=unpacked-tar4=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar4=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -README: - This file should be located at the top of the corba Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - - See ../README-builds.html for complete details on build machine requirements. - -Simple Build Instructions: - - cd make && gnumake - - The files that will be imported into the jdk build will be in the "dist" - directory. - diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/README openjdk-8-8u402-ga/=unpacked-tar5=/README --- openjdk-8-8u392-ga/=unpacked-tar5=/README 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -README: - This file should be located at the top of the hotspot Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - - See ../README-builds.html for complete details on build machine requirements. - -Simple Build Instructions: - - cd make && gnumake - - The files that will be imported into the jdk build will be in the "build" - directory. - diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/THIRD_PARTY_README openjdk-8-8u402-ga/=unpacked-tar5=/THIRD_PARTY_README --- openjdk-8-8u392-ga/=unpacked-tar5=/THIRD_PARTY_README 2023-10-21 19:26:54.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/THIRD_PARTY_README 2024-01-18 23:30:27.000000000 +0000 @@ -1472,7 +1472,7 @@ ------------------------------------------------------------------------------- -%% This notice is provided with respect to libpng 1.6.37, which may be +%% This notice is provided with respect to libpng 1.6.39, which may be included with JRE 8, JDK 8, and OpenJDK 8. --- begin of LICENSE --- @@ -1483,11 +1483,11 @@ PNG Reference Library License version 2 --------------------------------------- - * Copyright (c) 1995-2019 The PNG Reference Library Authors. - * Copyright (c) 2018-2019 Cosmin Truta. - * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. - * Copyright (c) 1996-1997 Andreas Dilger. - * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +Copyright (c) 1995-2022 The PNG Reference Library Authors. +Copyright (c) 2018-2022 Cosmin Truta +Copyright (c) 1998-2018 Glenn Randers-Pehrson +Copyright (c) 1996-1997 Andreas Dilger +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. The software is supplied "as is", without warranty of any kind, express or implied, including, without limitation, the warranties @@ -1614,10 +1614,10 @@ TRADEMARK: -The name "libpng" has not been registered by the Copyright owner +The name "libpng" has not been registered by the Copyright owners as a trademark in any jurisdiction. However, because libpng has been distributed and maintained world-wide, continually since 1995, -the Copyright owner claims "common-law trademark protection" in any +the Copyright owners claim "common-law trademark protection" in any jurisdiction where common-law trademark is recognized. OSI CERTIFICATION: @@ -1639,6 +1639,59 @@ glennrp at users.sourceforge.net July 15, 2018 +AUTHORS File Information: + +PNG REFERENCE LIBRARY AUTHORS +============================= + +This is the list of PNG Reference Library ("libpng") Contributing +Authors, for copyright and licensing purposes. + + * Andreas Dilger + * Cosmin Truta + * Dave Martindale + * Eric S. Raymond + * Gilles Vollant + * Glenn Randers-Pehrson + * Greg Roelofs + * Guy Eric Schalnat + * James Yu + * John Bowler + * Kevin Bracey + * Magnus Holmgren + * Mandar Sahastrabuddhe + * Mans Rullgard + * Matt Sarett + * Mike Klein + * Pascal Massimino + * Paul Schmidt + * Qiang Zhou + * Sam Bushell + * Samuel Williams + * Simon-Pierre Cadieux + * Tim Wegner + * Tom Lane + * Tom Tanner + * Vadim Barkov + * Willem van Schaik + * Zhijie Liang + * Arm Holdings + - Richard Townsend + * Google Inc. + - Dan Field + - Leon Scroggins III + - Matt Sarett + - Mike Klein + - Sami Boukortt + +The build projects, the build scripts, the test scripts, and other +files in the "ci", "projects", "scripts" and "tests" directories, have +other copyright owners, but are released under the libpng license. + +Some files in the "contrib" directory, and some tools-generated files +that are distributed with libpng, have other copyright owners, and are +released under other open source licenses. + --- end of LICENSE --- ------------------------------------------------------------------------------- diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_GraphBuilder.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_GraphBuilder.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_GraphBuilder.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_GraphBuilder.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -206,8 +206,10 @@ } void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) { - // start a new block after jsr-bytecode and link this block into cfg - make_block_at(next_bci, current); + if (next_bci < method()->code_size()) { + // start a new block after jsr-bytecode and link this block into cfg + make_block_at(next_bci, current); + } // start a new block at the subroutine entry at mark it with special flag BlockBegin* sr_block = make_block_at(sr_bci, current); @@ -227,6 +229,8 @@ // branch target and a modification of the successor lists. BitMap bci_block_start = method()->bci_block_start(); + int end_bci = method()->code_size(); + ciBytecodeStream s(method()); while (s.next() != ciBytecodeStream::EOBC()) { int cur_bci = s.cur_bci(); @@ -297,7 +301,9 @@ case Bytecodes::_if_acmpne: // fall through case Bytecodes::_ifnull: // fall through case Bytecodes::_ifnonnull: - make_block_at(s.next_bci(), current); + if (s.next_bci() < end_bci) { + make_block_at(s.next_bci(), current); + } make_block_at(s.get_dest(), current); current = NULL; break; diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_LIRGenerator.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_LIRGenerator.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_LIRGenerator.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_LIRGenerator.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -79,6 +79,7 @@ PhiResolver::PhiResolver(LIRGenerator* gen, int max_vregs) : _gen(gen) , _state(gen->resolver_state()) + , _loop(NULL) , _temp(LIR_OprFact::illegalOpr) { // reinitialize the shared state arrays diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_RangeCheckElimination.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_RangeCheckElimination.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/c1/c1_RangeCheckElimination.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/c1/c1_RangeCheckElimination.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -379,8 +379,11 @@ aii->_max = idx; aii->_list = new AccessIndexedList(); } else if (idx >= aii->_min && idx <= aii->_max) { - remove_range_check(ai); - return; + // Guard against underflow/overflow (see 'range_cond' check in RangeCheckEliminator::in_block_motion) + if (aii->_max < 0 || (aii->_max + min_jint) <= aii->_min) { + remove_range_check(ai); + return; + } } aii->_min = MIN2(aii->_min, idx); aii->_max = MAX2(aii->_max, idx); @@ -423,9 +426,9 @@ } } } else { - int last_integer = 0; + jint last_integer = 0; Instruction *last_instruction = index; - int base = 0; + jint base = 0; ArithmeticOp *ao = index->as_ArithmeticOp(); while (ao != NULL && (ao->x()->as_Constant() || ao->y()->as_Constant()) && (ao->op() == Bytecodes::_iadd || ao->op() == Bytecodes::_isub)) { @@ -437,12 +440,12 @@ } if (c) { - int value = c->type()->as_IntConstant()->value(); + jint value = c->type()->as_IntConstant()->value(); if (value != min_jint) { if (ao->op() == Bytecodes::_isub) { value = -value; } - base += value; + base = java_add(base, value); last_integer = base; last_instruction = other; } @@ -464,12 +467,12 @@ assert(info != NULL, "Info must not be null"); // if idx < 0, max > 0, max + idx may fall between 0 and - // length-1 and if min < 0, min + idx may overflow and be >= + // length-1 and if min < 0, min + idx may underflow/overflow and be >= // 0. The predicate wouldn't trigger but some accesses could // be with a negative index. This test guarantees that for the // min and max value that are kept the predicate can't let // some incorrect accesses happen. - bool range_cond = (info->_max < 0 || info->_max + min_jint <= info->_min); + bool range_cond = (info->_max < 0 || (info->_max + min_jint) <= info->_min); // Generate code only if more than 2 range checks can be eliminated because of that. // 2 because at least 2 comparisons are done @@ -809,7 +812,7 @@ ); remove_range_check(ai); - } else if (_optimistic && loop_header) { + } else if (false && _optimistic && loop_header) { assert(ai->array(), "Array must not be null!"); assert(ai->index(), "Index must not be null!"); diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/ci/ciMethodBlocks.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/ci/ciMethodBlocks.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/ci/ciMethodBlocks.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/ci/ciMethodBlocks.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,12 +33,13 @@ ciBlock *ciMethodBlocks::block_containing(int bci) { + assert(bci >= 0 && bci < _code_size, "valid bytecode range"); ciBlock *blk = _bci_to_block[bci]; return blk; } bool ciMethodBlocks::is_block_start(int bci) { - assert(bci >=0 && bci < _code_size, "valid bytecode range"); + assert(bci >= 0 && bci < _code_size, "valid bytecode range"); ciBlock *b = _bci_to_block[bci]; assert(b != NULL, "must have block for bytecode"); return b->start_bci() == bci; @@ -146,7 +147,9 @@ case Bytecodes::_ifnonnull : { cur_block->set_control_bci(bci); - ciBlock *fall_through = make_block_at(s.next_bci()); + if (s.next_bci() < limit_bci) { + ciBlock *fall_through = make_block_at(s.next_bci()); + } int dest_bci = s.get_dest(); ciBlock *dest = make_block_at(dest_bci); break; @@ -166,7 +169,9 @@ case Bytecodes::_jsr : { cur_block->set_control_bci(bci); - ciBlock *ret = make_block_at(s.next_bci()); + if (s.next_bci() < limit_bci) { + ciBlock *ret = make_block_at(s.next_bci()); + } int dest_bci = s.get_dest(); ciBlock *dest = make_block_at(dest_bci); break; @@ -224,7 +229,9 @@ case Bytecodes::_jsr_w : { cur_block->set_control_bci(bci); - ciBlock *ret = make_block_at(s.next_bci()); + if (s.next_bci() < limit_bci) { + ciBlock *ret = make_block_at(s.next_bci()); + } int dest_bci = s.get_far_dest(); ciBlock *dest = make_block_at(dest_bci); break; diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/classfile/verifier.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/classfile/verifier.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/classfile/verifier.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/classfile/verifier.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -2084,11 +2084,12 @@ "low must be less than or equal to high in tableswitch"); return; } - keys = high - low + 1; - if (keys < 0) { + int64_t keys64 = ((int64_t)high - low) + 1; + if (keys64 > 65535) { // Max code length verify_error(ErrorContext::bad_code(bci), "too many keys in tableswitch"); return; } + keys = (int)keys64; delta = 1; } else { keys = (int)Bytes::get_Java_u4(aligned_bcp + jintSize); diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/code/nmethod.hpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/code/nmethod.hpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/code/nmethod.hpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/code/nmethod.hpp 2024-01-18 10:40:14.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -363,8 +363,8 @@ // type info bool is_nmethod() const { return true; } - bool is_java_method() const { return !method()->is_native(); } - bool is_native_method() const { return method()->is_native(); } + bool is_java_method() const { return _method != NULL && !method()->is_native(); } + bool is_native_method() const { return _method != NULL && method()->is_native(); } bool is_osr_method() const { return _entry_bci != InvocationEntryBci; } bool is_compiled_by_c1() const; diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/compiler/methodLiveness.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/compiler/methodLiveness.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/compiler/methodLiveness.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/compiler/methodLiveness.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -268,10 +268,11 @@ case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: // Two way branch. Set predecessors at each destination. - dest = _block_map->at(bytes.next_bci()); - assert(dest != NULL, "must be a block immediately following this one."); - dest->add_normal_predecessor(current_block); - + if (bytes.next_bci() < method_len) { + dest = _block_map->at(bytes.next_bci()); + assert(dest != NULL, "must be a block immediately following this one."); + dest->add_normal_predecessor(current_block); + } dest = _block_map->at(bytes.get_dest()); assert(dest != NULL, "branch desination must start a block."); dest->add_normal_predecessor(current_block); diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/interpreter/bytecodes.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/interpreter/bytecodes.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/interpreter/bytecodes.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/interpreter/bytecodes.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -117,12 +117,18 @@ if (end != NULL && aligned_bcp + 3*jintSize >= end) { return -1; // don't read past end of code buffer } + // Promote calculation to signed 64 bits to do range checks, used by the verifier. jlong lo = (jint)Bytes::get_Java_u4(aligned_bcp + 1*jintSize); jlong hi = (jint)Bytes::get_Java_u4(aligned_bcp + 2*jintSize); jlong len = (aligned_bcp - bcp) + (3 + hi - lo + 1)*jintSize; - // only return len if it can be represented as a positive int; - // return -1 otherwise - return (len > 0 && len == (int)len) ? len : -1; + // Only return len if it can be represented as a positive int and lo <= hi. + // The caller checks for bytecode stream overflow. + if (lo <= hi && len == (int)len) { + assert(len > 0, "must be"); + return (int)len; + } else { + return -1; + } } case _lookupswitch: // fall through @@ -134,9 +140,13 @@ } jlong npairs = (jint)Bytes::get_Java_u4(aligned_bcp + jintSize); jlong len = (aligned_bcp - bcp) + (2 + 2*npairs)*jintSize; - // only return len if it can be represented as a positive int; - // return -1 otherwise - return (len > 0 && len == (int)len) ? len : -1; + // Only return len if it can be represented as a positive int and npairs >= 0. + if (npairs >= 0 && len == (int)len) { + assert(len > 0, "must be"); + return (int)len; + } else { + return -1; + } } } // Note: Length functions must return <=0 for invalid bytecodes. diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/ifnode.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/ifnode.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/ifnode.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/ifnode.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -882,6 +882,46 @@ // then we are guaranteed to fail, so just start interpreting there. // We 'expand' the top 3 range checks to include all post-dominating // checks. + // + // Example: + // a[i+x] // (1) 1 < x < 6 + // a[i+3] // (2) + // a[i+4] // (3) + // a[i+6] // max = max of all constants + // a[i+2] + // a[i+1] // min = min of all constants + // + // If x < 3: + // (1) a[i+x]: Leave unchanged + // (2) a[i+3]: Replace with a[i+max] = a[i+6]: i+x < i+3 <= i+6 -> (2) is covered + // (3) a[i+4]: Replace with a[i+min] = a[i+1]: i+1 < i+4 <= i+6 -> (3) and all following checks are covered + // Remove all other a[i+c] checks + // + // If x >= 3: + // (1) a[i+x]: Leave unchanged + // (2) a[i+3]: Replace with a[i+min] = a[i+1]: i+1 < i+3 <= i+x -> (2) is covered + // (3) a[i+4]: Replace with a[i+max] = a[i+6]: i+1 < i+4 <= i+6 -> (3) and all following checks are covered + // Remove all other a[i+c] checks + // + // We only need the top 2 range checks if x is the min or max of all constants. + // + // This, however, only works if the interval [i+min,i+max] is not larger than max_int (i.e. abs(max - min) < max_int): + // The theoretical max size of an array is max_int with: + // - Valid index space: [0,max_int-1] + // - Invalid index space: [max_int,-1] // max_int, min_int, min_int - 1 ..., -1 + // + // The size of the consecutive valid index space is smaller than the size of the consecutive invalid index space. + // If we choose min and max in such a way that: + // - abs(max - min) < max_int + // - i+max and i+min are inside the valid index space + // then all indices [i+min,i+max] must be in the valid index space. Otherwise, the invalid index space must be + // smaller than the valid index space which is never the case for any array size. + // + // Choosing a smaller array size only makes the valid index space smaller and the invalid index space larger and + // the argument above still holds. + // + // Note that the same optimization with the same maximal accepted interval size can also be found in C1. + const jlong maximum_number_of_min_max_interval_indices = (jlong)max_jint; // The top 3 range checks seen const int NRC =3; @@ -915,13 +955,18 @@ found_immediate_dominator = true; break; } - // Gather expanded bounds - off_lo = MIN2(off_lo,offset2); - off_hi = MAX2(off_hi,offset2); - // Record top NRC range checks - prev_checks[nb_checks%NRC].ctl = prev_dom; - prev_checks[nb_checks%NRC].off = offset2; - nb_checks++; + + // "x - y" -> must add one to the difference for number of elements in [x,y] + const jlong diff = (jlong)MIN2(offset2, off_lo) - (jlong)MAX2(offset2, off_hi); + if (ABS(diff) < maximum_number_of_min_max_interval_indices) { + // Gather expanded bounds + off_lo = MIN2(off_lo, offset2); + off_hi = MAX2(off_hi, offset2); + // Record top NRC range checks + prev_checks[nb_checks % NRC].ctl = prev_dom; + prev_checks[nb_checks % NRC].off = offset2; + nb_checks++; + } } } prev_dom = dom; diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.cpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.cpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.cpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.cpp 2024-01-18 10:40:14.000000000 +0000 @@ -260,6 +260,49 @@ set_early_ctrl( n ); } +void PhaseIdealLoop::insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol) { + Node* new_predicate_proj = create_new_if_for_predicate(limit_check_proj, NULL, + Deoptimization::Reason_loop_limit_check); + Node* iff = new_predicate_proj->in(0); + assert(iff->Opcode() == Op_If, "bad graph shape"); + Node* conv = iff->in(1); + assert(conv->Opcode() == Op_Conv2B, "bad graph shape"); + Node* opaq = conv->in(1); + assert(opaq->Opcode() == Op_Opaque1, "bad graph shape"); + cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); + bol = _igvn.register_new_node_with_optimizer(bol); + set_subtree_ctrl(bol); + _igvn.replace_input_of(iff, 1, bol); + +#ifndef PRODUCT + // report that the loop predication has been actually performed + // for this loop + if (TraceLoopLimitCheck) { + tty->print_cr("Counted Loop Limit Check generated:"); + debug_only( bol->dump(2); ) + } +#endif +} + +static int check_stride_overflow(jlong final_correction, const TypeInt* limit_t) { + if (final_correction > 0) { + if (limit_t->_lo > (max_jint - final_correction)) { + return -1; + } + if (limit_t->_hi > (max_jint - final_correction)) { + return 1; + } + } else { + if (limit_t->_hi < (min_jint - final_correction)) { + return -1; + } + if (limit_t->_lo < (min_jint - final_correction)) { + return 1; + } + } + return 0; +} + //------------------------------is_counted_loop-------------------------------- bool PhaseIdealLoop::is_counted_loop( Node *x, IdealLoopTree *loop ) { PhaseGVN *gvn = &_igvn; @@ -463,51 +506,256 @@ assert(x->Opcode() == Op_Loop, "regular loops only"); C->print_method(PHASE_BEFORE_CLOOPS, 3); - Node *hook = new (C) Node(6); + Node* adjusted_limit = limit; if (LoopLimitCheck) { // =================================================== - // Generate loop limit check to avoid integer overflow - // in cases like next (cyclic loops): + // We can only convert this loop to a counted loop if we can guarantee that the iv phi will never overflow at runtime. + // This is an implicit assumption taken by some loop optimizations. We therefore must ensure this property at all cost. + // At this point, we've already excluded some trivial cases where an overflow could have been proven statically. + // But even though we cannot prove that an overflow will *not* happen, we still want to speculatively convert this loop + // to a counted loop. This can be achieved by adding additional iv phi overflow checks before the loop. If they fail, + // we trap and resume execution before the loop without having executed any iteration of the loop, yet. // - // for (i=0; i <= max_jint; i++) {} - // for (i=0; i < max_jint; i+=2) {} + // These additional iv phi overflow checks can be inserted as Loop Limit Check Predicates above the Loop Limit Check + // Parse Predicate which captures a JVM state just before the entry of the loop. If there is no such Parse Predicate, + // we cannot generate a Loop Limit Check Predicate and thus cannot speculatively convert the loop to a counted loop. // + // In the following, we only focus on int loops with stride > 0 to keep things simple. The argumentation and proof + // for stride < 0 is analogously. For long loops, we would replace max_int with max_long. // - // Limit check predicate depends on the loop test: // - // for(;i != limit; i++) --> limit <= (max_jint) - // for(;i < limit; i+=stride) --> limit <= (max_jint - stride + 1) - // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride ) + // The loop to be converted does not always need to have the often used shape: // + // i = init + // i = init loop: + // do { ... + // // ... equivalent i+=stride + // i+=stride <==> if (i < limit) + // } while (i < limit); goto loop + // exit: + // ... + // + // where the loop exit check uses the post-incremented iv phi and a '<'-operator. + // + // We could also have '<='-operator (or '>='-operator for negative strides) or use the pre-incremented iv phi value + // in the loop exit check: + // + // i = init + // loop: + // ... + // if (i <= limit) + // i+=stride + // goto loop + // exit: + // ... + // + // Let's define the following terms: + // - iv_pre_i: The pre-incremented iv phi before the i-th iteration. + // - iv_post_i: The post-incremented iv phi after the i-th iteration. + // + // The iv_pre_i and iv_post_i have the following relation: + // iv_pre_i + stride = iv_post_i + // + // When converting a loop to a counted loop, we want to have a canonicalized loop exit check of the form: + // iv_post_i < adjusted_limit + // + // If that is not the case, we need to canonicalize the loop exit check by using different values for adjusted_limit: + // (LE1) iv_post_i < limit: Already canonicalized. We can directly use limit as adjusted_limit. + // -> adjusted_limit = limit. + // (LE2) iv_post_i <= limit: + // iv_post_i < limit + 1 + // -> adjusted limit = limit + 1 + // (LE3) iv_pre_i < limit: + // iv_pre_i + stride < limit + stride + // iv_post_i < limit + stride + // -> adjusted_limit = limit + stride + // (LE4) iv_pre_i <= limit: + // iv_pre_i < limit + 1 + // iv_pre_i + stride < limit + stride + 1 + // iv_post_i < limit + stride + 1 + // -> adjusted_limit = limit + stride + 1 + // + // Note that: + // (AL) limit <= adjusted_limit. + // + // The following loop invariant has to hold for counted loops with n iterations (i.e. loop exit check true after n-th + // loop iteration) and a canonicalized loop exit check to guarantee that no iv_post_i over- or underflows: + // (INV) For i = 1..n, min_int <= iv_post_i <= max_int + // + // To prove (INV), we require the following two conditions/assumptions: + // (i): adjusted_limit - 1 + stride <= max_int + // (ii): init < limit + // + // If we can prove (INV), we know that there can be no over- or underflow of any iv phi value. We prove (INV) by + // induction by assuming (i) and (ii). + // + // Proof by Induction + // ------------------ + // > Base case (i = 1): We show that (INV) holds after the first iteration: + // min_int <= iv_post_1 = init + stride <= max_int + // Proof: + // First, we note that (ii) implies + // (iii) init <= limit - 1 + // max_int >= adjusted_limit - 1 + stride [using (i)] + // >= limit - 1 + stride [using (AL)] + // >= init + stride [using (iii)] + // >= min_int [using stride > 0, no underflow] + // Thus, no overflow happens after the first iteration and (INV) holds for i = 1. + // + // Note that to prove the base case we need (i) and (ii). + // + // > Induction Hypothesis (i = j, j > 1): Assume that (INV) holds after the j-th iteration: + // min_int <= iv_post_j <= max_int + // > Step case (i = j + 1): We show that (INV) also holds after the j+1-th iteration: + // min_int <= iv_post_{j+1} = iv_post_j + stride <= max_int + // Proof: + // If iv_post_j >= adjusted_limit: + // We exit the loop after the j-th iteration, and we don't execute the j+1-th iteration anymore. Thus, there is + // also no iv_{j+1}. Since (INV) holds for iv_j, there is nothing left to prove. + // If iv_post_j < adjusted_limit: + // First, we note that: + // (iv) iv_post_j <= adjusted_limit - 1 + // max_int >= adjusted_limit - 1 + stride [using (i)] + // >= iv_post_j + stride [using (iv)] + // >= min_int [using stride > 0, no underflow] + // + // Note that to prove the step case we only need (i). + // + // Thus, by assuming (i) and (ii), we proved (INV). + // + // + // It is therefore enough to add the following two Loop Limit Check Predicates to check assumptions (i) and (ii): + // + // (1) Loop Limit Check Predicate for (i): + // Using (i): adjusted_limit - 1 + stride <= max_int + // + // This condition is now restated to use limit instead of adjusted_limit: + // + // To prevent an overflow of adjusted_limit -1 + stride itself, we rewrite this check to + // max_int - stride + 1 >= adjusted_limit + // We can merge the two constants into + // canonicalized_correction = stride - 1 + // which gives us + // max_int - canonicalized_correction >= adjusted_limit + // + // To directly use limit instead of adjusted_limit in the predicate condition, we split adjusted_limit into: + // adjusted_limit = limit + limit_correction + // Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into: + // max_int - canonicalized_correction - limit_correction >= limit + // Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant: + // final_correction = canonicalized_correction + limit_correction + // which gives us: + // + // Final predicate condition: + // max_int - final_correction >= limit + // + // (2) Loop Limit Check Predicate for (ii): + // Using (ii): init < limit + // + // This Loop Limit Check Predicate is not required if we can prove at compile time that either: + // (2.1) type(init) < type(limit) + // In this case, we know: + // all possible values of init < all possible values of limit + // and we can skip the predicate. + // + // (2.2) init < limit is already checked before (i.e. found as a dominating check) + // In this case, we do not need to re-check the condition and can skip the predicate. + // This is often found for while- and for-loops which have the following shape: + // + // if (init < limit) { // Dominating test. Do not need the Loop Limit Check Predicate below. + // i = init; + // if (init >= limit) { trap(); } // Here we would insert the Loop Limit Check Predicate + // do { + // i += stride; + // } while (i < limit); + // } + // + // (2.3) init + stride <= max_int + // In this case, there is no overflow of the iv phi after the first loop iteration. + // In the proof of the base case above we showed that init + stride <= max_int by using assumption (ii): + // init < limit + // In the proof of the step case above, we did not need (ii) anymore. Therefore, if we already know at + // compile time that init + stride <= max_int then we have trivially proven the base case and that + // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii) + // again and can skip the predicate. + + + // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check. + const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != NULL) ? stride_con : 0; + + // Accounting for (LE2) and (LE4) where we use <= or >= in the loop exit check. + const bool includes_limit = (bt == BoolTest::le || bt == BoolTest::ge); + const jlong limit_correction_for_le_ge_exit_check = (includes_limit ? (stride_con > 0 ? 1 : -1) : 0); + + const jlong limit_correction = limit_correction_for_pre_iv_exit_check + limit_correction_for_le_ge_exit_check; + const jlong canonicalized_correction = stride_con + (stride_con > 0 ? -1 : 1); + const jlong final_correction = canonicalized_correction + limit_correction; + + int sov = check_stride_overflow(final_correction, limit_t); + + // If sov==0, limit's type always satisfies the condition, for + // example, when it is an array length. + if (sov != 0) { + if (sov < 0) { + return false; // Bailout: integer overflow is certain. + } + // (1) Loop Limit Check Predicate is required because we could not statically prove that + // limit + final_correction = adjusted_limit - 1 + stride <= max_int + ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check); + if (!limit_check_proj) { + // The Loop Limit Check Parse Predicate is not generated if this method trapped here before. +#ifdef ASSERT + if (TraceLoopLimitCheck) { + tty->print("missing loop limit check:"); + loop->dump_head(); + x->dump(1); + } +#endif + return false; + } - // Check if limit is excluded to do more precise int overflow check. - bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge); - int stride_m = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1)); - - // If compare points directly to the phi we need to adjust - // the compare so that it points to the incr. Limit have - // to be adjusted to keep trip count the same and the - // adjusted limit should be checked for int overflow. - if (phi_incr != NULL) { - stride_m += stride_con; - } + IfNode* check_iff = limit_check_proj->in(0)->as_If(); - if (limit->is_Con()) { - int limit_con = limit->get_int(); - if ((stride_con > 0 && limit_con > (max_jint - stride_m)) || - (stride_con < 0 && limit_con < (min_jint - stride_m))) { - // Bailout: it could be integer overflow. + if (!is_dominator(get_ctrl(limit), check_iff->in(0))) { return false; } - } else if ((stride_con > 0 && limit_t->_hi <= (max_jint - stride_m)) || - (stride_con < 0 && limit_t->_lo >= (min_jint - stride_m))) { - // Limit's type may satisfy the condition, for example, - // when it is an array length. - } else { - // Generate loop's limit check. - // Loop limit check predicate should be near the loop. + + Node* cmp_limit; + Node* bol; + + if (stride_con > 0) { + cmp_limit = new (C) CmpINode(limit, _igvn.intcon(max_jint - final_correction)); + bol = new (C) BoolNode(cmp_limit, BoolTest::le); + } else { + cmp_limit = new (C) CmpINode(limit, _igvn.intcon(min_jint - final_correction)); + bol = new (C) BoolNode(cmp_limit, BoolTest::ge); + } + + insert_loop_limit_check(limit_check_proj, cmp_limit, bol); + } + + // (2.3) + const bool init_plus_stride_could_overflow = + (stride_con > 0 && init_t->_hi > max_jint - stride_con) || + (stride_con < 0 && init_t->_lo < min_jint - stride_con); + // (2.1) + const bool init_gte_limit = (stride_con > 0 && init_t->_hi >= limit_t->_lo) || + (stride_con < 0 && init_t->_lo <= limit_t->_hi); + + if (init_gte_limit && // (2.1) + ((bt == BoolTest::ne || init_plus_stride_could_overflow) && // (2.3) + !has_dominating_loop_limit_check(init_trip, limit, stride_con, init_control))) { // (2.2) + // (2) Iteration Loop Limit Check Predicate is required because neither (2.1), (2.2), nor (2.3) holds. + // We use the following condition: + // - stride > 0: init < limit + // - stride < 0: init > limit + // + // This predicate is always required if we have a non-equal-operator in the loop exit check (where stride = 1 is + // a requirement). We transform the loop exit check by using a less-than-operator. By doing so, we must always + // check that init < limit. Otherwise, we could have a different number of iterations at runtime. + ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check); if (!limit_check_proj) { // The limit check predicate is not generated if this method trapped here before. @@ -520,41 +768,38 @@ #endif return false; } - IfNode* check_iff = limit_check_proj->in(0)->as_If(); + + if (!is_dominator(get_ctrl(limit), check_iff->in(0)) || + !is_dominator(get_ctrl(init_trip), check_iff->in(0))) { + return false; + } + Node* cmp_limit; Node* bol; if (stride_con > 0) { - cmp_limit = new (C) CmpINode(limit, _igvn.intcon(max_jint - stride_m)); - bol = new (C) BoolNode(cmp_limit, BoolTest::le); + cmp_limit = new (C) CmpINode(init_trip, limit); + bol = new (C) BoolNode(cmp_limit, BoolTest::lt); } else { - cmp_limit = new (C) CmpINode(limit, _igvn.intcon(min_jint - stride_m)); - bol = new (C) BoolNode(cmp_limit, BoolTest::ge); + cmp_limit = new (C) CmpINode(init_trip, limit); + bol = new (C) BoolNode(cmp_limit, BoolTest::gt); } - cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); - bol = _igvn.register_new_node_with_optimizer(bol); - set_subtree_ctrl(bol); - - // Replace condition in original predicate but preserve Opaque node - // so that previous predicates could be found. - assert(check_iff->in(1)->Opcode() == Op_Conv2B && - check_iff->in(1)->in(1)->Opcode() == Op_Opaque1, ""); - Node* opq = check_iff->in(1)->in(1); - _igvn.hash_delete(opq); - opq->set_req(1, bol); - // Update ctrl. - set_ctrl(opq, check_iff->in(0)); - set_ctrl(check_iff->in(1), check_iff->in(0)); -#ifndef PRODUCT - // report that the loop predication has been actually performed - // for this loop - if (TraceLoopLimitCheck) { - tty->print_cr("Counted Loop Limit Check generated:"); - debug_only( bol->dump(2); ) + insert_loop_limit_check(limit_check_proj, cmp_limit, bol); + } + + if (bt == BoolTest::ne) { + // Now we need to canonicalize the loop condition if it is 'ne'. + assert(stride_con == 1 || stride_con == -1, "simple increment only - checked before"); + if (stride_con > 0) { + // 'ne' can be replaced with 'lt' only when init < limit. This is ensured by the inserted predicate above. + bt = BoolTest::lt; + } else { + assert(stride_con < 0, "must be"); + // 'ne' can be replaced with 'gt' only when init > limit. This is ensured by the inserted predicate above. + bt = BoolTest::gt; } -#endif } if (phi_incr != NULL) { @@ -567,26 +812,15 @@ // is converted to // i = init; do {} while(++i < limit+1); // - limit = gvn->transform(new (C) AddINode(limit, stride)); + adjusted_limit = gvn->transform(new (C) AddINode(limit, stride)); } - // Now we need to canonicalize loop condition. - if (bt == BoolTest::ne) { - assert(stride_con == 1 || stride_con == -1, "simple increment only"); - // 'ne' can be replaced with 'lt' only when init < limit. - if (stride_con > 0 && init_t->_hi < limit_t->_lo) - bt = BoolTest::lt; - // 'ne' can be replaced with 'gt' only when init > limit. - if (stride_con < 0 && init_t->_lo > limit_t->_hi) - bt = BoolTest::gt; - } - - if (incl_limit) { + if (includes_limit) { // The limit check guaranties that 'limit <= (max_jint - stride)' so // we can convert 'i <= limit' to 'i < limit+1' since stride != 0. // Node* one = (stride_con > 0) ? gvn->intcon( 1) : gvn->intcon(-1); - limit = gvn->transform(new (C) AddINode(limit, one)); + adjusted_limit = gvn->transform(new (C) AddINode(adjusted_limit, one)); if (bt == BoolTest::le) bt = BoolTest::lt; else if (bt == BoolTest::ge) @@ -594,10 +828,11 @@ else ShouldNotReachHere(); } - set_subtree_ctrl( limit ); + set_subtree_ctrl(adjusted_limit); } else { // LoopLimitCheck + Node *hook = new (C) Node(6); // If compare points to incr, we are ok. Otherwise the compare // can directly point to the phi; in this case adjust the compare so that // it points to the incr by adjusting the limit. @@ -691,6 +926,11 @@ limit = gvn->transform(new (C) AddINode(span,init_trip)); set_subtree_ctrl( limit ); + adjusted_limit = limit; + + // Free up intermediate goo + _igvn.remove_dead_node(hook); + } // LoopLimitCheck if (!UseCountedLoopSafepoints) { @@ -728,7 +968,7 @@ } cmp = cmp->clone(); cmp->set_req(1,incr); - cmp->set_req(2,limit); + cmp->set_req(2, adjusted_limit); cmp = _igvn.register_new_node_with_optimizer(cmp); set_ctrl(cmp, iff->in(0)); @@ -802,9 +1042,6 @@ } } - // Free up intermediate goo - _igvn.remove_dead_node(hook); - #ifdef ASSERT assert(l->is_valid_counted_loop(), "counted loop shape is messed up"); assert(l == loop->_head && l->phi() == phi && l->loopexit() == lex, "" ); @@ -821,6 +1058,37 @@ return true; } +// Check if there is a dominating loop limit check of the form 'init < limit' starting at the loop entry. +// If there is one, then we do not need to create an additional Loop Limit Check Predicate. +bool PhaseIdealLoop::has_dominating_loop_limit_check(Node* init_trip, Node* limit, const int stride_con, + Node* loop_entry) { + // Eagerly call transform() on the Cmp and Bool node to common them up if possible. This is required in order to + // successfully find a dominated test with the If node below. + Node* cmp_limit; + Node* bol; + if (stride_con > 0) { + cmp_limit = _igvn.transform(new (C) CmpINode(init_trip, limit)); + bol = _igvn.transform(new (C) BoolNode(cmp_limit, BoolTest::lt)); + } else { + cmp_limit = _igvn.transform(new (C) CmpINode(init_trip, limit)); + bol = _igvn.transform(new (C) BoolNode(cmp_limit, BoolTest::gt)); + } + + // Check if there is already a dominating init < limit check. If so, we do not need a Loop Limit Check Predicate. + IfNode* iff = new (C) IfNode(loop_entry, bol, PROB_MIN, COUNT_UNKNOWN); + // Also add fake IfProj nodes in order to call transform() on the newly created IfNode. + IfFalseNode* if_false = new (C) IfFalseNode(iff); + IfTrueNode* if_true = new (C) IfTrueNode(iff); + Node* dominated_iff = _igvn.transform(iff); + // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node). + const bool found_dominating_test = dominated_iff != NULL && dominated_iff->Opcode() == Op_ConI; + + // Kill the If with its projections again in the next IGVN round by cutting it off from the graph. + _igvn.replace_input_of(iff, 0, C->top()); + _igvn.replace_input_of(iff, 1, C->top()); + return found_dominating_test; +} + //----------------------exact_limit------------------------------------------- Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) { assert(loop->_head->is_CountedLoop(), ""); diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.hpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.hpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.hpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/loopnode.hpp 2024-01-18 10:40:14.000000000 +0000 @@ -896,6 +896,10 @@ // Create a new if above the uncommon_trap_if_pattern for the predicate to be promoted ProjNode* create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry, Deoptimization::DeoptReason reason); + void insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol); + bool has_dominating_loop_limit_check(Node* init_trip, Node* limit, int stride_con, + Node* loop_entry); + void register_control(Node* n, IdealLoopTree *loop, Node* pred); // Clone loop predicates to cloned loops (peeled, unswitched) diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/phaseX.hpp openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/phaseX.hpp --- openjdk-8-8u392-ga/=unpacked-tar5=/src/share/vm/opto/phaseX.hpp 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/src/share/vm/opto/phaseX.hpp 2024-01-18 10:40:14.000000000 +0000 @@ -433,9 +433,6 @@ protected: - // Idealize new Node 'n' with respect to its inputs and its value - virtual Node *transform( Node *a_node ); - // Warm up hash table, type table and initial worklist void init_worklist( Node *a_root ); @@ -449,6 +446,9 @@ PhaseIterGVN( PhaseGVN *gvn ); // Used after Parser PhaseIterGVN( PhaseIterGVN *igvn, const char *dummy ); // Used after +VerifyOpto + // Idealize new Node 'n' with respect to its inputs and its value + virtual Node *transform( Node *a_node ); + virtual PhaseIterGVN *is_IterGVN() { return this; } Unique_Node_List _worklist; // Iterative worklist diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/test/TEST.ROOT openjdk-8-8u402-ga/=unpacked-tar5=/test/TEST.ROOT --- openjdk-8-8u392-ga/=unpacked-tar5=/test/TEST.ROOT 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/test/TEST.ROOT 2024-01-18 10:40:14.000000000 +0000 @@ -37,3 +37,7 @@ requires.properties=sun.arch.data.model \ vm.flavor \ vm.bits + +# Path to libraries in the topmost test directory. This is needed so @library +# does not need ../../ notation to reach them +external.lib.roots = ../../ diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/test/compiler/parsing/Custom.jasm openjdk-8-8u402-ga/=unpacked-tar5=/test/compiler/parsing/Custom.jasm --- openjdk-8-8u392-ga/=unpacked-tar5=/test/compiler/parsing/Custom.jasm 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/test/compiler/parsing/Custom.jasm 2024-01-18 10:40:14.000000000 +0000 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package compiler/parsing; + +super public class Custom { + + public static Method test:"(I)V" stack 2 locals 1 { + return; +Loop: + // Unreachable block + iload_0; + bipush 100; + if_icmpge Loop; + // Falls through + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/test/compiler/parsing/UnreachableBlockFallsThroughEndOfCode.java openjdk-8-8u402-ga/=unpacked-tar5=/test/compiler/parsing/UnreachableBlockFallsThroughEndOfCode.java --- openjdk-8-8u392-ga/=unpacked-tar5=/test/compiler/parsing/UnreachableBlockFallsThroughEndOfCode.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/test/compiler/parsing/UnreachableBlockFallsThroughEndOfCode.java 2024-01-18 10:40:14.000000000 +0000 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +/* + * @test UnreachableBlockFallsThroughEndOfCode.java + * @bug 8283441 + * @compile Custom.jasm UnreachableBlockFallsThroughEndOfCode.java + * @summary Compiling method that falls off the end of the code array + * @run main/othervm -XX:TieredStopAtLevel=1 -Xbatch compiler.parsing.UnreachableBlockFallsThroughEndOfCode + * @run main/othervm -XX:-TieredCompilation -Xbatch compiler.parsing.UnreachableBlockFallsThroughEndOfCode + */ + +package compiler.parsing; + +public class UnreachableBlockFallsThroughEndOfCode { + public static void main(String[] strArr) { + for (int i = 0; i < 20000; i++) { + Custom.test(i); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar5=/test/runtime/memory/ReserveMemory.java openjdk-8-8u402-ga/=unpacked-tar5=/test/runtime/memory/ReserveMemory.java --- openjdk-8-8u392-ga/=unpacked-tar5=/test/runtime/memory/ReserveMemory.java 2023-10-02 06:41:10.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar5=/test/runtime/memory/ReserveMemory.java 2024-01-18 10:40:14.000000000 +0000 @@ -21,10 +21,12 @@ * questions. */ +// Aix commits on touch, so this test won't work. /* * @test * @key regression * @bug 8012015 + * @requires !(os.family == "aix") * @summary Make sure reserved (but uncommitted) memory is not accessible * @library /testlibrary /testlibrary/whitebox * @build ReserveMemory @@ -37,14 +39,6 @@ import sun.hotspot.WhiteBox; public class ReserveMemory { - private static boolean isWindows() { - return System.getProperty("os.name").toLowerCase().startsWith("win"); - } - - private static boolean isOsx() { - return System.getProperty("os.name").toLowerCase().startsWith("mac"); - } - public static void main(String args[]) throws Exception { if (args.length > 0) { WhiteBox.getWhiteBox().readReservedMemory(); @@ -61,9 +55,9 @@ "test"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); - if (isWindows()) { + if (Platform.isWindows()) { output.shouldContain("EXCEPTION_ACCESS_VIOLATION"); - } else if (isOsx()) { + } else if (Platform.isOSX()) { output.shouldContain("SIGBUS"); } else { output.shouldContain("SIGSEGV"); diff -Nru openjdk-8-8u392-ga/=unpacked-tar7=/README openjdk-8-8u402-ga/=unpacked-tar7=/README --- openjdk-8-8u392-ga/=unpacked-tar7=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar7=/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -README: - - This file should be located at the top of the Mercurial repository. - - See http://openjdk.java.net/ for more information about the OpenJDK. - - See ../README-builds.html for complete details on build machine requirements. - -Simple Build Instructions: - This repository can be loaded as a NetBeans project, built with ant, or - built with GNU make, e.g. - ant - -OR- - cd make && gnumake - - The built files that will be imported into the jdk build will be in the - "dist" directory. - Help information is available by running "ant -projecthelp" or "make help". - diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/.github/workflows/submit.yml openjdk-8-8u402-ga/=unpacked-tar8=/.github/workflows/submit.yml --- openjdk-8-8u392-ga/=unpacked-tar8=/.github/workflows/submit.yml 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/.github/workflows/submit.yml 2024-01-11 01:53:23.000000000 +0000 @@ -277,7 +277,7 @@ run: > if cat test-results/testoutput/*/exitcode.txt | grep -q -v '^0$' || ! cat test-results/testoutput/*/Stats.txt | grep -q 'fail=0' ; then - cat test-results/testoutput/*/JTreport/text/newfailures.txt ; + cat test-results/testoutput/*/JTreport/text/{newfailures,other_errors}.txt ; exit 1 ; fi @@ -638,7 +638,7 @@ run: > if cat test-results/testoutput/*/exitcode.txt | grep -q -v '^0$' || ! cat test-results/testoutput/*/Stats.txt | grep -q 'fail=0' ; then - cat test-results/testoutput/*/JTreport/text/newfailures.txt ; + cat test-results/testoutput/*/JTreport/text/{newfailures,other_errors}.txt ; exit 1 ; fi @@ -1143,6 +1143,7 @@ run: > if ((Get-ChildItem -Path test-results\testoutput\*\exitcode.txt -Recurse | Select-String -Pattern '^0$' -NotMatch ).Count -gt 0) { Get-Content -Path test-results\testoutput\*\JTreport\text\newfailures.txt ; + Get-Content -Path test-results\testoutput\*\JTreport\text\other_errors.txt ; exit 1 } @@ -1299,6 +1300,7 @@ run: > if ((Get-ChildItem -Path test-results\testoutput\*\exitcode.txt -Recurse | Select-String -Pattern '^0$' -NotMatch ).Count -gt 0) { Get-Content -Path test-results\testoutput\*\JTreport\text\newfailures.txt ; + Get-Content -Path test-results\testoutput\*\JTreport\text\other_errors.txt ; exit 1 } @@ -1529,7 +1531,7 @@ run: > if cat test-results/testoutput/*/exitcode.txt | grep -q -v '^0$' || ! cat test-results/testoutput/*/Stats.txt | grep -q 'fail=0' ; then - cat test-results/testoutput/*/JTreport/text/newfailures.txt ; + cat test-results/testoutput/*/JTreport/text/{newfailures,other_errors}.txt ; exit 1 ; fi diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/.jcheck/conf openjdk-8-8u402-ga/=unpacked-tar8=/.jcheck/conf --- openjdk-8-8u392-ga/=unpacked-tar8=/.jcheck/conf 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/.jcheck/conf 2024-01-11 01:53:23.000000000 +0000 @@ -1,7 +1,7 @@ [general] project=jdk8u jbs=JDK -version=openjdk8u392 +version=openjdk8u402 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/README openjdk-8-8u402-ga/=unpacked-tar8=/README --- openjdk-8-8u392-ga/=unpacked-tar8=/README 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/README 2024-01-11 01:53:23.000000000 +0000 @@ -1,40 +1,10 @@ -README: - This file should be located at the top of the OpenJDK Mercurial root - repository. A full OpenJDK repository set (forest) should also include - the following 6 nested repositories: - "jdk", "hotspot", "langtools", "corba", "jaxws" and "jaxp". +Welcome to OpenJDK! +=================== - The root repository can be obtained with something like: - hg clone http://hg.openjdk.java.net/jdk8/jdk8 openjdk8 - - You can run the get_source.sh script located in the root repository to get - the other needed repositories: - cd openjdk8 && sh ./get_source.sh +For information about building OpenJDK, including how to fully retrieve all +source code, please see either of these: - People unfamiliar with Mercurial should read the first few chapters of - the Mercurial book: http://hgbook.red-bean.com/read/ + * doc/building.html (html version) + * doc/building.md (markdown version) - See http://openjdk.java.net/ for more information about OpenJDK. - -Simple Build Instructions: - - 0. Get the necessary system software/packages installed on your system, see - http://hg.openjdk.java.net/jdk8/jdk8/raw-file/tip/README-builds.html - - 1. If you don't have a jdk7u7 or newer jdk, download and install it from - http://java.sun.com/javase/downloads/index.jsp - Add the /bin directory of this installation to your PATH environment - variable. - - 2. Configure the build: - bash ./configure - - 3. Build the OpenJDK: - make all - The resulting JDK image should be found in build/*/images/j2sdk-image - -where make is GNU make 3.81 or newer, /usr/bin/make on Linux usually -is 3.81 or newer. Note that on Solaris, GNU make is called "gmake". - -Complete details are available in the file: - http://hg.openjdk.java.net/jdk8/jdk8/raw-file/tip/README-builds.html +See http://openjdk.java.net/ for more information about OpenJDK. diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/README-builds.html openjdk-8-8u402-ga/=unpacked-tar8=/README-builds.html --- openjdk-8-8u392-ga/=unpacked-tar8=/README-builds.html 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/README-builds.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,1389 +0,0 @@ - - - OpenJDK Build README - - -

OpenJDK

- -

OpenJDK Build README

- -
- -

- -

Introduction

- -

This README file contains build instructions for the -OpenJDK. Building the source code for the OpenJDK -requires a certain degree of technical expertise.

- -

!!!!!!!!!!!!!!! THIS IS A MAJOR RE-WRITE of this document. !!!!!!!!!!!!!

- -

Some Headlines:

- -
    -
  • The build is now a "configure && make" style build
  • -
  • Any GNU make 3.81 or newer should work
  • -
  • The build should scale, i.e. more processors should cause the build to be -done in less wall-clock time
  • -
  • Nested or recursive make invocations have been significantly reduced, -as has the total fork/exec or spawning of sub processes during the build
  • -
  • Windows MKS usage is no longer supported
  • -
  • Windows Visual Studio vsvars*.bat and vcvars*.bat files are run -automatically
  • -
  • Ant is no longer used when building the OpenJDK
  • -
  • Use of ALT_* environment variables for configuring the build is no longer -supported
  • -
- -
- -

Contents

- - - -
- - - -
- -

- -

Use of Mercurial

- -

The OpenJDK sources are maintained with the revision control system -Mercurial. If you are new to -Mercurial, please see the Beginner Guides or refer to the Mercurial Book. -The first few chapters of the book provide an excellent overview of Mercurial, -what it is and how it works.

- -

For using Mercurial with the OpenJDK refer to the Developer Guide: Installing -and Configuring Mercurial section for more information.

- -

- -

Getting the Source

- -

To get the entire set of OpenJDK Mercurial repositories use the script -get_source.sh located in the root repository:

- -
  hg clone http://hg.openjdk.java.net/jdk8/jdk8 YourOpenJDK
-  cd YourOpenJDK
-  bash ./get_source.sh
-
- -

Once you have all the repositories, keep in mind that each repository is its -own independent repository. You can also re-run ./get_source.sh anytime to -pull over all the latest changesets in all the repositories. This set of -nested repositories has been given the term "forest" and there are various -ways to apply the same hg command to each of the repositories. For -example, the script make/scripts/hgforest.sh can be used to repeat the -same hg command on every repository, e.g.

- -
  cd YourOpenJDK
-  bash ./make/scripts/hgforest.sh status
-
- -

- -

Repositories

- -

The set of repositories and what they contain:

- -
    -
  • . (root) contains common configure and makefile logic
  • -
  • hotspot contains source code and make files for building the OpenJDK -Hotspot Virtual Machine
  • -
  • langtools contains source code for the OpenJDK javac and language tools
  • -
  • jdk contains source code and make files for building the OpenJDK runtime -libraries and misc files
  • -
  • jaxp contains source code for the OpenJDK JAXP functionality
  • -
  • jaxws contains source code for the OpenJDK JAX-WS functionality
  • -
  • corba contains source code for the OpenJDK Corba functionality
  • -
  • nashorn contains source code for the OpenJDK JavaScript implementation
  • -
- -

Repository Source Guidelines

- -

There are some very basic guidelines:

- -
    -
  • Use of whitespace in source files (.java, .c, .h, .cpp, and .hpp files) is -restricted. No TABs, no trailing whitespace on lines, and files should not -terminate in more than one blank line.
  • -
  • Files with execute permissions should not be added to the source -repositories.
  • -
  • All generated files need to be kept isolated from the files maintained or -managed by the source control system. The standard area for generated files -is the top level build/ directory.
  • -
  • The default build process should be to build the product and nothing else, -in one form, e.g. a product (optimized), debug (non-optimized, -g plus -assert logic), or fastdebug (optimized, -g plus assert logic).
  • -
  • The .hgignore file in each repository must exist and should include -^build/, ^dist/ and optionally any nbproject/private directories. It -should NEVER include anything in the src/ or test/ or any managed -directory area of a repository.
  • -
  • Directory names and file names should never contain blanks or non-printing -characters.
  • -
  • Generated source or binary files should NEVER be added to the repository -(that includes javah output). There are some exceptions to this rule, in -particular with some of the generated configure scripts.
  • -
  • Files not needed for typical building or testing of the repository should -not be added to the repository.
  • -
- -
- -

- -

Building

- -

The very first step in building the OpenJDK is making sure the system itself -has everything it needs to do OpenJDK builds. Once a system is setup, it -generally doesn't need to be done again.

- -

Building the OpenJDK is now done with running a configure script which will -try and find and verify you have everything you need, followed by running -make, e.g.

- -
-

bash ./configure
- make all

-
- -

Where possible the configure script will attempt to located the various -components in the default locations or via component specific variable -settings. When the normal defaults fail or components cannot be found, -additional configure options may be necessary to help configure find the -necessary tools for the build, or you may need to re-visit the setup of your -system due to missing software packages.

- -

NOTE: The configure script file does not have execute permissions and -will need to be explicitly run with bash, see the source guidelines.

- -
- -

- -

System Setup

- -

Before even attempting to use a system to build the OpenJDK there are some very -basic system setups needed. For all systems:

- -
    -
  • Be sure the GNU make utility is version 3.81 or newer, e.g. -run "make -version"

    - -

  • -
  • Install a Bootstrap JDK. All OpenJDK builds require access to a previously -released JDK called the bootstrap JDK or boot JDK. The general rule is -that the bootstrap JDK must be an instance of the previous major release of -the JDK. In addition, there may be a requirement to use a release at or -beyond a particular update level.

    - -

    Building JDK 8 requires use of a version of JDK 7 this is at Update 7 -or newer. JDK 8 developers should not use JDK 8 as the boot JDK, to ensure -that JDK 8 dependencies are not introduced into the parts of the system -that are built with JDK 7.

    - -

    The JDK 7 binaries can be downloaded from Oracle's JDK 7 download -site. -For build performance reasons it is very important that this bootstrap JDK -be made available on the local disk of the machine doing the build. You -should add its bin directory to the PATH environment variable. If -configure has any issues finding this JDK, you may need to use the -configure option --with-boot-jdk.

  • -
  • Ensure that GNU make, the Bootstrap JDK, and the compilers are all in your -PATH environment variable.

  • -
- -

And for specific systems:

- - - -

- -

Linux

- -

With Linux, try and favor the system packages over building your own or getting -packages from other areas. Most Linux builds should be possible with the -system's available packages.

- -

Note that some Linux systems have a habit of pre-populating your environment -variables for you, for example JAVA_HOME might get pre-defined for you to -refer to the JDK installed on your Linux system. You will need to unset -JAVA_HOME. It's a good idea to run env and verify the environment variables -you are getting from the default system settings make sense for building the -OpenJDK.

- -

- -

Solaris

- -

- -
Studio Compilers
- -

At a minimum, the Studio 12 Update 1 Compilers (containing -version 5.10 of the C and C++ compilers) is required, including specific -patches.

- -

The Solaris SPARC patch list is:

- -
    -
  • 118683-05: SunOS 5.10: Patch for profiling libraries and assembler
  • -
  • 119963-21: SunOS 5.10: Shared library patch for C++
  • -
  • 120753-08: SunOS 5.10: Microtasking libraries (libmtsk) patch
  • -
  • 128228-09: Sun Studio 12 Update 1: Patch for Sun C++ Compiler
  • -
  • 141860-03: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C -C++ F77 F95
  • -
  • 141861-05: Sun Studio 12 Update 1: Patch for Sun C Compiler
  • -
  • 142371-01: Sun Studio 12.1 Update 1: Patch for dbx
  • -
  • 143384-02: Sun Studio 12 Update 1: Patch for debuginfo handling
  • -
  • 143385-02: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C -C++ F77 F95
  • -
  • 142369-01: Sun Studio 12.1: Patch for Performance Analyzer Tools
  • -
- -

The Solaris X86 patch list is:

- -
    -
  • 119961-07: SunOS 5.10_x86, x64, Patch for profiling libraries and assembler
  • -
  • 119964-21: SunOS 5.10_x86: Shared library patch for C++_x86
  • -
  • 120754-08: SunOS 5.10_x86: Microtasking libraries (libmtsk) patch
  • -
  • 141858-06: Sun Studio 12 Update 1_x86: Sun Compiler Common patch for x86 -backend
  • -
  • 128229-09: Sun Studio 12 Update 1_x86: Patch for C++ Compiler
  • -
  • 142363-05: Sun Studio 12 Update 1_x86: Patch for C Compiler
  • -
  • 142368-01: Sun Studio 12.1_x86: Patch for Performance Analyzer Tools
  • -
- -

Place the bin directory in PATH.

- -

The Oracle Solaris Studio Express compilers at: Oracle Solaris Studio Express -Download site are also an option, although these compilers -have not been extensively used yet.

- -

- -

Windows

- -
Windows Unix Toolkit
- -

Building on Windows requires a Unix-like environment, notably a Unix-like -shell. There are several such environments available of which -Cygwin and -MinGW/MSYS are currently supported for the -OpenJDK build. One of the differences of these systems from standard Windows -tools is the way they handle Windows path names, particularly path names which -contain spaces, backslashes as path separators and possibly drive letters. -Depending on the use case and the specifics of each environment these path -problems can be solved by a combination of quoting whole paths, translating -backslashes to forward slashes, escaping backslashes with additional -backslashes and translating the path names to their "8.3" -version.

- -

- -
CYGWIN
- -

CYGWIN is an open source, Linux-like environment which tries to emulate a -complete POSIX layer on Windows. It tries to be smart about path names and can -usually handle all kinds of paths if they are correctly quoted or escaped -although internally it maps drive letters <drive>: to a virtual directory -/cygdrive/<drive>.

- -

You can always use the cygpath utility to map pathnames with spaces or the -backslash character into the C:/ style of pathname (called 'mixed'), e.g. -cygpath -s -m "<path>".

- -

Note that the use of CYGWIN creates a unique problem with regards to setting -PATH. Normally on Windows the PATH variable contains directories -separated with the ";" character (Solaris and Linux use ":"). With CYGWIN, it -uses ":", but that means that paths like "C:/path" cannot be placed in the -CYGWIN version of PATH and instead CYGWIN uses something like -/cygdrive/c/path which CYGWIN understands, but only CYGWIN understands.

- -

The OpenJDK build requires CYGWIN version 1.7.16 or newer. Information about -CYGWIN can be obtained from the CYGWIN website at -www.cygwin.com.

- -

By default CYGWIN doesn't install all the tools required for building the -OpenJDK. Along with the default installation, you need to install the following -tools.

- -
-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Binary NameCategoryPackageDescription
ar.exeDevelbinutilsThe GNU assembler, linker and binary utilities
make.exeDevelmakeThe GNU version of the 'make' utility built for CYGWIN
m4.exeInterpretersm4GNU implementation of the traditional Unix macro processor
cpio.exeUtilscpioA program to manage archives of files
gawk.exeUtilsawkPattern-directed scanning and processing language
file.exeUtilsfileDetermines file type using 'magic' numbers
zip.exeArchivezipPackage and compress (archive) files
unzip.exeArchiveunzipExtract compressed files in a ZIP archive
free.exeSystemprocpsDisplay amount of free and used memory in the system

-
- -

Note that the CYGWIN software can conflict with other non-CYGWIN software on -your Windows system. CYGWIN provides a FAQ for known issues and problems, of particular interest is the -section on BLODA (applications that interfere with -CYGWIN).

- -

- -
MinGW/MSYS
- -

MinGW ("Minimalist GNU for Windows") is a collection of free Windows specific -header files and import libraries combined with GNU toolsets that allow one to -produce native Windows programs that do not rely on any 3rd-party C runtime -DLLs. MSYS is a supplement to MinGW which allows building applications and -programs which rely on traditional UNIX tools to be present. Among others this -includes tools like bash and make. See MinGW/MSYS for more information.

- -

Like Cygwin, MinGW/MSYS can handle different types of path formats. They are -internally converted to paths with forward slashes and drive letters -<drive>: replaced by a virtual directory /<drive>. Additionally, MSYS -automatically detects binaries compiled for the MSYS environment and feeds them -with the internal, Unix-style path names. If native Windows applications are -called from within MSYS programs their path arguments are automatically -converted back to Windows style path names with drive letters and backslashes -as path separators. This may cause problems for Windows applications which use -forward slashes as parameter separator (e.g. cl /nologo /I) because MSYS may -wrongly replace such parameters by drive letters.

- -

In addition to the tools which will be installed by default, you have to -manually install the msys-zip and msys-unzip packages. This can be easily -done with the MinGW command line installer:

- -
  mingw-get.exe install msys-zip
-  mingw-get.exe install msys-unzip
-
- -

- -
Visual Studio 2010 Compilers
- -

The 32-bit and 64-bit OpenJDK Windows build requires Microsoft Visual Studio -C++ 2010 (VS2010) Professional Edition or Express compiler. The compiler and -other tools are expected to reside in the location defined by the variable -VS100COMNTOOLS which is set by the Microsoft Visual Studio installer.

- -

Only the C++ part of VS2010 is needed. Try to let the installation go to the -default install directory. Always reboot your system after installing VS2010. -The system environment variable VS100COMNTOOLS should be set in your -environment.

- -

Make sure that TMP and TEMP are also set in the environment and refer to -Windows paths that exist, like C:\temp, not /tmp, not /cygdrive/c/temp, -and not C:/temp. C:\temp is just an example, it is assumed that this area -is private to the user, so by default after installs you should see a unique -user path in these variables.

- -

- -

Mac OS X

- -

Make sure you get the right XCode version.

- -
- -

- -

Configure

- -

The basic invocation of the configure script looks like:

- -
-

bash ./configure [options]

-
- -

This will create an output directory containing the "configuration" and setup -an area for the build result. This directory typically looks like:

- -
-

build/linux-x64-normal-server-release

-
- -

configure will try to figure out what system you are running on and where all -necessary build components are. If you have all prerequisites for building -installed, it should find everything. If it fails to detect any component -automatically, it will exit and inform you about the problem. When this -happens, read more below in the configure options.

- -

Some examples:

- -
-

Windows 32bit build with freetype specified:
- bash ./configure --with-freetype=/cygdrive/c/freetype-i586 --with-target- -bits=32

- -

Debug 64bit Build:
- bash ./configure --enable-debug --with-target-bits=64

-
- -

- -

Configure Options

- -

Complete details on all the OpenJDK configure options can be seen with:

- -
-

bash ./configure --help=short

-
- -

Use -help to see all the configure options available. You can generate any -number of different configurations, e.g. debug, release, 32, 64, etc.

- -

Some of the more commonly used configure options are:

- -
-

--enable-debug
- set the debug level to fastdebug (this is a shorthand for --with-debug- - level=fastdebug)

-
- -

- -
-

--with-alsa=path
- select the location of the Advanced Linux Sound Architecture (ALSA)

- -

Version 0.9.1 or newer of the ALSA files are required for building the - OpenJDK on Linux. These Linux files are usually available from an "alsa" of - "libasound" development package, and it's highly recommended that you try - and use the package provided by the particular version of Linux that you are - using.

- -

--with-boot-jdk=path
- select the Bootstrap JDK

- -

--with-boot-jdk-jvmargs="args"
- provide the JVM options to be used to run the Bootstrap JDK

- -

--with-cacerts=path
- select the path to the cacerts file.

- -

See Certificate Authority on Wikipedia for a better understanding of the Certificate - Authority (CA). A certificates file named "cacerts" represents a system-wide - keystore with CA certificates. In JDK and JRE binary bundles, the "cacerts" - file contains root CA certificates from several public CAs (e.g., VeriSign, - Thawte, and Baltimore). The source contain a cacerts file without CA root - certificates. Formal JDK builders will need to secure permission from each - public CA and include the certificates into their own custom cacerts file. - Failure to provide a populated cacerts file will result in verification - errors of a certificate chain during runtime. By default an empty cacerts - file is provided and that should be fine for most JDK developers.

-
- -

- -
-

--with-cups=path
- select the CUPS install location

- -

The Common UNIX Printing System (CUPS) Headers are required for building the - OpenJDK on Solaris and Linux. The Solaris header files can be obtained by - installing the package SFWcups from the Solaris Software Companion - CD/DVD, these often will be installed into the directory /opt/sfw/cups.

- -

The CUPS header files can always be downloaded from - www.cups.org.

- -

--with-cups-include=path
- select the CUPS include directory location

- -

--with-debug-level=level
- select the debug information level of release, fastdebug, or slowdebug

- -

--with-dev-kit=path
- select location of the compiler install or developer install location

-
- -

- -
-

--with-freetype=path
- select the freetype files to use.

- -

Expecting the freetype libraries under lib/ and the headers under - include/.

- -

Version 2.3 or newer of FreeType is required. On Unix systems required files - can be available as part of your distribution (while you still may need to - upgrade them). Note that you need development version of package that - includes both the FreeType library and header files.

- -

You can always download latest FreeType version from the FreeType - website. Building the freetype 2 libraries from - scratch is also possible, however on Windows refer to the Windows FreeType - DLL build instructions.

- -

Note that by default FreeType is built with byte code hinting support - disabled due to licensing restrictions. In this case, text appearance and - metrics are expected to differ from Sun's official JDK build. See the - SourceForge FreeType2 Home Page - for more information.

- -

--with-import-hotspot=path
- select the location to find hotspot binaries from a previous build to avoid - building hotspot

- -

--with-target-bits=arg
- select 32 or 64 bit build

- -

--with-jvm-variants=variants
- select the JVM variants to build from, comma separated list that can - include: server, client, kernel, zero and zeroshark

- -

--with-memory-size=size
- select the RAM size that GNU make will think this system has

- -

--with-msvcr-dll=path
- select the msvcr100.dll file to include in the Windows builds (C/C++ - runtime library for Visual Studio).

- -

This is usually picked up automatically from the redist directories of - Visual Studio 2010.

- -

--with-num-cores=cores
- select the number of cores to use (processor count or CPU count)

-
- -

- -
-

--with-x=path
- select the location of the X11 and xrender files.

- -

The XRender Extension Headers are required for building the OpenJDK on - Solaris and Linux. The Linux header files are usually available from a - "Xrender" development package, it's recommended that you try and use the - package provided by the particular distribution of Linux that you are using. - The Solaris XRender header files is included with the other X11 header files - in the package SFWxwinc on new enough versions of Solaris and will be - installed in /usr/X11/include/X11/extensions/Xrender.h or - /usr/openwin/share/include/X11/extensions/Xrender.h

-
- -
- -

- -

Make

- -

The basic invocation of the make utility looks like:

- -
-

make all

-
- -

This will start the build to the output directory containing the -"configuration" that was created by the configure script. Run make help for -more information on the available targets.

- -

There are some of the make targets that are of general interest:

- -
-

empty
- build everything but no images

- -

all
- build everything including images

- -

all-conf
- build all configurations

- -

images
- create complete j2sdk and j2re images

- -

install
- install the generated images locally, typically in /usr/local

- -

clean
- remove all files generated by make, but not those generated by configure

- -

dist-clean
- remove all files generated by both and configure (basically killing the - configuration)

- -

help
- give some help on using make, including some interesting make targets

-
- -
- -

- -

Testing

- -

When the build is completed, you should see the generated binaries and -associated files in the j2sdk-image directory in the output directory. In -particular, the build/*/images/j2sdk-image/bin directory should contain -executables for the OpenJDK tools and utilities for that configuration. The -testing tool jtreg will be needed and can be found at: the jtreg -site. The provided regression tests in the -repositories can be run with the command:

- -
-

cd test && make PRODUCT_HOME=`pwd`/../build/*/images/j2sdk-image all

-
- -
- -

- -

Appendix A: Hints and Tips

- -

- -

FAQ

- -

Q: The generated-configure.sh file looks horrible! How are you going to -edit it?
-A: The generated-configure.sh file is generated (think "compiled") by the -autoconf tools. The source code is in configure.ac and various .m4 files in -common/autoconf, which are much more readable.

- -

Q: Why is the generated-configure.sh file checked in, if it is -generated?
-A: If it was not generated, every user would need to have the autoconf -tools installed, and re-generate the configure file as the first step. Our -goal is to minimize the work needed to be done by the user to start building -OpenJDK, and to minimize the number of external dependencies required.

- -

Q: Do you require a specific version of autoconf for regenerating -generated-configure.sh?
-A: Yes, version 2.69 is required and should be easy enough to aquire on all -supported operating systems. The reason for this is to avoid large spurious -changes in generated-configure.sh.

- -

Q: How do you regenerate generated-configure.sh after making changes to -the input files?
-A: Regnerating generated-configure.sh should always be done using the -script common/autoconf/autogen.sh to ensure that the correct files get -updated. This script should also be run after mercurial tries to merge -generated-configure.sh as a merge of the generated file is not guaranteed to -be correct.

- -

Q: What are the files in common/makefiles/support/* for? They look like -gibberish.
-A: They are a somewhat ugly hack to compensate for command line length -limitations on certain platforms (Windows, Solaris). Due to a combination of -limitations in make and the shell, command lines containing too many files will -not work properly. These helper files are part of an elaborate hack that will -compress the command line in the makefile and then uncompress it safely. We're -not proud of it, but it does fix the problem. If you have any better -suggestions, we're all ears! :-)

- -

Q: I want to see the output of the commands that make runs, like in the old -build. How do I do that?
-A: You specify the LOG variable to make. There are several log levels:

- -
    -
  • warn -- Default and very quiet.
  • -
  • info -- Shows more progress information than warn.
  • -
  • debug -- Echos all command lines and prints all macro calls for -compilation definitions.
  • -
  • trace -- Echos all $(shell) command lines as well.
  • -
- -

Q: When do I have to re-run configure?
-A: Normally you will run configure only once for creating a -configuration. You need to re-run configuration only if you want to change any -configuration options, or if you pull down changes to the configure script.

- -

Q: I have added a new source file. Do I need to modify the makefiles?
-A: Normally, no. If you want to create e.g. a new native library, you will -need to modify the makefiles. But for normal file additions or removals, no -changes are needed. There are certan exceptions for some native libraries where -the source files are spread over many directories which also contain sources -for other libraries. In these cases it was simply easier to create include -lists rather than excludes.

- -

Q: When I run configure --help, I see many strange options, like ---dvidir. What is this?
-A: Configure provides a slew of options by default, to all projects that -use autoconf. Most of them are not used in OpenJDK, so you can safely ignore -them. To list only OpenJDK specific features, use configure --help=short -instead.

- -

Q: configure provides OpenJDK-specific features such as --with- -builddeps-server that are not described in this document. What about those?
-A: Try them out if you like! But be aware that most of these are -experimental features. Many of them don't do anything at all at the moment; the -option is just a placeholder. Others depend on pieces of code or infrastructure -that is currently not ready for prime time.

- -

Q: How will you make sure you don't break anything?
-A: We have a script that compares the result of the new build system with -the result of the old. For most part, we aim for (and achieve) byte-by-byte -identical output. There are however technical issues with e.g. native binaries, -which might differ in a byte-by-byte comparison, even when building twice with -the old build system. For these, we compare relevant aspects (e.g. the symbol -table and file size). Note that we still don't have 100% equivalence, but we're -close.

- -

Q: I noticed this thing X in the build that looks very broken by design. -Why don't you fix it?
-A: Our goal is to produce a build output that is as close as technically -possible to the old build output. If things were weird in the old build, they -will be weird in the new build. Often, things were weird before due to -obscurity, but in the new build system the weird stuff comes up to the surface. -The plan is to attack these things at a later stage, after the new build system -is established.

- -

Q: The code in the new build system is not that well-structured. Will you -fix this?
-A: Yes! The new build system has grown bit by bit as we converted the old -system. When all of the old build system is converted, we can take a step back -and clean up the structure of the new build system. Some of this we plan to do -before replacing the old build system and some will need to wait until after.

- -

Q: Is anything able to use the results of the new build's default make -target?
-A: Yes, this is the minimal (or roughly minimal) set of compiled output -needed for a developer to actually execute the newly built JDK. The idea is -that in an incremental development fashion, when doing a normal make, you -should only spend time recompiling what's changed (making it purely -incremental) and only do the work that's needed to actually run and test your -code. The packaging stuff that is part of the images target is not needed for -a normal developer who wants to test his new code. Even if it's quite fast, -it's still unnecessary. We're targeting sub-second incremental rebuilds! ;-) -(Or, well, at least single-digit seconds...)

- -

Q: I usually set a specific environment variable when building, but I can't -find the equivalent in the new build. What should I do?
-A: It might very well be that we have neglected to add support for an -option that was actually used from outside the build system. Email us and we -will add support for it!

- -

- -

Build Performance Tips

- -

Building OpenJDK requires a lot of horsepower. Some of the build tools can be -adjusted to utilize more or less of resources such as parallel threads and -memory. The configure script analyzes your system and selects reasonable -values for such options based on your hardware. If you encounter resource -problems, such as out of memory conditions, you can modify the detected values -with:

- -
    -
  • --with-num-cores -- number of cores in the build system, e.g. ---with-num-cores=8
  • -
  • --with-memory-size -- memory (in MB) available in the build system, -e.g. --with-memory-size=1024
  • -
- -

It might also be necessary to specify the JVM arguments passed to the Bootstrap -JDK, using e.g. --with-boot-jdk-jvmargs="-Xmx8G -enableassertions". Doing -this will override the default JVM arguments passed to the Bootstrap JDK.

- -

One of the top goals of the new build system is to improve the build -performance and decrease the time needed to build. This will soon also apply to -the java compilation when the Smart Javac wrapper is making its way into jdk8. -It can be tried in the build-infra repository already. You are likely to find -that the new build system is faster than the old one even without this feature.

- -

At the end of a successful execution of configure, you will get a performance -summary, indicating how well the build will perform. Here you will also get -performance hints. If you want to build fast, pay attention to those!

- -

Building with ccache

- -

A simple way to radically speed up compilation of native code -(typically hotspot and native libraries in JDK) is to install -ccache. This will cache and reuse prior compilation results, if the -source code is unchanged. However, ccache versions prior to 3.1.4 does -not work correctly with the precompiled headers used in OpenJDK. So if -your platform supports ccache at 3.1.4 or later, we highly recommend -installing it. This is currently only supported on linux.

- -

Building on local disk

- -

If you are using network shares, e.g. via NFS, for your source code, make sure -the build directory is situated on local disk. The performance penalty is -extremely high for building on a network share, close to unusable.

- -

Building only one JVM

- -

The old build builds multiple JVMs on 32-bit systems (client and server; and on -Windows kernel as well). In the new build we have changed this default to only -build server when it's available. This improves build times for those not -interested in multiple JVMs. To mimic the old behavior on platforms that -support it, use --with-jvm-variants=client,server.

- -

Selecting the number of cores to build on

- -

By default, configure will analyze your machine and run the make process in -parallel with as many threads as you have cores. This behavior can be -overridden, either "permanently" (on a configure basis) using ---with-num-cores=N or for a single build only (on a make basis), using -make JOBS=N.

- -

If you want to make a slower build just this time, to save some CPU power for -other processes, you can run e.g. make JOBS=2. This will force the makefiles -to only run 2 parallel processes, or even make JOBS=1 which will disable -parallelism.

- -

If you want to have it the other way round, namely having slow builds default -and override with fast if you're impatient, you should call configure with ---with-num-cores=2, making 2 the default. If you want to run with more cores, -run make JOBS=8

- -

- -

Troubleshooting

- -

Solving build problems

- -

If the build fails (and it's not due to a compilation error in a source file -you've changed), the first thing you should do is to re-run the build with more -verbosity. Do this by adding LOG=debug to your make command line.

- -

The build log (with both stdout and stderr intermingled, basically the same as -you see on your console) can be found as build.log in your build directory.

- -

You can ask for help on build problems with the new build system on either the -build-dev or the -build-infra-dev -mailing lists. Please include the relevant parts of the build log.

- -

A build can fail for any number of reasons. Most failures are a result of -trying to build in an environment in which all the pre-build requirements have -not been met. The first step in troubleshooting a build failure is to recheck -that you have satisfied all the pre-build requirements for your platform. -Scanning the configure log is a good first step, making sure that what it -found makes sense for your system. Look for strange error messages or any -difficulties that configure had in finding things.

- -

Some of the more common problems with builds are briefly described below, with -suggestions for remedies.

- -
    -
  • Corrupted Bundles on Windows:
    -Some virus scanning software has been known to corrupt the downloading of -zip bundles. It may be necessary to disable the 'on access' or 'real time' -virus scanning features to prevent this corruption. This type of 'real time' -virus scanning can also slow down the build process significantly. -Temporarily disabling the feature, or excluding the build output directory -may be necessary to get correct and faster builds.

  • -
  • Slow Builds:
    -If your build machine seems to be overloaded from too many simultaneous C++ -compiles, try setting the JOBS=1 on the make command line. Then try -increasing the count slowly to an acceptable level for your system. Also:

    - -

    Creating the javadocs can be very slow, if you are running javadoc, consider -skipping that step.

    - -

    Faster CPUs, more RAM, and a faster DISK usually helps. The VM build tends -to be CPU intensive (many C++ compiles), and the rest of the JDK will often -be disk intensive.

    - -

    Faster compiles are possible using a tool called -ccache.

  • -
  • File time issues:
    -If you see warnings that refer to file time stamps, e.g.

    - -
    -

    Warning message: File 'xxx' has modification time in the future.
    -Warning message: Clock skew detected. Your build may be incomplete.

    -
    - -

    These warnings can occur when the clock on the build machine is out of sync -with the timestamps on the source files. Other errors, apparently unrelated -but in fact caused by the clock skew, can occur along with the clock skew -warnings. These secondary errors may tend to obscure the fact that the true -root cause of the problem is an out-of-sync clock.

    - -

    If you see these warnings, reset the clock on the build machine, run -"gmake clobber" or delete the directory containing the build output, and -restart the build from the beginning.

  • -
  • Error message: Trouble writing out table to disk
    -Increase the amount of swap space on your build machine. This could be -caused by overloading the system and it may be necessary to use:

    - -
    -

    make JOBS=1

    -
    - -

    to reduce the load on the system.

  • -
  • Error Message: libstdc++ not found:
    -This is caused by a missing libstdc++.a library. This is installed as part -of a specific package (e.g. libstdc++.so.devel.386). By default some 64-bit -Linux versions (e.g. Fedora) only install the 64-bit version of the -libstdc++ package. Various parts of the JDK build require a static link of -the C++ runtime libraries to allow for maximum portability of the built -images.

  • -
  • Linux Error Message: cannot restore segment prot after reloc
    -This is probably an issue with SELinux (See SELinux on -Wikipedia). Parts of the VM is built -without the -fPIC for performance reasons.

    - -

    To completely disable SELinux:

    - -
      -
    1. $ su root
    2. -
    3. # system-config-securitylevel
    4. -
    5. In the window that appears, select the SELinux tab
    6. -
    7. Disable SELinux
    8. -
    - -

    Alternatively, instead of completely disabling it you could disable just -this one check.

    - -
      -
    1. Select System->Administration->SELinux Management
    2. -
    3. In the SELinux Management Tool which appears, select "Boolean" from the -menu on the left
    4. -
    5. Expand the "Memory Protection" group
    6. -
    7. Check the first item, labeled "Allow all unconfined executables to use -libraries requiring text relocation ..."
    8. -
  • -
  • Windows Error Messages:
    -*** fatal error - couldn't allocate heap, ...
    -rm fails with "Directory not empty"
    -unzip fails with "cannot create ... Permission denied"
    -unzip fails with "cannot create ... Error 50"

    - -

    The CYGWIN software can conflict with other non-CYGWIN software. See the -CYGWIN FAQ section on BLODA (applications that interfere with -CYGWIN).

  • -
  • Windows Error Message: spawn failed
    -Try rebooting the system, or there could be some kind of issue with the disk -or disk partition being used. Sometimes it comes with a "Permission Denied" -message.

  • -
- -
- -

- -

Appendix B: GNU make

- -

The Makefiles in the OpenJDK are only valid when used with the GNU version of -the utility command make (usually called gmake on Solaris). A few notes -about using GNU make:

- -
    -
  • You need GNU make version 3.81 or newer. If the GNU make utility on your -systems is not 3.81 or newer, see "Building GNU make".
  • -
  • Place the location of the GNU make binary in the PATH.
  • -
  • Solaris: Do NOT use /usr/bin/make on Solaris. If your Solaris system -has the software from the Solaris Developer Companion CD installed, you -should try and use gmake which will be located in either the /usr/bin, -/opt/sfw/bin or /usr/sfw/bin directory.
  • -
  • Windows: Make sure you start your build inside a bash shell.
  • -
  • Mac OS X: The XCode "command line tools" must be installed on your Mac.
  • -
- -

Information on GNU make, and access to ftp download sites, are available on the -GNU make web site . The latest -source to GNU make is available at -ftp.gnu.org/pub/gnu/make/.

- -

- -

Building GNU make

- -

First step is to get the GNU make 3.81 or newer source from -ftp.gnu.org/pub/gnu/make/. Building is a -little different depending on the OS but is basically done with:

- -
  bash ./configure
-  make
-
- -
- -

- -

Appendix C: Build Environments

- -

Minimum Build Environments

- -

This file often describes specific requirements for what we call the "minimum -build environments" (MBE) for this specific release of the JDK. What is listed -below is what the Oracle Release Engineering Team will use to build the Oracle -JDK product. Building with the MBE will hopefully generate the most compatible -bits that install on, and run correctly on, the most variations of the same -base OS and hardware architecture. In some cases, these represent what is often -called the least common denominator, but each Operating System has different -aspects to it.

- -

In all cases, the Bootstrap JDK version minimum is critical, we cannot -guarantee builds will work with older Bootstrap JDK's. Also in all cases, more -RAM and more processors is better, the minimums listed below are simply -recommendations.

- -

With Solaris and Mac OS X, the version listed below is the oldest release we -can guarantee builds and works, and the specific version of the compilers used -could be critical.

- -

With Windows the critical aspect is the Visual Studio compiler used, which due -to it's runtime, generally dictates what Windows systems can do the builds and -where the resulting bits can be used.

- -

NOTE: We expect a change here off these older Windows OS releases and to a -'less older' one, probably Windows 2008R2 X64.

- -

With Linux, it was just a matter of picking a stable distribution that is a -good representative for Linux in general.

- -

NOTE: We expect a change here from Fedora 9 to something else, but it has not -been completely determined yet, possibly Ubuntu 12.04 X64, unbiased community -feedback would be welcome on what a good choice would be here.

- -

It is understood that most developers will NOT be using these specific -versions, and in fact creating these specific versions may be difficult due to -the age of some of this software. It is expected that developers are more often -using the more recent releases and distributions of these operating systems.

- -

Compilation problems with newer or different C/C++ compilers is a common -problem. Similarly, compilation problems related to changes to the -/usr/include or system header files is also a common problem with older, -newer, or unreleased OS versions. Please report these types of problems as bugs -so that they can be dealt with accordingly.

- -
-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Base OS and ArchitectureOSC/C++ CompilerBootstrap JDKProcessorsRAM MinimumDISK Needs
Linux X86 (32-bit) and X64 (64-bit)Fedora 9gcc 4.3 JDK 7u72 or more1 GB6 GB
Solaris SPARC (32-bit) and SPARCV9 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patchesJDK 7u74 or more4 GB8 GB
Solaris X86 (32-bit) and X64 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patchesJDK 7u74 or more4 GB8 GB
Windows X86 (32-bit)Windows XPMicrosoft Visual Studio C++ 2010 Professional EditionJDK 7u72 or more2 GB6 GB
Windows X64 (64-bit)Windows Server 2003 - Enterprise x64 EditionMicrosoft Visual Studio C++ 2010 Professional EditionJDK 7u72 or more2 GB6 GB
Mac OS X X64 (64-bit)Mac OS X 10.7 "Lion"XCode 4.5.2 or newerJDK 7u72 or more4 GB6 GB

-
- -
- -

- -

Specific Developer Build Environments

- -

We won't be listing all the possible environments, but we will try to provide -what information we have available to us.

- -

NOTE: The community can help out by updating this part of the document.

- -

Fedora

- -

After installing the latest Fedora you need to -install several build dependencies. The simplest way to do it is to execute the -following commands as user root:

- -
  yum-builddep java-1.7.0-openjdk
-  yum install gcc gcc-c++
-
- -

In addition, it's necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/usr/lib/jvm/java-openjdk/bin:${PATH}"
-
- -

CentOS 5.5

- -

After installing CentOS 5.5 you need to make sure you -have the following Development bundles installed:

- -
    -
  • Development Libraries
  • -
  • Development Tools
  • -
  • Java Development
  • -
  • X Software Development (Including XFree86-devel)
  • -
- -

Plus the following packages:

- -
    -
  • cups devel: Cups Development Package
  • -
  • alsa devel: Alsa Development Package
  • -
  • Xi devel: libXi.so Development Package
  • -
- -

The freetype 2.3 packages don't seem to be available, but the freetype 2.3 -sources can be downloaded, built, and installed easily enough from the -freetype site. Build and install -with something like:

- -
  bash ./configure
-  make
-  sudo -u root make install
-
- -

Mercurial packages could not be found easily, but a Google search should find -ones, and they usually include Python if it's needed.

- -

Debian 5.0 (Lenny)

- -

After installing Debian 5 you need to install several -build dependencies. The simplest way to install the build dependencies is to -execute the following commands as user root:

- -
  aptitude build-dep openjdk-7
-  aptitude install openjdk-7-jdk libmotif-dev
-
- -

In addition, it's necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}"
-
- -

Ubuntu 12.04

- -

After installing Ubuntu 12.04 you need to install several -build dependencies. The simplest way to do it is to execute the following -commands:

- -
  sudo aptitude build-dep openjdk-7
-  sudo aptitude install openjdk-7-jdk
-
- -

In addition, it's necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}"
-
- -

OpenSUSE 11.1

- -

After installing OpenSUSE 11.1 you need to install -several build dependencies. The simplest way to install the build dependencies -is to execute the following commands:

- -
  sudo zypper source-install -d java-1_7_0-openjdk
-  sudo zypper install make
-
- -

In addition, it is necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:$[PATH}"
-
- -

Finally, you need to unset the JAVA_HOME environment variable:

- -
  export -n JAVA_HOME`
-
- -

Mandriva Linux One 2009 Spring

- -

After installing Mandriva Linux One 2009 Spring you need -to install several build dependencies. The simplest way to install the build -dependencies is to execute the following commands as user root:

- -
  urpmi java-1.7.0-openjdk-devel make gcc gcc-c++ freetype-devel zip unzip
-    libcups2-devel libxrender1-devel libalsa2-devel libstc++-static-devel
-    libxtst6-devel libxi-devel
-
- -

In addition, it is necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:${PATH}"
-
- -

OpenSolaris 2009.06

- -

After installing OpenSolaris 2009.06 you need to -install several build dependencies. The simplest way to install the build -dependencies is to execute the following commands:

- -
  pfexec pkg install SUNWgmake SUNWj7dev sunstudioexpress SUNWcups SUNWzip
-    SUNWunzip SUNWxwhl SUNWxorg-headers SUNWaudh SUNWfreetype2
-
- -

In addition, it is necessary to set a few environment variables for the build:

- -
  export LANG=C
-  export PATH="/opt/SunStudioExpress/bin:${PATH}"
-
- -
- -

End of the OpenJDK build README document.

- -

Please come again!

- - diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/README-builds.md openjdk-8-8u402-ga/=unpacked-tar8=/README-builds.md --- openjdk-8-8u392-ga/=unpacked-tar8=/README-builds.md 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/README-builds.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,1266 +0,0 @@ -![OpenJDK](http://openjdk.java.net/images/openjdk.png) -# OpenJDK Build README - -***** - - -## Introduction - -This README file contains build instructions for the -[OpenJDK](http://openjdk.java.net). Building the source code for the OpenJDK -requires a certain degree of technical expertise. - -### !!!!!!!!!!!!!!! THIS IS A MAJOR RE-WRITE of this document. !!!!!!!!!!!!! - -Some Headlines: - - * The build is now a "`configure && make`" style build - * Any GNU make 3.81 or newer should work - * The build should scale, i.e. more processors should cause the build to be - done in less wall-clock time - * Nested or recursive make invocations have been significantly reduced, - as has the total fork/exec or spawning of sub processes during the build - * Windows MKS usage is no longer supported - * Windows Visual Studio `vsvars*.bat` and `vcvars*.bat` files are run - automatically - * Ant is no longer used when building the OpenJDK - * Use of ALT_* environment variables for configuring the build is no longer - supported - -***** - -## Contents - - * [Introduction](#introduction) - * [Use of Mercurial](#hg) - * [Getting the Source](#get_source) - * [Repositories](#repositories) - * [Building](#building) - * [System Setup](#setup) - * [Linux](#linux) - * [Solaris](#solaris) - * [Mac OS X](#macosx) - * [Windows](#windows) - * [Configure](#configure) - * [Make](#make) - * [Testing](#testing) - -***** - - * [Appendix A: Hints and Tips](#hints) - * [FAQ](#faq) - * [Build Performance Tips](#performance) - * [Troubleshooting](#troubleshooting) - * [Appendix B: GNU Make Information](#gmake) - * [Appendix C: Build Environments](#buildenvironments) - -***** - - -## Use of Mercurial - -The OpenJDK sources are maintained with the revision control system -[Mercurial](http://mercurial.selenic.com/wiki/Mercurial). If you are new to -Mercurial, please see the [Beginner Guides](http://mercurial.selenic.com/wiki/ -BeginnersGuides) or refer to the [Mercurial Book](http://hgbook.red-bean.com/). -The first few chapters of the book provide an excellent overview of Mercurial, -what it is and how it works. - -For using Mercurial with the OpenJDK refer to the [Developer Guide: Installing -and Configuring Mercurial](http://openjdk.java.net/guide/ -repositories.html#installConfig) section for more information. - - -### Getting the Source - -To get the entire set of OpenJDK Mercurial repositories use the script -`get_source.sh` located in the root repository: - - hg clone http://hg.openjdk.java.net/jdk8/jdk8 YourOpenJDK - cd YourOpenJDK - bash ./get_source.sh - -Once you have all the repositories, keep in mind that each repository is its -own independent repository. You can also re-run `./get_source.sh` anytime to -pull over all the latest changesets in all the repositories. This set of -nested repositories has been given the term "forest" and there are various -ways to apply the same `hg` command to each of the repositories. For -example, the script `make/scripts/hgforest.sh` can be used to repeat the -same `hg` command on every repository, e.g. - - cd YourOpenJDK - bash ./make/scripts/hgforest.sh status - - -### Repositories - -The set of repositories and what they contain: - - * **. (root)** contains common configure and makefile logic - * **hotspot** contains source code and make files for building the OpenJDK - Hotspot Virtual Machine - * **langtools** contains source code for the OpenJDK javac and language tools - * **jdk** contains source code and make files for building the OpenJDK runtime - libraries and misc files - * **jaxp** contains source code for the OpenJDK JAXP functionality - * **jaxws** contains source code for the OpenJDK JAX-WS functionality - * **corba** contains source code for the OpenJDK Corba functionality - * **nashorn** contains source code for the OpenJDK JavaScript implementation - -### Repository Source Guidelines - -There are some very basic guidelines: - - * Use of whitespace in source files (.java, .c, .h, .cpp, and .hpp files) is - restricted. No TABs, no trailing whitespace on lines, and files should not - terminate in more than one blank line. - * Files with execute permissions should not be added to the source - repositories. - * All generated files need to be kept isolated from the files maintained or - managed by the source control system. The standard area for generated files - is the top level `build/` directory. - * The default build process should be to build the product and nothing else, - in one form, e.g. a product (optimized), debug (non-optimized, -g plus - assert logic), or fastdebug (optimized, -g plus assert logic). - * The `.hgignore` file in each repository must exist and should include - `^build/`, `^dist/` and optionally any `nbproject/private` directories. **It - should NEVER** include anything in the `src/` or `test/` or any managed - directory area of a repository. - * Directory names and file names should never contain blanks or non-printing - characters. - * Generated source or binary files should NEVER be added to the repository - (that includes `javah` output). There are some exceptions to this rule, in - particular with some of the generated configure scripts. - * Files not needed for typical building or testing of the repository should - not be added to the repository. - -***** - - -## Building - -The very first step in building the OpenJDK is making sure the system itself -has everything it needs to do OpenJDK builds. Once a system is setup, it -generally doesn't need to be done again. - -Building the OpenJDK is now done with running a `configure` script which will -try and find and verify you have everything you need, followed by running -`make`, e.g. - -> **`bash ./configure`** -> **`make all`** - -Where possible the `configure` script will attempt to located the various -components in the default locations or via component specific variable -settings. When the normal defaults fail or components cannot be found, -additional `configure` options may be necessary to help `configure` find the -necessary tools for the build, or you may need to re-visit the setup of your -system due to missing software packages. - -**NOTE:** The `configure` script file does not have execute permissions and -will need to be explicitly run with `bash`, see the source guidelines. - -***** - - -### System Setup - -Before even attempting to use a system to build the OpenJDK there are some very -basic system setups needed. For all systems: - - * Be sure the GNU make utility is version 3.81 or newer, e.g. - run "`make -version`" - - - * Install a Bootstrap JDK. All OpenJDK builds require access to a previously - released JDK called the _bootstrap JDK_ or _boot JDK._ The general rule is - that the bootstrap JDK must be an instance of the previous major release of - the JDK. In addition, there may be a requirement to use a release at or - beyond a particular update level. - - **_Building JDK 8 requires use of a version of JDK 7 this is at Update 7 - or newer. JDK 8 developers should not use JDK 8 as the boot JDK, to ensure - that JDK 8 dependencies are not introduced into the parts of the system - that are built with JDK 7._** - - The JDK 7 binaries can be downloaded from Oracle's [JDK 7 download - site](http://www.oracle.com/technetwork/java/javase/downloads/index.html). - For build performance reasons it is very important that this bootstrap JDK - be made available on the local disk of the machine doing the build. You - should add its `bin` directory to the `PATH` environment variable. If - `configure` has any issues finding this JDK, you may need to use the - `configure` option `--with-boot-jdk`. - - * Ensure that GNU make, the Bootstrap JDK, and the compilers are all in your - PATH environment variable. - -And for specific systems: - - * **Linux** - - Install all the software development packages needed including - [alsa](#alsa), [freetype](#freetype), [cups](#cups), and - [xrender](#xrender). See [specific system packages](#SDBE). - - * **Solaris** - - Install all the software development packages needed including [Studio - Compilers](#studio), [freetype](#freetype), [cups](#cups), and - [xrender](#xrender). See [specific system packages](#SDBE). - - * **Windows** - - * Install one of [CYGWIN](#cygwin) or [MinGW/MSYS](#msys) - * Install [Visual Studio 2010](#vs2010) - - * **Mac OS X** - - Install [XCode 4.5.2](https://developer.apple.com/xcode/) and also - install the "Command line tools" found under the preferences pane - "Downloads" - - -#### Linux - -With Linux, try and favor the system packages over building your own or getting -packages from other areas. Most Linux builds should be possible with the -system's available packages. - -Note that some Linux systems have a habit of pre-populating your environment -variables for you, for example `JAVA_HOME` might get pre-defined for you to -refer to the JDK installed on your Linux system. You will need to unset -`JAVA_HOME`. It's a good idea to run `env` and verify the environment variables -you are getting from the default system settings make sense for building the -OpenJDK. - - -#### Solaris - - -##### Studio Compilers - -At a minimum, the [Studio 12 Update 1 Compilers](http://www.oracle.com/ -technetwork/server-storage/solarisstudio/downloads/index.htm) (containing -version 5.10 of the C and C++ compilers) is required, including specific -patches. - -The Solaris SPARC patch list is: - - * 118683-05: SunOS 5.10: Patch for profiling libraries and assembler - * 119963-21: SunOS 5.10: Shared library patch for C++ - * 120753-08: SunOS 5.10: Microtasking libraries (libmtsk) patch - * 128228-09: Sun Studio 12 Update 1: Patch for Sun C++ Compiler - * 141860-03: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C - C++ F77 F95 - * 141861-05: Sun Studio 12 Update 1: Patch for Sun C Compiler - * 142371-01: Sun Studio 12.1 Update 1: Patch for dbx - * 143384-02: Sun Studio 12 Update 1: Patch for debuginfo handling - * 143385-02: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C - C++ F77 F95 - * 142369-01: Sun Studio 12.1: Patch for Performance Analyzer Tools - -The Solaris X86 patch list is: - - * 119961-07: SunOS 5.10_x86, x64, Patch for profiling libraries and assembler - * 119964-21: SunOS 5.10_x86: Shared library patch for C++\_x86 - * 120754-08: SunOS 5.10_x86: Microtasking libraries (libmtsk) patch - * 141858-06: Sun Studio 12 Update 1_x86: Sun Compiler Common patch for x86 - backend - * 128229-09: Sun Studio 12 Update 1_x86: Patch for C++ Compiler - * 142363-05: Sun Studio 12 Update 1_x86: Patch for C Compiler - * 142368-01: Sun Studio 12.1_x86: Patch for Performance Analyzer Tools - -Place the `bin` directory in `PATH`. - -The Oracle Solaris Studio Express compilers at: [Oracle Solaris Studio Express -Download site](http://www.oracle.com/technetwork/server-storage/solarisstudio/ -downloads/index-jsp-142582.html) are also an option, although these compilers -have not been extensively used yet. - - -#### Windows - -##### Windows Unix Toolkit - -Building on Windows requires a Unix-like environment, notably a Unix-like -shell. There are several such environments available of which -[Cygwin](http://www.cygwin.com/) and -[MinGW/MSYS](http://www.mingw.org/wiki/MSYS) are currently supported for the -OpenJDK build. One of the differences of these systems from standard Windows -tools is the way they handle Windows path names, particularly path names which -contain spaces, backslashes as path separators and possibly drive letters. -Depending on the use case and the specifics of each environment these path -problems can be solved by a combination of quoting whole paths, translating -backslashes to forward slashes, escaping backslashes with additional -backslashes and translating the path names to their ["8.3" -version](http://en.wikipedia.org/wiki/8.3_filename). - - -###### CYGWIN - -CYGWIN is an open source, Linux-like environment which tries to emulate a -complete POSIX layer on Windows. It tries to be smart about path names and can -usually handle all kinds of paths if they are correctly quoted or escaped -although internally it maps drive letters `:` to a virtual directory -`/cygdrive/`. - -You can always use the `cygpath` utility to map pathnames with spaces or the -backslash character into the `C:/` style of pathname (called 'mixed'), e.g. -`cygpath -s -m ""`. - -Note that the use of CYGWIN creates a unique problem with regards to setting -[`PATH`](#path). Normally on Windows the `PATH` variable contains directories -separated with the ";" character (Solaris and Linux use ":"). With CYGWIN, it -uses ":", but that means that paths like "C:/path" cannot be placed in the -CYGWIN version of `PATH` and instead CYGWIN uses something like -`/cygdrive/c/path` which CYGWIN understands, but only CYGWIN understands. - -The OpenJDK build requires CYGWIN version 1.7.16 or newer. Information about -CYGWIN can be obtained from the CYGWIN website at -[www.cygwin.com](http://www.cygwin.com). - -By default CYGWIN doesn't install all the tools required for building the -OpenJDK. Along with the default installation, you need to install the following -tools. - -> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Binary NameCategoryPackageDescription
ar.exeDevelbinutilsThe GNU assembler, linker and binary utilities
make.exeDevelmakeThe GNU version of the 'make' utility built for CYGWIN
m4.exeInterpretersm4GNU implementation of the traditional Unix macro processor
cpio.exeUtilscpioA program to manage archives of files
gawk.exeUtilsawkPattern-directed scanning and processing language
file.exeUtilsfileDetermines file type using 'magic' numbers
zip.exeArchivezipPackage and compress (archive) files
unzip.exeArchiveunzipExtract compressed files in a ZIP archive
free.exeSystemprocpsDisplay amount of free and used memory in the system
- -Note that the CYGWIN software can conflict with other non-CYGWIN software on -your Windows system. CYGWIN provides a [FAQ](http://cygwin.com/faq/ -faq.using.html) for known issues and problems, of particular interest is the -section on [BLODA (applications that interfere with -CYGWIN)](http://cygwin.com/faq/faq.using.html#faq.using.bloda). - - -###### MinGW/MSYS - -MinGW ("Minimalist GNU for Windows") is a collection of free Windows specific -header files and import libraries combined with GNU toolsets that allow one to -produce native Windows programs that do not rely on any 3rd-party C runtime -DLLs. MSYS is a supplement to MinGW which allows building applications and -programs which rely on traditional UNIX tools to be present. Among others this -includes tools like `bash` and `make`. See [MinGW/MSYS](http://www.mingw.org/ -wiki/MSYS) for more information. - -Like Cygwin, MinGW/MSYS can handle different types of path formats. They are -internally converted to paths with forward slashes and drive letters -`:` replaced by a virtual directory `/`. Additionally, MSYS -automatically detects binaries compiled for the MSYS environment and feeds them -with the internal, Unix-style path names. If native Windows applications are -called from within MSYS programs their path arguments are automatically -converted back to Windows style path names with drive letters and backslashes -as path separators. This may cause problems for Windows applications which use -forward slashes as parameter separator (e.g. `cl /nologo /I`) because MSYS may -wrongly [replace such parameters by drive letters](http://mingw.org/wiki/ -Posix_path_conversion). - -In addition to the tools which will be installed by default, you have to -manually install the `msys-zip` and `msys-unzip` packages. This can be easily -done with the MinGW command line installer: - - mingw-get.exe install msys-zip - mingw-get.exe install msys-unzip - - -##### Visual Studio 2010 Compilers - -The 32-bit and 64-bit OpenJDK Windows build requires Microsoft Visual Studio -C++ 2010 (VS2010) Professional Edition or Express compiler. The compiler and -other tools are expected to reside in the location defined by the variable -`VS100COMNTOOLS` which is set by the Microsoft Visual Studio installer. - -Only the C++ part of VS2010 is needed. Try to let the installation go to the -default install directory. Always reboot your system after installing VS2010. -The system environment variable VS100COMNTOOLS should be set in your -environment. - -Make sure that TMP and TEMP are also set in the environment and refer to -Windows paths that exist, like `C:\temp`, not `/tmp`, not `/cygdrive/c/temp`, -and not `C:/temp`. `C:\temp` is just an example, it is assumed that this area -is private to the user, so by default after installs you should see a unique -user path in these variables. - - -#### Mac OS X - -Make sure you get the right XCode version. - -***** - - -### Configure - -The basic invocation of the `configure` script looks like: - -> **`bash ./configure [options]`** - -This will create an output directory containing the "configuration" and setup -an area for the build result. This directory typically looks like: - -> **`build/linux-x64-normal-server-release`** - -`configure` will try to figure out what system you are running on and where all -necessary build components are. If you have all prerequisites for building -installed, it should find everything. If it fails to detect any component -automatically, it will exit and inform you about the problem. When this -happens, read more below in [the `configure` options](#configureoptions). - -Some examples: - -> **Windows 32bit build with freetype specified:** -> `bash ./configure --with-freetype=/cygdrive/c/freetype-i586 --with-target- -bits=32` - -> **Debug 64bit Build:** -> `bash ./configure --enable-debug --with-target-bits=64` - - -#### Configure Options - -Complete details on all the OpenJDK `configure` options can be seen with: - -> **`bash ./configure --help=short`** - -Use `-help` to see all the `configure` options available. You can generate any -number of different configurations, e.g. debug, release, 32, 64, etc. - -Some of the more commonly used `configure` options are: - -> **`--enable-debug`** -> set the debug level to fastdebug (this is a shorthand for `--with-debug- - level=fastdebug`) - - -> **`--with-alsa=`**_path_ -> select the location of the Advanced Linux Sound Architecture (ALSA) - -> Version 0.9.1 or newer of the ALSA files are required for building the - OpenJDK on Linux. These Linux files are usually available from an "alsa" of - "libasound" development package, and it's highly recommended that you try - and use the package provided by the particular version of Linux that you are - using. - -> **`--with-boot-jdk=`**_path_ -> select the [Bootstrap JDK](#bootjdk) - -> **`--with-boot-jdk-jvmargs=`**"_args_" -> provide the JVM options to be used to run the [Bootstrap JDK](#bootjdk) - -> **`--with-cacerts=`**_path_ -> select the path to the cacerts file. - -> See [Certificate Authority on Wikipedia](http://en.wikipedia.org/wiki/ - Certificate_Authority) for a better understanding of the Certificate - Authority (CA). A certificates file named "cacerts" represents a system-wide - keystore with CA certificates. In JDK and JRE binary bundles, the "cacerts" - file contains root CA certificates from several public CAs (e.g., VeriSign, - Thawte, and Baltimore). The source contain a cacerts file without CA root - certificates. Formal JDK builders will need to secure permission from each - public CA and include the certificates into their own custom cacerts file. - Failure to provide a populated cacerts file will result in verification - errors of a certificate chain during runtime. By default an empty cacerts - file is provided and that should be fine for most JDK developers. - - -> **`--with-cups=`**_path_ -> select the CUPS install location - -> The Common UNIX Printing System (CUPS) Headers are required for building the - OpenJDK on Solaris and Linux. The Solaris header files can be obtained by - installing the package **SFWcups** from the Solaris Software Companion - CD/DVD, these often will be installed into the directory `/opt/sfw/cups`. - -> The CUPS header files can always be downloaded from - [www.cups.org](http://www.cups.org). - -> **`--with-cups-include=`**_path_ -> select the CUPS include directory location - -> **`--with-debug-level=`**_level_ -> select the debug information level of release, fastdebug, or slowdebug - -> **`--with-dev-kit=`**_path_ -> select location of the compiler install or developer install location - - -> **`--with-freetype=`**_path_ -> select the freetype files to use. - -> Expecting the freetype libraries under `lib/` and the headers under - `include/`. - -> Version 2.3 or newer of FreeType is required. On Unix systems required files - can be available as part of your distribution (while you still may need to - upgrade them). Note that you need development version of package that - includes both the FreeType library and header files. - -> You can always download latest FreeType version from the [FreeType - website](http://www.freetype.org). Building the freetype 2 libraries from - scratch is also possible, however on Windows refer to the [Windows FreeType - DLL build instructions](http://freetype.freedesktop.org/wiki/FreeType_DLL). - -> Note that by default FreeType is built with byte code hinting support - disabled due to licensing restrictions. In this case, text appearance and - metrics are expected to differ from Sun's official JDK build. See the - [SourceForge FreeType2 Home Page](http://freetype.sourceforge.net/freetype2) - for more information. - -> **`--with-import-hotspot=`**_path_ -> select the location to find hotspot binaries from a previous build to avoid - building hotspot - -> **`--with-target-bits=`**_arg_ -> select 32 or 64 bit build - -> **`--with-jvm-variants=`**_variants_ -> select the JVM variants to build from, comma separated list that can - include: server, client, kernel, zero and zeroshark - -> **`--with-memory-size=`**_size_ -> select the RAM size that GNU make will think this system has - -> **`--with-msvcr-dll=`**_path_ -> select the `msvcr100.dll` file to include in the Windows builds (C/C++ - runtime library for Visual Studio). - -> This is usually picked up automatically from the redist directories of - Visual Studio 2010. - -> **`--with-num-cores=`**_cores_ -> select the number of cores to use (processor count or CPU count) - - -> **`--with-x=`**_path_ -> select the location of the X11 and xrender files. - -> The XRender Extension Headers are required for building the OpenJDK on - Solaris and Linux. The Linux header files are usually available from a - "Xrender" development package, it's recommended that you try and use the - package provided by the particular distribution of Linux that you are using. - The Solaris XRender header files is included with the other X11 header files - in the package **SFWxwinc** on new enough versions of Solaris and will be - installed in `/usr/X11/include/X11/extensions/Xrender.h` or - `/usr/openwin/share/include/X11/extensions/Xrender.h` - -***** - - -### Make - -The basic invocation of the `make` utility looks like: - -> **`make all`** - -This will start the build to the output directory containing the -"configuration" that was created by the `configure` script. Run `make help` for -more information on the available targets. - -There are some of the make targets that are of general interest: - -> _empty_ -> build everything but no images - -> **`all`** -> build everything including images - -> **`all-conf`** -> build all configurations - -> **`images`** -> create complete j2sdk and j2re images - -> **`install`** -> install the generated images locally, typically in `/usr/local` - -> **`clean`** -> remove all files generated by make, but not those generated by `configure` - -> **`dist-clean`** -> remove all files generated by both and `configure` (basically killing the - configuration) - -> **`help`** -> give some help on using `make`, including some interesting make targets - -***** - - -## Testing - -When the build is completed, you should see the generated binaries and -associated files in the `j2sdk-image` directory in the output directory. In -particular, the `build/*/images/j2sdk-image/bin` directory should contain -executables for the OpenJDK tools and utilities for that configuration. The -testing tool `jtreg` will be needed and can be found at: [the jtreg -site](http://openjdk.java.net/jtreg/). The provided regression tests in the -repositories can be run with the command: - -> **``cd test && make PRODUCT_HOME=`pwd`/../build/*/images/j2sdk-image all``** - -***** - - -## Appendix A: Hints and Tips - - -### FAQ - -**Q:** The `generated-configure.sh` file looks horrible! How are you going to -edit it? -**A:** The `generated-configure.sh` file is generated (think "compiled") by the -autoconf tools. The source code is in `configure.ac` and various .m4 files in -common/autoconf, which are much more readable. - -**Q:** Why is the `generated-configure.sh` file checked in, if it is -generated? -**A:** If it was not generated, every user would need to have the autoconf -tools installed, and re-generate the `configure` file as the first step. Our -goal is to minimize the work needed to be done by the user to start building -OpenJDK, and to minimize the number of external dependencies required. - -**Q:** Do you require a specific version of autoconf for regenerating -`generated-configure.sh`? -**A:** Yes, version 2.69 is required and should be easy enough to aquire on all -supported operating systems. The reason for this is to avoid large spurious -changes in `generated-configure.sh`. - -**Q:** How do you regenerate `generated-configure.sh` after making changes to -the input files? -**A:** Regnerating `generated-configure.sh` should always be done using the -script `common/autoconf/autogen.sh` to ensure that the correct files get -updated. This script should also be run after mercurial tries to merge -`generated-configure.sh` as a merge of the generated file is not guaranteed to -be correct. - -**Q:** What are the files in `common/makefiles/support/*` for? They look like -gibberish. -**A:** They are a somewhat ugly hack to compensate for command line length -limitations on certain platforms (Windows, Solaris). Due to a combination of -limitations in make and the shell, command lines containing too many files will -not work properly. These helper files are part of an elaborate hack that will -compress the command line in the makefile and then uncompress it safely. We're -not proud of it, but it does fix the problem. If you have any better -suggestions, we're all ears! :-) - -**Q:** I want to see the output of the commands that make runs, like in the old -build. How do I do that? -**A:** You specify the `LOG` variable to make. There are several log levels: - - * **`warn`** -- Default and very quiet. - * **`info`** -- Shows more progress information than warn. - * **`debug`** -- Echos all command lines and prints all macro calls for - compilation definitions. - * **`trace`** -- Echos all $(shell) command lines as well. - -**Q:** When do I have to re-run `configure`? -**A:** Normally you will run `configure` only once for creating a -configuration. You need to re-run configuration only if you want to change any -configuration options, or if you pull down changes to the `configure` script. - -**Q:** I have added a new source file. Do I need to modify the makefiles? -**A:** Normally, no. If you want to create e.g. a new native library, you will -need to modify the makefiles. But for normal file additions or removals, no -changes are needed. There are certan exceptions for some native libraries where -the source files are spread over many directories which also contain sources -for other libraries. In these cases it was simply easier to create include -lists rather than excludes. - -**Q:** When I run `configure --help`, I see many strange options, like -`--dvidir`. What is this? -**A:** Configure provides a slew of options by default, to all projects that -use autoconf. Most of them are not used in OpenJDK, so you can safely ignore -them. To list only OpenJDK specific features, use `configure --help=short` -instead. - -**Q:** `configure` provides OpenJDK-specific features such as `--with- -builddeps-server` that are not described in this document. What about those? -**A:** Try them out if you like! But be aware that most of these are -experimental features. Many of them don't do anything at all at the moment; the -option is just a placeholder. Others depend on pieces of code or infrastructure -that is currently not ready for prime time. - -**Q:** How will you make sure you don't break anything? -**A:** We have a script that compares the result of the new build system with -the result of the old. For most part, we aim for (and achieve) byte-by-byte -identical output. There are however technical issues with e.g. native binaries, -which might differ in a byte-by-byte comparison, even when building twice with -the old build system. For these, we compare relevant aspects (e.g. the symbol -table and file size). Note that we still don't have 100% equivalence, but we're -close. - -**Q:** I noticed this thing X in the build that looks very broken by design. -Why don't you fix it? -**A:** Our goal is to produce a build output that is as close as technically -possible to the old build output. If things were weird in the old build, they -will be weird in the new build. Often, things were weird before due to -obscurity, but in the new build system the weird stuff comes up to the surface. -The plan is to attack these things at a later stage, after the new build system -is established. - -**Q:** The code in the new build system is not that well-structured. Will you -fix this? -**A:** Yes! The new build system has grown bit by bit as we converted the old -system. When all of the old build system is converted, we can take a step back -and clean up the structure of the new build system. Some of this we plan to do -before replacing the old build system and some will need to wait until after. - -**Q:** Is anything able to use the results of the new build's default make -target? -**A:** Yes, this is the minimal (or roughly minimal) set of compiled output -needed for a developer to actually execute the newly built JDK. The idea is -that in an incremental development fashion, when doing a normal make, you -should only spend time recompiling what's changed (making it purely -incremental) and only do the work that's needed to actually run and test your -code. The packaging stuff that is part of the `images` target is not needed for -a normal developer who wants to test his new code. Even if it's quite fast, -it's still unnecessary. We're targeting sub-second incremental rebuilds! ;-) -(Or, well, at least single-digit seconds...) - -**Q:** I usually set a specific environment variable when building, but I can't -find the equivalent in the new build. What should I do? -**A:** It might very well be that we have neglected to add support for an -option that was actually used from outside the build system. Email us and we -will add support for it! - - -### Build Performance Tips - -Building OpenJDK requires a lot of horsepower. Some of the build tools can be -adjusted to utilize more or less of resources such as parallel threads and -memory. The `configure` script analyzes your system and selects reasonable -values for such options based on your hardware. If you encounter resource -problems, such as out of memory conditions, you can modify the detected values -with: - - * **`--with-num-cores`** -- number of cores in the build system, e.g. - `--with-num-cores=8` - * **`--with-memory-size`** -- memory (in MB) available in the build system, - e.g. `--with-memory-size=1024` - -It might also be necessary to specify the JVM arguments passed to the Bootstrap -JDK, using e.g. `--with-boot-jdk-jvmargs="-Xmx8G -enableassertions"`. Doing -this will override the default JVM arguments passed to the Bootstrap JDK. - -One of the top goals of the new build system is to improve the build -performance and decrease the time needed to build. This will soon also apply to -the java compilation when the Smart Javac wrapper is making its way into jdk8. -It can be tried in the build-infra repository already. You are likely to find -that the new build system is faster than the old one even without this feature. - -At the end of a successful execution of `configure`, you will get a performance -summary, indicating how well the build will perform. Here you will also get -performance hints. If you want to build fast, pay attention to those! - -#### Building with ccache - -A simple way to radically speed up compilation of native code -(typically hotspot and native libraries in JDK) is to install -ccache. This will cache and reuse prior compilation results, if the -source code is unchanged. However, ccache versions prior to 3.1.4 does -not work correctly with the precompiled headers used in OpenJDK. So if -your platform supports ccache at 3.1.4 or later, we highly recommend -installing it. This is currently only supported on linux. - -#### Building on local disk - -If you are using network shares, e.g. via NFS, for your source code, make sure -the build directory is situated on local disk. The performance penalty is -extremely high for building on a network share, close to unusable. - -#### Building only one JVM - -The old build builds multiple JVMs on 32-bit systems (client and server; and on -Windows kernel as well). In the new build we have changed this default to only -build server when it's available. This improves build times for those not -interested in multiple JVMs. To mimic the old behavior on platforms that -support it, use `--with-jvm-variants=client,server`. - -#### Selecting the number of cores to build on - -By default, `configure` will analyze your machine and run the make process in -parallel with as many threads as you have cores. This behavior can be -overridden, either "permanently" (on a `configure` basis) using -`--with-num-cores=N` or for a single build only (on a make basis), using -`make JOBS=N`. - -If you want to make a slower build just this time, to save some CPU power for -other processes, you can run e.g. `make JOBS=2`. This will force the makefiles -to only run 2 parallel processes, or even `make JOBS=1` which will disable -parallelism. - -If you want to have it the other way round, namely having slow builds default -and override with fast if you're impatient, you should call `configure` with -`--with-num-cores=2`, making 2 the default. If you want to run with more cores, -run `make JOBS=8` - - -### Troubleshooting - -#### Solving build problems - -If the build fails (and it's not due to a compilation error in a source file -you've changed), the first thing you should do is to re-run the build with more -verbosity. Do this by adding `LOG=debug` to your make command line. - -The build log (with both stdout and stderr intermingled, basically the same as -you see on your console) can be found as `build.log` in your build directory. - -You can ask for help on build problems with the new build system on either the -[build-dev](http://mail.openjdk.java.net/mailman/listinfo/build-dev) or the -[build-infra-dev](http://mail.openjdk.java.net/mailman/listinfo/build-infra-dev) -mailing lists. Please include the relevant parts of the build log. - -A build can fail for any number of reasons. Most failures are a result of -trying to build in an environment in which all the pre-build requirements have -not been met. The first step in troubleshooting a build failure is to recheck -that you have satisfied all the pre-build requirements for your platform. -Scanning the `configure` log is a good first step, making sure that what it -found makes sense for your system. Look for strange error messages or any -difficulties that `configure` had in finding things. - -Some of the more common problems with builds are briefly described below, with -suggestions for remedies. - - * **Corrupted Bundles on Windows:** - Some virus scanning software has been known to corrupt the downloading of - zip bundles. It may be necessary to disable the 'on access' or 'real time' - virus scanning features to prevent this corruption. This type of 'real time' - virus scanning can also slow down the build process significantly. - Temporarily disabling the feature, or excluding the build output directory - may be necessary to get correct and faster builds. - - * **Slow Builds:** - If your build machine seems to be overloaded from too many simultaneous C++ - compiles, try setting the `JOBS=1` on the `make` command line. Then try - increasing the count slowly to an acceptable level for your system. Also: - - Creating the javadocs can be very slow, if you are running javadoc, consider - skipping that step. - - Faster CPUs, more RAM, and a faster DISK usually helps. The VM build tends - to be CPU intensive (many C++ compiles), and the rest of the JDK will often - be disk intensive. - - Faster compiles are possible using a tool called - [ccache](http://ccache.samba.org/). - - * **File time issues:** - If you see warnings that refer to file time stamps, e.g. - - > _Warning message:_ ` File 'xxx' has modification time in the future.` - > _Warning message:_ ` Clock skew detected. Your build may be incomplete.` - - These warnings can occur when the clock on the build machine is out of sync - with the timestamps on the source files. Other errors, apparently unrelated - but in fact caused by the clock skew, can occur along with the clock skew - warnings. These secondary errors may tend to obscure the fact that the true - root cause of the problem is an out-of-sync clock. - - If you see these warnings, reset the clock on the build machine, run - "`gmake clobber`" or delete the directory containing the build output, and - restart the build from the beginning. - - * **Error message: `Trouble writing out table to disk`** - Increase the amount of swap space on your build machine. This could be - caused by overloading the system and it may be necessary to use: - - > `make JOBS=1` - - to reduce the load on the system. - - * **Error Message: `libstdc++ not found`:** - This is caused by a missing libstdc++.a library. This is installed as part - of a specific package (e.g. libstdc++.so.devel.386). By default some 64-bit - Linux versions (e.g. Fedora) only install the 64-bit version of the - libstdc++ package. Various parts of the JDK build require a static link of - the C++ runtime libraries to allow for maximum portability of the built - images. - - * **Linux Error Message: `cannot restore segment prot after reloc`** - This is probably an issue with SELinux (See [SELinux on - Wikipedia](http://en.wikipedia.org/wiki/SELinux)). Parts of the VM is built - without the `-fPIC` for performance reasons. - - To completely disable SELinux: - - 1. `$ su root` - 2. `# system-config-securitylevel` - 3. `In the window that appears, select the SELinux tab` - 4. `Disable SELinux` - - Alternatively, instead of completely disabling it you could disable just - this one check. - - 1. Select System->Administration->SELinux Management - 2. In the SELinux Management Tool which appears, select "Boolean" from the - menu on the left - 3. Expand the "Memory Protection" group - 4. Check the first item, labeled "Allow all unconfined executables to use - libraries requiring text relocation ..." - - * **Windows Error Messages:** - `*** fatal error - couldn't allocate heap, ... ` - `rm fails with "Directory not empty"` - `unzip fails with "cannot create ... Permission denied"` - `unzip fails with "cannot create ... Error 50"` - - The CYGWIN software can conflict with other non-CYGWIN software. See the - CYGWIN FAQ section on [BLODA (applications that interfere with - CYGWIN)](http://cygwin.com/faq/faq.using.html#faq.using.bloda). - - * **Windows Error Message: `spawn failed`** - Try rebooting the system, or there could be some kind of issue with the disk - or disk partition being used. Sometimes it comes with a "Permission Denied" - message. - -***** - - -## Appendix B: GNU make - -The Makefiles in the OpenJDK are only valid when used with the GNU version of -the utility command `make` (usually called `gmake` on Solaris). A few notes -about using GNU make: - - * You need GNU make version 3.81 or newer. If the GNU make utility on your - systems is not 3.81 or newer, see "[Building GNU make](#buildgmake)". - * Place the location of the GNU make binary in the `PATH`. - * **Solaris:** Do NOT use `/usr/bin/make` on Solaris. If your Solaris system - has the software from the Solaris Developer Companion CD installed, you - should try and use `gmake` which will be located in either the `/usr/bin`, - `/opt/sfw/bin` or `/usr/sfw/bin` directory. - * **Windows:** Make sure you start your build inside a bash shell. - * **Mac OS X:** The XCode "command line tools" must be installed on your Mac. - -Information on GNU make, and access to ftp download sites, are available on the -[GNU make web site ](http://www.gnu.org/software/make/make.html). The latest -source to GNU make is available at -[ftp.gnu.org/pub/gnu/make/](http://ftp.gnu.org/pub/gnu/make/). - - -### Building GNU make - -First step is to get the GNU make 3.81 or newer source from -[ftp.gnu.org/pub/gnu/make/](http://ftp.gnu.org/pub/gnu/make/). Building is a -little different depending on the OS but is basically done with: - - bash ./configure - make - -***** - - -## Appendix C: Build Environments - -### Minimum Build Environments - -This file often describes specific requirements for what we call the "minimum -build environments" (MBE) for this specific release of the JDK. What is listed -below is what the Oracle Release Engineering Team will use to build the Oracle -JDK product. Building with the MBE will hopefully generate the most compatible -bits that install on, and run correctly on, the most variations of the same -base OS and hardware architecture. In some cases, these represent what is often -called the least common denominator, but each Operating System has different -aspects to it. - -In all cases, the Bootstrap JDK version minimum is critical, we cannot -guarantee builds will work with older Bootstrap JDK's. Also in all cases, more -RAM and more processors is better, the minimums listed below are simply -recommendations. - -With Solaris and Mac OS X, the version listed below is the oldest release we -can guarantee builds and works, and the specific version of the compilers used -could be critical. - -With Windows the critical aspect is the Visual Studio compiler used, which due -to it's runtime, generally dictates what Windows systems can do the builds and -where the resulting bits can be used. - -**NOTE: We expect a change here off these older Windows OS releases and to a -'less older' one, probably Windows 2008R2 X64.** - -With Linux, it was just a matter of picking a stable distribution that is a -good representative for Linux in general. - -**NOTE: We expect a change here from Fedora 9 to something else, but it has not -been completely determined yet, possibly Ubuntu 12.04 X64, unbiased community -feedback would be welcome on what a good choice would be here.** - -It is understood that most developers will NOT be using these specific -versions, and in fact creating these specific versions may be difficult due to -the age of some of this software. It is expected that developers are more often -using the more recent releases and distributions of these operating systems. - -Compilation problems with newer or different C/C++ compilers is a common -problem. Similarly, compilation problems related to changes to the -`/usr/include` or system header files is also a common problem with older, -newer, or unreleased OS versions. Please report these types of problems as bugs -so that they can be dealt with accordingly. - -> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Base OS and ArchitectureOSC/C++ CompilerBootstrap JDKProcessorsRAM MinimumDISK Needs
Linux X86 (32-bit) and X64 (64-bit)Fedora 9gcc 4.3 JDK 7u72 or more1 GB6 GB
Solaris SPARC (32-bit) and SPARCV9 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patchesJDK 7u74 or more4 GB8 GB
Solaris X86 (32-bit) and X64 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patchesJDK 7u74 or more4 GB8 GB
Windows X86 (32-bit)Windows XPMicrosoft Visual Studio C++ 2010 Professional EditionJDK 7u72 or more2 GB6 GB
Windows X64 (64-bit)Windows Server 2003 - Enterprise x64 EditionMicrosoft Visual Studio C++ 2010 Professional EditionJDK 7u72 or more2 GB6 GB
Mac OS X X64 (64-bit)Mac OS X 10.7 "Lion"XCode 4.5.2 or newerJDK 7u72 or more4 GB6 GB
- -***** - - -### Specific Developer Build Environments - -We won't be listing all the possible environments, but we will try to provide -what information we have available to us. - -**NOTE: The community can help out by updating this part of the document.** - -#### Fedora - -After installing the latest [Fedora](http://fedoraproject.org) you need to -install several build dependencies. The simplest way to do it is to execute the -following commands as user `root`: - - yum-builddep java-1.7.0-openjdk - yum install gcc gcc-c++ - -In addition, it's necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/usr/lib/jvm/java-openjdk/bin:${PATH}" - -#### CentOS 5.5 - -After installing [CentOS 5.5](http://www.centos.org/) you need to make sure you -have the following Development bundles installed: - - * Development Libraries - * Development Tools - * Java Development - * X Software Development (Including XFree86-devel) - -Plus the following packages: - - * cups devel: Cups Development Package - * alsa devel: Alsa Development Package - * Xi devel: libXi.so Development Package - -The freetype 2.3 packages don't seem to be available, but the freetype 2.3 -sources can be downloaded, built, and installed easily enough from [the -freetype site](http://downloads.sourceforge.net/freetype). Build and install -with something like: - - bash ./configure - make - sudo -u root make install - -Mercurial packages could not be found easily, but a Google search should find -ones, and they usually include Python if it's needed. - -#### Debian 5.0 (Lenny) - -After installing [Debian](http://debian.org) 5 you need to install several -build dependencies. The simplest way to install the build dependencies is to -execute the following commands as user `root`: - - aptitude build-dep openjdk-7 - aptitude install openjdk-7-jdk libmotif-dev - -In addition, it's necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}" - -#### Ubuntu 12.04 - -After installing [Ubuntu](http://ubuntu.org) 12.04 you need to install several -build dependencies. The simplest way to do it is to execute the following -commands: - - sudo aptitude build-dep openjdk-7 - sudo aptitude install openjdk-7-jdk - -In addition, it's necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}" - -#### OpenSUSE 11.1 - -After installing [OpenSUSE](http://opensuse.org) 11.1 you need to install -several build dependencies. The simplest way to install the build dependencies -is to execute the following commands: - - sudo zypper source-install -d java-1_7_0-openjdk - sudo zypper install make - -In addition, it is necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:$[PATH}" - -Finally, you need to unset the `JAVA_HOME` environment variable: - - export -n JAVA_HOME` - -#### Mandriva Linux One 2009 Spring - -After installing [Mandriva](http://mandriva.org) Linux One 2009 Spring you need -to install several build dependencies. The simplest way to install the build -dependencies is to execute the following commands as user `root`: - - urpmi java-1.7.0-openjdk-devel make gcc gcc-c++ freetype-devel zip unzip - libcups2-devel libxrender1-devel libalsa2-devel libstc++-static-devel - libxtst6-devel libxi-devel - -In addition, it is necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:${PATH}" - -#### OpenSolaris 2009.06 - -After installing [OpenSolaris](http://opensolaris.org) 2009.06 you need to -install several build dependencies. The simplest way to install the build -dependencies is to execute the following commands: - - pfexec pkg install SUNWgmake SUNWj7dev sunstudioexpress SUNWcups SUNWzip - SUNWunzip SUNWxwhl SUNWxorg-headers SUNWaudh SUNWfreetype2 - -In addition, it is necessary to set a few environment variables for the build: - - export LANG=C - export PATH="/opt/SunStudioExpress/bin:${PATH}" - -***** - -End of the OpenJDK build README document. - -Please come again! diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/basics.m4 openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/basics.m4 --- openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/basics.m4 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/basics.m4 2024-01-11 01:53:23.000000000 +0000 @@ -427,6 +427,7 @@ BASIC_PATH_PROGS(DF, df) BASIC_PATH_PROGS(SETFILE, SetFile) BASIC_PATH_PROGS(CPIO, [cpio bsdcpio]) + BASIC_PATH_PROGS(PANDOC, pandoc) ]) # Setup basic configuration paths, and platform-specific stuff related to PATHs. diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/generated-configure.sh openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/generated-configure.sh --- openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/generated-configure.sh 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/generated-configure.sh 2024-01-11 01:53:23.000000000 +0000 @@ -948,6 +948,7 @@ build_vendor build_cpu build +PANDOC CPIO SETFILE DF @@ -1016,7 +1017,6 @@ docdir oldincludedir includedir -runstatedir localstatedir sharedstatedir sysconfdir @@ -1178,6 +1178,7 @@ DF SETFILE CPIO +PANDOC UNZIP ZIP LDD @@ -1261,7 +1262,6 @@ sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' -runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' @@ -1514,15 +1514,6 @@ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; - -runstatedir | --runstatedir | --runstatedi | --runstated \ - | --runstate | --runstat | --runsta | --runst | --runs \ - | --run | --ru | --r) - ac_prev=runstatedir ;; - -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ - | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ - | --run=* | --ru=* | --r=*) - runstatedir=$ac_optarg ;; - -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ @@ -1660,7 +1651,7 @@ for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir runstatedir + libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. @@ -1813,7 +1804,6 @@ --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] @@ -2074,6 +2064,7 @@ DF Override default value for DF SETFILE Override default value for SETFILE CPIO Override default value for CPIO + PANDOC Override default value for PANDOC UNZIP Override default value for UNZIP ZIP Override default value for ZIP LDD Override default value for LDD @@ -4437,7 +4428,7 @@ #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1670219878 +DATE_WHEN_GENERATED=1694011184 ############################################################################### # @@ -13490,6 +13481,192 @@ fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tool_specified" >&5 $as_echo "$tool_specified" >&6; } + fi + fi + fi + + + + + # Publish this variable in the help. + + + if test "x$PANDOC" = x; then + # The variable is not set by user, try to locate tool using the code snippet + for ac_prog in pandoc +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PANDOC+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PANDOC in + [\\/]* | ?:[\\/]*) + ac_cv_path_PANDOC="$PANDOC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PANDOC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PANDOC=$ac_cv_path_PANDOC +if test -n "$PANDOC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PANDOC" >&5 +$as_echo "$PANDOC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$PANDOC" && break +done + + else + # The variable is set, but is it from the command line or the environment? + + # Try to remove the string !PANDOC! from our list. + try_remove_var=${CONFIGURE_OVERRIDDEN_VARIABLES//!PANDOC!/} + if test "x$try_remove_var" = "x$CONFIGURE_OVERRIDDEN_VARIABLES"; then + # If it failed, the variable was not from the command line. Ignore it, + # but warn the user (except for BASH, which is always set by the calling BASH). + if test "xPANDOC" != xBASH; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Ignoring value of PANDOC from the environment. Use command line variables instead." >&5 +$as_echo "$as_me: WARNING: Ignoring value of PANDOC from the environment. Use command line variables instead." >&2;} + fi + # Try to locate tool using the code snippet + for ac_prog in pandoc +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PANDOC+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PANDOC in + [\\/]* | ?:[\\/]*) + ac_cv_path_PANDOC="$PANDOC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PANDOC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PANDOC=$ac_cv_path_PANDOC +if test -n "$PANDOC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PANDOC" >&5 +$as_echo "$PANDOC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$PANDOC" && break +done + + else + # If it succeeded, then it was overridden by the user. We will use it + # for the tool. + + # First remove it from the list of overridden variables, so we can test + # for unknown variables in the end. + CONFIGURE_OVERRIDDEN_VARIABLES="$try_remove_var" + + # Check if the provided tool contains a complete path. + tool_specified="$PANDOC" + tool_basename="${tool_specified##*/}" + if test "x$tool_basename" = "x$tool_specified"; then + # A command without a complete path is provided, search $PATH. + { $as_echo "$as_me:${as_lineno-$LINENO}: Will search for user supplied tool PANDOC=$tool_basename" >&5 +$as_echo "$as_me: Will search for user supplied tool PANDOC=$tool_basename" >&6;} + # Extract the first word of "$tool_basename", so it can be a program name with args. +set dummy $tool_basename; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PANDOC+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PANDOC in + [\\/]* | ?:[\\/]*) + ac_cv_path_PANDOC="$PANDOC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PANDOC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PANDOC=$ac_cv_path_PANDOC +if test -n "$PANDOC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PANDOC" >&5 +$as_echo "$PANDOC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + if test "x$PANDOC" = x; then + as_fn_error $? "User supplied tool $tool_basename could not be found" "$LINENO" 5 + fi + else + # Otherwise we believe it is a complete path. Use it as it is. + { $as_echo "$as_me:${as_lineno-$LINENO}: Will use user supplied tool PANDOC=$tool_specified" >&5 +$as_echo "$as_me: Will use user supplied tool PANDOC=$tool_specified" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PANDOC" >&5 +$as_echo_n "checking for PANDOC... " >&6; } + if test ! -x "$tool_specified"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 +$as_echo "not found" >&6; } + as_fn_error $? "User supplied tool PANDOC=$tool_specified does not exist or is not executable" "$LINENO" 5 + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tool_specified" >&5 +$as_echo "$tool_specified" >&6; } fi fi fi diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/spec.gmk.in openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/spec.gmk.in --- openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/spec.gmk.in 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/spec.gmk.in 2024-01-11 01:53:23.000000000 +0000 @@ -549,6 +549,7 @@ MKDIR:=@MKDIR@ MV:=@MV@ NAWK:=@NAWK@ +PANDOC:=@PANDOC@ PRINTF:=@PRINTF@ PWD:=@THEPWDCMD@ RM:=@RM@ diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/version-numbers openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/version-numbers --- openjdk-8-8u392-ga/=unpacked-tar8=/common/autoconf/version-numbers 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/common/autoconf/version-numbers 2024-01-11 01:53:23.000000000 +0000 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ JDK_MAJOR_VERSION=1 JDK_MINOR_VERSION=8 JDK_MICRO_VERSION=0 -JDK_UPDATE_VERSION=392 +JDK_UPDATE_VERSION=402 LAUNCHER_NAME=openjdk PRODUCT_NAME=OpenJDK PRODUCT_SUFFIX="Runtime Environment" diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/common/bin/update-build-readme.sh openjdk-8-8u402-ga/=unpacked-tar8=/common/bin/update-build-readme.sh --- openjdk-8-8u392-ga/=unpacked-tar8=/common/bin/update-build-readme.sh 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/common/bin/update-build-readme.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -#!/bin/bash - -# Get an absolute path to this script, since that determines the top-level -# directory. -this_script_dir=`dirname $0` -TOPDIR=`cd $this_script_dir/../.. > /dev/null && pwd` - -GREP=grep -MD_FILE=$TOPDIR/README-builds.md -HTML_FILE=$TOPDIR/README-builds.html - -# Locate the markdown processor tool and check that it is the correct version. -locate_markdown_processor() { - if [ -z "$MARKDOWN" ]; then - MARKDOWN=`which markdown 2> /dev/null` - if [ -z "$MARKDOWN" ]; then - echo "Error: Cannot locate markdown processor" 1>&2 - exit 1 - fi - fi - - # Test version - MARKDOWN_VERSION=`$MARKDOWN -version | $GREP version` - if [ "x$MARKDOWN_VERSION" != "xThis is Markdown, version 1.0.1." ]; then - echo "Error: Expected markdown version 1.0.1." 1>&2 - echo "Actual version found: $MARKDOWN_VERSION" 1>&2 - echo "Download markdown here: https://daringfireball.net/projects/markdown/" 1>&2 - exit 1 - fi - -} - -# Verify that the source markdown file looks sound. -verify_source_code() { - TOO_LONG_LINES=`$GREP -E -e '^.{80}.+$' $MD_FILE` - if [ "x$TOO_LONG_LINES" != x ]; then - echo "Warning: The following lines are longer than 80 characters:" - $GREP -E -e '^.{80}.+$' $MD_FILE - fi -} - -# Convert the markdown file to html format. -process_source() { - echo "Generating html file from markdown" - cat > $HTML_FILE << END - - - OpenJDK Build README - - -END - ${MARKDOWN} $MD_FILE >> $HTML_FILE - cat >> $HTML_FILE < - -END - echo "Done" -} - -locate_markdown_processor -verify_source_code -process_source diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/doc/building.html openjdk-8-8u402-ga/=unpacked-tar8=/doc/building.html --- openjdk-8-8u392-ga/=unpacked-tar8=/doc/building.html 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/doc/building.html 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,715 @@ + + + + + + + OpenJDK Build README + + + + +
+

OpenJDK Build README

+
+
+OpenJDK
OpenJDK
+
+
+

Introduction

+

This README file contains build instructions for the OpenJDK. Building the source code for the OpenJDK requires a certain degree of technical expertise.

+

!!!!!!!!!!!!!!! THIS IS A MAJOR RE-WRITE of this document. !!!!!!!!!!!!!

+

Some Headlines:

+
    +
  • The build is now a “configure && make” style build
  • +
  • Any GNU make 3.81 or newer should work
  • +
  • The build should scale, i.e. more processors should cause the build to be done in less wall-clock time
  • +
  • Nested or recursive make invocations have been significantly reduced, as has the total fork/exec or spawning of sub processes during the build
  • +
  • Windows MKS usage is no longer supported
  • +
  • Windows Visual Studio vsvars*.bat and vcvars*.bat files are run automatically
  • +
  • Ant is no longer used when building the OpenJDK
  • +
  • Use of ALT_* environment variables for configuring the build is no longer supported
  • +
+
+

Contents

+ +
+ +
+

Use of Mercurial

+

The OpenJDK sources are maintained with the revision control system Mercurial. If you are new to Mercurial, please see the Beginner Guides or refer to the Mercurial Book. The first few chapters of the book provide an excellent overview of Mercurial, what it is and how it works.

+

For using Mercurial with the OpenJDK refer to the Developer Guide: Installing and Configuring Mercurial section for more information.

+

Getting the Source

+

To get the entire set of OpenJDK Mercurial repositories use the script get_source.sh located in the root repository:

+
  hg clone http://hg.openjdk.java.net/jdk8/jdk8 YourOpenJDK
+  cd YourOpenJDK
+  bash ./get_source.sh
+

Once you have all the repositories, keep in mind that each repository is its own independent repository. You can also re-run ./get_source.sh anytime to pull over all the latest changesets in all the repositories. This set of nested repositories has been given the term “forest” and there are various ways to apply the same hg command to each of the repositories. For example, the script make/scripts/hgforest.sh can be used to repeat the same hg command on every repository, e.g.

+
  cd YourOpenJDK
+  bash ./make/scripts/hgforest.sh status
+

Repositories

+

The set of repositories and what they contain:

+
    +
  • . (root) contains common configure and makefile logic
  • +
  • hotspot contains source code and make files for building the OpenJDK Hotspot Virtual Machine
  • +
  • langtools contains source code for the OpenJDK javac and language tools
  • +
  • jdk contains source code and make files for building the OpenJDK runtime libraries and misc files
  • +
  • jaxp contains source code for the OpenJDK JAXP functionality
  • +
  • jaxws contains source code for the OpenJDK JAX-WS functionality
  • +
  • corba contains source code for the OpenJDK Corba functionality
  • +
  • nashorn contains source code for the OpenJDK JavaScript implementation
  • +
+

Repository Source Guidelines

+

There are some very basic guidelines:

+
    +
  • Use of whitespace in source files (.java, .c, .h, .cpp, and .hpp files) is restricted. No TABs, no trailing whitespace on lines, and files should not terminate in more than one blank line.
  • +
  • Files with execute permissions should not be added to the source repositories.
  • +
  • All generated files need to be kept isolated from the files maintained or managed by the source control system. The standard area for generated files is the top level build/ directory.
  • +
  • The default build process should be to build the product and nothing else, in one form, e.g. a product (optimized), debug (non-optimized, -g plus assert logic), or fastdebug (optimized, -g plus assert logic).
  • +
  • The .hgignore file in each repository must exist and should include ^build/, ^dist/ and optionally any nbproject/private directories. It should NEVER include anything in the src/ or test/ or any managed directory area of a repository.
  • +
  • Directory names and file names should never contain blanks or non-printing characters.
  • +
  • Generated source or binary files should NEVER be added to the repository (that includes javah output). There are some exceptions to this rule, in particular with some of the generated configure scripts.
  • +
  • Files not needed for typical building or testing of the repository should not be added to the repository.
  • +
+
+

Building

+

The very first step in building the OpenJDK is making sure the system itself has everything it needs to do OpenJDK builds. Once a system is setup, it generally doesn’t need to be done again.

+

Building the OpenJDK is now done with running a configure script which will try and find and verify you have everything you need, followed by running make, e.g.

+
+

bash ./configure
+make all

+
+

Where possible the configure script will attempt to located the various components in the default locations or via component specific variable settings. When the normal defaults fail or components cannot be found, additional configure options may be necessary to help configure find the necessary tools for the build, or you may need to re-visit the setup of your system due to missing software packages.

+

NOTE: The configure script file does not have execute permissions and will need to be explicitly run with bash, see the source guidelines.

+
+

System Setup

+

Before even attempting to use a system to build the OpenJDK there are some very basic system setups needed. For all systems:

+
    +
  • Be sure the GNU make utility is version 3.81 or newer, e.g. run “make -version

    +
  • +
  • Install a Bootstrap JDK. All OpenJDK builds require access to a previously released JDK called the bootstrap JDK or boot JDK. The general rule is that the bootstrap JDK must be an instance of the previous major release of the JDK. In addition, there may be a requirement to use a release at or beyond a particular update level.

    +

    Building JDK 8 requires use of a version of JDK 7 this is at Update 7 or newer. JDK 8 developers should not use JDK 8 as the boot JDK, to ensure that JDK 8 dependencies are not introduced into the parts of the system that are built with JDK 7.

    +

    The JDK 7 binaries can be downloaded from Oracle’s JDK 7 download site. For build performance reasons it is very important that this bootstrap JDK be made available on the local disk of the machine doing the build. You should add its bin directory to the PATH environment variable. If configure has any issues finding this JDK, you may need to use the configure option --with-boot-jdk.

  • +
  • Ensure that GNU make, the Bootstrap JDK, and the compilers are all in your PATH environment variable.

  • +
+

And for specific systems:

+ +

Linux

+

With Linux, try and favor the system packages over building your own or getting packages from other areas. Most Linux builds should be possible with the system’s available packages.

+

Note that some Linux systems have a habit of pre-populating your environment variables for you, for example JAVA_HOME might get pre-defined for you to refer to the JDK installed on your Linux system. You will need to unset JAVA_HOME. It’s a good idea to run env and verify the environment variables you are getting from the default system settings make sense for building the OpenJDK.

+

Solaris

+
Studio Compilers
+

At a minimum, the Studio 12 Update 1 Compilers (containing version 5.10 of the C and C++ compilers) is required, including specific patches.

+

The Solaris SPARC patch list is:

+
    +
  • 118683-05: SunOS 5.10: Patch for profiling libraries and assembler
  • +
  • 119963-21: SunOS 5.10: Shared library patch for C++
  • +
  • 120753-08: SunOS 5.10: Microtasking libraries (libmtsk) patch
  • +
  • 128228-09: Sun Studio 12 Update 1: Patch for Sun C++ Compiler
  • +
  • 141860-03: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C C++ F77 F95
  • +
  • 141861-05: Sun Studio 12 Update 1: Patch for Sun C Compiler
  • +
  • 142371-01: Sun Studio 12.1 Update 1: Patch for dbx
  • +
  • 143384-02: Sun Studio 12 Update 1: Patch for debuginfo handling
  • +
  • 143385-02: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C C++ F77 F95
  • +
  • 142369-01: Sun Studio 12.1: Patch for Performance Analyzer Tools
  • +
+

The Solaris X86 patch list is:

+
    +
  • 119961-07: SunOS 5.10_x86, x64, Patch for profiling libraries and assembler
  • +
  • 119964-21: SunOS 5.10_x86: Shared library patch for C++_x86
  • +
  • 120754-08: SunOS 5.10_x86: Microtasking libraries (libmtsk) patch
  • +
  • 141858-06: Sun Studio 12 Update 1_x86: Sun Compiler Common patch for x86 backend
  • +
  • 128229-09: Sun Studio 12 Update 1_x86: Patch for C++ Compiler
  • +
  • 142363-05: Sun Studio 12 Update 1_x86: Patch for C Compiler
  • +
  • 142368-01: Sun Studio 12.1_x86: Patch for Performance Analyzer Tools
  • +
+

Place the bin directory in PATH.

+

The Oracle Solaris Studio Express compilers at: Oracle Solaris Studio Express Download site are also an option, although these compilers have not been extensively used yet.

+

Windows

+
Windows Unix Toolkit
+

Building on Windows requires a Unix-like environment, notably a Unix-like shell. There are several such environments available of which Cygwin and MinGW/MSYS are currently supported for the OpenJDK build. One of the differences of these systems from standard Windows tools is the way they handle Windows path names, particularly path names which contain spaces, backslashes as path separators and possibly drive letters. Depending on the use case and the specifics of each environment these path problems can be solved by a combination of quoting whole paths, translating backslashes to forward slashes, escaping backslashes with additional backslashes and translating the path names to their “8.3” version.

+
CYGWIN
+

CYGWIN is an open source, Linux-like environment which tries to emulate a complete POSIX layer on Windows. It tries to be smart about path names and can usually handle all kinds of paths if they are correctly quoted or escaped although internally it maps drive letters <drive>: to a virtual directory /cygdrive/<drive>.

+

You can always use the cygpath utility to map pathnames with spaces or the backslash character into the C:/ style of pathname (called ‘mixed’), e.g. cygpath -s -m "<path>".

+

Note that the use of CYGWIN creates a unique problem with regards to setting PATH. Normally on Windows the PATH variable contains directories separated with the “;” character (Solaris and Linux use “:”). With CYGWIN, it uses “:”, but that means that paths like “C:/path” cannot be placed in the CYGWIN version of PATH and instead CYGWIN uses something like /cygdrive/c/path which CYGWIN understands, but only CYGWIN understands.

+

The OpenJDK build requires CYGWIN version 1.7.16 or newer. Information about CYGWIN can be obtained from the CYGWIN website at www.cygwin.com.

+

By default CYGWIN doesn’t install all the tools required for building the OpenJDK. Along with the default installation, you need to install the following tools.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Binary NameCategoryPackageDescription
ar.exeDevelbinutilsThe GNU assembler, linker and binary utilities
make.exeDevelmakeThe GNU version of the ‘make’ utility built for CYGWIN
m4.exeInterpretersm4GNU implementation of the traditional Unix macro processor
cpio.exeUtilscpioA program to manage archives of files
gawk.exeUtilsawkPattern-directed scanning and processing language
file.exeUtilsfileDetermines file type using ‘magic’ numbers
zip.exeArchivezipPackage and compress (archive) files
unzip.exeArchiveunzipExtract compressed files in a ZIP archive
free.exeSystemprocpsDisplay amount of free and used memory in the system
+

Note that the CYGWIN software can conflict with other non-CYGWIN software on your Windows system. CYGWIN provides a FAQ for known issues and problems, of particular interest is the section on BLODA (applications that interfere with CYGWIN).

+
MinGW/MSYS
+

MinGW (“Minimalist GNU for Windows”) is a collection of free Windows specific header files and import libraries combined with GNU toolsets that allow one to produce native Windows programs that do not rely on any 3rd-party C runtime DLLs. MSYS is a supplement to MinGW which allows building applications and programs which rely on traditional UNIX tools to be present. Among others this includes tools like bash and make. See MinGW/MSYS for more information.

+

Like Cygwin, MinGW/MSYS can handle different types of path formats. They are internally converted to paths with forward slashes and drive letters <drive>: replaced by a virtual directory /<drive>. Additionally, MSYS automatically detects binaries compiled for the MSYS environment and feeds them with the internal, Unix-style path names. If native Windows applications are called from within MSYS programs their path arguments are automatically converted back to Windows style path names with drive letters and backslashes as path separators. This may cause problems for Windows applications which use forward slashes as parameter separator (e.g. cl /nologo /I) because MSYS may wrongly replace such parameters by drive letters.

+

In addition to the tools which will be installed by default, you have to manually install the msys-zip and msys-unzip packages. This can be easily done with the MinGW command line installer:

+
  mingw-get.exe install msys-zip
+  mingw-get.exe install msys-unzip
+
Visual Studio 2010 Compilers
+

The 32-bit and 64-bit OpenJDK Windows build requires Microsoft Visual Studio C++ 2010 (VS2010) Professional Edition or Express compiler. The compiler and other tools are expected to reside in the location defined by the variable VS100COMNTOOLS which is set by the Microsoft Visual Studio installer.

+

Only the C++ part of VS2010 is needed. Try to let the installation go to the default install directory. Always reboot your system after installing VS2010. The system environment variable VS100COMNTOOLS should be set in your environment.

+

Make sure that TMP and TEMP are also set in the environment and refer to Windows paths that exist, like C:\temp, not /tmp, not /cygdrive/c/temp, and not C:/temp. C:\temp is just an example, it is assumed that this area is private to the user, so by default after installs you should see a unique user path in these variables.

+

Mac OS X

+

Make sure you get the right XCode version.

+
+

Configure

+

The basic invocation of the configure script looks like:

+
+

bash ./configure [options]

+
+

This will create an output directory containing the “configuration” and setup an area for the build result. This directory typically looks like:

+
+

build/linux-x64-normal-server-release

+
+

configure will try to figure out what system you are running on and where all necessary build components are. If you have all prerequisites for building installed, it should find everything. If it fails to detect any component automatically, it will exit and inform you about the problem. When this happens, read more below in the configure options.

+

Some examples:

+
+

Windows 32bit build with freetype specified:
+bash ./configure --with-freetype=/cygdrive/c/freetype-i586 --with-target-bits=32

+
+
+

Debug 64bit Build:
+bash ./configure --enable-debug --with-target-bits=64

+
+

Configure Options

+

Complete details on all the OpenJDK configure options can be seen with:

+
+

bash ./configure --help=short

+
+

Use -help to see all the configure options available. You can generate any number of different configurations, e.g. debug, release, 32, 64, etc.

+

Some of the more commonly used configure options are:

+
+

--enable-debug
+set the debug level to fastdebug (this is a shorthand for --with-debug-level=fastdebug)

+
+

+
+

--with-alsa=_path_
+select the location of the Advanced Linux Sound Architecture (ALSA)

+
+
+

Version 0.9.1 or newer of the ALSA files are required for building the OpenJDK on Linux. These Linux files are usually available from an “alsa” of “libasound” development package, and it’s highly recommended that you try and use the package provided by the particular version of Linux that you are using.

+
+
+

--with-boot-jdk=_path_
+select the Bootstrap JDK

+
+
+

--with-boot-jdk-jvmargs=args
+provide the JVM options to be used to run the Bootstrap JDK

+
+
+

--with-cacerts=_path_
+select the path to the cacerts file.

+
+
+

See Certificate Authority on Wikipedia for a better understanding of the Certificate Authority (CA). A certificates file named “cacerts” represents a system-wide keystore with CA certificates. In JDK and JRE binary bundles, the “cacerts” file contains root CA certificates from several public CAs (e.g., VeriSign, Thawte, and Baltimore). The source contain a cacerts file without CA root certificates. Formal JDK builders will need to secure permission from each public CA and include the certificates into their own custom cacerts file. Failure to provide a populated cacerts file will result in verification errors of a certificate chain during runtime. By default an empty cacerts file is provided and that should be fine for most JDK developers.

+
+

+
+

--with-cups=_path_
+select the CUPS install location

+
+
+

The Common UNIX Printing System (CUPS) Headers are required for building the OpenJDK on Solaris and Linux. The Solaris header files can be obtained by installing the package SFWcups from the Solaris Software Companion CD/DVD, these often will be installed into the directory /opt/sfw/cups.

+
+
+

The CUPS header files can always be downloaded from www.cups.org.

+
+
+

--with-cups-include=_path_
+select the CUPS include directory location

+
+
+

--with-debug-level=_level_
+select the debug information level of release, fastdebug, or slowdebug

+
+
+

--with-dev-kit=_path_
+select location of the compiler install or developer install location

+
+

+
+

--with-freetype=_path_
+select the freetype files to use.

+
+
+

Expecting the freetype libraries under lib/ and the headers under include/.

+
+
+

Version 2.3 or newer of FreeType is required. On Unix systems required files can be available as part of your distribution (while you still may need to upgrade them). Note that you need development version of package that includes both the FreeType library and header files.

+
+
+

You can always download latest FreeType version from the FreeType website. Building the freetype 2 libraries from scratch is also possible, however on Windows refer to the Windows FreeType DLL build instructions.

+
+
+

Note that by default FreeType is built with byte code hinting support disabled due to licensing restrictions. In this case, text appearance and metrics are expected to differ from Sun’s official JDK build. See the SourceForge FreeType2 Home Page for more information.

+
+
+

--with-import-hotspot=_path_
+select the location to find hotspot binaries from a previous build to avoid building hotspot

+
+
+

--with-target-bits=_arg_
+select 32 or 64 bit build

+
+
+

--with-jvm-variants=_variants_
+select the JVM variants to build from, comma separated list that can include: server, client, kernel, zero and zeroshark

+
+
+

--with-memory-size=_size_
+select the RAM size that GNU make will think this system has

+
+
+

--with-msvcr-dll=_path_
+select the msvcr100.dll file to include in the Windows builds (C/C++ runtime library for Visual Studio).

+
+
+

This is usually picked up automatically from the redist directories of Visual Studio 2010.

+
+
+

--with-num-cores=_cores_
+select the number of cores to use (processor count or CPU count)

+
+

+
+

--with-x=_path_
+select the location of the X11 and xrender files.

+
+
+

The XRender Extension Headers are required for building the OpenJDK on Solaris and Linux. The Linux header files are usually available from a “Xrender” development package, it’s recommended that you try and use the package provided by the particular distribution of Linux that you are using. The Solaris XRender header files is included with the other X11 header files in the package SFWxwinc on new enough versions of Solaris and will be installed in /usr/X11/include/X11/extensions/Xrender.h or /usr/openwin/share/include/X11/extensions/Xrender.h

+
+
+

Make

+

The basic invocation of the make utility looks like:

+
+

make all

+
+

This will start the build to the output directory containing the “configuration” that was created by the configure script. Run make help for more information on the available targets.

+

There are some of the make targets that are of general interest:

+
+

empty
+build everything but no images

+
+
+

all
+build everything including images

+
+
+

all-conf
+build all configurations

+
+
+

images
+create complete j2sdk and j2re images

+
+
+

install
+install the generated images locally, typically in /usr/local

+
+
+

clean
+remove all files generated by make, but not those generated by configure

+
+
+

dist-clean
+remove all files generated by both and configure (basically killing the configuration)

+
+
+

help
+give some help on using make, including some interesting make targets

+
+
+

Testing

+

When the build is completed, you should see the generated binaries and associated files in the j2sdk-image directory in the output directory. In particular, the build/*/images/j2sdk-image/bin directory should contain executables for the OpenJDK tools and utilities for that configuration. The testing tool jtreg will be needed and can be found at: the jtreg site. The provided regression tests in the repositories can be run with the command:

+
+

cd test && make PRODUCT_HOME=`pwd`/../build/*/images/j2sdk-image all

+
+
+

Appendix A: Hints and Tips

+

FAQ

+

Q: The generated-configure.sh file looks horrible! How are you going to edit it?
+A: The generated-configure.sh file is generated (think “compiled”) by the autoconf tools. The source code is in configure.ac and various .m4 files in common/autoconf, which are much more readable.

+

Q: Why is the generated-configure.sh file checked in, if it is generated?
+A: If it was not generated, every user would need to have the autoconf tools installed, and re-generate the configure file as the first step. Our goal is to minimize the work needed to be done by the user to start building OpenJDK, and to minimize the number of external dependencies required.

+

Q: Do you require a specific version of autoconf for regenerating generated-configure.sh?
+A: Yes, version 2.69 is required and should be easy enough to aquire on all supported operating systems. The reason for this is to avoid large spurious changes in generated-configure.sh.

+

Q: How do you regenerate generated-configure.sh after making changes to the input files?
+A: Regnerating generated-configure.sh should always be done using the script common/autoconf/autogen.sh to ensure that the correct files get updated. This script should also be run after mercurial tries to merge generated-configure.sh as a merge of the generated file is not guaranteed to be correct.

+

Q: What are the files in common/makefiles/support/* for? They look like gibberish.
+A: They are a somewhat ugly hack to compensate for command line length limitations on certain platforms (Windows, Solaris). Due to a combination of limitations in make and the shell, command lines containing too many files will not work properly. These helper files are part of an elaborate hack that will compress the command line in the makefile and then uncompress it safely. We’re not proud of it, but it does fix the problem. If you have any better suggestions, we’re all ears! :-)

+

Q: I want to see the output of the commands that make runs, like in the old build. How do I do that?
+A: You specify the LOG variable to make. There are several log levels:

+
    +
  • warn – Default and very quiet.
  • +
  • info – Shows more progress information than warn.
  • +
  • debug – Echos all command lines and prints all macro calls for compilation definitions.
  • +
  • trace – Echos all $(shell) command lines as well.
  • +
+

Q: When do I have to re-run configure?
+A: Normally you will run configure only once for creating a configuration. You need to re-run configuration only if you want to change any configuration options, or if you pull down changes to the configure script.

+

Q: I have added a new source file. Do I need to modify the makefiles?
+A: Normally, no. If you want to create e.g. a new native library, you will need to modify the makefiles. But for normal file additions or removals, no changes are needed. There are certan exceptions for some native libraries where the source files are spread over many directories which also contain sources for other libraries. In these cases it was simply easier to create include lists rather than excludes.

+

Q: When I run configure --help, I see many strange options, like --dvidir. What is this?
+A: Configure provides a slew of options by default, to all projects that use autoconf. Most of them are not used in OpenJDK, so you can safely ignore them. To list only OpenJDK specific features, use configure --help=short instead.

+

Q: configure provides OpenJDK-specific features such as --with-builddeps-server that are not described in this document. What about those?
+A: Try them out if you like! But be aware that most of these are experimental features. Many of them don’t do anything at all at the moment; the option is just a placeholder. Others depend on pieces of code or infrastructure that is currently not ready for prime time.

+

Q: How will you make sure you don’t break anything?
+A: We have a script that compares the result of the new build system with the result of the old. For most part, we aim for (and achieve) byte-by-byte identical output. There are however technical issues with e.g. native binaries, which might differ in a byte-by-byte comparison, even when building twice with the old build system. For these, we compare relevant aspects (e.g. the symbol table and file size). Note that we still don’t have 100% equivalence, but we’re close.

+

Q: I noticed this thing X in the build that looks very broken by design. Why don’t you fix it?
+A: Our goal is to produce a build output that is as close as technically possible to the old build output. If things were weird in the old build, they will be weird in the new build. Often, things were weird before due to obscurity, but in the new build system the weird stuff comes up to the surface. The plan is to attack these things at a later stage, after the new build system is established.

+

Q: The code in the new build system is not that well-structured. Will you fix this?
+A: Yes! The new build system has grown bit by bit as we converted the old system. When all of the old build system is converted, we can take a step back and clean up the structure of the new build system. Some of this we plan to do before replacing the old build system and some will need to wait until after.

+

Q: Is anything able to use the results of the new build’s default make target?
+A: Yes, this is the minimal (or roughly minimal) set of compiled output needed for a developer to actually execute the newly built JDK. The idea is that in an incremental development fashion, when doing a normal make, you should only spend time recompiling what’s changed (making it purely incremental) and only do the work that’s needed to actually run and test your code. The packaging stuff that is part of the images target is not needed for a normal developer who wants to test his new code. Even if it’s quite fast, it’s still unnecessary. We’re targeting sub-second incremental rebuilds! ;-) (Or, well, at least single-digit seconds…)

+

Q: I usually set a specific environment variable when building, but I can’t find the equivalent in the new build. What should I do?
+A: It might very well be that we have neglected to add support for an option that was actually used from outside the build system. Email us and we will add support for it!

+

Build Performance Tips

+

Building OpenJDK requires a lot of horsepower. Some of the build tools can be adjusted to utilize more or less of resources such as parallel threads and memory. The configure script analyzes your system and selects reasonable values for such options based on your hardware. If you encounter resource problems, such as out of memory conditions, you can modify the detected values with:

+
    +
  • --with-num-cores – number of cores in the build system, e.g. --with-num-cores=8
  • +
  • --with-memory-size – memory (in MB) available in the build system, e.g. --with-memory-size=1024
  • +
+

It might also be necessary to specify the JVM arguments passed to the Bootstrap JDK, using e.g. --with-boot-jdk-jvmargs="-Xmx8G -enableassertions". Doing this will override the default JVM arguments passed to the Bootstrap JDK.

+

One of the top goals of the new build system is to improve the build performance and decrease the time needed to build. This will soon also apply to the java compilation when the Smart Javac wrapper is making its way into jdk8. It can be tried in the build-infra repository already. You are likely to find that the new build system is faster than the old one even without this feature.

+

At the end of a successful execution of configure, you will get a performance summary, indicating how well the build will perform. Here you will also get performance hints. If you want to build fast, pay attention to those!

+

Building with ccache

+

A simple way to radically speed up compilation of native code (typically hotspot and native libraries in JDK) is to install ccache. This will cache and reuse prior compilation results, if the source code is unchanged. However, ccache versions prior to 3.1.4 does not work correctly with the precompiled headers used in OpenJDK. So if your platform supports ccache at 3.1.4 or later, we highly recommend installing it. This is currently only supported on linux.

+

Building on local disk

+

If you are using network shares, e.g. via NFS, for your source code, make sure the build directory is situated on local disk. The performance penalty is extremely high for building on a network share, close to unusable.

+

Building only one JVM

+

The old build builds multiple JVMs on 32-bit systems (client and server; and on Windows kernel as well). In the new build we have changed this default to only build server when it’s available. This improves build times for those not interested in multiple JVMs. To mimic the old behavior on platforms that support it, use --with-jvm-variants=client,server.

+

Selecting the number of cores to build on

+

By default, configure will analyze your machine and run the make process in parallel with as many threads as you have cores. This behavior can be overridden, either “permanently” (on a configure basis) using --with-num-cores=N or for a single build only (on a make basis), using make JOBS=N.

+

If you want to make a slower build just this time, to save some CPU power for other processes, you can run e.g. make JOBS=2. This will force the makefiles to only run 2 parallel processes, or even make JOBS=1 which will disable parallelism.

+

If you want to have it the other way round, namely having slow builds default and override with fast if you’re impatient, you should call configure with --with-num-cores=2, making 2 the default. If you want to run with more cores, run make JOBS=8

+

Troubleshooting

+

Solving build problems

+

If the build fails (and it’s not due to a compilation error in a source file you’ve changed), the first thing you should do is to re-run the build with more verbosity. Do this by adding LOG=debug to your make command line.

+

The build log (with both stdout and stderr intermingled, basically the same as you see on your console) can be found as build.log in your build directory.

+

You can ask for help on build problems with the new build system on either the build-dev or the build-infra-dev mailing lists. Please include the relevant parts of the build log.

+

A build can fail for any number of reasons. Most failures are a result of trying to build in an environment in which all the pre-build requirements have not been met. The first step in troubleshooting a build failure is to recheck that you have satisfied all the pre-build requirements for your platform. Scanning the configure log is a good first step, making sure that what it found makes sense for your system. Look for strange error messages or any difficulties that configure had in finding things.

+

Some of the more common problems with builds are briefly described below, with suggestions for remedies.

+
    +
  • Corrupted Bundles on Windows:
    +Some virus scanning software has been known to corrupt the downloading of zip bundles. It may be necessary to disable the ‘on access’ or ‘real time’ virus scanning features to prevent this corruption. This type of ‘real time’ virus scanning can also slow down the build process significantly. Temporarily disabling the feature, or excluding the build output directory may be necessary to get correct and faster builds.

  • +
  • Slow Builds:
    +If your build machine seems to be overloaded from too many simultaneous C++ compiles, try setting the JOBS=1 on the make command line. Then try increasing the count slowly to an acceptable level for your system. Also:

    +

    Creating the javadocs can be very slow, if you are running javadoc, consider skipping that step.

    +

    Faster CPUs, more RAM, and a faster DISK usually helps. The VM build tends to be CPU intensive (many C++ compiles), and the rest of the JDK will often be disk intensive.

    +

    Faster compiles are possible using a tool called ccache.

  • +
  • File time issues:
    +If you see warnings that refer to file time stamps, e.g.

    +
    +

    Warning message: File 'xxx' has modification time in the future.
    +Warning message: Clock skew detected. Your build may be incomplete.

    +
    +

    These warnings can occur when the clock on the build machine is out of sync with the timestamps on the source files. Other errors, apparently unrelated but in fact caused by the clock skew, can occur along with the clock skew warnings. These secondary errors may tend to obscure the fact that the true root cause of the problem is an out-of-sync clock.

    +

    If you see these warnings, reset the clock on the build machine, run “gmake clobber” or delete the directory containing the build output, and restart the build from the beginning.

  • +
  • Error message: Trouble writing out table to disk
    +Increase the amount of swap space on your build machine. This could be caused by overloading the system and it may be necessary to use:

    +
    +

    make JOBS=1

    +
    +

    to reduce the load on the system.

  • +
  • Error Message: libstdc++ not found:
    +This is caused by a missing libstdc++.a library. This is installed as part of a specific package (e.g. libstdc++.so.devel.386). By default some 64-bit Linux versions (e.g. Fedora) only install the 64-bit version of the libstdc++ package. Various parts of the JDK build require a static link of the C++ runtime libraries to allow for maximum portability of the built images.

  • +
  • Linux Error Message: cannot restore segment prot after reloc
    +This is probably an issue with SELinux (See SELinux on Wikipedia). Parts of the VM is built without the -fPIC for performance reasons.

    +

    To completely disable SELinux:

    +
      +
    1. $ su root
    2. +
    3. # system-config-securitylevel
    4. +
    5. In the window that appears, select the SELinux tab
    6. +
    7. Disable SELinux
    8. +
    +

    Alternatively, instead of completely disabling it you could disable just this one check.

    +
      +
    1. Select System->Administration->SELinux Management
    2. +
    3. In the SELinux Management Tool which appears, select “Boolean” from the menu on the left
    4. +
    5. Expand the “Memory Protection” group
    6. +
    7. Check the first item, labeled “Allow all unconfined executables to use libraries requiring text relocation …”
    8. +
  • +
  • Windows Error Messages:
    +*** fatal error - couldn't allocate heap, ...
    +rm fails with "Directory not empty"
    +unzip fails with "cannot create ... Permission denied"
    +unzip fails with "cannot create ... Error 50"

    +

    The CYGWIN software can conflict with other non-CYGWIN software. See the CYGWIN FAQ section on BLODA (applications that interfere with CYGWIN).

  • +
  • Windows Error Message: spawn failed
    +Try rebooting the system, or there could be some kind of issue with the disk or disk partition being used. Sometimes it comes with a “Permission Denied” message.

  • +
+
+

Appendix B: GNU make

+

The Makefiles in the OpenJDK are only valid when used with the GNU version of the utility command make (usually called gmake on Solaris). A few notes about using GNU make:

+
    +
  • You need GNU make version 3.81 or newer. If the GNU make utility on your systems is not 3.81 or newer, see “Building GNU make”.
  • +
  • Place the location of the GNU make binary in the PATH.
  • +
  • Solaris: Do NOT use /usr/bin/make on Solaris. If your Solaris system has the software from the Solaris Developer Companion CD installed, you should try and use gmake which will be located in either the /usr/bin, /opt/sfw/bin or /usr/sfw/bin directory.
  • +
  • Windows: Make sure you start your build inside a bash shell.
  • +
  • Mac OS X: The XCode “command line tools” must be installed on your Mac.
  • +
+

Information on GNU make, and access to ftp download sites, are available on the GNU make web site. The latest source to GNU make is available at ftp.gnu.org/pub/gnu/make/.

+

Building GNU make

+

First step is to get the GNU make 3.81 or newer source from ftp.gnu.org/pub/gnu/make/. Building is a little different depending on the OS but is basically done with:

+
  bash ./configure
+  make
+
+

Appendix C: Build Environments

+

Minimum Build Environments

+

This file often describes specific requirements for what we call the “minimum build environments” (MBE) for this specific release of the JDK. What is listed below is what the Oracle Release Engineering Team will use to build the Oracle JDK product. Building with the MBE will hopefully generate the most compatible bits that install on, and run correctly on, the most variations of the same base OS and hardware architecture. In some cases, these represent what is often called the least common denominator, but each Operating System has different aspects to it.

+

In all cases, the Bootstrap JDK version minimum is critical, we cannot guarantee builds will work with older Bootstrap JDK’s. Also in all cases, more RAM and more processors is better, the minimums listed below are simply recommendations.

+

With Solaris and Mac OS X, the version listed below is the oldest release we can guarantee builds and works, and the specific version of the compilers used could be critical.

+

With Windows the critical aspect is the Visual Studio compiler used, which due to it’s runtime, generally dictates what Windows systems can do the builds and where the resulting bits can be used.

+

NOTE: We expect a change here off these older Windows OS releases and to a ‘less older’ one, probably Windows 2008R2 X64.

+

With Linux, it was just a matter of picking a stable distribution that is a good representative for Linux in general.

+

NOTE: We expect a change here from Fedora 9 to something else, but it has not been completely determined yet, possibly Ubuntu 12.04 X64, unbiased community feedback would be welcome on what a good choice would be here.

+

It is understood that most developers will NOT be using these specific versions, and in fact creating these specific versions may be difficult due to the age of some of this software. It is expected that developers are more often using the more recent releases and distributions of these operating systems.

+

Compilation problems with newer or different C/C++ compilers is a common problem. Similarly, compilation problems related to changes to the /usr/include or system header files is also a common problem with older, newer, or unreleased OS versions. Please report these types of problems as bugs so that they can be dealt with accordingly.

+

Bootstrap JDK: JDK 7u7

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Base OS and ArchitectureOSC/C++ CompilerProcessorsRAM MinimumDISK Needs
Linux X86 (32-bit) and X64 (64-bit)Fedora 9gcc 4.32 or more1 GB6 GB
Solaris SPARC (32-bit) and SPARCV9 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patches4 or more4 GB8 GB
Solaris X86 (32-bit) and X64 (64-bit)Solaris 10 Update 6Studio 12 Update 1 + patches4 or more4 GB8 GB
Windows X86 (32-bit)Windows XPMicrosoft Visual Studio C++ 2010 Professional Edition2 or more2 GB6 GB
Windows X64 (64-bit)Windows Server 2003 - Enterprise x64 EditionMicrosoft Visual Studio C++ 2010 Professional Edition2 or more2 GB6 GB
Mac OS X X64 (64-bit)Mac OS X 10.7 “Lion”XCode 4.5.2 or newer2 or more4 GB6 GB
+
+

Specific Developer Build Environments

+

We won’t be listing all the possible environments, but we will try to provide what information we have available to us.

+

NOTE: The community can help out by updating this part of the document.

+

Fedora

+

After installing the latest Fedora you need to install several build dependencies. The simplest way to do it is to execute the following commands as user root:

+
  yum-builddep java-1.7.0-openjdk
+  yum install gcc gcc-c++
+

In addition, it’s necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/usr/lib/jvm/java-openjdk/bin:${PATH}"
+

CentOS 5.5

+

After installing CentOS 5.5 you need to make sure you have the following Development bundles installed:

+
    +
  • Development Libraries
  • +
  • Development Tools
  • +
  • Java Development
  • +
  • X Software Development (Including XFree86-devel)
  • +
+

Plus the following packages:

+
    +
  • cups devel: Cups Development Package
  • +
  • alsa devel: Alsa Development Package
  • +
  • Xi devel: libXi.so Development Package
  • +
+

The freetype 2.3 packages don’t seem to be available, but the freetype 2.3 sources can be downloaded, built, and installed easily enough from the freetype site. Build and install with something like:

+
  bash ./configure
+  make
+  sudo -u root make install
+

Mercurial packages could not be found easily, but a Google search should find ones, and they usually include Python if it’s needed.

+

Debian 5.0 (Lenny)

+

After installing Debian 5 you need to install several build dependencies. The simplest way to install the build dependencies is to execute the following commands as user root:

+
  aptitude build-dep openjdk-7
+  aptitude install openjdk-7-jdk libmotif-dev
+

In addition, it’s necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}"
+

Ubuntu 12.04

+

After installing Ubuntu 12.04 you need to install several build dependencies. The simplest way to do it is to execute the following commands:

+
  sudo aptitude build-dep openjdk-7
+  sudo aptitude install openjdk-7-jdk
+

In addition, it’s necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}"
+

OpenSUSE 11.1

+

After installing OpenSUSE 11.1 you need to install several build dependencies. The simplest way to install the build dependencies is to execute the following commands:

+
  sudo zypper source-install -d java-1_7_0-openjdk
+  sudo zypper install make
+

In addition, it is necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:$[PATH}"
+

Finally, you need to unset the JAVA_HOME environment variable:

+
  export -n JAVA_HOME`
+

Mandriva Linux One 2009 Spring

+

After installing Mandriva Linux One 2009 Spring you need to install several build dependencies. The simplest way to install the build dependencies is to execute the following commands as user root:

+
  urpmi java-1.7.0-openjdk-devel make gcc gcc-c++ freetype-devel zip unzip
+    libcups2-devel libxrender1-devel libalsa2-devel libstc++-static-devel
+    libxtst6-devel libxi-devel
+

In addition, it is necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:${PATH}"
+

OpenSolaris 2009.06

+

After installing OpenSolaris 2009.06 you need to install several build dependencies. The simplest way to install the build dependencies is to execute the following commands:

+
  pfexec pkg install SUNWgmake SUNWj7dev sunstudioexpress SUNWcups SUNWzip
+    SUNWunzip SUNWxwhl SUNWxorg-headers SUNWaudh SUNWfreetype2
+

In addition, it is necessary to set a few environment variables for the build:

+
  export LANG=C
+  export PATH="/opt/SunStudioExpress/bin:${PATH}"
+
+

End of the OpenJDK build README document.

+

Please come again!

+ + diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/doc/building.md openjdk-8-8u402-ga/=unpacked-tar8=/doc/building.md --- openjdk-8-8u392-ga/=unpacked-tar8=/doc/building.md 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/doc/building.md 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,1134 @@ +% OpenJDK Build README + +![OpenJDK](http://openjdk.java.net/images/openjdk.png) + +-------------------------------------------------------------------------------- + +## Introduction + +This README file contains build instructions for the +[OpenJDK](http://openjdk.java.net). Building the source code for the OpenJDK +requires a certain degree of technical expertise. + +### !!!!!!!!!!!!!!! THIS IS A MAJOR RE-WRITE of this document. !!!!!!!!!!!!! + +Some Headlines: + + * The build is now a "`configure && make`" style build + * Any GNU make 3.81 or newer should work + * The build should scale, i.e. more processors should cause the build to be + done in less wall-clock time + * Nested or recursive make invocations have been significantly reduced, as + has the total fork/exec or spawning of sub processes during the build + * Windows MKS usage is no longer supported + * Windows Visual Studio `vsvars*.bat` and `vcvars*.bat` files are run + automatically + * Ant is no longer used when building the OpenJDK + * Use of ALT\_\* environment variables for configuring the build is no longer + supported + +------------------------------------------------------------------------------- + +## Contents + + * [Introduction](#introduction) + * [Use of Mercurial](#hg) + * [Getting the Source](#get_source) + * [Repositories](#repositories) + * [Building](#building) + * [System Setup](#setup) + * [Linux](#linux) + * [Solaris](#solaris) + * [Mac OS X](#macosx) + * [Windows](#windows) + * [Configure](#configure) + * [Make](#make) + * [Testing](#testing) + +------------------------------------------------------------------------------- + + * [Appendix A: Hints and Tips](#hints) + * [FAQ](#faq) + * [Build Performance Tips](#performance) + * [Troubleshooting](#troubleshooting) + * [Appendix B: GNU Make Information](#gmake) + * [Appendix C: Build Environments](#buildenvironments) + +------------------------------------------------------------------------------- + +## Use of Mercurial + +The OpenJDK sources are maintained with the revision control system +[Mercurial](http://mercurial.selenic.com/wiki/Mercurial). If you are new to +Mercurial, please see the [Beginner +Guides](http://mercurial.selenic.com/wiki/BeginnersGuides) or refer to the +[Mercurial Book](http://hgbook.red-bean.com/). The first few chapters of the +book provide an excellent overview of Mercurial, what it is and how it works. + +For using Mercurial with the OpenJDK refer to the [Developer Guide: Installing +and Configuring +Mercurial](http://openjdk.java.net/guide/repositories.html#installConfig) +section for more information. + +### Getting the Source + +To get the entire set of OpenJDK Mercurial repositories use the script +`get_source.sh` located in the root repository: + + hg clone http://hg.openjdk.java.net/jdk8/jdk8 YourOpenJDK + cd YourOpenJDK + bash ./get_source.sh + +Once you have all the repositories, keep in mind that each repository is its +own independent repository. You can also re-run `./get_source.sh` anytime to +pull over all the latest changesets in all the repositories. This set of nested +repositories has been given the term "forest" and there are various ways to +apply the same `hg` command to each of the repositories. For example, the +script `make/scripts/hgforest.sh` can be used to repeat the same `hg` command +on every repository, e.g. + + cd YourOpenJDK + bash ./make/scripts/hgforest.sh status + +### Repositories + +The set of repositories and what they contain: + + * **. (root)** contains common configure and makefile logic + * **hotspot** contains source code and make files for building the OpenJDK + Hotspot Virtual Machine + * **langtools** contains source code for the OpenJDK javac and language tools + * **jdk** contains source code and make files for building the OpenJDK runtime + libraries and misc files + * **jaxp** contains source code for the OpenJDK JAXP functionality + * **jaxws** contains source code for the OpenJDK JAX-WS functionality + * **corba** contains source code for the OpenJDK Corba functionality + * **nashorn** contains source code for the OpenJDK JavaScript implementation + +### Repository Source Guidelines + +There are some very basic guidelines: + + * Use of whitespace in source files (.java, .c, .h, .cpp, and .hpp files) is + restricted. No TABs, no trailing whitespace on lines, and files should not + terminate in more than one blank line. + * Files with execute permissions should not be added to the source + repositories. + * All generated files need to be kept isolated from the files maintained or + managed by the source control system. The standard area for generated files + is the top level `build/` directory. + * The default build process should be to build the product and nothing else, + in one form, e.g. a product (optimized), debug (non-optimized, -g plus + assert logic), or fastdebug (optimized, -g plus assert logic). + * The `.hgignore` file in each repository must exist and should include + `^build/`, `^dist/` and optionally any `nbproject/private` directories. **It + should NEVER** include anything in the `src/` or `test/` or any managed + directory area of a repository. + * Directory names and file names should never contain blanks or non-printing + characters. + * Generated source or binary files should NEVER be added to the repository + (that includes `javah` output). There are some exceptions to this rule, in + particular with some of the generated configure scripts. + * Files not needed for typical building or testing of the repository should + not be added to the repository. + +------------------------------------------------------------------------------- + +## Building + +The very first step in building the OpenJDK is making sure the system itself +has everything it needs to do OpenJDK builds. Once a system is setup, it +generally doesn't need to be done again. + +Building the OpenJDK is now done with running a `configure` script which will +try and find and verify you have everything you need, followed by running +`make`, e.g. + +> **`bash ./configure`** \ +> **`make all`** + +Where possible the `configure` script will attempt to located the various +components in the default locations or via component specific variable +settings. When the normal defaults fail or components cannot be found, +additional `configure` options may be necessary to help `configure` find the +necessary tools for the build, or you may need to re-visit the setup of your +system due to missing software packages. + +**NOTE:** The `configure` script file does not have execute permissions and +will need to be explicitly run with `bash`, see the source guidelines. + +------------------------------------------------------------------------------- + +### System Setup + +Before even attempting to use a system to build the OpenJDK there are some very +basic system setups needed. For all systems: + + * Be sure the GNU make utility is version 3.81 or newer, e.g. + run "`make -version`" + + + * Install a Bootstrap JDK. All OpenJDK builds require access to a previously + released JDK called the *bootstrap JDK* or *boot JDK.* The general rule is + that the bootstrap JDK must be an instance of the previous major release of + the JDK. In addition, there may be a requirement to use a release at or + beyond a particular update level. + + ***Building JDK 8 requires use of a version of JDK 7 this is at Update 7 + or newer. JDK 8 developers should not use JDK 8 as the boot JDK, to ensure + that JDK 8 dependencies are not introduced into the parts of the system + that are built with JDK 7.*** + + The JDK 7 binaries can be downloaded from Oracle's [JDK 7 download + site](http://www.oracle.com/technetwork/java/javase/downloads/index.html). + For build performance reasons it is very important that this bootstrap JDK + be made available on the local disk of the machine doing the build. You + should add its `bin` directory to the `PATH` environment variable. If + `configure` has any issues finding this JDK, you may need to use the + `configure` option `--with-boot-jdk`. + + * Ensure that GNU make, the Bootstrap JDK, and the compilers are all in your + PATH environment variable. + +And for specific systems: + + * **Linux** + + Install all the software development packages needed including + [alsa](#alsa), [freetype](#freetype), [cups](#cups), and + [xrender](#xrender). See [specific system packages](#SDBE). + + * **Solaris** + + Install all the software development packages needed including [Studio + Compilers](#studio), [freetype](#freetype), [cups](#cups), and + [xrender](#xrender). See [specific system packages](#SDBE). + + * **Windows** + + * Install one of [CYGWIN](#cygwin) or [MinGW/MSYS](#msys) + * Install [Visual Studio 2010](#vs2010) + + * **Mac OS X** + + Install [XCode 4.5.2](https://developer.apple.com/xcode/) and also + install the "Command line tools" found under the preferences pane + "Downloads" + +#### Linux + +With Linux, try and favor the system packages over building your own or getting +packages from other areas. Most Linux builds should be possible with the +system's available packages. + +Note that some Linux systems have a habit of pre-populating your environment +variables for you, for example `JAVA_HOME` might get pre-defined for you to +refer to the JDK installed on your Linux system. You will need to unset +`JAVA_HOME`. It's a good idea to run `env` and verify the environment variables +you are getting from the default system settings make sense for building the +OpenJDK. + +#### Solaris + +##### Studio Compilers + +At a minimum, the [Studio 12 Update 1 +Compilers](http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index.htm) +(containing version 5.10 of the C and C++ compilers) is required, including +specific patches. + +The Solaris SPARC patch list is: + + * 118683-05: SunOS 5.10: Patch for profiling libraries and assembler + * 119963-21: SunOS 5.10: Shared library patch for C++ + * 120753-08: SunOS 5.10: Microtasking libraries (libmtsk) patch + * 128228-09: Sun Studio 12 Update 1: Patch for Sun C++ Compiler + * 141860-03: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C + C++ F77 F95 + * 141861-05: Sun Studio 12 Update 1: Patch for Sun C Compiler + * 142371-01: Sun Studio 12.1 Update 1: Patch for dbx + * 143384-02: Sun Studio 12 Update 1: Patch for debuginfo handling + * 143385-02: Sun Studio 12 Update 1: Patch for Compiler Common patch for Sun C + C++ F77 F95 + * 142369-01: Sun Studio 12.1: Patch for Performance Analyzer Tools + +The Solaris X86 patch list is: + + * 119961-07: SunOS 5.10_x86, x64, Patch for profiling libraries and assembler + * 119964-21: SunOS 5.10_x86: Shared library patch for C++\_x86 + * 120754-08: SunOS 5.10_x86: Microtasking libraries (libmtsk) patch + * 141858-06: Sun Studio 12 Update 1_x86: Sun Compiler Common patch for x86 + backend + * 128229-09: Sun Studio 12 Update 1_x86: Patch for C++ Compiler + * 142363-05: Sun Studio 12 Update 1_x86: Patch for C Compiler + * 142368-01: Sun Studio 12.1_x86: Patch for Performance Analyzer Tools + +Place the `bin` directory in `PATH`. + +The Oracle Solaris Studio Express compilers at: [Oracle Solaris Studio Express +Download +site](http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index-jsp-142582.html) +are also an option, although these compilers have not been extensively used +yet. + +#### Windows + +##### Windows Unix Toolkit + +Building on Windows requires a Unix-like environment, notably a Unix-like +shell. There are several such environments available of which +[Cygwin](http://www.cygwin.com/) and +[MinGW/MSYS](http://www.mingw.org/wiki/MSYS) are currently supported for the +OpenJDK build. One of the differences of these systems from standard Windows +tools is the way they handle Windows path names, particularly path names which +contain spaces, backslashes as path separators and possibly drive letters. +Depending on the use case and the specifics of each environment these path +problems can be solved by a combination of quoting whole paths, translating +backslashes to forward slashes, escaping backslashes with additional +backslashes and translating the path names to their ["8.3" +version](http://en.wikipedia.org/wiki/8.3_filename). + +###### CYGWIN + +CYGWIN is an open source, Linux-like environment which tries to emulate a +complete POSIX layer on Windows. It tries to be smart about path names and can +usually handle all kinds of paths if they are correctly quoted or escaped +although internally it maps drive letters `:` to a virtual directory +`/cygdrive/`. + +You can always use the `cygpath` utility to map pathnames with spaces or the +backslash character into the `C:/` style of pathname (called 'mixed'), e.g. +`cygpath -s -m ""`. + +Note that the use of CYGWIN creates a unique problem with regards to setting +[`PATH`](#path). Normally on Windows the `PATH` variable contains directories +separated with the ";" character (Solaris and Linux use ":"). With CYGWIN, it +uses ":", but that means that paths like "C:/path" cannot be placed in the +CYGWIN version of `PATH` and instead CYGWIN uses something like +`/cygdrive/c/path` which CYGWIN understands, but only CYGWIN understands. + +The OpenJDK build requires CYGWIN version 1.7.16 or newer. Information about +CYGWIN can be obtained from the CYGWIN website at +[www.cygwin.com](http://www.cygwin.com). + +By default CYGWIN doesn't install all the tools required for building the +OpenJDK. Along with the default installation, you need to install the following +tools. + + Binary Name Category Package Description + ------------- -------------- ---------- ------------------------------------------------------------ + ar.exe Devel binutils The GNU assembler, linker and binary utilities + make.exe Devel make The GNU version of the 'make' utility built for CYGWIN + m4.exe Interpreters m4 GNU implementation of the traditional Unix macro processor + cpio.exe Utils cpio A program to manage archives of files + gawk.exe Utils awk Pattern-directed scanning and processing language + file.exe Utils file Determines file type using 'magic' numbers + zip.exe Archive zip Package and compress (archive) files + unzip.exe Archive unzip Extract compressed files in a ZIP archive + free.exe System procps Display amount of free and used memory in the system + +Note that the CYGWIN software can conflict with other non-CYGWIN software on +your Windows system. CYGWIN provides a +[FAQ](http://cygwin.com/faq/faq.using.html) for known issues and problems, +of particular interest is the section on [BLODA (applications that interfere +with CYGWIN)](http://cygwin.com/faq/faq.using.html#faq.using.bloda). + +###### MinGW/MSYS + +MinGW ("Minimalist GNU for Windows") is a collection of free Windows specific +header files and import libraries combined with GNU toolsets that allow one to +produce native Windows programs that do not rely on any 3rd-party C runtime +DLLs. MSYS is a supplement to MinGW which allows building applications and +programs which rely on traditional UNIX tools to be present. Among others this +includes tools like `bash` and `make`. See +[MinGW/MSYS](http://www.mingw.org/wiki/MSYS) for more information. + +Like Cygwin, MinGW/MSYS can handle different types of path formats. They are +internally converted to paths with forward slashes and drive letters `:` +replaced by a virtual directory `/`. Additionally, MSYS automatically +detects binaries compiled for the MSYS environment and feeds them with the +internal, Unix-style path names. If native Windows applications are called from +within MSYS programs their path arguments are automatically converted back to +Windows style path names with drive letters and backslashes as path separators. +This may cause problems for Windows applications which use forward slashes as +parameter separator (e.g. `cl /nologo /I`) because MSYS may wrongly [replace +such parameters by drive +letters](http://mingw.org/wiki/Posix_path_conversion). + +In addition to the tools which will be installed by default, you have to +manually install the `msys-zip` and `msys-unzip` packages. This can be easily +done with the MinGW command line installer: + + mingw-get.exe install msys-zip + mingw-get.exe install msys-unzip + +##### Visual Studio 2010 Compilers + +The 32-bit and 64-bit OpenJDK Windows build requires Microsoft Visual Studio +C++ 2010 (VS2010) Professional Edition or Express compiler. The compiler and +other tools are expected to reside in the location defined by the variable +`VS100COMNTOOLS` which is set by the Microsoft Visual Studio installer. + +Only the C++ part of VS2010 is needed. Try to let the installation go to the +default install directory. Always reboot your system after installing VS2010. +The system environment variable VS100COMNTOOLS should be set in your +environment. + +Make sure that TMP and TEMP are also set in the environment and refer to +Windows paths that exist, like `C:\temp`, not `/tmp`, not `/cygdrive/c/temp`, +and not `C:/temp`. `C:\temp` is just an example, it is assumed that this area +is private to the user, so by default after installs you should see a unique +user path in these variables. + +#### Mac OS X + +Make sure you get the right XCode version. + +------------------------------------------------------------------------------- + +### Configure + +The basic invocation of the `configure` script looks like: + +> **`bash ./configure [options]`** + +This will create an output directory containing the "configuration" and setup +an area for the build result. This directory typically looks like: + +> **`build/linux-x64-normal-server-release`** + +`configure` will try to figure out what system you are running on and where all +necessary build components are. If you have all prerequisites for building +installed, it should find everything. If it fails to detect any component +automatically, it will exit and inform you about the problem. When this +happens, read more below in [the `configure` options](#configureoptions). + +Some examples: + +> **Windows 32bit build with freetype specified:** \ +> `bash ./configure --with-freetype=/cygdrive/c/freetype-i586 --with-target-bits=32` + +> **Debug 64bit Build:** \ +> `bash ./configure --enable-debug --with-target-bits=64` + +#### Configure Options + +Complete details on all the OpenJDK `configure` options can be seen with: + +> **`bash ./configure --help=short`** + +Use `-help` to see all the `configure` options available. You can generate any +number of different configurations, e.g. debug, release, 32, 64, etc. + +Some of the more commonly used `configure` options are: + +> **`--enable-debug`** \ +> set the debug level to fastdebug (this is a shorthand for +> `--with-debug-level=fastdebug`) + + + +> **`--with-alsa=`**_path_ \ +> select the location of the Advanced Linux Sound Architecture (ALSA) + +> Version 0.9.1 or newer of the ALSA files are required for building the + OpenJDK on Linux. These Linux files are usually available from an "alsa" of + "libasound" development package, and it's highly recommended that you try + and use the package provided by the particular version of Linux that you are + using. + +> **`--with-boot-jdk=`**_path_ \ +> select the [Bootstrap JDK](#bootjdk) + +> **`--with-boot-jdk-jvmargs=`**"_args_" \ +> provide the JVM options to be used to run the [Bootstrap JDK](#bootjdk) + +> **`--with-cacerts=`**_path_ \ +> select the path to the cacerts file. + +> See [Certificate Authority on + Wikipedia](http://en.wikipedia.org/wiki/Certificate_Authority) for a + better understanding of the Certificate Authority (CA). A certificates file + named "cacerts" represents a system-wide keystore with CA certificates. In + JDK and JRE binary bundles, the "cacerts" file contains root CA certificates + from several public CAs (e.g., VeriSign, Thawte, and Baltimore). The source + contain a cacerts file without CA root certificates. Formal JDK builders will + need to secure permission from each public CA and include the certificates + into their own custom cacerts file. Failure to provide a populated cacerts + file will result in verification errors of a certificate chain during + runtime. By default an empty cacerts file is provided and that should be fine + for most JDK developers. + + + +> **`--with-cups=`**_path_ \ +> select the CUPS install location + +> The Common UNIX Printing System (CUPS) Headers are required for building the + OpenJDK on Solaris and Linux. The Solaris header files can be obtained by + installing the package **SFWcups** from the Solaris Software Companion + CD/DVD, these often will be installed into the directory `/opt/sfw/cups`. + +> The CUPS header files can always be downloaded from + [www.cups.org](http://www.cups.org). + +> **`--with-cups-include=`**_path_ \ +> select the CUPS include directory location + +> **`--with-debug-level=`**_level_ \ +> select the debug information level of release, fastdebug, or slowdebug + +> **`--with-dev-kit=`**_path_ \ +> select location of the compiler install or developer install location + + + +> **`--with-freetype=`**_path_ \ +> select the freetype files to use. + +> Expecting the freetype libraries under `lib/` and the headers under + `include/`. + +> Version 2.3 or newer of FreeType is required. On Unix systems required files + can be available as part of your distribution (while you still may need to + upgrade them). Note that you need development version of package that + includes both the FreeType library and header files. + +> You can always download latest FreeType version from the [FreeType + website](http://www.freetype.org). Building the freetype 2 libraries from + scratch is also possible, however on Windows refer to the [Windows FreeType + DLL build instructions](http://freetype.freedesktop.org/wiki/FreeType_DLL). + +> Note that by default FreeType is built with byte code hinting support + disabled due to licensing restrictions. In this case, text appearance and + metrics are expected to differ from Sun's official JDK build. See the + [SourceForge FreeType2 Home Page](http://freetype.sourceforge.net/freetype2) + for more information. + +> **`--with-import-hotspot=`**_path_ \ +> select the location to find hotspot binaries from a previous build to avoid + building hotspot + +> **`--with-target-bits=`**_arg_ \ +> select 32 or 64 bit build + +> **`--with-jvm-variants=`**_variants_ \ +> select the JVM variants to build from, comma separated list that can + include: server, client, kernel, zero and zeroshark + +> **`--with-memory-size=`**_size_ \ +> select the RAM size that GNU make will think this system has + +> **`--with-msvcr-dll=`**_path_ \ +> select the `msvcr100.dll` file to include in the Windows builds (C/C++ + runtime library for Visual Studio). + +> This is usually picked up automatically from the redist directories of + Visual Studio 2010. + +> **`--with-num-cores=`**_cores_ \ +> select the number of cores to use (processor count or CPU count) + + + +> **`--with-x=`**_path_ \ +> select the location of the X11 and xrender files. + +> The XRender Extension Headers are required for building the OpenJDK on + Solaris and Linux. The Linux header files are usually available from a + "Xrender" development package, it's recommended that you try and use the + package provided by the particular distribution of Linux that you are using. + The Solaris XRender header files is included with the other X11 header files + in the package **SFWxwinc** on new enough versions of Solaris and will be + installed in `/usr/X11/include/X11/extensions/Xrender.h` or + `/usr/openwin/share/include/X11/extensions/Xrender.h` + +------------------------------------------------------------------------------- + +### Make + +The basic invocation of the `make` utility looks like: + +> **`make all`** + +This will start the build to the output directory containing the +"configuration" that was created by the `configure` script. Run `make help` for +more information on the available targets. + +There are some of the make targets that are of general interest: + +> _empty_ \ +> build everything but no images + +> **`all`** \ +> build everything including images + +> **`all-conf`** \ +> build all configurations + +> **`images`** \ +> create complete j2sdk and j2re images + +> **`install`** \ +> install the generated images locally, typically in `/usr/local` + +> **`clean`** \ +> remove all files generated by make, but not those generated by `configure` + +> **`dist-clean`** \ +> remove all files generated by both and `configure` (basically killing the + configuration) + +> **`help`** \ +> give some help on using `make`, including some interesting make targets + +------------------------------------------------------------------------------- + +## Testing + +When the build is completed, you should see the generated binaries and +associated files in the `j2sdk-image` directory in the output directory. In +particular, the `build/*/images/j2sdk-image/bin` directory should contain +executables for the OpenJDK tools and utilities for that configuration. The +testing tool `jtreg` will be needed and can be found at: [the jtreg +site](http://openjdk.java.net/jtreg/). The provided regression tests in the +repositories can be run with the command: + +> **``cd test && make PRODUCT_HOME=`pwd`/../build/*/images/j2sdk-image all``** + +------------------------------------------------------------------------------- + +## Appendix A: Hints and Tips + +### FAQ + +**Q:** The `generated-configure.sh` file looks horrible! How are you going to +edit it? \ +**A:** The `generated-configure.sh` file is generated (think "compiled") by the +autoconf tools. The source code is in `configure.ac` and various .m4 files in +common/autoconf, which are much more readable. + +**Q:** Why is the `generated-configure.sh` file checked in, if it is +generated? \ +**A:** If it was not generated, every user would need to have the autoconf +tools installed, and re-generate the `configure` file as the first step. Our +goal is to minimize the work needed to be done by the user to start building +OpenJDK, and to minimize the number of external dependencies required. + +**Q:** Do you require a specific version of autoconf for regenerating +`generated-configure.sh`? \ +**A:** Yes, version 2.69 is required and should be easy enough to aquire on all +supported operating systems. The reason for this is to avoid large spurious +changes in `generated-configure.sh`. + +**Q:** How do you regenerate `generated-configure.sh` after making changes to +the input files? \ +**A:** Regnerating `generated-configure.sh` should always be done using the +script `common/autoconf/autogen.sh` to ensure that the correct files get +updated. This script should also be run after mercurial tries to merge +`generated-configure.sh` as a merge of the generated file is not guaranteed to +be correct. + +**Q:** What are the files in `common/makefiles/support/*` for? They look like +gibberish. \ +**A:** They are a somewhat ugly hack to compensate for command line length +limitations on certain platforms (Windows, Solaris). Due to a combination of +limitations in make and the shell, command lines containing too many files will +not work properly. These helper files are part of an elaborate hack that will +compress the command line in the makefile and then uncompress it safely. We're +not proud of it, but it does fix the problem. If you have any better +suggestions, we're all ears! :-) + +**Q:** I want to see the output of the commands that make runs, like in the old +build. How do I do that? \ +**A:** You specify the `LOG` variable to make. There are several log levels: + + * **`warn`** -- Default and very quiet. + * **`info`** -- Shows more progress information than warn. + * **`debug`** -- Echos all command lines and prints all macro calls for + compilation definitions. + * **`trace`** -- Echos all \$(shell) command lines as well. + +**Q:** When do I have to re-run `configure`? \ +**A:** Normally you will run `configure` only once for creating a +configuration. You need to re-run configuration only if you want to change any +configuration options, or if you pull down changes to the `configure` script. + +**Q:** I have added a new source file. Do I need to modify the makefiles? \ +**A:** Normally, no. If you want to create e.g. a new native library, you will +need to modify the makefiles. But for normal file additions or removals, no +changes are needed. There are certan exceptions for some native libraries where +the source files are spread over many directories which also contain sources +for other libraries. In these cases it was simply easier to create include +lists rather than excludes. + +**Q:** When I run `configure --help`, I see many strange options, like +`--dvidir`. What is this? \ +**A:** Configure provides a slew of options by default, to all projects that +use autoconf. Most of them are not used in OpenJDK, so you can safely ignore +them. To list only OpenJDK specific features, use `configure --help=short` +instead. + +**Q:** `configure` provides OpenJDK-specific features such as +`--with-builddeps-server` that are not described in this document. What about +those? \ +**A:** Try them out if you like! But be aware that most of these are +experimental features. Many of them don't do anything at all at the moment; the +option is just a placeholder. Others depend on pieces of code or infrastructure +that is currently not ready for prime time. + +**Q:** How will you make sure you don't break anything? \ +**A:** We have a script that compares the result of the new build system with +the result of the old. For most part, we aim for (and achieve) byte-by-byte +identical output. There are however technical issues with e.g. native binaries, +which might differ in a byte-by-byte comparison, even when building twice with +the old build system. For these, we compare relevant aspects (e.g. the symbol +table and file size). Note that we still don't have 100% equivalence, but we're +close. + +**Q:** I noticed this thing X in the build that looks very broken by design. +Why don't you fix it? \ +**A:** Our goal is to produce a build output that is as close as technically +possible to the old build output. If things were weird in the old build, they +will be weird in the new build. Often, things were weird before due to +obscurity, but in the new build system the weird stuff comes up to the surface. +The plan is to attack these things at a later stage, after the new build system +is established. + +**Q:** The code in the new build system is not that well-structured. Will you +fix this? \ +**A:** Yes! The new build system has grown bit by bit as we converted the old +system. When all of the old build system is converted, we can take a step back +and clean up the structure of the new build system. Some of this we plan to do +before replacing the old build system and some will need to wait until after. + +**Q:** Is anything able to use the results of the new build's default make +target? \ +**A:** Yes, this is the minimal (or roughly minimal) set of compiled output +needed for a developer to actually execute the newly built JDK. The idea is +that in an incremental development fashion, when doing a normal make, you +should only spend time recompiling what's changed (making it purely +incremental) and only do the work that's needed to actually run and test your +code. The packaging stuff that is part of the `images` target is not needed for +a normal developer who wants to test his new code. Even if it's quite fast, +it's still unnecessary. We're targeting sub-second incremental rebuilds! ;-) +(Or, well, at least single-digit seconds...) + +**Q:** I usually set a specific environment variable when building, but I can't +find the equivalent in the new build. What should I do? \ +**A:** It might very well be that we have neglected to add support for an +option that was actually used from outside the build system. Email us and we +will add support for it! + +### Build Performance Tips + +Building OpenJDK requires a lot of horsepower. Some of the build tools can be +adjusted to utilize more or less of resources such as parallel threads and +memory. The `configure` script analyzes your system and selects reasonable +values for such options based on your hardware. If you encounter resource +problems, such as out of memory conditions, you can modify the detected values +with: + + * **`--with-num-cores`** -- number of cores in the build system, e.g. + `--with-num-cores=8` + * **`--with-memory-size`** -- memory (in MB) available in the build system, + e.g. `--with-memory-size=1024` + +It might also be necessary to specify the JVM arguments passed to the Bootstrap +JDK, using e.g. `--with-boot-jdk-jvmargs="-Xmx8G -enableassertions"`. Doing +this will override the default JVM arguments passed to the Bootstrap JDK. + +One of the top goals of the new build system is to improve the build +performance and decrease the time needed to build. This will soon also apply to +the java compilation when the Smart Javac wrapper is making its way into jdk8. +It can be tried in the build-infra repository already. You are likely to find +that the new build system is faster than the old one even without this feature. + +At the end of a successful execution of `configure`, you will get a performance +summary, indicating how well the build will perform. Here you will also get +performance hints. If you want to build fast, pay attention to those! + +#### Building with ccache + +A simple way to radically speed up compilation of native code +(typically hotspot and native libraries in JDK) is to install +ccache. This will cache and reuse prior compilation results, if the +source code is unchanged. However, ccache versions prior to 3.1.4 does +not work correctly with the precompiled headers used in OpenJDK. So if +your platform supports ccache at 3.1.4 or later, we highly recommend +installing it. This is currently only supported on linux. + +#### Building on local disk + +If you are using network shares, e.g. via NFS, for your source code, make sure +the build directory is situated on local disk. The performance penalty is +extremely high for building on a network share, close to unusable. + +#### Building only one JVM + +The old build builds multiple JVMs on 32-bit systems (client and server; and on +Windows kernel as well). In the new build we have changed this default to only +build server when it's available. This improves build times for those not +interested in multiple JVMs. To mimic the old behavior on platforms that +support it, use `--with-jvm-variants=client,server`. + +#### Selecting the number of cores to build on + +By default, `configure` will analyze your machine and run the make process in +parallel with as many threads as you have cores. This behavior can be +overridden, either "permanently" (on a `configure` basis) using +`--with-num-cores=N` or for a single build only (on a make basis), using +`make JOBS=N`. + +If you want to make a slower build just this time, to save some CPU power for +other processes, you can run e.g. `make JOBS=2`. This will force the makefiles +to only run 2 parallel processes, or even `make JOBS=1` which will disable +parallelism. + +If you want to have it the other way round, namely having slow builds default +and override with fast if you're impatient, you should call `configure` with +`--with-num-cores=2`, making 2 the default. If you want to run with more cores, +run `make JOBS=8` + +### Troubleshooting + +#### Solving build problems + +If the build fails (and it's not due to a compilation error in a source file +you've changed), the first thing you should do is to re-run the build with more +verbosity. Do this by adding `LOG=debug` to your make command line. + +The build log (with both stdout and stderr intermingled, basically the same as +you see on your console) can be found as `build.log` in your build directory. + +You can ask for help on build problems with the new build system on either the +[build-dev](http://mail.openjdk.java.net/mailman/listinfo/build-dev) or the +[build-infra-dev](http://mail.openjdk.java.net/mailman/listinfo/build-infra-dev) +mailing lists. Please include the relevant parts of the build log. + +A build can fail for any number of reasons. Most failures are a result of +trying to build in an environment in which all the pre-build requirements have +not been met. The first step in troubleshooting a build failure is to recheck +that you have satisfied all the pre-build requirements for your platform. +Scanning the `configure` log is a good first step, making sure that what it +found makes sense for your system. Look for strange error messages or any +difficulties that `configure` had in finding things. + +Some of the more common problems with builds are briefly described below, with +suggestions for remedies. + + * **Corrupted Bundles on Windows:** \ + Some virus scanning software has been known to corrupt the downloading of + zip bundles. It may be necessary to disable the 'on access' or 'real time' + virus scanning features to prevent this corruption. This type of 'real time' + virus scanning can also slow down the build process significantly. + Temporarily disabling the feature, or excluding the build output directory + may be necessary to get correct and faster builds. + + * **Slow Builds:** \ + If your build machine seems to be overloaded from too many simultaneous C++ + compiles, try setting the `JOBS=1` on the `make` command line. Then try + increasing the count slowly to an acceptable level for your system. Also: + + Creating the javadocs can be very slow, if you are running javadoc, consider + skipping that step. + + Faster CPUs, more RAM, and a faster DISK usually helps. The VM build tends + to be CPU intensive (many C++ compiles), and the rest of the JDK will often + be disk intensive. + + Faster compiles are possible using a tool called + [ccache](http://ccache.samba.org/). + + * **File time issues:** \ + If you see warnings that refer to file time stamps, e.g. + + > _Warning message:_ ` File 'xxx' has modification time in the future.` \ + > _Warning message:_ ` Clock skew detected. Your build may be incomplete.` + + These warnings can occur when the clock on the build machine is out of sync + with the timestamps on the source files. Other errors, apparently unrelated + but in fact caused by the clock skew, can occur along with the clock skew + warnings. These secondary errors may tend to obscure the fact that the true + root cause of the problem is an out-of-sync clock. + + If you see these warnings, reset the clock on the build machine, run + "`gmake clobber`" or delete the directory containing the build output, and + restart the build from the beginning. + + * **Error message: `Trouble writing out table to disk`** \ + Increase the amount of swap space on your build machine. This could be + caused by overloading the system and it may be necessary to use: + + > `make JOBS=1` + + to reduce the load on the system. + + * **Error Message: `libstdc++ not found`:** \ + This is caused by a missing libstdc++.a library. This is installed as part + of a specific package (e.g. libstdc++.so.devel.386). By default some 64-bit + Linux versions (e.g. Fedora) only install the 64-bit version of the + libstdc++ package. Various parts of the JDK build require a static link of + the C++ runtime libraries to allow for maximum portability of the built + images. + + * **Linux Error Message: `cannot restore segment prot after reloc`** \ + This is probably an issue with SELinux (See [SELinux on + Wikipedia](http://en.wikipedia.org/wiki/SELinux)). Parts of the VM is built + without the `-fPIC` for performance reasons. + + To completely disable SELinux: + + 1. `$ su root` + 2. `# system-config-securitylevel` + 3. `In the window that appears, select the SELinux tab` + 4. `Disable SELinux` + + Alternatively, instead of completely disabling it you could disable just + this one check. + + 1. Select System->Administration->SELinux Management + 2. In the SELinux Management Tool which appears, select "Boolean" from the + menu on the left + 3. Expand the "Memory Protection" group + 4. Check the first item, labeled "Allow all unconfined executables to use + libraries requiring text relocation ..." + + * **Windows Error Messages:** \ + `*** fatal error - couldn't allocate heap, ... ` \ + `rm fails with "Directory not empty"` \ + `unzip fails with "cannot create ... Permission denied"` \ + `unzip fails with "cannot create ... Error 50"` + + The CYGWIN software can conflict with other non-CYGWIN software. See the + CYGWIN FAQ section on [BLODA (applications that interfere with + CYGWIN)](http://cygwin.com/faq/faq.using.html#faq.using.bloda). + + * **Windows Error Message: `spawn failed`** \ + Try rebooting the system, or there could be some kind of issue with the disk + or disk partition being used. Sometimes it comes with a "Permission Denied" + message. + +------------------------------------------------------------------------------- + +## Appendix B: GNU make + +The Makefiles in the OpenJDK are only valid when used with the GNU version of +the utility command `make` (usually called `gmake` on Solaris). A few notes +about using GNU make: + + * You need GNU make version 3.81 or newer. If the GNU make utility on your + systems is not 3.81 or newer, see "[Building GNU make](#buildgmake)". + * Place the location of the GNU make binary in the `PATH`. + * **Solaris:** Do NOT use `/usr/bin/make` on Solaris. If your Solaris system + has the software from the Solaris Developer Companion CD installed, you + should try and use `gmake` which will be located in either the `/usr/bin`, + `/opt/sfw/bin` or `/usr/sfw/bin` directory. + * **Windows:** Make sure you start your build inside a bash shell. + * **Mac OS X:** The XCode "command line tools" must be installed on your Mac. + +Information on GNU make, and access to ftp download sites, are available on the +[GNU make web site](http://www.gnu.org/software/make/make.html). The latest +source to GNU make is available at +[ftp.gnu.org/pub/gnu/make/](http://ftp.gnu.org/pub/gnu/make/). + +### Building GNU make + +First step is to get the GNU make 3.81 or newer source from +[ftp.gnu.org/pub/gnu/make/](http://ftp.gnu.org/pub/gnu/make/). Building is a +little different depending on the OS but is basically done with: + + bash ./configure + make + +------------------------------------------------------------------------------- + +## Appendix C: Build Environments + +### Minimum Build Environments + +This file often describes specific requirements for what we call the "minimum +build environments" (MBE) for this specific release of the JDK. What is listed +below is what the Oracle Release Engineering Team will use to build the Oracle +JDK product. Building with the MBE will hopefully generate the most compatible +bits that install on, and run correctly on, the most variations of the same +base OS and hardware architecture. In some cases, these represent what is often +called the least common denominator, but each Operating System has different +aspects to it. + +In all cases, the Bootstrap JDK version minimum is critical, we cannot +guarantee builds will work with older Bootstrap JDK's. Also in all cases, more +RAM and more processors is better, the minimums listed below are simply +recommendations. + +With Solaris and Mac OS X, the version listed below is the oldest release we +can guarantee builds and works, and the specific version of the compilers used +could be critical. + +With Windows the critical aspect is the Visual Studio compiler used, which due +to it's runtime, generally dictates what Windows systems can do the builds and +where the resulting bits can be used. + +**NOTE: We expect a change here off these older Windows OS releases and to a +'less older' one, probably Windows 2008R2 X64.** + +With Linux, it was just a matter of picking a stable distribution that is a +good representative for Linux in general. + +**NOTE: We expect a change here from Fedora 9 to something else, but it has not +been completely determined yet, possibly Ubuntu 12.04 X64, unbiased community +feedback would be welcome on what a good choice would be here.** + +It is understood that most developers will NOT be using these specific +versions, and in fact creating these specific versions may be difficult due to +the age of some of this software. It is expected that developers are more often +using the more recent releases and distributions of these operating systems. + +Compilation problems with newer or different C/C++ compilers is a common +problem. Similarly, compilation problems related to changes to the +`/usr/include` or system header files is also a common problem with older, +newer, or unreleased OS versions. Please report these types of problems as bugs +so that they can be dealt with accordingly. + +Bootstrap JDK: JDK 7u7 + + Base OS and Architecture OS C/C++ Compiler Processors RAM Minimum DISK Needs + --------------------------------------------- ---------------------------------------------- ------------------------------------------------------- ------------ ------------- ------------ + Linux X86 (32-bit) and X64 (64-bit) Fedora 9 gcc 4.3 2 or more 1 GB 6 GB + Solaris SPARC (32-bit) and SPARCV9 (64-bit) Solaris 10 Update 6 Studio 12 Update 1 + patches 4 or more 4 GB 8 GB + Solaris X86 (32-bit) and X64 (64-bit) Solaris 10 Update 6 Studio 12 Update 1 + patches 4 or more 4 GB 8 GB + Windows X86 (32-bit) Windows XP Microsoft Visual Studio C++ 2010 Professional Edition 2 or more 2 GB 6 GB + Windows X64 (64-bit) Windows Server 2003 - Enterprise x64 Edition Microsoft Visual Studio C++ 2010 Professional Edition 2 or more 2 GB 6 GB + Mac OS X X64 (64-bit) Mac OS X 10.7 "Lion" XCode 4.5.2 or newer 2 or more 4 GB 6 GB + +------------------------------------------------------------------------------- + +### Specific Developer Build Environments + +We won't be listing all the possible environments, but we will try to provide +what information we have available to us. + +**NOTE: The community can help out by updating this part of the document.** + +#### Fedora + +After installing the latest [Fedora](http://fedoraproject.org) you need to +install several build dependencies. The simplest way to do it is to execute the +following commands as user `root`: + + yum-builddep java-1.7.0-openjdk + yum install gcc gcc-c++ + +In addition, it's necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/usr/lib/jvm/java-openjdk/bin:${PATH}" + +#### CentOS 5.5 + +After installing [CentOS 5.5](http://www.centos.org/) you need to make sure you +have the following Development bundles installed: + + * Development Libraries + * Development Tools + * Java Development + * X Software Development (Including XFree86-devel) + +Plus the following packages: + + * cups devel: Cups Development Package + * alsa devel: Alsa Development Package + * Xi devel: libXi.so Development Package + +The freetype 2.3 packages don't seem to be available, but the freetype 2.3 +sources can be downloaded, built, and installed easily enough from [the +freetype site](http://downloads.sourceforge.net/freetype). Build and install +with something like: + + bash ./configure + make + sudo -u root make install + +Mercurial packages could not be found easily, but a Google search should find +ones, and they usually include Python if it's needed. + +#### Debian 5.0 (Lenny) + +After installing [Debian](http://debian.org) 5 you need to install several +build dependencies. The simplest way to install the build dependencies is to +execute the following commands as user `root`: + + aptitude build-dep openjdk-7 + aptitude install openjdk-7-jdk libmotif-dev + +In addition, it's necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}" + +#### Ubuntu 12.04 + +After installing [Ubuntu](http://ubuntu.org) 12.04 you need to install several +build dependencies. The simplest way to do it is to execute the following +commands: + + sudo aptitude build-dep openjdk-7 + sudo aptitude install openjdk-7-jdk + +In addition, it's necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/usr/lib/jvm/java-7-openjdk/bin:${PATH}" + +#### OpenSUSE 11.1 + +After installing [OpenSUSE](http://opensuse.org) 11.1 you need to install +several build dependencies. The simplest way to install the build dependencies +is to execute the following commands: + + sudo zypper source-install -d java-1_7_0-openjdk + sudo zypper install make + +In addition, it is necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:$[PATH}" + +Finally, you need to unset the `JAVA_HOME` environment variable: + + export -n JAVA_HOME` + +#### Mandriva Linux One 2009 Spring + +After installing [Mandriva](http://mandriva.org) Linux One 2009 Spring you need +to install several build dependencies. The simplest way to install the build +dependencies is to execute the following commands as user `root`: + + urpmi java-1.7.0-openjdk-devel make gcc gcc-c++ freetype-devel zip unzip + libcups2-devel libxrender1-devel libalsa2-devel libstc++-static-devel + libxtst6-devel libxi-devel + +In addition, it is necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/usr/lib/jvm/java-1.7.0-openjdk/bin:${PATH}" + +#### OpenSolaris 2009.06 + +After installing [OpenSolaris](http://opensolaris.org) 2009.06 you need to +install several build dependencies. The simplest way to install the build +dependencies is to execute the following commands: + + pfexec pkg install SUNWgmake SUNWj7dev sunstudioexpress SUNWcups SUNWzip + SUNWunzip SUNWxwhl SUNWxorg-headers SUNWaudh SUNWfreetype2 + +In addition, it is necessary to set a few environment variables for the build: + + export LANG=C + export PATH="/opt/SunStudioExpress/bin:${PATH}" + +------------------------------------------------------------------------------- + +End of the OpenJDK build README document. + +Please come again! diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/make/Main.gmk openjdk-8-8u402-ga/=unpacked-tar8=/make/Main.gmk --- openjdk-8-8u392-ga/=unpacked-tar8=/make/Main.gmk 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/make/Main.gmk 2024-01-11 01:53:23.000000000 +0000 @@ -167,6 +167,9 @@ @($(CD) $(SRC_ROOT)/make && $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) -f Javadoc.gmk docs-zip) @$(call TargetExit) +update-build-docs: + +($(CD) $(SRC_ROOT)/make && $(MAKE) $(MAKE_ARGS) -f UpdateBuildDocs.gmk) + sign-jars: jdk sign-jars-only sign-jars-only: start-make @$(call TargetEnter) @@ -258,7 +261,7 @@ @( cd $(OUTPUT_ROOT) && $(BASH) $(TOPDIR)/configure $(CONFIGURE_COMMAND_LINE) ) .PHONY: langtools corba jaxp jaxws hotspot jdk nashorn images overlay-images install test docs docs-zip -.PHONY: langtools-only corba-only jaxp-only jaxws-only hotspot-only jdk-only nashorn-only images-only overlay-images-only install-only test-only docs-only docs-zip-only +.PHONY: langtools-only corba-only jaxp-only jaxws-only hotspot-only jdk-only nashorn-only images-only overlay-images-only install-only test-only docs-only docs-zip-only update-build-docs .PHONY: default all clean dist-clean bootcycle-images start-make .PHONY: clean-langtools clean-corba clean-jaxp clean-jaxws clean-hotspot clean-jdk clean-nashorn clean-images clean-docs clean-docs-zip clean-test clean-overlay-images clean-bootcycle-build .PHONY: profiles profiles-only diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/make/UpdateBuildDocs.gmk openjdk-8-8u402-ga/=unpacked-tar8=/make/UpdateBuildDocs.gmk --- openjdk-8-8u392-ga/=unpacked-tar8=/make/UpdateBuildDocs.gmk 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/make/UpdateBuildDocs.gmk 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,97 @@ +# +# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +default: all + +include $(SPEC) +include MakeBase.gmk + +################################################################################ +# This makefile updates the generated build html documentation. +# +################################################################################ + +ifeq ($(PANDOC), ) + $(info No pandoc executable was detected by configure) + $(error Cannot continue) +endif + +################################################################################ +# Setup make rules for converting a markdown file to html. +# +# Parameter 1 is the name of the rule. This name is used as variable prefix, +# and the targets generated are listed in a variable by that name. +# +# Remaining parameters are named arguments. These include: +# SOURCE_FILE The markdown source file +# TARGET_DIR The directory where to store the generated html file +# +define SetupMarkdownToHtml + $(foreach i,2 3, $(if $($i),$1_$(strip $($i)))$(NEWLINE)) + $(call LogSetupMacroEntry,SetupMarkdownToHtml($1),$2,$3) + $(if $(4),$(error Internal makefile error: Too many arguments to SetupMarkdownToHtml, please update UpdateBuildDocs.gmk)) + + ifeq ($$($1_SOURCE_FILE), ) + $$(error SOURCE_FILE is missing in SetupMarkdownToHtml $1) + endif + + ifeq ($$($1_TARGET_DIR), ) + $$(error TARGET_DIR is missing in SetupMarkdownToHtml $1) + endif + + $1_BASENAME := $$(notdir $$(basename $$($1_SOURCE_FILE))) + $1_OUTPUT_FILE := $$($1_TARGET_DIR)/$$($1_BASENAME).html + +$$($1_OUTPUT_FILE): $$($1_SOURCE_FILE) + $$(ECHO) $$(LOG_INFO) Converting $$(notdir $1) to html + $$(MKDIR) -p $$($1_TARGET_DIR) + $$(PANDOC) -f markdown -t html --standalone '$$<' -o '$$@' + TOO_LONG_LINES=`$$(GREP) -E -e '^.{80}.+$$$$' $$<` ; \ + if [ "x$${TOO_LONG_LINES}" != x ]; then \ + $$(ECHO) "Warning: Unsuitable markdown in $$<:" ; \ + $$(ECHO) "The following lines are longer than 80 characters:" ; \ + $$(GREP) -E -e '^.{80}.+$$$$' $$< ; \ + fi + + $1 := $$($1_OUTPUT_FILE) + + TARGETS += $$($1) +endef + +################################################################################ + +BUILD_DOCS_DIR := $(TOPDIR)/doc +BUILD_DOCS_MD_FILE := building.md + +$(eval $(call SetupMarkdownToHtml,building, \ + SOURCE_FILE := $(BUILD_DOCS_DIR)/$(BUILD_DOCS_MD_FILE), \ + TARGET_DIR := $(BUILD_DOCS_DIR) \ +)) + +################################################################################ + +all: $(TARGETS) + +.PHONY: all default diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/ClassFileInstaller.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/ClassFileInstaller.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/ClassFileInstaller.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/ClassFileInstaller.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * Dump a class file for a class on the class path in the current directory, or + * in the specified JAR file. This class is usually used when you build a class + * from a test library, but want to use this class in a sub-process. + * + * For example, to build the following library class: + * test/lib/sun/hotspot/WhiteBox.java + * + * You would use the following tags: + * + * @library /test/lib + * @build sun.hotspot.WhiteBox + * + * JTREG would build the class file under + * ${JTWork}/classes/test/lib/sun/hotspot/WhiteBox.class + * + * With you run your main test class using "@run main MyMainClass", JTREG would setup the + * -classpath to include "${JTWork}/classes/test/lib/", so MyMainClass would be able to + * load the WhiteBox class. + * + * However, if you run a sub process, and do not wish to use the exact same -classpath, + * You can use ClassFileInstaller to ensure that WhiteBox is available in the current + * directory of your test: + * + * @run main ClassFileInstaller sun.hotspot.WhiteBox + * + * Or, you can use the -jar option to store the class in the specified JAR file. If a relative + * path name is given, the JAR file would be relative to the current directory of + * + * @run main ClassFileInstaller -jar myjar.jar sun.hotspot.WhiteBox + */ +public class ClassFileInstaller { + /** + * You can enable debug tracing of ClassFileInstaller by running JTREG with + * jtreg -DClassFileInstaller.debug=true ... + */ + public static boolean DEBUG = Boolean.getBoolean("ClassFileInstaller.debug"); + + /** + * @param args The names of the classes to dump + * @throws Exception + */ + public static void main(String... args) throws Exception { + if (args.length > 1 && args[0].equals("-jar")) { + if (args.length < 2) { + throw new RuntimeException("Usage: ClassFileInstaller \n" + + "where possible options include:\n" + + " -jar Write to the JAR file "); + } + writeJar(args[1], null, args, 2, args.length); + } else { + if (DEBUG) { + System.out.println("ClassFileInstaller: Writing to " + System.getProperty("user.dir")); + } + for (String arg : args) { + writeClassToDisk(arg); + } + } + } + + public static class Manifest { + private InputStream in; + + private Manifest(InputStream in) { + this.in = in; + } + + static Manifest fromSourceFile(String fileName) throws Exception { + String pathName = System.getProperty("test.src") + File.separator + fileName; + return new Manifest(new FileInputStream(pathName)); + } + + // Example: + // String manifest = "Premain-Class: RedefineClassHelper\n" + + // "Can-Redefine-Classes: true\n"; + // ClassFileInstaller.writeJar("redefineagent.jar", + // ClassFileInstaller.Manifest.fromString(manifest), + // "RedefineClassHelper"); + static Manifest fromString(String manifest) throws Exception { + return new Manifest(new ByteArrayInputStream(manifest.getBytes())); + } + + public InputStream getInputStream() { + return in; + } + } + + private static void writeJar(String jarFile, Manifest manifest, String classes[], int from, int to) throws Exception { + if (DEBUG) { + System.out.println("ClassFileInstaller: Writing to " + getJarPath(jarFile)); + } + + (new File(jarFile)).delete(); + FileOutputStream fos = new FileOutputStream(jarFile); + ZipOutputStream zos = new ZipOutputStream(fos); + + // The manifest must be the first or second entry. See comments in JarInputStream + // constructor and JDK-5046178. + if (manifest != null) { + writeToDisk(zos, "META-INF/MANIFEST.MF", manifest.getInputStream()); + } + + for (int i=from; i 0) { + pathName = prependPath + "/" + pathName; + } + writeToDisk(zos, pathName, is); + } + + public static void writeClassToDisk(String className, byte[] bytecode) throws Exception { + writeClassToDisk(null, className, bytecode); + } + private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode) throws Exception { + writeClassToDisk(zos, className, bytecode, ""); + } + + public static void writeClassToDisk(String className, byte[] bytecode, String prependPath) throws Exception { + writeClassToDisk(null, className, bytecode, prependPath); + } + private static void writeClassToDisk(ZipOutputStream zos, String className, byte[] bytecode, String prependPath) throws Exception { + // Convert dotted class name to a path to a class file + String pathName = className.replace('.', '/').concat(".class"); + if (prependPath.length() > 0) { + pathName = prependPath + "/" + pathName; + } + writeToDisk(zos, pathName, new ByteArrayInputStream(bytecode)); + } + + private static void writeToDisk(ZipOutputStream zos, String pathName, InputStream is) throws Exception { + if (DEBUG) { + System.out.println("ClassFileInstaller: Writing " + pathName); + } + if (zos != null) { + ZipEntry ze = new ZipEntry(pathName); + zos.putNextEntry(ze); + byte[] buf = new byte[1024]; + int len; + while ((len = is.read(buf))>0){ + zos.write(buf, 0, len); + } + } else { + // Create the class file's package directory + Path p = Paths.get(pathName); + if (pathName.contains("/")) { + Files.createDirectories(p.getParent()); + } + // Create the class file + Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING); + } + is.close(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Asserts.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Asserts.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Asserts.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Asserts.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,620 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.Objects; + +/** + * Asserts that can be used for verifying assumptions in tests. + * + * An assertion will throw a {@link RuntimeException} if the assertion isn't true. + * All the asserts can be imported into a test by using a static import: + * + *
+ * {@code
+ * import static jdk.testlibrary.Asserts.*;
+ * }
+ *
+ * Always provide a message describing the assumption if the line number of the
+ * failing assertion isn't enough to understand why the assumption failed. For
+ * example, if the assertion is in a loop or in a method that is called
+ * multiple times, then the line number won't provide enough context to
+ * understand the failure.
+ * 
+ */ +public class Asserts { + + /** + * Shorthand for {@link #assertLessThan(Comparable, Comparable)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertLessThan(Comparable, Comparable) + */ + public static > void assertLT(T lhs, T rhs) { + assertLessThan(lhs, rhs); + } + + /** + * Shorthand for {@link #assertLessThan(Comparable, Comparable, String)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertLessThan(Comparable, Comparable, String) + */ + public static > void assertLT(T lhs, T rhs, String msg) { + assertLessThan(lhs, rhs, msg); + } + + /** + * Calls {@link #assertLessThan(Comparable, Comparable, String)} with a default message. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertLessThan(Comparable, Comparable, String) + */ + public static > void assertLessThan(T lhs, T rhs) { + assertLessThan(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is less than {@code rhs}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static >void assertLessThan(T lhs, T rhs, String msg) { + if (!(compare(lhs, rhs, msg) < 0)) { + msg = Objects.toString(msg, "assertLessThan") + + ": expected that " + Objects.toString(lhs) + + " < " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Shorthand for {@link #assertLessThanOrEqual(Comparable, Comparable)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertLessThanOrEqual(Comparable, Comparable) + */ + public static > void assertLTE(T lhs, T rhs) { + assertLessThanOrEqual(lhs, rhs); + } + + /** + * Shorthand for {@link #assertLessThanOrEqual(Comparable, Comparable, String)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertLessThanOrEqual(Comparable, Comparable, String) + */ + public static > void assertLTE(T lhs, T rhs, String msg) { + assertLessThanOrEqual(lhs, rhs, msg); + } + + /** + * Calls {@link #assertLessThanOrEqual(Comparable, Comparable, String)} with a default message. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertLessThanOrEqual(Comparable, Comparable, String) + */ + public static > void assertLessThanOrEqual(T lhs, T rhs) { + assertLessThanOrEqual(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is less than or equal to {@code rhs}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static > void assertLessThanOrEqual(T lhs, T rhs, String msg) { + if (!(compare(lhs, rhs, msg) <= 0)) { + msg = Objects.toString(msg, "assertLessThanOrEqual") + + ": expected that " + Objects.toString(lhs) + + " <= " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Shorthand for {@link #assertEquals(Object, Object)}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertEquals(Object, Object) + */ + public static void assertEQ(Object lhs, Object rhs) { + assertEquals(lhs, rhs); + } + + /** + * Shorthand for {@link #assertEquals(Object, Object, String)}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertEquals(Object, Object, String) + */ + public static void assertEQ(Object lhs, Object rhs, String msg) { + assertEquals(lhs, rhs, msg); + } + + /** + * Calls {@link #assertEquals(java.lang.Object, java.lang.Object, java.lang.String)} with a default message. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertEquals(Object, Object, String) + */ + public static void assertEquals(Object lhs, Object rhs) { + assertEquals(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is equal to {@code rhs}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertEquals(Object lhs, Object rhs, String msg) { + if ((lhs != rhs) && ((lhs == null) || !(lhs.equals(rhs)))) { + msg = Objects.toString(msg, "assertEquals") + + ": expected " + Objects.toString(lhs) + + " to equal " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Calls {@link #assertSame(java.lang.Object, java.lang.Object, java.lang.String)} with a default message. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertSame(Object, Object, String) + */ + public static void assertSame(Object lhs, Object rhs) { + assertSame(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is the same as {@code rhs}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertSame(Object lhs, Object rhs, String msg) { + if (lhs != rhs) { + msg = Objects.toString(msg, "assertSame") + + ": expected " + Objects.toString(lhs) + + " to equal " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Shorthand for {@link #assertGreaterThanOrEqual(Comparable, Comparable)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertGreaterThanOrEqual(Comparable, Comparable) + */ + public static > void assertGTE(T lhs, T rhs) { + assertGreaterThanOrEqual(lhs, rhs); + } + + /** + * Shorthand for {@link #assertGreaterThanOrEqual(Comparable, Comparable, String)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertGreaterThanOrEqual(Comparable, Comparable, String) + */ + public static > void assertGTE(T lhs, T rhs, String msg) { + assertGreaterThanOrEqual(lhs, rhs, msg); + } + + /** + * Calls {@link #assertGreaterThanOrEqual(Comparable, Comparable, String)} with a default message. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertGreaterThanOrEqual(Comparable, Comparable, String) + */ + public static > void assertGreaterThanOrEqual(T lhs, T rhs) { + assertGreaterThanOrEqual(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is greater than or equal to {@code rhs}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static > void assertGreaterThanOrEqual(T lhs, T rhs, String msg) { + if (!(compare(lhs, rhs, msg) >= 0)) { + msg = Objects.toString(msg, "assertGreaterThanOrEqual") + + ": expected " + Objects.toString(lhs) + + " >= " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Shorthand for {@link #assertGreaterThan(Comparable, Comparable)}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertGreaterThan(Comparable, Comparable) + */ + public static > void assertGT(T lhs, T rhs) { + assertGreaterThan(lhs, rhs); + } + + /** + * Shorthand for {@link #assertGreaterThan(Comparable, Comparable, String)}. + * + * @param a type + * @param lhs the left hand value + * @param rhs the right hand value + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertGreaterThan(Comparable, Comparable, String) + */ + public static > void assertGT(T lhs, T rhs, String msg) { + assertGreaterThan(lhs, rhs, msg); + } + + /** + * Calls {@link #assertGreaterThan(Comparable, Comparable, String)} with a default message. + * + * @param a type + * @param lhs the left hand value + * @param rhs the right hand value + * @see #assertGreaterThan(Comparable, Comparable, String) + */ + public static > void assertGreaterThan(T lhs, T rhs) { + assertGreaterThan(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is greater than {@code rhs}. + * + * @param a type + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static > void assertGreaterThan(T lhs, T rhs, String msg) { + if (!(compare(lhs, rhs, msg) > 0)) { + msg = Objects.toString(msg, "assertGreaterThan") + + ": expected " + Objects.toString(lhs) + + " > " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Shorthand for {@link #assertNotEquals(Object, Object)}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertNotEquals(Object, Object) + */ + public static void assertNE(Object lhs, Object rhs) { + assertNotEquals(lhs, rhs); + } + + /** + * Shorthand for {@link #assertNotEquals(Object, Object, String)}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @see #assertNotEquals(Object, Object, String) + */ + public static void assertNE(Object lhs, Object rhs, String msg) { + assertNotEquals(lhs, rhs, msg); + } + + /** + * Calls {@link #assertNotEquals(Object, Object, String)} with a default message. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @see #assertNotEquals(Object, Object, String) + */ + public static void assertNotEquals(Object lhs, Object rhs) { + assertNotEquals(lhs, rhs, null); + } + + /** + * Asserts that {@code lhs} is not equal to {@code rhs}. + * + * @param lhs The left hand side of the comparison. + * @param rhs The right hand side of the comparison. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertNotEquals(Object lhs, Object rhs, String msg) { + if ((lhs == rhs) || (lhs != null && lhs.equals(rhs))) { + msg = Objects.toString(msg, "assertNotEquals") + + ": expected " + Objects.toString(lhs) + + " to not equal " + Objects.toString(rhs); + fail(msg); + } + } + + /** + * Calls {@link #assertNull(Object, String)} with a default message. + * + * @param o The reference assumed to be null. + * @see #assertNull(Object, String) + */ + public static void assertNull(Object o) { + assertNull(o, null); + } + + /** + * Asserts that {@code o} is null. + * + * @param o The reference assumed to be null. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertNull(Object o, String msg) { + assertEquals(o, null, msg); + } + + /** + * Calls {@link #assertNotNull(Object, String)} with a default message. + * + * @param o The reference assumed not to be null, + * @see #assertNotNull(Object, String) + */ + public static void assertNotNull(Object o) { + assertNotNull(o, null); + } + + /** + * Asserts that {@code o} is not null. + * + * @param o The reference assumed not to be null, + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertNotNull(Object o, String msg) { + assertNotEquals(o, null, msg); + } + + /** + * Calls {@link #assertFalse(boolean, String)} with a default message. + * + * @param value The value assumed to be false. + * @see #assertFalse(boolean, String) + */ + public static void assertFalse(boolean value) { + assertFalse(value, null); + } + + /** + * Asserts that {@code value} is {@code false}. + * + * @param value The value assumed to be false. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertFalse(boolean value, String msg) { + if (value) { + msg = Objects.toString(msg, "assertFalse") + + ": expected false, was true"; + fail(msg); + } + } + + /** + * Calls {@link #assertTrue(boolean, String)} with a default message. + * + * @param value The value assumed to be true. + * @see #assertTrue(boolean, String) + */ + public static void assertTrue(boolean value) { + assertTrue(value, null); + } + + /** + * Asserts that {@code value} is {@code true}. + * + * @param value The value assumed to be true. + * @param msg A description of the assumption; {@code null} for a default message. + * @throws RuntimeException if the assertion is not true. + */ + public static void assertTrue(boolean value, String msg) { + if (!value) { + msg = Objects.toString(msg, "assertTrue") + + ": expected true, was false"; + fail(msg); + } + } + + private static > int compare(T lhs, T rhs, String msg) { + if (lhs == null || rhs == null) { + fail(lhs, rhs, msg + ": values must be non-null:", ","); + } + return lhs.compareTo(rhs); + } + +/** + * Asserts that two strings are equal. + * + * If strings are not equals, then exception message + * will contain {@code msg} followed by list of mismatched lines. + * + * @param str1 First string to compare. + * @param str2 Second string to compare. + * @param msg A description of the assumption. + * @throws RuntimeException if strings are not equal. + */ + public static void assertStringsEqual(String str1, String str2, + String msg) { + String lineSeparator = System.getProperty("line.separator"); + String str1Lines[] = str1.split(lineSeparator); + String str2Lines[] = str2.split(lineSeparator); + + int minLength = Math.min(str1Lines.length, str2Lines.length); + String longestStringLines[] = ((str1Lines.length == minLength) ? + str2Lines : str1Lines); + + boolean stringsAreDifferent = false; + + StringBuilder messageBuilder = new StringBuilder(msg); + + messageBuilder.append("\n"); + + for (int line = 0; line < minLength; line++) { + if (!str1Lines[line].equals(str2Lines[line])) { + messageBuilder.append(String. + format("[line %d] '%s' differs " + + "from '%s'\n", + line, + str1Lines[line], + str2Lines[line])); + stringsAreDifferent = true; + } + } + + if (minLength < longestStringLines.length) { + String stringName = ((longestStringLines == str1Lines) ? + "first" : "second"); + messageBuilder.append(String.format("Only %s string contains " + + "following lines:\n", + stringName)); + stringsAreDifferent = true; + for(int line = minLength; line < longestStringLines.length; line++) { + messageBuilder.append(String. + format("[line %d] '%s'", line, + longestStringLines[line])); + } + } + + if (stringsAreDifferent) { + fail(messageBuilder.toString()); + } + } + + /** + * Returns a string formatted with a message and expected and actual values. + * @param lhs the actual value + * @param rhs the expected value + * @param message the actual value + * @param relation the asserted relationship between lhs and rhs + * @return a formatted string + */ + public static String format(Object lhs, Object rhs, String message, String relation) { + StringBuilder sb = new StringBuilder(80); + if (message != null) { + sb.append(message); + sb.append(' '); + } + sb.append("<"); + sb.append(Objects.toString(lhs)); + sb.append("> "); + sb.append(Objects.toString(relation, ",")); + sb.append(" <"); + sb.append(Objects.toString(rhs)); + sb.append(">"); + return sb.toString(); + } + + /** + * Fail reports a failure with message fail. + * + * @throws RuntimeException always + */ + public static void fail() { + fail("fail"); + } + + /** + * Fail reports a failure with a message. + * @param message for the failure + * @throws RuntimeException always + */ + public static void fail(String message) { + throw new RuntimeException(message); + } + + /** + * Fail reports a failure with a formatted message. + * + * @param lhs the actual value + * @param rhs the expected value + * @param message to be format before the expected and actual values + * @param relation the asserted relationship between lhs and rhs + * @throws RuntimeException always + */ + public static void fail(Object lhs, Object rhs, String message, String relation) { + throw new RuntimeException(format(lhs, rhs, message, relation)); + } + + /** + * Fail reports a failure with a message and a cause. + * @param message to be format before the expected and actual values + * @param cause the exception that caused this failure + * @throws RuntimeException always + */ + public static void fail(String message, Throwable cause) { + throw new RuntimeException(message, cause); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/BuildHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/BuildHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/BuildHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/BuildHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.File; +import java.io.FileReader; +import java.util.Properties; + +public class BuildHelper { + + /** + * Commercial builds should have the BUILD_TYPE set to commercial + * within the release file, found at the root of the JDK. + */ + public static boolean isCommercialBuild() throws Exception { + String buildType = getReleaseProperty("BUILD_TYPE","notFound"); + return buildType.equals("commercial"); + } + + + /** + * Return the value for property key, or defaultValue if no property not found. + * If present, double quotes are trimmed. + */ + public static String getReleaseProperty(String key, String defaultValue) throws Exception { + Properties properties = getReleaseProperties(); + String value = properties.getProperty(key, defaultValue); + return trimDoubleQuotes(value); + } + + /** + * Return the value for property key, or null if no property not found. + * If present, double quotes are trimmed. + */ + public static String getReleaseProperty(String key) throws Exception { + return getReleaseProperty(key, null); + } + + /** + * Get properties from the release file + */ + public static Properties getReleaseProperties() throws Exception { + Properties properties = new Properties(); + properties.load(new FileReader(getReleaseFile())); + return properties; + } + + /** + * Every JDK has a release file in its root. + * @return A handler to the release file. + */ + public static File getReleaseFile() throws Exception { + String jdkPath = getJDKRoot(); + File releaseFile = new File(jdkPath,"release"); + if ( ! releaseFile.canRead() ) { + throw new Exception("Release file is not readable, or it is absent: " + + releaseFile.getCanonicalPath()); + } + return releaseFile; + } + + /** + * Returns path to the JDK under test. + * This path is obtained through the test.jdk property, usually set by JTREG. + */ + public static String getJDKRoot() { + String jdkPath = System.getProperty("test.jdk"); + if (jdkPath == null) { + throw new RuntimeException("System property 'test.jdk' not set. This property is normally set by jtreg. " + + "When running test separately, set this property using '-Dtest.jdk=/path/to/jdk'."); + } + return jdkPath; + } + + /** + * Trim double quotes from the beginning and the end of the given string. + * @param original string to trim. + * @return a new trimmed string. + */ + public static String trimDoubleQuotes(String original) { + if (original == null) { return null; } + String trimmed = original.replaceAll("^\"+|\"+$", ""); + return trimmed; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/ByteCodeLoader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/ByteCodeLoader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/ByteCodeLoader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/ByteCodeLoader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.security.SecureClassLoader; + +/** + * {@code ByteCodeLoader} can be used for easy loading of byte code already + * present in memory. + * + * {@code InMemoryCompiler} can be used for compiling source code in a string + * into byte code, which then can be loaded with {@code ByteCodeLoader}. + * + * @see InMemoryCompiler + */ +public class ByteCodeLoader extends SecureClassLoader { + private final String className; + private final byte[] byteCode; + private volatile Class holder; + + /** + * Creates a new {@code ByteCodeLoader} ready to load a class with the + * given name and the given byte code. + * + * @param className The name of the class + * @param byteCode The byte code of the class + */ + public ByteCodeLoader(String className, byte[] byteCode) { + this.className = className; + this.byteCode = byteCode; + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + if (!name.equals(className)) { + return super.loadClass(name); + } + if (holder == null) { + synchronized(this) { + if (holder == null) { + holder = findClass(name); + } + } + } + return holder; + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (!name.equals(className)) { + throw new ClassNotFoundException(name); + } + + return defineClass(name, byteCode, 0, byteCode.length); + } + + /** + * Utility method for creating a new {@code ByteCodeLoader} and then + * directly load the given byte code. + * + * @param className The name of the class + * @param byteCode The byte code for the class + * @throws ClassNotFoundException if the class can't be loaded + * @return A {@see Class} object representing the class + */ + public static Class load(String className, byte[] byteCode) throws ClassNotFoundException { + return new ByteCodeLoader(className, byteCode).loadClass(className); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Container.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Container.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Container.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Container.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2019, Red Hat Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib; + +public class Container { + // Use this property to specify docker location on your system. + // E.g.: "/usr/local/bin/docker". We define this constant here so + // that it can be used in VMProps as well which checks docker support + // via this command + public static final String ENGINE_COMMAND = + System.getProperty("jdk.test.container.command", "docker"); +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Convert.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Convert.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Convert.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Convert.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.math.BigInteger; + +/** + * Utility class containing conversions between strings, arrays, and numeric + * values. + */ + +public class Convert { + + // Convert from a byte array to a hexadecimal representation as a string. + public static String byteArrayToHexString(byte[] arr) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < arr.length; ++i) { + byte curVal = arr[i]; + result.append(Character.forDigit(curVal >> 4 & 0xF, 16)); + result.append(Character.forDigit(curVal & 0xF, 16)); + } + return result.toString(); + } + + // Expand a single byte to a byte array + public static byte[] byteToByteArray(byte v, int length) { + byte[] result = new byte[length]; + result[0] = v; + return result; + } + + // Convert a hexadecimal string to a byte array + public static byte[] hexStringToByteArray(String str) { + byte[] result = new byte[str.length() / 2]; + for (int i = 0; i < result.length; i++) { + result[i] = (byte) Character.digit(str.charAt(2 * i), 16); + result[i] <<= 4; + result[i] += Character.digit(str.charAt(2 * i + 1), 16); + } + return result; + } + + /* + * Convert a hexadecimal string to the corresponding little-ending number + * as a BigInteger. The clearHighBit argument determines whether the most + * significant bit of the highest byte should be set to 0 in the result. + */ + public static + BigInteger hexStringToBigInteger(boolean clearHighBit, String str) { + BigInteger result = BigInteger.ZERO; + for (int i = 0; i < str.length() / 2; i++) { + int curVal = Character.digit(str.charAt(2 * i), 16); + curVal <<= 4; + curVal += Character.digit(str.charAt(2 * i + 1), 16); + if (clearHighBit && i == str.length() / 2 - 1) { + curVal &= 0x7F; + } + result = result.add(BigInteger.valueOf(curVal).shiftLeft(8 * i)); + } + return result; + } +} + + diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/FileInstaller.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/FileInstaller.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/FileInstaller.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/FileInstaller.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; + +// !!! +// NOTE: this class is widely used. DO NOT depend on any other classes in any test library, or else +// you may see intermittent ClassNotFoundException as in JDK-8188828 +// !!! + +/** + * Copy a resource: file or directory recursively, using relative path(src and dst) + * which are applied to test source directory(src) and current directory(dst) + */ +public class FileInstaller { + public static final String TEST_SRC = System.getProperty("test.src", "").trim(); + + /** + * @param args source and destination + * @throws IOException if an I/O error occurs + */ + public static void main(String[] args) throws IOException { + if (args.length != 2) { + throw new IllegalArgumentException("Unexpected number of arguments for file copy"); + } + Path src = Paths.get(TEST_SRC, args[0]).toAbsolutePath().normalize(); + Path dst = Paths.get(args[1]).toAbsolutePath().normalize(); + if (src.toFile().exists()) { + System.out.printf("copying %s to %s%n", src, dst); + if (src.toFile().isDirectory()) { + // can't use Files::copy for dirs, as 'dst' might exist already + Files.walkFileTree(src, new CopyFileVisitor(src, dst)); + } else { + Path dstDir = dst.getParent(); + if (!dstDir.toFile().exists()) { + Files.createDirectories(dstDir); + } + Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); + } + } else { + throw new IOException("Can't find source " + src); + } + } + + private static class CopyFileVisitor extends SimpleFileVisitor { + private final Path copyFrom; + private final Path copyTo; + + public CopyFileVisitor(Path copyFrom, Path copyTo) { + this.copyFrom = copyFrom; + this.copyTo = copyTo; + } + + @Override + public FileVisitResult preVisitDirectory(Path file, + BasicFileAttributes attrs) throws IOException { + Path relativePath = copyFrom.relativize(file); + Path destination = copyTo.resolve(relativePath); + if (!destination.toFile().exists()) { + Files.createDirectories(destination); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { + if (!file.toFile().isFile()) { + return FileVisitResult.CONTINUE; + } + Path relativePath = copyFrom.relativize(file); + Path destination = copyTo.resolve(relativePath); + Files.copy(file, destination, StandardCopyOption.COPY_ATTRIBUTES); + return FileVisitResult.CONTINUE; + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/InfiniteLoop.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/InfiniteLoop.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/InfiniteLoop.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/InfiniteLoop.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.Objects; + +/** + * Class which runs another Runnable in infinite loop with certain pauses + * between cycles. + */ +public class InfiniteLoop implements Runnable { + private final Runnable target; + private final long mills; + + + /** + * @param target a target to run in a loop + * @param mills the length of pause time in milliseconds + * @throws NullPointerException if target is null + * @throws IllegalArgumentException if the value of millis is negative + */ + public InfiniteLoop(Runnable target, long mills) { + Objects.requireNonNull(target); + if (mills < 0) { + throw new IllegalArgumentException("mills < 0"); + } + this.target = target; + this.mills = mills; + } + + @Override + public void run() { + try { + while (true) { + target.run(); + if (mills > 0) { + Thread.sleep(mills); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new Error(e); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolFinder.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolFinder.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolFinder.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolFinder.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.FileNotFoundException; +import java.nio.file.Path; +import java.nio.file.Paths; + +public final class JDKToolFinder { + + private JDKToolFinder() { + } + + /** + * Returns the full path to an executable in jdk/bin based on System + * property {@code test.jdk} or {@code compile.jdk} (both are set by the jtreg test suite) + * + * @return Full path to an executable in jdk/bin + */ + public static String getJDKTool(String tool) { + + // First try to find the executable in test.jdk + try { + return getTool(tool, "test.jdk"); + } catch (FileNotFoundException e) { + + } + + // Now see if it's available in compile.jdk + try { + return getTool(tool, "compile.jdk"); + } catch (FileNotFoundException e) { + throw new RuntimeException("Failed to find " + tool + + ", looked in test.jdk (" + System.getProperty("test.jdk") + + ") and compile.jdk (" + System.getProperty("compile.jdk") + ")"); + } + } + + /** + * Returns the full path to an executable in jdk/bin based on System + * property {@code compile.jdk} + * + * @return Full path to an executable in jdk/bin + */ + public static String getCompileJDKTool(String tool) { + try { + return getTool(tool, "compile.jdk"); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the full path to an executable in jdk/bin based on System + * property {@code test.jdk} + * + * @return Full path to an executable in jdk/bin + */ + public static String getTestJDKTool(String tool) { + try { + return getTool(tool, "test.jdk"); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + private static String getTool(String tool, String property) throws FileNotFoundException { + String jdkPath = System.getProperty(property); + + if (jdkPath == null) { + throw new RuntimeException( + "System property '" + property + "' not set. This property is normally set by jtreg. " + + "When running test separately, set this property using '-D" + property + "=/path/to/jdk'."); + } + + Path toolName = Paths.get("bin", tool + (Platform.isWindows() ? ".exe" : "")); + + Path jdkTool = Paths.get(jdkPath, toolName.toString()); + if (!jdkTool.toFile().exists()) { + throw new FileNotFoundException("Could not find file " + jdkTool.toAbsolutePath()); + } + + return jdkTool.toAbsolutePath().toString(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolLauncher.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolLauncher.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolLauncher.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/JDKToolLauncher.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.ArrayList; +import java.util.List; + +/** + * A utility for constructing command lines for starting JDK tool processes. + * + * The JDKToolLauncher can in particular be combined with a + * java.lang.ProcessBuilder to easily run a JDK tool. For example, the following + * code run {@code jmap -heap} against a process with GC logging turned on for + * the {@code jmap} process: + * + *
+ * {@code
+ * JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
+ *                                       .addVMArg("-XX:+PrintGC");
+ *                                       .addVMArg("-XX:+PrintGCDetails")
+ *                                       .addToolArg("-heap")
+ *                                       .addToolArg(pid);
+ * ProcessBuilder pb = new ProcessBuilder(jmap.getCommand());
+ * Process p = pb.start();
+ * }
+ * 
+ */ +public class JDKToolLauncher { + private final String executable; + private final List vmArgs = new ArrayList(); + private final List toolArgs = new ArrayList(); + + private JDKToolLauncher(String tool, boolean useCompilerJDK) { + if (useCompilerJDK) { + executable = JDKToolFinder.getJDKTool(tool); + } else { + executable = JDKToolFinder.getTestJDKTool(tool); + } + } + + /** + * Creates a new JDKToolLauncher for the specified tool. Using tools path + * from the compiler JDK. + * + * @param tool + * The name of the tool + * @return A new JDKToolLauncher + */ + public static JDKToolLauncher create(String tool) { + return new JDKToolLauncher(tool, true); + } + + /** + * Creates a new JDKToolLauncher for the specified tool in the Tested JDK. + * + * @param tool + * The name of the tool + * + * @return A new JDKToolLauncher + */ + public static JDKToolLauncher createUsingTestJDK(String tool) { + return new JDKToolLauncher(tool, false); + } + + /** + * Adds an argument to the JVM running the tool. + * + * The JVM arguments are passed to the underlying JVM running the tool. + * Arguments will automatically be prepended with "-J". + * + * Any platform specific arguments required for running the tool are + * automatically added. + * + * + * @param arg + * The argument to VM running the tool + * @return The JDKToolLauncher instance + */ + public JDKToolLauncher addVMArg(String arg) { + vmArgs.add(arg); + return this; + } + + /** + * Adds an argument to the tool. + * + * @param arg + * The argument to the tool + * @return The JDKToolLauncher instance + */ + public JDKToolLauncher addToolArg(String arg) { + toolArgs.add(arg); + return this; + } + + /** + * Returns the command that can be used for running the tool. + * + * @return An array whose elements are the arguments of the command. + */ + public String[] getCommand() { + List command = new ArrayList(); + command.add(executable); + // Add -J in front of all vmArgs + for (String arg : vmArgs) { + command.add("-J" + arg); + } + command.addAll(toolArgs); + return command.toArray(new String[command.size()]); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/LockFreeLogger.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/LockFreeLogger.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/LockFreeLogger.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/LockFreeLogger.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.Collection; +import java.util.Comparator; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +/** + * A logger designed specifically to allow collecting ordered log messages + * in a multi-threaded environment without involving any kind of locking. + *

+ * It is particularly useful in situations when one needs to assert various + * details about the tested thread state or the locks it hold while also wanting + * to produce diagnostic log messages. + *

+ * The logger does not provide any guarantees about the completness of the + * logs written from different threads - it is up to the caller to make sure + * {@code toString()} method is called only when all the activity has ceased + * and the per-thread logs contain all the necessary data. + * + * @author Jaroslav Bachorik + **/ +public class LockFreeLogger { + private final AtomicInteger logCntr = new AtomicInteger(0); + private final Collection> allRecords = new ConcurrentLinkedQueue<>(); + private final ThreadLocal> records = ThreadLocal.withInitial(ConcurrentHashMap::new); + + public LockFreeLogger() { + allRecords.add(records.get()); + } + + /** + * Log a message + * @param format Message format + * @param params Message parameters + */ + public void log(String format, Object ... params) { + int id = logCntr.getAndIncrement(); + records.get().put(id, String.format(format, params)); + } + + /** + * Will generate an aggregated log of chronologically ordered messages. + *

+ * Make sure that you call this method only when all the related threads + * have finished; otherwise you might get incomplete data. + * + * @return An aggregated log of chronologically ordered messages + */ + @Override + public String toString() { + return allRecords.stream() + .flatMap(m -> m.entrySet().stream()) + .sorted(Comparator.comparing(Map.Entry::getKey)) + .map(Map.Entry::getValue) + .collect(Collectors.joining()); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/NetworkConfiguration.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/NetworkConfiguration.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/NetworkConfiguration.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/NetworkConfiguration.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,393 @@ +/* + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.IOException; +import java.io.PrintStream; +import java.io.UncheckedIOException; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.net.NetworkInterface.getNetworkInterfaces; +import static java.util.Collections.list; + +/** + * Helper class for retrieving network interfaces and local addresses + * suitable for testing. + */ +public class NetworkConfiguration { + + private Map> ip4Interfaces; + private Map> ip6Interfaces; + private final boolean isIPv6Available; + private boolean has_testableipv6address = false; + private boolean has_sitelocaladdress = false; + private boolean has_linklocaladdress = false; + private boolean has_globaladdress = false; + + private NetworkConfiguration( + Map> ip4Interfaces, + Map> ip6Interfaces) { + this.ip4Interfaces = ip4Interfaces; + this.ip6Interfaces = ip6Interfaces; + + // initialize properties that can be queried + isIPv6Available = !ip6Interfaces().collect(Collectors.toList()).isEmpty(); + ip6Interfaces().forEach(nif -> { + ip6Addresses(nif) + // On Solaris or AIX, a configuration with only local or loopback + // addresses does not fully enable IPv6 operations. + // E.g. IPv6 multicasting does not work. + // So, don't set has_testableipv6address if we only find these. + .filter(addr -> Platform.isSolaris() || Platform.isAix() ? + !(addr.isAnyLocalAddress() || addr.isLoopbackAddress()) : true) + .forEach(ia -> { + has_testableipv6address = true; + if (ia.isLinkLocalAddress()) has_linklocaladdress = true; + if (ia.isSiteLocalAddress()) has_sitelocaladdress = true; + + if (!ia.isLinkLocalAddress() && + !ia.isSiteLocalAddress() && + !ia.isLoopbackAddress()) { + has_globaladdress = true; + } + }); + }); + } + + private static boolean isNotExcludedInterface(NetworkInterface nif) { + if (Platform.isOSX() && nif.getName().contains("awdl")) { + return false; + } + if (Platform.isWindows()) { + String dName = nif.getDisplayName(); + if (dName != null && dName.contains("Teredo")) { + return false; + } + } + return true; + } + + private static boolean isNotLoopback(NetworkInterface nif) { + try { + return !nif.isLoopback(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private boolean hasIp4Addresses(NetworkInterface nif) { + return ip4Interfaces.get(nif).stream().anyMatch(a -> !a.isAnyLocalAddress()); + } + + private boolean hasIp6Addresses(NetworkInterface nif) { + return ip6Interfaces.get(nif).stream().anyMatch(a -> !a.isAnyLocalAddress()); + } + + private boolean supportsIp4Multicast(NetworkInterface nif) { + try { + if (!nif.supportsMulticast()) { + return false; + } + + // On AIX there is a bug: + // When IPv6 is enabled on the system, the JDK opens sockets as AF_INET6. + // If there's an interface configured with IPv4 addresses only, it should + // be able to become the network interface for a multicast socket (that + // could be in both, IPv4 or IPv6 space). But both possible setsockopt + // calls for either IPV6_MULTICAST_IF or IP_MULTICAST_IF return + // EADDRNOTAVAIL. So we must skip such interfaces here. + if (Platform.isAix() && isIPv6Available() && !hasIp6Addresses(nif)) { + return false; + } + + return hasIp4Addresses(nif); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private boolean supportsIp6Multicast(NetworkInterface nif) { + try { + if (!nif.supportsMulticast()) { + return false; + } + + return hasIp6Addresses(nif); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Returns whether IPv6 is available at all. + * This should resemble the result of native ipv6_available() in net_util.c + */ + public boolean isIPv6Available() { + return isIPv6Available; + } + + /** + * Does any (usable) IPv6 address exist in the network configuration? + */ + public boolean hasTestableIPv6Address() { + return has_testableipv6address; + } + + /** + * Does any site local address exist? + */ + public boolean hasSiteLocalAddress() { + return has_sitelocaladdress; + } + + /** + * Does any link local address exist? + */ + public boolean hasLinkLocalAddress() { + return has_linklocaladdress; + } + + /** + * Does any global IPv6 address exist? + */ + public boolean has_globaladdress() { + return has_globaladdress; + } + + /** + * Returns a stream of interfaces suitable for functional tests. + */ + public Stream interfaces() { + return Stream.concat(ip4Interfaces(), ip6Interfaces()) + .distinct(); + } + + /** + * Returns a stream of interfaces suitable for IPv4 functional tests. + */ + public Stream ip4Interfaces() { + return ip4Interfaces.keySet() + .stream() + .filter(NetworkConfiguration::isNotExcludedInterface) + .filter(this::hasIp4Addresses); + } + + /** + * Returns a stream of interfaces suitable for IPv6 functional tests. + */ + public Stream ip6Interfaces() { + return ip6Interfaces.keySet() + .stream() + .filter(NetworkConfiguration::isNotExcludedInterface) + .filter(this::hasIp6Addresses); + } + + /** + * Returns a stream of interfaces suitable for functional tests. + */ + public Stream multicastInterfaces(boolean includeLoopback) { + return Stream + .concat(ip4MulticastInterfaces(includeLoopback), + ip6MulticastInterfaces(includeLoopback)) + .distinct(); + } + + /** + * Returns a stream of interfaces suitable for IPv4 multicast tests. + * + * The loopback interface will not be included. + */ + public Stream ip4MulticastInterfaces() { + return ip4MulticastInterfaces(false); + } + + /** + * Returns a stream of interfaces suitable for IPv4 multicast tests. + */ + public Stream ip4MulticastInterfaces(boolean includeLoopback) { + return (includeLoopback) ? + ip4Interfaces().filter(this::supportsIp4Multicast) : + ip4Interfaces().filter(this::supportsIp4Multicast) + .filter(NetworkConfiguration::isNotLoopback); + } + + /** + * Returns a stream of interfaces suitable for IPv6 multicast tests. + * + * The loopback interface will not be included. + */ + public Stream ip6MulticastInterfaces() { + return ip6MulticastInterfaces(false); + } + + /** + * Returns a stream of interfaces suitable for IPv6 multicast tests. + */ + public Stream ip6MulticastInterfaces(boolean includeLoopback) { + return (includeLoopback) ? + ip6Interfaces().filter(this::supportsIp6Multicast) : + ip6Interfaces().filter(this::supportsIp6Multicast) + .filter(NetworkConfiguration::isNotLoopback); + } + + /** + * Returns all addresses on all "functional" interfaces. + */ + public Stream addresses(NetworkInterface nif) { + return Stream.concat(ip4Interfaces.get(nif).stream(), + ip6Interfaces.get(nif).stream()); + } + + /** + * Returns all IPv4 addresses on all "functional" interfaces. + */ + public Stream ip4Addresses() { + return ip4Interfaces().flatMap(this::ip4Addresses); + } + + /** + * Returns all IPv6 addresses on all "functional" interfaces. + */ + public Stream ip6Addresses() { + return ip6Interfaces().flatMap(this::ip6Addresses); + } + + /** + * Returns all IPv4 addresses the given interface. + */ + public Stream ip4Addresses(NetworkInterface nif) { + return ip4Interfaces.get(nif).stream(); + } + + /** + * Returns all IPv6 addresses for the given interface. + */ + public Stream ip6Addresses(NetworkInterface nif) { + return ip6Interfaces.get(nif).stream(); + } + + @Override + public String toString() { + return interfaces().map(NetworkConfiguration::interfaceInformation) + .collect(Collectors.joining()); + } + + /** + * Return a NetworkConfiguration instance. + */ + public static NetworkConfiguration probe() throws IOException { + Map> ip4Interfaces = new HashMap<>(); + Map> ip6Interfaces = new HashMap<>(); + + List nifs = list(getNetworkInterfaces()); + for (NetworkInterface nif : nifs) { + // ignore interfaces that are down + if (!nif.isUp() || nif.isPointToPoint()) { + continue; + } + + List ip4Addresses = new LinkedList<>(); + List ip6Addresses = new LinkedList<>(); + ip4Interfaces.put(nif, ip4Addresses); + ip6Interfaces.put(nif, ip6Addresses); + for (InetAddress addr : list(nif.getInetAddresses())) { + if (addr instanceof Inet4Address) { + ip4Addresses.add((Inet4Address) addr); + } else if (addr instanceof Inet6Address) { + ip6Addresses.add((Inet6Address) addr); + } + } + } + return new NetworkConfiguration(ip4Interfaces, ip6Interfaces); + } + + /** Returns detailed information for the given interface. */ + public static String interfaceInformation(NetworkInterface nif) { + StringBuilder sb = new StringBuilder(); + try { + sb.append("Display name: ") + .append(nif.getDisplayName()) + .append("\n"); + sb.append("Name: ") + .append(nif.getName()) + .append("\n"); + for (InetAddress inetAddress : list(nif.getInetAddresses())) { + sb.append("InetAddress: ") + .append(inetAddress) + .append("\n"); + } + sb.append("Up? ") + .append(nif.isUp()) + .append("\n"); + sb.append("Loopback? ") + .append(nif.isLoopback()) + .append("\n"); + sb.append("PointToPoint? ") + .append(nif.isPointToPoint()) + .append("\n"); + sb.append("Supports multicast? ") + .append(nif.supportsMulticast()) + .append("\n"); + sb.append("Virtual? ") + .append(nif.isVirtual()) + .append("\n"); + sb.append("Hardware address: ") + .append(Arrays.toString(nif.getHardwareAddress())) + .append("\n"); + sb.append("MTU: ") + .append(nif.getMTU()) + .append("\n"); + sb.append("Index: ") + .append(nif.getIndex()) + .append("\n"); + sb.append("\n"); + return sb.toString(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** Prints all the system interface information to the give stream. */ + public static void printSystemConfiguration(PrintStream out) { + try { + out.println("*** all system network interface configuration ***"); + for (NetworkInterface nif : list(getNetworkInterfaces())) { + out.print(interfaceInformation(nif)); + } + out.println("*** end ***"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Platform.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Platform.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Platform.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Platform.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class Platform { + public static final String vmName = System.getProperty("java.vm.name"); + public static final String vmInfo = System.getProperty("java.vm.info"); + private static final String osVersion = System.getProperty("os.version"); + private static String[] osVersionTokens; + private static int osVersionMajor = -1; + private static int osVersionMinor = -1; + private static final String osName = System.getProperty("os.name"); + private static final String dataModel = System.getProperty("sun.arch.data.model"); + private static final String vmVersion = System.getProperty("java.vm.version"); + private static final String jdkDebug = System.getProperty("jdk.debug"); + private static final String osArch = System.getProperty("os.arch"); + private static final String userName = System.getProperty("user.name"); + private static final String compiler = System.getProperty("sun.management.compiler"); + + public static boolean isClient() { + return vmName.endsWith(" Client VM"); + } + + public static boolean isServer() { + return vmName.endsWith(" Server VM"); + } + + public static boolean isGraal() { + return vmName.endsWith(" Graal VM"); + } + + public static boolean isZero() { + return vmName.endsWith(" Zero VM"); + } + + public static boolean isMinimal() { + return vmName.endsWith(" Minimal VM"); + } + + public static boolean isEmbedded() { + return vmName.contains("Embedded"); + } + + public static boolean isEmulatedClient() { + return vmInfo.contains(" emulated-client"); + } + + public static boolean isTieredSupported() { + return compiler.contains("Tiered Compilers"); + } + + public static boolean isInt() { + return vmInfo.contains("interpreted"); + } + + public static boolean isMixed() { + return vmInfo.contains("mixed"); + } + + public static boolean isComp() { + return vmInfo.contains("compiled"); + } + + public static boolean is32bit() { + return dataModel.equals("32"); + } + + public static boolean is64bit() { + return dataModel.equals("64"); + } + + public static boolean isAix() { + return isOs("aix"); + } + + public static boolean isLinux() { + return isOs("linux"); + } + + public static boolean isOSX() { + return isOs("mac"); + } + + public static boolean isSolaris() { + return isOs("sunos"); + } + + public static boolean isWindows() { + return isOs("win"); + } + + private static boolean isOs(String osname) { + return osName.toLowerCase().startsWith(osname.toLowerCase()); + } + + public static String getOsName() { + return osName; + } + + // Os version support. + private static void init_version() { + osVersionTokens = osVersion.split("\\."); + try { + if (osVersionTokens.length > 0) { + osVersionMajor = Integer.parseInt(osVersionTokens[0]); + if (osVersionTokens.length > 1) { + osVersionMinor = Integer.parseInt(osVersionTokens[1]); + } + } + } catch (NumberFormatException e) { + osVersionMajor = osVersionMinor = 0; + } + } + + public static String getOsVersion() { + return osVersion; + } + + // Returns major version number from os.version system property. + // E.g. 5 on Solaris 10 and 3 on SLES 11.3 (for the linux kernel version). + public static int getOsVersionMajor() { + if (osVersionMajor == -1) init_version(); + return osVersionMajor; + } + + // Returns minor version number from os.version system property. + // E.g. 10 on Solaris 10 and 0 on SLES 11.3 (for the linux kernel version). + public static int getOsVersionMinor() { + if (osVersionMinor == -1) init_version(); + return osVersionMinor; + } + + /** + * Compares the platform version with the supplied version. The + * version must be of the form a[.b[.c[.d...]]] where a, b, c, d, ... + * are decimal integers. + * + * @throws NullPointerException if the parameter is null + * @throws NumberFormatException if there is an error parsing either + * version as split into component strings + * @return -1, 0, or 1 according to whether the platform version is + * less than, equal to, or greater than the supplied version + */ + public static int compareOsVersion(String version) { + if (osVersionTokens == null) init_version(); + + Objects.requireNonNull(version); + + List s1 = Arrays + .stream(osVersionTokens) + .map(Integer::valueOf) + .collect(Collectors.toList()); + List s2 = Arrays + .stream(version.split("\\.")) + .map(Integer::valueOf) + .collect(Collectors.toList()); + + int count = Math.max(s1.size(), s2.size()); + for (int i = 0; i < count; i++) { + int i1 = i < s1.size() ? s1.get(i) : 0; + int i2 = i < s2.size() ? s2.get(i) : 0; + if (i1 > i2) { + return 1; + } else if (i2 > i1) { + return -1; + } + } + + return 0; + } + + public static boolean isDebugBuild() { + return (jdkDebug.toLowerCase().contains("debug")); + } + + public static boolean isSlowDebugBuild() { + return (jdkDebug.toLowerCase().equals("slowdebug")); + } + + public static boolean isFastDebugBuild() { + return (jdkDebug.toLowerCase().equals("fastdebug")); + } + + public static String getVMVersion() { + return vmVersion; + } + + public static boolean isAArch64() { + return isArch("aarch64"); + } + + public static boolean isARM() { + return isArch("arm.*"); + } + + public static boolean isPPC() { + return isArch("ppc.*"); + } + + // Returns true for IBM z System running linux. + public static boolean isS390x() { + return isArch("s390.*") || isArch("s/390.*") || isArch("zArch_64"); + } + + // Returns true for sparc and sparcv9. + public static boolean isSparc() { + return isArch("sparc.*"); + } + + public static boolean isX64() { + // On OSX it's 'x86_64' and on other (Linux, Windows and Solaris) platforms it's 'amd64' + return isArch("(amd64)|(x86_64)"); + } + + public static boolean isX86() { + // On Linux it's 'i386', Windows 'x86' without '_64' suffix. + return isArch("(i386)|(x86(?!_64))"); + } + + public static String getOsArch() { + return osArch; + } + + /** + * Return a boolean for whether SA and jhsdb are ported/available + * on this platform. + */ + public static boolean hasSA() { + if (isAix()) { + return false; // SA not implemented. + } else if (isLinux()) { + if (isS390x()) { + return false; // SA not implemented. + } + } + // Other platforms expected to work: + return true; + } + + /** + * Return a boolean for whether we expect to be able to attach + * the SA to our own processes on this system. This requires + * that SA is ported/available on this platform. + */ + public static boolean shouldSAAttach() throws IOException { + if (!hasSA()) return false; + if (isLinux()) { + return canPtraceAttachLinux(); + } else if (isOSX()) { + return canAttachOSX(); + } else { + // Other platforms expected to work: + return true; + } + } + + /** + * On Linux, first check the SELinux boolean "deny_ptrace" and return false + * as we expect to be denied if that is "1". Then expect permission to attach + * if we are root, so return true. Then return false for an expected denial + * if "ptrace_scope" is 1, and true otherwise. + */ + private static boolean canPtraceAttachLinux() throws IOException { + // SELinux deny_ptrace: + File deny_ptrace = new File("/sys/fs/selinux/booleans/deny_ptrace"); + if (deny_ptrace.exists()) { + try (RandomAccessFile file = new RandomAccessFile(deny_ptrace, "r")) { + if (file.readByte() != '0') { + return false; + } + } + } + + // YAMA enhanced security ptrace_scope: + // 0 - a process can PTRACE_ATTACH to any other process running under the same uid + // 1 - restricted ptrace: a process must be a children of the inferior or user is root + // 2 - only processes with CAP_SYS_PTRACE may use ptrace or user is root + // 3 - no attach: no processes may use ptrace with PTRACE_ATTACH + File ptrace_scope = new File("/proc/sys/kernel/yama/ptrace_scope"); + if (ptrace_scope.exists()) { + try (RandomAccessFile file = new RandomAccessFile(ptrace_scope, "r")) { + byte yama_scope = file.readByte(); + if (yama_scope == '3') { + return false; + } + + if (!userName.equals("root") && yama_scope != '0') { + return false; + } + } + } + // Otherwise expect to be permitted: + return true; + } + + /** + * On OSX, expect permission to attach only if we are root. + */ + private static boolean canAttachOSX() { + return userName.equals("root"); + } + + private static boolean isArch(String archnameRE) { + return Pattern.compile(archnameRE, Pattern.CASE_INSENSITIVE) + .matcher(osArch) + .matches(); + } + + /** + * Returns file extension of shared library, e.g. "so" on linux, "dll" on windows. + * @return file extension + */ + public static String sharedLibraryExt() { + if (isWindows()) { + return "dll"; + } else if (isOSX()) { + return "dylib"; + } else { + return "so"; + } + } + + /* + * Returns name of system variable containing paths to shared native libraries. + */ + public static String sharedLibraryPathVariableName() { + if (isWindows()) { + return "PATH"; + } else if (isOSX()) { + return "DYLD_LIBRARY_PATH"; + } else if (isAix()) { + return "LIBPATH"; + } else { + return "LD_LIBRARY_PATH"; + } + } + + /* + * This should match the #if condition in ClassListParser::load_class_from_source(). + */ + public static boolean areCustomLoadersSupportedForCDS() { + boolean isLinux = Platform.isLinux(); + boolean is64 = Platform.is64bit(); + boolean isSolaris = Platform.isSolaris(); + + return (is64 && (isLinux || isSolaris)); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/RandomFactory.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/RandomFactory.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/RandomFactory.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/RandomFactory.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.Random; +import java.util.SplittableRandom; + +/** + * Factory class which generates and prints to STDOUT a long-valued seed + * for use in initializing a PRNG. An instance of {@code Random} or + * {@code SplittableRandom} may likewise be obtained. + */ +public class RandomFactory { + /** + * Attempt to obtain the seed from the value of the "seed" property. + * @return The seed or {@code null} if the "seed" property was not set or + * could not be parsed. + */ + private static Long getSystemSeed() { + Long seed = null; + try { + // note that Long.valueOf(null) also throws a + // NumberFormatException so if the property is undefined this + // will still work correctly + seed = Long.valueOf(System.getProperty("seed")); + } catch (NumberFormatException e) { + // do nothing: seed is still null + } + + return seed; + } + + /** + * Obtain a seed from an independent PRNG. + * + * @return A random seed. + */ + private static long getRandomSeed() { + return new Random().nextLong(); + } + + /** + * Obtain and print to STDOUT a seed appropriate for initializing a PRNG. + * If the system property "seed" is set and has value which may be correctly + * parsed it is used, otherwise a seed is generated using an independent + * PRNG. + * + * @return The seed. + */ + public static long getSeed() { + Long seed = getSystemSeed(); + if (seed == null) { + seed = getRandomSeed(); + } + System.out.println("Seed from RandomFactory = "+seed+"L"); + return seed; + } + + /** + * Obtain and print to STDOUT a seed and use it to initialize a new + * {@code Random} instance which is returned. If the system + * property "seed" is set and has value which may be correctly parsed it + * is used, otherwise a seed is generated using an independent PRNG. + * + * @return The {@code Random} instance. + */ + public static Random getRandom() { + return new Random(getSeed()); + } + + /** + * Obtain and print to STDOUT a seed and use it to initialize a new + * {@code SplittableRandom} instance which is returned. If the system + * property "seed" is set and has value which may be correctly parsed it + * is used, otherwise a seed is generated using an independent PRNG. + * + * @return The {@code SplittableRandom} instance. + */ + public static SplittableRandom getSplittableRandom() { + return new SplittableRandom(getSeed()); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/SigTestUtil.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/SigTestUtil.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/SigTestUtil.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/SigTestUtil.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.security.*; +import java.security.spec.*; +import java.util.*; + +/* + * Utility class used by various Signature related regression tests for + * common functions such as generating the list of to-be-tested algorithms + * based on key size, etc. Currently, this is mostly needed by RSA + * signatures. + */ +public class SigTestUtil { + + public enum SignatureType { + RSA("RSA"), + RSASSA_PSS("RSASSA-PSS") + ; + + private String keyAlg; + + SignatureType(String keyAlg) { + this.keyAlg = keyAlg; + } + @Override + public String toString() { + return keyAlg; + } + } + + // collection of all supported digest algorithms + // note that the entries are ordered by required key sizes + private static final String[] DIGEST_ALGS = { + "SHA-512", + "SHA-384", + "SHA-256", + "SHA-512/256", + "SHA-224", + "SHA-512/224", + "SHA-1", + "MD2", "MD5" // these aren't supported by RSA PSS + }; + + // indice for message digest algorithms lookup + // may need to be adjusted if new algorithms are added + private static final int PKCS1_5_INDEX_768 = 0; + private static final int PKCS1_5_INDEX_512 = 2; + private static final int PKCS1_5_INDEX_END = DIGEST_ALGS.length; + private static final int PSS_INDEX_2048 = 0; + private static final int PSS_INDEX_1024 = 1; + private static final int PSS_INDEX_768 = 2; + private static final int PSS_INDEX_512 = 4; + private static final int PSS_INDEX_END = 7; + + public static Iterable getDigestAlgorithms(SignatureType type, + int keysize) throws RuntimeException { + + // initialize to all, then trim based on key size + List result = new ArrayList<>(Arrays.asList(DIGEST_ALGS)); + int index = 0; + switch (type) { + case RSA: + if (keysize >= 768) { + index = PKCS1_5_INDEX_768; + } else if (keysize >= 512) { + index = PKCS1_5_INDEX_512; + } else { + throw new RuntimeException("Keysize too small: " + keysize); + } + result = result.subList(index, PKCS1_5_INDEX_END); + break; + case RSASSA_PSS: + if (keysize >= 2048) { + index = PSS_INDEX_2048; + } else if (keysize >= 1024) { + index = PSS_INDEX_1024; + } else if (keysize >= 768) { + index = PSS_INDEX_768; + } else if (keysize >= 512) { + index = PSS_INDEX_512; + } else { + throw new RuntimeException("Keysize too small: " + keysize); + } + result = result.subList(index, PSS_INDEX_END); + break; + default: + // XXX maybe just return result instead of error out? + throw new RuntimeException("Unsupported signature type: " + type); + } + return result; + } + + public static AlgorithmParameterSpec generateDefaultParameter( + SignatureType type, String mdAlg) throws RuntimeException { + // only RSASSA-PSS signature uses parameters + switch (type) { + case RSASSA_PSS: + try { + MessageDigest md = MessageDigest.getInstance(mdAlg); + return new PSSParameterSpec(mdAlg, "MGF1", + new MGF1ParameterSpec(mdAlg), md.getDigestLength(), + PSSParameterSpec.TRAILER_FIELD_BC); + } catch (Exception e) { + throw new RuntimeException(e); + } + default: + return null; + } + } + + public static String generateSigAlg(SignatureType type, + String mdAlg) throws RuntimeException { + switch (type) { + case RSA: + int idx = mdAlg.indexOf("-"); + if (idx != -1) { + mdAlg = mdAlg.substring(0, idx) + mdAlg.substring(idx+1); + } + return mdAlg + "with" + type.toString(); + case RSASSA_PSS: + return type.toString(); + default: + throw new RuntimeException("Unsupported signature type " + type ); + } + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/TimeLimitedRunner.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/TimeLimitedRunner.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/TimeLimitedRunner.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/TimeLimitedRunner.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.util.Objects; +import java.util.concurrent.Callable; + +/** + * Auxiliary class to run target w/ given timeout. + */ +public class TimeLimitedRunner implements Callable { + private final long stoptime; + private final long timeout; + private final double factor; + private final Callable target; + + /** + * @param timeout a timeout. zero means no time limitation + * @param factor a multiplier used to estimate next iteration time + * @param target a target to run + * @throws NullPointerException if target is null + * @throws IllegalArgumentException if timeout is negative or + factor isn't positive + */ + public TimeLimitedRunner(long timeout, double factor, + Callable target) { + Objects.requireNonNull(target, "target must not be null"); + if (timeout < 0) { + throw new IllegalArgumentException("timeout[" + timeout + "] < 0"); + } + if (factor <= 0d) { + throw new IllegalArgumentException("factor[" + factor + "] <= 0"); + } + this.stoptime = System.currentTimeMillis() + timeout; + this.timeout = timeout; + this.factor = factor; + this.target = target; + } + + /** + * Runs @{linkplan target} while it returns true and timeout isn't exceeded + */ + @Override + public Void call() throws Exception { + long maxDuration = 0L; + long iterStart = System.currentTimeMillis(); + if (timeout != 0 && iterStart > stoptime) { + return null; + } + while (target.call()) { + if (timeout != 0) { + long iterDuration = System.currentTimeMillis() - iterStart; + maxDuration = Math.max(maxDuration, iterDuration); + iterStart = System.currentTimeMillis(); + if (iterStart + (maxDuration * factor) > stoptime) { + System.out.println("Not enough time to continue execution. " + + "Interrupted."); + break; + } + } + } + return null; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Utils.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Utils.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Utils.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/Utils.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,832 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.ServerSocket; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.UnknownHostException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.function.BooleanSupplier; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static jdk.test.lib.Asserts.assertTrue; +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.process.OutputAnalyzer; + +/** + * Common library for various test helper functions. + */ +public final class Utils { + + /** + * Returns the value of 'test.class.path' system property. + */ + public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); + + /** + * Returns the sequence used by operating system to separate lines. + */ + public static final String NEW_LINE = System.getProperty("line.separator"); + + /** + * Returns the value of 'test.vm.opts' system property. + */ + public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); + + /** + * Returns the value of 'test.java.opts' system property. + */ + public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); + + /** + * Returns the value of 'test.src' system property. + */ + public static final String TEST_SRC = System.getProperty("test.src", "").trim(); + + /* + * Returns the value of 'test.jdk' system property + */ + public static final String TEST_JDK = System.getProperty("test.jdk"); + + /* + * Returns the value of 'compile.jdk' system property + */ + public static final String COMPILE_JDK= System.getProperty("compile.jdk", TEST_JDK); + + /** + * Returns the value of 'test.classes' system property + */ + public static final String TEST_CLASSES = System.getProperty("test.classes", "."); + /** + * Defines property name for seed value. + */ + public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; + + /* (non-javadoc) + * Random generator with (or without) predefined seed. Depends on + * "jdk.test.lib.random.seed" property value. + */ + private static volatile Random RANDOM_GENERATOR; + + /** + * Contains the seed value used for {@link java.util.Random} creation. + */ + public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong()); + /** + * Returns the value of 'test.timeout.factor' system property + * converted to {@code double}. + */ + public static final double TIMEOUT_FACTOR; + static { + String toFactor = System.getProperty("test.timeout.factor", "1.0"); + TIMEOUT_FACTOR = Double.parseDouble(toFactor); + } + + /** + * Returns the value of JTREG default test timeout in milliseconds + * converted to {@code long}. + */ + public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); + + private Utils() { + // Private constructor to prevent class instantiation + } + + /** + * Returns the list of VM options. + * + * @return List of VM options + */ + public static List getVmOptions() { + return Arrays.asList(safeSplitString(VM_OPTIONS)); + } + + /** + * Returns the list of VM options with -J prefix. + * + * @return The list of VM options with -J prefix + */ + public static List getForwardVmOptions() { + String[] opts = safeSplitString(VM_OPTIONS); + for (int i = 0; i < opts.length; i++) { + opts[i] = "-J" + opts[i]; + } + return Arrays.asList(opts); + } + + /** + * Returns the default JTReg arguments for a jvm running a test. + * This is the combination of JTReg arguments test.vm.opts and test.java.opts. + * @return An array of options, or an empty array if no options. + */ + public static String[] getTestJavaOpts() { + List opts = new ArrayList(); + Collections.addAll(opts, safeSplitString(VM_OPTIONS)); + Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); + return opts.toArray(new String[0]); + } + + /** + * Combines given arguments with default JTReg arguments for a jvm running a test. + * This is the combination of JTReg arguments test.vm.opts and test.java.opts + * @return The combination of JTReg test java options and user args. + */ + public static String[] addTestJavaOpts(String... userArgs) { + List opts = new ArrayList(); + Collections.addAll(opts, getTestJavaOpts()); + Collections.addAll(opts, userArgs); + return opts.toArray(new String[0]); + } + + /** + * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". + * Removes any options matching: -XX:(+/-)Use*GC + * Used when a test need to set its own GC version. Then any + * GC specified by the framework must first be removed. + * @return A copy of given opts with all GC options removed. + */ + private static final Pattern useGcPattern = Pattern.compile( + "(?:\\-XX\\:[\\+\\-]Use.+GC)" + + "|(?:\\-Xconcgc)"); + public static List removeGcOpts(List opts) { + List optsWithoutGC = new ArrayList(); + for (String opt : opts) { + if (useGcPattern.matcher(opt).matches()) { + System.out.println("removeGcOpts: removed " + opt); + } else { + optsWithoutGC.add(opt); + } + } + return optsWithoutGC; + } + + /** + * Returns the default JTReg arguments for a jvm running a test without + * options that matches regular expressions in {@code filters}. + * This is the combination of JTReg arguments test.vm.opts and test.java.opts. + * @param filters Regular expressions used to filter out options. + * @return An array of options, or an empty array if no options. + */ + public static String[] getFilteredTestJavaOpts(String... filters) { + String options[] = getTestJavaOpts(); + + if (filters.length == 0) { + return options; + } + + List filteredOptions = new ArrayList(options.length); + Pattern patterns[] = new Pattern[filters.length]; + for (int i = 0; i < filters.length; i++) { + patterns[i] = Pattern.compile(filters[i]); + } + + for (String option : options) { + boolean matched = false; + for (int i = 0; i < patterns.length && !matched; i++) { + Matcher matcher = patterns[i].matcher(option); + matched = matcher.find(); + } + if (!matched) { + filteredOptions.add(option); + } + } + + return filteredOptions.toArray(new String[filteredOptions.size()]); + } + + /** + * Splits a string by white space. + * Works like String.split(), but returns an empty array + * if the string is null or empty. + */ + private static String[] safeSplitString(String s) { + if (s == null || s.trim().isEmpty()) { + return new String[] {}; + } + return s.trim().split("\\s+"); + } + + /** + * @return The full command line for the ProcessBuilder. + */ + public static String getCommandLine(ProcessBuilder pb) { + StringBuilder cmd = new StringBuilder(); + for (String s : pb.command()) { + cmd.append(s).append(" "); + } + return cmd.toString(); + } + + /** + * Returns the socket address of an endpoint that refuses connections. The + * endpoint is an InetSocketAddress where the address is the loopback address + * and the port is a system port (1-1023 range). + * This method is a better choice than getFreePort for tests that need + * an endpoint that refuses connections. + */ + public static InetSocketAddress refusingEndpoint() { + InetAddress lb = InetAddress.getLoopbackAddress(); + int port = 1; + while (port < 1024) { + InetSocketAddress sa = new InetSocketAddress(lb, port); + try { + SocketChannel.open(sa).close(); + } catch (IOException ioe) { + return sa; + } + port++; + } + throw new RuntimeException("Unable to find system port that is refusing connections"); + } + + /** + * Returns the free port on the local host. + * + * @return The port number + * @throws IOException if an I/O error occurs when opening the socket + */ + public static int getFreePort() throws IOException { + try (ServerSocket serverSocket = + new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { + return serverSocket.getLocalPort(); + } + } + + /** + * Returns the name of the local host. + * + * @return The host name + * @throws UnknownHostException if IP address of a host could not be determined + */ + public static String getHostname() throws UnknownHostException { + InetAddress inetAddress = InetAddress.getLocalHost(); + String hostName = inetAddress.getHostName(); + + assertTrue((hostName != null && !hostName.isEmpty()), + "Cannot get hostname"); + + return hostName; + } + + /** + * Uses "jcmd -l" to search for a jvm pid. This function will wait + * forever (until jtreg timeout) for the pid to be found. + * @param key Regular expression to search for + * @return The found pid. + */ + public static int waitForJvmPid(String key) throws Throwable { + final long iterationSleepMillis = 250; + System.out.println("waitForJvmPid: Waiting for key '" + key + "'"); + System.out.flush(); + while (true) { + int pid = tryFindJvmPid(key); + if (pid >= 0) { + return pid; + } + Thread.sleep(iterationSleepMillis); + } + } + + /** + * Searches for a jvm pid in the output from "jcmd -l". + * + * Example output from jcmd is: + * 12498 sun.tools.jcmd.JCmd -l + * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar + * + * @param key A regular expression to search for. + * @return The found pid, or -1 if not found. + * @throws Exception If multiple matching jvms are found. + */ + public static int tryFindJvmPid(String key) throws Throwable { + OutputAnalyzer output = null; + try { + JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd"); + jcmdLauncher.addToolArg("-l"); + output = ProcessTools.executeProcess(jcmdLauncher.getCommand()); + output.shouldHaveExitValue(0); + + // Search for a line starting with numbers (pid), follwed by the key. + Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n"); + Matcher matcher = pattern.matcher(output.getStdout()); + + int pid = -1; + if (matcher.find()) { + pid = Integer.parseInt(matcher.group(1)); + System.out.println("findJvmPid.pid: " + pid); + if (matcher.find()) { + throw new Exception("Found multiple JVM pids for key: " + key); + } + } + return pid; + } catch (Throwable t) { + System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t)); + throw t; + } + } + + /** + * Adjusts the provided timeout value for the TIMEOUT_FACTOR + * @param tOut the timeout value to be adjusted + * @return The timeout value adjusted for the value of "test.timeout.factor" + * system property + */ + public static long adjustTimeout(long tOut) { + return Math.round(tOut * Utils.TIMEOUT_FACTOR); + } + + /** + * Return the contents of the named file as a single String, + * or null if not found. + * @param filename name of the file to read + * @return String contents of file, or null if file not found. + * @throws IOException + * if an I/O error occurs reading from the file or a malformed or + * unmappable byte sequence is read + */ + public static String fileAsString(String filename) throws IOException { + Path filePath = Paths.get(filename); + if (!Files.exists(filePath)) return null; + return new String(Files.readAllBytes(filePath)); + } + + private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + + /** + * Returns hex view of byte array + * + * @param bytes byte array to process + * @return space separated hexadecimal string representation of bytes + */ + public static String toHexString(byte[] bytes) { + char[] hexView = new char[bytes.length * 3 - 1]; + for (int i = 0; i < bytes.length - 1; i++) { + hexView[i * 3] = hexArray[(bytes[i] >> 4) & 0x0F]; + hexView[i * 3 + 1] = hexArray[bytes[i] & 0x0F]; + hexView[i * 3 + 2] = ' '; + } + hexView[hexView.length - 2] = hexArray[(bytes[bytes.length - 1] >> 4) & 0x0F]; + hexView[hexView.length - 1] = hexArray[bytes[bytes.length - 1] & 0x0F]; + return new String(hexView); + } + + /** + * Returns byte array of hex view + * + * @param hex hexadecimal string representation + * @return byte array + */ + public static byte[] toByteArray(String hex) { + int length = hex.length(); + byte[] bytes = new byte[length / 2]; + for (int i = 0; i < length; i += 2) { + bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); + } + return bytes; + } + + /** + * Returns {@link java.util.Random} generator initialized with particular seed. + * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME} + * In case no seed is provided, the method uses a random number. + * The used seed printed to stdout. + * @return {@link java.util.Random} generator with particular seed. + */ + public static Random getRandomInstance() { + if (RANDOM_GENERATOR == null) { + synchronized (Utils.class) { + if (RANDOM_GENERATOR == null) { + RANDOM_GENERATOR = new Random(SEED); + System.out.printf("For random generator using seed: %d%n", SEED); + System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); + } + } + } + return RANDOM_GENERATOR; + } + + /** + * Returns random element of non empty collection + * + * @param a type of collection element + * @param collection collection of elements + * @return random element of collection + * @throws IllegalArgumentException if collection is empty + */ + public static T getRandomElement(Collection collection) + throws IllegalArgumentException { + if (collection.isEmpty()) { + throw new IllegalArgumentException("Empty collection"); + } + Random random = getRandomInstance(); + int elementIndex = 1 + random.nextInt(collection.size() - 1); + Iterator iterator = collection.iterator(); + while (--elementIndex != 0) { + iterator.next(); + } + return iterator.next(); + } + + /** + * Returns random element of non empty array + * + * @param a type of array element + * @param array array of elements + * @return random element of array + * @throws IllegalArgumentException if array is empty + */ + public static T getRandomElement(T[] array) + throws IllegalArgumentException { + if (array == null || array.length == 0) { + throw new IllegalArgumentException("Empty or null array"); + } + Random random = getRandomInstance(); + return array[random.nextInt(array.length)]; + } + + /** + * Wait for condition to be true + * + * @param condition, a condition to wait for + */ + public static final void waitForCondition(BooleanSupplier condition) { + waitForCondition(condition, -1L, 100L); + } + + /** + * Wait until timeout for condition to be true + * + * @param condition, a condition to wait for + * @param timeout a time in milliseconds to wait for condition to be true + * specifying -1 will wait forever + * @return condition value, to determine if wait was successful + */ + public static final boolean waitForCondition(BooleanSupplier condition, + long timeout) { + return waitForCondition(condition, timeout, 100L); + } + + /** + * Wait until timeout for condition to be true for specified time + * + * @param condition, a condition to wait for + * @param timeout a time in milliseconds to wait for condition to be true, + * specifying -1 will wait forever + * @param sleepTime a time to sleep value in milliseconds + * @return condition value, to determine if wait was successful + */ + public static final boolean waitForCondition(BooleanSupplier condition, + long timeout, long sleepTime) { + long startTime = System.currentTimeMillis(); + while (!(condition.getAsBoolean() || (timeout != -1L + && ((System.currentTimeMillis() - startTime) > timeout)))) { + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new Error(e); + } + } + return condition.getAsBoolean(); + } + + /** + * Interface same as java.lang.Runnable but with + * method {@code run()} able to throw any Throwable. + */ + public static interface ThrowingRunnable { + void run() throws Throwable; + } + + /** + * Filters out an exception that may be thrown by the given + * test according to the given filter. + * + * @param test - method that is invoked and checked for exception. + * @param filter - function that checks if the thrown exception matches + * criteria given in the filter's implementation. + * @return - exception that matches the filter if it has been thrown or + * {@code null} otherwise. + * @throws Throwable - if test has thrown an exception that does not + * match the filter. + */ + public static Throwable filterException(ThrowingRunnable test, + Function filter) throws Throwable { + try { + test.run(); + } catch (Throwable t) { + if (filter.apply(t)) { + return t; + } else { + throw t; + } + } + return null; + } + + /** + * Ensures a requested class is loaded + * @param aClass class to load + */ + public static void ensureClassIsLoaded(Class aClass) { + if (aClass == null) { + throw new Error("Requested null class"); + } + try { + Class.forName(aClass.getName(), /* initialize = */ true, + ClassLoader.getSystemClassLoader()); + } catch (ClassNotFoundException e) { + throw new Error("Class not found", e); + } + } + /** + * @param parent a class loader to be the parent for the returned one + * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg + * property and with the given parent + */ + public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { + URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) + .map(Paths::get) + .map(Path::toUri) + .map(x -> { + try { + return x.toURL(); + } catch (MalformedURLException ex) { + throw new Error("Test issue. JTREG property" + + " 'test.class.path'" + + " is not defined correctly", ex); + } + }).toArray(URL[]::new); + return new URLClassLoader(urls, parent); + } + + /** + * Runs runnable and checks that it throws expected exception. If exceptionException is null it means + * that we expect no exception to be thrown. + * @param runnable what we run + * @param expectedException expected exception + */ + public static void runAndCheckException(ThrowingRunnable runnable, Class expectedException) { + runAndCheckException(runnable, t -> { + if (t == null) { + if (expectedException != null) { + throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); + } + } else { + String message = "Got unexpected exception " + t.getClass().getSimpleName(); + if (expectedException == null) { + throw new AssertionError(message, t); + } else if (!expectedException.isAssignableFrom(t.getClass())) { + message += " instead of " + expectedException.getSimpleName(); + throw new AssertionError(message, t); + } + } + }); + } + + /** + * Runs runnable and makes some checks to ensure that it throws expected exception. + * @param runnable what we run + * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise + */ + public static void runAndCheckException(ThrowingRunnable runnable, Consumer checkException) { + Throwable throwable = null; + try { + runnable.run(); + } catch (Throwable t) { + throwable = t; + } + checkException.accept(throwable); + } + + /** + * Converts to VM type signature + * + * @param type Java type to convert + * @return string representation of VM type + */ + public static String toJVMTypeSignature(Class type) { + if (type.isPrimitive()) { + if (type == boolean.class) { + return "Z"; + } else if (type == byte.class) { + return "B"; + } else if (type == char.class) { + return "C"; + } else if (type == double.class) { + return "D"; + } else if (type == float.class) { + return "F"; + } else if (type == int.class) { + return "I"; + } else if (type == long.class) { + return "J"; + } else if (type == short.class) { + return "S"; + } else if (type == void.class) { + return "V"; + } else { + throw new Error("Unsupported type: " + type); + } + } + String result = type.getName().replaceAll("\\.", "/"); + if (!type.isArray()) { + return "L" + result + ";"; + } + return result; + } + + public static Object[] getNullValues(Class... types) { + Object[] result = new Object[types.length]; + int i = 0; + for (Class type : types) { + result[i++] = NULL_VALUES.get(type); + } + return result; + } + private static Map, Object> NULL_VALUES = new HashMap<>(); + static { + NULL_VALUES.put(boolean.class, false); + NULL_VALUES.put(byte.class, (byte) 0); + NULL_VALUES.put(short.class, (short) 0); + NULL_VALUES.put(char.class, '\0'); + NULL_VALUES.put(int.class, 0); + NULL_VALUES.put(long.class, 0L); + NULL_VALUES.put(float.class, 0.0f); + NULL_VALUES.put(double.class, 0.0d); + } + + /** + * Returns mandatory property value + * @param propName is a name of property to request + * @return a String with requested property value + */ + public static String getMandatoryProperty(String propName) { + Objects.requireNonNull(propName, "Requested null property"); + String prop = System.getProperty(propName); + Objects.requireNonNull(prop, + String.format("A mandatory property '%s' isn't set", propName)); + return prop; + } + + /* + * Run uname with specified arguments. + */ + public static OutputAnalyzer uname(String... args) throws Throwable { + String[] cmds = new String[args.length + 1]; + cmds[0] = "uname"; + System.arraycopy(args, 0, cmds, 1, args.length); + return ProcessTools.executeCommand(cmds); + } + + /* + * Returns the system distro. + */ + public static String distro() { + try { + return uname("-v").asLines().get(0); + } catch (Throwable t) { + throw new RuntimeException("Failed to determine distro.", t); + } + } + + // This method is intended to be called from a jtreg test. + // It will identify the name of the test by means of stack walking. + // It can handle both jtreg tests and a testng tests wrapped inside jtreg tests. + // For jtreg tests the name of the test will be searched by stack-walking + // until the method main() is found; the class containing that method is the + // main test class and will be returned as the name of the test. + // Special handling is used for testng tests. + public static String getTestName() { + String result = null; + // If we are using testng, then we should be able to load the "Test" annotation. + Class testClassAnnotation; + + try { + testClassAnnotation = Class.forName("org.testng.annotations.Test"); + } catch (ClassNotFoundException e) { + testClassAnnotation = null; + } + + StackTraceElement[] elms = (new Throwable()).getStackTrace(); + for (StackTraceElement n: elms) { + String className = n.getClassName(); + + // If this is a "main" method, then use its class name, but only + // if we are not using testng. + if (testClassAnnotation == null && "main".equals(n.getMethodName())) { + result = className; + break; + } + + // If this is a testng test, the test will have no "main" method. We can + // detect a testng test class by looking for the org.testng.annotations.Test + // annotation. If present, then use the name of this class. + if (testClassAnnotation != null) { + try { + Class c = Class.forName(className); + if (c.isAnnotationPresent(testClassAnnotation)) { + result = className; + break; + } + } catch (ClassNotFoundException e) { + throw new RuntimeException("Unexpected exception: " + e, e); + } + } + } + + if (result == null) { + throw new RuntimeException("Couldn't find main test class in stack trace"); + } + + return result; + } + + /** + * Creates an empty file in "user.dir" if the property set. + *

+ * This method is meant as a replacement for {@code Files#createTempFile(String, String, FileAttribute...)} + * that doesn't leave files behind in /tmp directory of the test machine + *

+ * If the property "user.dir" is not set, "." will be used. + * + * @param prefix + * @param suffix + * @param attrs + * @return the path to the newly created file that did not exist before this + * method was invoked + * @throws IOException + * + * @see {@link Files#createTempFile(String, String, FileAttribute...)} + */ + public static Path createTempFile(String prefix, String suffix, FileAttribute... attrs) throws IOException { + Path dir = Paths.get(System.getProperty("user.dir", ".")); + return Files.createTempFile(dir, prefix, suffix); + } + + /** + * Creates an empty directory in "user.dir" or "." + *

+ * This method is meant as a replacement for {@code Files#createTempDirectory(String, String, FileAttribute...)} + * that doesn't leave files behind in /tmp directory of the test machine + *

+ * If the property "user.dir" is not set, "." will be used. + * + * @param prefix + * @param attrs + * @return the path to the newly created directory + * @throws IOException + * + * @see {@link Files#createTempDirectory(String, String, FileAttribute...)} + */ + public static Path createTempDirectory(String prefix, FileAttribute... attrs) throws IOException { + Path dir = Paths.get(System.getProperty("user.dir", ".")); + return Files.createTempDirectory(dir, prefix); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/Artifact.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/Artifact.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/Artifact.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/Artifact.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.lang.annotation.*; + +@Target(ElementType.TYPE) +@Repeatable(ArtifactContainer.class) +@Retention(RetentionPolicy.RUNTIME) +public @interface Artifact { + String organization(); + String name(); + String revision(); + String extension(); + String classifier() default ""; + boolean unpack() default true; +} + diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactContainer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.lang.annotation.*; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface ArtifactContainer { + Artifact[] value(); +} + diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactManager.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.io.FileNotFoundException; +import java.nio.file.Path; + +public interface ArtifactManager { + public Path resolve(Artifact artifact) throws ArtifactResolverException; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.io.FileNotFoundException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +public class ArtifactResolver { + public static Map resolve(Class klass) throws ArtifactResolverException { + ArtifactManager manager = new DefaultArtifactManager(); + try { + String managerName = System.getProperty("jdk.test.lib.artifacts.artifactmanager"); + if (managerName != null) { + manager = (ArtifactManager) Class.forName(managerName).newInstance(); + } else { + manager = JibArtifactManager.newInstance(); + } + } catch (Exception e) { + // If we end up here, we'll use the DefaultArtifactManager + } + + ArtifactContainer artifactContainer = klass.getAnnotation(ArtifactContainer.class); + HashMap locations = new HashMap<>(); + Artifact[] artifacts; + + if (artifactContainer == null) { + artifacts = new Artifact[]{klass.getAnnotation(Artifact.class)}; + } else { + artifacts = artifactContainer.value(); + } + for (Artifact artifact : artifacts) { + locations.put(artifactName(artifact), manager.resolve(artifact)); + } + + return locations; + } + + private static String artifactName(Artifact artifact) { + // Format of the artifact name is .-(-) + String name = String.format("%s.%s-%s", artifact.organization(), artifact.name(), artifact.revision()); + if (artifact.classifier().length() != 0) { + name = name +"-" + artifact.classifier(); + } + return name; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/ArtifactResolverException.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,15 @@ +package jdk.test.lib.artifacts; + +/** + * Thrown by the ArtifactResolver when failing to resolve an Artifact. + */ +public class ArtifactResolverException extends Exception { + + public ArtifactResolverException(String message) { + super(message); + } + + public ArtifactResolverException(String message, Throwable cause) { + super(message, cause); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/DefaultArtifactManager.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.io.FileNotFoundException; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class DefaultArtifactManager implements ArtifactManager { + @Override + public Path resolve(Artifact artifact) throws ArtifactResolverException { + String name = artifact.name(); + String location = System.getProperty(artifactProperty(name)); + if (location == null) { + throw new ArtifactResolverException("Couldn't automatically resolve dependency for " + name + + " , revision " + artifact.revision() + "\n" + + "Please specify the location using " + artifactProperty(name)); + } + return Paths.get(location); + } + + private static String artifactProperty(String name) { + return "jdk.test.lib.artifacts." + name; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/artifacts/JibArtifactManager.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.artifacts; + +import java.io.FileNotFoundException; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +public class JibArtifactManager implements ArtifactManager { + private static final String JIB_SERVICE_FACTORY = "com.oracle.jib.api.JibServiceFactory"; + private static String jibVersion = "1.0"; + private Object installerObject; + + private JibArtifactManager(Object o) { + installerObject = o; + } + + public static JibArtifactManager newInstance() throws ClassNotFoundException { + try { + Class jibServiceFactory = Class.forName(JIB_SERVICE_FACTORY); + Object jibArtifactInstaller = jibServiceFactory.getMethod("createJibArtifactInstaller").invoke(null); + return new JibArtifactManager(jibArtifactInstaller); + } catch (Exception e) { + throw new ClassNotFoundException(JIB_SERVICE_FACTORY, e); + } + } + + private Path download(String jibVersion, HashMap artifactDescription) throws Exception { + return invokeInstallerMethod("download", jibVersion, artifactDescription); + } + + private Path install(String jibVersion, HashMap artifactDescription) throws Exception { + return invokeInstallerMethod("install", jibVersion, artifactDescription); + } + + private Path invokeInstallerMethod(String methodName, String jibVersion, HashMap artifactDescription) throws Exception { + Method m = Class.forName("com.oracle.jib.api.JibArtifactInstaller").getMethod(methodName, String.class, Map.class); + return (Path)m.invoke(installerObject, jibVersion, artifactDescription); + } + + @Override + public Path resolve(Artifact artifact) throws ArtifactResolverException { + Path path; + // Use the DefaultArtifactManager to enable users to override locations + try { + ArtifactManager manager = new DefaultArtifactManager(); + path = manager.resolve(artifact); + } catch (ArtifactResolverException e) { + // Location hasn't been overridden, continue to automatically try to resolve the dependency + try { + HashMap artifactDescription = new HashMap<>(); + artifactDescription.put("module", artifact.name()); + artifactDescription.put("organization", artifact.organization()); + artifactDescription.put("ext", artifact.extension()); + artifactDescription.put("revision", artifact.revision()); + if (artifact.classifier().length() > 0) { + artifactDescription.put("classifier", artifact.classifier()); + } + + path = download(jibVersion, artifactDescription); + if (artifact.unpack()) { + path = install(jibVersion, artifactDescription); + } + } catch (Exception e2) { + throw new ArtifactResolverException("Failed to resolve the artifact " + artifact, e2); + } + } + return path; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSOptions.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSOptions.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSOptions.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSOptions.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.cds; + +import java.util.ArrayList; + +// This class represents options used +// during creation of CDS archive and/or running JVM with a CDS archive +public class CDSOptions { + public String xShareMode = "on"; + public String archiveName; + public ArrayList prefix = new ArrayList(); + public ArrayList suffix = new ArrayList(); + + // Indicate whether to append "-version" when using CDS Archive. + // Most of tests will use '-version' + public boolean useVersion = true; + + + public CDSOptions() { + } + + + public CDSOptions addPrefix(String... prefix) { + for (String s : prefix) this.prefix.add(s); + return this; + } + + + public CDSOptions addSuffix(String... suffix) { + for (String s : suffix) this.suffix.add(s); + return this; + } + + public CDSOptions setXShareMode(String mode) { + this.xShareMode = mode; + return this; + } + + + public CDSOptions setArchiveName(String name) { + this.archiveName = name; + return this; + } + + + public CDSOptions setUseVersion(boolean use) { + this.useVersion = use; + return this; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSTestUtils.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSTestUtils.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSTestUtils.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cds/CDSTestUtils.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.cds; + +import java.io.IOException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import jdk.test.lib.Utils; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + + +// This class contains common test utilities for testing CDS +public class CDSTestUtils { + public interface Checker { + public void check(OutputAnalyzer output) throws Exception; + } + + /* + * INTRODUCTION + * + * When testing various CDS functionalities, we need to launch JVM processes + * using a "launch method" (such as TestCommon.run), and analyze the results of these + * processes. + * + * While typical jtreg tests would use OutputAnalyzer in such cases, due to the + * complexity of CDS failure modes, we have added the CDSTestUtils.Result class + * to make the analysis more convenient and less error prone. + * + * A Java process can end in one of the following 4 states: + * + * 1: Unexpected error - such as JVM crashing. In this case, the "launch method" + * will throw a RuntimeException. + * 2: Mapping Failure - this happens when the OS (intermittently) fails to map the + * CDS archive, normally caused by Address Space Layout Randomization. + * We usually treat this as "pass". + * 3: Normal Exit - the JVM process has finished without crashing, and the exit code is 0. + * 4: Abnormal Exit - the JVM process has finished without crashing, and the exit code is not 0. + * + * In most test cases, we need to check the JVM process's output in cases 3 and 4. However, we need + * to make sure that our test code is not confused by case 2. + * + * For example, a JVM process is expected to print the string "Hi" and exit with 0. With the old + * CDSTestUtils.runWithArchive API, the test may be written as this: + * + * OutputAnalyzer out = CDSTestUtils.runWithArchive(args); + * out.shouldContain("Hi"); + * + * However, if the JVM process fails with mapping failure, the string "Hi" will not be in the output, + * and your test case will fail intermittently. + * + * Instead, the test case should be written as + * + * CCDSTestUtils.run(args).assertNormalExit("Hi"); + * + * EXAMPLES/HOWTO + * + * 1. For simple substring matching: + * + * CCDSTestUtils.run(args).assertNormalExit("Hi"); + * CCDSTestUtils.run(args).assertNormalExit("a", "b", "x"); + * CCDSTestUtils.run(args).assertAbnormalExit("failure 1", "failure2"); + * + * 2. For more complex output matching: using Lambda expressions + * + * CCDSTestUtils.run(args) + * .assertNormalExit(output -> output.shouldNotContain("this should not be printed"); + * CCDSTestUtils.run(args) + * .assertAbnormalExit(output -> { + * output.shouldNotContain("this should not be printed"); + * output.shouldHaveExitValue(123); + * }); + * + * 3. Chaining several checks: + * + * CCDSTestUtils.run(args) + * .assertNormalExit(output -> output.shouldNotContain("this should not be printed") + * .assertNormalExit("should have this", "should have that"); + * + * 4. [Rare use case] if a test sometimes exit normally, and sometimes abnormally: + * + * CCDSTestUtils.run(args) + * .ifNormalExit("ths string is printed when exiting with 0") + * .ifAbNormalExit("ths string is printed when exiting with 1"); + * + * NOTE: you usually don't want to write your test case like this -- it should always + * exit with the same exit code. (But I kept this API because some existing test cases + * behave this way -- need to revisit). + */ + public static class Result { + private final OutputAnalyzer output; + private final CDSOptions options; + private final boolean hasMappingFailure; + private final boolean hasAbnormalExit; + private final boolean hasNormalExit; + private final String CDS_DISABLED = "warning: CDS is disabled when the"; + + public Result(CDSOptions opts, OutputAnalyzer out) throws Exception { + options = opts; + output = out; + hasMappingFailure = CDSTestUtils.checkCommonExecExceptions(output); + hasAbnormalExit = (!hasMappingFailure) && (output.getExitValue() != 0); + hasNormalExit = (!hasMappingFailure) && (output.getExitValue() == 0); + + if (hasNormalExit) { + if ("on".equals(options.xShareMode) && + output.getStderr().contains("java version") && + !output.getStderr().contains(CDS_DISABLED)) { + // "-showversion" is always passed in the command-line by the execXXX methods. + // During normal exit, we require that the VM to show that sharing was enabled. + output.shouldContain("sharing"); + } + } + } + + public Result assertNormalExit(Checker checker) throws Exception { + if (!hasMappingFailure) { + checker.check(output); + output.shouldHaveExitValue(0); + } + return this; + } + + public Result assertAbnormalExit(Checker checker) throws Exception { + if (!hasMappingFailure) { + checker.check(output); + output.shouldNotHaveExitValue(0); + } + return this; + } + + // When {--limit-modules, --patch-module, and/or --upgrade-module-path} + // are specified, CDS is silently disabled for both -Xshare:auto and -Xshare:on. + public Result assertSilentlyDisabledCDS(Checker checker) throws Exception { + if (hasMappingFailure) { + throw new RuntimeException("Unexpected mapping failure"); + } + // this comes from a JVM warning message. + output.shouldContain(CDS_DISABLED); + + checker.check(output); + return this; + } + + public Result assertSilentlyDisabledCDS(int exitCode, String... matches) throws Exception { + return assertSilentlyDisabledCDS((out) -> { + out.shouldHaveExitValue(exitCode); + checkMatches(out, matches); + }); + } + + public Result ifNormalExit(Checker checker) throws Exception { + if (hasNormalExit) { + checker.check(output); + } + return this; + } + + public Result ifAbnormalExit(Checker checker) throws Exception { + if (hasAbnormalExit) { + checker.check(output); + } + return this; + } + + public Result ifNoMappingFailure(Checker checker) throws Exception { + if (!hasMappingFailure) { + checker.check(output); + } + return this; + } + + + public Result assertNormalExit(String... matches) throws Exception { + if (!hasMappingFailure) { + checkMatches(output, matches); + output.shouldHaveExitValue(0); + } + return this; + } + + public Result assertAbnormalExit(String... matches) throws Exception { + if (!hasMappingFailure) { + checkMatches(output, matches); + output.shouldNotHaveExitValue(0); + } + + return this; + } + } + + // Specify this property to copy sdandard output of the child test process to + // the parent/main stdout of the test. + // By default such output is logged into a file, and is copied into the main stdout. + public static final boolean CopyChildStdoutToMainStdout = + Boolean.valueOf(System.getProperty("test.cds.copy.child.stdout", "true")); + + // This property is passed to child test processes + public static final String TestTimeoutFactor = System.getProperty("test.timeout.factor", "1.0"); + + public static final String UnableToMapMsg = + "Unable to map shared archive: test did not complete; assumed PASS"; + + // Create bootstrap CDS archive, + // use extra JVM command line args as a prefix. + // For CDS tests specifying prefix makes more sense than specifying suffix, since + // normally there are no classes or arguments to classes, just "-version" + // To specify suffix explicitly use CDSOptions.addSuffix() + public static OutputAnalyzer createArchive(String... cliPrefix) + throws Exception { + return createArchive((new CDSOptions()).addPrefix(cliPrefix)); + } + + // Create bootstrap CDS archive + public static OutputAnalyzer createArchive(CDSOptions opts) + throws Exception { + + startNewArchiveName(); + + ArrayList cmd = new ArrayList(); + + for (String p : opts.prefix) cmd.add(p); + + cmd.add("-Xshare:dump"); + cmd.add("-Xlog:cds,cds+hashtables"); + if (opts.archiveName == null) + opts.archiveName = getDefaultArchiveName(); + cmd.add("-XX:SharedArchiveFile=./" + opts.archiveName); + + for (String s : opts.suffix) cmd.add(s); + + String[] cmdLine = cmd.toArray(new String[cmd.size()]); + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine); + return executeAndLog(pb, "dump"); + } + + + // check result of 'dump-the-archive' operation, that is "-Xshare:dump" + public static OutputAnalyzer checkDump(OutputAnalyzer output, String... extraMatches) + throws Exception { + + output.shouldContain("Loading classes to share"); + output.shouldHaveExitValue(0); + + for (String match : extraMatches) { + output.shouldContain(match); + } + + return output; + } + + + // A commonly used convenience methods to create an archive and check the results + // Creates an archive and checks for errors + public static OutputAnalyzer createArchiveAndCheck(CDSOptions opts) + throws Exception { + return checkDump(createArchive(opts)); + } + + + public static OutputAnalyzer createArchiveAndCheck(String... cliPrefix) + throws Exception { + return checkDump(createArchive(cliPrefix)); + } + + + // This method should be used to check the output of child VM for common exceptions. + // Most of CDS tests deal with child VM processes for creating and using the archive. + // However exceptions that occur in the child process do not automatically propagate + // to the parent process. This mechanism aims to improve the propagation + // of exceptions and common errors. + // Exception e argument - an exception to be re-thrown if none of the common + // exceptions match. Pass null if you wish not to re-throw any exception. + public static boolean checkCommonExecExceptions(OutputAnalyzer output, Exception e) + throws Exception { + if (output.getStdout().contains("http://bugreport.java.com/bugreport/crash.jsp")) { + throw new RuntimeException("Hotspot crashed"); + } + if (output.getStdout().contains("TEST FAILED")) { + throw new RuntimeException("Test Failed"); + } + if (output.getOutput().contains("shared class paths mismatch")) { +// throw new RuntimeException("shared class paths mismatch"); + } + if (output.getOutput().contains("Unable to unmap shared space")) { + throw new RuntimeException("Unable to unmap shared space"); + } + + // Special case -- sometimes Xshare:on fails because it failed to map + // at given address. This behavior is platform-specific, machine config-specific + // and can be random (see ASLR). + if (isUnableToMap(output)) { + System.out.println(UnableToMapMsg); + return true; + } + + if (e != null) { + throw e; + } + return false; + } + + public static boolean checkCommonExecExceptions(OutputAnalyzer output) throws Exception { + return checkCommonExecExceptions(output, null); + } + + + // Check the output for indication that mapping of the archive failed. + // Performance note: this check seems to be rather costly - searching the entire + // output stream of a child process for multiple strings. However, it is necessary + // to detect this condition, a failure to map an archive, since this is not a real + // failure of the test or VM operation, and results in a test being "skipped". + // Suggestions to improve: + // 1. VM can designate a special exit code for such condition. + // 2. VM can print a single distinct string indicating failure to map an archive, + // instead of utilizing multiple messages. + // These are suggestions to improve testibility of the VM. However, implementing them + // could also improve usability in the field. + public static boolean isUnableToMap(OutputAnalyzer output) { + String outStr = output.getOutput(); + if ((output.getExitValue() == 1) && ( + outStr.contains("Unable to reserve shared space at required address") || + outStr.contains("Unable to map ReadOnly shared space at required address") || + outStr.contains("Unable to map ReadWrite shared space at required address") || + outStr.contains("Unable to map MiscData shared space at required address") || + outStr.contains("Unable to map MiscCode shared space at required address") || + outStr.contains("Unable to map OptionalData shared space at required address") || + outStr.contains("Could not allocate metaspace at a compatible address") || + outStr.contains("UseSharedSpaces: Unable to allocate region, range is not within java heap") )) + { + return true; + } + + return false; + } + + public static Result run(String... cliPrefix) throws Exception { + CDSOptions opts = new CDSOptions(); + opts.setArchiveName(getDefaultArchiveName()); + opts.addPrefix(cliPrefix); + return new Result(opts, runWithArchive(opts)); + } + + public static Result run(CDSOptions opts) throws Exception { + return new Result(opts, runWithArchive(opts)); + } + + // Execute JVM with CDS archive, specify command line args suffix + public static OutputAnalyzer runWithArchive(String... cliPrefix) + throws Exception { + + return runWithArchive( (new CDSOptions()) + .setArchiveName(getDefaultArchiveName()) + .addPrefix(cliPrefix) ); + } + + + // Execute JVM with CDS archive, specify CDSOptions + public static OutputAnalyzer runWithArchive(CDSOptions opts) + throws Exception { + + ArrayList cmd = new ArrayList(); + + for (String p : opts.prefix) cmd.add(p); + + cmd.add("-Xshare:" + opts.xShareMode); + cmd.add("-Dtest.timeout.factor=" + TestTimeoutFactor); + + if (opts.archiveName == null) + opts.archiveName = getDefaultArchiveName(); + cmd.add("-XX:SharedArchiveFile=" + opts.archiveName); + + if (opts.useVersion) + cmd.add("-version"); + + for (String s : opts.suffix) cmd.add(s); + + String[] cmdLine = cmd.toArray(new String[cmd.size()]); + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine); + return executeAndLog(pb, "exec"); + } + + + // A commonly used convenience methods to create an archive and check the results + // Creates an archive and checks for errors + public static OutputAnalyzer runWithArchiveAndCheck(CDSOptions opts) throws Exception { + return checkExec(runWithArchive(opts)); + } + + + public static OutputAnalyzer runWithArchiveAndCheck(String... cliPrefix) throws Exception { + return checkExec(runWithArchive(cliPrefix)); + } + + + public static OutputAnalyzer checkExec(OutputAnalyzer output, + String... extraMatches) throws Exception { + CDSOptions opts = new CDSOptions(); + return checkExec(output, opts, extraMatches); + } + + + // check result of 'exec' operation, that is when JVM is run using the archive + public static OutputAnalyzer checkExec(OutputAnalyzer output, CDSOptions opts, + String... extraMatches) throws Exception { + try { + if ("on".equals(opts.xShareMode)) { + output.shouldContain("sharing"); + } + output.shouldHaveExitValue(0); + } catch (RuntimeException e) { + checkCommonExecExceptions(output, e); + return output; + } + + checkMatches(output, extraMatches); + return output; + } + + + public static OutputAnalyzer checkExecExpectError(OutputAnalyzer output, + int expectedExitValue, + String... extraMatches) throws Exception { + if (isUnableToMap(output)) { + System.out.println(UnableToMapMsg); + return output; + } + + output.shouldHaveExitValue(expectedExitValue); + checkMatches(output, extraMatches); + return output; + } + + public static OutputAnalyzer checkMatches(OutputAnalyzer output, + String... matches) throws Exception { + for (String match : matches) { + output.shouldContain(match); + } + return output; + } + + + // get the file object for the test artifact + public static File getTestArtifact(String name, boolean checkExistence) { + File dir = new File(System.getProperty("test.classes", ".")); + File file = new File(dir, name); + + if (checkExistence && !file.exists()) { + throw new RuntimeException("Cannot find " + file.getPath()); + } + + return file; + } + + + // create file containing the specified class list + public static File makeClassList(String classes[]) + throws Exception { + return makeClassList(getTestName() + "-", classes); + } + + // create file containing the specified class list + public static File makeClassList(String testCaseName, String classes[]) + throws Exception { + + File classList = getTestArtifact(testCaseName + "test.classlist", false); + FileOutputStream fos = new FileOutputStream(classList); + PrintStream ps = new PrintStream(fos); + + addToClassList(ps, classes); + + ps.close(); + fos.close(); + + return classList; + } + + + public static void addToClassList(PrintStream ps, String classes[]) + throws IOException + { + if (classes != null) { + for (String s : classes) { + ps.println(s); + } + } + } + + + // Optimization for getting a test name. + // Test name does not change during execution of the test, + // but getTestName() uses stack walking hence it is expensive. + // Therefore cache it and reuse it. + private static String testName; + public static String getTestName() { + if (testName == null) { + testName = Utils.getTestName(); + } + return testName; + } + + private static final SimpleDateFormat timeStampFormat = + new SimpleDateFormat("HH'h'mm'm'ss's'SSS"); + + private static String defaultArchiveName; + + // Call this method to start new archive with new unique name + public static void startNewArchiveName() { + defaultArchiveName = getTestName() + + timeStampFormat.format(new Date()) + ".jsa"; + } + + public static String getDefaultArchiveName() { + return defaultArchiveName; + } + + + // ===================== FILE ACCESS convenience methods + public static File getOutputFile(String name) { + File dir = new File(System.getProperty("test.classes", ".")); + return new File(dir, getTestName() + "-" + name); + } + + + public static File getOutputSourceFile(String name) { + File dir = new File(System.getProperty("test.classes", ".")); + return new File(dir, name); + } + + + public static File getSourceFile(String name) { + File dir = new File(System.getProperty("test.src", ".")); + return new File(dir, name); + } + + + // ============================= Logging + public static OutputAnalyzer executeAndLog(ProcessBuilder pb, String logName) throws Exception { + long started = System.currentTimeMillis(); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + + writeFile(getOutputFile(logName + ".stdout"), output.getStdout()); + writeFile(getOutputFile(logName + ".stderr"), output.getStderr()); + System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]"); + System.out.println("[STDERR]\n" + output.getStderr()); + + if (CopyChildStdoutToMainStdout) + System.out.println("[STDOUT]\n" + output.getStdout()); + + return output; + } + + + private static void writeFile(File file, String content) throws Exception { + FileOutputStream fos = new FileOutputStream(file); + PrintStream ps = new PrintStream(fos); + ps.print(content); + ps.close(); + fos.close(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ClassLoadUtils.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.classloader; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.FileInputStream; + +public class ClassLoadUtils { + + private ClassLoadUtils() { + } + + /** + * Get filename of class file from classpath for given class name. + * + * @param className class name + * @return filename or null if not found + */ + public static String getClassPath(String className) { + String fileName = className.replace(".", File.separator) + ".class"; + String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); + File target = null; + int i; + for (i = 0; i < classPath.length; ++i) { + target = new File(classPath[i] + File.separator + fileName); + System.out.println("Try: " + target); + if (target.exists()) { + break; + } + } + if (i != classPath.length) { + return classPath[i]; + } + return null; + } + + /** + * Get filename of class file from classpath for given class name. + * + * @param className class name + * @return filename or null if not found + */ + public static String getClassPathFileName(String className) { + String fileName = className.replace(".", File.separator) + ".class"; + String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); + File target = null; + int i; + for (i = 0; i < classPath.length; ++i) { + target = new File(classPath[i] + File.separator + fileName); + System.out.println("Try: " + target); + if (target.exists()) { + break; + } + } + if (i != classPath.length) { + try { + return target.getCanonicalPath(); + } catch (IOException e) { + return null; + } + } + return null; + } + + public static String getRedefineClassFileName(String dir, String className) { + String fileName = getClassPathFileName(className); + if (fileName == null) { + return null; + } + if (fileName.contains("classes")) { + return fileName.replace("classes", dir); + } else { + String classPath = getClassPath(className); + if (classPath != null) { + return classPath + File.separator + "newclass" + File.separator + className.replace(".", File.separator) + ".class"; + } else { + return null; + } + } + } + + /** + * Get filename of class file which is to be redefined. + */ + public static String getRedefineClassFileName(String className) { + return getRedefineClassFileName("newclass", className); + } + + /** + * Read whole file. + * + * @param file file + * @return contents of file as byte array + */ + public static byte[] readFile(File file) throws IOException { + InputStream in = new FileInputStream(file); + long countl = file.length(); + if (countl > Integer.MAX_VALUE) { + throw new IOException("File is too huge"); + } + int count = (int) countl; + byte[] buffer = new byte[count]; + int n = 0; + try { + while (n < count) { + int k = in.read(buffer, n, count - n); + if (k < 0) { + throw new IOException("Unexpected EOF"); + } + n += k; + } + } finally { + in.close(); + } + return buffer; + } + + /** + * Read whole file. + * + * @param name file name + * @return contents of file as byte array + */ + public static byte[] readFile(String name) throws IOException { + return readFile(new File(name)); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/FilterClassLoader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.classloader; + +import java.util.function.Predicate; +/** + * A classloader, which using target classloader in case provided condition + * for class name is met, and using parent otherwise + */ +public class FilterClassLoader extends ClassLoader { + + private final ClassLoader target; + private final Predicate condition; + + public FilterClassLoader(ClassLoader target, ClassLoader parent, + Predicate condition) { + super(parent); + this.condition = condition; + this.target = target; + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + if (condition.test(name)) { + return target.loadClass(name); + } + return super.loadClass(name); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/GeneratingClassLoader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.classloader; + +import java.io.*; +import java.util.*; + +/** + * Classloader that generates classes on the fly. + * + * This classloader can load classes with name starting with 'Class'. It will + * use TemplateClass as template and will replace class name in the bytecode of + * template class. It can be used for example to detect memory leaks in class + * loading or to quickly fill Metaspace. + */ +class TemplateClass { +} + +public class GeneratingClassLoader extends ClassLoader { + + public synchronized Class loadClass(String name) throws ClassNotFoundException { + return loadClass(name, false); + } + + public synchronized Class loadClass(String name, boolean resolve) + throws ClassNotFoundException { + Class c = findLoadedClass(name); + if (c != null) { + return c; + } + if (!name.startsWith(PREFIX)) { + return super.loadClass(name, resolve); + } + if (name.length() != templateClassName.length()) { + throw new ClassNotFoundException("Only can load classes with name.length() = " + getNameLength() + " got: '" + name + "' length: " + name.length()); + } + byte[] bytecode = getPatchedByteCode(name); + c = defineClass(name, bytecode, 0, bytecode.length); + if (resolve) { + resolveClass(c); + } + return c; + } + + /** + * Create generating class loader that will use class file for given class + * from classpath as template. + */ + public GeneratingClassLoader(String templateClassName) { + this.templateClassName = templateClassName; + classPath = System.getProperty("java.class.path").split(File.pathSeparator); + try { + templateClassNameBytes = templateClassName.getBytes(encoding); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + /** + * Create generating class loader that will use class file for + * nsk.share.classload.TemplateClass as template. + */ + public GeneratingClassLoader() { + this(TemplateClass.class.getName()); + } + + public int getNameLength() { + return templateClassName.length(); + } + + String getPrefix() { + return PREFIX; + } + + public String getClassName(int number) { + StringBuffer sb = new StringBuffer(); + sb.append(PREFIX); + sb.append(number); + int n = templateClassName.length() - sb.length(); + for (int i = 0; i < n; ++i) { + sb.append("_"); + } + return sb.toString(); + } + + private byte[] getPatchedByteCode(String name) throws ClassNotFoundException { + try { + byte[] bytecode = getByteCode(); + String fname = name.replace(".", File.separator); + byte[] replaceBytes = fname.getBytes(encoding); + for (int offset : offsets) { + for (int i = 0; i < replaceBytes.length; ++i) { + bytecode[offset + i] = replaceBytes[i]; + } + } + return bytecode; + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + private byte[] getByteCode() throws ClassNotFoundException { + if (bytecode == null) { + readByteCode(); + } + if (offsets == null) { + getOffsets(bytecode); + if (offsets == null) { + throw new RuntimeException("Class name not found in template class file"); + } + } + return (byte[]) bytecode.clone(); + } + + private void readByteCode() throws ClassNotFoundException { + String fname = templateClassName.replace(".", File.separator) + ".class"; + File target = null; + for (int i = 0; i < classPath.length; ++i) { + target = new File(classPath[i] + File.separator + fname); + if (target.exists()) { + break; + } + } + + if (target == null || !target.exists()) { + throw new ClassNotFoundException("File not found: " + target); + } + try { + bytecode = ClassLoadUtils.readFile(target); + } catch (IOException e) { + throw new ClassNotFoundException(templateClassName, e); + } + } + + private void getOffsets(byte[] bytecode) { + List offsets = new ArrayList(); + if (this.offsets == null) { + String pname = templateClassName.replace(".", "/"); + try { + byte[] pnameb = pname.getBytes(encoding); + int i = 0; + while (true) { + while (i < bytecode.length) { + int j = 0; + while (j < pnameb.length && bytecode[i + j] == pnameb[j]) { + ++j; + } + if (j == pnameb.length) { + break; + } + i++; + } + if (i == bytecode.length) { + break; + } + offsets.add(new Integer(i)); + i++; + } + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + this.offsets = new int[offsets.size()]; + for (int i = 0; i < offsets.size(); ++i) { + this.offsets[i] = offsets.get(i).intValue(); + } + } + } + + public static final String DEFAULT_CLASSNAME = TemplateClass.class.getName(); + static final String PREFIX = "Class"; + + private final String[] classPath; + private byte[] bytecode; + private int[] offsets; + private final String encoding = "UTF8"; + private final String templateClassName; + private final byte[] templateClassNameBytes; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/classloader/ParentLastURLClassLoader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.classloader; + +import java.net.URL; +import java.net.URLClassLoader; + +/** + * An url classloader, which trying to load class from provided URL[] first, + * and using parent classloader in case it failed + */ +public class ParentLastURLClassLoader extends URLClassLoader { + + public ParentLastURLClassLoader(URL urls[], ClassLoader parent) { + super(urls, parent); + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + try { + Class c = findClass(name); + if (c != null) { + return c; + } + } catch (ClassNotFoundException e) { + // ignore + } + return super.loadClass(name); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CPUSpecificCommandLineOptionTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli; + +import jdk.test.lib.cli.predicate.CPUSpecificPredicate; + +/** + * Base class for command line options tests that + * requires specific CPU arch or specific CPU features. + */ +public abstract class CPUSpecificCommandLineOptionTest + extends CommandLineOptionTest { + /** + * Creates new CPU specific test instance that does not + * require any CPU features. + * + * @param cpuArchPattern Regular expression that should + * match os.arch. + */ + public CPUSpecificCommandLineOptionTest(String cpuArchPattern) { + this(cpuArchPattern, null, null); + } + + /** + * Creates new CPU specific test instance that does not + * require from CPU support of {@code supportedCPUFeatures} features + * and no support of {@code unsupportedCPUFeatures}. + * + * @param cpuArchPattern Regular expression that should + * match os.arch. + * @param supportedCPUFeatures Array with names of features that + * should be supported by CPU. If {@code null}, + * then no features have to be supported. + * @param unsupportedCPUFeatures Array with names of features that + * should not be supported by CPU. + * If {@code null}, then CPU may support any + * features. + */ + public CPUSpecificCommandLineOptionTest(String cpuArchPattern, + String supportedCPUFeatures[], String unsupportedCPUFeatures[]) { + super(new CPUSpecificPredicate(cpuArchPattern, supportedCPUFeatures, + unsupportedCPUFeatures)); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,545 @@ +/* + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import java.util.function.BooleanSupplier; + +import jdk.test.lib.management.InputArguments; +import jdk.test.lib.process.ExitCode; +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.Platform; +import jdk.test.lib.Utils; + +/** + * Base class for command line option tests. + */ +public abstract class CommandLineOptionTest { + public static final String UNLOCK_DIAGNOSTIC_VM_OPTIONS + = "-XX:+UnlockDiagnosticVMOptions"; + public static final String UNLOCK_EXPERIMENTAL_VM_OPTIONS + = "-XX:+UnlockExperimentalVMOptions"; + protected static final String UNRECOGNIZED_OPTION_ERROR_FORMAT + = "Unrecognized VM option '[+-]?%s(=.*)?'"; + protected static final String EXPERIMENTAL_OPTION_ERROR_FORMAT + = "VM option '%s' is experimental and must be enabled via " + + "-XX:\\+UnlockExperimentalVMOptions."; + protected static final String DIAGNOSTIC_OPTION_ERROR_FORMAT + = " VM option '%s' is diagnostic and must be enabled via " + + "-XX:\\+UnlockDiagnosticVMOptions."; + private static final String PRINT_FLAGS_FINAL_FORMAT = "%s\\s*:?=\\s*%s"; + + /** + * Verifies that JVM startup behavior matches our expectations. + * + * @param option an option that should be passed to JVM + * @param expectedMessages an array of patterns that should occur + * in JVM output. If {@code null} then + * JVM output could be empty. + * @param unexpectedMessages an array of patterns that should not + * occur in JVM output. If {@code null} then + * JVM output could be empty. + * @param exitErrorMessage message that will be shown if exit code is not + * as expected. + * @param wrongWarningMessage message that will be shown if warning + * messages are not as expected. + * @param exitCode expected exit code. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyJVMStartup(String option, + String expectedMessages[], String unexpectedMessages[], + String exitErrorMessage, String wrongWarningMessage, + ExitCode exitCode) throws Throwable { + CommandLineOptionTest.verifyJVMStartup(expectedMessages, + unexpectedMessages, exitErrorMessage, + wrongWarningMessage, exitCode, false, option); + } + + /** + * Verifies that JVM startup behavior matches our expectations. + * + * @param expectedMessages an array of patterns that should occur + * in JVM output. If {@code null} then + * JVM output could be empty. + * @param unexpectedMessages an array of patterns that should not + * occur in JVM output. If {@code null} then + * JVM output could be empty. + * @param exitErrorMessage message that will be shown if exit code is not + * as expected. + * @param wrongWarningMessage message that will be shown if warning + * messages are not as expected. + * @param exitCode expected exit code. + * @param addTestVMOptions if {@code true} then test VM options will be + * passed to VM. + * @param options options that should be passed to VM in addition to mode + * flag. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyJVMStartup(String expectedMessages[], + String unexpectedMessages[], String exitErrorMessage, + String wrongWarningMessage, ExitCode exitCode, + boolean addTestVMOptions, String... options) + throws Throwable { + List finalOptions = new ArrayList<>(); + if (addTestVMOptions) { + Collections.addAll(finalOptions, InputArguments.getVmInputArgs()); + Collections.addAll(finalOptions, Utils.getTestJavaOpts()); + } + Collections.addAll(finalOptions, options); + finalOptions.add("-version"); + + ProcessBuilder processBuilder + = ProcessTools.createJavaProcessBuilder(finalOptions.toArray( + new String[finalOptions.size()])); + OutputAnalyzer outputAnalyzer + = new OutputAnalyzer(processBuilder.start()); + + try { + outputAnalyzer.shouldHaveExitValue(exitCode.value); + } catch (RuntimeException e) { + String errorMessage = String.format( + "JVM process should have exit value '%d'.%n%s", + exitCode.value, exitErrorMessage); + throw new AssertionError(errorMessage, e); + } + + verifyOutput(expectedMessages, unexpectedMessages, + wrongWarningMessage, outputAnalyzer); + } + + /** + * Verifies that JVM startup behavior matches our expectations. + * + * @param expectedMessages an array of patterns that should occur in JVM + * output. If {@code null} then + * JVM output could be empty. + * @param unexpectedMessages an array of patterns that should not occur + * in JVM output. If {@code null} then + * JVM output could be empty. + * @param wrongWarningMessage message that will be shown if messages are + * not as expected. + * @param outputAnalyzer OutputAnalyzer instance + * @throws AssertionError if verification fails. + */ + public static void verifyOutput(String[] expectedMessages, + String[] unexpectedMessages, String wrongWarningMessage, + OutputAnalyzer outputAnalyzer) { + if (expectedMessages != null) { + for (String expectedMessage : expectedMessages) { + try { + outputAnalyzer.shouldMatch(expectedMessage); + } catch (RuntimeException e) { + String errorMessage = String.format( + "Expected message not found: '%s'.%n%s", + expectedMessage, wrongWarningMessage); + throw new AssertionError(errorMessage, e); + } + } + } + + if (unexpectedMessages != null) { + for (String unexpectedMessage : unexpectedMessages) { + try { + outputAnalyzer.shouldNotMatch(unexpectedMessage); + } catch (RuntimeException e) { + String errorMessage = String.format( + "Unexpected message found: '%s'.%n%s", + unexpectedMessage, wrongWarningMessage); + throw new AssertionError(errorMessage, e); + } + } + } + } + + /** + * Verifies that JVM startup behavior matches our expectations when type + * of newly started VM is the same as the type of current. + * + * @param expectedMessages an array of patterns that should occur + * in JVM output. If {@code null} then + * JVM output could be empty. + * @param unexpectedMessages an array of patterns that should not + * occur in JVM output. If {@code null} then + * JVM output could be empty. + * @param exitErrorMessage Message that will be shown if exit value is not + * as expected. + * @param wrongWarningMessage message that will be shown if warning + * messages are not as expected. + * @param exitCode expected exit code. + * @param options options that should be passed to VM in addition to mode + * flag. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifySameJVMStartup(String expectedMessages[], + String unexpectedMessages[], String exitErrorMessage, + String wrongWarningMessage, ExitCode exitCode, String... options) + throws Throwable { + List finalOptions = new ArrayList<>(); + finalOptions.add(CommandLineOptionTest.getVMTypeOption()); + String extraFlagForEmulated = CommandLineOptionTest.getVMTypeOptionForEmulated(); + if (extraFlagForEmulated != null) { + finalOptions.add(extraFlagForEmulated); + } + Collections.addAll(finalOptions, options); + + CommandLineOptionTest.verifyJVMStartup(expectedMessages, + unexpectedMessages, exitErrorMessage, + wrongWarningMessage, exitCode, false, + finalOptions.toArray(new String[finalOptions.size()])); + } + + /** + * Verifies that value of specified JVM option is the same as + * expected value. + * This method filter out option with {@code optionName} + * name from test java options. + * + * @param optionName a name of tested option. + * @param expectedValue expected value of tested option. + * @param optionErrorString message will be shown if option value is not as + * expected. + * @param additionalVMOpts additional options that should be + * passed to JVM. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyOptionValue(String optionName, + String expectedValue, String optionErrorString, + String... additionalVMOpts) throws Throwable { + verifyOptionValue(optionName, expectedValue, optionErrorString, + true, additionalVMOpts); + } + + /** + * Verifies that value of specified JVM option is the same as + * expected value. + * This method filter out option with {@code optionName} + * name from test java options. + * + * @param optionName a name of tested option. + * @param expectedValue expected value of tested option. + * @param addTestVmOptions if {@code true}, then test VM options + * will be used. + * @param optionErrorString message will be shown if option value is not as + * expected. + * @param additionalVMOpts additional options that should be + * passed to JVM. + * @throws Throwable if verification fails or some other issues + * occur. + */ + public static void verifyOptionValue(String optionName, + String expectedValue, String optionErrorString, + boolean addTestVmOptions, String... additionalVMOpts) + throws Throwable { + List vmOpts = new ArrayList<>(); + + if (addTestVmOptions) { + Collections.addAll(vmOpts, + Utils.getFilteredTestJavaOpts(optionName)); + } + Collections.addAll(vmOpts, additionalVMOpts); + Collections.addAll(vmOpts, "-XX:+PrintFlagsFinal", "-version"); + + ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + vmOpts.toArray(new String[vmOpts.size()])); + + OutputAnalyzer outputAnalyzer + = new OutputAnalyzer(processBuilder.start()); + + try { + outputAnalyzer.shouldHaveExitValue(0); + } catch (RuntimeException e) { + String errorMessage = String.format( + "JVM should start with option '%s' without errors.", + optionName); + throw new AssertionError(errorMessage, e); + } + verifyOptionValue(optionName, expectedValue, optionErrorString, + outputAnalyzer); + } + + /** + * Verifies that value of specified JVM option is the same as + * expected value. + * + * @param optionName a name of tested option. + * @param expectedValue expected value of tested option. + * @param optionErrorString message will be shown if option value is not + * as expected. + * @param outputAnalyzer OutputAnalyzer instance + * @throws AssertionError if verification fails + */ + public static void verifyOptionValue(String optionName, + String expectedValue, String optionErrorString, + OutputAnalyzer outputAnalyzer) { + try { + outputAnalyzer.shouldMatch(String.format( + CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT, + optionName, expectedValue)); + } catch (RuntimeException e) { + String errorMessage = String.format( + "Option '%s' is expected to have '%s' value%n%s", + optionName, expectedValue, + optionErrorString); + throw new AssertionError(errorMessage, e); + } + } + + /** + * Start VM with given options and values. + * Generates command line option flags from + * {@code optionNames} and {@code optionValues}. + * + * @param optionNames names of options to pass in + * @param optionValues values of option + * @param additionalVMOpts additional options that should be + * passed to JVM. + * @return output from vm process + */ + public static OutputAnalyzer startVMWithOptions(String[] optionNames, + String[] optionValues, + String... additionalVMOpts) throws Throwable { + List vmOpts = new ArrayList<>(); + if (optionNames == null || optionValues == null || optionNames.length != optionValues.length) { + throw new IllegalArgumentException("optionNames and/or optionValues"); + } + + for (int i = 0; i < optionNames.length; i++) { + vmOpts.add(prepareFlag(optionNames[i], optionValues[i])); + } + Collections.addAll(vmOpts, additionalVMOpts); + Collections.addAll(vmOpts, "-version"); + + ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + vmOpts.toArray(new String[vmOpts.size()])); + + return new OutputAnalyzer(processBuilder.start()); + } + + /** + * Verifies from the output that values of specified JVM options were the same as + * expected values. + * + * @param outputAnalyzer search output for expect options and values. + * @param optionNames names of tested options. + * @param expectedValues expected values of tested options. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyOptionValuesFromOutput(OutputAnalyzer outputAnalyzer, + String[] optionNames, + String[] expectedValues) throws Throwable { + outputAnalyzer.shouldHaveExitValue(0); + for (int i = 0; i < optionNames.length; i++) { + outputAnalyzer.shouldMatch(String.format( + CommandLineOptionTest.PRINT_FLAGS_FINAL_FORMAT, + optionNames[i], expectedValues[i])); + } + } + + /** + * Verifies that value of specified JVM options are the same as + * expected values. + * Generates command line option flags from + * {@code optionNames} and {@code expectedValues}. + * + * @param optionNames names of tested options. + * @param expectedValues expected values of tested options. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyOptionValues(String[] optionNames, + String[] expectedValues) throws Throwable { + OutputAnalyzer outputAnalyzer = startVMWithOptions(optionNames, expectedValues, "-XX:+PrintFlagsFinal"); + verifyOptionValuesFromOutput(outputAnalyzer, optionNames, expectedValues); + } + + /** + * Verifies that value of specified JVM when type of newly started VM + * is the same as the type of current. + * This method filter out option with {@code optionName} + * name from test java options. + * Only mode flag will be passed to VM in addition to + * {@code additionalVMOpts} + * + * @param optionName name of tested option. + * @param expectedValue expected value of tested option. + * @param optionErrorString message to show if option has another value + * @param additionalVMOpts additional options that should be + * passed to JVM. + * @throws Throwable if verification fails or some other issues occur. + */ + public static void verifyOptionValueForSameVM(String optionName, + String expectedValue, String optionErrorString, + String... additionalVMOpts) throws Throwable { + List finalOptions = new ArrayList<>(); + finalOptions.add(CommandLineOptionTest.getVMTypeOption()); + String extraFlagForEmulated = CommandLineOptionTest.getVMTypeOptionForEmulated(); + if (extraFlagForEmulated != null) { + finalOptions.add(extraFlagForEmulated); + } + Collections.addAll(finalOptions, additionalVMOpts); + + CommandLineOptionTest.verifyOptionValue(optionName, expectedValue, + optionErrorString, false, + finalOptions.toArray(new String[finalOptions.size()])); + } + + /** + * Prepares boolean command line flag with name {@code name} according + * to it's {@code value}. + * + * @param name the name of option to be prepared + * @param value the value of option + * @return prepared command line flag + */ + public static String prepareBooleanFlag(String name, boolean value) { + return String.format("-XX:%c%s", (value ? '+' : '-'), name); + } + + /** + * Prepares numeric command line flag with name {@code name} by setting + * it's value to {@code value}. + * + * @param name the name of option to be prepared + * @param value the value of option + * @return prepared command line flag + */ + public static String prepareNumericFlag(String name, Number value) { + return String.format("-XX:%s=%s", name, value.toString()); + } + + /** + * Prepares generic command line flag with name {@code name} by setting + * it's value to {@code value}. + * + * @param name the name of option to be prepared + * @param value the value of option ("+" or "-" can be used instead of "true" or "false") + * @return prepared command line flag + */ + public static String prepareFlag(String name, String value) { + if (value.equals("+") || value.equalsIgnoreCase("true")) { + return "-XX:+" + name; + } else if (value.equals("-") || value.equalsIgnoreCase("false")) { + return "-XX:-" + name; + } else { + return "-XX:" + name + "=" + value; + } + } + + /** + * Returns message that should occur in VM output if option + * {@code optionName} if unrecognized. + * + * @param optionName the name of option for which message should be returned + * @return message saying that option {@code optionName} is unrecognized + */ + public static String getUnrecognizedOptionErrorMessage(String optionName) { + return String.format( + CommandLineOptionTest.UNRECOGNIZED_OPTION_ERROR_FORMAT, + optionName); + } + + /** + * Returns message that should occur in VM output if option + * {@code optionName} is experimental and + * -XX:+UnlockExperimentalVMOptions was not passed to VM. + * + * @param optionName the name of option for which message should be returned + * @return message saying that option {@code optionName} is experimental + */ + public static String getExperimentalOptionErrorMessage(String optionName) { + return String.format( + CommandLineOptionTest.EXPERIMENTAL_OPTION_ERROR_FORMAT, + optionName); + } + + /** + * Returns message that should occur in VM output if option + * {@code optionName} is diagnostic and -XX:+UnlockDiagnosticVMOptions + * was not passed to VM. + * + * @param optionName the name of option for which message should be returned + * @return message saying that option {@code optionName} is diganostic + */ + public static String getDiagnosticOptionErrorMessage(String optionName) { + return String.format( + CommandLineOptionTest.DIAGNOSTIC_OPTION_ERROR_FORMAT, + optionName); + } + + /** + * @return option required to start a new VM with the same type as current. + * @throws RuntimeException when VM type is unknown. + */ + private static String getVMTypeOption() { + if (Platform.isServer()) { + return "-server"; + } else if (Platform.isClient()) { + return "-client"; + } else if (Platform.isMinimal()) { + return "-minimal"; + } else if (Platform.isGraal()) { + return "-graal"; + } + throw new RuntimeException("Unknown VM mode."); + } + + /** + * @return addtional VMoptions(Emulated related) required to start a new VM with the same type as current. + */ + private static String getVMTypeOptionForEmulated() { + if (Platform.isServer() && !Platform.isEmulatedClient()) { + return "-XX:-NeverActAsServerClassMachine"; + } else if (Platform.isEmulatedClient()) { + return "-XX:+NeverActAsServerClassMachine"; + } + return null; + } + + private final BooleanSupplier predicate; + + /** + * Constructs new CommandLineOptionTest that will be executed only if + * predicate {@code predicate} return {@code true}. + * @param predicate a predicate responsible for test's preconditions check. + */ + public CommandLineOptionTest(BooleanSupplier predicate) { + this.predicate = predicate; + } + + /** + * Runs command line option test. + */ + public final void test() throws Throwable { + if (predicate.getAsBoolean()) { + runTestCases(); + } + } + + /** + * @throws Throwable if some issue happened during test cases execution. + */ + protected abstract void runTestCases() throws Throwable; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/AndPredicate.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli.predicate; + +import java.util.function.BooleanSupplier; + +public class AndPredicate implements BooleanSupplier { + private final BooleanSupplier a; + private final BooleanSupplier b; + private final BooleanSupplier c; + + public AndPredicate(BooleanSupplier a, BooleanSupplier b) { + this.a = a; + this.b = b; + this.c = () -> true; // Boolean.TRUE::booleanValue + } + + public AndPredicate(BooleanSupplier a, BooleanSupplier b, BooleanSupplier c) { + this.a = a; + this.b = b; + this.c = c; + } + + @Override + public boolean getAsBoolean() { + return a.getAsBoolean() && b.getAsBoolean() && c.getAsBoolean(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/CPUSpecificPredicate.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli.predicate; + +import jdk.test.lib.Platform; +import sun.hotspot.cpuinfo.CPUInfo; + +import java.util.function.BooleanSupplier; + +public class CPUSpecificPredicate implements BooleanSupplier { + private final String cpuArchPattern; + private final String supportedCPUFeatures[]; + private final String unsupportedCPUFeatures[]; + + public CPUSpecificPredicate(String cpuArchPattern, + String supportedCPUFeatures[], + String unsupportedCPUFeatures[]) { + this.cpuArchPattern = cpuArchPattern; + this.supportedCPUFeatures = supportedCPUFeatures; + this.unsupportedCPUFeatures = unsupportedCPUFeatures; + } + + @Override + public boolean getAsBoolean() { + if (!Platform.getOsArch().matches(cpuArchPattern)) { + System.out.println("CPU arch " + Platform.getOsArch() + " does not match " + cpuArchPattern); + return false; + } + + if (supportedCPUFeatures != null) { + for (String feature : supportedCPUFeatures) { + if (!CPUInfo.hasFeature(feature)) { + System.out.println("CPU does not support " + feature + + " feature"); + return false; + } + } + } + + if (unsupportedCPUFeatures != null) { + for (String feature : unsupportedCPUFeatures) { + if (CPUInfo.hasFeature(feature)) { + System.out.println("CPU support " + feature + " feature"); + return false; + } + } + } + return true; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/NotPredicate.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli.predicate; + +import java.util.function.BooleanSupplier; + +public class NotPredicate implements BooleanSupplier { + private final BooleanSupplier s; + + public NotPredicate(BooleanSupplier s) { + this.s = s; + } + + @Override + public boolean getAsBoolean() { + return !s.getAsBoolean(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/cli/predicate/OrPredicate.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.cli.predicate; + +import java.util.function.BooleanSupplier; + +public class OrPredicate implements BooleanSupplier { + private final BooleanSupplier a; + private final BooleanSupplier b; + + public OrPredicate(BooleanSupplier a, BooleanSupplier b) { + this.a = a; + this.b = b; + } + + @Override + public boolean getAsBoolean() { + return a.getAsBoolean() || b.getAsBoolean(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CPUSetsReader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.cgroup; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import jdk.test.lib.Asserts; + + +// A simple CPU sets reader and parser +public class CPUSetsReader { + public static String PROC_SELF_STATUS_PATH = "/proc/self/status"; + + // Test the parser + public static void test() { + assertParse("0-7", "0,1,2,3,4,5,6,7"); + assertParse("1,3,6", "1,3,6"); + assertParse("0,2-4,6,10-11", "0,2,3,4,6,10,11"); + assertParse("0", "0"); + } + + + private static void assertParse(String cpuSet, String expectedResult) { + Asserts.assertEquals(listToString(parseCpuSet(cpuSet)), expectedResult); + } + + public static int getNumCpus() { + String path = "/proc/cpuinfo"; + try (Stream stream = Files.lines(Paths.get(path))) { + return (int) stream.filter(line -> line.startsWith("processor")).count(); + } catch (IOException e) { + return 0; + } + } + + + public static String readFromProcStatus(String setType) { + String path = PROC_SELF_STATUS_PATH; + Optional o = Optional.empty(); + + System.out.println("readFromProcStatus() entering for: " + setType); + + try (Stream stream = Files.lines(Paths.get(path))) { + o = stream + .filter(line -> line.contains(setType)) + .findFirst(); + } catch (IOException e) { + return null; + } + + if (!o.isPresent()) { + return null; // entry not found + } + + String[] parts = o.get().replaceAll("\\s", "").split(":"); + + // Should be 2 parts, before and after ":" + Asserts.assertEquals(parts.length, 2); + + String result = parts[1]; + System.out.println("readFromProcStatus() returning: " + result); + return result; + } + + + public static List parseCpuSet(String value) { + ArrayList result = new ArrayList(); + + try { + String[] commaSeparated = value.split(","); + + for (String item : commaSeparated) { + if (item.contains("-")) { + addRange(result, item); + } else { + result.add(Integer.parseInt(item)); + } + } + } catch (Exception e) { + System.err.println("Exception in getMaxCpuSets(): " + e); + return null; + } + + return result; + } + + private static void addRange(ArrayList list, String s) { + String[] range = s.split("-"); + if (range.length != 2) { + throw new RuntimeException("Range should only contain two items, but contains " + + range.length + " items"); + } + + int min = Integer.parseInt(range[0]); + int max = Integer.parseInt(range[1]); + + if (min >= max) { + String msg = String.format("min is greater or equals to max, min = %d, max = %d", + min, max); + throw new RuntimeException(msg); + } + + for (int i = min; i <= max; i++) { + list.add(i); + } + } + + + // Convert list of integers to string with comma-separated values + public static String listToString(List list) { + return listToString(list, Integer.MAX_VALUE); + } + + // Convert list of integers to a string with comma-separated values; + // include up to maxCount. + public static String listToString(List list, int maxCount) { + return list.stream() + .limit(maxCount) + .map(Object::toString) + .collect(Collectors.joining(",")); + } + + public static String numberToString(int num) { + return IntStream.range(0, num).boxed().map(Object::toString).collect(Collectors.joining(",")); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/CgroupMetricsTester.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2020, Red Hat Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.cgroup; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +interface CgroupMetricsTester { + + public static final double ERROR_MARGIN = 0.1; + public static final String EMPTY_STR = ""; + + public void testMemorySubsystem(); + public void testCpuAccounting(); + public void testCpuSchedulingMetrics(); + public void testCpuSets(); + public void testCpuConsumption() throws IOException, InterruptedException; + public void testMemoryUsage() throws Exception; + public void testMisc(); + + public static long convertStringToLong(String strval, long initialVal, long overflowRetval) { + long retval = initialVal; + if (strval == null) return retval; + + try { + retval = Long.parseLong(strval); + } catch (NumberFormatException e) { + // For some properties (e.g. memory.limit_in_bytes) we may overflow the range of signed long. + // In this case, return Long.MAX_VALUE + BigInteger b = new BigInteger(strval); + if (b.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { + return overflowRetval; + } + } + return retval; + } + + public static boolean compareWithErrorMargin(long oldVal, long newVal) { + return Math.abs(oldVal - newVal) <= Math.abs(oldVal * ERROR_MARGIN); + } + + public static boolean compareWithErrorMargin(double oldVal, double newVal) { + return Math.abs(oldVal - newVal) <= Math.abs(oldVal * ERROR_MARGIN); + } + + public static void fail(String controller, String metric, long oldVal, long testVal) { + throw new RuntimeException("Test failed for - " + controller + ":" + + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); + } + + public static void fail(String controller, String metric, String oldVal, String testVal) { + throw new RuntimeException("Test failed for - " + controller + ":" + + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); + } + + public static void fail(String controller, String metric, double oldVal, double testVal) { + throw new RuntimeException("Test failed for - " + controller + ":" + + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); + } + + public static void fail(String controller, String metric, boolean oldVal, boolean testVal) { + throw new RuntimeException("Test failed for - " + controller + ":" + + metric + ", expected [" + oldVal + "], got [" + testVal + "]"); + } + + public static void warn(String controller, String metric, long oldVal, long testVal) { + System.err.println("Warning - " + controller + ":" + metric + + ", expected [" + oldVal + "], got [" + testVal + "]"); + } + + public static Integer[] convertCpuSetsToArray(String cpusstr) { + if (cpusstr == null || EMPTY_STR.equals(cpusstr)) { + return null; + } + // Parse range string in the format 1,2-6,7 + Integer[] cpuSets = Stream.of(cpusstr.split(",")).flatMap(a -> { + if (a.contains("-")) { + String[] range = a.split("-"); + return IntStream.rangeClosed(Integer.parseInt(range[0]), + Integer.parseInt(range[1])).boxed(); + } else { + return Stream.of(Integer.parseInt(a)); + } + }).toArray(Integer[]::new); + return cpuSets; + } + + public static Integer[] boxedArrayOrNull(int[] primitiveArray) { + if (primitiveArray == null) { + return null; + } + return Arrays.stream(primitiveArray).boxed().toArray(Integer[]::new); + } + + public static Integer[] sortAllowNull(Integer[] array) { + if (array == null) { + return null; + } + Arrays.sort(array); + return array; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTester.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2020, Red Hat Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package jdk.test.lib.containers.cgroup; + +import java.util.Objects; + +import jdk.internal.platform.Metrics; + +/** + * Cgroup version agnostic metrics tester + * + */ +public class MetricsTester { + + private static final String CGROUP_V1 = "cgroupv1"; + private static final String CGROUP_V2 = "cgroupv2"; + + private static CgroupMetricsTester createInstance(Metrics m) { + Objects.requireNonNull(m); + if (CGROUP_V1.equals(m.getProvider())) { + MetricsTesterCgroupV1 t = new MetricsTesterCgroupV1(); + t.setup(); + return t; + } else if (CGROUP_V2.equals(m.getProvider())) { + return new MetricsTesterCgroupV2(); + } else { + System.err.println("WARNING: Metrics provider, '" + m.getProvider() + + "' is unknown!"); + return null; + } + } + + public void testAll(Metrics m) throws Exception { + CgroupMetricsTester tester = createInstance(m); + tester.testCpuAccounting(); + tester.testCpuConsumption(); + tester.testCpuSchedulingMetrics(); + tester.testCpuSets(); + tester.testMemorySubsystem(); + tester.testMemoryUsage(); + tester.testMisc(); + } + + public static void main(String[] args) throws Exception { + Metrics m = Metrics.systemMetrics(); + // If cgroups is not configured, report success + if (m == null) { + System.out.println("TEST PASSED!!!"); + return; + } + + MetricsTester metricsTester = new MetricsTester(); + metricsTester.testAll(m); + System.out.println("TEST PASSED!!!"); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV1.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.cgroup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import jdk.internal.platform.CgroupSubsystem; +import jdk.internal.platform.CgroupV1Metrics; +import jdk.internal.platform.Metrics; +import jdk.test.lib.Asserts; + +public class MetricsTesterCgroupV1 implements CgroupMetricsTester { + + // Aliased for readability + private static final long RETVAL_UNAVAILABLE = CgroupSubsystem.LONG_RETVAL_UNLIMITED; + private static long unlimited_minimum = 0x7FFFFFFFFF000000L; + long startSysVal; + long startUserVal; + long startUsage; + long startPerCpu[]; + + enum Controller { + MEMORY("memory"), + CPUSET("cpuset"), + CPU("cpu"), + CPUACCT("cpuacct"), + BLKIO("blkio"); + + private String value; + + Controller(String value) { + this.value = value; + } + + public String value() { + return value; + } + } + + private static final Set allowedSubSystems = + Stream.of(Controller.values()).map(Controller::value).collect(Collectors.toSet()); + + private static final Map subSystemPaths = new HashMap<>(); + + private static void setPath(String[] line) { + String cgroupPath = line[2]; + String[] subSystems = line[1].split(","); + + for (String subSystem : subSystems) { + if (allowedSubSystems.contains(subSystem)) { + String[] paths = subSystemPaths.get(subSystem); + String finalPath = ""; + String root = paths[0]; + String mountPoint = paths[1]; + if (root != null && cgroupPath != null) { + if (root.equals("/")) { + if (!cgroupPath.equals("/")) { + finalPath = mountPoint + cgroupPath; + } else { + finalPath = mountPoint; + } + } else { + if (root.equals(cgroupPath)) { + finalPath = mountPoint; + } else { + if (cgroupPath.startsWith(root)) { + if (cgroupPath.length() > root.length()) { + String cgroupSubstr = cgroupPath.substring(root.length()); + finalPath = mountPoint + cgroupSubstr; + } + } + } + } + } + subSystemPaths.put(subSystem, new String[]{finalPath, mountPoint}); + } + } + } + + private static void createSubsystems(String[] line) { + if (line.length < 5) return; + Path p = Paths.get(line[4]); + String subsystemName = p.getFileName().toString(); + if (subsystemName != null) { + for (String subSystem : subsystemName.split(",")) { + if (allowedSubSystems.contains(subSystem)) { + subSystemPaths.put(subSystem, new String[]{line[3], line[4]}); + } + } + } + } + + public void setup() { + Metrics metrics = Metrics.systemMetrics(); + // Initialize CPU usage metrics before we do any testing. + startSysVal = metrics.getCpuSystemUsage(); + startUserVal = metrics.getCpuUserUsage(); + startUsage = metrics.getCpuUsage(); + startPerCpu = metrics.getPerCpuUsage(); + + try { + Stream lines = Files.lines(Paths.get("/proc/self/mountinfo")); + lines.filter(line -> line.contains(" - cgroup cgroup ")) + .map(line -> line.split(" ")) + .forEach(MetricsTesterCgroupV1::createSubsystems); + lines.close(); + + lines = Files.lines(Paths.get("/proc/self/cgroup")); + lines.map(line -> line.split(":")) + .filter(line -> (line.length >= 3)) + .forEach(MetricsTesterCgroupV1::setPath); + lines.close(); + } catch (IOException e) { + } + } + + private static String getFileContents(Controller subSystem, String fileName) { + String fname = subSystemPaths.get(subSystem.value())[0] + File.separator + fileName; + try { + return new Scanner(new File(fname)).useDelimiter("\\Z").next(); + } catch (FileNotFoundException e) { + System.err.println("Unable to open : " + fname); + return null; + } + } + + private static long getLongValueFromFile(Controller subSystem, String fileName) { + String data = getFileContents(subSystem, fileName); + return (data == null || data.isEmpty()) ? RETVAL_UNAVAILABLE : convertStringToLong(data); + } + + private static long convertStringToLong(String strval) { + return CgroupMetricsTester.convertStringToLong(strval, RETVAL_UNAVAILABLE, Long.MAX_VALUE); + } + + private static long getLongValueFromFile(Controller subSystem, String metric, String subMetric) { + String stats = getFileContents(subSystem, metric); + String[] tokens = stats.split("[\\r\\n]+"); + for (int i = 0; i < tokens.length; i++) { + if (tokens[i].startsWith(subMetric)) { + String strval = tokens[i].split("\\s+")[1]; + return convertStringToLong(strval); + } + } + return RETVAL_UNAVAILABLE; + } + + private static double getDoubleValueFromFile(Controller subSystem, String fileName) { + String data = getFileContents(subSystem, fileName); + return data == null || data.isEmpty() ? RETVAL_UNAVAILABLE : Double.parseDouble(data); + } + + private static void fail(Controller system, String metric, long oldVal, long testVal) { + CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); + } + + private static void fail(Controller system, String metric, String oldVal, String testVal) { + CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); + } + + private static void fail(Controller system, String metric, double oldVal, double testVal) { + CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); + } + + private static void fail(Controller system, String metric, boolean oldVal, boolean testVal) { + CgroupMetricsTester.fail(system.value, metric, oldVal, testVal); + } + + private static void warn(Controller system, String metric, long oldVal, long testVal) { + CgroupMetricsTester.warn(system.value, metric, oldVal, testVal); + } + + private Long[] boxedArrayOrNull(long[] primitiveArray) { + if (primitiveArray == null) { + return null; + } + return LongStream.of(primitiveArray).boxed().toArray(Long[]::new); + } + + public void testMemorySubsystem() { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + + // User Memory + long oldVal = metrics.getMemoryFailCount(); + long newVal = getLongValueFromFile(Controller.MEMORY, "memory.failcnt"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.failcnt", oldVal, newVal); + } + + oldVal = metrics.getMemoryLimit(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.limit_in_bytes"); + newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.limit_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getMemoryMaxUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.max_usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.max_usage_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getMemoryUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.usage_in_bytes", oldVal, newVal); + } + + // Kernel memory + oldVal = metrics.getKernelMemoryFailCount(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.failcnt"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.failcnt", oldVal, newVal); + } + + oldVal = metrics.getKernelMemoryLimit(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.limit_in_bytes"); + newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.limit_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getKernelMemoryMaxUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.max_usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.max_usage_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getKernelMemoryUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.usage_in_bytes", oldVal, newVal); + } + + //TCP Memory + oldVal = metrics.getTcpMemoryFailCount(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.failcnt"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.tcp.failcnt", oldVal, newVal); + } + + oldVal = metrics.getTcpMemoryLimit(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.limit_in_bytes"); + newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED: newVal; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.tcp.limit_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getTcpMemoryMaxUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.max_usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.tcp.max_usage_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getTcpMemoryUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.kmem.tcp.usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.kmem.tcp.usage_in_bytes", oldVal, newVal); + } + + // Memory and Swap + // Skip swap tests if no swap is configured. + if (metrics.getMemoryAndSwapLimit() > metrics.getMemoryLimit()) { + oldVal = metrics.getMemoryAndSwapFailCount(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.failcnt"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.memsw.failcnt", oldVal, newVal); + } + + oldVal = metrics.getMemoryAndSwapLimit(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.limit_in_bytes"); + newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.memsw.limit_in_bytes", oldVal, newVal); + } + + oldVal = metrics.getMemoryAndSwapMaxUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.max_usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.memsw.max_usage_in_bytes", oldVal, newVal); + } + + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.memsw.usage_in_bytes", oldVal, newVal); + oldVal = metrics.getMemoryAndSwapUsage(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.memsw.usage_in_bytes"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.memsw.usage_in_bytes", oldVal, newVal); + } + } + } + + oldVal = metrics.getMemorySoftLimit(); + newVal = getLongValueFromFile(Controller.MEMORY, "memory.soft_limit_in_bytes"); + newVal = newVal > unlimited_minimum ? CgroupSubsystem.LONG_RETVAL_UNLIMITED : newVal; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.MEMORY, "memory.soft_limit_in_bytes", oldVal, newVal); + } + + boolean oomKillEnabled = metrics.isMemoryOOMKillEnabled(); + boolean newOomKillEnabled = getLongValueFromFile(Controller.MEMORY, + "memory.oom_control", "oom_kill_disable") == 0L ? true : false; + if (oomKillEnabled != newOomKillEnabled) { + throw new RuntimeException("Test failed for - " + Controller.MEMORY.value + ":" + + "memory.oom_control:oom_kill_disable" + ", expected [" + + oomKillEnabled + "], got [" + newOomKillEnabled + "]"); + } + } + + public void testCpuAccounting() { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + long oldVal = metrics.getCpuUsage(); + long newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.usage"); + + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn(Controller.CPUACCT, "cpuacct.usage", oldVal, newVal); + } + + String newValsStr = getFileContents(Controller.CPUACCT, "cpuacct.usage_percpu"); + Long[] newVals = null; + if (newValsStr != null) { + newVals = Stream.of(newValsStr + .split("\\s+")) + .map(Long::parseLong) + .toArray(Long[]::new); + } + Long[] oldVals = boxedArrayOrNull(metrics.getPerCpuUsage()); + if (oldVals != null) { + for (int i = 0; i < oldVals.length; i++) { + if (!CgroupMetricsTester.compareWithErrorMargin(oldVals[i], newVals[i])) { + warn(Controller.CPUACCT, "cpuacct.usage_percpu", oldVals[i], newVals[i]); + } + } + } else { + Asserts.assertNull(newVals, Controller.CPUACCT.value() + "cpuacct.usage_percpu not both null"); + } + + oldVal = metrics.getCpuUserUsage(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.stat", "user"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn(Controller.CPUACCT, "cpuacct.usage - user", oldVal, newVal); + } + + oldVal = metrics.getCpuSystemUsage(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpuacct.stat", "system"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn(Controller.CPUACCT, "cpuacct.usage - system", oldVal, newVal); + } + } + + public void testCpuSchedulingMetrics() { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + long oldVal = metrics.getCpuPeriod(); + long newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.cfs_period_us"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.cfs_period_us", oldVal, newVal); + } + + oldVal = metrics.getCpuQuota(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.cfs_quota_us"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.cfs_quota_us", oldVal, newVal); + } + + oldVal = metrics.getCpuShares(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.shares"); + if (newVal == 0 || newVal == 1024) newVal = -1; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.shares", oldVal, newVal); + } + + oldVal = metrics.getCpuNumPeriods(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "nr_periods"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.stat - nr_periods", oldVal, newVal); + } + + oldVal = metrics.getCpuNumThrottled(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "nr_throttled"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.stat - nr_throttled", oldVal, newVal); + } + + oldVal = metrics.getCpuThrottledTime(); + newVal = getLongValueFromFile(Controller.CPUACCT, "cpu.stat", "throttled_time"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.CPUACCT, "cpu.stat - throttled_time", oldVal, newVal); + } + } + + public void testCpuSets() { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + Integer[] oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetCpus()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + + String cpusstr = getFileContents(Controller.CPUSET, "cpuset.cpus"); + // Parse range string in the format 1,2-6,7 + Integer[] newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail(Controller.CPUSET, "cpuset.cpus", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + int [] cpuSets = metrics.getEffectiveCpuSetCpus(); + + oldVal = CgroupMetricsTester.boxedArrayOrNull(cpuSets); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getFileContents(Controller.CPUSET, "cpuset.effective_cpus"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail(Controller.CPUSET, "cpuset.effective_cpus", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetMems()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getFileContents(Controller.CPUSET, "cpuset.mems"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail(Controller.CPUSET, "cpuset.mems", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + int [] cpuSetMems = metrics.getEffectiveCpuSetMems(); + + oldVal = CgroupMetricsTester.boxedArrayOrNull(cpuSetMems); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getFileContents(Controller.CPUSET, "cpuset.effective_mems"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail(Controller.CPUSET, "cpuset.effective_mems", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + double oldValue = metrics.getCpuSetMemoryPressure(); + double newValue = getDoubleValueFromFile(Controller.CPUSET, "cpuset.memory_pressure"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldValue, newValue)) { + fail(Controller.CPUSET, "cpuset.memory_pressure", oldValue, newValue); + } + + boolean oldV = metrics.isCpuSetMemoryPressureEnabled(); + boolean newV = getLongValueFromFile(Controller.CPUSET, + "cpuset.memory_pressure_enabled") == 1 ? true : false; + if (oldV != newV) { + fail(Controller.CPUSET, "cpuset.memory_pressure_enabled", oldV, newV); + } + } + + private void testBlkIO() { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + long oldVal = metrics.getBlkIOServiceCount(); + long newVal = getLongValueFromFile(Controller.BLKIO, + "blkio.throttle.io_service_bytes", "Total"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.BLKIO, "blkio.throttle.io_service_bytes - Total", + oldVal, newVal); + } + + oldVal = metrics.getBlkIOServiced(); + newVal = getLongValueFromFile(Controller.BLKIO, "blkio.throttle.io_serviced", "Total"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail(Controller.BLKIO, "blkio.throttle.io_serviced - Total", oldVal, newVal); + } + } + + public void testCpuConsumption() throws IOException, InterruptedException { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + // make system call + long newSysVal = metrics.getCpuSystemUsage(); + long newUserVal = metrics.getCpuUserUsage(); + long newUsage = metrics.getCpuUsage(); + long[] newPerCpu = metrics.getPerCpuUsage(); + + // system/user CPU usage counters may be slowly increasing. + // allow for equal values for a pass + if (newSysVal < startSysVal) { + fail(Controller.CPU, "getCpuSystemUsage", newSysVal, startSysVal); + } + + // system/user CPU usage counters may be slowly increasing. + // allow for equal values for a pass + if (newUserVal < startUserVal) { + fail(Controller.CPU, "getCpuUserUsage", newUserVal, startUserVal); + } + + if (newUsage <= startUsage) { + fail(Controller.CPU, "getCpuUsage", newUsage, startUsage); + } + + if (startPerCpu != null) { + boolean success = false; + for (int i = 0; i < startPerCpu.length; i++) { + if (newPerCpu[i] > startPerCpu[i]) { + success = true; + break; + } + } + if (!success) { + fail(Controller.CPU, "getPerCpuUsage", Arrays.toString(newPerCpu), + Arrays.toString(startPerCpu)); + } + } else { + Asserts.assertNull(newPerCpu, Controller.CPU.value() + " getPerCpuUsage not both null"); + } + + } + + public void testMemoryUsage() throws Exception { + CgroupV1Metrics metrics = (CgroupV1Metrics)Metrics.systemMetrics(); + long memoryMaxUsage = metrics.getMemoryMaxUsage(); + long memoryUsage = metrics.getMemoryUsage(); + long newMemoryMaxUsage = 0, newMemoryUsage = 0; + + // allocate memory in a loop and check more than once for new values + // otherwise we might see seldom the effect of decreasing new memory values + // e.g. because the system could free up memory + byte[][] bytes = new byte[32][]; + for (int i = 0; i < 32; i++) { + bytes[i] = new byte[8*1024*1024]; + newMemoryUsage = metrics.getMemoryUsage(); + if (newMemoryUsage > memoryUsage) { + break; + } + } + newMemoryMaxUsage = metrics.getMemoryMaxUsage(); + + if (newMemoryMaxUsage < memoryMaxUsage) { + fail(Controller.MEMORY, "getMemoryMaxUsage", memoryMaxUsage, + newMemoryMaxUsage); + } + + if (newMemoryUsage < memoryUsage) { + fail(Controller.MEMORY, "getMemoryUsage", memoryUsage, newMemoryUsage); + } + } + + @Override + public void testMisc() { + testBlkIO(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/cgroup/MetricsTesterCgroupV2.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,484 @@ +/* + * Copyright (c) 2020, Red Hat Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.cgroup; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import jdk.internal.platform.Metrics; + +public class MetricsTesterCgroupV2 implements CgroupMetricsTester { + + private static final long UNLIMITED = -1; + private static final long NOT_AVAILABLE = -1; + private static final UnifiedController UNIFIED = new UnifiedController(); + private static final String MAX = "max"; + private static final int PER_CPU_SHARES = 1024; + + private final long startSysVal; + private final long startUserVal; + private final long startUsage; + + static class UnifiedController { + + private static final String NAME = "unified"; + private final String path; + + UnifiedController() { + path = constructPath(); + } + + String getPath() { + return path; + } + + private static String constructPath() { + String mountPath; + String cgroupPath; + try { + List fifthTokens = Files.lines(Paths.get("/proc/self/mountinfo")) + .filter( l -> l.contains("- cgroup2")) + .map(UnifiedController::splitAndMountPath) + .collect(Collectors.toList()); + if (fifthTokens.size() != 1) { + throw new AssertionError("Expected only one cgroup2 line"); + } + mountPath = fifthTokens.get(0); + + List cgroupPaths = Files.lines(Paths.get("/proc/self/cgroup")) + .filter( l -> l.startsWith("0:")) + .map(UnifiedController::splitAndCgroupPath) + .collect(Collectors.toList()); + if (cgroupPaths.size() != 1) { + throw new AssertionError("Expected only one unified controller line"); + } + cgroupPath = cgroupPaths.get(0); + return Paths.get(mountPath, cgroupPath).toString(); + } catch (IOException e) { + return null; + } + } + + public static String splitAndMountPath(String input) { + String[] tokens = input.split("\\s+"); + return tokens[4]; // fifth entry is the mount path + } + + public static String splitAndCgroupPath(String input) { + String[] tokens = input.split(":"); + return tokens[2]; + } + } + + private long getLongLimitValueFromFile(String file) { + String strVal = getStringVal(file); + if (MAX.equals(strVal)) { + return UNLIMITED; + } + return convertStringToLong(strVal); + } + + public MetricsTesterCgroupV2() { + Metrics metrics = Metrics.systemMetrics(); + // Initialize CPU usage metrics before we do any testing. + startSysVal = metrics.getCpuSystemUsage(); + startUserVal = metrics.getCpuUserUsage(); + startUsage = metrics.getCpuUsage(); + } + + private long getLongValueFromFile(String file) { + return convertStringToLong(getStringVal(file)); + } + + private long getLongValueEntryFromFile(String file, String metric) { + Path filePath = Paths.get(UNIFIED.getPath(), file); + try { + String strVal = Files.lines(filePath).filter(l -> l.startsWith(metric)).collect(Collectors.joining()); + if (strVal.isEmpty()) { + // sometimes the match for the metric does not exist, e.g. cpu.stat's nr_periods iff the controller + // is not enabled + return UNLIMITED; + } + String[] keyValues = strVal.split("\\s+"); + String value = keyValues[1]; + return convertStringToLong(value); + } catch (IOException e) { + return NOT_AVAILABLE; + } + } + + private String getStringVal(String file) { + Path filePath = Paths.get(UNIFIED.getPath(), file); + try { + return Files.lines(filePath).collect(Collectors.joining()); + } catch (IOException e) { + return null; + } + } + + private void fail(String metric, long oldVal, long newVal) { + CgroupMetricsTester.fail(UnifiedController.NAME, metric, oldVal, newVal); + } + + private void fail(String metric, String oldVal, String newVal) { + CgroupMetricsTester.fail(UnifiedController.NAME, metric, oldVal, newVal); + } + + private void warn(String metric, long oldVal, long newVal) { + CgroupMetricsTester.warn(UnifiedController.NAME, metric, oldVal, newVal); + } + + private long getCpuShares(String file) { + long rawVal = getLongValueFromFile(file); + if (rawVal == NOT_AVAILABLE || rawVal == 100) { + return UNLIMITED; + } + int shares = (int)rawVal; + // CPU shares (OCI) value needs to get translated into + // a proper Cgroups v2 value. See: + // https://github.com/containers/crun/blob/master/crun.1.md#cpu-controller + // + // Use the inverse of (x == OCI value, y == cgroupsv2 value): + // ((262142 * y - 1)/9999) + 2 = x + // + int x = 262142 * shares - 1; + double frac = x/9999.0; + x = ((int)frac) + 2; + if ( x <= PER_CPU_SHARES ) { + return PER_CPU_SHARES; // mimic cgroups v1 + } + int f = x/PER_CPU_SHARES; + int lower_multiple = f * PER_CPU_SHARES; + int upper_multiple = (f + 1) * PER_CPU_SHARES; + int distance_lower = Math.max(lower_multiple, x) - Math.min(lower_multiple, x); + int distance_upper = Math.max(upper_multiple, x) - Math.min(upper_multiple, x); + x = distance_lower <= distance_upper ? lower_multiple : upper_multiple; + return x; + } + + private long getCpuMaxValueFromFile(String file) { + return getCpuValueFromFile(file, 0 /* $MAX index */); + } + + private long getCpuPeriodValueFromFile(String file) { + return getCpuValueFromFile(file, 1 /* $PERIOD index */); + } + + private long getCpuValueFromFile(String file, int index) { + String maxPeriod = getStringVal(file); + if (maxPeriod == null) { + return UNLIMITED; + } + String[] tokens = maxPeriod.split("\\s+"); + String val = tokens[index]; + if (MAX.equals(val)) { + return UNLIMITED; + } + return convertStringToLong(val); + } + + private long convertStringToLong(String val) { + return CgroupMetricsTester.convertStringToLong(val, NOT_AVAILABLE, UNLIMITED); + } + + private long nanosOrUnlimited(long micros) { + if (micros < 0) { + return UNLIMITED; + } + return TimeUnit.MICROSECONDS.toNanos(micros); + } + + @Override + public void testMemorySubsystem() { + Metrics metrics = Metrics.systemMetrics(); + + // User Memory + long oldVal = metrics.getMemoryFailCount(); + long newVal = getLongValueEntryFromFile("memory.events", "max"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.events[max]", oldVal, newVal); + } + + oldVal = metrics.getMemoryLimit(); + newVal = getLongLimitValueFromFile("memory.max"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.max", oldVal, newVal); + } + + oldVal = metrics.getMemoryUsage(); + newVal = getLongValueFromFile("memory.current"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.current", oldVal, newVal); + } + + oldVal = metrics.getTcpMemoryUsage(); + newVal = getLongValueEntryFromFile("memory.stat", "sock"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.stat[sock]", oldVal, newVal); + } + + long memAndSwapLimit = metrics.getMemoryAndSwapLimit(); + long memLimit = metrics.getMemoryLimit(); + // Only test swap memory limits if we can. On systems with swapaccount=0 + // we cannot, as swap limits are disabled. + if (memAndSwapLimit <= memLimit) { + System.out.println("No swap memory limits, test case(s) skipped"); + } else { + oldVal = memAndSwapLimit; + long valSwap = getLongLimitValueFromFile("memory.swap.max"); + long valMemory = getLongLimitValueFromFile("memory.max"); + if (valSwap == UNLIMITED) { + newVal = valSwap; + } else { + assert valMemory >= 0; + newVal = valSwap + valMemory; + } + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.swap.max", oldVal, newVal); + } + + oldVal = metrics.getMemoryAndSwapUsage(); + long swapUsage = getLongValueFromFile("memory.swap.current"); + long memUsage = getLongValueFromFile("memory.current"); + newVal = swapUsage + memUsage; + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.swap.current", oldVal, newVal); + } + } + + oldVal = metrics.getMemorySoftLimit(); + newVal = getLongLimitValueFromFile("memory.low"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("memory.low", oldVal, newVal); + } + + } + + @Override + public void testCpuAccounting() { + Metrics metrics = Metrics.systemMetrics(); + long oldVal = metrics.getCpuUsage(); + long newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "usage_usec")); + + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn("cpu.stat[usage_usec]", oldVal, newVal); + } + + oldVal = metrics.getCpuUserUsage(); + newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "user_usec")); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn("cpu.stat[user_usec]", oldVal, newVal); + } + + oldVal = metrics.getCpuSystemUsage(); + newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "system_usec")); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + warn("cpu.stat[system_usec]", oldVal, newVal); + } + } + + @Override + public void testCpuSchedulingMetrics() { + Metrics metrics = Metrics.systemMetrics(); + long oldVal = metrics.getCpuPeriod(); + long newVal = getCpuPeriodValueFromFile("cpu.max"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.max[$PERIOD]", oldVal, newVal); + } + + oldVal = metrics.getCpuQuota(); + newVal = getCpuMaxValueFromFile("cpu.max"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.max[$MAX]", oldVal, newVal); + } + + oldVal = metrics.getCpuShares(); + newVal = getCpuShares("cpu.weight"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.weight", oldVal, newVal); + } + + oldVal = metrics.getCpuNumPeriods(); + newVal = getLongValueEntryFromFile("cpu.stat", "nr_periods"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.stat[nr_periods]", oldVal, newVal); + } + + oldVal = metrics.getCpuNumThrottled(); + newVal = getLongValueEntryFromFile("cpu.stat", "nr_throttled"); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.stat[nr_throttled]", oldVal, newVal); + } + + oldVal = metrics.getCpuThrottledTime(); + newVal = nanosOrUnlimited(getLongValueEntryFromFile("cpu.stat", "throttled_usec")); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("cpu.stat[throttled_usec]", oldVal, newVal); + } + } + + @Override + public void testCpuSets() { + Metrics metrics = Metrics.systemMetrics(); + Integer[] oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetCpus()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + + String cpusstr = getStringVal("cpuset.cpus"); + // Parse range string in the format 1,2-6,7 + Integer[] newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail("cpuset.cpus", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getEffectiveCpuSetCpus()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getStringVal("cpuset.cpus.effective"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail("cpuset.cpus.effective", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getCpuSetMems()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getStringVal("cpuset.mems"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail("cpuset.mems", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + + oldVal = CgroupMetricsTester.boxedArrayOrNull(metrics.getEffectiveCpuSetMems()); + oldVal = CgroupMetricsTester.sortAllowNull(oldVal); + cpusstr = getStringVal("cpuset.mems.effective"); + newVal = CgroupMetricsTester.convertCpuSetsToArray(cpusstr); + newVal = CgroupMetricsTester.sortAllowNull(newVal); + if (!Arrays.equals(oldVal, newVal)) { + fail("cpuset.mems.effective", Arrays.toString(oldVal), + Arrays.toString(newVal)); + } + } + + @Override + public void testCpuConsumption() { + Metrics metrics = Metrics.systemMetrics(); + // make system call + long newSysVal = metrics.getCpuSystemUsage(); + long newUserVal = metrics.getCpuUserUsage(); + long newUsage = metrics.getCpuUsage(); + + // system/user CPU usage counters may be slowly increasing. + // allow for equal values for a pass + if (newSysVal < startSysVal) { + fail("getCpuSystemUsage", newSysVal, startSysVal); + } + + // system/user CPU usage counters may be slowly increasing. + // allow for equal values for a pass + if (newUserVal < startUserVal) { + fail("getCpuUserUsage", newUserVal, startUserVal); + } + + if (newUsage <= startUsage) { + fail("getCpuUsage", newUsage, startUsage); + } + } + + @Override + public void testMemoryUsage() { + Metrics metrics = Metrics.systemMetrics(); + long memoryUsage = metrics.getMemoryUsage(); + long newMemoryUsage = 0; + + // allocate memory in a loop and check more than once for new values + // otherwise we might occasionally see the effect of decreasing new memory + // values. For example because the system could free up memory + byte[][] bytes = new byte[32][]; + for (int i = 0; i < 32; i++) { + bytes[i] = new byte[8*1024*1024]; + newMemoryUsage = metrics.getMemoryUsage(); + if (newMemoryUsage > memoryUsage) { + break; + } + } + + if (newMemoryUsage < memoryUsage) { + fail("getMemoryUsage", memoryUsage, newMemoryUsage); + } + } + + @Override + public void testMisc() { + testIOStat(); + } + + private void testIOStat() { + Metrics metrics = Metrics.systemMetrics(); + long oldVal = metrics.getBlkIOServiceCount(); + long newVal = getIoStatAccumulate(new String[] { "rios", "wios" }); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("io.stat->rios/wios: ", oldVal, newVal); + } + + oldVal = metrics.getBlkIOServiced(); + newVal = getIoStatAccumulate(new String[] { "rbytes", "wbytes" }); + if (!CgroupMetricsTester.compareWithErrorMargin(oldVal, newVal)) { + fail("io.stat->rbytes/wbytes: ", oldVal, newVal); + } + } + + private long getIoStatAccumulate(String[] matchNames) { + try { + return Files.lines(Paths.get(UNIFIED.getPath(), "io.stat")) + .map(line -> { + long accumulator = 0; + String[] tokens = line.split("\\s+"); + for (String t: tokens) { + String[] keyVal = t.split("="); + if (keyVal.length != 2) { + continue; + } + for (String match: matchNames) { + if (match.equals(keyVal[0])) { + accumulator += Long.parseLong(keyVal[1]); + } + } + } + return accumulator; + }).collect(Collectors.summingLong(e -> e)); + } catch (IOException e) { + return NOT_AVAILABLE; + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/Common.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/Common.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/Common.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/Common.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.docker; + +/* + * Methods and definitions common to docker tests container in this directory + */ + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import jdk.test.lib.containers.docker.DockerRunOptions; +import jdk.test.lib.containers.docker.DockerTestUtils; +import jdk.test.lib.Utils; +import jdk.test.lib.process.OutputAnalyzer; + + +public class Common { + public static final String imageNameAndTag = "jdk-internal:test"; + + public static String imageName(String suffix) { + return imageNameAndTag + "-" + suffix; + } + + + public static void prepareWhiteBox() throws Exception { + Files.copy(Paths.get(new File("whitebox.jar").getAbsolutePath()), + Paths.get(Utils.TEST_CLASSES, "whitebox.jar")); + } + + + // create simple commonly used options + public static DockerRunOptions newOpts(String imageNameAndTag) { + return new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version") + .addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo"); + } + + + // create commonly used options with class to be launched inside container + public static DockerRunOptions newOpts(String imageNameAndTag, String testClass) { + DockerRunOptions opts = + new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", testClass); + opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/"); + opts.addJavaOpts("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintContainerInfo"); + opts.addJavaOpts("-cp", "/test-classes/"); + return opts; + } + + + public static DockerRunOptions addWhiteBoxOpts(DockerRunOptions opts) { + opts.addJavaOpts("-Xbootclasspath/a:/test-classes/whitebox.jar", + "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI"); + return opts; + } + + + // most common type of run and checks + public static OutputAnalyzer run(DockerRunOptions opts) throws Exception { + return DockerTestUtils.dockerRunJava(opts) + .shouldHaveExitValue(0).shouldContain("Initializing Container Support"); + } + + + // log beginning of a test case + public static void logNewTestCase(String msg) { + System.out.println("========== NEW TEST CASE: " + msg); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerRunOptions.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.docker; + +import java.util.ArrayList; +import java.util.Collections; + + +// This class represents options for running java inside docker containers +// in test environment. +public class DockerRunOptions { + public String imageNameAndTag; + public ArrayList dockerOpts = new ArrayList(); + public String command; // normally a full path to java + public ArrayList javaOpts = new ArrayList(); + public String classToRun; // class or "-version" + public ArrayList classParams = new ArrayList(); + + public boolean tty = true; + public boolean removeContainerAfterUse = true; + public boolean appendTestJavaOptions = true; + public boolean retainChildStdout = false; + + /** + * Convenience constructor for most common use cases in testing. + * @param imageNameAndTag a string representing name and tag for the + * docker image to run, as "name:tag" + * @param javaCmd a java command to run (e.g. /jdk/bin/java) + * @param classToRun a class to run, or "-version" + * @param javaOpts java options to use + * + * @return Default docker run options + */ + public DockerRunOptions(String imageNameAndTag, String javaCmd, + String classToRun, String... javaOpts) { + this.imageNameAndTag = imageNameAndTag; + this.command = javaCmd; + this.classToRun = classToRun; + this.addJavaOpts(javaOpts); + } + + public DockerRunOptions addDockerOpts(String... opts) { + Collections.addAll(dockerOpts, opts); + return this; + } + + public DockerRunOptions addJavaOpts(String... opts) { + Collections.addAll(javaOpts, opts); + return this; + } + + public DockerRunOptions addClassOptions(String... opts) { + Collections.addAll(classParams,opts); + return this; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.docker; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.FileVisitResult; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import jdk.test.lib.Container; +import jdk.test.lib.Utils; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + + +public class DockerTestUtils { + private static final String FS = File.separator; + private static boolean isDockerEngineAvailable = false; + private static boolean wasDockerEngineChecked = false; + + // Set this property to true to retain image after test. By default + // images are removed after test execution completes. + // Retaining the image can be useful for diagnostics and image inspection. + // E.g.: start image interactively: docker run -it . + public static final boolean RETAIN_IMAGE_AFTER_TEST = + Boolean.getBoolean("jdk.test.docker.retain.image"); + + // Path to a JDK under test. + // This may be useful when developing tests on non-Linux platforms. + public static final String JDK_UNDER_TEST = + System.getProperty("jdk.test.docker.jdk", Utils.TEST_JDK); + + + /** + * Optimized check of whether the docker engine is available in a given + * environment. Checks only once, then remembers the result in a singleton. + * + * @return true if docker engine is available + * @throws Exception + */ + public static boolean isDockerEngineAvailable() throws Exception { + if (wasDockerEngineChecked) + return isDockerEngineAvailable; + + isDockerEngineAvailable = isDockerEngineAvailableCheck(); + wasDockerEngineChecked = true; + return isDockerEngineAvailable; + } + + + /** + * Convenience method, will check if docker engine is available and usable; + * will print the appropriate message when not available. + * + * @return true if docker engine is available + * @throws Exception + */ + public static boolean canTestDocker() throws Exception { + if (isDockerEngineAvailable()) { + return true; + } else { + System.out.println("Docker engine is not available on this system"); + System.out.println("This test is SKIPPED"); + return false; + } + } + + + /** + * Simple check - is docker engine available, accessible and usable. + * Run basic docker command: 'docker ps' - list docker instances. + * If docker engine is available and accesible then true is returned + * and we can proceed with testing docker. + * + * @return true if docker engine is available and usable + * @throws Exception + */ + private static boolean isDockerEngineAvailableCheck() throws Exception { + try { + execute(Container.ENGINE_COMMAND, "ps") + .shouldHaveExitValue(0) + .shouldContain("CONTAINER") + .shouldContain("IMAGE"); + } catch (Exception e) { + return false; + } + return true; + } + + + /** + * Build a docker image that contains JDK under test. + * The jdk will be placed under the "/jdk/" folder inside the docker file system. + * + * @param imageName name of the image to be created, including version tag + * @param dockerfile name of the dockerfile residing in the test source; + * we check for a platform specific dockerfile as well + * and use this one in case it exists + * @param buildDirName name of the docker build/staging directory, which will + * be created in the jtreg's scratch folder + * @throws Exception + */ + public static void + buildJdkDockerImage(String imageName, String dockerfile, String buildDirName) + throws Exception { + + Path buildDir = Paths.get(".", buildDirName); + if (Files.exists(buildDir)) { + throw new RuntimeException("The docker build directory already exists: " + buildDir); + } + + Path jdkSrcDir = Paths.get(JDK_UNDER_TEST); + Path jdkDstDir = buildDir.resolve("jdk"); + + Files.createDirectories(jdkDstDir); + + // Copy JDK-under-test tree to the docker build directory. + // This step is required for building a docker image. + Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir)); + buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir); + } + + + /** + * Build a docker image based on given docker file and docker build directory. + * + * @param imageName name of the image to be created, including version tag + * @param dockerfile path to the Dockerfile to be used for building the docker + * image. The specified dockerfile will be copied to the docker build + * directory as 'Dockerfile' + * @param buildDir build directory; it should already contain all the content + * needed to build the docker image. + * @throws Exception + */ + public static void + buildDockerImage(String imageName, Path dockerfile, Path buildDir) throws Exception { + + generateDockerFile(buildDir.resolve("Dockerfile"), + DockerfileConfig.getBaseImageName(), + DockerfileConfig.getBaseImageVersion()); + + // Build the docker + execute(Container.ENGINE_COMMAND, "build", "--no-cache", "--tag", imageName, buildDir.toString()) + .shouldHaveExitValue(0); + } + + + /** + * Run Java inside the docker image with specified parameters and options. + * + * @param DockerRunOptions optins for running docker + * + * @return output of the run command + * @throws Exception + */ + public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception { + ArrayList cmd = new ArrayList<>(); + + cmd.add(Container.ENGINE_COMMAND); + cmd.add("run"); + if (opts.tty) + cmd.add("--tty=true"); + if (opts.removeContainerAfterUse) + cmd.add("--rm"); + + cmd.addAll(opts.dockerOpts); + cmd.add(opts.imageNameAndTag); + cmd.add(opts.command); + + cmd.addAll(opts.javaOpts); + if (opts.appendTestJavaOptions) { + Collections.addAll(cmd, Utils.getTestJavaOpts()); + } + + cmd.add(opts.classToRun); + cmd.addAll(opts.classParams); + + return execute(cmd); + } + + + /** + * Remove docker image + * + * @param DockerRunOptions optins for running docker + * @throws Exception + */ + public static void removeDockerImage(String imageNameAndTag) throws Exception { + execute(Container.ENGINE_COMMAND, "rmi", "--force", imageNameAndTag); + } + + + + /** + * Convenience method - express command as sequence of strings + * + * @param command to execute + * @return The output from the process + * @throws Exception + */ + public static OutputAnalyzer execute(List command) throws Exception { + return execute(command.toArray(new String[command.size()])); + } + + + /** + * Execute a specified command in a process, report diagnostic info. + * + * @param command to be executed + * @return The output from the process + * @throws Exception + */ + public static OutputAnalyzer execute(String... command) throws Exception { + + ProcessBuilder pb = new ProcessBuilder(command); + System.out.println("[COMMAND]\n" + Utils.getCommandLine(pb)); + + long started = System.currentTimeMillis(); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + + System.out.println("[ELAPSED: " + (System.currentTimeMillis() - started) + " ms]"); + System.out.println("[STDERR]\n" + output.getStderr()); + System.out.println("[STDOUT]\n" + output.getStdout()); + + return output; + } + + + private static void generateDockerFile(Path dockerfile, String baseImage, + String baseImageVersion) throws Exception { + String template = + "FROM %s:%s\n" + + "COPY /jdk /jdk\n" + + "ENV JAVA_HOME=/jdk\n" + + "CMD [\"/bin/bash\"]\n"; + String dockerFileStr = String.format(template, baseImage, baseImageVersion); + Files.write(dockerfile, dockerFileStr.getBytes(StandardCharsets.UTF_8)); + } + + + private static class CopyFileVisitor extends SimpleFileVisitor { + private final Path src; + private final Path dst; + + public CopyFileVisitor(Path src, Path dst) { + this.src = src; + this.dst = dst; + } + + + @Override + public FileVisitResult preVisitDirectory(Path file, + BasicFileAttributes attrs) throws IOException { + Path dstDir = dst.resolve(src.relativize(file)); + if (!dstDir.toFile().exists()) { + Files.createDirectories(dstDir); + } + return FileVisitResult.CONTINUE; + } + + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { + if (!file.toFile().isFile()) { + return FileVisitResult.CONTINUE; + } + Path dstFile = dst.resolve(src.relativize(file)); + Files.copy(file, dstFile, StandardCopyOption.COPY_ATTRIBUTES); + return FileVisitResult.CONTINUE; + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/containers/docker/DockerfileConfig.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.containers.docker; + +import jdk.test.lib.Platform; + +// Use the following properties to specify docker base image at test execution time: +// Image name: jdk.test.docker.image.name +// Image version: jdk.test.docker.image.version +// Usage: +// jtreg -Djdk.test.docker.image.name= -Djdk.test.docker.image.version= test/hotspot/jtreg/runtime/containers/docker/ +// E.g.: +// jtreg -Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest test/hotspot/jtreg/runtime/containers/docker/ +// Using make: +// make test TEST="test/hotspot/jtreg/runtime/containers/docker" JTREG="JAVA_OPTIONS=-Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest" +// Note: base image version should not be an empty string. Use "latest" to get the latest version. + +public class DockerfileConfig { + static String getBaseImageName() { + String name = System.getProperty("jdk.test.docker.image.name"); + if (name != null) { + System.out.println("DockerfileConfig: using custom image name: " + name); + return name; + } + + switch (Platform.getOsArch()) { + case "aarch64": + return "arm64v8/ubuntu"; + case "ppc64le": + return "ppc64le/ubuntu"; + case "s390x": + return "s390x/ubuntu"; + default: + return "oraclelinux"; + } + } + + static String getBaseImageVersion() { + String version = System.getProperty("jdk.test.docker.image.version"); + if (version != null) { + System.out.println("DockerfileConfig: using custom image version: " + version); + return version; + } + + switch (Platform.getOsArch()) { + case "aarch64": + case "ppc64le": + case "s390x": + return "latest"; + default: + return "7.6"; + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import jdk.test.lib.process.OutputAnalyzer; + +/** + * Abstract base class for Diagnostic Command executors + */ +public abstract class CommandExecutor { + + /** + * Execute a diagnostic command + * + * @param cmd The diagnostic command to execute + * @return an {@link jdk.testlibrary.OutputAnalyzer} encapsulating the output of the command + * @throws CommandExecutorException if there is an exception on the "calling side" while trying to execute the + * Diagnostic Command. Exceptions thrown on the remote side are available as textual representations in + * stderr, regardless of the specific executor used. + */ + public final OutputAnalyzer execute(String cmd) throws CommandExecutorException { + return execute(cmd, false); + } + + /** + * Execute a diagnostic command + * + * @param cmd The diagnostic command to execute + * @param silent Do not print the command output + * @return an {@link jdk.testlibrary.OutputAnalyzer} encapsulating the output of the command + * @throws CommandExecutorException if there is an exception on the "calling side" while trying to execute the + * Diagnostic Command. Exceptions thrown on the remote side are available as textual representations in + * stderr, regardless of the specific executor used. + */ + public final OutputAnalyzer execute(String cmd, boolean silent) throws CommandExecutorException { + if (!silent) { + System.out.printf("Running DCMD '%s' through '%s'%n", cmd, this.getClass().getSimpleName()); + } + + OutputAnalyzer oa = executeImpl(cmd); + + if (!silent) { + System.out.println("---------------- stdout ----------------"); + System.out.println(oa.getStdout()); + System.out.println("---------------- stderr ----------------"); + System.out.println(oa.getStderr()); + System.out.println("----------------------------------------"); + System.out.println(); + } + return oa; + } + + protected abstract OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/CommandExecutorException.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +/** + * CommandExecutorException encapsulates exceptions thrown (on the "calling side") from the execution of Diagnostic + * Commands + */ +public class CommandExecutorException extends RuntimeException { + private static final long serialVersionUID = -7039597746579144280L; + + public CommandExecutorException(String message, Throwable e) { + super(message, e); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/FileJcmdExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.List; + +/** + * Executes Diagnostic Commands on the target VM (specified by pid) using the jcmd tool and its ability to read + * Diagnostic Commands from a file. + */ +public class FileJcmdExecutor extends PidJcmdExecutor { + + /** + * Instantiates a new FileJcmdExecutor targeting the current VM + */ + public FileJcmdExecutor() { + super(); + } + + /** + * Instantiates a new FileJcmdExecutor targeting the VM indicated by the given pid + * + * @param target Pid of the target VM + */ + public FileJcmdExecutor(String target) { + super(target); + } + + protected List createCommandLine(String cmd) throws CommandExecutorException { + File cmdFile = createTempFile(); + writeCommandToTemporaryFile(cmd, cmdFile); + + return Arrays.asList(jcmdBinary, Long.toString(pid), + "-f", cmdFile.getAbsolutePath()); + } + + private void writeCommandToTemporaryFile(String cmd, File cmdFile) { + try (PrintWriter pw = new PrintWriter(cmdFile)) { + pw.println(cmd); + } catch (IOException e) { + String message = "Could not write to file: " + cmdFile.getAbsolutePath(); + throw new CommandExecutorException(message, e); + } + } + + private File createTempFile() { + try { + File cmdFile = File.createTempFile("input", "jcmd"); + cmdFile.deleteOnExit(); + return cmdFile; + } catch (IOException e) { + throw new CommandExecutorException("Could not create temporary file", e); + } + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JMXExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import jdk.test.lib.process.OutputAnalyzer; + +import javax.management.*; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.lang.management.ManagementFactory; + +import java.util.HashMap; + +/** + * Executes Diagnostic Commands on the target VM (specified by a host/port combination or a full JMX Service URL) using + * the JMX interface. If the target is not the current VM, the JMX Remote interface must be enabled beforehand. + */ +public class JMXExecutor extends CommandExecutor { + + private final MBeanServerConnection mbs; + + /** + * Instantiates a new JMXExecutor targeting the current VM + */ + public JMXExecutor() { + super(); + mbs = ManagementFactory.getPlatformMBeanServer(); + } + + /** + * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX + * Service URL + * + * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM + */ + public JMXExecutor(String target) { + String urlStr; + + if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) { + /* Matches "hostname:port" */ + urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target); + } else if (target.startsWith("service:")) { + urlStr = target; + } else { + throw new IllegalArgumentException("Could not recognize target string: " + target); + } + + try { + JMXServiceURL url = new JMXServiceURL(urlStr); + JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>()); + mbs = c.getMBeanServerConnection(); + } catch (IOException e) { + throw new CommandExecutorException("Could not initiate connection to target: " + target, e); + } + } + + protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException { + String stdout = ""; + String stderr = ""; + + String[] cmdParts = cmd.split(" ", 2); + String operation = commandToMethodName(cmdParts[0]); + Object[] dcmdArgs = produceArguments(cmdParts); + String[] signature = {String[].class.getName()}; + + ObjectName beanName = getMBeanName(); + + try { + stdout = (String) mbs.invoke(beanName, operation, dcmdArgs, signature); + } + + /* Failures on the "local" side, the one invoking the command. */ + catch (ReflectionException e) { + Throwable cause = e.getCause(); + if (cause instanceof NoSuchMethodException) { + /* We want JMXExecutor to match the behavior of the other CommandExecutors */ + String message = "Unknown diagnostic command: " + operation; + stderr = exceptionTraceAsString(new IllegalArgumentException(message, e)); + } else { + rethrowExecutorException(operation, dcmdArgs, e); + } + } + + /* Failures on the "local" side, the one invoking the command. */ + catch (InstanceNotFoundException | IOException e) { + rethrowExecutorException(operation, dcmdArgs, e); + } + + /* Failures on the remote side, the one executing the invoked command. */ + catch (MBeanException e) { + stdout = exceptionTraceAsString(e); + } + + return new OutputAnalyzer(stdout, stderr); + } + + private void rethrowExecutorException(String operation, Object[] dcmdArgs, + Exception e) throws CommandExecutorException { + String message = String.format("Could not invoke: %s %s", operation, + String.join(" ", (String[]) dcmdArgs[0])); + throw new CommandExecutorException(message, e); + } + + private ObjectName getMBeanName() throws CommandExecutorException { + String MBeanName = "com.sun.management:type=DiagnosticCommand"; + + try { + return new ObjectName(MBeanName); + } catch (MalformedObjectNameException e) { + String message = "MBean not found: " + MBeanName; + throw new CommandExecutorException(message, e); + } + } + + private Object[] produceArguments(String[] cmdParts) { + Object[] dcmdArgs = {new String[0]}; /* Default: No arguments */ + + if (cmdParts.length == 2) { + dcmdArgs[0] = cmdParts[1].split(" "); + } + return dcmdArgs; + } + + /** + * Convert from diagnostic command to MBean method name + * + * Examples: + * help --> help + * VM.version --> vmVersion + * VM.command_line --> vmCommandLine + */ + private static String commandToMethodName(String cmd) { + String operation = ""; + boolean up = false; /* First letter is to be lower case */ + + /* + * If a '.' or '_' is encountered it is not copied, + * instead the next character will be converted to upper case + */ + for (char c : cmd.toCharArray()) { + if (('.' == c) || ('_' == c)) { + up = true; + } else if (up) { + operation = operation.concat(Character.toString(c).toUpperCase()); + up = false; + } else { + operation = operation.concat(Character.toString(c).toLowerCase()); + } + } + + return operation; + } + + private static String exceptionTraceAsString(Throwable cause) { + StringWriter sw = new StringWriter(); + cause.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/JcmdExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import jdk.test.lib.JDKToolFinder; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +import java.util.List; + +/** + * Base class for Diagnostic Command Executors using the jcmd tool + */ +public abstract class JcmdExecutor extends CommandExecutor { + protected String jcmdBinary; + + protected abstract List createCommandLine(String cmd) throws CommandExecutorException; + + protected JcmdExecutor() { + jcmdBinary = JDKToolFinder.getJDKTool("jcmd"); + } + + protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException { + List commandLine = createCommandLine(cmd); + + try { + System.out.printf("Executing command '%s'%n", commandLine); + OutputAnalyzer output = ProcessTools.executeProcess(new ProcessBuilder(commandLine)); + System.out.printf("Command returned with exit code %d%n", output.getExitValue()); + + return output; + } catch (Exception e) { + String message = String.format("Caught exception while executing '%s'", commandLine); + throw new CommandExecutorException(message, e); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/MainClassJcmdExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import java.util.Arrays; +import java.util.List; + +/** + * Executes Diagnostic Commands on the target VM (specified by main class) using the jcmd tool + */ +public class MainClassJcmdExecutor extends JcmdExecutor { + private final String mainClass; + + /** + * Instantiates a new MainClassJcmdExecutor targeting the current VM + */ + public MainClassJcmdExecutor() { + super(); + mainClass = System.getProperty("sun.java.command").split(" ")[0]; + } + + /** + * Instantiates a new MainClassJcmdExecutor targeting the VM indicated by the given main class + * + * @param target Main class of the target VM + */ + public MainClassJcmdExecutor(String target) { + super(); + mainClass = target; + } + + protected List createCommandLine(String cmd) throws CommandExecutorException { + return Arrays.asList(jcmdBinary, mainClass, cmd); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/dcmd/PidJcmdExecutor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.dcmd; + +import jdk.test.lib.process.ProcessTools; + +import java.util.Arrays; +import java.util.List; + +/** + * Executes Diagnostic Commands on the target VM (specified by pid) using the jcmd tool + */ +public class PidJcmdExecutor extends JcmdExecutor { + protected final long pid; + + /** + * Instantiates a new PidJcmdExecutor targeting the current VM + */ + public PidJcmdExecutor() { + super(); + try { + pid = ProcessTools.getProcessId(); + } catch (Exception e) { + throw new CommandExecutorException("Could not determine own pid", e); + } + } + + /** + * Instantiates a new PidJcmdExecutor targeting the VM indicated by the given pid + * + * @param target Pid of the target VM + */ + public PidJcmdExecutor(String target) { + super(); + pid = Long.valueOf(target); + } + + protected List createCommandLine(String cmd) throws CommandExecutorException { + return Arrays.asList(jcmdBinary, Long.toString(pid), cmd); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/HprofParser.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/HprofParser.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/HprofParser.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/HprofParser.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.hprof; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; + +import jdk.test.lib.hprof.model.Snapshot; +import jdk.test.lib.hprof.parser.Reader; + +/** + * Helper class to parse a java heap dump file. + */ +public class HprofParser { + + public static void main(String[] args) throws Exception { + if (args.length < 1) { + System.out.println("No arguments supplied"); + } + File dump = new File(args[0]); + if (!dump.exists() || !dump.isFile()) { + throw new RuntimeException("The dump file does not exist or not a file"); + } + parse(dump); + } + + /** + * @see #parse(File, boolean, boolean, boolean) + */ + public static File parse(File dump) throws Exception { + return parse(dump, false, true, true); + } + + /** + * @see #parse(File, boolean, boolean, boolean) + */ + public static File parseWithDebugInfo(File dump) throws Exception { + return parse(dump, true, true, true); + } + + /** + * Parse a java heap dump file + * + * @param dump Heap dump file to parse + * @param debug Turn on/off debug file parsing + * @param callStack Turn on/off tracking of object allocation call stack + * @param calculateRefs Turn on/off tracking object allocation call stack + * @throws Exception + * @return File containing output from the parser + */ + public static File parse(File dump, boolean debug, boolean callStack, boolean calculateRefs) throws Exception { + File out = new File("hprof." + System.currentTimeMillis() + ".out"); + if (out.exists()) { + out.delete(); + } + + PrintStream psSystemOut = System.out; + try (PrintStream psHprof = new PrintStream(new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath())))) { + System.setOut(psHprof); + + int debugLevel = debug ? 2 : 0; + try (Snapshot snapshot = Reader.readFile(dump.getAbsolutePath(), callStack, debugLevel)) { + System.out.println("Snapshot read, resolving..."); + snapshot.resolve(calculateRefs); + System.out.println("Snapshot resolved."); + } + } finally { + System.setOut(psSystemOut); + } + + return out; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/README openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/README --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/README 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/README 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,13 @@ +The jhat tool has been removed. jhat hprof file parser/validator +are needed for tests. The old packages for jhat were moved here: +com.sun.tools.hat.internal.model -> jdk.test.lib.hprof.model +com.sun.tools.hat.internal.parser -> jdk.test.lib.hprof.parser +com.sun.tools.hat.internal.util -> jdk.test.lib.hprof.util + +jhat was added in JDK 6 and its original implementation was from +java.net HAT project [1]. jhat is an experimental, unsupported tool. +There hasn't been much update to jhat tool in the JDK. In addition, +there are several better heap dump visualizer/analyzer emerged since +JDK 5/6 serviceability support. + +[1] https://java.net/projects/hat diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/AbstractJavaHeapObjectVisitor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * A visitor for a JavaThing. @see JavaObject#visitReferencedObjects() + * + */ + + +abstract public class AbstractJavaHeapObjectVisitor + implements JavaHeapObjectVisitor { + abstract public void visit(JavaHeapObject other); + + /** + * Should the given field be excluded from the set of things visited? + * @return true if it should. + */ + public boolean exclude(JavaClass clazz, JavaField f) { + return false; + } + + /** + * @return true iff exclude might ever return true + */ + public boolean mightExclude() { + return false; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ArrayTypeCodes.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Primitive array type codes as defined by VM specification. + * + */ +public interface ArrayTypeCodes { + // Typecodes for array elements. + // Refer to newarray instruction in VM Spec. + public static final int T_BOOLEAN = 4; + public static final int T_CHAR = 5; + public static final int T_FLOAT = 6; + public static final int T_DOUBLE = 7; + public static final int T_BYTE = 8; + public static final int T_SHORT = 9; + public static final int T_INT = 10; + public static final int T_LONG = 11; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/HackJavaValue.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * This is used to represent values that the program doesn't really understand. + * This includes the null vlaue, and unresolved references (which shouldn't + * happen in well-formed hprof files). + * + * + * @author Bill Foote + */ + + + + +public class HackJavaValue extends JavaValue { + + private String value; + private long size; + + public HackJavaValue(String value, long size) { + this.value = value; + this.size = size; + } + + public String toString() { + return value; + } + + @Override + public long getSize() { + return size; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaBoolean.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a boolean (i.e. a boolean field in an instance). + * + * @author Bill Foote + */ + + +public class JavaBoolean extends JavaValue { + + boolean value; + + public JavaBoolean(boolean value) { + this.value = value; + } + + public String toString() { + return "" + value; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaByte.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaByte.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaByte.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaByte.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents an byte (i.e. a byte field in an instance). + * + * @author Bill Foote + */ + + +public class JavaByte extends JavaValue { + + byte value; + + public JavaByte(byte value) { + this.value = value; + } + + public String toString() { + return "0x" + Integer.toString(((int) value) & 0xff, 16); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaChar.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaChar.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaChar.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaChar.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a char (i.e. a char field in an instance). + * + * @author Bill Foote + */ + + +public class JavaChar extends JavaValue { + + char value; + + public JavaChar(char value) { + this.value = value; + } + + public String toString() { + return "" + value; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaClass.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaClass.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaClass.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaClass.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,504 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.util.Vector; +import java.util.Enumeration; +import jdk.test.lib.hprof.util.CompositeEnumeration; +import jdk.test.lib.hprof.parser.ReadBuffer; + +/** + * + * @author Bill Foote + */ + + +public class JavaClass extends JavaHeapObject { + // my id + private long id; + // my name + private String name; + + // These are JavaObjectRef before resolve + private JavaThing superclass; + private JavaThing loader; + private JavaThing signers; + private JavaThing protectionDomain; + + // non-static fields + private JavaField[] fields; + // static fields + private JavaStatic[] statics; + + private static final JavaClass[] EMPTY_CLASS_ARRAY = new JavaClass[0]; + // my subclasses + private JavaClass[] subclasses = EMPTY_CLASS_ARRAY; + + // my instances + private Vector instances = new Vector(); + + // Who I belong to. Set on resolve. + private Snapshot mySnapshot; + + // Size of an instance, including VM overhead + private int instanceSize; + // Total number of fields including inherited ones + private int totalNumFields; + + + public JavaClass(long id, String name, long superclassId, long loaderId, + long signersId, long protDomainId, + JavaField[] fields, JavaStatic[] statics, + int instanceSize) { + this.id = id; + this.name = name; + this.superclass = new JavaObjectRef(superclassId); + this.loader = new JavaObjectRef(loaderId); + this.signers = new JavaObjectRef(signersId); + this.protectionDomain = new JavaObjectRef(protDomainId); + this.fields = fields; + this.statics = statics; + this.instanceSize = instanceSize; + } + + public JavaClass(String name, long superclassId, long loaderId, + long signersId, long protDomainId, + JavaField[] fields, JavaStatic[] statics, + int instanceSize) { + this(-1L, name, superclassId, loaderId, signersId, + protDomainId, fields, statics, instanceSize); + } + + public final JavaClass getClazz() { + return mySnapshot.getJavaLangClass(); + } + + public final int getIdentifierSize() { + return mySnapshot.getIdentifierSize(); + } + + public final int getMinimumObjectSize() { + return mySnapshot.getMinimumObjectSize(); + } + + public void resolve(Snapshot snapshot) { + if (mySnapshot != null) { + return; + } + mySnapshot = snapshot; + resolveSuperclass(snapshot); + if (superclass != null) { + ((JavaClass) superclass).addSubclass(this); + } + + loader = loader.dereference(snapshot, null); + signers = signers.dereference(snapshot, null); + protectionDomain = protectionDomain.dereference(snapshot, null); + + for (int i = 0; i < statics.length; i++) { + statics[i].resolve(this, snapshot); + } + snapshot.getJavaLangClass().addInstance(this); + super.resolve(snapshot); + return; + } + + /** + * Resolve our superclass. This might be called well before + * all instances are available (like when reading deferred + * instances in a 1.2 dump file :-) Calling this is sufficient + * to be able to explore this class' fields. + */ + public void resolveSuperclass(Snapshot snapshot) { + if (superclass == null) { + // We must be java.lang.Object, so we have no superclass. + } else { + totalNumFields = fields.length; + superclass = superclass.dereference(snapshot, null); + if (superclass == snapshot.getNullThing()) { + superclass = null; + } else { + try { + JavaClass sc = (JavaClass) superclass; + sc.resolveSuperclass(snapshot); + totalNumFields += sc.totalNumFields; + } catch (ClassCastException ex) { + System.out.println("Warning! Superclass of " + name + " is " + superclass); + superclass = null; + } + } + } + } + + public boolean isString() { + return mySnapshot.getJavaLangString() == this; + } + + public boolean isClassLoader() { + return mySnapshot.getJavaLangClassLoader().isAssignableFrom(this); + } + + /** + * Get a numbered field from this class + */ + public JavaField getField(int i) { + if (i < 0 || i >= fields.length) { + throw new Error("No field " + i + " for " + name); + } + return fields[i]; + } + + /** + * Get the total number of fields that are part of an instance of + * this class. That is, include superclasses. + */ + public int getNumFieldsForInstance() { + return totalNumFields; + } + + /** + * Get a numbered field from all the fields that are part of instance + * of this class. That is, include superclasses. + */ + public JavaField getFieldForInstance(int i) { + if (superclass != null) { + JavaClass sc = (JavaClass) superclass; + if (i < sc.totalNumFields) { + return sc.getFieldForInstance(i); + } + i -= sc.totalNumFields; + } + return getField(i); + } + + /** + * Get the class responsible for field i, where i is a field number that + * could be passed into getFieldForInstance. + * + * @see JavaClass.getFieldForInstance() + */ + public JavaClass getClassForField(int i) { + if (superclass != null) { + JavaClass sc = (JavaClass) superclass; + if (i < sc.totalNumFields) { + return sc.getClassForField(i); + } + } + return this; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public boolean isArray() { + return name.indexOf('[') != -1; + } + + public Enumeration getInstances(boolean includeSubclasses) { + if (includeSubclasses) { + Enumeration res = instances.elements(); + for (int i = 0; i < subclasses.length; i++) { + res = new CompositeEnumeration(res, + subclasses[i].getInstances(true)); + } + return res; + } else { + return instances.elements(); + } + } + + /** + * @return a count of the instances of this class + */ + public int getInstancesCount(boolean includeSubclasses) { + int result = instances.size(); + if (includeSubclasses) { + for (int i = 0; i < subclasses.length; i++) { + result += subclasses[i].getInstancesCount(includeSubclasses); + } + } + return result; + } + + public JavaClass[] getSubclasses() { + return subclasses; + } + + /** + * This can only safely be called after resolve() + */ + public JavaClass getSuperclass() { + return (JavaClass) superclass; + } + + /** + * This can only safely be called after resolve() + */ + public JavaThing getLoader() { + return loader; + } + + /** + * This can only safely be called after resolve() + */ + public boolean isBootstrap() { + return loader == mySnapshot.getNullThing(); + } + + /** + * This can only safely be called after resolve() + */ + public JavaThing getSigners() { + return signers; + } + + /** + * This can only safely be called after resolve() + */ + public JavaThing getProtectionDomain() { + return protectionDomain; + } + + public JavaField[] getFields() { + return fields; + } + + /** + * Includes superclass fields + */ + public JavaField[] getFieldsForInstance() { + Vector v = new Vector(); + addFields(v); + JavaField[] result = new JavaField[v.size()]; + for (int i = 0; i < v.size(); i++) { + result[i] = v.elementAt(i); + } + return result; + } + + + public JavaStatic[] getStatics() { + return statics; + } + + // returns value of static field of given name + public JavaThing getStaticField(String name) { + for (int i = 0; i < statics.length; i++) { + JavaStatic s = statics[i]; + if (s.getField().getName().equals(name)) { + return s.getValue(); + } + } + return null; + } + + public String toString() { + return "class " + name; + } + + public int compareTo(JavaThing other) { + if (other instanceof JavaClass) { + return name.compareTo(((JavaClass) other).name); + } + return super.compareTo(other); + } + + + /** + * @return true iff a variable of type this is assignable from an instance + * of other + */ + public boolean isAssignableFrom(JavaClass other) { + if (this == other) { + return true; + } else if (other == null) { + return false; + } else { + return isAssignableFrom((JavaClass) other.superclass); + // Trivial tail recursion: I have faith in javac. + } + } + + /** + * Describe the reference that this thing has to target. This will only + * be called if target is in the array returned by getChildrenForRootset. + */ + public String describeReferenceTo(JavaThing target, Snapshot ss) { + for (int i = 0; i < statics.length; i++) { + JavaField f = statics[i].getField(); + if (f.hasId()) { + JavaThing other = statics[i].getValue(); + if (other == target) { + return "static field " + f.getName(); + } + } + } + return super.describeReferenceTo(target, ss); + } + + /** + * @return the size of an instance of this class. Gives 0 for an array + * type. + */ + public int getInstanceSize() { + return instanceSize + mySnapshot.getMinimumObjectSize(); + } + + + /** + * @return The size of all instances of this class. Correctly handles + * arrays. + */ + public long getTotalInstanceSize() { + int count = instances.size(); + if (count == 0 || !isArray()) { + return count * instanceSize; + } + + // array class and non-zero count, we have to + // get the size of each instance and sum it + long result = 0; + for (int i = 0; i < count; i++) { + JavaThing t = (JavaThing) instances.elementAt(i); + result += t.getSize(); + } + return result; + } + + /** + * @return the size of this object + */ + @Override + public long getSize() { + JavaClass cl = mySnapshot.getJavaLangClass(); + if (cl == null) { + return 0; + } else { + return cl.getInstanceSize(); + } + } + + public void visitReferencedObjects(JavaHeapObjectVisitor v) { + super.visitReferencedObjects(v); + JavaHeapObject sc = getSuperclass(); + if (sc != null) v.visit(getSuperclass()); + + JavaThing other; + other = getLoader(); + if (other instanceof JavaHeapObject) { + v.visit((JavaHeapObject)other); + } + other = getSigners(); + if (other instanceof JavaHeapObject) { + v.visit((JavaHeapObject)other); + } + other = getProtectionDomain(); + if (other instanceof JavaHeapObject) { + v.visit((JavaHeapObject)other); + } + + for (int i = 0; i < statics.length; i++) { + JavaField f = statics[i].getField(); + if (!v.exclude(this, f) && f.hasId()) { + other = statics[i].getValue(); + if (other instanceof JavaHeapObject) { + v.visit((JavaHeapObject) other); + } + } + } + } + + // package-privates below this point + final ReadBuffer getReadBuffer() { + return mySnapshot.getReadBuffer(); + } + + final void setNew(JavaHeapObject obj, boolean flag) { + mySnapshot.setNew(obj, flag); + } + + final boolean isNew(JavaHeapObject obj) { + return mySnapshot.isNew(obj); + } + + final StackTrace getSiteTrace(JavaHeapObject obj) { + return mySnapshot.getSiteTrace(obj); + } + + final void addReferenceFromRoot(Root root, JavaHeapObject obj) { + mySnapshot.addReferenceFromRoot(root, obj); + } + + final Root getRoot(JavaHeapObject obj) { + return mySnapshot.getRoot(obj); + } + + final Snapshot getSnapshot() { + return mySnapshot; + } + + void addInstance(JavaHeapObject inst) { + instances.addElement(inst); + } + + // Internals only below this point + private void addFields(Vector v) { + if (superclass != null) { + ((JavaClass) superclass).addFields(v); + } + for (int i = 0; i < fields.length; i++) { + v.addElement(fields[i]); + } + } + + private void addSubclassInstances(Vector v) { + for (int i = 0; i < subclasses.length; i++) { + subclasses[i].addSubclassInstances(v); + } + for (int i = 0; i < instances.size(); i++) { + v.addElement(instances.elementAt(i)); + } + } + + private void addSubclass(JavaClass sub) { + JavaClass newValue[] = new JavaClass[subclasses.length + 1]; + System.arraycopy(subclasses, 0, newValue, 0, subclasses.length); + newValue[subclasses.length] = sub; + subclasses = newValue; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaDouble.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a double (i.e. a double field in an instance). + * + * @author Bill Foote + */ + + +public class JavaDouble extends JavaValue { + + double value; + + public JavaDouble(double value) { + this.value = value; + } + + public String toString() { + return Double.toString(value); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaField.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaField.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaField.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaField.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + + +/** + * + * @author Bill Foote + */ + +public class JavaField { + + private String name; + private String signature; + + public JavaField(String name, String signature) { + this.name = name; + this.signature = signature; + } + + + /** + * @return true if the type of this field is something that has an ID. + * int fields, for exampe, don't. + */ + public boolean hasId() { + char ch = signature.charAt(0); + return (ch == '[' || ch == 'L'); + } + + public String getName() { + return name; + } + + public String getSignature() { + return signature; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaFloat.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a float (i.e. a float field in an instance). + * + * @author Bill Foote + */ + + +public class JavaFloat extends JavaValue { + + float value; + + public JavaFloat(float value) { + this.value = value; + } + + public String toString() { + return Float.toString(value); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObject.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,207 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import jdk.test.lib.hprof.util.Misc; + + +/** + * + * @author Bill Foote + */ + +/** + * Represents an object that's allocated out of the Java heap. It occupies + * memory in the VM, and is the sort of thing that in a JDK 1.1 VM had + * a handle. It can be a + * JavaClass, a JavaObjectArray, a JavaValueArray or a JavaObject. + */ + +public abstract class JavaHeapObject extends JavaThing { + + // + // Who we refer to. This is heavily optimized for space, because it's + // well worth trading a bit of speed for less swapping. + // referers and referersLen go through two phases: Building and + // resolved. When building, referers might have duplicates, but can + // be appended to. When resolved, referers has no duplicates or + // empty slots. + // + private JavaThing[] referers = null; + private int referersLen = 0; // -1 when resolved + + public abstract JavaClass getClazz(); + public abstract long getSize(); + public abstract long getId(); + + /** + * Do any initialization this thing needs after its data is read in. + * Subclasses that override this should call super.resolve(). + */ + public void resolve(Snapshot snapshot) { + StackTrace trace = snapshot.getSiteTrace(this); + if (trace != null) { + trace.resolve(snapshot); + } + } + + // + // Eliminate duplicates from referers, and size the array exactly. + // This sets us up to answer queries. See the comments around the + // referers data member for details. + // + void setupReferers() { + if (referersLen > 1) { + // Copy referers to map, screening out duplicates + Map map = new HashMap(); + for (int i = 0; i < referersLen; i++) { + if (map.get(referers[i]) == null) { + map.put(referers[i], referers[i]); + } + } + + // Now copy into the array + referers = new JavaThing[map.size()]; + map.keySet().toArray(referers); + } + referersLen = -1; + } + + + /** + * @return the id of this thing as hex string + */ + public String getIdString() { + return Misc.toHex(getId()); + } + + public String toString() { + return getClazz().getName() + "@" + getIdString(); + } + + /** + * @return the StackTrace of the point of allocation of this object, + * or null if unknown + */ + public StackTrace getAllocatedFrom() { + return getClazz().getSiteTrace(this); + } + + public boolean isNew() { + return getClazz().isNew(this); + } + + void setNew(boolean flag) { + getClazz().setNew(this, flag); + } + + /** + * Tell the visitor about all of the objects we refer to + */ + public void visitReferencedObjects(JavaHeapObjectVisitor v) { + v.visit(getClazz()); + } + + void addReferenceFrom(JavaHeapObject other) { + if (referersLen == 0) { + referers = new JavaThing[1]; // It was null + } else if (referersLen == referers.length) { + JavaThing[] copy = new JavaThing[(3 * (referersLen + 1)) / 2]; + System.arraycopy(referers, 0, copy, 0, referersLen); + referers = copy; + } + referers[referersLen++] = other; + // We just append to referers here. Measurements have shown that + // around 10% to 30% are duplicates, so it's better to just append + // blindly and screen out all the duplicates at once. + } + + void addReferenceFromRoot(Root r) { + getClazz().addReferenceFromRoot(r, this); + } + + /** + * If the rootset includes this object, return a Root describing one + * of the reasons why. + */ + public Root getRoot() { + return getClazz().getRoot(this); + } + + /** + * Tell who refers to us. + * + * @return an Enumeration of JavaHeapObject instances + */ + public Enumeration getReferers() { + if (referersLen != -1) { + throw new RuntimeException("not resolved: " + getIdString()); + } + return new Enumeration() { + + private int num = 0; + + public boolean hasMoreElements() { + return referers != null && num < referers.length; + } + + public JavaThing nextElement() { + return referers[num++]; + } + }; + } + + /** + * Given other, which the caller promises is in referers, determines if + * the reference is only a weak reference. + */ + public boolean refersOnlyWeaklyTo(Snapshot ss, JavaThing other) { + return false; + } + + /** + * Describe the reference that this thing has to target. This will only + * be called if target is in the array returned by getChildrenForRootset. + */ + public String describeReferenceTo(JavaThing target, Snapshot ss) { + return "??"; + } + + public boolean isHeapAllocated() { + return true; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaHeapObjectVisitor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * A visitor for a JavaThing. @see JavaObject#visitReferencedObjects() + * + * @author Bill Foote + */ + + +public interface JavaHeapObjectVisitor { + public void visit(JavaHeapObject other); + + /** + * Should the given field be excluded from the set of things visited? + * @return true if it should. + */ + public boolean exclude(JavaClass clazz, JavaField f); + + /** + * @return true iff exclude might ever return true + */ + public boolean mightExclude(); +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaInt.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaInt.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaInt.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaInt.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents an integer (i.e. an int field in an instance). + * + * @author Bill Foote + */ + + +public class JavaInt extends JavaValue { + + int value; + + public JavaInt(int value) { + this.value = value; + } + + public String toString() { + return "" + value; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLazyReadObject.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.io.IOException; +import jdk.test.lib.hprof.parser.ReadBuffer; + +/* + * Base class for lazily read Java heap objects. + */ +public abstract class JavaLazyReadObject extends JavaHeapObject { + + // file offset from which this object data starts + private final long offset; + + protected JavaLazyReadObject(long offset) { + this.offset = offset; + } + + @Override + public final long getSize() { + return getValueLength() + getClazz().getMinimumObjectSize(); + } + + protected final long getOffset() { + return offset; + } + + protected ReadBuffer buf() { + return getClazz().getReadBuffer(); + } + + protected int idSize() { + return getClazz().getIdentifierSize(); + } + + // return the length of the data for this object + protected final long getValueLength() { + try { + return readValueLength(); + } catch (IOException exp) { + System.err.println("lazy read failed at offset " + offset); + exp.printStackTrace(); + return 0; + } + } + + // get this object's content as byte array + protected final JavaThing[] getValue() { + try { + return readValue(); + } catch (IOException exp) { + System.err.println("lazy read failed at offset " + offset); + exp.printStackTrace(); + return Snapshot.EMPTY_JAVATHING_ARRAY; + } + } + + // get ID of this object + public final long getId() { + try { + if (idSize() == 4) { + return ((long)buf().getInt(offset)) & Snapshot.SMALL_ID_MASK; + } else { + return buf().getLong(offset); + } + } catch (IOException exp) { + System.err.println("lazy read failed at offset " + offset); + exp.printStackTrace(); + return -1; + } + } + + protected abstract long readValueLength() throws IOException; + protected abstract JavaThing[] readValue() throws IOException; + + // make Integer or Long for given object ID + protected static Number makeId(long id) { + if ((id & ~Snapshot.SMALL_ID_MASK) == 0) { + return (int)id; + } else { + return id; + } + } + + // get ID as long value from Number + protected static long getIdValue(Number num) { + long id = num.longValue(); + if (num instanceof Integer) { + id &= Snapshot.SMALL_ID_MASK; + } + return id; + } + + // read object ID from given index from given byte array + protected final long objectIdAt(long offset) throws IOException { + if (idSize() == 4) { + return ((long)intAt(offset)) & Snapshot.SMALL_ID_MASK; + } else { + return longAt(offset); + } + } + + // utility methods to read primitive types from byte array + protected byte byteAt(long offset) throws IOException { + return buf().getByte(offset); + } + + protected boolean booleanAt(long offset) throws IOException { + return byteAt(offset) == 0 ? false : true; + } + + protected char charAt(long offset) throws IOException { + return buf().getChar(offset); + } + + protected short shortAt(long offset) throws IOException { + return buf().getShort(offset); + } + + protected int intAt(long offset) throws IOException { + return buf().getInt(offset); + } + + protected long longAt(long offset) throws IOException { + return buf().getLong(offset); + } + + protected float floatAt(long offset) throws IOException { + int val = intAt(offset); + return Float.intBitsToFloat(val); + } + + protected double doubleAt(long offset) throws IOException { + long val = longAt(offset); + return Double.longBitsToDouble(val); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLong.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLong.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLong.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaLong.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a long (i.e. a long field in an instance). + * + * @author Bill Foote + */ + + +public class JavaLong extends JavaValue { + + long value; + + public JavaLong(long value) { + this.value = value; + } + + public String toString() { + return Long.toString(value); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObject.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObject.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObject.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObject.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,333 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.io.IOException; +import jdk.test.lib.hprof.parser.ReadBuffer; + +/** + * Represents Java instance + * + * @author Bill Foote + */ +public class JavaObject extends JavaLazyReadObject { + + private Object clazz; // Number before resolve + // JavaClass after resolve + /** + * Construct a new JavaObject. + * + * @param classID id of the class object + * @param offset The offset of field data + */ + public JavaObject(long classID, long offset) { + super(offset); + this.clazz = makeId(classID); + } + + public void resolve(Snapshot snapshot) { + if (clazz instanceof JavaClass) { + return; + } + if (clazz instanceof Number) { + long classID = getIdValue((Number)clazz); + clazz = snapshot.findThing(classID); + if (! (clazz instanceof JavaClass)) { + warn("Class " + Long.toHexString(classID) + " not found, " + + "adding fake class!"); + int length; + ReadBuffer buf = snapshot.getReadBuffer(); + int idSize = snapshot.getIdentifierSize(); + long lenOffset = getOffset() + 2*idSize + 4; + try { + length = buf.getInt(lenOffset); + } catch (IOException exp) { + throw new RuntimeException(exp); + } + clazz = snapshot.addFakeInstanceClass(classID, length); + } + } else { + throw new InternalError("should not reach here"); + } + + JavaClass cl = (JavaClass) clazz; + cl.resolve(snapshot); + + // while resolving, parse fields in verbose mode. + // but, getFields calls parseFields in non-verbose mode + // to avoid printing warnings repeatedly. + parseFields(true); + + cl.addInstance(this); + super.resolve(snapshot); + } + + /** + * Are we the same type as other? We are iff our clazz is the + * same type as other's. + */ + public boolean isSameTypeAs(JavaThing other) { + if (!(other instanceof JavaObject)) { + return false; + } + JavaObject oo = (JavaObject) other; + return getClazz().equals(oo.getClazz()); + } + + /** + * Return our JavaClass object. This may only be called after resolve. + */ + public JavaClass getClazz() { + return (JavaClass) clazz; + } + + public JavaThing[] getFields() { + // pass false to verbose mode so that dereference + // warnings are not printed. + return parseFields(false); + } + + // returns the value of field of given name + public JavaThing getField(String name) { + JavaThing[] flds = getFields(); + JavaField[] instFields = getClazz().getFieldsForInstance(); + for (int i = 0; i < instFields.length; i++) { + if (instFields[i].getName().equals(name)) { + return flds[i]; + } + } + return null; + } + + public int compareTo(JavaThing other) { + if (other instanceof JavaObject) { + JavaObject oo = (JavaObject) other; + return getClazz().getName().compareTo(oo.getClazz().getName()); + } + return super.compareTo(other); + } + + public void visitReferencedObjects(JavaHeapObjectVisitor v) { + super.visitReferencedObjects(v); + JavaThing[] flds = getFields(); + for (int i = 0; i < flds.length; i++) { + if (flds[i] != null) { + if (v.mightExclude() + && v.exclude(getClazz().getClassForField(i), + getClazz().getFieldForInstance(i))) + { + // skip it + } else if (flds[i] instanceof JavaHeapObject) { + v.visit((JavaHeapObject) flds[i]); + } + } + } + } + + public boolean refersOnlyWeaklyTo(Snapshot ss, JavaThing other) { + if (ss.getWeakReferenceClass() != null) { + final int referentFieldIndex = ss.getReferentFieldIndex(); + if (ss.getWeakReferenceClass().isAssignableFrom(getClazz())) { + // + // REMIND: This introduces a dependency on the JDK + // implementation that is undesirable. + JavaThing[] flds = getFields(); + for (int i = 0; i < flds.length; i++) { + if (i != referentFieldIndex && flds[i] == other) { + return false; + } + } + return true; + } + } + return false; + } + + /** + * Describe the reference that this thing has to target. This will only + * be called if target is in the array returned by getChildrenForRootset. + */ + public String describeReferenceTo(JavaThing target, Snapshot ss) { + JavaThing[] flds = getFields(); + for (int i = 0; i < flds.length; i++) { + if (flds[i] == target) { + JavaField f = getClazz().getFieldForInstance(i); + return "field " + f.getName(); + } + } + return super.describeReferenceTo(target, ss); + } + + public String toString() { + if (getClazz().isString()) { + JavaThing value = getField("value"); + if (value instanceof JavaValueArray) { + return ((JavaValueArray)value).valueString(); + } else { + return "null"; + } + } else { + return super.toString(); + } + } + + // Internals only below this point + + /* + * Java instance record (HPROF_GC_INSTANCE_DUMP) looks as below: + * + * object ID + * stack trace serial number (int) + * class ID + * data length (int) + * byte[length] + */ + @Override + protected final long readValueLength() throws IOException { + long lengthOffset = getOffset() + 2 * idSize() + 4; + return buf().getInt(lengthOffset); + } + + @Override + protected final JavaThing[] readValue() throws IOException { + return parseFields(false); + } + + private long dataStartOffset() { + return getOffset() + idSize() + 4 + idSize() + 4; + } + + private JavaThing[] parseFields(boolean verbose) { + JavaClass cl = getClazz(); + int target = cl.getNumFieldsForInstance(); + JavaField[] fields = cl.getFields(); + JavaThing[] fieldValues = new JavaThing[target]; + Snapshot snapshot = cl.getSnapshot(); + int fieldNo = 0; + // In the dump file, the fields are stored in this order: + // fields of most derived class (immediate class) are stored + // first and then the super class and so on. In this object, + // fields are stored in the reverse ("natural") order. i.e., + // fields of most super class are stored first. + + // target variable is used to compensate for the fact that + // the dump file starts field values from the leaf working + // upwards in the inheritance hierarchy, whereas JavaObject + // starts with the top of the inheritance hierarchy and works down. + target -= fields.length; + JavaClass currClass = cl; + long offset = dataStartOffset(); + for (int i = 0; i < fieldValues.length; i++, fieldNo++) { + while (fieldNo >= fields.length) { + currClass = currClass.getSuperclass(); + fields = currClass.getFields(); + fieldNo = 0; + target -= fields.length; + } + JavaField f = fields[fieldNo]; + char sig = f.getSignature().charAt(0); + try { + switch (sig) { + case 'L': + case '[': { + long id = objectIdAt(offset); + offset += idSize(); + JavaObjectRef ref = new JavaObjectRef(id); + fieldValues[target+fieldNo] = ref.dereference(snapshot, f, verbose); + break; + } + case 'Z': { + byte value = byteAt(offset); + offset++; + fieldValues[target+fieldNo] = new JavaBoolean(value != 0); + break; + } + case 'B': { + byte value = byteAt(offset); + offset++; + fieldValues[target+fieldNo] = new JavaByte(value); + break; + } + case 'S': { + short value = shortAt(offset); + offset += 2; + fieldValues[target+fieldNo] = new JavaShort(value); + break; + } + case 'C': { + char value = charAt(offset); + offset += 2; + fieldValues[target+fieldNo] = new JavaChar(value); + break; + } + case 'I': { + int value = intAt(offset); + offset += 4; + fieldValues[target+fieldNo] = new JavaInt(value); + break; + } + case 'J': { + long value = longAt(offset); + offset += 8; + fieldValues[target+fieldNo] = new JavaLong(value); + break; + } + case 'F': { + float value = floatAt(offset); + offset += 4; + fieldValues[target+fieldNo] = new JavaFloat(value); + break; + } + case 'D': { + double value = doubleAt(offset); + offset += 8; + fieldValues[target+fieldNo] = new JavaDouble(value); + break; + } + default: + throw new RuntimeException("invalid signature: " + sig); + + } + } catch (IOException exp) { + System.err.println("lazy read failed at offset " + offset); + exp.printStackTrace(); + return Snapshot.EMPTY_JAVATHING_ARRAY; + } + } + return fieldValues; + } + + private void warn(String msg) { + System.out.println("WARNING: " + msg); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectArray.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.io.IOException; +import jdk.test.lib.hprof.parser.ReadBuffer; + +/** + * @author Bill Foote + */ +public class JavaObjectArray extends JavaLazyReadObject { + + private Object clazz; // Long before resolve, the class after resolve + + public JavaObjectArray(long classID, long offset) { + super(offset); + this.clazz = makeId(classID); + } + + public JavaClass getClazz() { + return (JavaClass) clazz; + } + + public void resolve(Snapshot snapshot) { + if (clazz instanceof JavaClass) { + return; + } + long classID = getIdValue((Number)clazz); + if (snapshot.isNewStyleArrayClass()) { + // Modern heap dumps do this + JavaThing t = snapshot.findThing(classID); + if (t instanceof JavaClass) { + clazz = (JavaClass) t; + } + } + if (!(clazz instanceof JavaClass)) { + JavaThing t = snapshot.findThing(classID); + if (t != null && t instanceof JavaClass) { + JavaClass el = (JavaClass) t; + String nm = el.getName(); + if (!nm.startsWith("[")) { + nm = "L" + el.getName() + ";"; + } + clazz = snapshot.getArrayClass(nm); + } + } + + if (!(clazz instanceof JavaClass)) { + clazz = snapshot.getOtherArrayType(); + } + ((JavaClass)clazz).addInstance(this); + super.resolve(snapshot); + } + + public JavaThing[] getValues() { + return getElements(); + } + + public JavaThing[] getElements() { + return getValue(); + } + + public int compareTo(JavaThing other) { + if (other instanceof JavaObjectArray) { + return 0; + } + return super.compareTo(other); + } + + public int getLength() { + return (int)(getValueLength() / idSize()); + } + + public void visitReferencedObjects(JavaHeapObjectVisitor v) { + super.visitReferencedObjects(v); + JavaThing[] elements = getElements(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] != null && elements[i] instanceof JavaHeapObject) { + v.visit((JavaHeapObject) elements[i]); + } + } + } + + /** + * Describe the reference that this thing has to target. This will only + * be called if target is in the array returned by getChildrenForRootset. + */ + public String describeReferenceTo(JavaThing target, Snapshot ss) { + JavaThing[] elements = getElements(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] == target) { + return "Element " + i + " of " + this; + } + } + return super.describeReferenceTo(target, ss); + } + + /* + * Java object array record (HPROF_GC_OBJ_ARRAY_DUMP) + * looks as below: + * + * object ID + * stack trace serial number (int) + * array length (int) + * array class ID + * array element IDs + */ + @Override + protected final long readValueLength() throws IOException { + long offset = getOffset() + idSize() + 4; + // length of the array in elements + long len = buf().getInt(offset); + // byte length of array + return len * idSize(); + } + + private long dataStartOffset() { + return getOffset() + idSize() + 4 + 4 + idSize(); + } + + @Override + protected final JavaThing[] readValue() throws IOException { + Snapshot snapshot = getClazz().getSnapshot(); + int len = getLength(); + long offset = dataStartOffset(); + + JavaThing[] res = new JavaThing[len]; + for (int i = 0; i < len; i++) { + long id = objectIdAt(offset); + res[i] = snapshot.findThing(id); + offset += idSize(); + } + return res; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaObjectRef.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import jdk.test.lib.hprof.util.Misc; + +/** + * A forward reference to an object. This is an intermediate representation + * for a JavaThing, when we have the thing's ID, but we might not have read + * the thing yet. + * + * @author Bill Foote + */ +public class JavaObjectRef extends JavaThing { + private long id; + + public JavaObjectRef(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public boolean isHeapAllocated() { + return true; + } + + public JavaThing dereference(Snapshot snapshot, JavaField field) { + return dereference(snapshot, field, true); + } + + public JavaThing dereference(Snapshot snapshot, JavaField field, boolean verbose) { + if (field != null && !field.hasId()) { + // If this happens, we must be a field that represents an int. + // (This only happens with .bod-style files) + return new JavaLong(id); + } + if (id == 0) { + return snapshot.getNullThing(); + } + JavaThing result = snapshot.findThing(id); + if (result == null) { + if (!snapshot.getUnresolvedObjectsOK() && verbose) { + String msg = "WARNING: Failed to resolve object id " + + Misc.toHex(id); + if (field != null) { + msg += " for field " + field.getName() + + " (signature " + field.getSignature() + ")"; + } + System.out.println(msg); + // Thread.dumpStack(); + } + result = new HackJavaValue("Unresolved object " + + Misc.toHex(id), 0); + } + return result; + } + + @Override + public long getSize() { + return 0; + } + + public String toString() { + return "Unresolved object " + Misc.toHex(id); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaShort.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaShort.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaShort.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaShort.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a short (i.e. a short field in an instance). + * + * @author Bill Foote + */ + + +public class JavaShort extends JavaValue { + + short value; + + public JavaShort(short value) { + this.value = value; + } + + public String toString() { + return "" + value; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaStatic.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * + * @author Bill Foote + */ + +/** + * Represents the value of a static field of a JavaClass + */ + +public class JavaStatic { + + private JavaField field; + private JavaThing value; + + public JavaStatic(JavaField field, JavaThing value) { + this.field = field; + this.value = value; + } + + public void resolve(JavaClass clazz, Snapshot snapshot) { + long id = -1; + if (value instanceof JavaObjectRef) { + id = ((JavaObjectRef)value).getId(); + } + value = value.dereference(snapshot, field); + if (value.isHeapAllocated() && + clazz.getLoader() == snapshot.getNullThing()) { + // static fields are only roots if they are in classes + // loaded by the root classloader. + JavaHeapObject ho = (JavaHeapObject) value; + String s = "Static reference from " + clazz.getName() + + "." + field.getName(); + snapshot.addRoot(new Root(id, clazz.getId(), + Root.JAVA_STATIC, s)); + } + } + + public JavaField getField() { + return field; + } + + public JavaThing getValue() { + return value; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaThing.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaThing.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaThing.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaThing.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.util.Enumeration; +import java.util.Hashtable; + + +/** + * + * @author Bill Foote + */ + + +/** + * Represents a java "Thing". A thing is anything that can be the value of + * a field. This includes JavaHeapObject, JavaObjectRef, and JavaValue. + */ + +public abstract class JavaThing { + + protected JavaThing() { + } + + /** + * If this is a forward reference, figure out what it really + * refers to. + * + * @param snapshot The snapshot this is for + * @param field The field this thing represents. If null, it is + * assumed this thing is an object (and never a value). + */ + public JavaThing dereference(Snapshot shapshot, JavaField field) { + return this; + } + + + /** + * Are we the same type as other? + * + * @see JavaObject.isSameTypeAs() + */ + public boolean isSameTypeAs(JavaThing other) { + return getClass() == other.getClass(); + } + /** + * @return true iff this represents a heap-allocated object + */ + abstract public boolean isHeapAllocated(); + + /** + * @return the size of this object, in bytes, including VM overhead + */ + abstract public long getSize(); + + /** + * @return a human-readable string representation of this thing + */ + abstract public String toString(); + + /** + * Compare our string representation to other's + * @see java.lang.String.compareTo() + */ + public int compareTo(JavaThing other) { + return toString().compareTo(other.toString()); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValue.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValue.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValue.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValue.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Abstract base class for all value types (ints, longs, floats, etc.) + * + * @author Bill Foote + */ + + + + +public abstract class JavaValue extends JavaThing { + + protected JavaValue() { + } + + public boolean isHeapAllocated() { + return false; + } + + abstract public String toString(); + + @Override + public long getSize() { + // The size of a value is already accounted for in the class + // that has the data member. + return 0; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/JavaValueArray.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,354 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import jdk.test.lib.hprof.parser.ReadBuffer; +import java.io.IOException; + +/** + * An array of values, that is, an array of ints, boolean, floats or the like. + * + * @author Bill Foote + */ +public class JavaValueArray extends JavaLazyReadObject + /*imports*/ implements ArrayTypeCodes { + + private static String arrayTypeName(byte sig) { + switch (sig) { + case 'B': + return "byte[]"; + case 'Z': + return "boolean[]"; + case 'C': + return "char[]"; + case 'S': + return "short[]"; + case 'I': + return "int[]"; + case 'F': + return "float[]"; + case 'J': + return "long[]"; + case 'D': + return "double[]"; + default: + throw new RuntimeException("invalid array element sig: " + sig); + } + } + + private static int elementSize(byte type) { + switch (type) { + case T_BYTE: + case T_BOOLEAN: + return 1; + case T_CHAR: + case T_SHORT: + return 2; + case T_INT: + case T_FLOAT: + return 4; + case T_LONG: + case T_DOUBLE: + return 8; + default: + throw new RuntimeException("invalid array element type: " + type); + } + } + + /* + * Java primitive array record (HPROF_GC_PRIM_ARRAY_DUMP) looks + * as below: + * + * object ID + * stack trace serial number (int) + * number of elements (int) + * element type (byte) + * array data + */ + @Override + protected final long readValueLength() throws IOException { + long offset = getOffset() + idSize() + 4; + // length of the array in elements + long len = buf().getInt(offset); + // byte length of array + return len * elementSize(getElementType()); + } + + private long dataStartOffset() { + return getOffset() + idSize() + 4 + 4 + 1; + } + + + @Override + protected final JavaThing[] readValue() throws IOException { + int len = getLength(); + long offset = dataStartOffset(); + + JavaThing[] res = new JavaThing[len]; + synchronized (buf()) { + switch (getElementType()) { + case 'Z': { + for (int i = 0; i < len; i++) { + res[i] = new JavaBoolean(booleanAt(offset)); + offset += 1; + } + return res; + } + case 'B': { + for (int i = 0; i < len; i++) { + res[i] = new JavaByte(byteAt(offset)); + offset += 1; + } + return res; + } + case 'C': { + for (int i = 0; i < len; i++) { + res[i] = new JavaChar(charAt(offset)); + offset += 2; + } + return res; + } + case 'S': { + for (int i = 0; i < len; i++) { + res[i] = new JavaShort(shortAt(offset)); + offset += 2; + } + return res; + } + case 'I': { + for (int i = 0; i < len; i++) { + res[i] = new JavaInt(intAt(offset)); + offset += 4; + } + return res; + } + case 'J': { + for (int i = 0; i < len; i++) { + res[i] = new JavaLong(longAt(offset)); + offset += 8; + } + return res; + } + case 'F': { + for (int i = 0; i < len; i++) { + res[i] = new JavaFloat(floatAt(offset)); + offset += 4; + } + return res; + } + case 'D': { + for (int i = 0; i < len; i++) { + res[i] = new JavaDouble(doubleAt(offset)); + offset += 8; + } + return res; + } + default: { + throw new RuntimeException("unknown primitive type?"); + } + } + } + } + + // JavaClass set only after resolve. + private JavaClass clazz; + + // This field contains elementSignature byte and + // divider to be used to calculate length. Note that + // length of content byte[] is not same as array length. + // Actual array length is (byte[].length / divider) + private int data; + + // First 8 bits of data is used for element signature + private static final int SIGNATURE_MASK = 0x0FF; + + // Next 8 bits of data is used for length divider + private static final int LENGTH_DIVIDER_MASK = 0x0FF00; + + // Number of bits to shift to get length divider + private static final int LENGTH_DIVIDER_SHIFT = 8; + + public JavaValueArray(byte elementSignature, long offset) { + super(offset); + this.data = (elementSignature & SIGNATURE_MASK); + } + + public JavaClass getClazz() { + return clazz; + } + + public void visitReferencedObjects(JavaHeapObjectVisitor v) { + super.visitReferencedObjects(v); + } + + public void resolve(Snapshot snapshot) { + if (clazz instanceof JavaClass) { + return; + } + byte elementSig = getElementType(); + clazz = snapshot.findClass(arrayTypeName(elementSig)); + if (clazz == null) { + clazz = snapshot.getArrayClass("" + ((char) elementSig)); + } + getClazz().addInstance(this); + super.resolve(snapshot); + } + + public int getLength() { + int divider = (data & LENGTH_DIVIDER_MASK) >>> LENGTH_DIVIDER_SHIFT; + if (divider == 0) { + byte elementSignature = getElementType(); + switch (elementSignature) { + case 'B': + case 'Z': + divider = 1; + break; + case 'C': + case 'S': + divider = 2; + break; + case 'I': + case 'F': + divider = 4; + break; + case 'J': + case 'D': + divider = 8; + break; + default: + throw new RuntimeException("unknown primitive type: " + + elementSignature); + } + data |= (divider << LENGTH_DIVIDER_SHIFT); + } + return (int)(getValueLength() / divider); + } + + public JavaThing[] getElements() { + return getValue(); + } + + public byte getElementType() { + return (byte) (data & SIGNATURE_MASK); + } + + private void checkIndex(int index) { + if (index < 0 || index >= getLength()) { + throw new ArrayIndexOutOfBoundsException(index); + } + } + + private void requireType(char type) { + if (getElementType() != type) { + throw new RuntimeException("not of type : " + type); + } + } + + public String valueString() { + return valueString(true); + } + + public String valueString(boolean bigLimit) { + // Char arrays deserve special treatment + StringBuilder result; + JavaThing[] things = getValue(); + byte elementSignature = getElementType(); + if (elementSignature == 'C') { + result = new StringBuilder(); + for (int i = 0; i < things.length; i++) { + result.append(things[i]); + } + } else { + int limit = 8; + if (bigLimit) { + limit = 1000; + } + result = new StringBuilder("{"); + for (int i = 0; i < things.length; i++) { + if (i > 0) { + result.append(", "); + } + if (i >= limit) { + result.append("... "); + break; + } + switch (elementSignature) { + case 'Z': { + boolean val = ((JavaBoolean)things[i]).value; + if (val) { + result.append("true"); + } else { + result.append("false"); + } + break; + } + case 'B': { + byte val = ((JavaByte)things[i]).value; + result.append("0x").append(Integer.toString(val, 16)); + break; + } + case 'S': { + short val = ((JavaShort)things[i]).value; + result.append(val); + break; + } + case 'I': { + int val = ((JavaInt)things[i]).value; + result.append(val); + break; + } + case 'J': { // long + long val = ((JavaLong)things[i]).value; + result.append(val); + break; + } + case 'F': { + float val = ((JavaFloat)things[i]).value; + result.append(val); + break; + } + case 'D': { // double + double val = ((JavaDouble)things[i]).value; + result.append(val); + break; + } + default: { + throw new RuntimeException("unknown primitive type?"); + } + } + } + result.append('}'); + } + return result.toString(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludes.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + + +/** + * This represents a set of data members that should be excluded from the + * reachable objects query. This is useful to exclude observers from the + * transitive closure of objects reachable from a given object, allowing + * some kind of real determination of the "size" of that object. + * + */ + +public interface ReachableExcludes { + /** + * @return true iff the given field is on the hitlist of excluded + * fields. + */ + public boolean isExcluded(String fieldName); +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableExcludesImpl.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.BufferedReader; +import java.io.IOException; + +import java.util.Hashtable; + +/** + * This represents a set of data members that should be excluded from the + * reachable objects query. + * This is useful to exclude observers from the + * transitive closure of objects reachable from a given object, allowing + * some kind of real determination of the "size" of that object. + * + * @author Bill Foote + */ +public class ReachableExcludesImpl implements ReachableExcludes { + + private File excludesFile; + private long lastModified; + private Hashtable methods; // Used as a bag + + /** + * Create a new ReachableExcludesImpl over the given file. The file will be + * re-read whenever the timestamp changes. + */ + public ReachableExcludesImpl(File excludesFile) { + this.excludesFile = excludesFile; + readFile(); + } + + private void readFileIfNeeded() { + if (excludesFile.lastModified() != lastModified) { + synchronized(this) { + if (excludesFile.lastModified() != lastModified) { + readFile(); + } + } + } + } + + private void readFile() { + long lm = excludesFile.lastModified(); + Hashtable m = new Hashtable(); + + try (BufferedReader r = new BufferedReader(new InputStreamReader( + new FileInputStream(excludesFile)))) { + String method; + while ((method = r.readLine()) != null) { + m.put(method, method); + } + lastModified = lm; + methods = m; // We want this to be atomic + } catch (IOException ex) { + System.out.println("Error reading " + excludesFile + ": " + ex); + } + } + + /** + * @return true iff the given field is on the histlist of excluded + * fields. + */ + public boolean isExcluded(String fieldName) { + readFileIfNeeded(); + return methods.get(fieldName) != null; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReachableObjects.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.util.Vector; +import java.util.Hashtable; +import java.util.Enumeration; + +import jdk.test.lib.hprof.util.ArraySorter; +import jdk.test.lib.hprof.util.Comparer; + +/** + * @author A. Sundararajan + */ + +public class ReachableObjects { + public ReachableObjects(JavaHeapObject root, + final ReachableExcludes excludes) { + this.root = root; + + final Hashtable bag = new Hashtable(); + final Hashtable fieldsExcluded = new Hashtable(); //Bag + final Hashtable fieldsUsed = new Hashtable(); // Bag + JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() { + public void visit(JavaHeapObject t) { + // Size is zero for things like integer fields + if (t != null && t.getSize() > 0 && bag.get(t) == null) { + bag.put(t, t); + t.visitReferencedObjects(this); + } + } + + public boolean mightExclude() { + return excludes != null; + } + + public boolean exclude(JavaClass clazz, JavaField f) { + if (excludes == null) { + return false; + } + String nm = clazz.getName() + "." + f.getName(); + if (excludes.isExcluded(nm)) { + fieldsExcluded.put(nm, nm); + return true; + } else { + fieldsUsed.put(nm, nm); + return false; + } + } + }; + // Put the closure of root and all objects reachable from root into + // bag (depth first), but don't include root: + visitor.visit(root); + bag.remove(root); + + // Now grab the elements into a vector, and sort it in decreasing size + JavaThing[] things = new JavaThing[bag.size()]; + int i = 0; + for (Enumeration e = bag.elements(); e.hasMoreElements(); ) { + things[i++] = (JavaThing) e.nextElement(); + } + ArraySorter.sort(things, new Comparer() { + public int compare(Object lhs, Object rhs) { + JavaThing left = (JavaThing) lhs; + JavaThing right = (JavaThing) rhs; + long diff = right.getSize() - left.getSize(); + if (diff != 0) { + return Long.signum(diff); + } + return left.compareTo(right); + } + }); + this.reachables = things; + + this.totalSize = root.getSize(); + for (i = 0; i < things.length; i++) { + this.totalSize += things[i].getSize(); + } + + excludedFields = getElements(fieldsExcluded); + usedFields = getElements(fieldsUsed); + } + + public JavaHeapObject getRoot() { + return root; + } + + public JavaThing[] getReachables() { + return reachables; + } + + public long getTotalSize() { + return totalSize; + } + + public String[] getExcludedFields() { + return excludedFields; + } + + public String[] getUsedFields() { + return usedFields; + } + + private String[] getElements(Hashtable ht) { + Object[] keys = ht.keySet().toArray(); + int len = keys.length; + String[] res = new String[len]; + System.arraycopy(keys, 0, res, 0, len); + ArraySorter.sortArrayOfStrings(res); + return res; + } + + private JavaHeapObject root; + private JavaThing[] reachables; + private String[] excludedFields; + private String[] usedFields; + private long totalSize; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/ReferenceChain.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * Represents a chain of references to some target object + * + * @author Bill Foote + */ + +public class ReferenceChain { + + JavaHeapObject obj; // Object referred to + ReferenceChain next; // Next in chain + + public ReferenceChain(JavaHeapObject obj, ReferenceChain next) { + this.obj = obj; + this.next = next; + } + + public JavaHeapObject getObj() { + return obj; + } + + public ReferenceChain getNext() { + return next; + } + + public int getDepth() { + int count = 1; + ReferenceChain tmp = next; + while (tmp != null) { + count++; + tmp = tmp.next; + } + return count; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Root.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Root.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Root.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Root.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,174 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import jdk.test.lib.hprof.util.Misc; + +/** + * + * @author Bill Foote + */ + + +/** + * Represents a member of the rootset, that is, one of the objects that + * the GC starts from when marking reachable objects. + */ + +public class Root { + + private long id; // ID of the JavaThing we refer to + private long refererId; // Thread or Class responsible for this, or 0 + private int index = -1; // Index in Snapshot.roots + private int type; + private String description; + private JavaHeapObject referer = null; + private StackTrace stackTrace = null; + + // Values for type. Higher values are more interesting -- see getType(). + // See also getTypeName() + public final static int INVALID_TYPE = 0; + public final static int UNKNOWN = 1; + public final static int SYSTEM_CLASS = 2; + + public final static int NATIVE_LOCAL = 3; + public final static int NATIVE_STATIC = 4; + public final static int THREAD_BLOCK = 5; + public final static int BUSY_MONITOR = 6; + public final static int JAVA_LOCAL = 7; + public final static int NATIVE_STACK = 8; + public final static int JAVA_STATIC = 9; + + + public Root(long id, long refererId, int type, String description) { + this(id, refererId, type, description, null); + } + + + public Root(long id, long refererId, int type, String description, + StackTrace stackTrace) { + this.id = id; + this.refererId = refererId; + this.type = type; + this.description = description; + this.stackTrace = stackTrace; + } + + public long getId() { + return id; + } + + public String getIdString() { + return Misc.toHex(id); + } + + public String getDescription() { + if ("".equals(description)) { + return getTypeName() + " Reference"; + } else { + return description; + } + } + + /** + * Return type. We guarantee that more interesting roots will have + * a type that is numerically higher. + */ + public int getType() { + return type; + } + + public String getTypeName() { + switch(type) { + case INVALID_TYPE: return "Invalid (?!?)"; + case UNKNOWN: return "Unknown"; + case SYSTEM_CLASS: return "System Class"; + case NATIVE_LOCAL: return "JNI Local"; + case NATIVE_STATIC: return "JNI Global"; + case THREAD_BLOCK: return "Thread Block"; + case BUSY_MONITOR: return "Busy Monitor"; + case JAVA_LOCAL: return "Java Local"; + case NATIVE_STACK: return "Native Stack (possibly Java local)"; + case JAVA_STATIC: return "Java Static"; + default: return "??"; + } + } + + /** + * Given two Root instances, return the one that is most interesting. + */ + public Root mostInteresting(Root other) { + if (other.type > this.type) { + return other; + } else { + return this; + } + } + + /** + * Get the object that's responsible for this root, if there is one. + * This will be null, a Thread object, or a Class object. + */ + public JavaHeapObject getReferer() { + return referer; + } + + /** + * @return the stack trace responsible for this root, or null if there + * is none. + */ + public StackTrace getStackTrace() { + return stackTrace; + } + + /** + * @return The index of this root in Snapshot.roots + */ + public int getIndex() { + return index; + } + + void resolve(Snapshot ss) { + if (refererId != 0) { + referer = ss.findThing(refererId); + } + if (stackTrace != null) { + stackTrace.resolve(ss); + } + } + + void setIndex(int i) { + index = i; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Snapshot.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Snapshot.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Snapshot.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/Snapshot.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,635 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +import java.lang.ref.SoftReference; +import java.util.*; + +import jdk.test.lib.hprof.parser.ReadBuffer; +import jdk.test.lib.hprof.util.Misc; + +/** + * + * @author Bill Foote + */ + +/** + * Represents a snapshot of the Java objects in the VM at one instant. + * This is the top-level "model" object read out of a single .hprof or .bod + * file. + */ + +public class Snapshot implements AutoCloseable { + + public static final long SMALL_ID_MASK = 0x0FFFFFFFFL; + public static final JavaThing[] EMPTY_JAVATHING_ARRAY = new JavaThing[0]; + + private static final JavaField[] EMPTY_FIELD_ARRAY = new JavaField[0]; + private static final JavaStatic[] EMPTY_STATIC_ARRAY = new JavaStatic[0]; + + // all heap objects + private Hashtable heapObjects = + new Hashtable(); + + private Hashtable fakeClasses = + new Hashtable(); + + // all Roots in this Snapshot + private Vector roots = new Vector(); + + // name-to-class map + private Map classes = + new TreeMap(); + + // new objects relative to a baseline - lazily initialized + private volatile Map newObjects; + + // allocation site traces for all objects - lazily initialized + private volatile Map siteTraces; + + // object-to-Root map for all objects + private Map rootsMap = + new HashMap(); + + // soft cache of finalizeable objects - lazily initialized + private SoftReference> finalizablesCache; + + // represents null reference + private JavaThing nullThing; + + // java.lang.ref.Reference class + private JavaClass weakReferenceClass; + // index of 'referent' field in java.lang.ref.Reference class + private int referentFieldIndex; + + // java.lang.Class class + private JavaClass javaLangClass; + // java.lang.String class + private JavaClass javaLangString; + // java.lang.ClassLoader class + private JavaClass javaLangClassLoader; + + // unknown "other" array class + private volatile JavaClass otherArrayType; + // Stuff to exclude from reachable query + private ReachableExcludes reachableExcludes; + // the underlying heap dump buffer + private ReadBuffer readBuf; + + // True iff some heap objects have isNew set + private boolean hasNewSet; + private boolean unresolvedObjectsOK; + + // whether object array instances have new style class or + // old style (element) class. + private boolean newStyleArrayClass; + + // object id size in the heap dump + private int identifierSize = 4; + + // minimum object size - accounts for object header in + // most Java virtual machines - we assume 2 identifierSize + // (which is true for Sun's hotspot JVM). + private int minimumObjectSize; + + public Snapshot(ReadBuffer buf) { + nullThing = new HackJavaValue("", 0); + readBuf = buf; + } + + public void setSiteTrace(JavaHeapObject obj, StackTrace trace) { + if (trace != null && trace.getFrames().length != 0) { + initSiteTraces(); + siteTraces.put(obj, trace); + } + } + + public StackTrace getSiteTrace(JavaHeapObject obj) { + if (siteTraces != null) { + return siteTraces.get(obj); + } else { + return null; + } + } + + public void setNewStyleArrayClass(boolean value) { + newStyleArrayClass = value; + } + + public boolean isNewStyleArrayClass() { + return newStyleArrayClass; + } + + public void setIdentifierSize(int size) { + identifierSize = size; + minimumObjectSize = 2 * size; + } + + public int getIdentifierSize() { + return identifierSize; + } + + public int getMinimumObjectSize() { + return minimumObjectSize; + } + + public void addHeapObject(long id, JavaHeapObject ho) { + heapObjects.put(makeId(id), ho); + } + + public void addRoot(Root r) { + r.setIndex(roots.size()); + roots.addElement(r); + } + + public void addClass(long id, JavaClass c) { + addHeapObject(id, c); + putInClassesMap(c); + } + + JavaClass addFakeInstanceClass(long classID, int instSize) { + // Create a fake class name based on ID. + String name = "unknown-class<@" + Misc.toHex(classID) + ">"; + + // Create fake fields convering the given instance size. + // Create as many as int type fields and for the left over + // size create byte type fields. + int numInts = instSize / 4; + int numBytes = instSize % 4; + JavaField[] fields = new JavaField[numInts + numBytes]; + int i; + for (i = 0; i < numInts; i++) { + fields[i] = new JavaField("unknown-field-" + i, "I"); + } + for (i = 0; i < numBytes; i++) { + fields[i + numInts] = new JavaField("unknown-field-" + + i + numInts, "B"); + } + + // Create fake instance class + JavaClass c = new JavaClass(name, 0, 0, 0, 0, fields, + EMPTY_STATIC_ARRAY, instSize); + // Add the class + addFakeClass(makeId(classID), c); + return c; + } + + + /** + * @return true iff it's possible that some JavaThing instances might + * isNew set + * + * @see JavaThing.isNew() + */ + public boolean getHasNewSet() { + return hasNewSet; + } + + // + // Used in the body of resolve() + // + private static class MyVisitor extends AbstractJavaHeapObjectVisitor { + JavaHeapObject t; + public void visit(JavaHeapObject other) { + other.addReferenceFrom(t); + } + } + + // To show heap parsing progress, we print a '.' after this limit + private static final int DOT_LIMIT = 5000; + + /** + * Called after reading complete, to initialize the structure + */ + public void resolve(boolean calculateRefs) { + System.out.println("Resolving " + heapObjects.size() + " objects..."); + + // First, resolve the classes. All classes must be resolved before + // we try any objects, because the objects use classes in their + // resolution. + javaLangClass = findClass("java.lang.Class"); + if (javaLangClass == null) { + System.out.println("WARNING: hprof file does not include java.lang.Class!"); + javaLangClass = new JavaClass("java.lang.Class", 0, 0, 0, 0, + EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); + addFakeClass(javaLangClass); + } + javaLangString = findClass("java.lang.String"); + if (javaLangString == null) { + System.out.println("WARNING: hprof file does not include java.lang.String!"); + javaLangString = new JavaClass("java.lang.String", 0, 0, 0, 0, + EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); + addFakeClass(javaLangString); + } + javaLangClassLoader = findClass("java.lang.ClassLoader"); + if (javaLangClassLoader == null) { + System.out.println("WARNING: hprof file does not include java.lang.ClassLoader!"); + javaLangClassLoader = new JavaClass("java.lang.ClassLoader", 0, 0, 0, 0, + EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); + addFakeClass(javaLangClassLoader); + } + + for (JavaHeapObject t : heapObjects.values()) { + if (t instanceof JavaClass) { + t.resolve(this); + } + } + + // Now, resolve everything else. + for (JavaHeapObject t : heapObjects.values()) { + if (!(t instanceof JavaClass)) { + t.resolve(this); + } + } + + heapObjects.putAll(fakeClasses); + fakeClasses.clear(); + + weakReferenceClass = findClass("java.lang.ref.Reference"); + referentFieldIndex = 0; + if (weakReferenceClass != null) { + JavaField[] fields = weakReferenceClass.getFieldsForInstance(); + for (int i = 0; i < fields.length; i++) { + if ("referent".equals(fields[i].getName())) { + referentFieldIndex = i; + break; + } + } + } + + if (calculateRefs) { + calculateReferencesToObjects(); + System.out.print("Eliminating duplicate references"); + System.out.flush(); + // This println refers to the *next* step + } + int count = 0; + for (JavaHeapObject t : heapObjects.values()) { + t.setupReferers(); + ++count; + if (calculateRefs && count % DOT_LIMIT == 0) { + System.out.print("."); + System.out.flush(); + } + } + if (calculateRefs) { + System.out.println(""); + } + + // to ensure that Iterator.remove() on getClasses() + // result will throw exception.. + classes = Collections.unmodifiableMap(classes); + } + + private void calculateReferencesToObjects() { + System.out.print("Chasing references, expect " + + (heapObjects.size() / DOT_LIMIT) + " dots"); + System.out.flush(); + int count = 0; + MyVisitor visitor = new MyVisitor(); + for (JavaHeapObject t : heapObjects.values()) { + visitor.t = t; + // call addReferenceFrom(t) on all objects t references: + t.visitReferencedObjects(visitor); + ++count; + if (count % DOT_LIMIT == 0) { + System.out.print("."); + System.out.flush(); + } + } + System.out.println(); + for (Root r : roots) { + r.resolve(this); + JavaHeapObject t = findThing(r.getId()); + if (t != null) { + t.addReferenceFromRoot(r); + } + } + } + + public void markNewRelativeTo(Snapshot baseline) { + hasNewSet = true; + for (JavaHeapObject t : heapObjects.values()) { + boolean isNew; + long thingID = t.getId(); + if (thingID == 0L || thingID == -1L) { + isNew = false; + } else { + JavaThing other = baseline.findThing(t.getId()); + if (other == null) { + isNew = true; + } else { + isNew = !t.isSameTypeAs(other); + } + } + t.setNew(isNew); + } + } + + public Enumeration getThings() { + return heapObjects.elements(); + } + + + public JavaHeapObject findThing(long id) { + Number idObj = makeId(id); + JavaHeapObject jho = heapObjects.get(idObj); + return jho != null? jho : fakeClasses.get(idObj); + } + + public JavaHeapObject findThing(String id) { + return findThing(Misc.parseHex(id)); + } + + public JavaClass findClass(String name) { + if (name.startsWith("0x")) { + return (JavaClass) findThing(name); + } else { + return classes.get(name); + } + } + + /** + * Return an Iterator of all of the classes in this snapshot. + **/ + public Iterator getClasses() { + // note that because classes is a TreeMap + // classes are already sorted by name + return classes.values().iterator(); + } + + public JavaClass[] getClassesArray() { + JavaClass[] res = new JavaClass[classes.size()]; + classes.values().toArray(res); + return res; + } + + public synchronized Enumeration getFinalizerObjects() { + Vector obj; + if (finalizablesCache != null && + (obj = finalizablesCache.get()) != null) { + return obj.elements(); + } + + JavaClass clazz = findClass("java.lang.ref.Finalizer"); + JavaObject queue = (JavaObject) clazz.getStaticField("queue"); + JavaThing tmp = queue.getField("head"); + Vector finalizables = new Vector(); + if (tmp != getNullThing()) { + JavaObject head = (JavaObject) tmp; + while (true) { + JavaHeapObject referent = (JavaHeapObject) head.getField("referent"); + JavaThing next = head.getField("next"); + if (next == getNullThing() || next.equals(head)) { + break; + } + head = (JavaObject) next; + finalizables.add(referent); + } + } + finalizablesCache = new SoftReference>(finalizables); + return finalizables.elements(); + } + + public Enumeration getRoots() { + return roots.elements(); + } + + public Root[] getRootsArray() { + Root[] res = new Root[roots.size()]; + roots.toArray(res); + return res; + } + + public Root getRootAt(int i) { + return roots.elementAt(i); + } + + public ReferenceChain[] + rootsetReferencesTo(JavaHeapObject target, boolean includeWeak) { + Vector fifo = new Vector(); // This is slow... A real fifo would help + // Must be a fifo to go breadth-first + Hashtable visited = new Hashtable(); + // Objects are added here right after being added to fifo. + Vector result = new Vector(); + visited.put(target, target); + fifo.addElement(new ReferenceChain(target, null)); + + while (fifo.size() > 0) { + ReferenceChain chain = fifo.elementAt(0); + fifo.removeElementAt(0); + JavaHeapObject curr = chain.getObj(); + if (curr.getRoot() != null) { + result.addElement(chain); + // Even though curr is in the rootset, we want to explore its + // referers, because they might be more interesting. + } + Enumeration referers = curr.getReferers(); + while (referers.hasMoreElements()) { + JavaHeapObject t = (JavaHeapObject) referers.nextElement(); + if (t != null && !visited.containsKey(t)) { + if (includeWeak || !t.refersOnlyWeaklyTo(this, curr)) { + visited.put(t, t); + fifo.addElement(new ReferenceChain(t, chain)); + } + } + } + } + + ReferenceChain[] realResult = new ReferenceChain[result.size()]; + for (int i = 0; i < result.size(); i++) { + realResult[i] = result.elementAt(i); + } + return realResult; + } + + public boolean getUnresolvedObjectsOK() { + return unresolvedObjectsOK; + } + + public void setUnresolvedObjectsOK(boolean v) { + unresolvedObjectsOK = v; + } + + public JavaClass getWeakReferenceClass() { + return weakReferenceClass; + } + + public int getReferentFieldIndex() { + return referentFieldIndex; + } + + public JavaThing getNullThing() { + return nullThing; + } + + public void setReachableExcludes(ReachableExcludes e) { + reachableExcludes = e; + } + + public ReachableExcludes getReachableExcludes() { + return reachableExcludes; + } + + // package privates + void addReferenceFromRoot(Root r, JavaHeapObject obj) { + Root root = rootsMap.get(obj); + if (root == null) { + rootsMap.put(obj, r); + } else { + rootsMap.put(obj, root.mostInteresting(r)); + } + } + + Root getRoot(JavaHeapObject obj) { + return rootsMap.get(obj); + } + + JavaClass getJavaLangClass() { + return javaLangClass; + } + + JavaClass getJavaLangString() { + return javaLangString; + } + + JavaClass getJavaLangClassLoader() { + return javaLangClassLoader; + } + + JavaClass getOtherArrayType() { + if (otherArrayType == null) { + synchronized(this) { + if (otherArrayType == null) { + addFakeClass(new JavaClass("[", 0, 0, 0, 0, + EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, + 0)); + otherArrayType = findClass("["); + } + } + } + return otherArrayType; + } + + JavaClass getArrayClass(String elementSignature) { + JavaClass clazz; + synchronized(classes) { + clazz = findClass("[" + elementSignature); + if (clazz == null) { + clazz = new JavaClass("[" + elementSignature, 0, 0, 0, 0, + EMPTY_FIELD_ARRAY, EMPTY_STATIC_ARRAY, 0); + addFakeClass(clazz); + // This is needed because the JDK only creates Class structures + // for array element types, not the arrays themselves. For + // analysis, though, we need to pretend that there's a + // JavaClass for the array type, too. + } + } + return clazz; + } + + ReadBuffer getReadBuffer() { + return readBuf; + } + + void setNew(JavaHeapObject obj, boolean isNew) { + initNewObjects(); + if (isNew) { + newObjects.put(obj, Boolean.TRUE); + } + } + + boolean isNew(JavaHeapObject obj) { + if (newObjects != null) { + return newObjects.get(obj) != null; + } else { + return false; + } + } + + // Internals only below this point + private Number makeId(long id) { + if (identifierSize == 4) { + return (int)id; + } else { + return id; + } + } + + private void putInClassesMap(JavaClass c) { + String name = c.getName(); + if (classes.containsKey(name)) { + // more than one class can have the same name + // if so, create a unique name by appending + // - and id string to it. + name += "-" + c.getIdString(); + } + classes.put(c.getName(), c); + } + + private void addFakeClass(JavaClass c) { + putInClassesMap(c); + c.resolve(this); + } + + private void addFakeClass(Number id, JavaClass c) { + fakeClasses.put(id, c); + addFakeClass(c); + } + + private synchronized void initNewObjects() { + if (newObjects == null) { + synchronized (this) { + if (newObjects == null) { + newObjects = new HashMap(); + } + } + } + } + + private synchronized void initSiteTraces() { + if (siteTraces == null) { + synchronized (this) { + if (siteTraces == null) { + siteTraces = new HashMap(); + } + } + } + } + + @Override + public void close() throws Exception { + readBuf.close(); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackFrame.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackFrame.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackFrame.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackFrame.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * + * @author Bill Foote + */ + + +/** + * Represents a stack frame. + */ + +public class StackFrame { + + // + // Values for the lineNumber data member. These are the same + // as the values used in the JDK 1.2 heap dump file. + // + public final static int LINE_NUMBER_UNKNOWN = -1; + public final static int LINE_NUMBER_COMPILED = -2; + public final static int LINE_NUMBER_NATIVE = -3; + + private String methodName; + private String methodSignature; + private String className; + private String sourceFileName; + private int lineNumber; + + public StackFrame(String methodName, String methodSignature, + String className, String sourceFileName, int lineNumber) { + this.methodName = methodName; + this.methodSignature = methodSignature; + this.className = className; + this.sourceFileName = sourceFileName; + this.lineNumber = lineNumber; + } + + public void resolve(Snapshot snapshot) { + } + + public String getMethodName() { + return methodName; + } + + public String getMethodSignature() { + return methodSignature; + } + + public String getClassName() { + return className; + } + + public String getSourceFileName() { + return sourceFileName; + } + + public String getLineNumber() { + switch(lineNumber) { + case LINE_NUMBER_UNKNOWN: + return "(unknown)"; + case LINE_NUMBER_COMPILED: + return "(compiled method)"; + case LINE_NUMBER_NATIVE: + return "(native method)"; + default: + return Integer.toString(lineNumber, 10); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackTrace.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackTrace.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackTrace.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/model/StackTrace.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.model; + +/** + * + * @author Bill Foote + */ + + +/** + * Represents a stack trace, that is, an ordered collection of stack frames. + */ + +public class StackTrace { + + private StackFrame[] frames; + + public StackTrace(StackFrame[] frames) { + this.frames = frames; + } + + /** + * @param depth. The minimum reasonable depth is 1. + * + * @return a (possibly new) StackTrace that is limited to depth. + */ + public StackTrace traceForDepth(int depth) { + if (depth >= frames.length) { + return this; + } else { + StackFrame[] f = new StackFrame[depth]; + System.arraycopy(frames, 0, f, 0, depth); + return new StackTrace(f); + } + } + + public void resolve(Snapshot snapshot) { + for (int i = 0; i < frames.length; i++) { + frames[i].resolve(snapshot); + } + } + + public StackFrame[] getFrames() { + return frames; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/FileReadBuffer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * Implementation of ReadBuffer using a RandomAccessFile + * + * @author A. Sundararajan + */ +class FileReadBuffer implements ReadBuffer { + // underlying file to read + private RandomAccessFile file; + + FileReadBuffer(RandomAccessFile file) { + this.file = file; + } + + private void seek(long pos) throws IOException { + file.getChannel().position(pos); + } + + public synchronized void get(long pos, byte[] buf) throws IOException { + seek(pos); + file.read(buf); + } + + @Override + public synchronized char getChar(long pos) throws IOException { + seek(pos); + return file.readChar(); + } + + @Override + public synchronized byte getByte(long pos) throws IOException { + seek(pos); + return (byte) file.read(); + } + + @Override + public synchronized short getShort(long pos) throws IOException { + seek(pos); + return file.readShort(); + } + + @Override + public synchronized int getInt(long pos) throws IOException { + seek(pos); + return file.readInt(); + } + + @Override + public synchronized long getLong(long pos) throws IOException { + seek(pos); + return file.readLong(); + } + + @Override + public void close() throws Exception { + file.close(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/HprofReader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,926 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.*; +import java.util.Date; +import java.util.Hashtable; +import java.util.Map; +import jdk.test.lib.hprof.model.ArrayTypeCodes; +import jdk.test.lib.hprof.model.*; + +/** + * Object that's used to read a hprof file. + * + * @author Bill Foote + */ + +public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes { + + final static int MAGIC_NUMBER = 0x4a415641; + // That's "JAVA", the first part of "JAVA PROFILE ..." + private final static String[] VERSIONS = { + " PROFILE 1.0\0", + " PROFILE 1.0.1\0", + " PROFILE 1.0.2\0", + }; + + private final static int VERSION_JDK12BETA3 = 0; + private final static int VERSION_JDK12BETA4 = 1; + private final static int VERSION_JDK6 = 2; + // These version numbers are indices into VERSIONS. The instance data + // member version is set to one of these, and it drives decisions when + // reading the file. + // + // Version 1.0.1 added HPROF_GC_PRIM_ARRAY_DUMP, which requires no + // version-sensitive parsing. + // + // Version 1.0.1 changed the type of a constant pool entry from a signature + // to a typecode. + // + // Version 1.0.2 added HPROF_HEAP_DUMP_SEGMENT and HPROF_HEAP_DUMP_END + // to allow a large heap to be dumped as a sequence of heap dump segments. + // + // The HPROF agent in J2SE 1.2 through to 5.0 generate a version 1.0.1 + // file. In Java SE 6.0 the version is either 1.0.1 or 1.0.2 depending on + // the size of the heap (normally it will be 1.0.1 but for multi-GB + // heaps the heap dump will not fit in a HPROF_HEAP_DUMP record so the + // dump is generated as version 1.0.2). + + // + // Record types: + // + static final int HPROF_UTF8 = 0x01; + static final int HPROF_LOAD_CLASS = 0x02; + static final int HPROF_UNLOAD_CLASS = 0x03; + static final int HPROF_FRAME = 0x04; + static final int HPROF_TRACE = 0x05; + static final int HPROF_ALLOC_SITES = 0x06; + static final int HPROF_HEAP_SUMMARY = 0x07; + + static final int HPROF_START_THREAD = 0x0a; + static final int HPROF_END_THREAD = 0x0b; + + static final int HPROF_HEAP_DUMP = 0x0c; + + static final int HPROF_CPU_SAMPLES = 0x0d; + static final int HPROF_CONTROL_SETTINGS = 0x0e; + static final int HPROF_LOCKSTATS_WAIT_TIME = 0x10; + static final int HPROF_LOCKSTATS_HOLD_TIME = 0x11; + + static final int HPROF_GC_ROOT_UNKNOWN = 0xff; + static final int HPROF_GC_ROOT_JNI_GLOBAL = 0x01; + static final int HPROF_GC_ROOT_JNI_LOCAL = 0x02; + static final int HPROF_GC_ROOT_JAVA_FRAME = 0x03; + static final int HPROF_GC_ROOT_NATIVE_STACK = 0x04; + static final int HPROF_GC_ROOT_STICKY_CLASS = 0x05; + static final int HPROF_GC_ROOT_THREAD_BLOCK = 0x06; + static final int HPROF_GC_ROOT_MONITOR_USED = 0x07; + static final int HPROF_GC_ROOT_THREAD_OBJ = 0x08; + + static final int HPROF_GC_CLASS_DUMP = 0x20; + static final int HPROF_GC_INSTANCE_DUMP = 0x21; + static final int HPROF_GC_OBJ_ARRAY_DUMP = 0x22; + static final int HPROF_GC_PRIM_ARRAY_DUMP = 0x23; + + static final int HPROF_HEAP_DUMP_SEGMENT = 0x1c; + static final int HPROF_HEAP_DUMP_END = 0x2c; + + private final static int T_CLASS = 2; + + private int version; // The version of .hprof being read + + private int debugLevel; + private long currPos; // Current position in the file + + private int dumpsToSkip; + private boolean callStack; // If true, read the call stack of objects + + private int identifierSize; // Size, in bytes, of identifiers. + private Hashtable names; + + // Hashtable, used to map the thread sequence number + // (aka "serial number") to the thread object ID for + // HPROF_GC_ROOT_THREAD_OBJ. ThreadObject is a trivial inner class, + // at the end of this file. + private Hashtable threadObjects; + + // Hashtable, maps class object ID to class name + // (with / converted to .) + private Hashtable classNameFromObjectID; + + // Hashtable, maps class serial # to class object ID + private Hashtable classNameFromSerialNo; + + // Hashtable maps stack frame ID to StackFrame. + // Null if we're not tracking them. + private Hashtable stackFrames; + + // Hashtable maps stack frame ID to StackTrace + // Null if we're not tracking them. + private Hashtable stackTraces; + + private Snapshot snapshot; + + public static boolean verifyMagicNumber(int numberRead) { + return (numberRead == MAGIC_NUMBER); + } + + public HprofReader(String fileName, PositionDataInputStream in, + int dumpNumber, boolean callStack, int debugLevel) + throws IOException { + super(in); + RandomAccessFile file = new RandomAccessFile(fileName, "r"); + this.snapshot = new Snapshot(MappedReadBuffer.create(file)); + this.dumpsToSkip = dumpNumber - 1; + this.callStack = callStack; + this.debugLevel = debugLevel; + names = new Hashtable(); + threadObjects = new Hashtable(43); + classNameFromObjectID = new Hashtable(); + if (callStack) { + stackFrames = new Hashtable(43); + stackTraces = new Hashtable(43); + classNameFromSerialNo = new Hashtable(); + } + } + + public Snapshot read() throws IOException { + currPos = 4; // 4 because of the magic number + version = readVersionHeader(); + identifierSize = in.readInt(); + snapshot.setIdentifierSize(identifierSize); + if (version >= VERSION_JDK12BETA4) { + snapshot.setNewStyleArrayClass(true); + } else { + snapshot.setNewStyleArrayClass(false); + } + + currPos += 4; + if (identifierSize != 4 && identifierSize != 8) { + throw new IOException("I'm sorry, but I can't deal with an identifier size of " + identifierSize + ". I can only deal with 4 or 8."); + } + System.out.println("Dump file created " + (new Date(in.readLong()))); + currPos += 8; + + for (;;) { + int type; + try { + type = in.readUnsignedByte(); + } catch (EOFException ignored) { + break; + } + in.readInt(); // Timestamp of this record + // Length of record: readInt() will return negative value for record + // length >2GB. so store 32bit value in long to keep it unsigned. + long length = in.readInt() & 0xffffffffL; + if (debugLevel > 0) { + System.out.println("Read record type " + type + + ", length " + length + + " at position " + toHex(currPos)); + } + if (length < 0) { + throw new IOException("Bad record length of " + length + + " at byte " + toHex(currPos+5) + + " of file."); + } + currPos += 9 + length; + switch (type) { + case HPROF_UTF8: { + long id = readID(); + byte[] chars = new byte[(int)length - identifierSize]; + in.readFully(chars); + names.put(id, new String(chars)); + break; + } + case HPROF_LOAD_CLASS: { + int serialNo = in.readInt(); // Not used + long classID = readID(); + int stackTraceSerialNo = in.readInt(); + long classNameID = readID(); + Long classIdI = classID; + String nm = getNameFromID(classNameID).replace('/', '.'); + classNameFromObjectID.put(classIdI, nm); + if (classNameFromSerialNo != null) { + classNameFromSerialNo.put(serialNo, nm); + } + break; + } + + case HPROF_HEAP_DUMP: { + if (dumpsToSkip <= 0) { + try { + readHeapDump(length, currPos); + } catch (EOFException exp) { + handleEOF(exp, snapshot); + } + if (debugLevel > 0) { + System.out.println(" Finished processing instances in heap dump."); + } + return snapshot; + } else { + dumpsToSkip--; + skipBytes(length); + } + break; + } + + case HPROF_HEAP_DUMP_END: { + if (version >= VERSION_JDK6) { + if (dumpsToSkip <= 0) { + skipBytes(length); // should be no-op + return snapshot; + } else { + // skip this dump (of the end record for a sequence of dump segments) + dumpsToSkip--; + } + } else { + // HPROF_HEAP_DUMP_END only recognized in >= 1.0.2 + warn("Ignoring unrecognized record type " + type); + } + skipBytes(length); // should be no-op + break; + } + + case HPROF_HEAP_DUMP_SEGMENT: { + if (version >= VERSION_JDK6) { + if (dumpsToSkip <= 0) { + try { + // read the dump segment + readHeapDump(length, currPos); + } catch (EOFException exp) { + handleEOF(exp, snapshot); + } + } else { + // all segments comprising the heap dump will be skipped + skipBytes(length); + } + } else { + // HPROF_HEAP_DUMP_SEGMENT only recognized in >= 1.0.2 + warn("Ignoring unrecognized record type " + type); + skipBytes(length); + } + break; + } + + case HPROF_FRAME: { + if (stackFrames == null) { + skipBytes(length); + } else { + long id = readID(); + String methodName = getNameFromID(readID()); + String methodSig = getNameFromID(readID()); + String sourceFile = getNameFromID(readID()); + int classSer = in.readInt(); + String className = classNameFromSerialNo.get(classSer); + int lineNumber = in.readInt(); + if (lineNumber < StackFrame.LINE_NUMBER_NATIVE) { + warn("Weird stack frame line number: " + lineNumber); + lineNumber = StackFrame.LINE_NUMBER_UNKNOWN; + } + stackFrames.put(id, + new StackFrame(methodName, methodSig, + className, sourceFile, + lineNumber)); + } + break; + } + case HPROF_TRACE: { + if (stackTraces == null) { + skipBytes(length); + } else { + int serialNo = in.readInt(); + int threadSeq = in.readInt(); // Not used + StackFrame[] frames = new StackFrame[in.readInt()]; + for (int i = 0; i < frames.length; i++) { + long fid = readID(); + frames[i] = stackFrames.get(fid); + if (frames[i] == null) { + throw new IOException("Stack frame " + toHex(fid) + " not found"); + } + } + stackTraces.put(serialNo, + new StackTrace(frames)); + } + break; + } + case HPROF_UNLOAD_CLASS: + case HPROF_ALLOC_SITES: + case HPROF_START_THREAD: + case HPROF_END_THREAD: + case HPROF_HEAP_SUMMARY: + case HPROF_CPU_SAMPLES: + case HPROF_CONTROL_SETTINGS: + case HPROF_LOCKSTATS_WAIT_TIME: + case HPROF_LOCKSTATS_HOLD_TIME: + { + // Ignore these record types + skipBytes(length); + break; + } + default: { + skipBytes(length); + warn("Ignoring unrecognized record type " + type); + } + } + } + + return snapshot; + } + + public String printStackTraces() { + StringBuffer output = new StringBuffer(); + for (Map.Entry entry : stackTraces.entrySet()) { + StackFrame[] frames = entry.getValue().getFrames(); + output.append("SerialNo " + entry.getKey() + "\n"); + for (int i = 0; i < frames.length; i++) { + output.append(" " + frames[i].getClassName() + "." + frames[i].getMethodName() + + frames[i].getMethodSignature() + " (" + frames[i].getSourceFileName() + + ":" + frames[i].getLineNumber() + ")" + "\n"); + } + } + + System.out.println(output); + return output.toString(); + } + + private void skipBytes(long length) throws IOException { + while (length > 0) { + long skipped = in.skip(length); + if (skipped == 0) { + // EOF or other problem, throw exception + throw new EOFException("Couldn't skip enough bytes"); + } + length -= skipped; + } + } + + private int readVersionHeader() throws IOException { + int candidatesLeft = VERSIONS.length; + boolean[] matched = new boolean[VERSIONS.length]; + for (int i = 0; i < candidatesLeft; i++) { + matched[i] = true; + } + + int pos = 0; + while (candidatesLeft > 0) { + char c = (char) in.readByte(); + currPos++; + for (int i = 0; i < VERSIONS.length; i++) { + if (matched[i]) { + if (c != VERSIONS[i].charAt(pos)) { // Not matched + matched[i] = false; + --candidatesLeft; + } else if (pos == VERSIONS[i].length() - 1) { // Full match + return i; + } + } + } + ++pos; + } + throw new IOException("Version string not recognized at byte " + (pos+3)); + } + + private void readHeapDump(long bytesLeft, long posAtEnd) throws IOException { + while (bytesLeft > 0) { + int type = in.readUnsignedByte(); + if (debugLevel > 0) { + System.out.println(" Read heap sub-record type " + type + + " at position " + + toHex(posAtEnd - bytesLeft)); + } + bytesLeft--; + switch(type) { + case HPROF_GC_ROOT_UNKNOWN: { + long id = readID(); + bytesLeft -= identifierSize; + snapshot.addRoot(new Root(id, 0, Root.UNKNOWN, "")); + break; + } + case HPROF_GC_ROOT_THREAD_OBJ: { + long id = readID(); + int threadSeq = in.readInt(); + int stackSeq = in.readInt(); + bytesLeft -= identifierSize + 8; + threadObjects.put(threadSeq, + new ThreadObject(id, stackSeq)); + break; + } + case HPROF_GC_ROOT_JNI_GLOBAL: { + long id = readID(); + long globalRefId = readID(); // Ignored, for now + bytesLeft -= 2*identifierSize; + snapshot.addRoot(new Root(id, 0, Root.NATIVE_STATIC, "")); + break; + } + case HPROF_GC_ROOT_JNI_LOCAL: { + long id = readID(); + int threadSeq = in.readInt(); + int depth = in.readInt(); + bytesLeft -= identifierSize + 8; + ThreadObject to = getThreadObjectFromSequence(threadSeq); + StackTrace st = getStackTraceFromSerial(to.stackSeq); + if (st != null) { + st = st.traceForDepth(depth+1); + } + snapshot.addRoot(new Root(id, to.threadId, + Root.NATIVE_LOCAL, "", st)); + break; + } + case HPROF_GC_ROOT_JAVA_FRAME: { + long id = readID(); + int threadSeq = in.readInt(); + int depth = in.readInt(); + bytesLeft -= identifierSize + 8; + ThreadObject to = getThreadObjectFromSequence(threadSeq); + StackTrace st = getStackTraceFromSerial(to.stackSeq); + if (st != null) { + st = st.traceForDepth(depth+1); + } + snapshot.addRoot(new Root(id, to.threadId, + Root.JAVA_LOCAL, "", st)); + break; + } + case HPROF_GC_ROOT_NATIVE_STACK: { + long id = readID(); + int threadSeq = in.readInt(); + bytesLeft -= identifierSize + 4; + ThreadObject to = getThreadObjectFromSequence(threadSeq); + StackTrace st = getStackTraceFromSerial(to.stackSeq); + snapshot.addRoot(new Root(id, to.threadId, + Root.NATIVE_STACK, "", st)); + break; + } + case HPROF_GC_ROOT_STICKY_CLASS: { + long id = readID(); + bytesLeft -= identifierSize; + snapshot.addRoot(new Root(id, 0, Root.SYSTEM_CLASS, "")); + break; + } + case HPROF_GC_ROOT_THREAD_BLOCK: { + long id = readID(); + int threadSeq = in.readInt(); + bytesLeft -= identifierSize + 4; + ThreadObject to = getThreadObjectFromSequence(threadSeq); + StackTrace st = getStackTraceFromSerial(to.stackSeq); + snapshot.addRoot(new Root(id, to.threadId, + Root.THREAD_BLOCK, "", st)); + break; + } + case HPROF_GC_ROOT_MONITOR_USED: { + long id = readID(); + bytesLeft -= identifierSize; + snapshot.addRoot(new Root(id, 0, Root.BUSY_MONITOR, "")); + break; + } + case HPROF_GC_CLASS_DUMP: { + int bytesRead = readClass(); + bytesLeft -= bytesRead; + break; + } + case HPROF_GC_INSTANCE_DUMP: { + int bytesRead = readInstance(); + bytesLeft -= bytesRead; + break; + } + case HPROF_GC_OBJ_ARRAY_DUMP: { + long bytesRead = readArray(false); + bytesLeft -= bytesRead; + break; + } + case HPROF_GC_PRIM_ARRAY_DUMP: { + long bytesRead = readArray(true); + bytesLeft -= bytesRead; + break; + } + default: { + throw new IOException("Unrecognized heap dump sub-record type: " + type); + } + } + } + if (bytesLeft != 0) { + warn("Error reading heap dump or heap dump segment: Byte count is " + bytesLeft + " instead of 0"); + skipBytes(bytesLeft); + } + if (debugLevel > 0) { + System.out.println(" Finished heap sub-records."); + } + } + + private long readID() throws IOException { + return (identifierSize == 4)? + (Snapshot.SMALL_ID_MASK & (long)in.readInt()) : in.readLong(); + } + + // + // Read a java value. If result is non-null, it's expected to be an + // array of one element. We use it to fake multiple return values. + // @returns the number of bytes read + // + private int readValue(JavaThing[] resultArr) throws IOException { + byte type = in.readByte(); + return 1 + readValueForType(type, resultArr); + } + + private int readValueForType(byte type, JavaThing[] resultArr) + throws IOException { + if (version >= VERSION_JDK12BETA4) { + type = signatureFromTypeId(type); + } + return readValueForTypeSignature(type, resultArr); + } + + private int readValueForTypeSignature(byte type, JavaThing[] resultArr) + throws IOException { + switch (type) { + case '[': + case 'L': { + long id = readID(); + if (resultArr != null) { + resultArr[0] = new JavaObjectRef(id); + } + return identifierSize; + } + case 'Z': { + int b = in.readByte(); + if (b != 0 && b != 1) { + warn("Illegal boolean value read"); + } + if (resultArr != null) { + resultArr[0] = new JavaBoolean(b != 0); + } + return 1; + } + case 'B': { + byte b = in.readByte(); + if (resultArr != null) { + resultArr[0] = new JavaByte(b); + } + return 1; + } + case 'S': { + short s = in.readShort(); + if (resultArr != null) { + resultArr[0] = new JavaShort(s); + } + return 2; + } + case 'C': { + char ch = in.readChar(); + if (resultArr != null) { + resultArr[0] = new JavaChar(ch); + } + return 2; + } + case 'I': { + int val = in.readInt(); + if (resultArr != null) { + resultArr[0] = new JavaInt(val); + } + return 4; + } + case 'J': { + long val = in.readLong(); + if (resultArr != null) { + resultArr[0] = new JavaLong(val); + } + return 8; + } + case 'F': { + float val = in.readFloat(); + if (resultArr != null) { + resultArr[0] = new JavaFloat(val); + } + return 4; + } + case 'D': { + double val = in.readDouble(); + if (resultArr != null) { + resultArr[0] = new JavaDouble(val); + } + return 8; + } + default: { + throw new IOException("Bad value signature: " + type); + } + } + } + + private ThreadObject getThreadObjectFromSequence(int threadSeq) + throws IOException { + ThreadObject to = threadObjects.get(threadSeq); + if (to == null) { + throw new IOException("Thread " + threadSeq + + " not found for JNI local ref"); + } + return to; + } + + private String getNameFromID(long id) throws IOException { + return getNameFromID(Long.valueOf(id)); + } + + private String getNameFromID(Long id) throws IOException { + if (id.longValue() == 0L) { + return ""; + } + String result = names.get(id); + if (result == null) { + warn("Name not found at " + toHex(id.longValue())); + return "unresolved name " + toHex(id.longValue()); + } + return result; + } + + private StackTrace getStackTraceFromSerial(int ser) throws IOException { + if (stackTraces == null) { + return null; + } + StackTrace result = stackTraces.get(ser); + if (result == null) { + warn("Stack trace not found for serial # " + ser); + } + return result; + } + + // + // Handle a HPROF_GC_CLASS_DUMP + // Return number of bytes read + // + private int readClass() throws IOException { + long id = readID(); + StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); + long superId = readID(); + long classLoaderId = readID(); + long signersId = readID(); + long protDomainId = readID(); + long reserved1 = readID(); + long reserved2 = readID(); + int instanceSize = in.readInt(); + int bytesRead = 7 * identifierSize + 8; + + int numConstPoolEntries = in.readUnsignedShort(); + bytesRead += 2; + for (int i = 0; i < numConstPoolEntries; i++) { + int index = in.readUnsignedShort(); // unused + bytesRead += 2; + bytesRead += readValue(null); // We ignore the values + } + + int numStatics = in.readUnsignedShort(); + bytesRead += 2; + JavaThing[] valueBin = new JavaThing[1]; + JavaStatic[] statics = new JavaStatic[numStatics]; + for (int i = 0; i < numStatics; i++) { + long nameId = readID(); + bytesRead += identifierSize; + byte type = in.readByte(); + bytesRead++; + bytesRead += readValueForType(type, valueBin); + String fieldName = getNameFromID(nameId); + if (version >= VERSION_JDK12BETA4) { + type = signatureFromTypeId(type); + } + String signature = "" + ((char) type); + JavaField f = new JavaField(fieldName, signature); + statics[i] = new JavaStatic(f, valueBin[0]); + } + + int numFields = in.readUnsignedShort(); + bytesRead += 2; + JavaField[] fields = new JavaField[numFields]; + for (int i = 0; i < numFields; i++) { + long nameId = readID(); + bytesRead += identifierSize; + byte type = in.readByte(); + bytesRead++; + String fieldName = getNameFromID(nameId); + if (version >= VERSION_JDK12BETA4) { + type = signatureFromTypeId(type); + } + String signature = "" + ((char) type); + fields[i] = new JavaField(fieldName, signature); + } + String name = classNameFromObjectID.get(id); + if (name == null) { + warn("Class name not found for " + toHex(id)); + name = "unknown-name@" + toHex(id); + } + JavaClass c = new JavaClass(id, name, superId, classLoaderId, signersId, + protDomainId, fields, statics, + instanceSize); + snapshot.addClass(id, c); + snapshot.setSiteTrace(c, stackTrace); + + return bytesRead; + } + + private String toHex(long addr) { + return jdk.test.lib.hprof.util.Misc.toHex(addr); + } + + // + // Handle a HPROF_GC_INSTANCE_DUMP + // Return number of bytes read + // + private int readInstance() throws IOException { + long start = in.position(); + long id = readID(); + StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); + long classID = readID(); + JavaClass searchedClass = snapshot.findClass( + "0x" + Long.toHexString(classID)); + if (searchedClass == null) { + throw new IOException( + "Class Record for 0x" + Long.toHexString(classID) + " not found"); + } + int bytesFollowing = in.readInt(); + int bytesRead = (2 * identifierSize) + 8 + bytesFollowing; + JavaObject jobj = new JavaObject(classID, start); + skipBytes(bytesFollowing); + snapshot.addHeapObject(id, jobj); + snapshot.setSiteTrace(jobj, stackTrace); + return bytesRead; + } + + // + // Handle a HPROF_GC_OBJ_ARRAY_DUMP or HPROF_GC_PRIM_ARRAY_DUMP + // Return number of bytes read + // + private long readArray(boolean isPrimitive) throws IOException { + long start = in.position(); + long id = readID(); + StackTrace stackTrace = getStackTraceFromSerial(in.readInt()); + int num = in.readInt(); + long bytesRead = identifierSize + 8; + long elementClassID; + if (isPrimitive) { + elementClassID = in.readByte(); + bytesRead++; + } else { + elementClassID = readID(); + bytesRead += identifierSize; + } + + // Check for primitive arrays: + byte primitiveSignature = 0x00; + int elSize = 0; + if (isPrimitive || version < VERSION_JDK12BETA4) { + switch ((int)elementClassID) { + case T_BOOLEAN: { + primitiveSignature = (byte) 'Z'; + elSize = 1; + break; + } + case T_CHAR: { + primitiveSignature = (byte) 'C'; + elSize = 2; + break; + } + case T_FLOAT: { + primitiveSignature = (byte) 'F'; + elSize = 4; + break; + } + case T_DOUBLE: { + primitiveSignature = (byte) 'D'; + elSize = 8; + break; + } + case T_BYTE: { + primitiveSignature = (byte) 'B'; + elSize = 1; + break; + } + case T_SHORT: { + primitiveSignature = (byte) 'S'; + elSize = 2; + break; + } + case T_INT: { + primitiveSignature = (byte) 'I'; + elSize = 4; + break; + } + case T_LONG: { + primitiveSignature = (byte) 'J'; + elSize = 8; + break; + } + } + if (version >= VERSION_JDK12BETA4 && primitiveSignature == 0x00) { + throw new IOException("Unrecognized typecode: " + + elementClassID); + } + } + if (primitiveSignature != 0x00) { + long size = elSize * (long)num; + bytesRead += size; + JavaValueArray va = new JavaValueArray(primitiveSignature, start); + skipBytes(size); + snapshot.addHeapObject(id, va); + snapshot.setSiteTrace(va, stackTrace); + } else { + long sz = (long)num * identifierSize; + bytesRead += sz; + JavaObjectArray arr = new JavaObjectArray(elementClassID, start); + skipBytes(sz); + snapshot.addHeapObject(id, arr); + snapshot.setSiteTrace(arr, stackTrace); + } + return bytesRead; + } + + private byte signatureFromTypeId(byte typeId) throws IOException { + switch (typeId) { + case T_CLASS: { + return (byte) 'L'; + } + case T_BOOLEAN: { + return (byte) 'Z'; + } + case T_CHAR: { + return (byte) 'C'; + } + case T_FLOAT: { + return (byte) 'F'; + } + case T_DOUBLE: { + return (byte) 'D'; + } + case T_BYTE: { + return (byte) 'B'; + } + case T_SHORT: { + return (byte) 'S'; + } + case T_INT: { + return (byte) 'I'; + } + case T_LONG: { + return (byte) 'J'; + } + default: { + throw new IOException("Invalid type id of " + typeId); + } + } + } + + private void handleEOF(EOFException exp, Snapshot snapshot) { + if (debugLevel > 0) { + exp.printStackTrace(); + } + warn("Unexpected EOF. Will miss information..."); + // we have EOF, we have to tolerate missing references + snapshot.setUnresolvedObjectsOK(true); + } + + private void warn(String msg) { + System.out.println("WARNING: " + msg); + } + + // + // A trivial data-holder class for HPROF_GC_ROOT_THREAD_OBJ. + // + private class ThreadObject { + + long threadId; + int stackSeq; + + ThreadObject(long threadId, int stackSeq) { + this.threadId = threadId; + this.stackSeq = stackSeq; + } + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/MappedReadBuffer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; + +/** + * Implementation of ReadBuffer using mapped file buffer + * + * @author A. Sundararajan + */ +class MappedReadBuffer implements ReadBuffer { + private MappedByteBuffer buf; + private RandomAccessFile file; + + MappedReadBuffer(RandomAccessFile file, MappedByteBuffer buf) { + this.file = file; + this.buf = buf; + } + + /** + * Factory method to create correct ReadBuffer for a given file. + * + * The initial purpose of this method was to choose how to read hprof file for parsing + * depending on the size of the file and the system property 'jhat.disableFileMap': + * "If file size is more than 2 GB and when file mapping is configured (default), + * use mapped file reader". + * + * However, it has been discovered a problem with this approach. + * Creating java.nio.MappedByteBuffer from inside the test leads to hprof file + * is locked on Windows until test process dies since there is no good way to + * release this resource. + * + * java.nio.MappedByteBuffer will be used only if 'jhat.enableFileMap' is set to true. + * Per default 'jhat.enableFileMap' is not set. + */ + static ReadBuffer create(RandomAccessFile file) throws IOException { + if (canUseFileMap()) { + MappedByteBuffer buf; + try { + FileChannel ch = file.getChannel(); + long size = ch.size(); + buf = ch.map(FileChannel.MapMode.READ_ONLY, 0, size); + ch.close(); + return new MappedReadBuffer(file, buf); + } catch (IOException exp) { + exp.printStackTrace(); + System.err.println("File mapping failed, will use direct read"); + // fall through + } + } // else fall through + return new FileReadBuffer(file); + } + + /** + * Set system property 'jhat.enableFileMap' to 'true' to enable file mapping. + */ + private static boolean canUseFileMap() { + String prop = System.getProperty("jhat.enableFileMap"); + return prop != null && prop.equals("true"); + } + + private void seek(long pos) throws IOException { + assert pos <= Integer.MAX_VALUE : "position overflow"; + buf.position((int)pos); + } + + @Override + public synchronized char getChar(long pos) throws IOException { + seek(pos); + return buf.getChar(); + } + + @Override + public synchronized byte getByte(long pos) throws IOException { + seek(pos); + return buf.get(); + } + + @Override + public synchronized short getShort(long pos) throws IOException { + seek(pos); + return buf.getShort(); + } + + @Override + public synchronized int getInt(long pos) throws IOException { + seek(pos); + return buf.getInt(); + } + + @Override + public synchronized long getLong(long pos) throws IOException { + seek(pos); + return buf.getLong(); + } + + @Override + public void close() throws Exception { + file.close(); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionDataInputStream.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.DataInputStream; +import java.io.InputStream; + +/** + * A DataInputStream that keeps track of total bytes read + * (in effect 'position' in stream) so far. + * + */ +public class PositionDataInputStream extends DataInputStream { + public PositionDataInputStream(InputStream in) { + super(in instanceof PositionInputStream? + in : new PositionInputStream(in)); + } + + public boolean markSupported() { + return false; + } + + public void mark(int readLimit) { + throw new UnsupportedOperationException("mark"); + } + + public void reset() { + throw new UnsupportedOperationException("reset"); + } + + public long position() { + return ((PositionInputStream)in).position(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/PositionInputStream.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * InputStream that keeps track of total bytes read (in effect + * 'position' in stream) from the input stream. + * + */ +public class PositionInputStream extends FilterInputStream { + private long position = 0L; + + public PositionInputStream(InputStream in) { + super(in); + } + + public int read() throws IOException { + int res = super.read(); + if (res != -1) position++; + return res; + } + + public int read(byte[] b, int off, int len) throws IOException { + int res = super.read(b, off, len); + if (res != -1) position += res; + return res; + } + + public long skip(long n) throws IOException { + long res = super.skip(n); + position += res; + return res; + } + + public boolean markSupported() { + return false; + } + + public void mark(int readLimit) { + throw new UnsupportedOperationException("mark"); + } + + public void reset() { + throw new UnsupportedOperationException("reset"); + } + + public long position() { + return position; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/ReadBuffer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.IOException; + +/** + * Positionable read only buffer + * + * @author A. Sundararajan + */ +public interface ReadBuffer extends AutoCloseable { + public char getChar(long pos) throws IOException; + public byte getByte(long pos) throws IOException; + public short getShort(long pos) throws IOException; + public int getInt(long pos) throws IOException; + public long getLong(long pos) throws IOException; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/Reader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/Reader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/Reader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/parser/Reader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.parser; + +import java.io.*; +import jdk.test.lib.hprof.model.*; + +/** + * Abstract base class for reading object dump files. A reader need not be + * thread-safe. + * + * @author Bill Foote + */ + + +public abstract class Reader { + protected PositionDataInputStream in; + + protected Reader(PositionDataInputStream in) { + this.in = in; + } + + /** + * Read a snapshot from a data input stream. It is assumed that the magic + * number has already been read. + */ + abstract public Snapshot read() throws IOException; + + /** + * Read a snapshot from a file. + * + * @param heapFile The name of a file containing a heap dump + * @param callStack If true, read the call stack of allocaation sites + */ + public static Snapshot readFile(String heapFile, boolean callStack, + int debugLevel) + throws IOException { + int dumpNumber = 1; + int pos = heapFile.lastIndexOf('#'); + if (pos > -1) { + String num = heapFile.substring(pos+1, heapFile.length()); + try { + dumpNumber = Integer.parseInt(num, 10); + } catch (java.lang.NumberFormatException ex) { + String msg = "In file name \"" + heapFile + + "\", a dump number was " + + "expected after the :, but \"" + + num + "\" was found instead."; + System.err.println(msg); + throw new IOException(msg); + } + heapFile = heapFile.substring(0, pos); + } + try (PositionDataInputStream in = new PositionDataInputStream( + new BufferedInputStream(new FileInputStream(heapFile)))) { + int i = in.readInt(); + if (i == HprofReader.MAGIC_NUMBER) { + Reader r + = new HprofReader(heapFile, in, dumpNumber, + callStack, debugLevel); + return r.read(); + } else { + throw new IOException("Unrecognized magic number: " + i); + } + } + } + + /** + * Get Stack Traces from a Hprof file. + * + * @param heapFile The name of a file containing a heap dump + */ + public static String getStack(String heapFile, int debugLevel) + throws IOException { + int dumpNumber = 1; + int pos = heapFile.lastIndexOf('#'); + if (pos > -1) { + String num = heapFile.substring(pos+1, heapFile.length()); + try { + dumpNumber = Integer.parseInt(num, 10); + } catch (java.lang.NumberFormatException ex) { + String msg = "In file name \"" + heapFile + + "\", a dump number was " + + "expected after the :, but \"" + + num + "\" was found instead."; + System.err.println(msg); + throw new IOException(msg); + } + heapFile = heapFile.substring(0, pos); + } + try (PositionDataInputStream in = new PositionDataInputStream( + new BufferedInputStream(new FileInputStream(heapFile)))) { + int i = in.readInt(); + if (i == HprofReader.MAGIC_NUMBER) { + HprofReader r + = new HprofReader(heapFile, in, dumpNumber, + true, debugLevel); + r.read(); + return r.printStackTraces(); + } else { + throw new IOException("Unrecognized magic number: " + i); + } + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/ArraySorter.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.util; +import java.util.*; + +/** + * A singleton utility class that sorts an array of objects. + *

+ * Use: + *

+ *
+ *  Stuff[] arr = ...;
+ *  ArraySorter.sort(arr, new Comparer() {
+ *      public int compare(Object lhs, Object rhs) {
+ *          return ((String) lhs).compareTo((String) rhs);
+ *      }
+ *  });
+ * 
+ * + * @author Bill Foote + */ + +public class ArraySorter { + + /** + * Sort the given array, using c for comparison + **/ + static public void sort(Object[] arr, Comparer c) { + quickSort(arr, c, 0, arr.length-1); + } + + + /** + * Sort an array of strings, using String.compareTo() + **/ + static public void sortArrayOfStrings(Object[] arr) { + sort(arr, new Comparer() { + public int compare(Object lhs, Object rhs) { + return ((String) lhs).compareTo((String) rhs); + } + }); + } + + + static private void swap(Object[] arr, int a, int b) { + Object tmp = arr[a]; + arr[a] = arr[b]; + arr[b] = tmp; + } + + // + // Sorts arr between from and to, inclusive. This is a quick, off-the-top- + // of-my-head quicksort: I haven't put any thought into optimizing it. + // I _did_ put thought into making sure it's safe (it will always + // terminate). Worst-case it's O(n^2), but it will usually run in + // in O(n log n). It's well-behaved if the list is already sorted, + // or nearly so. + // + static private void quickSort(Object[] arr, Comparer c, int from, int to) { + if (to <= from) + return; + int mid = (from + to) / 2; + if (mid != from) + swap(arr, mid, from); + Object pivot = arr[from]; // Simple-minded, but reasonable + int highestBelowPivot = from - 1; + int low = from+1; + int high = to; + // We now move low and high toward each other, maintaining the + // invariants: + // arr[i] <= pivot for all i < low + // arr[i] > pivot for all i > high + // As long as these invariants hold, and every iteration makes + // progress, we are safe. + while (low <= high) { + int cmp = c.compare(arr[low], pivot); + if (cmp <= 0) { // arr[low] <= pivot + if (cmp < 0) { + highestBelowPivot = low; + } + low++; + } else { + int c2; + for (;;) { + // arr[high] > pivot: + c2 = c.compare(arr[high], pivot); + if (c2 > 0) { + high--; + if (low > high) { + break; + } + } else { + break; + } + } + // At this point, low is never == high, BTW + if (low <= high) { + swap(arr, low, high); + if (c2 < 0) { + highestBelowPivot = low; + } + low++; + high--; + } + } + } + // At this point, low == high+1 + // Now we just need to sort from from..highestBelowPivot + // and from high+1..to + if (highestBelowPivot > from) { + // pivot == pivot, so ensure algorithm terminates + swap(arr, from, highestBelowPivot); + quickSort(arr, c, from, highestBelowPivot-1); + } + quickSort(arr, c, high+1, to); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Comparer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Comparer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Comparer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Comparer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.util; + +/** + * Base class for comparison of two objects. + * @see VectorSorter + * + * @author Bill Foote + */ + +abstract public class Comparer { + + /** + * @return a number <, == or > 0 depending on lhs compared to rhs + * @see java.lang.String.compareTo + **/ + abstract public int compare(Object lhs, Object rhs); +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/CompositeEnumeration.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.util; + +import java.util.Enumeration; +import java.util.NoSuchElementException; +import jdk.test.lib.hprof.model.JavaHeapObject; + +public class CompositeEnumeration implements Enumeration { + Enumeration e1; + Enumeration e2; + + public CompositeEnumeration(Enumeration e1, Enumeration e2) { + this.e1 = e1; + this.e2 = e2; + } + + public boolean hasMoreElements() { + return e1.hasMoreElements() || e2.hasMoreElements(); + } + + public JavaHeapObject nextElement() { + if (e1.hasMoreElements()) { + return e1.nextElement(); + } + + if (e2.hasMoreElements()) { + return e2.nextElement(); + } + + throw new NoSuchElementException(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Misc.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Misc.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Misc.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/Misc.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.util; +import java.util.*; + +/** + * Miscellaneous functions I couldn't think of a good place to put. + * + * @author Bill Foote + */ + + +public class Misc { + + private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + public final static String toHex(int addr) { + char[] buf = new char[8]; + int i = 0; + for (int s = 28; s >= 0; s -= 4) { + buf[i++] = digits[(addr >> s) & 0xf]; + } + return "0x" + new String(buf); + } + + public final static String toHex(long addr) { + return "0x" + Long.toHexString(addr); + } + + public final static long parseHex(String value) { + long result = 0; + if (value.length() < 2 || value.charAt(0) != '0' || + value.charAt(1) != 'x') { + return -1L; + } + for(int i = 2; i < value.length(); i++) { + result *= 16; + char ch = value.charAt(i); + if (ch >= '0' && ch <= '9') { + result += (ch - '0'); + } else if (ch >= 'a' && ch <= 'f') { + result += (ch - 'a') + 10; + } else if (ch >= 'A' && ch <= 'F') { + result += (ch - 'A') + 10; + } else { + throw new NumberFormatException("" + ch + + " is not a valid hex digit"); + } + } + return result; + } + + public static String encodeHtml(String str) { + final int len = str.length(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < len; i++) { + char ch = str.charAt(i); + if (ch == '<') { + sb.append("<"); + } else if (ch == '>') { + sb.append(">"); + } else if (ch == '"') { + sb.append("""); + } else if (ch == '\'') { + sb.append("'"); + } else if (ch == '&') { + sb.append("&"); + } else if (ch < ' ') { + sb.append("&#").append((int)ch).append(';'); + } else { + int c = (ch & 0xFFFF); + if (c > 127) { + sb.append("&#").append(c).append(';'); + } else { + sb.append(ch); + } + } + } + return sb.toString(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/hprof/util/VectorSorter.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * The Original Code is HAT. The Initial Developer of the + * Original Code is Bill Foote, with contributions from others + * at JavaSoft/Sun. + */ + +package jdk.test.lib.hprof.util; +import java.util.*; + +/** + * A singleton utility class that sorts a vector. + *

+ * Use: + *

+ *
+ *  Vector v =   ;
+ *  VectorSorter.sort(v, new Comparer() {
+ *      public int compare(Object lhs, Object rhs) {
+ *          return ((String) lhs).compareTo((String) rhs);
+ *      }
+ *  });
+ * 
+ * + * @author Bill Foote + */ + + +public class VectorSorter { + + /** + * Sort the given vector, using c for comparison + **/ + static public void sort(Vector v, Comparer c) { + quickSort(v, c, 0, v.size()-1); + } + + + /** + * Sort a vector of strings, using String.compareTo() + **/ + static public void sortVectorOfStrings(Vector v) { + sort(v, new Comparer() { + public int compare(Object lhs, Object rhs) { + return ((String) lhs).compareTo((String) rhs); + } + }); + } + + + static private void swap(Vector v, int a, int b) { + Object tmp = v.elementAt(a); + v.setElementAt(v.elementAt(b), a); + v.setElementAt(tmp, b); + } + + // + // Sorts v between from and to, inclusive. This is a quick, off-the-top- + // of-my-head quicksort: I haven't put any thought into optimizing it. + // I _did_ put thought into making sure it's safe (it will always + // terminate). Worst-case it's O(n^2), but it will usually run in + // in O(n log n). It's well-behaved if the list is already sorted, + // or nearly so. + // + static private void quickSort(Vector v, Comparer c, int from, int to) { + if (to <= from) + return; + int mid = (from + to) / 2; + if (mid != from) + swap(v, mid, from); + Object pivot = v.elementAt(from); + // Simple-minded, but reasonable + int highestBelowPivot = from - 1; + int low = from+1; + int high = to; + // We now move low and high toward eachother, maintaining the + // invariants: + // v[i] <= pivot for all i < low + // v[i] > pivot for all i > high + // As long as these invariants hold, and every iteration makes + // progress, we are safe. + while (low <= high) { + int cmp = c.compare(v.elementAt(low), pivot); + if (cmp <= 0) { // v[low] <= pivot + if (cmp < 0) { + highestBelowPivot = low; + } + low++; + } else { + int c2; + for (;;) { + c2 = c.compare(v.elementAt(high), pivot); + // v[high] > pivot: + if (c2 > 0) { + high--; + if (low > high) { + break; + } + } else { + break; + } + } + // At this point, low is never == high + if (low <= high) { + swap(v, low, high); + if (c2 < 0) { + highestBelowPivot = low; + } + low++; + high--; + } + } + } + // Now we just need to sort from from..highestBelowPivot + // and from high+1..to + if (highestBelowPivot > from) { + // pivot == pivot, so ensure algorithm terminates + swap(v, from, highestBelowPivot); + quickSort(v, c, from, highestBelowPivot-1); + } + quickSort(v, c, high+1, to); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + + +/** + * Helper class for running applications with enabled JFR recording + */ +public class AppExecutorHelper { + + /** + * Executes an application with enabled JFR and writes collected events + * to the given output file. + * Which events to track and other parameters are taken from the setting .jfc file. + * + * @param setting JFR settings file(optional) + * @param jfrFilename JFR resulting recording filename(optional) + * @param additionalVMFlags additional VM flags passed to the java(optional) + * @param className name of the class to execute + * @param classArguments arguments passed to the class(optional) + * @return output analyzer for executed application + */ + public static OutputAnalyzer executeAndRecord(String settings, String jfrFilename, String[] additionalVmFlags, + String className, String... classArguments) throws Exception { + List arguments = new ArrayList<>(); + String baseStartFlightRecording = "-XX:StartFlightRecording"; + String additionalStartFlightRecording = ""; + + if (additionalVmFlags != null) { + Collections.addAll(arguments, additionalVmFlags); + } + + if (settings != null & jfrFilename != null) { + additionalStartFlightRecording = String.format("=settings=%s,filename=%s", settings, jfrFilename); + } else if (settings != null) { + additionalStartFlightRecording = String.format("=settings=%s", settings); + } else if (jfrFilename != null) { + additionalStartFlightRecording = String.format("=filename=%s", jfrFilename); + } + arguments.add(baseStartFlightRecording + additionalStartFlightRecording); + + arguments.add(className); + if (classArguments.length > 0) { + Collections.addAll(arguments, classArguments); + } + + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, arguments.toArray(new String[0])); + return ProcessTools.executeProcess(pb); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/CommonHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/CommonHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/CommonHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/CommonHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.fail; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import jdk.jfr.Recording; +import jdk.jfr.RecordingState; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingFile; +import jdk.test.lib.Asserts; +import jdk.test.lib.Utils; + + +/** + * Common helper class. + */ +public final class CommonHelper { + + private static RecordedEvent timeStampCounterEvent; + + public static void verifyException(VoidFunction f, String msg, Class expectedException) throws Throwable { + try { + f.run(); + } catch (Throwable t) { + if (expectedException.isAssignableFrom(t.getClass())) { + return; + } + t.printStackTrace(); + assertEquals(t.getClass(), expectedException, "Wrong exception class"); + } + fail("Missing Exception for: " + msg); + } + + public static Recording verifyExists(long recId, List recordings) { + for (Recording r : recordings) { + if (recId == r.getId()) { + return r; + } + } + Asserts.fail("Recording not found, id=" + recId); + return null; + } + + + public static void waitForRecordingState(Recording r, RecordingState expectedState) throws Exception { + while (r.getState() != expectedState) { + Thread.sleep(20); + } + } + + public static void verifyRecordingState(Recording r, RecordingState expectedState) throws Exception { + assertEquals(expectedState, r.getState(), "Wrong state"); + } + + public static boolean hasFastTimeEnabled() throws Exception { + return getTimeStampCounterEvent().getValue("fastTimeEnabled"); + } + + private synchronized static RecordedEvent getTimeStampCounterEvent() throws IOException, Exception { + if (timeStampCounterEvent == null) { + try (Recording r = new Recording()) { + r.enable(EventNames.CPUTimeStampCounter); + r.start(); + r.stop(); + Path p = Utils.createTempFile("timestamo", ".jfr"); + r.dump(p); + List events = RecordingFile.readAllEvents(p); + Files.deleteIfExists(p); + if (events.isEmpty()) { + throw new Exception("Could not locate CPUTimeStampCounter event"); + } + timeStampCounterEvent = events.get(0); + } + } + return timeStampCounterEvent; + } + + public static void waitForSystemCurrentMillisToChange() { + long t = System.currentTimeMillis(); + while (t == System.currentTimeMillis()) { + try { + Thread.sleep(2); + } catch (InterruptedException e) { + throw new Error("Sleep interupted", e); + } + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventField.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventField.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventField.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventField.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import jdk.jfr.ValueDescriptor; +import jdk.jfr.consumer.RecordedObject; +import jdk.test.lib.Asserts; + + +public final class EventField { + public final RecordedObject event; + public final ValueDescriptor desc; + + public EventField(RecordedObject event, ValueDescriptor valueDescriptor) { + this.event = event; + this.desc = valueDescriptor; + } + + @SuppressWarnings("unchecked") + public > boolean isEqual(T value) { + return value == (T)getValue(); + } + + @SuppressWarnings("unchecked") + public > EventField equal(T value) { + doAssert(()-> Asserts.assertEquals((T)getValue(), value, getErrMsg("Value not equal to " + value))); + return this; + } + + @SuppressWarnings("unchecked") + public > EventField notEqual(T value) { + doAssert(()-> Asserts.assertNotEquals((T)getValue(), value, getErrMsg("Value equal to " + value))); + return this; + } + + @SuppressWarnings("unchecked") + public > EventField above(T value) { + doAssert(()-> Asserts.assertGreaterThan((T)getValue(), value, getErrMsg("Value not above " + value))); + return this; + } + + @SuppressWarnings("unchecked") + public > EventField below(T value) { + doAssert(()-> Asserts.assertLessThan((T)getValue(), value, getErrMsg("Value not below " + value))); + return this; + } + + @SuppressWarnings("unchecked") + public > EventField atLeast(T value) { + doAssert(()-> Asserts.assertGreaterThanOrEqual((T)getValue(), value, getErrMsg("Value not atLeast" + value))); + return this; + } + + @SuppressWarnings("unchecked") + public > EventField atMost(T value) { + doAssert(()-> Asserts.assertLessThanOrEqual((T)getValue(), value, getErrMsg("Value not atMost " + value))); + return this; + } + + public > EventField instring(String part) { + final String value = getValue(); + doAssert(()-> Asserts.assertTrue(value.contains(part), getErrMsg("Value does not contain '" + part +"'"))); + return this; + } + + @SuppressWarnings("unchecked") + public T getValue() { + return (T)event.getValue(desc.getName()); + } + + public EventField notNull() { + doAssert(()-> Asserts.assertNotNull(getValue(), getErrMsg("Field is null"))); + return this; + } + + public EventField isNull() { + doAssert(()-> Asserts.assertNull(getValue(), getErrMsg("Field is not null"))); + return this; + } + + public EventField notEmpty() { + notNull(); + final String s = getValue(); + doAssert(()-> Asserts.assertFalse(s.isEmpty(), getErrMsg("Field is empty"))); + return this; + } + + private void doAssert(AssertFunction f) { + try { + f.doAssert(); + } catch (RuntimeException e) { + System.out.printf("Error: %s%nFailed event:%n%s%n", e.getMessage(), event.toString()); + throw e; + } + } + + public EventField containsAny(String... allowed) { + final String value = getValue(); + final List allowedValues = Arrays.asList(allowed); + boolean contains = false; + for(String allowedValue : allowed) { + if (value.contains(allowedValue)) { + contains = true; + } + } + if (!contains) { + doAssert(()-> Asserts.fail(getErrMsg(String.format("Value not in (%s)", + allowedValues.stream().collect(Collectors.joining(", ")))))); + } + return this; + } + + private String getErrMsg(String msg) { + final String name = desc.getName(); + final Object value = event.getValue(name); + return String.format("%s, field='%s', value='%s'", msg, name, value); + } + + @FunctionalInterface + public interface AssertFunction { + void doAssert(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventNames.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventNames.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventNames.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventNames.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import jdk.jfr.EventType; + +/** + * Contains id for events that are shipped with the JDK. + * + */ +public class EventNames { + + public final static String PREFIX = "jdk."; + private static final String GC_CATEGORY = "GC"; + + // JVM Configuration + public final static String JVMInformation = PREFIX + "JVMInformation"; + public final static String InitialSystemProperty = PREFIX + "InitialSystemProperty"; + public final static String IntFlag = PREFIX + "IntFlag"; + public final static String UnsignedIntFlag = PREFIX + "UnsignedIntFlag"; + public final static String LongFlag = PREFIX + "LongFlag"; + public final static String UnsignedLongFlag = PREFIX + "UnsignedLongFlag"; + public final static String DoubleFlag = PREFIX + "DoubleFlag"; + public final static String BooleanFlag = PREFIX + "BooleanFlag"; + public final static String StringFlag = PREFIX + "StringFlag"; + public final static String IntFlagChanged = PREFIX + "IntFlagChanged"; + public final static String UnsignedIntFlagChanged = PREFIX + "UnsignedIntFlagChanged"; + public final static String LongFlagChanged = PREFIX + "LongFlagChanged"; + public final static String UnsignedLongFlagChanged = PREFIX + "UnsignedLongFlagChanged"; + public final static String DoubleFlagChanged = PREFIX + "DoubleFlagChanged"; + public final static String BooleanFlagChanged = PREFIX + "BooleanFlagChanged"; + public final static String StringFlagChanged = PREFIX + "StringFlagChanged"; + + // Runtime + public final static String ThreadStart = PREFIX + "ThreadStart"; + public final static String ThreadEnd = PREFIX + "ThreadEnd"; + public final static String ThreadSleep = PREFIX + "ThreadSleep"; + public final static String ThreadPark = PREFIX + "ThreadPark"; + public final static String JavaMonitorEnter = PREFIX + "JavaMonitorEnter"; + public final static String JavaMonitorWait = PREFIX + "JavaMonitorWait"; + public final static String JavaMonitorInflate = PREFIX + "JavaMonitorInflate"; + public final static String ClassLoad = PREFIX + "ClassLoad"; + public final static String ClassDefine = PREFIX + "ClassDefine"; + public final static String ClassUnload = PREFIX + "ClassUnload"; + public final static String SafepointBegin = PREFIX + "SafepointBegin"; + public final static String SafepointStateSynchronization = PREFIX + "SafepointStateSynchronization"; + public final static String SafepointWaitBlocked = PREFIX + "SafepointWaitBlocked"; + public final static String SafepointCleanup = PREFIX + "SafepointCleanup"; + public final static String SafepointCleanupTask = PREFIX + "SafepointCleanupTask"; + public final static String SafepointEnd = PREFIX + "SafepointEnd"; + public final static String ExecuteVMOperation = PREFIX + "ExecuteVMOperation"; + public final static String Shutdown = PREFIX + "Shutdown"; + public final static String JavaThreadStatistics = PREFIX + "JavaThreadStatistics"; + public final static String ClassLoadingStatistics = PREFIX + "ClassLoadingStatistics"; + public final static String ClassLoaderStatistics = PREFIX + "ClassLoaderStatistics"; + public final static String ThreadAllocationStatistics = PREFIX + "ThreadAllocationStatistics"; + public final static String ExecutionSample = PREFIX + "ExecutionSample"; + public final static String NativeMethodSample = PREFIX + "NativeMethodSample"; + public final static String ThreadDump = PREFIX + "ThreadDump"; + public final static String OldObjectSample = PREFIX + "OldObjectSample"; + public final static String BiasedLockRevocation = PREFIX + "BiasedLockRevocation"; + public final static String BiasedLockSelfRevocation = PREFIX + "BiasedLockSelfRevocation"; + public final static String BiasedLockClassRevocation = PREFIX + "BiasedLockClassRevocation"; + // This event is hard to test + public final static String ReservedStackActivation = PREFIX + "ReservedStackActivation"; + + // GC + public final static String GCHeapSummary = PREFIX + "GCHeapSummary"; + public final static String MetaspaceSummary = PREFIX + "MetaspaceSummary"; + public final static String MetaspaceGCThreshold = PREFIX + "MetaspaceGCThreshold"; + public final static String MetaspaceAllocationFailure = PREFIX + "MetaspaceAllocationFailure"; + public final static String MetaspaceOOM = PREFIX + "MetaspaceOOM"; + public final static String MetaspaceChunkFreeListSummary = PREFIX + "MetaspaceChunkFreeListSummary"; + public final static String PSHeapSummary = PREFIX + "PSHeapSummary"; + public final static String G1HeapSummary = PREFIX + "G1HeapSummary"; + public final static String G1HeapRegionInformation = PREFIX + "G1HeapRegionInformation"; + public final static String G1HeapRegionTypeChange = PREFIX + "G1HeapRegionTypeChange"; + public final static String TenuringDistribution = PREFIX + "TenuringDistribution"; + public final static String GarbageCollection = PREFIX + "GarbageCollection"; + public final static String ParallelOldGarbageCollection = PREFIX + "ParallelOldGarbageCollection"; + public final static String ParallelOldCollection = ParallelOldGarbageCollection; + public final static String YoungGarbageCollection = PREFIX + "YoungGarbageCollection"; + public final static String OldGarbageCollection = PREFIX + "OldGarbageCollection"; + public final static String G1GarbageCollection = PREFIX + "G1GarbageCollection"; + public final static String G1MMU = PREFIX + "G1MMU"; + public final static String EvacuationInformation = PREFIX + "EvacuationInformation"; + public final static String GCReferenceStatistics = PREFIX + "GCReferenceStatistics"; + public final static String ObjectCountAfterGC = PREFIX + "ObjectCountAfterGC"; + public final static String PromoteObjectInNewPLAB = PREFIX + "PromoteObjectInNewPLAB"; + public final static String PromoteObjectOutsidePLAB = PREFIX + "PromoteObjectOutsidePLAB"; + public final static String PromotionFailed = PREFIX + "PromotionFailed"; + public final static String EvacuationFailed = PREFIX + "EvacuationFailed"; + public final static String ConcurrentModeFailure = PREFIX + "ConcurrentModeFailure"; + public final static String GCPhasePause = PREFIX + "GCPhasePause"; + public final static String GCPhasePauseLevel1 = PREFIX + "GCPhasePauseLevel1"; + public final static String GCPhasePauseLevel2 = PREFIX + "GCPhasePauseLevel2"; + public final static String GCPhasePauseLevel3 = PREFIX + "GCPhasePauseLevel3"; + public final static String GCPhasePauseLevel4 = PREFIX + "GCPhasePauseLevel4"; + public final static String ObjectCount = PREFIX + "ObjectCount"; + public final static String GCConfiguration = PREFIX + "GCConfiguration"; + public final static String GCSurvivorConfiguration = PREFIX + "GCSurvivorConfiguration"; + public final static String GCTLABConfiguration = PREFIX + "GCTLABConfiguration"; + public final static String GCHeapConfiguration = PREFIX + "GCHeapConfiguration"; + public final static String YoungGenerationConfiguration = PREFIX + "YoungGenerationConfiguration"; + public final static String G1AdaptiveIHOP = PREFIX + "G1AdaptiveIHOP"; + public final static String G1EvacuationYoungStatistics = PREFIX + "G1EvacuationYoungStatistics"; + public final static String G1EvacuationOldStatistics = PREFIX + "G1EvacuationOldStatistics"; + public final static String G1BasicIHOP = PREFIX + "G1BasicIHOP"; + public final static String AllocationRequiringGC = PREFIX + "AllocationRequiringGC"; + public final static String GCPhaseConcurrent = PREFIX + "GCPhaseConcurrent"; + + // Compiler + public final static String Compilation = PREFIX + "Compilation"; + public final static String CompilerPhase = PREFIX + "CompilerPhase"; + public final static String CompilationFailure = PREFIX + "CompilationFailure"; + public final static String CompilerInlining = PREFIX + "CompilerInlining"; + public final static String CompilerStatistics = PREFIX + "CompilerStatistics"; + public final static String CompilerConfiguration = PREFIX + "CompilerConfiguration"; + public final static String CodeCacheStatistics = PREFIX + "CodeCacheStatistics"; + public final static String CodeCacheConfiguration = PREFIX + "CodeCacheConfiguration"; + public final static String CodeSweeperStatistics = PREFIX + "CodeSweeperStatistics"; + public final static String CodeSweeperConfiguration = PREFIX + "CodeSweeperConfiguration"; + public final static String SweepCodeCache = PREFIX + "SweepCodeCache"; + public final static String CodeCacheFull = PREFIX + "CodeCacheFull"; + public final static String ObjectAllocationInNewTLAB = PREFIX + "ObjectAllocationInNewTLAB"; + public final static String ObjectAllocationOutsideTLAB = PREFIX + "ObjectAllocationOutsideTLAB"; + + // OS + public final static String OSInformation = PREFIX + "OSInformation"; + public final static String CPUInformation = PREFIX + "CPUInformation"; + public final static String CPULoad = PREFIX + "CPULoad"; + public final static String ThreadCPULoad = PREFIX + "ThreadCPULoad"; + public final static String SystemProcess = PREFIX + "SystemProcess"; + public final static String ThreadContextSwitchRate = PREFIX + "ThreadContextSwitchRate"; + public final static String InitialEnvironmentVariable = PREFIX + "InitialEnvironmentVariable"; + public final static String NativeLibrary = PREFIX + "NativeLibrary"; + public final static String PhysicalMemory = PREFIX + "PhysicalMemory"; + public final static String NetworkUtilization = PREFIX + "NetworkUtilization"; + + // JDK + public static final String FileForce = PREFIX + "FileForce"; + public static final String FileRead = PREFIX + "FileRead"; + public static final String FileWrite = PREFIX + "FileWrite"; + public static final String SocketRead = PREFIX + "SocketRead"; + public static final String SocketWrite = PREFIX + "SocketWrite"; + public final static String ExceptionStatistics = PREFIX + "ExceptionStatistics"; + public final static String JavaExceptionThrow = PREFIX + "JavaExceptionThrow"; + public final static String JavaErrorThrow = PREFIX + "JavaErrorThrow"; + + // Flight Recorder + public final static String DumpReason = PREFIX + "DumpReason"; + public final static String DataLoss = PREFIX + "DataLoss"; + public final static String CPUTimeStampCounter = PREFIX + "CPUTimeStampCounter"; + public final static String ActiveRecording = PREFIX + "ActiveRecording"; + public final static String ActiveSetting = PREFIX + "ActiveSetting"; + + public static boolean isGcEvent(EventType et) { + return et.getCategoryNames().contains(GC_CATEGORY); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventTypePrototype.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import java.util.ArrayList; +import java.util.List; + +import jdk.jfr.AnnotationElement; +import jdk.jfr.Name; +import jdk.jfr.ValueDescriptor; + +public final class EventTypePrototype { + private final List fields; + private final List annotations; + private final String name; + + public EventTypePrototype(String name, List as, List fields) { + this.annotations = new ArrayList<>(as); + this.annotations.add(new AnnotationElement(Name.class, name)); + this.fields = fields; + this.name = name; + } + + public EventTypePrototype(String name) { + this(name, new ArrayList<>(), new ArrayList<>()); + } + + public int getFieldIndex(String key) { + int index = 0; + for (ValueDescriptor f : fields) { + if (f.getName().equals(key)) { + return index; + } + index++; + } + throw new NoSuchFieldError(key); + } + + public void addField(ValueDescriptor fieldDescriptor) { + fields.add(fieldDescriptor); + } + + public void addAnnotation(AnnotationElement annotation) { + annotations.add(annotation); + } + + public List getFields() { + return fields; + } + + public List getAnnotations() { + return annotations; + } + + public String getName() { + return name; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventVerifier.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventVerifier.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventVerifier.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/EventVerifier.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import jdk.jfr.consumer.RecordedEvent; + +public abstract class EventVerifier { + protected final RecordedEvent event; + + public EventVerifier(RecordedEvent event) { + this.event = event; + } + + public > void verifyEquals(String name, T value) { + Events.assertField(event, name).equal(value); + } + + public void verifyContains(String name, String value) { + Events.assertField(event, name).containsAny(value); + } + + protected long gigabytes(int num) { + return num * 1024L * 1024L * 1024L; + } + + protected long megabytes(int num) { + return num * 1024L * 1024L; + } + + public abstract void verify() throws Exception; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Events.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Events.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Events.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Events.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertFalse; +import static jdk.test.lib.Asserts.assertNotNull; +import static jdk.test.lib.Asserts.assertTrue; +import static jdk.test.lib.Asserts.fail; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.lang.management.ManagementFactory; + +import jdk.jfr.AnnotationElement; +import jdk.jfr.EventType; +import jdk.jfr.Recording; +import jdk.jfr.SettingDescriptor; +import jdk.jfr.Timespan; +import jdk.jfr.Timestamp; +import jdk.jfr.ValueDescriptor; +import jdk.jfr.consumer.RecordingFile; +import jdk.test.lib.Asserts; +import jdk.jfr.consumer.RecordedClass; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedObject; +import jdk.jfr.consumer.RecordedThread; +import jdk.jfr.consumer.RecordedThreadGroup; + + +/** + * Helper class to verify RecordedEvent content + */ +public class Events { + + public static EventField assertField(RecordedEvent event, String name) { + String[] partNames = name.split("\\."); + RecordedObject struct = event; + try { + for (int i=0; i valueDescriptors = struct.getFields(); + for (ValueDescriptor d : valueDescriptors) { + if (name.equals(d.getName())) { + return d; + } + } + System.out.printf("Failed struct:%s", struct.toString()); + fail(String.format("Field %s not in struct", name)); + return null; + } + + public static void hasEvents(List events) { + assertFalse(events.isEmpty(), "No events"); + } + + public static void hasEvents(RecordingFile file) { + assertTrue(file.hasMoreEvents(), "No events"); + } + + public static void assertEventThread(RecordedEvent event) { + RecordedThread eventThread = event.getThread(); + if (eventThread == null) { + System.out.printf("Failed event:%n%s%n", event.toString()); + fail("No thread in event"); + } + } + + public static void assertJavaMethod(RecordedEvent event) { + assertField(event, "method.name").notEmpty(); + assertField(event, "method.descriptor").notEmpty(); + assertField(event, "method.modifiers").atLeast(0); + assertField(event, "method.hidden"); + assertField(event, "method.type.name").notEmpty(); + assertField(event, "method.type.modifiers").atLeast(0); + } + + public static void assertEventThread(RecordedEvent event, Thread thread) { + assertThread(event.getThread(), thread); + } + + public static void assertEventThread(RecordedEvent event, String structName, Thread thread) { + assertThread(assertField(event, structName).notNull().getValue(), thread); + } + + public static void assertDuration(RecordedEvent event, String name, Duration duration) { + assertEquals(event.getDuration(name), duration); + } + + public static void assertInstant(RecordedEvent event, String name, Instant instant) { + assertEquals(event.getInstant(name), instant); + } + + public static void assertMissingValue(RecordedEvent event, String name) { + ValueDescriptor v = event.getEventType().getField(name); + if (v.getAnnotation(Timespan.class) != null) { + Duration d = event.getDuration(name); + assertTrue(d.getSeconds() == Long.MIN_VALUE && d.getNano() == 0); + return; + } + if (v.getAnnotation(Timestamp.class) != null) { + Instant instant = event.getInstant(name); + assertTrue(instant.equals(Instant.MIN)); + return; + } + if (v.getTypeName().equals("double")) { + double d = event.getDouble(name); + assertTrue(Double.isNaN(d) || d == Double.NEGATIVE_INFINITY); + return; + } + if (v.getTypeName().equals("float")) { + float f = event.getFloat(name); + assertTrue(Float.isNaN(f) || f == Float.NEGATIVE_INFINITY); + return; + } + if (v.getTypeName().equals("int")) { + int i = event.getInt(name); + assertTrue(i == Integer.MIN_VALUE); + return; + } + if (v.getTypeName().equals("long")) { + assertEquals(event.getLong(name), Long.MIN_VALUE); + return; + } + Object o = event.getValue(name); + Asserts.assertNull(o); + } + + private static void assertThread(RecordedThread eventThread, Thread thread) { + assertNotNull(eventThread, "Thread in event was null"); + assertEquals(eventThread.getJavaThreadId(), thread.getId(), "Wrong thread id"); + assertEquals(eventThread.getJavaName(), thread.getName(), "Wrong thread name"); + + ThreadGroup threadGroup = thread.getThreadGroup(); + RecordedThreadGroup eventThreadGroup = eventThread.getThreadGroup(); + assertNotNull(eventThreadGroup, "eventThreadGroup was null"); + + // Iterate and check all threadGroups + while (eventThreadGroup != null) { + final String groupName = eventThreadGroup.getName(); + if (threadGroup != null) { + assertEquals(groupName, threadGroup.getName(), "Wrong threadGroup name"); + threadGroup = threadGroup.getParent(); + } else { + assertNotNull(groupName, "threadGroup name was null"); + assertFalse(groupName.isEmpty(), "threadGroup name was empty"); + } + eventThreadGroup = eventThreadGroup.getParent(); + } + } + + public static boolean hasField(RecordedEvent event, String name) { + return event.getFields().stream().map(vd -> vd.getName()).anyMatch(s -> s.equals(name)); + } + + public static boolean isEventType(RecordedEvent event, String typeName) { + return typeName.equals(event.getEventType().getName()); + } + + + /** + * Creates a list of events from a recording. + * + * @param recording recording, not {@code null} + * @return an a list, not null + * @throws IOException if an event set could not be created due to I/O + * errors. + */ + public static List fromRecording(Recording recording) throws IOException { + return RecordingFile.readAllEvents(makeCopy(recording)); + } + + public static RecordingFile copyTo(Recording r) throws IOException { + return new RecordingFile(makeCopy(r)); + } + + private static String getProcessId(final String fallback) { + // Note: may fail in some JVM implementations + // therefore fallback has to be provided + + // something like '@', at least in SUN / Oracle JVMs + final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + + final int index = jvmName.indexOf('@'); + + if (index < 1) { + // part before '@' empty (index = 0) / '@' not found (index = -1) + return fallback; + } + + try { + return Long.toString(Long.parseLong(jvmName.substring(0, index))); + } catch (NumberFormatException e) { + // ignore + } + return fallback; + } + + private static Path makeCopy(Recording recording) throws IOException { + Path p = recording.getDestination(); + if (p == null) { + File directory = new File("."); + // FIXME: Must come up with a way to give human-readable name + // this will at least not clash when running parallel. + //ProcessHandle h = ProcessHandle.current(); + //p = new File(directory.getAbsolutePath(), "recording-" + recording.getId() + "-pid" + h.pid() + ".jfr").toPath(); + p = new File(directory.getAbsolutePath(), "recording-" + recording.getId() + "-pid" + getProcessId("666") + ".jfr").toPath(); + recording.dump(p); + } + return p; + } + + public static void hasAnnotation(ValueDescriptor field, Class annotationClass) throws Exception { + AnnotationElement a = getAnnotation(field, annotationClass); + if (a == null) { + throw new Exception("Expected " + annotationClass.getSimpleName() + " on field " + field.getName()); + } + } + + public static void assertAnnotation(ValueDescriptor field, Class annotationClass, String value) throws Exception { + AnnotationElement a = getAnnotation(field, annotationClass); + Object v = a.getValue("value"); + if (!v.equals(value)) { + throw new Exception("Expected " + annotationClass.getSimpleName() + " on field " + field.getName() + " to have value " + value + ", but got " + v); + } + } + + // candidate for moving into API + public static AnnotationElement getAnnotation(ValueDescriptor v, Class clazz) throws Exception { + for (AnnotationElement a : v.getAnnotationElements()) { + if (a.getTypeName().equals(clazz.getName())) { + return a; + } + } + + throw new Exception("Could not find annotation " + clazz.getName()); + } + + // candidate for moving into API + public static AnnotationElement getAnnotationByName(EventType t, String name) throws Exception { + for (AnnotationElement a : t.getAnnotationElements()) { + if (a.getTypeName().equals(name)) { + return a; + } + } + throw new Exception("Could not find annotation '" + name + " in type " + t.getName()); + } + + // candidate for moving into API + public static SettingDescriptor getSetting(EventType type, String name) { + for (SettingDescriptor s : type.getSettingDescriptors()) { + if (s.getName().equals(name)) { + return s; + } + } + throw new IllegalArgumentException("Could not setting with name " + name); + } + + public static void hasEvent(Recording r, String name) throws IOException { + List events = fromRecording(r); + Events.hasEvents(events); + Events.hasEvent(events, name); + } + + public static void hasEvent(List events, String name) throws IOException { + if (!containsEvent(events, name)) { + Asserts.fail("Missing event " + name + " in recording " + events.toString()); + } + } + + public static void hasNotEvent(List events, String name) throws IOException { + if (containsEvent(events, name)) { + Asserts.fail("Rercording should not contain event " + name + " " + events.toString()); + } + } + + private static boolean containsEvent(List events, String name) { + for (RecordedEvent event : events) { + if (event.getEventType().getName().equals(name)) { + return true; + } + } + return false; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/FileHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/FileHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/FileHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/FileHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import java.io.File; +import java.io.IOException; +import java.nio.file.AccessDeniedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingFile; +import jdk.test.lib.Asserts; + +/** + * Common helper class. + */ +public class FileHelper { + + public static Path getDest(String subPath) throws IOException { + Path path = Paths.get(subPath + "/test.jfr"); + Path parent = path.getParent(); + if (parent == null) { + throw new IOException("No parent cound be found for path " + subPath); + } + Files.createDirectories(parent); + return path; + } + + public static Path createLongDir(Path root) throws IOException { + final int minPathLength = 400; + StringBuilder buff = new StringBuilder(); + buff.append(root.toString()); + while (buff.length() < minPathLength) { + buff.append("/veryLongPath012345678901234567890123456789"); + } + Path path = Paths.get(buff.toString()); + System.out.println("long dir=" + path); + Files.createDirectories(path); + return path; + } + + public static Path getDestReadOnly(String subPath) throws IOException { + final Path path = getDest(subPath); + Path parent = path.getParent(); + if (parent == null) { + throw new IOException("No parent cound be found for path " + subPath); + } + parent.toFile().setReadOnly(); + return path; + } + + public static Path createReadOnlyFile(Path path) throws IOException { + final Path createdPath = Files.createFile(path); + createdPath.toFile().setReadOnly(); + return createdPath; + } + + public static Path createReadOnlyDir(Path path) throws IOException { + final Path createdPath = Files.createDirectories(path); + createdPath.toFile().setReadOnly(); + return createdPath; + } + + public static Path getDestNotExist() { + return Paths.get(".", "thisDirDoesNotExist/test.jfr"); + } + + public static boolean isReadOnlyPath(Path path) throws IOException { + // Files.isWritable(path) can not really be trusted. At least not on Windows. + // If path is a directory, we try to create a new file in it. + if (Files.isDirectory(path)) { + try { + Path f = Files.createFile(Paths.get(path.toString(), "dummyFileToCheckReadOnly")); + System.out.printf("Dir is not read-only, created %s, exists=%b%n", f, Files.exists(f)); + return false; + } catch (AccessDeniedException e) { + System.out.printf("'%s' verified read-only by %s%n", path, e.toString()); + return true; + } + } else { + boolean isReadOnly = !Files.isWritable(path); + System.out.format("isReadOnly '%s': %b%n", path, isReadOnly); + return isReadOnly; + } + } + + public static void verifyRecording(File file) throws Exception { + Asserts.assertTrue(file.exists(), file.getAbsolutePath() + " does not exist"); + Asserts.assertTrue(file.isFile(), file.getAbsolutePath() + " is not a file"); + Asserts.assertGreaterThan(file.length(), 0L, "Size of recording is 0."); + List events = RecordingFile.readAllEvents(file.toPath()); + for (RecordedEvent event : events) { + System.out.printf("First event in recording '%s':%n%s", file.getName(), event); + return; + } + Asserts.fail("No events in file " + file.getName()); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/GCHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/GCHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/GCHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/GCHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertNotEquals; +import static jdk.test.lib.Asserts.assertNotNull; +import static jdk.test.lib.Asserts.assertNull; +import static jdk.test.lib.Asserts.fail; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Stack; + +import jdk.jfr.ValueDescriptor; +import jdk.jfr.consumer.RecordedEvent; + +/** + * Mixed helper classes to test GC events. + */ +public class GCHelper { + public static final String event_garbage_collection = EventNames.GarbageCollection; + public static final String event_young_garbage_collection = EventNames.YoungGarbageCollection; + public static final String event_old_garbage_collection = EventNames.OldGarbageCollection; + public static final String event_parold_garbage_collection = EventNames.ParallelOldCollection; + public static final String event_g1_garbage_collection = EventNames.G1GarbageCollection; + public static final String event_heap_summary = EventNames.GCHeapSummary; + public static final String event_heap_ps_summary = EventNames.PSHeapSummary; + public static final String event_heap_metaspace_summary = EventNames.MetaspaceSummary; + public static final String event_reference_statistics = EventNames.GCReferenceStatistics; + public static final String event_phases_pause = EventNames.GCPhasePause; + public static final String event_phases_level_1 = EventNames.GCPhasePauseLevel1; + public static final String event_phases_level_2 = EventNames.GCPhasePauseLevel2; + public static final String event_phases_level_3 = EventNames.GCPhasePauseLevel3; + + public static final String gcG1New = "G1New"; + public static final String gcParNew = "ParNew"; + public static final String gcDefNew = "DefNew"; + public static final String gcParallelScavenge = "ParallelScavenge"; + public static final String gcG1Old = "G1Old"; + public static final String gcG1Full = "G1Full"; + public static final String gcConcurrentMarkSweep = "ConcurrentMarkSweep"; + public static final String gcSerialOld = "SerialOld"; + public static final String gcPSMarkSweep = "PSMarkSweep"; + public static final String gcParallelOld = "ParallelOld"; + public static final String pauseLevelEvent = "GCPhasePauseLevel"; + + private static final List g1HeapRegionTypes; + private static PrintStream defaultErrorLog = null; + + public static int getGcId(RecordedEvent event) { + return Events.assertField(event, "gcId").getValue(); + } + + public static boolean isGcEvent(RecordedEvent event) { + for (ValueDescriptor v : event.getFields()) { + if ("gcId".equals(v.getName())) { + return true; + } + } + return false; + } + +// public static String getEventDesc(RecordedEvent event) { +// final String path = event.getEventType().getName(); +// if (!isGcEvent(event)) { +// return path; +// } +// if (event_garbage_collection.equals(path)) { +// String name = Events.assertField(event, "name").getValue(); +// String cause = Events.assertField(event, "cause").getValue(); +// return String.format("path=%s, gcId=%d, endTime=%d, name=%s, cause=%s, startTime=%d", +// path, getGcId(event), event.getEndTime(), name, cause, event.getStartTime()); +// } else { +// return String.format("path=%s, gcId=%d, endTime=%d", path, getGcId(event), event.getEndTime()); +// } +// } + + public static RecordedEvent getConfigEvent(List events) throws Exception { + for (RecordedEvent event : events) { + if (EventNames.GCConfiguration.equals(event.getEventType().getName())) { + return event; + } + } + fail("Could not find event " + EventNames.GCConfiguration); + return null; + } + + public static void callSystemGc(int num, boolean withGarbage) { + for (int i = 0; i < num; i++) { + if (withGarbage) { + makeGarbage(); + } + System.gc(); + } + } + + private static void makeGarbage() { + Object[] garbage = new Object[1024]; + for (int i = 0; i < 1024; i++) { + garbage[i] = new Object(); + } + } + + // Removes gcEvents with lowest and highest gcID. This is used to filter out + // any incomplete GCs if the recording started/stopped in the middle of a GC. + // We also filters out events without gcId. Those events are not needed. + public static List removeFirstAndLastGC(List events) { + int minGcId = Integer.MAX_VALUE; + int maxGcId = Integer.MIN_VALUE; + // Find min/max gcId + for (RecordedEvent event : events) { + if (Events.hasField(event, "gcId")) { + int gcId = Events.assertField(event, "gcId").getValue(); + minGcId = Math.min(gcId, minGcId); + maxGcId = Math.max(gcId, maxGcId); + } + } + + // Add all events except those with gcId = min/max gcId + List filteredEvents = new ArrayList<>(); + for (RecordedEvent event : events) { + if (Events.hasField(event, "gcId")) { + int gcId = Events.assertField(event, "gcId").getValue(); + if (gcId != minGcId && gcId != maxGcId) { + filteredEvents.add(event); + } + } + } + return filteredEvents; + } + + public static Map beanCollectorTypes = new HashMap<>(); + public static Set collectorOverrides = new HashSet<>(); + public static Map requiredEvents = new HashMap<>(); + + static { + // young GarbageCollectionMXBeans. + beanCollectorTypes.put("G1 Young Generation", true); + beanCollectorTypes.put("Copy", true); + beanCollectorTypes.put("PS Scavenge", true); + beanCollectorTypes.put("ParNew", true); + + // old GarbageCollectionMXBeans. + beanCollectorTypes.put("G1 Old Generation", false); + beanCollectorTypes.put("ConcurrentMarkSweep", false); + beanCollectorTypes.put("PS MarkSweep", false); + beanCollectorTypes.put("MarkSweepCompact", false); + + // List of expected collector overrides. "A.B" means that collector A may use collector B. + collectorOverrides.add("G1Old.G1Full"); + collectorOverrides.add("G1Old.SerialOld"); + collectorOverrides.add("ConcurrentMarkSweep.SerialOld"); + collectorOverrides.add("SerialOld.PSMarkSweep"); + + requiredEvents.put(gcG1New, new String[] {event_heap_summary, event_young_garbage_collection}); + requiredEvents.put(gcParNew, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); + requiredEvents.put(gcDefNew, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); + requiredEvents.put(gcParallelScavenge, new String[] {event_heap_summary, event_heap_ps_summary, event_heap_metaspace_summary, event_reference_statistics, event_phases_pause, event_phases_level_1, event_young_garbage_collection}); + requiredEvents.put(gcG1Old, new String[] {event_heap_summary, event_old_garbage_collection}); + requiredEvents.put(gcG1Full, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_old_garbage_collection}); + requiredEvents.put(gcConcurrentMarkSweep, new String[] {event_phases_pause, event_phases_level_1, event_old_garbage_collection}); + requiredEvents.put(gcSerialOld, new String[] {event_heap_summary, event_heap_metaspace_summary, event_phases_pause, event_phases_level_1, event_old_garbage_collection}); + requiredEvents.put(gcParallelOld, new String[] {event_heap_summary, event_heap_ps_summary, event_heap_metaspace_summary, event_reference_statistics, event_phases_pause, event_phases_level_1, event_old_garbage_collection, event_parold_garbage_collection}); + + String[] g1HeapRegionTypeLiterals = new String[] { + "Free", + "Eden", + "Survivor", + "Starts Humongous", + "Continues Humongous", + "Old", + "Archive" + }; + + g1HeapRegionTypes = Collections.unmodifiableList(Arrays.asList(g1HeapRegionTypeLiterals)); + } + + /** + * Contains all GC events belonging to the same GC (same gcId). + */ + public static class GcBatch { + private List events = new ArrayList<>(); + + public int getGcId() { + if (events.isEmpty()) { + return -1; + } + return GCHelper.getGcId(events.get(0)); + } + + public String getName() { + RecordedEvent endEvent = getEndEvent(); + String name = endEvent == null ? null : Events.assertField(endEvent, "name").getValue(); + return name == null ? "null" : name; + } + + public RecordedEvent getEndEvent() { + return getEvent(event_garbage_collection); + } + + public boolean addEvent(RecordedEvent event) { + if (!events.isEmpty()) { + assertEquals(getGcId(), GCHelper.getGcId(event), "Wrong gcId in event. Error in test code."); + } + boolean isEndEvent = event_garbage_collection.equals(event.getEventType().getName()); + if (isEndEvent) { + // Verify that we have not already got a garbage_collection event with this gcId. + assertNull(getEndEvent(), String.format("Multiple %s for gcId %d", event_garbage_collection, getGcId())); + } + events.add(event); + return isEndEvent; + } + + public boolean isYoungCollection() { + boolean isYoung = containsEvent(event_young_garbage_collection); + boolean isOld = containsEvent(event_old_garbage_collection); + assertNotEquals(isYoung, isOld, "isYoung and isOld was same for batch: " + toString()); + return isYoung; + } + + public int getEventCount() { + return events.size(); + } + + public RecordedEvent getEvent(int index) { + return events.get(index); + } + + public List getEvents() { + return events; + } + + public RecordedEvent getEvent(String eventPath) { + for (RecordedEvent event : events) { + if (eventPath.equals(event.getEventType().getName())) { + return event; + } + } + return null; + } + + public boolean containsEvent(String eventPath) { + return getEvent(eventPath) != null; + } + + public String toString() { + RecordedEvent endEvent = getEndEvent(); + Instant startTime = Instant.EPOCH; + String cause = "?"; + String name = "?"; + if (endEvent != null) { + name = getName(); + startTime = endEvent.getStartTime(); + cause = Events.assertField(endEvent, "cause").getValue(); + } + return String.format("GcEvent: gcId=%d, method=%s, cause=%s, startTime=%s", + getGcId(), name, cause, startTime); + } + + public String getLog() { + StringBuilder sb = new StringBuilder(); + sb.append(this.toString() + System.getProperty("line.separator")); + for (RecordedEvent event : events) { + sb.append(String.format("event: %s%n", event)); + } + return sb.toString(); + } + + // Group all events info batches. + public static List createFromEvents(List events) throws Exception { + Stack openGcIds = new Stack<>(); + List batches = new ArrayList<>(); + GcBatch currBatch = null; + + for (RecordedEvent event : events) { + if (!isGcEvent(event)) { + continue; + } + int gcId = GCHelper.getGcId(event); + if (currBatch == null || currBatch.getGcId() != gcId) { + currBatch = null; + // Search for existing batch + for (GcBatch loopBatch : batches) { + if (gcId == loopBatch.getGcId()) { + currBatch = loopBatch; + break; + } + } + if (currBatch == null) { + // No existing batch. Create new. + currBatch = new GcBatch(); + batches.add(currBatch); + openGcIds.push(new Integer(gcId)); + } + } + boolean isEndEvent = currBatch.addEvent(event); + if (isEndEvent) { + openGcIds.pop(); + } + } + // Verify that all start_garbage_collection events have received a corresponding "garbage_collection" event. + for (GcBatch batch : batches) { + if (batch.getEndEvent() == null) { + System.out.println(batch.getLog()); + } + assertNotNull(batch.getEndEvent(), "GcBatch has no end event"); + } + return batches; + } + } + + /** + * Contains number of collections and sum pause time for young and old collections. + */ + public static class CollectionSummary { + public long collectionCountOld; + public long collectionCountYoung; + public long collectionTimeOld; + public long collectionTimeYoung; + private Set names = new HashSet<>(); + + public void add(String collectorName, boolean isYoung, long count, long time) { + if (isYoung) { + collectionCountYoung += count; + collectionTimeYoung += time; + } else { + collectionCountOld += count; + collectionTimeOld += time; + } + if (!names.contains(collectorName)) { + names.add(collectorName); + } + } + + public long sum() { + return collectionCountOld + collectionCountYoung; + } + + public CollectionSummary calcDelta(CollectionSummary prev) { + CollectionSummary delta = new CollectionSummary(); + delta.collectionCountOld = this.collectionCountOld - prev.collectionCountOld; + delta.collectionTimeOld = this.collectionTimeOld - prev.collectionTimeOld; + delta.collectionCountYoung = this.collectionCountYoung - prev.collectionCountYoung; + delta.collectionTimeYoung = this.collectionTimeYoung - prev.collectionTimeYoung; + delta.names.addAll(this.names); + delta.names.addAll(prev.names); + return delta; + } + + public static CollectionSummary createFromMxBeans() { + CollectionSummary summary = new CollectionSummary(); + List gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); + for (int c=0; c batches) { + CollectionSummary summary = new CollectionSummary(); + for (GcBatch batch : batches) { + RecordedEvent endEvent = batch.getEndEvent(); + assertNotNull(endEvent, "No end event in batch with gcId " + batch.getGcId()); + String name = batch.getName(); + summary.add(name, batch.isYoungCollection(), 1, Events.assertField(endEvent, "sumOfPauses").getValue()); + } + return summary; + } + + public String toString() { + StringBuilder collectorNames = new StringBuilder(); + for (String s : names) { + if (collectorNames.length() > 0) { + collectorNames.append(", "); + } + collectorNames.append(s); + } + return String.format("CollectionSummary: young.collections=%d, young.time=%d, old.collections=%d, old.time=%d, collectors=(%s)", + collectionCountYoung, collectionTimeYoung, collectionCountOld, collectionTimeOld, collectorNames); + } + } + + public static PrintStream getDefaultErrorLog() { + if (defaultErrorLog == null) { + try { + defaultErrorLog = new PrintStream(new FileOutputStream("error.log", true)); + } catch (IOException e) { + e.printStackTrace(); + defaultErrorLog = System.err; + } + } + return defaultErrorLog; + } + + public static void log(Object msg) { + log(msg, System.err); + log(msg, getDefaultErrorLog()); + } + + public static void log(Object msg, PrintStream ps) { + ps.println(msg); + } + + public static boolean isValidG1HeapRegionType(final String type) { + return g1HeapRegionTypes.contains(type); + } + + /** + * Helper function to align heap size up. + * + * @param value + * @param alignment + * @return aligned value + */ + public static long alignUp(long value, long alignment) { + return (value + alignment - 1) & ~(alignment - 1); + } + + /** + * Helper function to align heap size down. + * + * @param value + * @param alignment + * @return aligned value + */ + public static long alignDown(long value, long alignment) { + return value & ~(alignment - 1); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/RecurseThread.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/RecurseThread.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/RecurseThread.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/RecurseThread.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import jdk.test.lib.Asserts; + +public class RecurseThread extends Thread { + + public int totalDepth; + public long dummy = 0; // Just to make sure the optimizer does not remove the test code. + private volatile boolean timeToQuit = false; + private volatile boolean isInRunLoop = false; + + public RecurseThread(int totalDepth) { + this.totalDepth = totalDepth; + } + + @Override + public void run() { + // totalDepth includes functions run() and recurse() and runloop(). + // Remove 3 from totalDepth when recursing. + final int minDepth = 3; + Asserts.assertGreaterThanOrEqual(totalDepth, minDepth, "totalDepth too small"); + int recurseDepth = totalDepth - minDepth; + + // We want the last function before runloop() to be recurseA(). + boolean startWithRecurseA = (totalDepth % 2) != 0; + dummy = startWithRecurseA ? recurseA(recurseDepth) : recurseB(recurseDepth); + } + + public void quit() { + timeToQuit = true; + } + + public boolean isInRunLoop() { + return isInRunLoop; + } + + private long recurseA(int depth) { + if (depth == 0) { + return recurseEnd(); + } else { + return recurseB(depth - 1); + } + } + + private long recurseB(int depth) { + if (depth == 0) { + return recurseEnd(); + } else { + return recurseA(depth - 1); + } + } + + // Test expects this function to be at the top of the stack. + // We should not call other functions from here. + private long recurseEnd() { + isInRunLoop = true; + long[] dummyTable = new long[] { 0, 2, 4, 8, 16 }; + long dummyTotal = 0; + while (!timeToQuit) { + dummyTotal = 0; + for (int i = 0; i < 5; ++i) { + dummyTotal += dummyTable[i]; + } + } + return dummyTotal; + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEvent.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEvent.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEvent.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEvent.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import jdk.jfr.Event; + +public class SimpleEvent extends Event { + public int id; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleEventHelper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.test.lib.Asserts; + +public class SimpleEventHelper { + + public static void enable(Recording r, boolean isEnabled) { + if (isEnabled) { + r.enable(SimpleEvent.class).withThreshold(Duration.ofMillis(0)).withoutStackTrace(); + } else { + r.disable(SimpleEvent.class); + } + } + + public static SimpleEvent createEvent(int id) { + SimpleEvent event = new SimpleEvent(); + event.begin(); + event.id = id; + event.end(); + event.commit(); + return event; + } + + public static void verifyEvents(Recording r, int ... ids) throws Exception { + List eventIds = new ArrayList<>(); + for (RecordedEvent event : Events.fromRecording(r)) { + if (Events.isEventType(event, SimpleEvent.class.getName())) { + int id = Events.assertField(event, "id").getValue(); + System.out.printf("recording %s: event.id=%d%n", r.getName(), id); + eventIds.add(id); + } + } + Asserts.assertEquals(eventIds.size(), ids.length, "Wrong number of events"); + for (int i = 0; i < ids.length; ++i) { + Asserts.assertEquals(eventIds.get(i).intValue(), ids[i], "Wrong id in event"); + } + } + + public static void verifyContains(List events, int ... ids) throws Exception { + Set missingIds = new HashSet<>(); + for (int id : ids) { + missingIds.add(id); + } + for (RecordedEvent event : getSimpleEvents(events)) { + int id = Events.assertField(event, "id").getValue(); + System.out.printf("event.id=%d%n", id); + missingIds.remove(new Integer(id)); + } + if (!missingIds.isEmpty()) { + missingIds.forEach(id -> System.out.println("Missing MyEvent with id " + id)); + Asserts.fail("Missing some MyEvent events"); + } + } + + public static void verifyNotContains(List events, int ... ids) throws Exception { + for (RecordedEvent event : getSimpleEvents(events)) { + int eventId = Events.assertField(event, "id").getValue(); + System.out.printf("event.id=%d%n", eventId); + for (int id : ids) { + Events.assertField(event, "id").notEqual(id); + } + } + } + + public static List getSimpleEvents(List events) { + List myEvents = new ArrayList<>(); + for (RecordedEvent event : events) { + if (Events.isEventType(event, SimpleEvent.class.getName())) { + myEvents.add(event); + } + } + return myEvents; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleSetting.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleSetting.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleSetting.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/SimpleSetting.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import java.util.Set; + +import jdk.jfr.SettingControl; + +public class SimpleSetting extends SettingControl { + + @Override + public String combine(Set settingValue) { + return "none"; + } + + @Override + public void setValue(String value) { + } + + @Override + public String getValue() { + return "none"; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Stressor.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Stressor.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Stressor.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/Stressor.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.jfr; + +import java.util.ArrayList; +import java.util.List; + +/** + * Class to help run multiple threads executing some task + * + * + * @since 1.9 + */ +public class Stressor { + public static void execute(int numberOfThreads, Thread.UncaughtExceptionHandler eh, Runnable task) throws Exception { + List threads = new ArrayList<>(); + for (int n = 0; n < numberOfThreads; ++n) { + Thread t = new Thread(task); + t.setUncaughtExceptionHandler(eh); + threads.add(t); + t.start(); + } + for (Thread t : threads) { + t.join(); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/TestClassLoader.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/TestClassLoader.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/TestClassLoader.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/TestClassLoader.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Custom class loader which will try to load the class via getResourceAsStream(). + * If there are any errors, the parent class loader will be used instead. + */ +public class TestClassLoader extends ClassLoader { + static public final String CLASS_LOADER_NAME = "jdk/test/lib/jfr/TestClassLoader";// XXX since JDK 9 "JFR TestClassLoader"; + + public TestClassLoader() { + //super(CLASS_LOADER_NAME, ClassLoader.getSystemClassLoader()); + super(ClassLoader.getSystemClassLoader()); + } + + public Class loadClass(String name) throws ClassNotFoundException { + + InputStream is = null; + DataInputStream dis = null; + try { + String resourceName = name.replace('.', '/') + ".class"; + is = getResourceAsStream(resourceName); + if (is != null) { + int i = is.available(); + byte buf[] = new byte[i]; + dis = new DataInputStream(is); + dis.readFully(buf); + dis.close(); + return defineClass(name, buf, 0, buf.length); + } + } catch (SecurityException e) { + // This error will happen quite often (for example when loading + // "java.lang..."). + // Ignore this error and use parent class loader. + } catch (IOException e) { + // Unexpected error. Use parent class loader. + e.printStackTrace(); + } finally { + if (dis != null) { + try { + dis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return super.loadClass(name); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/VoidFunction.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/VoidFunction.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/VoidFunction.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/jfr/VoidFunction.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.jfr; + +@FunctionalInterface +public interface VoidFunction { + void run() throws Throwable; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/DynamicVMOption.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/DynamicVMOption.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/DynamicVMOption.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/DynamicVMOption.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.management; + +import com.sun.management.HotSpotDiagnosticMXBean; +import java.lang.management.ManagementFactory; + +/** + * A utility class to work with VM options which could be altered during + * execution. + * + * This class is a wrapper around {@code com.sun.management.VMOption}. + * It provides more convenient interface to read/write the values. + * + */ +public class DynamicVMOption { + + private final HotSpotDiagnosticMXBean mxBean; + + /** + * VM option name, like "MinHeapFreeRatio". + */ + public final String name; + + /** + * Creates an instance of DynamicVMOption. + * + * @param name the VM option name + */ + public DynamicVMOption(String name) { + this.name = name; + mxBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); + } + + /** + * Sets a new value for the option. + * Trying to set not applicable value will cause IllegalArgumentException. + * Behavior with null is undefined, most likely NPE will be thrown. + * + * @param newValue the value to be set + * @see #getValue() + * @throws IllegalArgumentException if newValue is not applicable to the option + */ + public final void setValue(String newValue) { + mxBean.setVMOption(name, newValue); + } + + /** + * Returns the value of option. + * + * @return the current option value + * @see #setValue(java.lang.String) + */ + public final String getValue() { + return mxBean.getVMOption(name).getValue(); + } + + /** + * Returns true, if option is writable, false otherwise. + * + * @return true, if option is writable, false otherwise + */ + public final boolean isWriteable() { + return mxBean.getVMOption(name).isWriteable(); + } + + /** + * Checks if the given value is applicable for the option. + * + * This method tries to set the option to the new value. If no exception + * has been thrown the value is treated as valid. + * + * Calling this method will not change the option value. After an attempt + * to set a new value, the option will be restored to its previous value. + * + * @param value the value to verify + * @return true if option could be set to the given value + */ + public boolean isValidValue(String value) { + boolean isValid = true; + String oldValue = getValue(); + try { + setValue(value); + } catch (NullPointerException e) { + if (value == null) { + isValid = false; + } + } catch (IllegalArgumentException e) { + isValid = false; + } finally { + setValue(oldValue); + } + return isValid; + } + + /** + * Returns the value of the given VM option as String. + * + * This is a simple shortcut for {@code new DynamicVMOption(name).getValue()} + * + * @param name the name of VM option + * @return value as a string + * @see #getValue() + */ + public static String getString(String name) { + return new DynamicVMOption(name).getValue(); + } + + /** + * Returns the value of the given option as int. + * + * @param name the name of VM option + * @return value parsed as integer + * @see #getString(java.lang.String) + * + */ + public static int getInt(String name) { + return Integer.parseInt(getString(name)); + } + + /** + * Sets the VM option to a new value. + * + * This is a simple shortcut for {@code new DynamicVMOption(name).setValue(value)} + * + * @param name the name of VM option + * @param value the value to be set + * @see #setValue(java.lang.String) + */ + public static void setString(String name, String value) { + new DynamicVMOption(name).setValue(value); + } + + /** + * Sets the VM option value to a new integer value. + * + * @param name the name of VM option + * @param value the integer value to be set + * @see #setString(java.lang.String, java.lang.String) + */ + public static void setInt(String name, int value) { + new DynamicVMOption(name).setValue(Integer.toString(value)); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/InputArguments.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/InputArguments.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/InputArguments.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/InputArguments.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.util.List; + +public class InputArguments { + /** + * Gets the array of strings containing input arguments passed to the VM + * + * @return arguments + */ + public static String[] getVmInputArgs() { + RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); + List args = runtime.getInputArguments(); + return args.toArray(new String[args.size()]); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/management/ThreadMXBeanTool.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; + +/** + * A few utility methods to use ThreadMXBean. + */ +public final class ThreadMXBeanTool { + + /** + * Waits until {@link Thread} is in the certain {@link Thread.State} + * and blocking on {@code object}. + * + * @param state The thread state + * @param object The object to block on + */ + public static void waitUntilBlockingOnObject(Thread thread, Thread.State state, Object object) + throws InterruptedException { + String want = object == null ? null : object.getClass().getName() + '@' + + Integer.toHexString(System.identityHashCode(object)); + ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); + while (thread.isAlive()) { + ThreadInfo ti = tmx.getThreadInfo(thread.getId()); + if (ti.getThreadState() == state + && (want == null || want.equals(ti.getLockName()))) { + return; + } + Thread.sleep(1); + } + } + + /** + * Waits until {@link Thread} is in native. + */ + public static void waitUntilInNative(Thread thread) throws InterruptedException { + ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); + while (thread.isAlive()) { + ThreadInfo ti = tmx.getThreadInfo(thread.getId()); + if (ti.isInNative()) { + return; + } + Thread.sleep(1); + } + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ExitCode.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ExitCode.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ExitCode.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ExitCode.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.process; + +/** + * Exit code values that could be returned by the JVM. + */ +public enum ExitCode { + OK(0), + FAIL(1), + CRASH(134); + + public final int value; + + ExitCode(int value) { + this.value = value; + } +} + diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputAnalyzer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputAnalyzer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputAnalyzer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputAnalyzer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,557 @@ +/* + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.process; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class OutputAnalyzer { + + private final String stdout; + private final String stderr; + private final int exitValue; + + /** + * Create an OutputAnalyzer, a utility class for verifying output and exit + * value from a Process + * + * @param process Process to analyze + * @throws IOException If an I/O error occurs. + */ + public OutputAnalyzer(Process process) throws IOException { + OutputBuffer output = ProcessTools.getOutput(process); + exitValue = process.exitValue(); + this.stdout = output.getStdout(); + this.stderr = output.getStderr(); + } + + /** + * Create an OutputAnalyzer, a utility class for verifying output + * + * @param buf String buffer to analyze + */ + public OutputAnalyzer(String buf) { + this(buf, buf); + } + + /** + * Create an OutputAnalyzer, a utility class for verifying output + * + * @param stdout stdout buffer to analyze + * @param stderr stderr buffer to analyze + */ + public OutputAnalyzer(String stdout, String stderr) { + this.stdout = stdout; + this.stderr = stderr; + exitValue = -1; + } + + /** + * Verify that the stdout contents of output buffer is empty + * + * @throws RuntimeException + * If stdout was not empty + */ + public void stdoutShouldBeEmpty() { + if (!getStdout().isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stdout was not empty"); + } + } + + /** + * Verify that the stderr contents of output buffer is empty + * + * @throws RuntimeException + * If stderr was not empty + */ + public void stderrShouldBeEmpty() { + if (!getStderr().isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stderr was not empty"); + } + } + + /** + * Verify that the stderr contents of output buffer is empty, + * after filtering out the Hotspot warning messages + * + * @throws RuntimeException + * If stderr was not empty + */ + public void stderrShouldBeEmptyIgnoreVMWarnings() { + if (!getStderr().replaceAll(jvmwarningmsg + "\\R", "").isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stderr was not empty"); + } + } + + /** + * Verify that the stdout contents of output buffer is not empty + * + * @throws RuntimeException + * If stdout was empty + */ + public void stdoutShouldNotBeEmpty() { + if (getStdout().isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stdout was empty"); + } + } + + /** + * Verify that the stderr contents of output buffer is not empty + * + * @throws RuntimeException + * If stderr was empty + */ + public void stderrShouldNotBeEmpty() { + if (getStderr().isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stderr was empty"); + } + } + + /** + * Verify that the stdout and stderr contents of output buffer contains the string + * + * @param expectedString String that buffer should contain + * @throws RuntimeException If the string was not found + */ + public OutputAnalyzer shouldContain(String expectedString) { + if (!stdout.contains(expectedString) && !stderr.contains(expectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + expectedString + "' missing from stdout/stderr \n"); + } + return this; + } + + /** + * Verify that the stdout contents of output buffer contains the string + * + * @param expectedString String that buffer should contain + * @throws RuntimeException If the string was not found + */ + public OutputAnalyzer stdoutShouldContain(String expectedString) { + if (!stdout.contains(expectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + expectedString + "' missing from stdout \n"); + } + return this; + } + + /** + * Verify that the stderr contents of output buffer contains the string + * + * @param expectedString String that buffer should contain + * @throws RuntimeException If the string was not found + */ + public OutputAnalyzer stderrShouldContain(String expectedString) { + if (!stderr.contains(expectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + expectedString + "' missing from stderr \n"); + } + return this; + } + + /** + * Verify that the stdout and stderr contents of output buffer does not contain the string + * + * @param expectedString String that the buffer should not contain + * @throws RuntimeException If the string was found + */ + public OutputAnalyzer shouldNotContain(String notExpectedString) { + if (stdout.contains(notExpectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + notExpectedString + "' found in stdout \n"); + } + if (stderr.contains(notExpectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + notExpectedString + "' found in stderr \n"); + } + return this; + } + + /** + * Verify that the stdout and stderr contents of output buffer are empty + * + * @throws RuntimeException If the stdout and stderr are not empty + */ + public OutputAnalyzer shouldBeEmpty() { + if (!stdout.isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stdout was not empty"); + } + if (!stderr.isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stderr was not empty"); + } + return this; + } + + /** + * Verify that the stdout contents of output buffer does not contain the string + * + * @param expectedString String that the buffer should not contain + * @throws RuntimeException If the string was found + */ + public OutputAnalyzer stdoutShouldNotContain(String notExpectedString) { + if (stdout.contains(notExpectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + notExpectedString + "' found in stdout \n"); + } + return this; + } + + /** + * Verify that the stderr contents of output buffer does not contain the string + * + * @param expectedString String that the buffer should not contain + * @throws RuntimeException If the string was found + */ + public OutputAnalyzer stderrShouldNotContain(String notExpectedString) { + if (stderr.contains(notExpectedString)) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + notExpectedString + "' found in stderr \n"); + } + return this; + } + + /** + * Verify that the stdout and stderr contents of output buffer matches + * the pattern + * + * @param pattern + * @throws RuntimeException If the pattern was not found + */ + public OutputAnalyzer shouldMatch(String pattern) { + Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); + Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + if (!stdoutMatcher.find() && !stderrMatcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' missing from stdout/stderr \n"); + } + return this; + } + + /** + * Verify that the stdout contents of output buffer matches the + * pattern + * + * @param pattern + * @throws RuntimeException If the pattern was not found + */ + public OutputAnalyzer stdoutShouldMatch(String pattern) { + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); + if (!matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' missing from stdout \n"); + } + return this; + } + + /** + * Verify that the stderr contents of output buffer matches the + * pattern + * + * @param pattern + * @throws RuntimeException If the pattern was not found + */ + public OutputAnalyzer stderrShouldMatch(String pattern) { + + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + if (!matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' missing from stderr \n"); + } + return this; + } + + /** + * Verify that the stdout and stderr contents of output buffer does not + * match the pattern + * + * @param pattern + * @throws RuntimeException If the pattern was found + */ + public OutputAnalyzer shouldNotMatch(String pattern) { + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); + if (matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' found in stdout: '" + matcher.group() + "' \n"); + } + matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + if (matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' found in stderr: '" + matcher.group() + "' \n"); + } + return this; + } + + /** + * Verify that the stdout contents of output buffer does not match the + * pattern + * + * @param pattern + * @throws RuntimeException If the pattern was found + */ + public OutputAnalyzer stdoutShouldNotMatch(String pattern) { + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); + if (matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' found in stdout \n"); + } + return this; + } + + /** + * Verify that the stderr contents of output buffer does not match the + * pattern + * + * @param pattern + * @throws RuntimeException If the pattern was found + */ + public OutputAnalyzer stderrShouldNotMatch(String pattern) { + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + if (matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' found in stderr \n"); + } + return this; + } + + /** + * Get the captured group of the first string matching the pattern. + * stderr is searched before stdout. + * + * @param pattern The multi-line pattern to match + * @param group The group to capture + * @return The matched string or null if no match was found + */ + public String firstMatch(String pattern, int group) { + Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout); + if (stderrMatcher.find()) { + return stderrMatcher.group(group); + } + if (stdoutMatcher.find()) { + return stdoutMatcher.group(group); + } + return null; + } + + /** + * Get the first string matching the pattern. + * stderr is searched before stdout. + * + * @param pattern The multi-line pattern to match + * @return The matched string or null if no match was found + */ + public String firstMatch(String pattern) { + return firstMatch(pattern, 0); + } + + /** + * Verify the exit value of the process + * + * @param expectedExitValue Expected exit value from process + * @throws RuntimeException If the exit value from the process did not match the expected value + */ + public OutputAnalyzer shouldHaveExitValue(int expectedExitValue) { + if (getExitValue() != expectedExitValue) { + reportDiagnosticSummary(); + throw new RuntimeException("Expected to get exit value of [" + + expectedExitValue + "]\n"); + } + return this; + } + + /** + * Verify the exit value of the process + * + * @param notExpectedExitValue Unexpected exit value from process + * @throws RuntimeException If the exit value from the process did match the expected value + */ + public OutputAnalyzer shouldNotHaveExitValue(int notExpectedExitValue) { + if (getExitValue() == notExpectedExitValue) { + reportDiagnosticSummary(); + throw new RuntimeException("Unexpected to get exit value of [" + + notExpectedExitValue + "]\n"); + } + return this; + } + + + /** + * Report summary that will help to diagnose the problem + * Currently includes: + * - standard input produced by the process under test + * - standard output + * - exit code + * Note: the command line is printed by the ProcessTools + */ + public void reportDiagnosticSummary() { + String msg = + " stdout: [" + stdout + "];\n" + + " stderr: [" + stderr + "]\n" + + " exitValue = " + getExitValue() + "\n"; + + System.err.println(msg); + } + + /** + * Print the stdout buffer to the given {@code PrintStream}. + * + * @return this OutputAnalyzer + */ + public OutputAnalyzer outputTo(PrintStream out) { + out.println(getStdout()); + return this; + } + + /** + * Print the stderr buffer to the given {@code PrintStream}. + * + * @return this OutputAnalyzer + */ + public OutputAnalyzer errorTo(PrintStream out) { + out.println(getStderr()); + return this; + } + + /** + * Get the contents of the output buffer (stdout and stderr) + * + * @return Content of the output buffer + */ + public String getOutput() { + return stdout + stderr; + } + + /** + * Get the contents of the stdout buffer + * + * @return Content of the stdout buffer + */ + public String getStdout() { + return stdout; + } + + /** + * Get the contents of the stderr buffer + * + * @return Content of the stderr buffer + */ + public String getStderr() { + return stderr; + } + + /** + * Get the process exit value + * + * @return Process exit value + */ + public int getExitValue() { + return exitValue; + } + + /** + * Get the contents of the output buffer (stdout and stderr) as list of strings. + * Output will be split by newlines. + * + * @return Contents of the output buffer as list of strings + */ + public List asLines() { + return asLines(getOutput()); + } + + private List asLines(String buffer) { + return Arrays.asList(buffer.split("(\\r\\n|\\n|\\r)")); + } + + + private static final String jvmwarningmsg = ".* VM warning:.*"; + + /** + * Verifies that the stdout and stderr contents of output buffer are empty, after + * filtering out the HotSpot warning messages. + * + * @throws RuntimeException If the stdout and stderr are not empty + */ + public OutputAnalyzer shouldBeEmptyIgnoreVMWarnings() { + if (!stdout.isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stdout was not empty"); + } + if (!stderr.replaceAll(jvmwarningmsg + "\\R", "").isEmpty()) { + reportDiagnosticSummary(); + throw new RuntimeException("stderr was not empty"); + } + return this; + } + + /** + * Verify that the stderr contents of output buffer matches the pattern, + * after filtering out the Hotespot warning messages + * + * @param pattern + * @throws RuntimeException If the pattern was not found + */ + public OutputAnalyzer stderrShouldMatchIgnoreVMWarnings(String pattern) { + String stderr = this.stderr.replaceAll(jvmwarningmsg + "\\R", ""); + Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr); + if (!matcher.find()) { + reportDiagnosticSummary(); + throw new RuntimeException("'" + pattern + + "' missing from stderr \n"); + } + return this; + } + + /** + * Returns the contents of the output buffer (stdout and stderr), without those + * JVM warning msgs, as list of strings. Output is split by newlines. + * + * @return Contents of the output buffer as list of strings + */ + public List asLinesWithoutVMWarnings() { + return Arrays.asList(getOutput().split("\\R")) + .stream() + .filter(Pattern.compile(jvmwarningmsg).asPredicate().negate()) + .collect(Collectors.toList()); + } + +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputBuffer.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputBuffer.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputBuffer.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/OutputBuffer.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.process; + +public class OutputBuffer { + private final String stdout; + private final String stderr; + + /** + * Create an OutputBuffer, a class for storing and managing stdout and stderr + * results separately + * + * @param stdout stdout result + * @param stderr stderr result + */ + public OutputBuffer(String stdout, String stderr) { + this.stdout = stdout; + this.stderr = stderr; + } + + /** + * Returns the stdout result + * + * @return stdout result + */ + public String getStdout() { + return stdout; + } + + /** + * Returns the stderr result + * + * @return stderr result + */ + public String getStderr() { + return stderr; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ProcessTools.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ProcessTools.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ProcessTools.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/ProcessTools.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,596 @@ +/* + * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.process; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Predicate; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.lang.management.ManagementFactory; + +import jdk.test.lib.JDKToolFinder; +import jdk.test.lib.Utils; + +public final class ProcessTools { + private static final class LineForwarder extends StreamPumper.LinePump { + private final PrintStream ps; + private final String prefix; + LineForwarder(String prefix, PrintStream os) { + this.ps = os; + this.prefix = prefix; + } + @Override + protected void processLine(String line) { + ps.println("[" + prefix + "] " + line); + } + } + + private ProcessTools() { + } + + /** + * Pumps stdout and stderr from running the process into a String. + * + * @param processBuilder ProcessBuilder to run. + * @return Output from process. + * @throws IOException If an I/O error occurs. + */ + public static OutputBuffer getOutput(ProcessBuilder processBuilder) throws IOException { + return getOutput(processBuilder.start()); + } + + /** + * Pumps stdout and stderr the running process into a String. + * + * @param process Process to pump. + * @return Output from process. + * @throws IOException If an I/O error occurs. + */ + public static OutputBuffer getOutput(Process process) throws IOException { + ByteArrayOutputStream stderrBuffer = new ByteArrayOutputStream(); + ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream(); + StreamPumper outPumper = new StreamPumper(process.getInputStream(), stdoutBuffer); + StreamPumper errPumper = new StreamPumper(process.getErrorStream(), stderrBuffer); + Thread outPumperThread = new Thread(outPumper); + Thread errPumperThread = new Thread(errPumper); + + outPumperThread.setDaemon(true); + errPumperThread.setDaemon(true); + + outPumperThread.start(); + errPumperThread.start(); + + try { + process.waitFor(); + outPumperThread.join(); + errPumperThread.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } + + return new OutputBuffer(stdoutBuffer.toString(), stderrBuffer.toString()); + } + + /** + *

Starts a process from its builder.

+ * The default redirects of STDOUT and STDERR are started + * @param name The process name + * @param processBuilder The process builder + * @return Returns the initialized process + * @throws IOException + */ + public static Process startProcess(String name, + ProcessBuilder processBuilder) + throws IOException { + return startProcess(name, processBuilder, (Consumer)null); + } + + /** + *

Starts a process from its builder.

+ * The default redirects of STDOUT and STDERR are started + *

It is possible to monitor the in-streams via the provided {@code consumer} + * @param name The process name + * @param consumer {@linkplain Consumer} instance to process the in-streams + * @param processBuilder The process builder + * @return Returns the initialized process + * @throws IOException + */ + @SuppressWarnings("overloads") + public static Process startProcess(String name, + ProcessBuilder processBuilder, + Consumer consumer) + throws IOException { + try { + return startProcess(name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS); + } catch (InterruptedException | TimeoutException e) { + // will never happen + throw new RuntimeException(e); + } + } + + /** + *

Starts a process from its builder.

+ * The default redirects of STDOUT and STDERR are started + *

+ * It is possible to wait for the process to get to a warmed-up state + * via {@linkplain Predicate} condition on the STDOUT + *

+ * @param name The process name + * @param processBuilder The process builder + * @param linePredicate The {@linkplain Predicate} to use on the STDOUT + * Used to determine the moment the target app is + * properly warmed-up. + * It can be null - in that case the warmup is skipped. + * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever + * @param unit The timeout {@linkplain TimeUnit} + * @return Returns the initialized {@linkplain Process} + * @throws IOException + * @throws InterruptedException + * @throws TimeoutException + */ + public static Process startProcess(String name, + ProcessBuilder processBuilder, + final Predicate linePredicate, + long timeout, + TimeUnit unit) + throws IOException, InterruptedException, TimeoutException { + return startProcess(name, processBuilder, null, linePredicate, timeout, unit); + } + + /** + *

Starts a process from its builder.

+ * The default redirects of STDOUT and STDERR are started + *

+ * It is possible to wait for the process to get to a warmed-up state + * via {@linkplain Predicate} condition on the STDOUT and monitor the + * in-streams via the provided {@linkplain Consumer} + *

+ * @param name The process name + * @param processBuilder The process builder + * @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to + * @param linePredicate The {@linkplain Predicate} to use on the STDOUT + * Used to determine the moment the target app is + * properly warmed-up. + * It can be null - in that case the warmup is skipped. + * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever + * @param unit The timeout {@linkplain TimeUnit} + * @return Returns the initialized {@linkplain Process} + * @throws IOException + * @throws InterruptedException + * @throws TimeoutException + */ + public static Process startProcess(String name, + ProcessBuilder processBuilder, + final Consumer lineConsumer, + final Predicate linePredicate, + long timeout, + TimeUnit unit) + throws IOException, InterruptedException, TimeoutException { + System.out.println("["+name+"]:" + processBuilder.command().stream().collect(Collectors.joining(" "))); + Process p = processBuilder.start(); + StreamPumper stdout = new StreamPumper(p.getInputStream()); + StreamPumper stderr = new StreamPumper(p.getErrorStream()); + + stdout.addPump(new LineForwarder(name, System.out)); + stderr.addPump(new LineForwarder(name, System.err)); + if (lineConsumer != null) { + StreamPumper.LinePump pump = new StreamPumper.LinePump() { + @Override + protected void processLine(String line) { + lineConsumer.accept(line); + } + }; + stdout.addPump(pump); + stderr.addPump(pump); + } + + + CountDownLatch latch = new CountDownLatch(1); + if (linePredicate != null) { + StreamPumper.LinePump pump = new StreamPumper.LinePump() { + @Override + protected void processLine(String line) { + if (latch.getCount() > 0 && linePredicate.test(line)) { + latch.countDown(); + } + } + }; + stdout.addPump(pump); + stderr.addPump(pump); + } else { + latch.countDown(); + } + final Future stdoutTask = stdout.process(); + final Future stderrTask = stderr.process(); + + try { + if (timeout > -1) { + if (timeout == 0) { + latch.await(); + } else { + if (!latch.await(Utils.adjustTimeout(timeout), unit)) { + throw new TimeoutException(); + } + } + } + } catch (TimeoutException | InterruptedException e) { + System.err.println("Failed to start a process (thread dump follows)"); + for(Map.Entry s : Thread.getAllStackTraces().entrySet()) { + printStack(s.getKey(), s.getValue()); + } + + if (p.isAlive()) { + p.destroyForcibly(); + } + + stdoutTask.cancel(true); + stderrTask.cancel(true); + throw e; + } + + return new ProcessImpl(p, stdoutTask, stderrTask); + } + + /** + *

Starts a process from its builder.

+ * The default redirects of STDOUT and STDERR are started + *

+ * It is possible to wait for the process to get to a warmed-up state + * via {@linkplain Predicate} condition on the STDOUT. The warm-up will + * wait indefinitely. + *

+ * @param name The process name + * @param processBuilder The process builder + * @param linePredicate The {@linkplain Predicate} to use on the STDOUT + * Used to determine the moment the target app is + * properly warmed-up. + * It can be null - in that case the warmup is skipped. + * @return Returns the initialized {@linkplain Process} + * @throws IOException + * @throws InterruptedException + * @throws TimeoutException + */ + @SuppressWarnings("overloads") + public static Process startProcess(String name, + ProcessBuilder processBuilder, + final Predicate linePredicate) + throws IOException, InterruptedException, TimeoutException { + return startProcess(name, processBuilder, linePredicate, 0, TimeUnit.SECONDS); + } + + /** + * Get the process id of the current running Java process + * + * @return Process id + */ + public static long getProcessId() throws Exception { + final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + + final int index = jvmName.indexOf('@'); + + if (index < 1) { + // part before '@' empty (index = 0) / '@' not found (index = -1) + return 42; + } + + try { + return Long.parseLong(jvmName.substring(0, index)); + } catch (NumberFormatException e) { + // ignore + } + return 42; + } + + + + /** + * Create ProcessBuilder using the java launcher from the jdk to be tested and + * with any platform specific arguments prepended + */ + public static ProcessBuilder createJavaProcessBuilder(String... command) { + return createJavaProcessBuilder(false, command); + } + + /** + * Create ProcessBuilder using the java launcher from the jdk to be tested, + * and with any platform specific arguments prepended. + * + * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts + * to the java arguments. + * @param command Arguments to pass to the java command. + * @return The ProcessBuilder instance representing the java command. + */ + public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) { + String javapath = JDKToolFinder.getJDKTool("java"); + + ArrayList args = new ArrayList<>(); + args.add(javapath); + + args.add("-cp"); + args.add(System.getProperty("java.class.path")); + + if (addTestVmAndJavaOptions) { + Collections.addAll(args, Utils.getTestJavaOpts()); + } + + Collections.addAll(args, command); + + // Reporting + StringBuilder cmdLine = new StringBuilder(); + for (String cmd : args) + cmdLine.append(cmd).append(' '); + System.out.println("Command line: [" + cmdLine.toString() + "]"); + + return new ProcessBuilder(args.toArray(new String[args.size()])); + } + + private static void printStack(Thread t, StackTraceElement[] stack) { + System.out.println("\t" + t + + " stack: (length = " + stack.length + ")"); + if (t != null) { + for (StackTraceElement stack1 : stack) { + System.out.println("\t" + stack1); + } + System.out.println(); + } + } + + /** + * Executes a test jvm process, waits for it to finish and returns the process output. + * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. + * The java from the test.jdk is used to execute the command. + * + * The command line will be like: + * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds + * + * The jvm process will have exited before this method returns. + * + * @param cmds User specified arguments. + * @return The output from the process. + */ + public static OutputAnalyzer executeTestJvm(String... cmds) throws Exception { + ProcessBuilder pb = createJavaProcessBuilder(Utils.addTestJavaOpts(cmds)); + return executeProcess(pb); + } + + /** + * @see #executeTestJvm(String...) + * @param cmds User specified arguments. + * @return The output from the process. + */ + public static OutputAnalyzer executeTestJava(String... cmds) throws Exception { + return executeTestJvm(cmds); + } + + /** + * Executes a process, waits for it to finish and returns the process output. + * The process will have exited before this method returns. + * @param pb The ProcessBuilder to execute. + * @return The {@linkplain OutputAnalyzer} instance wrapping the process. + */ + public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Exception { + OutputAnalyzer output = null; + Process p = null; + boolean failed = false; + try { + p = pb.start(); + output = new OutputAnalyzer(p); + p.waitFor(); + + return output; + } catch (Throwable t) { + if (p != null) { + p.destroyForcibly().waitFor(); + } + + failed = true; + System.out.println("executeProcess() failed: " + t); + throw t; + } finally { + if (failed) { + System.err.println(getProcessLog(pb, output)); + } + } + } + + /** + * Executes a process, waits for it to finish and returns the process output. + * + * The process will have exited before this method returns. + * + * @param cmds The command line to execute. + * @return The output from the process. + */ + public static OutputAnalyzer executeProcess(String... cmds) throws Throwable { + return executeProcess(new ProcessBuilder(cmds)); + } + + /** + * Used to log command line, stdout, stderr and exit code from an executed process. + * @param pb The executed process. + * @param output The output from the process. + */ + public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) { + String stderr = output == null ? "null" : output.getStderr(); + String stdout = output == null ? "null" : output.getStdout(); + String exitValue = output == null ? "null": Integer.toString(output.getExitValue()); + StringBuilder logMsg = new StringBuilder(); + final String nl = System.getProperty("line.separator"); + logMsg.append("--- ProcessLog ---" + nl); + logMsg.append("cmd: " + getCommandLine(pb) + nl); + logMsg.append("exitvalue: " + exitValue + nl); + logMsg.append("stderr: " + stderr + nl); + logMsg.append("stdout: " + stdout + nl); + + return logMsg.toString(); + } + + /** + * @return The full command line for the ProcessBuilder. + */ + public static String getCommandLine(ProcessBuilder pb) { + if (pb == null) { + return "null"; + } + StringBuilder cmd = new StringBuilder(); + for (String s : pb.command()) { + cmd.append(s).append(" "); + } + return cmd.toString().trim(); + } + + /** + * Executes a process, waits for it to finish, prints the process output + * to stdout, and returns the process output. + * + * The process will have exited before this method returns. + * + * @param cmds The command line to execute. + * @return The {@linkplain OutputAnalyzer} instance wrapping the process. + */ + public static OutputAnalyzer executeCommand(String... cmds) + throws Throwable { + String cmdLine = Arrays.stream(cmds).collect(Collectors.joining(" ")); + System.out.println("Command line: [" + cmdLine + "]"); + OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds); + System.out.println(analyzer.getOutput()); + return analyzer; + } + + /** + * Executes a process, waits for it to finish, prints the process output + * to stdout and returns the process output. + * + * The process will have exited before this method returns. + * + * @param pb The ProcessBuilder to execute. + * @return The {@linkplain OutputAnalyzer} instance wrapping the process. + */ + public static OutputAnalyzer executeCommand(ProcessBuilder pb) + throws Throwable { + String cmdLine = pb.command().stream().collect(Collectors.joining(" ")); + System.out.println("Command line: [" + cmdLine + "]"); + OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); + System.out.println(analyzer.getOutput()); + return analyzer; + } + + private static class ProcessImpl extends Process { + + private final Process p; + private final Future stdoutTask; + private final Future stderrTask; + + public ProcessImpl(Process p, Future stdoutTask, Future stderrTask) { + this.p = p; + this.stdoutTask = stdoutTask; + this.stderrTask = stderrTask; + } + + @Override + public OutputStream getOutputStream() { + return p.getOutputStream(); + } + + @Override + public InputStream getInputStream() { + return p.getInputStream(); + } + + @Override + public InputStream getErrorStream() { + return p.getErrorStream(); + } + + @Override + public int waitFor() throws InterruptedException { + int rslt = p.waitFor(); + waitForStreams(); + return rslt; + } + + @Override + public int exitValue() { + return p.exitValue(); + } + + @Override + public void destroy() { + p.destroy(); + } + + public long pid() { + try { + return ProcessTools.getProcessId(); + } catch (Exception e) { + //shit happens, ignore + } + return 42; + } + + @Override + public boolean isAlive() { + return p.isAlive(); + } + + @Override + public Process destroyForcibly() { + return p.destroyForcibly(); + } + + @Override + public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { + boolean rslt = p.waitFor(timeout, unit); + if (rslt) { + waitForStreams(); + } + return rslt; + } + + private void waitForStreams() throws InterruptedException { + try { + stdoutTask.get(); + } catch (ExecutionException e) { + } + try { + stderrTask.get(); + } catch (ExecutionException e) { + } + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/StreamPumper.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/StreamPumper.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/StreamPumper.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/process/StreamPumper.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.process; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.atomic.AtomicBoolean; + +public final class StreamPumper implements Runnable { + + private static final int BUF_SIZE = 256; + + /** + * Pump will be called by the StreamPumper to process the incoming data + */ + abstract public static class Pump { + abstract void register(StreamPumper d); + } + + /** + * OutputStream -> Pump adapter + */ + final public static class StreamPump extends Pump { + private final OutputStream out; + public StreamPump(OutputStream out) { + this.out = out; + } + + @Override + void register(StreamPumper sp) { + sp.addOutputStream(out); + } + } + + /** + * Used to process the incoming data line-by-line + */ + abstract public static class LinePump extends Pump { + @Override + final void register(StreamPumper sp) { + sp.addLineProcessor(this); + } + + abstract protected void processLine(String line); + } + + private final InputStream in; + private final Set outStreams = new HashSet<>(); + private final Set linePumps = new HashSet<>(); + + private final AtomicBoolean processing = new AtomicBoolean(false); + private final FutureTask processingTask = new FutureTask<>(this, null); + + public StreamPumper(InputStream in) { + this.in = in; + } + + /** + * Create a StreamPumper that reads from in and writes to out. + * + * @param in The stream to read from. + * @param out The stream to write to. + */ + public StreamPumper(InputStream in, OutputStream out) { + this(in); + this.addOutputStream(out); + } + + /** + * Implements Thread.run(). Continuously read from {@code in} and write to + * {@code out} until {@code in} has reached end of stream. Abort on + * interruption. Abort on IOExceptions. + */ + @Override + public void run() { + try (BufferedInputStream is = new BufferedInputStream(in)) { + ByteArrayOutputStream lineBos = new ByteArrayOutputStream(); + byte[] buf = new byte[BUF_SIZE]; + int len = 0; + int linelen = 0; + + while ((len = is.read(buf)) > 0 && !Thread.interrupted()) { + for(OutputStream out : outStreams) { + out.write(buf, 0, len); + } + if (!linePumps.isEmpty()) { + int i = 0; + int lastcrlf = -1; + while (i < len) { + if (buf[i] == '\n' || buf[i] == '\r') { + int bufLinelen = i - lastcrlf - 1; + if (bufLinelen > 0) { + lineBos.write(buf, lastcrlf + 1, bufLinelen); + } + linelen += bufLinelen; + + if (linelen > 0) { + lineBos.flush(); + final String line = lineBos.toString(); + linePumps.stream().forEach((lp) -> { + lp.processLine(line); + }); + lineBos.reset(); + linelen = 0; + } + lastcrlf = i; + } + + i++; + } + if (lastcrlf == -1) { + lineBos.write(buf, 0, len); + linelen += len; + } else if (lastcrlf < len - 1) { + lineBos.write(buf, lastcrlf + 1, len - lastcrlf - 1); + linelen += len - lastcrlf - 1; + } + } + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + for(OutputStream out : outStreams) { + try { + out.flush(); + } catch (IOException e) {} + } + try { + in.close(); + } catch (IOException e) {} + } + } + + final void addOutputStream(OutputStream out) { + outStreams.add(out); + } + + final void addLineProcessor(LinePump lp) { + linePumps.add(lp); + } + + final public StreamPumper addPump(Pump ... pump) { + if (processing.get()) { + throw new IllegalStateException("Can not modify pumper while " + + "processing is in progress"); + } + for(Pump p : pump) { + p.register(this); + } + return this; + } + + final public Future process() { + if (!processing.compareAndSet(false, true)) { + throw new IllegalStateException("Can not re-run the processing"); + } + Thread t = new Thread(new Runnable() { + @Override + public void run() { + processingTask.run(); + } + }); + t.setDaemon(true); + t.start(); + + return processingTask; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/TestThread.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/TestThread.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/TestThread.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/TestThread.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.thread; + +import java.util.concurrent.TimeoutException; + +/** + * Thread which catches exceptions thrown during the execution + * and stores them for later analysis. + * + *
+ * {@code
+ * TestThread thread = new TestThread(new XRun() {
+ *      public void run() {
+ *      // do something
+ *      }
+ * });
+ * thread.start();
+ * // do something
+ * Throwable uncaught = thread.getUncaught();
+ * }
+ * 
+ */ +public class TestThread extends Thread { + + private final Runnable runnable; + private volatile Throwable uncaught; + + /** + * Returns {@link Runnable} the thread has been created with. + * + * @return The object whose {@code run} method is called + */ + public Runnable getRunnable() { + return runnable; + } + + /** + * Creates a new {@code TestThread} object. + * + * @param target The object whose {@code run} method is called + * @param name The thread name + */ + public TestThread(Runnable target, String name) { + super(target, name); + this.runnable = target; + } + + /** + * Creates a new {@code TestThread} object. + * + * @param target The object whose {@code run} method is called + */ + public TestThread(Runnable target) { + super(target); + this.runnable = target; + } + + /** + * Creates a new {@code TestThread} object. + * + * @param group The thread group + * @param target The object whose {@code run} method is called + * @param name The thread name + * @param stackSize Stack size + */ + public TestThread(ThreadGroup group, Runnable target, String name, + long stackSize) { + super(group, target, name, stackSize); + this.runnable = target; + } + + /** + * Creates a new {@code TestThread} object. + * + * @param group The thread group + * @param target The object whose {@code run} method is called + * @param name The thread name + */ + public TestThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + this.runnable = target; + } + + /** + * Creates a new {@code TestThread} object. + * + * @param group The thread group + * @param target The object whose {@code run} method is called + */ + public TestThread(ThreadGroup group, Runnable target) { + super(group, target); + this.runnable = target; + } + + /** + * The thread executor. + */ + @Override + public void run() { + try { + super.run(); + } catch (Throwable t) { + uncaught = t; + } + } + + /** + * Returns exception caught during the execution. + * + * @return {@link Throwable} + */ + public Throwable getUncaught() { + return uncaught; + } + + /** + * Waits for {@link TestThread} to die + * and throws exception caught during the execution. + * + * @throws InterruptedException + * @throws Throwable + */ + public void joinAndThrow() throws InterruptedException, Throwable { + join(); + if (uncaught != null) { + throw uncaught; + } + } + + /** + * Waits during {@code timeout} for {@link TestThread} to die + * and throws exception caught during the execution. + * + * @param timeout The time to wait in milliseconds + * @throws InterruptedException + * @throws Throwable + */ + public void joinAndThrow(long timeout) throws InterruptedException, + Throwable { + join(timeout); + if (isAlive()) { + throw new TimeoutException(); + } + if (uncaught != null) { + throw uncaught; + } + } + + /** + * Waits for {@link TestThread} to die + * and returns exception caught during the execution. + * + * @return Exception caught during the execution + * @throws InterruptedException + */ + public Throwable joinAndReturn() throws InterruptedException { + join(); + if (uncaught != null) { + return uncaught; + } + return null; + } + + /** + * Waits during {@code timeout} for {@link TestThread} to die + * and returns exception caught during the execution. + * + * @param timeout The time to wait in milliseconds + * @return Exception caught during the execution + * @throws InterruptedException + */ + public Throwable joinAndReturn(long timeout) throws InterruptedException { + join(timeout); + if (isAlive()) { + return new TimeoutException(); + } + if (uncaught != null) { + return uncaught; + } + return null; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/XRun.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/XRun.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/XRun.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/thread/XRun.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.thread; + +/** + * This type serves no other purpose than to simply allow automatically running + * something in a thread, and have all exceptions propagated to + * RuntimeExceptions, which are thrown up to thread, which in turn should + * probably be a {@link TestThread} to they are stored. + */ +public abstract class XRun implements Runnable { + + /** + * Invokes {@code xrun()} and throws all exceptions caught in it + * up to the thread. + */ + public final void run() { + try { + xrun(); + } catch (Error e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + /** + * Override this method to implement what to run in the thread. + * + * @throws Throwable + */ + protected abstract void xrun() throws Throwable; +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Pair.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Pair.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Pair.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Pair.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.util; + +import java.util.Objects; + +/** + * Pair - a two element tuple + * + * @param first type + * @param second type + */ +public class Pair { + public final F first; + public final S second; + + public Pair(F first, S second) { + this.first = first; + this.second = second; + } + + @Override + public String toString() { + return "(" + first + ":" + second + ")"; + } + + @Override + public boolean equals(Object other) { + if (other instanceof Pair) { + Pair otherPair = (Pair) other; + return Objects.equals(first, otherPair.first) && + Objects.equals(second, otherPair.second); + } + return false; + } + + @Override + public int hashCode() { + if (first == null) { + return (second == null) ? 0 : second.hashCode(); + } else if (second == null) { + return first.hashCode(); + } else { + return first.hashCode() * 17 + second.hashCode(); + } + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/SerializationUtils.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/SerializationUtils.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/SerializationUtils.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/SerializationUtils.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +/** + * Common library for various test serialization utility functions. + */ +public final class SerializationUtils { + /** + * Serialize an object into byte array. + */ + public static byte[] serialize(Object obj) throws IOException { + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bs)) { + out.writeObject(obj); + } + return bs.toByteArray(); + } + + /** + * Deserialize an object from byte array. + */ + public static Object deserialize(byte[] ba) throws IOException, ClassNotFoundException { + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(ba))) { + return in.readObject(); + } + } + private SerializationUtils() {} +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Triple.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Triple.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Triple.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/jdk/test/lib/util/Triple.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test.lib.util; + +import java.util.Objects; + +/** + * Triple - a three element tuple + * + * @param first element type + * @param second element type + * @param third element type + */ +public class Triple { + private final Pair> container; + + /** + * Constructor + * + * @param first first element of the triple + * @param second second element of the triple + * @param third third element of the triple + */ + public Triple(F first, S second, T third) { + container = new Pair<>(first, new Pair<>(second, third)); + } + + /** + * Gets first element of the triple + */ + public F getFirst() { + return container.first; + } + + /** + * Gets second element of the triple + */ + public S getSecond() { + return container.second.first; + } + + /** + * Gets third element of the triple + */ + public T getThird() { + return container.second.second; + } + + @Override + public int hashCode() { + return container.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Triple) { + Triple objTriple = (Triple) obj; + return Objects.equals(container.first, objTriple.container.first) + && Objects.equals(container.second, + objTriple.container.second); + } + return false; + } + + @Override + public String toString() { + return "(" + getFirst() + " : " + getSecond() + " : " + getThird() + ")"; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/WhiteBox.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/WhiteBox.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/WhiteBox.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/WhiteBox.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,450 @@ +/* + * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot; + +import java.lang.management.MemoryUsage; +import java.lang.reflect.Executable; +import java.util.Arrays; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.security.BasicPermission; +import java.util.Objects; +import java.net.URL; + +import sun.hotspot.parser.DiagnosticCommand; + +public class WhiteBox { + @SuppressWarnings("serial") + public static class WhiteBoxPermission extends BasicPermission { + public WhiteBoxPermission(String s) { + super(s); + } + } + + private WhiteBox() {} + private static final WhiteBox instance = new WhiteBox(); + private static native void registerNatives(); + + /** + * Returns the singleton WhiteBox instance. + * + * The returned WhiteBox object should be carefully guarded + * by the caller, since it can be used to read and write data + * at arbitrary memory addresses. It must never be passed to + * untrusted code. + */ + public synchronized static WhiteBox getWhiteBox() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new WhiteBoxPermission("getInstance")); + } + return instance; + } + + static { + registerNatives(); + } + + // Get the maximum heap size supporting COOPs + public native long getCompressedOopsMaxHeapSize(); + // Arguments + public native void printHeapSizes(); + + // Memory + public native long getObjectAddress(Object o); + public native int getHeapOopSize(); + public native int getVMPageSize(); + public native long getVMAllocationGranularity(); + public native long getVMLargePageSize(); + public native long getHeapSpaceAlignment(); + public native long getHeapAlignment(); + + public native boolean isObjectInOldGen(Object o); + public native long getObjectSize(Object o); + + public native boolean classKnownToNotExist(ClassLoader loader, String name); + public native URL[] getLookupCacheURLs(ClassLoader loader); + public native int[] getLookupCacheMatches(ClassLoader loader, String name); + + // Runtime + // Make sure class name is in the correct format + public boolean isClassAlive(String name) { + return isClassAlive0(name.replace('.', '/')); + } + private native boolean isClassAlive0(String name); + + public native boolean isMonitorInflated(Object obj); + + public native void forceSafepoint(); + + private native long getConstantPool0(Class aClass); + public long getConstantPool(Class aClass) { + Objects.requireNonNull(aClass); + return getConstantPool0(aClass); + } + + private native int getConstantPoolCacheIndexTag0(); + public int getConstantPoolCacheIndexTag() { + return getConstantPoolCacheIndexTag0(); + } + + private native int getConstantPoolCacheLength0(Class aClass); + public int getConstantPoolCacheLength(Class aClass) { + Objects.requireNonNull(aClass); + return getConstantPoolCacheLength0(aClass); + } + + private native int remapInstructionOperandFromCPCache0(Class aClass, int index); + public int remapInstructionOperandFromCPCache(Class aClass, int index) { + Objects.requireNonNull(aClass); + return remapInstructionOperandFromCPCache0(aClass, index); + } + + private native int encodeConstantPoolIndyIndex0(int index); + public int encodeConstantPoolIndyIndex(int index) { + return encodeConstantPoolIndyIndex0(index); + } + + // JVMTI + public native void addToBootstrapClassLoaderSearch(String segment); + public native void addToSystemClassLoaderSearch(String segment); + + // G1 + public native boolean g1InConcurrentMark(); + public native boolean g1IsHumongous(Object o); + public native boolean g1BelongsToHumongousRegion(long adr); + public native boolean g1BelongsToFreeRegion(long adr); + public native long g1NumMaxRegions(); + public native long g1NumFreeRegions(); + public native int g1RegionSize(); + public native MemoryUsage g1AuxiliaryMemoryUsage(); + public native Object[] parseCommandLine(String commandline, DiagnosticCommand[] args); + + // Parallel GC + public native long psVirtualSpaceAlignment(); + public native long psHeapGenerationAlignment(); + + /** + * Enumerates old regions with liveness less than specified and produces some statistics + * @param liveness percent of region's liveness (live_objects / total_region_size * 100). + * @return long[3] array where long[0] - total count of old regions + * long[1] - total memory of old regions + * long[2] - lowest estimation of total memory of old regions to be freed (non-full + * regions are not included) + */ + public native long[] g1GetMixedGCInfo(int liveness); + + // NMT + public native long NMTMalloc(long size); + public native void NMTFree(long mem); + public native long NMTReserveMemory(long size); + public native long NMTAttemptReserveMemoryAt(long addr, long size); + public native void NMTCommitMemory(long addr, long size); + public native void NMTUncommitMemory(long addr, long size); + public native void NMTReleaseMemory(long addr, long size); + public native long NMTMallocWithPseudoStack(long size, int index); + public native long NMTMallocWithPseudoStackAndType(long size, int index, int type); + public native boolean NMTIsDetailSupported(); + public native boolean NMTChangeTrackingLevel(); + public native int NMTGetHashSize(); + + // Compiler + public native int matchesMethod(Executable method, String pattern); + public native int matchesInline(Executable method, String pattern); + public native boolean shouldPrintAssembly(Executable method, int comp_level); + public native int deoptimizeFrames(boolean makeNotEntrant); + public native void deoptimizeAll(); + + public boolean isMethodCompiled(Executable method) { + return isMethodCompiled(method, false /*not osr*/); + } + public native boolean isMethodCompiled(Executable method, boolean isOsr); + public boolean isMethodCompilable(Executable method) { + return isMethodCompilable(method, -2 /*any*/); + } + public boolean isMethodCompilable(Executable method, int compLevel) { + return isMethodCompilable(method, compLevel, false /*not osr*/); + } + public native boolean isMethodCompilable(Executable method, int compLevel, boolean isOsr); + + public native boolean isMethodQueuedForCompilation(Executable method); + + // Determine if the compiler corresponding to the compilation level 'compLevel' + // and to the compilation context 'compilation_context' provides an intrinsic + // for the method 'method'. An intrinsic is available for method 'method' if: + // - the intrinsic is enabled (by using the appropriate command-line flag) and + // - the platform on which the VM is running provides the instructions necessary + // for the compiler to generate the intrinsic code. + // + // The compilation context is related to using the DisableIntrinsic flag on a + // per-method level, see hotspot/src/share/vm/compiler/abstractCompiler.hpp + // for more details. + public boolean isIntrinsicAvailable(Executable method, + Executable compilationContext, + int compLevel) { + Objects.requireNonNull(method); + return isIntrinsicAvailable0(method, compilationContext, compLevel); + } + // If usage of the DisableIntrinsic flag is not expected (or the usage can be ignored), + // use the below method that does not require the compilation context as argument. + public boolean isIntrinsicAvailable(Executable method, int compLevel) { + return isIntrinsicAvailable(method, null, compLevel); + } + private native boolean isIntrinsicAvailable0(Executable method, + Executable compilationContext, + int compLevel); + public int deoptimizeMethod(Executable method) { + return deoptimizeMethod(method, false /*not osr*/); + } + public native int deoptimizeMethod(Executable method, boolean isOsr); + public void makeMethodNotCompilable(Executable method) { + makeMethodNotCompilable(method, -2 /*any*/); + } + public void makeMethodNotCompilable(Executable method, int compLevel) { + makeMethodNotCompilable(method, compLevel, false /*not osr*/); + } + public native void makeMethodNotCompilable(Executable method, int compLevel, boolean isOsr); + public int getMethodCompilationLevel(Executable method) { + return getMethodCompilationLevel(method, false /*not ost*/); + } + public native int getMethodCompilationLevel(Executable method, boolean isOsr); + public native boolean testSetDontInlineMethod(Executable method, boolean value); + public int getCompileQueuesSize() { + return getCompileQueueSize(-2 /*any*/); + } + public native int getCompileQueueSize(int compLevel); + public native boolean testSetForceInlineMethod(Executable method, boolean value); + + public boolean enqueueMethodForCompilation(Executable method, int compLevel) { + return enqueueMethodForCompilation(method, compLevel, -1 /*InvocationEntryBci*/); + } + private native boolean enqueueMethodForCompilation0(Executable method, int compLevel, int entry_bci); + public boolean enqueueMethodForCompilation(Executable method, int compLevel, int entry_bci) { + Objects.requireNonNull(method); + return enqueueMethodForCompilation0(method, compLevel, entry_bci); + } + private native boolean enqueueInitializerForCompilation0(Class aClass, int compLevel); + public boolean enqueueInitializerForCompilation(Class aClass, int compLevel) { + Objects.requireNonNull(aClass); + return enqueueInitializerForCompilation0(aClass, compLevel); + } + public native void clearMethodState(Executable method); + public native void markMethodProfiled(Executable method); + public native void lockCompilation(); + public native void unlockCompilation(); + public native int getMethodEntryBci(Executable method); + public native Object[] getNMethod(Executable method, boolean isOsr); + public native long allocateCodeBlob(int size, int type); + public long allocateCodeBlob(long size, int type) { + int intSize = (int) size; + if ((long) intSize != size || size < 0) { + throw new IllegalArgumentException( + "size argument has illegal value " + size); + } + return allocateCodeBlob( intSize, type); + } + public native void freeCodeBlob(long addr); + public native Object[] getCodeHeapEntries(int type); + public native int getCompilationActivityMode(); + private native long getMethodData0(Executable method); + public long getMethodData(Executable method) { + Objects.requireNonNull(method); + return getMethodData0(method); + } + public native Object[] getCodeBlob(long addr); + + private native void clearInlineCaches0(boolean preserve_static_stubs); + public void clearInlineCaches() { + clearInlineCaches0(false); + } + public void clearInlineCaches(boolean preserve_static_stubs) { + clearInlineCaches0(preserve_static_stubs); + } + + // Intered strings + public native boolean isInStringTable(String str); + + // Memory + public native void readReservedMemory(); + public native long allocateMetaspace(ClassLoader classLoader, long size); + public native void freeMetaspace(ClassLoader classLoader, long addr, long size); + public native long incMetaspaceCapacityUntilGC(long increment); + public native long metaspaceCapacityUntilGC(); + public native boolean metaspaceShouldConcurrentCollect(); + public native long metaspaceReserveAlignment(); + + // Don't use these methods directly + // Use sun.hotspot.gc.GC class instead. + public native boolean isGCSupported(int name); + public native boolean isGCSelected(int name); + public native boolean isGCSelectedErgonomically(); + + // Force Young GC + public native void youngGC(); + + // Force Full GC + public native void fullGC(); + + // Returns true if the current GC supports control of its concurrent + // phase via requestConcurrentGCPhase(). If false, a request will + // always fail. + public native boolean supportsConcurrentGCPhaseControl(); + + // Returns an array of concurrent phase names provided by this + // collector. These are the names recognized by + // requestConcurrentGCPhase(). + public native String[] getConcurrentGCPhases(); + + // Attempt to put the collector into the indicated concurrent phase, + // and attempt to remain in that state until a new request is made. + // + // Returns immediately if already in the requested phase. + // Otherwise, waits until the phase is reached. + // + // Throws IllegalStateException if unsupported by the current collector. + // Throws NullPointerException if phase is null. + // Throws IllegalArgumentException if phase is not valid for the current collector. + public void requestConcurrentGCPhase(String phase) { + if (!supportsConcurrentGCPhaseControl()) { + throw new IllegalStateException("Concurrent GC phase control not supported"); + } else if (phase == null) { + throw new NullPointerException("null phase"); + } else if (!requestConcurrentGCPhase0(phase)) { + throw new IllegalArgumentException("Unknown concurrent GC phase: " + phase); + } + } + + // Helper for requestConcurrentGCPhase(). Returns true if request + // succeeded, false if the phase is invalid. + private native boolean requestConcurrentGCPhase0(String phase); + + // Method tries to start concurrent mark cycle. + // It returns false if CM Thread is always in concurrent cycle. + public native boolean g1StartConcMarkCycle(); + + // Tests on ReservedSpace/VirtualSpace classes + public native int stressVirtualSpaceResize(long reservedSpaceSize, long magnitude, long iterations); + public native void runMemoryUnitTests(); + public native void readFromNoaccessArea(); + public native long getThreadStackSize(); + public native long getThreadRemainingStackSize(); + + // CPU features + public native String getCPUFeatures(); + + // VM flags + public native boolean isConstantVMFlag(String name); + public native boolean isLockedVMFlag(String name); + public native void setBooleanVMFlag(String name, boolean value); + public native void setIntVMFlag(String name, long value); + public native void setUintVMFlag(String name, long value); + public native void setIntxVMFlag(String name, long value); + public native void setUintxVMFlag(String name, long value); + public native void setUint64VMFlag(String name, long value); + public native void setSizeTVMFlag(String name, long value); + public native void setStringVMFlag(String name, String value); + public native void setDoubleVMFlag(String name, double value); + public native Boolean getBooleanVMFlag(String name); + public native Long getIntVMFlag(String name); + public native Long getUintVMFlag(String name); + public native Long getIntxVMFlag(String name); + public native Long getUintxVMFlag(String name); + public native Long getUint64VMFlag(String name); + public native Long getSizeTVMFlag(String name); + public native String getStringVMFlag(String name); + public native Double getDoubleVMFlag(String name); + private final List> flagsGetters = Arrays.asList( + this::getBooleanVMFlag, this::getIntVMFlag, this::getUintVMFlag, + this::getIntxVMFlag, this::getUintxVMFlag, this::getUint64VMFlag, + this::getSizeTVMFlag, this::getStringVMFlag, this::getDoubleVMFlag); + + public Object getVMFlag(String name) { + return flagsGetters.stream() + .map(f -> f.apply(name)) + .filter(x -> x != null) + .findAny() + .orElse(null); + } + + // Jigsaw + public native void DefineModule(Object module, boolean is_open, String version, + String location, Object[] packages); + public native void AddModuleExports(Object from_module, String pkg, Object to_module); + public native void AddReadsModule(Object from_module, Object source_module); + public native void AddModuleExportsToAllUnnamed(Object module, String pkg); + public native void AddModuleExportsToAll(Object module, String pkg); + + public native int getOffsetForName0(String name); + public int getOffsetForName(String name) throws Exception { + int offset = getOffsetForName0(name); + if (offset == -1) { + throw new RuntimeException(name + " not found"); + } + return offset; + } + public native Boolean getMethodBooleanOption(Executable method, String name); + public native Long getMethodIntxOption(Executable method, String name); + public native Long getMethodUintxOption(Executable method, String name); + public native Double getMethodDoubleOption(Executable method, String name); + public native String getMethodStringOption(Executable method, String name); + private final List> methodOptionGetters + = Arrays.asList(this::getMethodBooleanOption, this::getMethodIntxOption, + this::getMethodUintxOption, this::getMethodDoubleOption, + this::getMethodStringOption); + + public Object getMethodOption(Executable method, String name) { + return methodOptionGetters.stream() + .map(f -> f.apply(method, name)) + .filter(x -> x != null) + .findAny() + .orElse(null); + } + + // Safepoint Checking + public native void assertMatchingSafepointCalls(boolean mutexSafepointValue, boolean attemptedNoSafepointValue); + + // Sharing & archiving + public native boolean isShared(Object o); + public native boolean isSharedClass(Class c); + public native boolean areSharedStringsIgnored(); + public native boolean isCDSIncludedInVmBuild(); + public native boolean isJFRIncludedInVmBuild(); + public native boolean isJavaHeapArchiveSupported(); + public native Object getResolvedReferences(Class c); + public native boolean areOpenArchiveHeapObjectsMapped(); + + // Handshakes + public native int handshakeWalkStack(Thread t, boolean all_threads); + + // Returns true on linux if library has the noexecstack flag set. + public native boolean checkLibSpecifiesNoexecstack(String libfilename); + + // Container testing + public native boolean isContainerized(); + public native void printOsInfo(); + + // Decoder + public native void disableElfSectionCache(); +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/BlobType.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/BlobType.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/BlobType.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/BlobType.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.code; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; +import java.util.EnumSet; + +import sun.hotspot.WhiteBox; + +public enum BlobType { + // All types (No code cache segmentation) + All(0, "CodeCache", "Code Cache", "ReservedCodeCacheSize"); + + public final int id; + public final String sizeOptionName; + public final String beanName; + public final String name; + + private BlobType(int id, String name, String beanName, String sizeOptionName) { + this.id = id; + this.name = name; + this.beanName = beanName; + this.sizeOptionName = sizeOptionName; + } + + public MemoryPoolMXBean getMemoryPool() { + for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) { + String name = bean.getName(); + if (beanName.equals(name)) { + return bean; + } + } + return null; + } + + public boolean allowTypeWhenOverflow(BlobType type) { + return type == this; + } + + public static EnumSet getAvailable() { + return EnumSet.of(All); + } + + public long getSize() { + return WhiteBox.getWhiteBox().getUintxVMFlag(sizeOptionName); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/CodeBlob.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/CodeBlob.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/CodeBlob.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/CodeBlob.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.code; + +import sun.hotspot.WhiteBox; + +public class CodeBlob { + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + public static CodeBlob[] getCodeBlobs(BlobType type) { + Object[] obj = WB.getCodeHeapEntries(type.id); + if (obj == null) { + return null; + } + CodeBlob[] result = new CodeBlob[obj.length]; + for (int i = 0, n = result.length; i < n; ++i) { + result[i] = new CodeBlob((Object[]) obj[i]); + } + return result; + } + public static CodeBlob getCodeBlob(long addr) { + Object[] obj = WB.getCodeBlob(addr); + if (obj == null) { + return null; + } + return new CodeBlob(obj); + } + protected CodeBlob(Object[] obj) { + assert obj.length == 4; + name = (String) obj[0]; + size = (Integer) obj[1]; + int blob_type_index = (Integer) obj[2]; + if (blob_type_index == -1) { // AOT + code_blob_type = null; + } else { + code_blob_type = BlobType.values()[blob_type_index]; + assert code_blob_type.id == (Integer) obj[2]; + } + address = (Long) obj[3]; + } + public final String name; + public final int size; + public final BlobType code_blob_type; + public final long address; + @Override + public String toString() { + return "CodeBlob{" + + "name=" + name + + ", size=" + size + + ", code_blob_type=" + code_blob_type + + ", address=" + address + + '}'; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/Compiler.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/Compiler.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/Compiler.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/Compiler.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.code; + +import sun.hotspot.WhiteBox; + +/** + * API to obtain information about enabled JIT compilers + * retrieved from the VM with the WhiteBox API. + */ +public class Compiler { + + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + + /** + * Check if Graal is used as JIT compiler. + * + * Graal is enabled if following conditions are true: + * - we are not in Interpreter mode + * - UseJVMCICompiler flag is true + * - jvmci.Compiler variable is equal to 'graal' + * - TieredCompilation is not used or TieredStopAtLevel is greater than 3 + * No need to check client mode because it set UseJVMCICompiler to false. + * + * @return true if Graal is used as JIT compiler. + */ + public static boolean isGraalEnabled() { + Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); + if (useCompiler == null || !useCompiler) { + return false; + } + Boolean useJvmciComp = WB.getBooleanVMFlag("UseJVMCICompiler"); + if (useJvmciComp == null || !useJvmciComp) { + return false; + } + // This check might be redundant but let's keep it for now. + String jvmciCompiler = System.getProperty("jvmci.Compiler"); + if (jvmciCompiler == null || !jvmciCompiler.equals("graal")) { + return false; + } + + Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); + Long compLevel = WB.getIntxVMFlag("TieredStopAtLevel"); + // if TieredCompilation is enabled and compilation level is <= 3 then no Graal is used + if (tieredCompilation != null && tieredCompilation && + compLevel != null && compLevel <= 3) { + return false; + } + return true; + } + + /** + * Check if C2 is used as JIT compiler. + * + * C2 is enabled if following conditions are true: + * - we are not in Interpreter mode + * - we are in Server compilation mode + * - TieredCompilation is not used or TieredStopAtLevel is greater than 3 + * - Graal is not used + * + * @return true if C2 is used as JIT compiler. + */ + public static boolean isC2Enabled() { + Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); + if (useCompiler == null || !useCompiler) { + return false; + } + Boolean serverMode = WB.getBooleanVMFlag("ProfileInterpreter"); + if (serverMode == null || !serverMode) { + return false; + } + + Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); + Long compLevel = WB.getIntxVMFlag("TieredStopAtLevel"); + // if TieredCompilation is enabled and compilation level is <= 3 then no Graal is used + if (tieredCompilation != null && tieredCompilation && + compLevel != null && compLevel <= 3) { + return false; + } + + if (isGraalEnabled()) { + return false; + } + + return true; + } + + /* + * Check if C1 is used as JIT compiler. + * + * C1 is enabled if following conditions are true: + * - we are not in Interpreter mode + * - we are not in Server compilation mode + * - TieredCompilation is used in Server mode + * + * @return true if C1 is used as JIT compiler. + */ + public static boolean isC1Enabled() { + Boolean useCompiler = WB.getBooleanVMFlag("UseCompiler"); + if (useCompiler == null || !useCompiler) { + return false; + } + Boolean serverMode = WB.getBooleanVMFlag("ProfileInterpreter"); + if (serverMode == null || !serverMode) { + return true; // Client mode + } + + Boolean tieredCompilation = WB.getBooleanVMFlag("TieredCompilation"); + // C1 is not used in server mode if TieredCompilation is off. + if (tieredCompilation != null && !tieredCompilation) { + return false; + } + return true; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/NMethod.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/NMethod.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/NMethod.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/code/NMethod.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.code; + +import java.lang.reflect.Executable; +import sun.hotspot.WhiteBox; + +public class NMethod extends CodeBlob { + private static final WhiteBox wb = WhiteBox.getWhiteBox(); + public static NMethod get(Executable method, boolean isOsr) { + Object[] obj = wb.getNMethod(method, isOsr); + return obj == null ? null : new NMethod(obj); + } + private NMethod(Object[] obj) { + super((Object[])obj[0]); + assert obj.length == 5; + comp_level = (Integer) obj[1]; + insts = (byte[]) obj[2]; + compile_id = (Integer) obj[3]; + entry_point = (Long) obj[4]; + } + public final byte[] insts; + public final int comp_level; + public final int compile_id; + public final long entry_point; + + @Override + public String toString() { + return "NMethod{" + + super.toString() + + ", insts=" + insts + + ", comp_level=" + comp_level + + ", compile_id=" + compile_id + + ", entry_point=" + entry_point + + '}'; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/cpuinfo/CPUInfo.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.cpuinfo; + +import java.util.List; +import java.util.Arrays; +import java.util.Collections; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import sun.hotspot.WhiteBox; + +/** + * Information about CPU on test box. + * + * CPUInfo uses WhiteBox to gather information, + * so WhiteBox class should be added to bootclasspath + * and option -XX:+WhiteBoxAPI should be explicitly + * specified on command line. + */ +public class CPUInfo { + + private static final List features; + private static final String additionalCPUInfo; + + static { + WhiteBox wb = WhiteBox.getWhiteBox(); + + Pattern additionalCPUInfoRE = + Pattern.compile("([^(]*\\([^)]*\\)[^,]*),\\s*"); + + String cpuFeaturesString = wb.getCPUFeatures(); + Matcher matcher = additionalCPUInfoRE.matcher(cpuFeaturesString); + if (matcher.find()) { + additionalCPUInfo = matcher.group(1); + } else { + additionalCPUInfo = ""; + } + String splittedFeatures[] = matcher.replaceAll("").split("(, )| "); + + features = Collections.unmodifiableList(Arrays. + asList(splittedFeatures)); + } + + /** + * Get additional information about CPU. + * For example, on X86 in will be family/model/stepping + * and number of cores. + * + * @return additional CPU info + */ + public static String getAdditionalCPUInfo() { + return additionalCPUInfo; + } + + /** + * Get all known features supported by CPU. + * + * @return unmodifiable list with names of all known features + * supported by CPU. + */ + public static List getFeatures() { + return features; + } + + /** + * Check if some feature is supported by CPU. + * + * @param feature Name of feature to be tested. + * @return true if tested feature is supported by CPU. + */ + public static boolean hasFeature(String feature) { + return features.contains(feature.toLowerCase()); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/gc/GC.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/gc/GC.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/gc/GC.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/gc/GC.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.gc; + +import sun.hotspot.WhiteBox; + +/** + * API to obtain information about selected and supported Garbage Collectors + * retrieved from the VM with the WhiteBox API. + */ +public enum GC { + /* + * Enum values much match CollectedHeap::Name + */ + Serial(1), + Parallel(2), + ConcMarkSweep(3), + G1(4), + Epsilon(5), + Z(6); + + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + + private final int name; + + private GC(int name) { + this.name = name; + } + + /** + * @return true if this GC is supported by the VM + */ + public boolean isSupported() { + return WB.isGCSupported(name); + } + + /** + * @return true if this GC is currently selected/used + */ + public boolean isSelected() { + return WB.isGCSelected(name); + } + + /** + * @return true if GC was selected ergonomically, as opposed + * to being explicitly specified on the command line + */ + public static boolean isSelectedErgonomically() { + return WB.isGCSelectedErgonomically(); + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/parser/DiagnosticCommand.java openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/parser/DiagnosticCommand.java --- openjdk-8-8u392-ga/=unpacked-tar8=/test/lib/sun/hotspot/parser/DiagnosticCommand.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar8=/test/lib/sun/hotspot/parser/DiagnosticCommand.java 2024-01-11 01:53:23.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.hotspot.parser; + +public class DiagnosticCommand { + + public enum DiagnosticArgumentType { + JLONG, BOOLEAN, STRING, NANOTIME, STRINGARRAY, MEMORYSIZE + } + + private String name; + private String desc; + private DiagnosticArgumentType type; + private boolean mandatory; + private String defaultValue; + private boolean argument; + + public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type, + boolean mandatory, String defaultValue) { + this(name, desc, type, false, mandatory, defaultValue); + } + + public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type, + boolean argument, boolean mandatory, String defaultValue) { + this.name = name; + this.desc = desc; + this.type = type; + this.mandatory = mandatory; + this.defaultValue = defaultValue; + this.argument = argument; + } + + public String getName() { + return name; + } + + public String getDesc() { + return desc; + } + + public DiagnosticArgumentType getType() { + return type; + } + + public boolean isMandatory() { + return mandatory; + } + + public boolean isArgument() { + return argument; + } + + public String getDefaultValue() { + return defaultValue; + } +} diff -Nru openjdk-8-8u392-ga/=unpacked-tar9=/src/jdk/nashorn/internal/objects/Global.java openjdk-8-8u402-ga/=unpacked-tar9=/src/jdk/nashorn/internal/objects/Global.java --- openjdk-8-8u392-ga/=unpacked-tar9=/src/jdk/nashorn/internal/objects/Global.java 2023-10-07 21:09:58.000000000 +0000 +++ openjdk-8-8u402-ga/=unpacked-tar9=/src/jdk/nashorn/internal/objects/Global.java 2024-01-11 01:53:23.000000000 +0000 @@ -1430,9 +1430,11 @@ if ("context".equals(nameStr)) { return sctxt; } else if ("engine".equals(nameStr)) { - // expose "engine" variable only when there is no security manager - // or when no class filter is set. - if (System.getSecurityManager() == null || global.getClassFilter() == null) { + // expose "engine" variable only when there is no security manager, + // or when no class filter is set and --no-java is not set + if (System.getSecurityManager() == null || + (global.getClassFilter() == null && + !global.getContext().getEnv()._no_java)) { return global.engine; } } Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/corba.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/corba.tar.xz differ diff -Nru openjdk-8-8u392-ga/debian/JB-jre-headless.overrides.in openjdk-8-8u402-ga/debian/JB-jre-headless.overrides.in --- openjdk-8-8u392-ga/debian/JB-jre-headless.overrides.in 2023-05-11 20:30:25.000000000 +0000 +++ openjdk-8-8u402-ga/debian/JB-jre-headless.overrides.in 2024-02-27 05:59:16.000000000 +0000 @@ -1,6 +1,3 @@ -# empty directory by intent -@basename@-jre-headless binary: package-contains-empty-directory *usr/share/binfmts/* - # Ignore the mouse cursors @basename@-jre-headless binary: image-file-in-usr-lib @@ -16,7 +13,3 @@ # not documentation @basename@-jre-headless binary: package-contains-documentation-outside-usr-share-doc */Xusage.txt* @basename@-jre-headless binary: package-contains-documentation-outside-usr-share-doc */jvm.hprof.txt* - -# this is a plugin -@basename@-jre-headless binary: library-not-linked-against-libc */libjawt.so* -@basename@-jre-headless binary: shared-library-lacks-prerequisites */libjsound.so* diff -Nru openjdk-8-8u392-ga/debian/JB-jre-headless.postinst.in openjdk-8-8u402-ga/debian/JB-jre-headless.postinst.in --- openjdk-8-8u392-ga/debian/JB-jre-headless.postinst.in 2023-06-29 19:26:12.000000000 +0000 +++ openjdk-8-8u402-ga/debian/JB-jre-headless.postinst.in 2024-02-27 05:59:16.000000000 +0000 @@ -13,6 +13,17 @@ case "$1" in configure) + if test -z "$2" || dpkg --compare-versions "$2" lt '8u402-ga-2~'; then + # try to remove and ignore the error + update-binfmts --package @basename@ \ + --remove jar /usr/bin/jexec 2>/dev/null || true + update-alternatives --remove jexec \ + $basedir/jre/lib/jexec 2>/dev/null || true + if [ -e /usr/share/binfmts ]; then + rmdir --ignore-fail-on-non-empty /usr/share/binfmts + fi + fi + # fail early. java currently uses tricks to find its own shared # libraries depending on the path of the binary. Will be changed # in OpenJDK7 @@ -80,20 +91,8 @@ $priority \ $slave1 $slave2 done - update-alternatives \ - --install /usr/bin/jexec jexec $basedir/jre/lib/jexec $priority \ - --slave \ - /usr/share/binfmts/jar \ - jexec-binfmt \ - $basedir/jre/lib/jar.binfmt fi # update alternatives - # register binfmt; ignore errors, the alternative may already be - # registered by another JRE. - if which update-binfmts >/dev/null && [ -r /usr/share/binfmts/jar ]; then - update-binfmts --package @basename@ --import jar || true - fi - # activate class data sharing case @archdir@ in i386|sparc) rm -f $basedir/jre/lib/@archdir@/client/classes.jsa diff -Nru openjdk-8-8u392-ga/debian/JB-jre-headless.prerm.in openjdk-8-8u402-ga/debian/JB-jre-headless.prerm.in --- openjdk-8-8u392-ga/debian/JB-jre-headless.prerm.in 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/JB-jre-headless.prerm.in 2024-02-27 05:59:16.000000000 +0000 @@ -17,11 +17,11 @@ # try to remove and ignore the error if [ -e /var/lib/binfmts/jar ]; then update-binfmts --package @basename@ \ - --remove jar /usr/bin/jexec || true + --remove jar /usr/bin/jexec 2>/dev/null || true fi fi - - update-alternatives --remove jexec $basedir/jre/lib/jexec + update-alternatives --remove jexec \ + $basedir/jre/lib/jexec 2>/dev/null || true fi #DEBHELPER# diff -Nru openjdk-8-8u392-ga/debian/changelog openjdk-8-8u402-ga/debian/changelog --- openjdk-8-8u392-ga/debian/changelog 2023-10-23 08:35:55.000000000 +0000 +++ openjdk-8-8u402-ga/debian/changelog 2024-02-27 14:37:00.000000000 +0000 @@ -1,8 +1,90 @@ -openjdk-8 (8u392-ga-1~23.10) mantic-security; urgency=low +openjdk-8 (8u402-ga-2ubuntu1~23.10.1) mantic-security; urgency=medium - * Upload to Ubuntu 23.10. + * Upload to Ubuntu 23.10 + * Includes fixes to the following CVEs: + - CVE-2024-20918 + - CVE-2024-20919 + - CVE-2024-20921 + - CVE-2024-20926 + - CVE-2024-20945 + - CVE-2024-20952 + * Includes the following Security fixes: + - JDK-8308204: Enhanced certificate processing + - JDK-8314284: Enhance Nashorn performance + - JDK-8314295: Enhance verification of verifier + - JDK-8314307: Improve loop handling + - JDK-8314468: Improve Compiler loops + - JDK-8316976: Improve signature handling + - JDK-8317547: Enhance TLS connection support - -- Vladimir Petko Mon, 23 Oct 2023 21:35:55 +1300 + -- Pushkar Kulkarni Tue, 27 Feb 2024 20:07:00 +0530 + +openjdk-8 (8u402-ga-2ubuntu1) noble; urgency=medium + + * Fix installation issue on i386 (LP: #2053110): + - d/rules: build without atk bridge on i386 for Ubuntu versions that + do not have it. + - d/JB-jre-headless.postinst.in: check that /usr/share/binfmts exists + before trying to delete it. + + -- Vladimir Petko Wed, 14 Feb 2024 19:58:48 +1300 + +openjdk-8 (8u402-ga-2) unstable; urgency=low + + * d/rules reliability fixes and extra checks + * Patch OpenJDK to pass errorlevel when configure fails + * Show config.log if present in such cases + * Do not install jexec alternative any more (unlike newer + versions it cannot run just any JAR), drop .jar binfmt + registration with it (LP#1775785); please use jarwrapper + * Restore M-A installability of focal/i386 package (LP#1916327) + by adding xenial, bionic, focal, jammy to the list of releases + built with the ATK bridge, but not enabling it by default; + keep jessie on, stretch and sid and mantic/noble off the list: + please report bugs for issues with the bridge, so sthibault + can find, debug, fix them + + -- Thorsten Glaser Wed, 31 Jan 2024 06:05:28 +0100 + +openjdk-8 (8u402-ga-1) unstable; urgency=low + + [ Leslie Zhai ] + * Add openjdk-8 zero support for loong64 (Closes: #1060236) + + [ Thorsten Glaser ] + * Merge 8u392-ga-1+sparc64 + * Drop alpha-float-const.diff, seems no longer needed + * Use config.{guess,sub} from autotools-dev for the JDK as well + as icedtea-sound; autoreconf the latter; use sh explicitly + * Enable pulse for alpha and loong64 + * New upstream release + * CVEs + - CVE-2024-20918 + - CVE-2024-20919 + - CVE-2024-20921 + - CVE-2024-20926 + - CVE-2024-20945 + - CVE-2024-20952 + * Security fixes + - JDK-8308204: Enhanced certificate processing + - JDK-8314284: Enhance Nashorn performance + - JDK-8314295: Enhance verification of verifier + - JDK-8314307: Improve loop handling + - JDK-8314468: Improve Compiler loops + - JDK-8316976: Improve signature handling + - JDK-8317547: Enhance TLS connection support + * Other changes see + https://mail.openjdk.org/pipermail/jdk8u-dev/2024-January/017883.html + * Upload sponsored by QVEST ⮡ dıgıtal + + -- Thorsten Glaser Fri, 19 Jan 2024 00:30:27 +0100 + +openjdk-8 (8u392-ga-1+sparc64) unreleased; urgency=medium + + * Disable Hotspot on sparc64 as it is currently broken + (Closes: #1056570) + + -- John Paul Adrian Glaubitz Thu, 23 Nov 2023 11:01:30 +0100 openjdk-8 (8u392-ga-1) unstable; urgency=low diff -Nru openjdk-8-8u392-ga/debian/control openjdk-8-8u402-ga/debian/control --- openjdk-8-8u392-ga/debian/control 2023-10-23 08:35:55.000000000 +0000 +++ openjdk-8-8u402-ga/debian/control 2024-02-27 14:37:00.000000000 +0000 @@ -1,7 +1,8 @@ Source: openjdk-8 Section: java Priority: optional -Maintainer: Java Maintenance +Maintainer: Ubuntu Developers +XSBC-Original-Maintainer: Java Maintenance Uploaders: Thorsten Glaser Build-Depends: debhelper (>= 11), quilt, m4, lsb-release, zip, unzip, openjdk-8-jdk, @@ -9,15 +10,15 @@ xvfb, xauth, xfonts-base, libgl1-mesa-dri, xfwm4, x11-xkb-utils, dbus-x11, openjdk-8-jre-headless | default-jre-headless (>= 2:1.8), jtreg, libasmtools-java, testng, time, autoconf (>= 2.69), automake, ant, ant-optional, fastjar (>= 2:0.96-0ubuntu2), gcc-13, g++-13, libxtst-dev, libxi-dev, libxt-dev, libxaw7-dev, libxrender-dev, libcups2-dev, libasound2-dev, liblcms2-dev, libxinerama-dev, libkrb5-dev, xsltproc, libpcsclite-dev, libfreetype-dev, libgtk2.0-dev, libffi-dev, - zlib1g-dev, libattr1-dev, libpng-dev, libjpeg-dev, libgif-dev, libpulse-dev (>= 0.9.12) [!alpha], systemtap-sdt-dev, + zlib1g-dev, libattr1-dev, libpng-dev, libjpeg-dev, libgif-dev, libpulse-dev (>= 0.9.12), systemtap-sdt-dev, libnss3-dev (>= 2:3.26), openjdk-8-jdk-headless , dpkg-dev (>= 1.17.14), Standards-Version: 4.6.2 -Homepage: http://openjdk.java.net/ +Homepage: https://openjdk.org/projects/jdk8u/ VCS-git: https://evolvis.org/anonscm/git/alioth/openjdk-8.git -b master VCS-Browser: https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=alioth/openjdk-8.git;a=shortlog;h=refs/heads/master Package: openjdk-8-jdk-headless -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Multi-Arch: same Pre-Depends: ${dpkg:Depends} Depends: openjdk-8-jre-headless (= ${binary:Version}), @@ -40,7 +41,7 @@ from the IcedTea project. Package: openjdk-8-jre-headless -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Multi-Arch: same Pre-Depends: ${dpkg:Depends} Depends: ${jredefault:Depends}, ${cacert:Depends}, @@ -65,7 +66,7 @@ from the IcedTea project. Package: openjdk-8-jdk -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Multi-Arch: same Pre-Depends: ${dpkg:Depends} Depends: openjdk-8-jre (= ${binary:Version}), @@ -86,7 +87,7 @@ from the IcedTea project. Package: openjdk-8-jre -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Multi-Arch: same Pre-Depends: ${dpkg:Depends} Depends: openjdk-8-jre-headless (= ${binary:Version}), @@ -106,7 +107,7 @@ from the IcedTea project. Package: openjdk-8-demo -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Pre-Depends: ${dpkg:Depends} Depends: openjdk-8-jre (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} @@ -150,7 +151,7 @@ from the IcedTea project. Package: openjdk-8-dbg -Architecture: alpha amd64 armel armhf arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +Architecture: alpha amd64 arm64 armel armhf i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 Multi-Arch: same Section: debug Pre-Depends: ${dpkg:Depends} @@ -168,7 +169,7 @@ from the IcedTea project. Package: openjdk-8-jre-zero -Architecture: amd64 i386 arm64 ppc64 ppc64el sparc64 armhf +Architecture: amd64 arm64 i386 ppc64 ppc64el armhf Multi-Arch: same Pre-Depends: ${dpkg:Depends} Depends: openjdk-8-jre-headless (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} diff -Nru openjdk-8-8u392-ga/debian/control.in openjdk-8-8u402-ga/debian/control.in --- openjdk-8-8u392-ga/debian/control.in 2023-09-01 16:42:56.000000000 +0000 +++ openjdk-8-8u402-ga/debian/control.in 2024-02-27 05:59:16.000000000 +0000 @@ -1,7 +1,8 @@ Source: @basename@ Section: java Priority: optional -Maintainer: Java Maintenance +Maintainer: Ubuntu Developers +XSBC-Original-Maintainer: Java Maintenance Uploaders: Thorsten Glaser Build-Depends: @bd_debhelper@ quilt, m4, lsb-release, zip, unzip, @bd_bootstrap@ @@ -12,7 +13,7 @@ @bd_syslibs@ @bd_pulsejava@ @bd_systemtap@ @bd_nss@ @bd_cross@ Standards-Version: 4.6.2 -Homepage: http://openjdk.java.net/ +Homepage: https://openjdk.org/projects/jdk8u/ VCS-git: https://evolvis.org/anonscm/git/alioth/openjdk-8.git -b master VCS-Browser: https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=alioth/openjdk-8.git;a=shortlog;h=refs/heads/master diff -Nru openjdk-8-8u392-ga/debian/copyright openjdk-8-8u402-ga/debian/copyright --- openjdk-8-8u392-ga/debian/copyright 2023-10-21 19:26:54.000000000 +0000 +++ openjdk-8-8u402-ga/debian/copyright 2024-02-27 05:59:16.000000000 +0000 @@ -74,7 +74,7 @@ Packaging: Copyright © 2007-2014 Canonical Ltd. Copyright © 2021, 2022 mirabilos and ⮡ tarent solutions GmbH - Copyright © 2023 mirabilos and Qvest Digital AG + Copyright © 2023, 2024 mirabilos and Qvest Digital AG SipHash: Copyright © Copyright (c) 2012-2014 Daniel J. Bernstein diff -Nru openjdk-8-8u392-ga/debian/patches/aarch32.diff openjdk-8-8u402-ga/debian/patches/aarch32.diff --- openjdk-8-8u392-ga/debian/patches/aarch32.diff 2023-06-29 20:42:12.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/aarch32.diff 2024-02-27 05:59:16.000000000 +0000 @@ -44,7 +44,7 @@ VAR_CPU_BITS=32 VAR_CPU_ENDIAN=little ;; -@@ -346,6 +346,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], +@@ -352,6 +352,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], elif test "x$OPENJDK_TARGET_OS" != xmacosx && test "x$OPENJDK_TARGET_CPU" = xx86_64; then # On all platforms except MacOSX replace x86_64 with amd64. OPENJDK_TARGET_CPU_LEGACY="amd64" @@ -53,7 +53,7 @@ fi AC_SUBST(OPENJDK_TARGET_CPU_LEGACY) -@@ -356,6 +358,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], +@@ -362,6 +364,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], OPENJDK_TARGET_CPU_LEGACY_LIB="i386" elif test "x$OPENJDK_TARGET_CPU" = xx86_64; then OPENJDK_TARGET_CPU_LEGACY_LIB="amd64" @@ -62,7 +62,7 @@ fi AC_SUBST(OPENJDK_TARGET_CPU_LEGACY_LIB) -@@ -389,6 +393,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], +@@ -395,6 +399,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], elif test "x$OPENJDK_TARGET_OS" != xmacosx && test "x$OPENJDK_TARGET_CPU" = xx86_64; then # On all platforms except macosx, we replace x86_64 with amd64. OPENJDK_TARGET_CPU_OSARCH="amd64" @@ -71,7 +71,7 @@ fi AC_SUBST(OPENJDK_TARGET_CPU_OSARCH) -@@ -398,6 +404,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], +@@ -404,6 +410,8 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], elif test "x$OPENJDK_TARGET_OS" != xmacosx && test "x$OPENJDK_TARGET_CPU" = xx86_64; then # On all platforms except macosx, we replace x86_64 with amd64. OPENJDK_TARGET_CPU_JLI="amd64" diff -Nru openjdk-8-8u392-ga/debian/patches/aarch64.diff openjdk-8-8u402-ga/debian/patches/aarch64.diff --- openjdk-8-8u392-ga/debian/patches/aarch64.diff 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/aarch64.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -# DP: Add missing build bits for AArch64 from the AArch64 branch. - ---- a/common/autoconf/build-aux/autoconf-config.sub -+++ b/common/autoconf/build-aux/autoconf-config.sub -@@ -264,6 +264,7 @@ case $basic_machine in - # Some are omitted here because they have special meanings below. - 1750a | 580 \ - | a29k \ -+ | aarch64 \ - | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ - | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ - | am33_2.0 \ -@@ -340,6 +341,7 @@ case $basic_machine in - # Recognize the basic CPU types with company name. - 580-* \ - | a29k-* \ -+ | aarch64-* \ - | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ - | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ - | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ diff -Nru openjdk-8-8u392-ga/debian/patches/alpha-float-const.diff openjdk-8-8u402-ga/debian/patches/alpha-float-const.diff --- openjdk-8-8u392-ga/debian/patches/alpha-float-const.diff 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/alpha-float-const.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ ---- a/jdk/src/share/classes/java/lang/Float.java -+++ b/jdk/src/share/classes/java/lang/Float.java -@@ -85,7 +85,9 @@ public final class Float extends Number - * - * @since 1.6 - */ -- public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f -+ // FIXME: still required on alpha? -+ // public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f -+ public static final float MIN_NORMAL = Float.intBitsToFloat(0x00800000); - - /** - * A constant holding the smallest positive nonzero value of type diff -Nru openjdk-8-8u392-ga/debian/patches/b07-to-b08-hotspot.diff openjdk-8-8u402-ga/debian/patches/b07-to-b08-hotspot.diff --- openjdk-8-8u392-ga/debian/patches/b07-to-b08-hotspot.diff 2023-10-21 19:25:02.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/b07-to-b08-hotspot.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,299 +0,0 @@ -# DP: git diff jdk8u392-b07..jdk8u392-b08 hotspot - ---- a/hotspot/THIRD_PARTY_README -+++ b/hotspot/THIRD_PARTY_README -@@ -1472,7 +1472,7 @@ included with JDK 8 and OpenJDK 8 source - - ------------------------------------------------------------------------------- - --%% This notice is provided with respect to libpng 1.6.37, which may be -+%% This notice is provided with respect to libpng 1.6.39, which may be - included with JRE 8, JDK 8, and OpenJDK 8. - - --- begin of LICENSE --- -@@ -1483,11 +1483,11 @@ COPYRIGHT NOTICE, DISCLAIMER, and LICENS - PNG Reference Library License version 2 - --------------------------------------- - -- * Copyright (c) 1995-2019 The PNG Reference Library Authors. -- * Copyright (c) 2018-2019 Cosmin Truta. -- * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. -- * Copyright (c) 1996-1997 Andreas Dilger. -- * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. -+Copyright (c) 1995-2022 The PNG Reference Library Authors. -+Copyright (c) 2018-2022 Cosmin Truta -+Copyright (c) 1998-2018 Glenn Randers-Pehrson -+Copyright (c) 1996-1997 Andreas Dilger -+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - - The software is supplied "as is", without warranty of any kind, - express or implied, including, without limitation, the warranties -@@ -1614,10 +1614,10 @@ be appreciated. - - TRADEMARK: - --The name "libpng" has not been registered by the Copyright owner -+The name "libpng" has not been registered by the Copyright owners - as a trademark in any jurisdiction. However, because libpng has - been distributed and maintained world-wide, continually since 1995, --the Copyright owner claims "common-law trademark protection" in any -+the Copyright owners claim "common-law trademark protection" in any - jurisdiction where common-law trademark is recognized. - - OSI CERTIFICATION: -@@ -1639,6 +1639,59 @@ Glenn Randers-Pehrson - glennrp at users.sourceforge.net - July 15, 2018 - -+AUTHORS File Information: -+ -+PNG REFERENCE LIBRARY AUTHORS -+============================= -+ -+This is the list of PNG Reference Library ("libpng") Contributing -+Authors, for copyright and licensing purposes. -+ -+ * Andreas Dilger -+ * Cosmin Truta -+ * Dave Martindale -+ * Eric S. Raymond -+ * Gilles Vollant -+ * Glenn Randers-Pehrson -+ * Greg Roelofs -+ * Guy Eric Schalnat -+ * James Yu -+ * John Bowler -+ * Kevin Bracey -+ * Magnus Holmgren -+ * Mandar Sahastrabuddhe -+ * Mans Rullgard -+ * Matt Sarett -+ * Mike Klein -+ * Pascal Massimino -+ * Paul Schmidt -+ * Qiang Zhou -+ * Sam Bushell -+ * Samuel Williams -+ * Simon-Pierre Cadieux -+ * Tim Wegner -+ * Tom Lane -+ * Tom Tanner -+ * Vadim Barkov -+ * Willem van Schaik -+ * Zhijie Liang -+ * Arm Holdings -+ - Richard Townsend -+ * Google Inc. -+ - Dan Field -+ - Leon Scroggins III -+ - Matt Sarett -+ - Mike Klein -+ - Sami Boukortt -+ -+The build projects, the build scripts, the test scripts, and other -+files in the "ci", "projects", "scripts" and "tests" directories, have -+other copyright owners, but are released under the libpng license. -+ -+Some files in the "contrib" directory, and some tools-generated files -+that are distributed with libpng, have other copyright owners, and are -+released under other open source licenses. -+ - --- end of LICENSE --- - - ------------------------------------------------------------------------------- ---- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp -+++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp -@@ -206,8 +206,10 @@ void BlockListBuilder::handle_exceptions - } - - void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) { -- // start a new block after jsr-bytecode and link this block into cfg -- make_block_at(next_bci, current); -+ if (next_bci < method()->code_size()) { -+ // start a new block after jsr-bytecode and link this block into cfg -+ make_block_at(next_bci, current); -+ } - - // start a new block at the subroutine entry at mark it with special flag - BlockBegin* sr_block = make_block_at(sr_bci, current); -@@ -227,6 +229,8 @@ void BlockListBuilder::set_leaders() { - // branch target and a modification of the successor lists. - BitMap bci_block_start = method()->bci_block_start(); - -+ int end_bci = method()->code_size(); -+ - ciBytecodeStream s(method()); - while (s.next() != ciBytecodeStream::EOBC()) { - int cur_bci = s.cur_bci(); -@@ -297,7 +301,9 @@ void BlockListBuilder::set_leaders() { - case Bytecodes::_if_acmpne: // fall through - case Bytecodes::_ifnull: // fall through - case Bytecodes::_ifnonnull: -- make_block_at(s.next_bci(), current); -+ if (s.next_bci() < end_bci) { -+ make_block_at(s.next_bci(), current); -+ } - make_block_at(s.get_dest(), current); - current = NULL; - break; ---- a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp -+++ b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp -@@ -1,5 +1,5 @@ - /* -- * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. -+ * Copyright (c) 2006, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it -@@ -33,12 +33,13 @@ - - - ciBlock *ciMethodBlocks::block_containing(int bci) { -+ assert(bci >= 0 && bci < _code_size, "valid bytecode range"); - ciBlock *blk = _bci_to_block[bci]; - return blk; - } - - bool ciMethodBlocks::is_block_start(int bci) { -- assert(bci >=0 && bci < _code_size, "valid bytecode range"); -+ assert(bci >= 0 && bci < _code_size, "valid bytecode range"); - ciBlock *b = _bci_to_block[bci]; - assert(b != NULL, "must have block for bytecode"); - return b->start_bci() == bci; -@@ -146,7 +147,9 @@ void ciMethodBlocks::do_analysis() { - case Bytecodes::_ifnonnull : - { - cur_block->set_control_bci(bci); -- ciBlock *fall_through = make_block_at(s.next_bci()); -+ if (s.next_bci() < limit_bci) { -+ ciBlock *fall_through = make_block_at(s.next_bci()); -+ } - int dest_bci = s.get_dest(); - ciBlock *dest = make_block_at(dest_bci); - break; -@@ -166,7 +169,9 @@ void ciMethodBlocks::do_analysis() { - case Bytecodes::_jsr : - { - cur_block->set_control_bci(bci); -- ciBlock *ret = make_block_at(s.next_bci()); -+ if (s.next_bci() < limit_bci) { -+ ciBlock *ret = make_block_at(s.next_bci()); -+ } - int dest_bci = s.get_dest(); - ciBlock *dest = make_block_at(dest_bci); - break; -@@ -224,7 +229,9 @@ void ciMethodBlocks::do_analysis() { - case Bytecodes::_jsr_w : - { - cur_block->set_control_bci(bci); -- ciBlock *ret = make_block_at(s.next_bci()); -+ if (s.next_bci() < limit_bci) { -+ ciBlock *ret = make_block_at(s.next_bci()); -+ } - int dest_bci = s.get_far_dest(); - ciBlock *dest = make_block_at(dest_bci); - break; ---- a/hotspot/src/share/vm/compiler/methodLiveness.cpp -+++ b/hotspot/src/share/vm/compiler/methodLiveness.cpp -@@ -268,10 +268,11 @@ void MethodLiveness::init_basic_blocks() - case Bytecodes::_ifnull: - case Bytecodes::_ifnonnull: - // Two way branch. Set predecessors at each destination. -- dest = _block_map->at(bytes.next_bci()); -- assert(dest != NULL, "must be a block immediately following this one."); -- dest->add_normal_predecessor(current_block); -- -+ if (bytes.next_bci() < method_len) { -+ dest = _block_map->at(bytes.next_bci()); -+ assert(dest != NULL, "must be a block immediately following this one."); -+ dest->add_normal_predecessor(current_block); -+ } - dest = _block_map->at(bytes.get_dest()); - assert(dest != NULL, "branch desination must start a block."); - dest->add_normal_predecessor(current_block); ---- /dev/null -+++ b/hotspot/test/compiler/parsing/Custom.jasm -@@ -0,0 +1,38 @@ -+/* -+ * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. -+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -+ * -+ * This code is free software; you can redistribute it and/or modify it -+ * under the terms of the GNU General Public License version 2 only, as -+ * published by the Free Software Foundation. -+ * -+ * This code is distributed in the hope that it will be useful, but WITHOUT -+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -+ * version 2 for more details (a copy is included in the LICENSE file that -+ * accompanied this code). -+ * -+ * You should have received a copy of the GNU General Public License version -+ * 2 along with this work; if not, write to the Free Software Foundation, -+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -+ * -+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -+ * or visit www.oracle.com if you need additional information or have any -+ * questions. -+ */ -+ -+package compiler/parsing; -+ -+super public class Custom { -+ -+ public static Method test:"(I)V" stack 2 locals 1 { -+ return; -+Loop: -+ // Unreachable block -+ iload_0; -+ bipush 100; -+ if_icmpge Loop; -+ // Falls through -+ } -+ -+} ---- /dev/null -+++ b/hotspot/test/compiler/parsing/UnreachableBlockFallsThroughEndOfCode.java -@@ -0,0 +1,42 @@ -+/* -+ * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. -+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -+ * -+ * This code is free software; you can redistribute it and/or modify it -+ * under the terms of the GNU General Public License version 2 only, as -+ * published by the Free Software Foundation. -+ * -+ * This code is distributed in the hope that it will be useful, but WITHOUT -+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -+ * version 2 for more details (a copy is included in the LICENSE file that -+ * accompanied this code). -+ * -+ * You should have received a copy of the GNU General Public License version -+ * 2 along with this work; if not, write to the Free Software Foundation, -+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -+ * -+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -+ * or visit www.oracle.com if you need additional information or have any -+ * questions. -+ * -+ */ -+ -+/* -+ * @test UnreachableBlockFallsThroughEndOfCode.java -+ * @bug 8283441 -+ * @compile Custom.jasm UnreachableBlockFallsThroughEndOfCode.java -+ * @summary Compiling method that falls off the end of the code array -+ * @run main/othervm -XX:TieredStopAtLevel=1 -Xbatch compiler.parsing.UnreachableBlockFallsThroughEndOfCode -+ * @run main/othervm -XX:-TieredCompilation -Xbatch compiler.parsing.UnreachableBlockFallsThroughEndOfCode -+ */ -+ -+package compiler.parsing; -+ -+public class UnreachableBlockFallsThroughEndOfCode { -+ public static void main(String[] strArr) { -+ for (int i = 0; i < 20000; i++) { -+ Custom.test(i); -+ } -+ } -+} diff -Nru openjdk-8-8u392-ga/debian/patches/build-warnings.diff openjdk-8-8u402-ga/debian/patches/build-warnings.diff --- openjdk-8-8u392-ga/debian/patches/build-warnings.diff 2023-05-11 20:30:25.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/build-warnings.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -# DP: - implicit free() decl - ---- a/jdk/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c -+++ b/jdk/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c -@@ -29,6 +29,7 @@ - #include "jlong.h" - - #include -+#include - #include - #include - #include diff -Nru openjdk-8-8u392-ga/debian/patches/catch-configure-errors.diff openjdk-8-8u402-ga/debian/patches/catch-configure-errors.diff --- openjdk-8-8u392-ga/debian/patches/catch-configure-errors.diff 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/catch-configure-errors.diff 2024-02-27 05:59:16.000000000 +0000 @@ -0,0 +1,19 @@ +Description: actually do catch errors from configure +Author: mirabilos +Forwarded: https://mail.openjdk.org/pipermail/jdk8u-dev/2024-January/017918.html + +--- a/common/autoconf/configure ++++ b/common/autoconf/configure +@@ -253,9 +253,10 @@ fi + # Now transfer control to the script generated by autoconf. This is where the + # main work is done. + conf_logfile=./configure.log +-(exec 3>&1 ; (. $conf_script_to_run "${conf_processed_arguments[@]}" 2>&1 1>&3 ) | tee -a $conf_logfile 1>&2 ; exec 3>&-) | tee -a $conf_logfile ++conf_result_code_file=./configure.errorlevel ++(exec 3>&1 ; (set +e; (. $conf_script_to_run "${conf_processed_arguments[@]}" 2>&1 1>&3 ); echo $? >$conf_result_code_file) | tee -a $conf_logfile 1>&2 ; exec 3>&-) | tee -a $conf_logfile + +-conf_result_code=$? ++conf_result_code=$(cat $conf_result_code_file || echo 255) + ### + ### Post-processing + ### diff -Nru openjdk-8-8u392-ga/debian/patches/icedtea-sound.diff openjdk-8-8u402-ga/debian/patches/icedtea-sound.diff --- openjdk-8-8u392-ga/debian/patches/icedtea-sound.diff 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/icedtea-sound.diff 2024-02-27 05:59:16.000000000 +0000 @@ -18,26 +18,6 @@ -I$(ICEDTEA_SOUND_NATIVE_BUILDDIR) -o $@ -c $< $(ICEDTEA_SOUND_NATIVE_BUILDDIR)/$(TARGET_NAME): $(ICEDTEA_SOUND_NATIVE_OBJECTS) ---- a/icedtea-sound/Makefile.in -+++ b/icedtea-sound/Makefile.in -@@ -313,7 +313,7 @@ - @ENABLE_DOCS_TRUE@JAVADOC_OPTS = -use -keywords -encoding UTF-8 -splitIndex \ - @ENABLE_DOCS_TRUE@ -bottom ' Submit a bug or feature' - --@ENABLE_DOCS_TRUE@@JAVADOC_SUPPORTS_J_OPTIONS_TRUE@JAVADOC_MEM_OPTS = -J-Xmx1024m -J-Xms128m -J-XX:PermSize=32m -J-XX:MaxPermSize=160m -+@ENABLE_DOCS_TRUE@@JAVADOC_SUPPORTS_J_OPTIONS_TRUE@JAVADOC_MEM_OPTS = -J-Xmx1000m -J-Xms128m -J-XX:PermSize=32m -J-XX:MaxPermSize=160m - all: all-am - - .SUFFIXES: -@@ -721,7 +721,7 @@ - touch $@ - - $(ICEDTEA_SOUND_NATIVE_BUILDDIR)/%.o: $(ICEDTEA_SOUND_NATIVE_SRCDIR)/%.c stamps/icedtea-sound-headers.stamp -- $(CC) $(IT_CFLAGS) -fPIC -I$(SYSTEM_JDK_DIR)/include/linux -I$(SYSTEM_JDK_DIR)/include \ -+ $(CC) $(IT_CFLAGS) -fPIC -I$(SYSTEM_JDK_DIR)/include/linux -I$(SYSTEM_JDK_DIR)/include/bsd -I$(SYSTEM_JDK_DIR)/include \ - -I$(ICEDTEA_SOUND_NATIVE_BUILDDIR) -o $@ -c $< - - $(ICEDTEA_SOUND_NATIVE_BUILDDIR)/$(TARGET_NAME): $(ICEDTEA_SOUND_NATIVE_OBJECTS) --- a/icedtea-sound/acinclude.m4 +++ b/icedtea-sound/acinclude.m4 @@ -24,14 +24,12 @@ @@ -93,85 +73,6 @@ JRE_ARCH_DIR=sparc CROSS_TARGET_ARCH=sparc ARCH_PREFIX=${LINUX32} -- ARCHFLAG="-m32" - ;; - sparc64) - BUILD_ARCH_DIR=sparcv9 - INSTALL_ARCH_DIR=sparcv9 - JRE_ARCH_DIR=sparc64 -- ARCHFLAG="-m64" - ;; - s390) - BUILD_ARCH_DIR=s390 - INSTALL_ARCH_DIR=s390 - JRE_ARCH_DIR=s390 - ARCH_PREFIX=${LINUX32} -- ARCHFLAG="-m31" - ;; - s390x) - BUILD_ARCH_DIR=s390x - INSTALL_ARCH_DIR=s390x - JRE_ARCH_DIR=s390x - CROSS_TARGET_ARCH=s390x -- ARCHFLAG="-m64" - ;; - sh*) - BUILD_ARCH_DIR=sh ---- a/icedtea-sound/configure -+++ b/icedtea-sound/configure -@@ -3719,14 +3719,12 @@ - BUILD_ARCH_DIR=amd64 - INSTALL_ARCH_DIR=amd64 - JRE_ARCH_DIR=amd64 -- ARCHFLAG="-m64" - ;; - i?86) - BUILD_ARCH_DIR=i586 - INSTALL_ARCH_DIR=i386 - JRE_ARCH_DIR=i386 - ARCH_PREFIX=${LINUX32} -- ARCHFLAG="-m32" - ;; - alpha*) - BUILD_ARCH_DIR=alpha -@@ -3737,13 +3735,11 @@ - BUILD_ARCH_DIR=arm - INSTALL_ARCH_DIR=arm - JRE_ARCH_DIR=arm -- ARCHFLAG="-D_LITTLE_ENDIAN" - ;; - arm64|aarch64) - BUILD_ARCH_DIR=aarch64 - INSTALL_ARCH_DIR=aarch64 - JRE_ARCH_DIR=aarch64 -- ARCHFLAG="-D_LITTLE_ENDIAN" - ;; - mips) - BUILD_ARCH_DIR=mips -@@ -3760,19 +3756,16 @@ - INSTALL_ARCH_DIR=ppc - JRE_ARCH_DIR=ppc - ARCH_PREFIX=${LINUX32} -- ARCHFLAG="-m32" - ;; - powerpc64) - BUILD_ARCH_DIR=ppc64 - INSTALL_ARCH_DIR=ppc64 - JRE_ARCH_DIR=ppc64 -- ARCHFLAG="-m64" - ;; - powerpc64le) - BUILD_ARCH_DIR=ppc64 - INSTALL_ARCH_DIR=ppc64 - JRE_ARCH_DIR=ppc64 -- ARCHFLAG="-m64" - ;; - sparc) - BUILD_ARCH_DIR=sparc -@@ -3780,27 +3773,23 @@ - JRE_ARCH_DIR=sparc - CROSS_TARGET_ARCH=sparc - ARCH_PREFIX=${LINUX32} - ARCHFLAG="-m32" ;; sparc64) diff -Nru openjdk-8-8u392-ga/debian/patches/link-with-as-needed.diff openjdk-8-8u402-ga/debian/patches/link-with-as-needed.diff --- openjdk-8-8u392-ga/debian/patches/link-with-as-needed.diff 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/link-with-as-needed.diff 2024-02-27 05:59:16.000000000 +0000 @@ -2,7 +2,7 @@ --- a/jdk/make/CompileLaunchers.gmk +++ b/jdk/make/CompileLaunchers.gmk -@@ -464,7 +464,7 @@ endif +@@ -471,7 +471,7 @@ endif # binary (at least on linux) which causes the size to differ between old and new build. ifeq ($(USE_EXTERNAL_LIBZ), true) UNPACKEXE_CFLAGS := -DSYSTEM_ZLIB @@ -11,7 +11,7 @@ else UNPACKEXE_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/java/util/zip/zlib UNPACKEXE_ZIPOBJS := $(JDK_OUTPUTDIR)/objs/libzip/zcrc32$(OBJ_SUFFIX) \ -@@ -524,9 +524,9 @@ $(eval $(call SetupNativeCompilation,BUI +@@ -531,9 +531,9 @@ $(eval $(call SetupNativeCompilation,BUI LDFLAGS_posix := $(LDFLAGS_JDKEXE) $(LDFLAGS_CXX_JDK) \ $(call SET_SHARED_LIBRARY_NAME,$(LIBRARY_PREFIX)unpack$(SHARED_LIBRARY_SUFFIX)) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ diff -Nru openjdk-8-8u392-ga/debian/patches/loong64-backport-jdk-8270517-and-8315020.diff openjdk-8-8u402-ga/debian/patches/loong64-backport-jdk-8270517-and-8315020.diff --- openjdk-8-8u392-ga/debian/patches/loong64-backport-jdk-8270517-and-8315020.diff 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/loong64-backport-jdk-8270517-and-8315020.diff 2024-02-27 05:59:16.000000000 +0000 @@ -0,0 +1,58 @@ +--- a/common/autoconf/platform.m4 ++++ b/common/autoconf/platform.m4 +@@ -169,6 +169,12 @@ AC_DEFUN([PLATFORM_EXTRACT_VARS_FROM_CPU + VAR_CPU_BITS=32 + VAR_CPU_ENDIAN=big + ;; ++ loongarch64) ++ VAR_CPU=loongarch64 ++ VAR_CPU_ARCH=loongarch ++ VAR_CPU_BITS=64 ++ VAR_CPU_ENDIAN=little ++ ;; + *) + AC_MSG_ERROR([unsupported cpu $1]) + ;; +@@ -450,6 +456,7 @@ AC_DEFUN([PLATFORM_SETUP_LEGACY_VARS], + case "${OPENJDK_TARGET_CPU}" in + alpha*) ZERO_ARCHDEF=ALPHA ;; + ia64) ZERO_ARCHDEF=IA64 ;; ++ loongarch64) ZERO_ARCHDEF=LOONGARCH64 ;; + m68k) ZERO_ARCHDEF=M68K ;; + mips|mipsn32|mips64) ZERO_ARCHDEF=MIPS ;; + mipsel|mipsn32el|mips64el) ZERO_ARCHDEF=MIPSEL ;; +--- a/hotspot/src/os/linux/vm/os_linux.cpp ++++ b/hotspot/src/os/linux/vm/os_linux.cpp +@@ -1949,6 +1949,9 @@ void * os::dll_load(const char *filename + #ifndef EM_AARCH64 + #define EM_AARCH64 183 /* ARM AARCH64 */ + #endif ++ #ifndef EM_LOONGARCH ++ #define EM_LOONGARCH 258 /* LoongArch */ ++ #endif + + static const arch_t arch_array[]={ + {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, +@@ -1972,7 +1975,8 @@ void * os::dll_load(const char *filename + {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, + {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}, + {EM_AARCH64, EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"}, +- {EM_SH, EM_SH, ELFCLASS32, ELFDATA2LSB, (char*)"Hitachi SH"} ++ {EM_SH, EM_SH, ELFCLASS32, ELFDATA2LSB, (char*)"Hitachi SH"}, ++ {EM_LOONGARCH, EM_LOONGARCH, ELFCLASS64, ELFDATA2LSB, (char*)"LoongArch"} + }; + + #if (defined IA32) +@@ -2007,9 +2011,11 @@ void * os::dll_load(const char *filename + static Elf32_Half running_arch_code=EM_AARCH64; + #elif (defined ZERO_SH) + static Elf32_Half running_arch_code=EM_SH; ++ #elif (defined LOONGARCH64) ++ static Elf32_Half running_arch_code=EM_LOONGARCH; + #else + #error Method os::dll_load requires that one of following is defined:\ +- IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K, AARCH64, SH ++ IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K, AARCH64, SH, LOONGARCH64 + #endif + + // Identify compatability class for VM's architecture and library's architecture diff -Nru openjdk-8-8u392-ga/debian/patches/system-libpng.diff openjdk-8-8u402-ga/debian/patches/system-libpng.diff --- openjdk-8-8u392-ga/debian/patches/system-libpng.diff 2023-10-21 19:24:54.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/system-libpng.diff 2024-02-27 05:59:16.000000000 +0000 @@ -52,7 +52,7 @@ --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in -@@ -604,6 +604,7 @@ endif +@@ -605,6 +605,7 @@ endif ENABLE_JFR=@ENABLE_JFR@ ENABLE_INTREE_EC=@ENABLE_INTREE_EC@ USE_EXTERNAL_LIBJPEG:=@USE_EXTERNAL_LIBJPEG@ diff -Nru openjdk-8-8u392-ga/debian/patches/system-pcsclite.diff openjdk-8-8u402-ga/debian/patches/system-pcsclite.diff --- openjdk-8-8u392-ga/debian/patches/system-pcsclite.diff 2023-02-06 21:58:29.000000000 +0000 +++ openjdk-8-8u402-ga/debian/patches/system-pcsclite.diff 2024-02-27 05:59:16.000000000 +0000 @@ -56,7 +56,7 @@ --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in -@@ -606,6 +606,7 @@ ENABLE_INTREE_EC=@ENABLE_INTREE_EC@ +@@ -607,6 +607,7 @@ ENABLE_INTREE_EC=@ENABLE_INTREE_EC@ USE_EXTERNAL_LIBJPEG:=@USE_EXTERNAL_LIBJPEG@ USE_EXTERNAL_LIBPNG:=@USE_EXTERNAL_LIBPNG@ USE_EXTERNAL_LIBGIF:=@USE_EXTERNAL_LIBGIF@ diff -Nru openjdk-8-8u392-ga/debian/refresher.sh openjdk-8-8u402-ga/debian/refresher.sh --- openjdk-8-8u392-ga/debian/refresher.sh 2023-05-11 20:30:25.000000000 +0000 +++ openjdk-8-8u402-ga/debian/refresher.sh 2024-02-27 05:59:16.000000000 +0000 @@ -6,6 +6,22 @@ qrc=$PWD/debian/refresher.rc arch=amd64 q() { quilt --quiltrc "$qrc" "$@"; } +function qpush { + set +e + local rc + + q push "$@" + rc=$? + if [[ $rc != [02] ]]; then + print -ru2 "E: quilt push returned errorlevel $rc" + print -ru2 "N: use the following command to clean up after inspecting:" + print -ru2 "N: fakeroot debian/rules DEB_HOST_ARCH=$arch clean" + exit $rc + fi + return $rc +} +typeset -ft q +set +o inherit-xtrace set -x for action in "$@"; do @@ -20,7 +36,7 @@ arch=$action debian/rules DEB_HOST_ARCH=$arch stamps/series cd src - while q push; do + while qpush; do q refresh done q pop -a @@ -28,3 +44,4 @@ ;; } done +exit 0 diff -Nru openjdk-8-8u392-ga/debian/rules openjdk-8-8u402-ga/debian/rules --- openjdk-8-8u392-ga/debian/rules 2023-10-23 08:35:54.000000000 +0000 +++ openjdk-8-8u402-ga/debian/rules 2024-02-27 07:56:51.000000000 +0000 @@ -50,11 +50,11 @@ hotspot_aarch32_archs = armhf -hotspot_archs = amd64 i386 arm64 ppc64 ppc64el sparc64 \ - $(hotspot_aarch32_archs) -jtreg_archs = $(hotspot_archs) alpha armel armhf \ - ia64 mips mipsel mips64 mips64el powerpc \ - powerpcspe ppc64 ppc64el s390x sh4 x32 +hotspot_archs = amd64 arm64 i386 ppc64 ppc64el \ + ${hotspot_aarch32_archs} +jtreg_archs = ${hotspot_archs} alpha armel \ + ia64 loong64 mips mipsel mips64 mips64el \ + powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc64 x32 # FIXME: use bootcycle builds for zero archs? bootcycle_build = $(if $(filter $(DEB_HOST_ARCH), $(hotspot_archs)),yes) ifneq ($(DEB_HOST_ARCH),$(DEB_BUILD_ARCH)) @@ -63,7 +63,7 @@ # we know about: # wheezy jessie stretch buster bullseye bookworm trixie sid -# precise trusty xenial bionic focal jammy (kinetic lunar mantic) +# precise trusty xenial bionic focal jammy (kinetic lunar mantic) noble ifneq (,$(filter $(distrel),wheezy precise trusty)) is_default = no @@ -95,11 +95,10 @@ is_release = is_release = yes gh_project = jdk8u -gh_tag = jdk8u392-ga +gh_tag = jdk8u402-ga version_dash_buildnr = $(subst ${gh_project},,${gh_tag}) -version_dash_buildnr = 392-b08 -# patched to get up to b08 (${UPSTREAM_PATCHES}) -gh_tag_aarch32 = jdk8u392-b07-aarch32-20231002 +version_dash_buildnr = 402-b06 +gh_tag_aarch32 = jdk8u402-ga-aarch32-20240118 package_version = $(subst jdk,,${gh_tag}) ifneq ($(is_release),yes) package_version := $(subst -,~,$(package_version)) @@ -152,8 +151,8 @@ with_docs = $(if $(findstring nodoc, $(DEB_BUILD_OPTIONS)),,yes) -arch_map := alpha=alpha arm=arm armel=arm armhf=arm arm64=aarch64 amd64=amd64 hppa=parisc i386=i586 m68k=m68k mips=mips mipsel=mipsel mips64=mips64 mips64el=mips64el powerpc=ppc powerpcspe=ppc ppc64=ppc64 ppc64el=ppc64le sparc=sparc sparc64=sparcv9 sh4=sh s390x=s390x ia64=ia64 x32=x32 -archdir_map := alpha=alpha arm=arm armel=arm armhf=arm arm64=aarch64 amd64=amd64 hppa=parisc i386=i386 m68k=m68k mips=mips mipsel=mipsel mips64=mips64 mips64el=mips64el powerpc=ppc powerpcspe=ppc ppc64=ppc64 ppc64el=ppc64le sparc=sparc sparc64=sparcv9 sh4=sh s390x=s390x ia64=ia64 x32=x32 +arch_map := alpha=alpha amd64=amd64 arm64=aarch64 arm=arm armel=arm armhf=arm hppa=parisc i386=i586 ia64=ia64 loong64=loongarch64 m68k=m68k mips=mips mipsel=mipsel mips64=mips64 mips64el=mips64el powerpc=ppc powerpcspe=ppc ppc64=ppc64 ppc64el=ppc64le s390x=s390x sh4=sh sparc64=sparcv9 sparc=sparc x32=x32 +archdir_map := alpha=alpha amd64=amd64 arm64=aarch64 arm=arm armel=arm armhf=arm hppa=parisc i386=i386 ia64=ia64 loong64=loongarch64 m68k=m68k mips=mips mipsel=mipsel mips64=mips64 mips64el=mips64el powerpc=ppc powerpcspe=ppc ppc64=ppc64 ppc64el=ppc64le s390x=s390x sh4=sh sparc64=sparcv9 sparc=sparc x32=x32 jvmarch := $(strip $(patsubst $(DEB_HOST_ARCH_CPU)=%, %, \ $(filter $(DEB_HOST_ARCH_CPU)=%, $(arch_map)))) @@ -171,7 +170,7 @@ hotspot_version = aarch32 endif -any_archs = alpha amd64 armel ${hotspot_aarch32_archs} arm64 i386 ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el m68k sh4 sparc sparc64 s390x x32 +any_archs = alpha amd64 arm64 armel ${hotspot_aarch32_archs} i386 ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc sparc64 x32 ifneq (,$(filter $(distrel),xenial)) transitional_jamvm_pkg = yes @@ -298,20 +297,20 @@ endif with_pulse = yes -ifneq (,$(filter $(DEB_HOST_ARCH), alpha)) - with_pulse = -endif ifneq (,$(filter $(distrel),xenial)) # TCK tests still failing with_bridge = else with_bridge = atk - ifeq ($(derivative),Ubuntu) - ifeq ($(DEB_HOST_ARCH),i386) - ifeq (,$(filter $(distrel),precise trusty xenial bionic)) - with_bridge = - endif +endif + +ifeq ($(derivative),Ubuntu) + ifeq ($(DEB_HOST_ARCH),i386) +# disable bridge on focal, jammy and mantic until atk wrapper is introduced +# in those releases on i386 + ifneq (,$(filter $(distrel),focal jammy mantic)) + with_bridge = endif endif endif @@ -337,10 +336,9 @@ COMMON_PATCHES = \ autoconf-select.diff \ bootstrap-with-8.diff \ - build-warnings.diff \ fix-encoding.diff \ + catch-configure-errors.diff \ disable-werror.diff \ - aarch64.diff \ hotspot-set-compiler.diff \ ppc64el.diff \ system-libjpeg.diff \ @@ -376,6 +374,11 @@ jdk-841269-filechooser.patch \ jdk-i18n-pt_BR.diff \ hotspot-ia64.diff \ + dnd-files.patch \ + zero-x32.diff \ + sparc-inline-conflict.diff \ + zero-sh.diff \ + loong64-backport-jdk-8270517-and-8315020.diff \ ifeq ($(derivative),Debian) COMMON_PATCHES += \ @@ -388,30 +391,13 @@ COMMON_PATCHES += java-access-bridge-security.patch endif -COMMON_PATCHES += \ - dnd-files.patch \ - zero-x32.diff \ - sparc-inline-conflict.diff \ - -ifeq (,$(filter $(DEB_HOST_ARCH),$(hotspot_aarch32_archs))) - COMMON_PATCHES += \ - zero-sh.diff -endif - ifeq ($(with_pulse),yes) COMMON_PATCHES += \ jdk-pulseaudio.diff endif -ifneq (,$(filter $(DEB_HOST_ARCH), alpha)) - # FIXME: Needed for non-bootstrap builds? - COMMON_PATCHES += \ - alpha-float-const.diff -endif - # set LIBARCH/aarch32 to arm ifneq (,$(filter $(DEB_HOST_ARCH), $(hotspot_aarch32_archs))) - UPSTREAM_PATCHES += b07-to-b08-hotspot.diff COMMON_PATCHES += \ aarch32.diff endif @@ -734,7 +720,7 @@ bd_fastjar = fastjar (>= 2:0.96-0ubuntu2), ifeq ($(with_pulse),yes) - bd_pulsejava = libpulse-dev (>= 0.9.12) [!alpha], + bd_pulsejava = libpulse-dev (>= 0.9.12), endif ifeq ($(with_nss),yes) bd_nss = libnss3-dev (>= 2:3.26), @@ -963,9 +949,10 @@ configure: stamps/configure stamps/configure: stamps/patch -cat /etc/hosts + -cat /proc/cpuinfo mkdir -p bin -ifeq (,$(filter $(DEB_HOST_ARCH), alpha amd64 arm64 hppa mips64 mips64el ppc64 ppc64el s390x sparc64 x32)) +ifeq (,$(filter $(DEB_HOST_ARCH), alpha amd64 arm64 ia64 loong64 mips64 mips64el ppc64 ppc64el s390x sparc64 x32)) ( \ echo '#! /bin/sh'; \ echo 'if [ -x /usr/bin/linux32 ]; then'; \ @@ -975,9 +962,9 @@ echo 'fi'; \ ) > bin/uname chmod +x bin/uname +endif echo "UNAME checks" uname -a -endif /bin/uname -a lsb_release -a @@ -985,20 +972,27 @@ mkdir -p stamps mkdir -p $(builddir) + cd ${srcdir}/common/autoconf/build-aux && \ + rm -f autoconf-config.* config.guess config.sub && \ + cp /usr/share/misc/config.guess /usr/share/misc/config.sub . cd $(srcdir) && sh common/autoconf/autogen.sh - cd $(builddir) && $(EXTRA_BUILD_ENV) ../$(srcdir)/configure \ - $(DEFAULT_CONFIGURE_ARGS) \ - $(COMMON_CONFIGURE_ARGS) - + cd $(builddir) && $(EXTRA_BUILD_ENV) sh ../$(srcdir)/configure \ + ${DEFAULT_CONFIGURE_ARGS} ${COMMON_CONFIGURE_ARGS} || { \ + tail -v -n +0 config.log || :; \ + echo >&2 'E: configure for $@ failed'; \ + exit 1; \ + } touch $@ stamps/zero-configure: stamps/build stamps/patch mkdir -p stamps mkdir -p $(zbuilddir) - cd $(zbuilddir) && $(EXTRA_BUILD_ENV) ../$(srcdir)/configure \ - $(ZERO_CONFIGURE_ARGS) \ - $(COMMON_CONFIGURE_ARGS) - + cd $(zbuilddir) && $(EXTRA_BUILD_ENV) sh ../$(srcdir)/configure \ + ${ZERO_CONFIGURE_ARGS} ${COMMON_CONFIGURE_ARGS} || { \ + tail -v -n +0 config.log || :; \ + echo >&2 'E: configure for $@ failed'; \ + exit 1; \ + } touch $@ stamps/sound-configure: stamps/build @@ -1007,18 +1001,23 @@ mv $$(tar tf icedtea-sound.tar.xz | head -1 | sed 's,/.*,,') \ icedtea-sound patch -p1 < debian/patches/icedtea-sound.diff - if [ -x icedtea-sound/autogen.sh ]; then \ - cd icedtea-sound && ./autogen.sh; \ - fi - cd icedtea-sound && ./configure \ - --build=$(DEB_BUILD_GNU_TYPE) \ - --host=$(DEB_HOST_GNU_TYPE) \ - --disable-maintainer-mode \ - --with-jdk-home=$(BUILDJDK_HOME) \ - CPPFLAGS="$(EXTRA_CPPFLAGS_IT)" \ - CFLAGS="$(EXTRA_CFLAGS_IT)" \ - CXXFLAGS="$(EXTRA_CXXFLAGS_IT)" \ - LDFLAGS="$(EXTRA_LDFLAGS_IT)" + cd icedtea-sound && \ + rm -f config.guess config.sub configure && \ + cp /usr/share/misc/config.guess /usr/share/misc/config.sub . + cd icedtea-sound && autoreconf -f -i -v + cd icedtea-sound && sh configure \ + --build=$(DEB_BUILD_GNU_TYPE) \ + --host=$(DEB_HOST_GNU_TYPE) \ + --disable-maintainer-mode \ + --with-jdk-home=$(BUILDJDK_HOME) \ + CPPFLAGS="$(EXTRA_CPPFLAGS_IT)" \ + CFLAGS="$(EXTRA_CFLAGS_IT)" \ + CXXFLAGS="$(EXTRA_CXXFLAGS_IT)" \ + LDFLAGS="$(EXTRA_LDFLAGS_IT)" || { \ + tail -v -n +0 config.log || :; \ + echo >&2 'E: configure for $@ failed'; \ + exit 1; \ + } touch $@ stamps/sound-build: stamps/sound-configure @@ -1030,7 +1029,6 @@ rm -rf $(srcdir) mkdir -p $(srcdir) tar -xf root.tar.xz --strip-components=1 -C $(srcdir) - chmod +x $(srcdir)/configure for tb in corba jaxp jaxws langtools hotspot jdk nashorn; do \ tar -C $(srcdir) -x -f $$tb.tar.xz; \ done @@ -1051,9 +1049,7 @@ patch: stamps/patch stamps/series: stamps/unpack - for i in $(DEFAULT_PATCHES); do \ - echo $$i; \ - done > $(srcdir)/series + printf '%s\n' ${DEFAULT_PATCHES} >${srcdir}/series @:>$@ stamps/patch: stamps/series @@ -1063,7 +1059,7 @@ echo ""; echo "Patches applied in this version:"; \ for i in $$(egrep -v '^#|^ *$$' $(srcdir)/series); do \ echo ""; echo "$$i:"; \ - sed -n 's/^# *DP: */ /p' debian/patches/$$i; \ + sed -n -E 's/^(# *DP|Description): */ /p' debian/patches/$$i; \ done \ ) > stamps/pxx mv stamps/pxx $@ @@ -1112,7 +1108,7 @@ rm -f buildwatch.pid stamps/build: stamps/configure -ifneq (,$(filter $(DEB_HOST_ARCH), alpha armel armhf ia64 m68k mips mipsel mips64 mips64el powerpc powerpcspe s390x sh4 sparc sparc64)) +ifneq (,$(filter $(DEB_HOST_ARCH), alpha armel armhf ia64 loong64 m68k mips mipsel mips64 mips64el powerpc powerpcspe s390x sh4 sparc sparc64)) sh -c 'sh debian/buildwatch.sh $(CURDIR)/$(builddir) &' endif if $(EXTRA_BUILD_ENV) $(MAKE) -C $(builddir) $(build_target); then \ @@ -1337,7 +1333,7 @@ done ifeq ($(with_bridge),atk) - ifneq (,$(filter $(distrel),wheezy jessie precise trusty)) + ifneq (,$(filter $(distrel),wheezy jessie precise trusty xenial bionic focal jammy)) cp -p debian/accessibility-atk.properties.disabled \ $(d)/$(basedir)/jre/lib/accessibility.properties else @@ -1607,8 +1603,7 @@ # 'make Emacs Makefile mode happy dh_installdirs -p$(p_jrehl) \ - usr/share/doc/$(p_jrehl) \ - usr/share/binfmts + usr/share/doc/$(p_jrehl) dh_installdirs -p$(p_jre) \ usr/share/applications \ @@ -1746,12 +1741,6 @@ done; \ ) > $(d_jrehl)/$(TOP)/.$(jdiralias).jinfo - ( \ - echo 'package $(basename)'; \ - echo 'interpreter /usr/bin/jexec'; \ - echo 'magic PK\x03\x04'; \ - ) > $(d_jrehl)/$(basedir)/jre/lib/jar.binfmt - : # another jvm symlink ln -sf $(jdirname) $(d_jrehl)/usr/lib/jvm/$(jdiralias) mkdir -p $(d_jrehl)/usr/lib/debug/usr/lib/jvm @@ -2032,7 +2021,7 @@ debian/refresh: mksh debian/refresher.sh : \ $(if ${hotspot_aarch32_archs}, armhf : ) \ - alpha . amd64 : + amd64 : binary: binary-arch binary-indep .PHONY: build build-arch build-indep clean binary-indep binary-arch binary install packaging-files diff -Nru openjdk-8-8u392-ga/debian/tests/hotspot-archs openjdk-8-8u402-ga/debian/tests/hotspot-archs --- openjdk-8-8u392-ga/debian/tests/hotspot-archs 2023-05-11 20:30:25.000000000 +0000 +++ openjdk-8-8u402-ga/debian/tests/hotspot-archs 2024-02-27 05:59:16.000000000 +0000 @@ -1 +1 @@ -amd64 i386 arm64 ppc64 ppc64el sparc64 armhf +amd64 arm64 i386 ppc64 ppc64el armhf diff -Nru openjdk-8-8u392-ga/debian/tests/jtreg-autopkgtest.sh openjdk-8-8u402-ga/debian/tests/jtreg-autopkgtest.sh --- openjdk-8-8u392-ga/debian/tests/jtreg-autopkgtest.sh 2023-05-11 20:30:25.000000000 +0000 +++ openjdk-8-8u402-ga/debian/tests/jtreg-autopkgtest.sh 2024-02-27 05:59:16.000000000 +0000 @@ -36,7 +36,7 @@ fi # restrict the tests to a few archs (set from debian/rules) -if ! echo "${host_arch}" | grep -qE "^($(echo amd64 i386 arm64 ppc64 ppc64el sparc64 armhf alpha armel armhf ia64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 x32 | tr ' ' '|'))$"; then +if ! echo "${host_arch}" | grep -qE "^($(echo amd64 arm64 i386 ppc64 ppc64el armhf alpha armel ia64 loong64 mips mipsel mips64 mips64el powerpc powerpcspe ppc64 ppc64el s390x sh4 sparc64 x32 | tr ' ' '|'))$"; then echo "Error: ${host_arch} is not on the jtreg_archs list, ignoring it." exit 77 fi Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/hotspot-aarch32.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/hotspot-aarch32.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/hotspot.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/hotspot.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/jaxp.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/jaxp.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/jaxws.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/jaxws.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/jdk.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/jdk.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/langtools.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/langtools.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/nashorn.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/nashorn.tar.xz differ Binary files /tmp/tmp7xo4xcx8/VEJuGUbOjo/openjdk-8-8u392-ga/root.tar.xz and /tmp/tmp7xo4xcx8/lM1s6TdDX8/openjdk-8-8u402-ga/root.tar.xz differ