1 /*
   2  * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 package jdk.test.lib;
  25 
  26 import static jdk.test.lib.Asserts.assertTrue;
  27 import java.io.IOException;
  28 import java.lang.reflect.Field;
  29 import java.net.InetAddress;
  30 import java.net.ServerSocket;
  31 import java.net.UnknownHostException;
  32 import java.nio.file.Files;
  33 import java.nio.file.Path;
  34 import java.nio.file.Paths;
  35 import java.util.ArrayList;
  36 import java.util.Arrays;
  37 import java.util.Collection;
  38 import java.util.Collections;
  39 import java.util.Iterator;
  40 import java.util.List;
  41 import java.util.Random;
  42 import java.util.function.BooleanSupplier;
  43 import java.util.concurrent.TimeUnit;
  44 import java.util.regex.Matcher;
  45 import java.util.regex.Pattern;
  46 import java.util.stream.Collectors;
  47 import sun.misc.Unsafe;
  48 
  49 /**
  50  * Common library for various test helper functions.
  51  */
  52 public final class Utils {
  53 
  54     /**
  55      * Returns the sequence used by operating system to separate lines.
  56      */
  57     public static final String NEW_LINE = System.getProperty("line.separator");
  58 
  59     /**
  60      * Returns the value of 'test.vm.opts' system property.
  61      */
  62     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  63 
  64     /**
  65      * Returns the value of 'test.java.opts' system property.
  66      */
  67     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  68 
  69     /**
  70      * Returns the value of 'test.src' system property.
  71      */
  72     public static final String TEST_SRC = System.getProperty("test.src", "").trim();
  73 
  74     private static Unsafe unsafe = null;
  75 
  76     /**
  77      * Defines property name for seed value.
  78      */
  79     public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed";
  80 
  81     /* (non-javadoc)
  82      * Random generator with (or without) predefined seed. Depends on
  83      * "jdk.test.lib.random.seed" property value.
  84      */
  85     private static volatile Random RANDOM_GENERATOR;
  86 
  87     /**
  88      * Contains the seed value used for {@link java.util.Random} creation.
  89      */
  90     public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong());
  91     /**
  92     * Returns the value of 'test.timeout.factor' system property
  93     * converted to {@code double}.
  94     */
  95     public static final double TIMEOUT_FACTOR;
  96     static {
  97         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  98         TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  99     }
 100 
 101     /**
 102     * Returns the value of JTREG default test timeout in milliseconds
 103     * converted to {@code long}.
 104     */
 105     public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
 106 
 107     private Utils() {
 108         // Private constructor to prevent class instantiation
 109     }
 110 
 111     /**
 112      * Returns the list of VM options.
 113      *
 114      * @return List of VM options
 115      */
 116     public static List<String> getVmOptions() {
 117         return Arrays.asList(safeSplitString(VM_OPTIONS));
 118     }
 119 
 120     /**
 121      * Returns the list of VM options with -J prefix.
 122      *
 123      * @return The list of VM options with -J prefix
 124      */
 125     public static List<String> getForwardVmOptions() {
 126         String[] opts = safeSplitString(VM_OPTIONS);
 127         for (int i = 0; i < opts.length; i++) {
 128             opts[i] = "-J" + opts[i];
 129         }
 130         return Arrays.asList(opts);
 131     }
 132 
 133     /**
 134      * Returns the default JTReg arguments for a jvm running a test.
 135      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 136      * @return An array of options, or an empty array if no options.
 137      */
 138     public static String[] getTestJavaOpts() {
 139         List<String> opts = new ArrayList<String>();
 140         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 141         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 142         return opts.toArray(new String[0]);
 143     }
 144 
 145     /**
 146      * Returns the default JTReg arguments for a jvm running a test without
 147      * options that matches regular expressions in {@code filters}.
 148      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 149      * @param filters Regular expressions used to filter out options.
 150      * @return An array of options, or an empty array if no options.
 151      */
 152     public static String[] getFilteredTestJavaOpts(String... filters) {
 153         String options[] = getTestJavaOpts();
 154 
 155         if (filters.length == 0) {
 156             return options;
 157         }
 158 
 159         List<String> filteredOptions = new ArrayList<String>(options.length);
 160         Pattern patterns[] = new Pattern[filters.length];
 161         for (int i = 0; i < filters.length; i++) {
 162             patterns[i] = Pattern.compile(filters[i]);
 163         }
 164 
 165         for (String option : options) {
 166             boolean matched = false;
 167             for (int i = 0; i < patterns.length && !matched; i++) {
 168                 Matcher matcher = patterns[i].matcher(option);
 169                 matched = matcher.find();
 170             }
 171             if (!matched) {
 172                 filteredOptions.add(option);
 173             }
 174         }
 175 
 176         return filteredOptions.toArray(new String[filteredOptions.size()]);
 177     }
 178 
 179     /**
 180      * Combines given arguments with default JTReg arguments for a jvm running a test.
 181      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 182      * @return The combination of JTReg test java options and user args.
 183      */
 184     public static String[] addTestJavaOpts(String... userArgs) {
 185         List<String> opts = new ArrayList<String>();
 186         Collections.addAll(opts, getTestJavaOpts());
 187         Collections.addAll(opts, userArgs);
 188         return opts.toArray(new String[0]);
 189     }
 190 
 191     /**
 192      * Splits a string by white space.
 193      * Works like String.split(), but returns an empty array
 194      * if the string is null or empty.
 195      */
 196     private static String[] safeSplitString(String s) {
 197         if (s == null || s.trim().isEmpty()) {
 198             return new String[] {};
 199         }
 200         return s.trim().split("\\s+");
 201     }
 202 
 203     /**
 204      * @return The full command line for the ProcessBuilder.
 205      */
 206     public static String getCommandLine(ProcessBuilder pb) {
 207         StringBuilder cmd = new StringBuilder();
 208         for (String s : pb.command()) {
 209             cmd.append(s).append(" ");
 210         }
 211         return cmd.toString();
 212     }
 213 
 214     /**
 215      * Returns the free port on the local host.
 216      * The function will spin until a valid port number is found.
 217      *
 218      * @return The port number
 219      * @throws InterruptedException if any thread has interrupted the current thread
 220      * @throws IOException if an I/O error occurs when opening the socket
 221      */
 222     public static int getFreePort() throws InterruptedException, IOException {
 223         int port = -1;
 224 
 225         while (port <= 0) {
 226             Thread.sleep(100);
 227 
 228             ServerSocket serverSocket = null;
 229             try {
 230                 serverSocket = new ServerSocket(0);
 231                 port = serverSocket.getLocalPort();
 232             } finally {
 233                 serverSocket.close();
 234             }
 235         }
 236 
 237         return port;
 238     }
 239 
 240     /**
 241      * Returns the name of the local host.
 242      *
 243      * @return The host name
 244      * @throws UnknownHostException if IP address of a host could not be determined
 245      */
 246     public static String getHostname() throws UnknownHostException {
 247         InetAddress inetAddress = InetAddress.getLocalHost();
 248         String hostName = inetAddress.getHostName();
 249 
 250         assertTrue((hostName != null && !hostName.isEmpty()),
 251                 "Cannot get hostname");
 252 
 253         return hostName;
 254     }
 255 
 256     /**
 257      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 258      * forever (until jtreg timeout) for the pid to be found.
 259      * @param key Regular expression to search for
 260      * @return The found pid.
 261      */
 262     public static int waitForJvmPid(String key) throws Throwable {
 263         final long iterationSleepMillis = 250;
 264         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 265         System.out.flush();
 266         while (true) {
 267             int pid = tryFindJvmPid(key);
 268             if (pid >= 0) {
 269                 return pid;
 270             }
 271             Thread.sleep(iterationSleepMillis);
 272         }
 273     }
 274 
 275     /**
 276      * Searches for a jvm pid in the output from "jcmd -l".
 277      *
 278      * Example output from jcmd is:
 279      * 12498 sun.tools.jcmd.JCmd -l
 280      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 281      *
 282      * @param key A regular expression to search for.
 283      * @return The found pid, or -1 if not found.
 284      * @throws Exception If multiple matching jvms are found.
 285      */
 286     public static int tryFindJvmPid(String key) throws Throwable {
 287         OutputAnalyzer output = null;
 288         try {
 289             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 290             jcmdLauncher.addToolArg("-l");
 291             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 292             output.shouldHaveExitValue(0);
 293 
 294             // Search for a line starting with numbers (pid), follwed by the key.
 295             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 296             Matcher matcher = pattern.matcher(output.getStdout());
 297 
 298             int pid = -1;
 299             if (matcher.find()) {
 300                 pid = Integer.parseInt(matcher.group(1));
 301                 System.out.println("findJvmPid.pid: " + pid);
 302                 if (matcher.find()) {
 303                     throw new Exception("Found multiple JVM pids for key: " + key);
 304                 }
 305             }
 306             return pid;
 307         } catch (Throwable t) {
 308             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 309             throw t;
 310         }
 311     }
 312 
 313     /**
 314      * Return the contents of the named file as a single String,
 315      * or null if not found.
 316      * @param filename name of the file to read
 317      * @return String contents of file, or null if file not found.
 318      * @throws  IOException
 319      *          if an I/O error occurs reading from the file or a malformed or
 320      *          unmappable byte sequence is read
 321      */
 322     public static String fileAsString(String filename) throws IOException {
 323         Path filePath = Paths.get(filename);
 324         if (!Files.exists(filePath)) return null;
 325         return new String(Files.readAllBytes(filePath));
 326     }
 327 
 328     /**
 329      * @return Unsafe instance.
 330      */
 331     public static synchronized Unsafe getUnsafe() {
 332         if (unsafe == null) {
 333             try {
 334                 Field f = Unsafe.class.getDeclaredField("theUnsafe");
 335                 f.setAccessible(true);
 336                 unsafe = (Unsafe) f.get(null);
 337             } catch (NoSuchFieldException | IllegalAccessException e) {
 338                 throw new RuntimeException("Unable to get Unsafe instance.", e);
 339             }
 340         }
 341         return unsafe;
 342     }
 343     private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 344 
 345     /**
 346      * Returns hex view of byte array
 347      *
 348      * @param bytes byte array to process
 349      * @return Space separated hexadecimal string representation of bytes
 350      */
 351 
 352     public static String toHexString(byte[] bytes) {
 353         char[] hexView = new char[bytes.length * 3];
 354         int i = 0;
 355         for (byte b : bytes) {
 356             hexView[i++] = hexArray[(b >> 4) & 0x0F];
 357             hexView[i++] = hexArray[b & 0x0F];
 358             hexView[i++] = ' ';
 359         }
 360         return new String(hexView);
 361     }
 362 
 363     /**
 364      * Returns {@link java.util.Random} generator initialized with particular seed.
 365      * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}
 366      * In case no seed is provided, the method uses a random number.
 367      * The used seed printed to stdout.
 368      * @return {@link java.util.Random} generator with particular seed.
 369      */
 370     public static Random getRandomInstance() {
 371         if (RANDOM_GENERATOR == null) {
 372             synchronized (Utils.class) {
 373                 if (RANDOM_GENERATOR == null) {
 374                     RANDOM_GENERATOR = new Random(SEED);
 375                     System.out.printf("For random generator using seed: %d%n", SEED);
 376                     System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED);
 377                 }
 378             }
 379         }
 380         return RANDOM_GENERATOR;
 381     }
 382 
 383     /**
 384      * Returns random element of non empty collection
 385      *
 386      * @param <T> a type of collection element
 387      * @param collection collection of elements
 388      * @return random element of collection
 389      * @throws IllegalArgumentException if collection is empty
 390      */
 391     public static <T> T getRandomElement(Collection<T> collection)
 392             throws IllegalArgumentException {
 393         if (collection.isEmpty()) {
 394             throw new IllegalArgumentException("Empty collection");
 395         }
 396         Random random = getRandomInstance();
 397         int elementIndex = 1 + random.nextInt(collection.size() - 1);
 398         Iterator<T> iterator = collection.iterator();
 399         while (--elementIndex != 0) {
 400             iterator.next();
 401         }
 402         return iterator.next();
 403     }
 404 
 405     /**
 406      * Returns random element of non empty array
 407      *
 408      * @param <T> a type of array element
 409      * @param array array of elements
 410      * @return random element of array
 411      * @throws IllegalArgumentException if array is empty
 412      */
 413     public static <T> T getRandomElement(T[] array)
 414             throws IllegalArgumentException {
 415         if (array == null || array.length == 0) {
 416             throw new IllegalArgumentException("Empty or null array");
 417         }
 418         Random random = getRandomInstance();
 419         return array[random.nextInt(array.length)];
 420     }
 421 
 422     /**
 423      * Wait for condition to be true
 424      *
 425      * @param condition, a condition to wait for
 426      */
 427     public static final void waitForCondition(BooleanSupplier condition) {
 428         waitForCondition(condition, -1L, 100L);
 429     }
 430 
 431     /**
 432      * Wait until timeout for condition to be true
 433      *
 434      * @param condition, a condition to wait for
 435      * @param timeout a time in milliseconds to wait for condition to be true
 436      * specifying -1 will wait forever
 437      * @return condition value, to determine if wait was successful
 438      */
 439     public static final boolean waitForCondition(BooleanSupplier condition,
 440             long timeout) {
 441         return waitForCondition(condition, timeout, 100L);
 442     }
 443 
 444     /**
 445      * Wait until timeout for condition to be true for specified time
 446      *
 447      * @param condition, a condition to wait for
 448      * @param timeout a time in milliseconds to wait for condition to be true,
 449      * specifying -1 will wait forever
 450      * @param sleepTime a time to sleep value in milliseconds
 451      * @return condition value, to determine if wait was successful
 452      */
 453     public static final boolean waitForCondition(BooleanSupplier condition,
 454             long timeout, long sleepTime) {
 455         long startTime = System.currentTimeMillis();
 456         while (!(condition.getAsBoolean() || (timeout != -1L
 457                 && ((System.currentTimeMillis() - startTime) > timeout)))) {
 458             try {
 459                 Thread.sleep(sleepTime);
 460             } catch (InterruptedException e) {
 461                 Thread.currentThread().interrupt();
 462                 throw new Error(e);
 463             }
 464         }
 465         return condition.getAsBoolean();
 466     }
 467 
 468     /**
 469      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 470      * @param tOut the timeout value to be adjusted
 471      * @return The timeout value adjusted for the value of "test.timeout.factor"
 472      *         system property
 473      */
 474     public static long adjustTimeout(long tOut) {
 475         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 476     }
 477 
 478     /**
 479      * Ensures a requested class is loaded
 480      * @param aClass class to load
 481      */
 482     public static void ensureClassIsLoaded(Class<?> aClass) {
 483         if (aClass == null) {
 484             throw new Error("Requested null class");
 485         }
 486         try {
 487             Class.forName(aClass.getName(), /* initialize = */ true,
 488                     ClassLoader.getSystemClassLoader());
 489         } catch (ClassNotFoundException e) {
 490             throw new Error("Class not found", e);
 491         }
 492     }
 493     /**
 494      * Runs runnable and checks that it throws expected exception. If exceptionException is null it means
 495      * that we expect no exception to be thrown.
 496      * @param runnable what we run
 497      * @param expectedException expected exception
 498      */
 499     public static void runAndCheckException(Runnable runnable, Class<? extends Throwable> expectedException) {
 500         boolean expectedExceptionWasNotThrown = false;
 501         try {
 502             runnable.run();
 503             if (expectedException != null) {
 504                 expectedExceptionWasNotThrown = true;
 505             }
 506         } catch (Throwable t) {
 507             if (expectedException == null) {
 508                 throw new AssertionError("Got unexpected exception ", t);
 509             }
 510             if (!expectedException.isAssignableFrom(t.getClass())) {
 511                 throw new AssertionError(String.format("Got unexpected exception %s instead of %s",
 512                         t.getClass().getSimpleName(), expectedException.getSimpleName()), t);
 513             }
 514         }
 515         if (expectedExceptionWasNotThrown) {
 516            throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName());
 517         }
 518     }
 519 
 520     /**
 521      * Converts to VM type signature
 522      *
 523      * @param type Java type to convert
 524      * @return string representation of VM type
 525      */
 526     public static String toJVMTypeSignature(Class<?> type) {
 527         if (type.isPrimitive()) {
 528             if (type == boolean.class) {
 529                 return "Z";
 530             } else if (type == byte.class) {
 531                 return "B";
 532             } else if (type == char.class) {
 533                 return "C";
 534             } else if (type == double.class) {
 535                 return "D";
 536             } else if (type == float.class) {
 537                 return "F";
 538             } else if (type == int.class) {
 539                 return "I";
 540             } else if (type == long.class) {
 541                 return "J";
 542             } else if (type == short.class) {
 543                 return "S";
 544             } else if (type == void.class) {
 545                 return "V";
 546             } else {
 547                 throw new Error("Unsupported type: " + type);
 548             }
 549         }
 550         String result = type.getName().replaceAll("\\.", "/");
 551         if (!type.isArray()) {
 552             return "L" + result + ";";
 553         }
 554         return result;
 555     }
 556 }
 557