Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/tools/launcher/TestHelper.java
38833 views
1
/*
2
* Copyright (c) 2008, 2013, 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
import java.io.OutputStream;
25
import java.io.InputStream;
26
import java.lang.annotation.ElementType;
27
import java.lang.annotation.Retention;
28
import java.lang.annotation.RetentionPolicy;
29
import java.lang.annotation.Target;
30
import java.lang.reflect.Method;
31
import java.util.regex.Pattern;
32
import java.io.StringWriter;
33
import java.io.PrintWriter;
34
import java.util.Set;
35
import java.io.BufferedReader;
36
import java.io.File;
37
import java.io.FileFilter;
38
import java.io.FileNotFoundException;
39
import java.io.FileOutputStream;
40
import java.io.IOException;
41
import java.io.InputStreamReader;
42
import java.io.PrintStream;
43
import java.nio.charset.Charset;
44
import java.nio.file.attribute.BasicFileAttributes;
45
import java.nio.file.Files;
46
import java.nio.file.FileVisitResult;
47
import java.nio.file.SimpleFileVisitor;
48
import java.nio.file.Path;
49
import java.util.ArrayList;
50
import java.util.List;
51
import java.util.Locale;
52
import java.util.Map;
53
import javax.tools.JavaCompiler;
54
import javax.tools.ToolProvider;
55
56
import static java.nio.file.StandardCopyOption.*;
57
import static java.nio.file.StandardOpenOption.*;
58
59
/**
60
* This class provides some common utilities for the launcher tests.
61
*/
62
public class TestHelper {
63
// commonly used jtreg constants
64
static final File TEST_CLASSES_DIR;
65
static final File TEST_SOURCES_DIR;
66
67
static final String JAVAHOME = System.getProperty("java.home");
68
static final String JAVA_BIN;
69
static final String JAVA_JRE_BIN;
70
static final String JAVA_LIB;
71
static final String JAVA_JRE_LIB;
72
static final boolean isSDK = JAVAHOME.endsWith("jre");
73
static final String javaCmd;
74
static final String javawCmd;
75
static final String javacCmd;
76
static final String jarCmd;
77
static final boolean haveServerVM;
78
static final boolean haveClientVM;
79
80
static final JavaCompiler compiler;
81
82
static final boolean debug = Boolean.getBoolean("TestHelper.Debug");
83
static final boolean isWindows =
84
System.getProperty("os.name", "unknown").startsWith("Windows");
85
static final boolean isMacOSX =
86
System.getProperty("os.name", "unknown").contains("OS X");
87
static final boolean is64Bit =
88
System.getProperty("sun.arch.data.model").equals("64");
89
static final boolean is32Bit =
90
System.getProperty("sun.arch.data.model").equals("32");
91
static final boolean isSolaris =
92
System.getProperty("os.name", "unknown").startsWith("SunOS");
93
static final boolean isLinux =
94
System.getProperty("os.name", "unknown").startsWith("Linux");
95
static final boolean isAIX =
96
System.getProperty("os.name", "unknown").startsWith("AIX");
97
static final String LIBJVM = isWindows
98
? "jvm.dll"
99
: "libjvm" + (isMacOSX ? ".dylib" : ".so");
100
101
static final boolean isSparc = System.getProperty("os.arch").startsWith("sparc");
102
103
// make a note of the golden default locale
104
static final Locale DefaultLocale = Locale.getDefault();
105
106
static final String JAVA_FILE_EXT = ".java";
107
static final String CLASS_FILE_EXT = ".class";
108
static final String JAR_FILE_EXT = ".jar";
109
static final String EXE_FILE_EXT = ".exe";
110
static final String JLDEBUG_KEY = "_JAVA_LAUNCHER_DEBUG";
111
static final String EXPECTED_MARKER = "TRACER_MARKER:About to EXEC";
112
static final String TEST_PREFIX = "###TestError###: ";
113
114
static int testExitValue = 0;
115
116
static {
117
String tmp = System.getProperty("test.classes", null);
118
if (tmp == null) {
119
throw new Error("property test.classes not defined ??");
120
}
121
TEST_CLASSES_DIR = new File(tmp).getAbsoluteFile();
122
123
tmp = System.getProperty("test.src", null);
124
if (tmp == null) {
125
throw new Error("property test.src not defined ??");
126
}
127
TEST_SOURCES_DIR = new File(tmp).getAbsoluteFile();
128
129
if (is64Bit && is32Bit) {
130
throw new RuntimeException("arch model cannot be both 32 and 64 bit");
131
}
132
if (!is64Bit && !is32Bit) {
133
throw new RuntimeException("arch model is not 32 or 64 bit ?");
134
}
135
compiler = ToolProvider.getSystemJavaCompiler();
136
137
File binDir = (isSDK)
138
? new File((new File(JAVAHOME)).getParentFile(), "bin")
139
: new File(JAVAHOME, "bin");
140
JAVA_BIN = binDir.getAbsolutePath();
141
JAVA_JRE_BIN = new File(JAVAHOME, "bin").getAbsolutePath();
142
143
File libDir = (isSDK)
144
? new File((new File(JAVAHOME)).getParentFile(), "lib")
145
: new File(JAVAHOME, "lib");
146
JAVA_LIB = libDir.getAbsolutePath();
147
JAVA_JRE_LIB = new File(JAVAHOME, "lib").getAbsolutePath();
148
149
File javaCmdFile = (isWindows)
150
? new File(binDir, "java.exe")
151
: new File(binDir, "java");
152
javaCmd = javaCmdFile.getAbsolutePath();
153
if (!javaCmdFile.canExecute()) {
154
throw new RuntimeException("java <" + TestHelper.javaCmd +
155
"> must exist and should be executable");
156
}
157
158
File javacCmdFile = (isWindows)
159
? new File(binDir, "javac.exe")
160
: new File(binDir, "javac");
161
javacCmd = javacCmdFile.getAbsolutePath();
162
163
File jarCmdFile = (isWindows)
164
? new File(binDir, "jar.exe")
165
: new File(binDir, "jar");
166
jarCmd = jarCmdFile.getAbsolutePath();
167
if (!jarCmdFile.canExecute()) {
168
throw new RuntimeException("java <" + TestHelper.jarCmd +
169
"> must exist and should be executable");
170
}
171
172
if (isWindows) {
173
File javawCmdFile = new File(binDir, "javaw.exe");
174
javawCmd = javawCmdFile.getAbsolutePath();
175
if (!javawCmdFile.canExecute()) {
176
throw new RuntimeException("java <" + javawCmd +
177
"> must exist and should be executable");
178
}
179
} else {
180
javawCmd = null;
181
}
182
183
if (!javacCmdFile.canExecute()) {
184
throw new RuntimeException("java <" + javacCmd +
185
"> must exist and should be executable");
186
}
187
188
haveClientVM = haveVmVariant("client");
189
haveServerVM = haveVmVariant("server");
190
}
191
private static boolean haveVmVariant(String type) {
192
if (isWindows) {
193
File vmDir = new File(JAVA_JRE_BIN, type);
194
File jvmFile = new File(vmDir, LIBJVM);
195
return jvmFile.exists();
196
} else {
197
File vmDir = new File(JAVA_JRE_LIB, type);
198
File vmArchDir = new File(vmDir, getJreArch());
199
File jvmFile = new File(vmArchDir, LIBJVM);
200
return jvmFile.exists();
201
}
202
}
203
void run(String[] args) throws Exception {
204
int passed = 0, failed = 0;
205
final Pattern p = (args != null && args.length > 0)
206
? Pattern.compile(args[0])
207
: null;
208
for (Method m : this.getClass().getDeclaredMethods()) {
209
boolean selected = (p == null)
210
? m.isAnnotationPresent(Test.class)
211
: p.matcher(m.getName()).matches();
212
if (selected) {
213
try {
214
m.invoke(this, (Object[]) null);
215
System.out.println(m.getName() + ": OK");
216
passed++;
217
System.out.printf("Passed: %d, Failed: %d, ExitValue: %d%n",
218
passed, failed, testExitValue);
219
} catch (Throwable ex) {
220
System.out.printf("Test %s failed: %s %n", m, ex);
221
System.out.println("----begin detailed exceptions----");
222
ex.printStackTrace(System.out);
223
for (Throwable t : ex.getSuppressed()) {
224
t.printStackTrace(System.out);
225
}
226
System.out.println("----end detailed exceptions----");
227
failed++;
228
}
229
}
230
}
231
System.out.printf("Total: Passed: %d, Failed %d%n", passed, failed);
232
if (failed > 0) {
233
throw new RuntimeException("Tests failed: " + failed);
234
}
235
if (passed == 0 && failed == 0) {
236
throw new AssertionError("No test(s) selected: passed = " +
237
passed + ", failed = " + failed + " ??????????");
238
}
239
}
240
241
/*
242
* usually the jre/lib/arch-name is the same as os.arch, except for x86.
243
*/
244
static String getJreArch() {
245
String arch = System.getProperty("os.arch");
246
return arch.equals("x86") ? "i386" : arch;
247
}
248
static String getArch() {
249
return System.getProperty("os.arch");
250
}
251
static File getClassFile(File javaFile) {
252
String s = javaFile.getAbsolutePath().replace(JAVA_FILE_EXT, CLASS_FILE_EXT);
253
return new File(s);
254
}
255
256
static File getJavaFile(File classFile) {
257
String s = classFile.getAbsolutePath().replace(CLASS_FILE_EXT, JAVA_FILE_EXT);
258
return new File(s);
259
}
260
261
static String baseName(File f) {
262
String s = f.getName();
263
return s.substring(0, s.indexOf("."));
264
}
265
266
/*
267
* A convenience method to create a jar with jar file name and defs
268
*/
269
static void createJar(File jarName, String... mainDefs)
270
throws FileNotFoundException{
271
createJar(null, jarName, new File("Foo"), mainDefs);
272
}
273
274
/*
275
* A convenience method to create a java file, compile and jar it up, using
276
* the sole class file name in the jar, as the Main-Class attribute value.
277
*/
278
static void createJar(File jarName, File mainClass, String... mainDefs)
279
throws FileNotFoundException {
280
createJar(null, jarName, mainClass, mainDefs);
281
}
282
283
/*
284
* A convenience method to compile java files.
285
*/
286
static void compile(String... compilerArgs) {
287
if (compiler.run(null, null, null, compilerArgs) != 0) {
288
String sarg = "";
289
for (String x : compilerArgs) {
290
sarg.concat(x + " ");
291
}
292
throw new Error("compilation failed: " + sarg);
293
}
294
}
295
296
/*
297
* A generic jar file creator to create a java file, compile it
298
* and jar it up, a specific Main-Class entry name in the
299
* manifest can be specified or a null to use the sole class file name
300
* as the Main-Class attribute value.
301
*/
302
static void createJar(String mEntry, File jarName, File mainClass,
303
String... mainDefs) throws FileNotFoundException {
304
if (jarName.exists()) {
305
jarName.delete();
306
}
307
try (PrintStream ps = new PrintStream(new FileOutputStream(mainClass + ".java"))) {
308
ps.println("public class Foo {");
309
if (mainDefs != null) {
310
for (String x : mainDefs) {
311
ps.println(x);
312
}
313
}
314
ps.println("}");
315
}
316
317
String compileArgs[] = {
318
mainClass + ".java"
319
};
320
if (compiler.run(null, null, null, compileArgs) != 0) {
321
throw new RuntimeException("compilation failed " + mainClass + ".java");
322
}
323
if (mEntry == null) {
324
mEntry = mainClass.getName();
325
}
326
String jarArgs[] = {
327
(debug) ? "cvfe" : "cfe",
328
jarName.getAbsolutePath(),
329
mEntry,
330
mainClass.getName() + ".class"
331
};
332
createJar(jarArgs);
333
}
334
335
static void createJar(String... args) {
336
sun.tools.jar.Main jarTool =
337
new sun.tools.jar.Main(System.out, System.err, "JarCreator");
338
if (!jarTool.run(args)) {
339
String message = "jar creation failed with command:";
340
for (String x : args) {
341
message = message.concat(" " + x);
342
}
343
throw new RuntimeException(message);
344
}
345
}
346
347
static void copyStream(InputStream in, OutputStream out) throws IOException {
348
byte[] buf = new byte[8192];
349
int n = in.read(buf);
350
while (n > 0) {
351
out.write(buf, 0, n);
352
n = in.read(buf);
353
}
354
}
355
356
static void copyFile(File src, File dst) throws IOException {
357
Path parent = dst.toPath().getParent();
358
if (parent != null) {
359
Files.createDirectories(parent);
360
}
361
Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
362
}
363
364
/**
365
* Attempt to create a file at the given location. If an IOException
366
* occurs then back off for a moment and try again. When a number of
367
* attempts fail, give up and throw an exception.
368
*/
369
void createAFile(File aFile, List<String> contents) throws IOException {
370
IOException cause = null;
371
for (int attempts = 0; attempts < 10; attempts++) {
372
try {
373
Files.write(aFile.getAbsoluteFile().toPath(), contents,
374
Charset.defaultCharset(), CREATE, TRUNCATE_EXISTING, WRITE);
375
if (cause != null) {
376
/*
377
* report attempts and errors that were encountered
378
* for diagnostic purposes
379
*/
380
System.err.println("Created batch file " +
381
aFile + " in " + (attempts + 1) +
382
" attempts");
383
System.err.println("Errors encountered: " + cause);
384
cause.printStackTrace();
385
}
386
return;
387
} catch (IOException ioe) {
388
if (cause != null) {
389
// chain the exceptions so they all get reported for diagnostics
390
cause.addSuppressed(ioe);
391
} else {
392
cause = ioe;
393
}
394
}
395
396
try {
397
Thread.sleep(500);
398
} catch (InterruptedException ie) {
399
if (cause != null) {
400
// cause should alway be non-null here
401
ie.addSuppressed(cause);
402
}
403
throw new RuntimeException("Interrupted while creating batch file", ie);
404
}
405
}
406
throw new RuntimeException("Unable to create batch file", cause);
407
}
408
409
static void createFile(File outFile, List<String> content) throws IOException {
410
Files.write(outFile.getAbsoluteFile().toPath(), content,
411
Charset.defaultCharset(), CREATE_NEW);
412
}
413
414
static void recursiveDelete(File target) throws IOException {
415
if (!target.exists()) {
416
return;
417
}
418
Files.walkFileTree(target.toPath(), new SimpleFileVisitor<Path>() {
419
@Override
420
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
421
try {
422
Files.deleteIfExists(dir);
423
} catch (IOException ex) {
424
System.out.println("Error: could not delete: " + dir.toString());
425
System.out.println(ex.getMessage());
426
return FileVisitResult.TERMINATE;
427
}
428
return FileVisitResult.CONTINUE;
429
}
430
@Override
431
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
432
try {
433
Files.deleteIfExists(file);
434
} catch (IOException ex) {
435
System.out.println("Error: could not delete: " + file.toString());
436
System.out.println(ex.getMessage());
437
return FileVisitResult.TERMINATE;
438
}
439
return FileVisitResult.CONTINUE;
440
}
441
});
442
}
443
444
static TestResult doExec(String...cmds) {
445
return doExec(null, null, cmds);
446
}
447
448
static TestResult doExec(Map<String, String> envToSet, String...cmds) {
449
return doExec(envToSet, null, cmds);
450
}
451
/*
452
* A method which executes a java cmd and returns the results in a container
453
*/
454
static TestResult doExec(Map<String, String> envToSet,
455
Set<String> envToRemove, String...cmds) {
456
String cmdStr = "";
457
for (String x : cmds) {
458
cmdStr = cmdStr.concat(x + " ");
459
}
460
ProcessBuilder pb = new ProcessBuilder(cmds);
461
Map<String, String> env = pb.environment();
462
if (envToRemove != null) {
463
for (String key : envToRemove) {
464
env.remove(key);
465
}
466
}
467
if (envToSet != null) {
468
env.putAll(envToSet);
469
}
470
BufferedReader rdr = null;
471
try {
472
List<String> outputList = new ArrayList<>();
473
pb.redirectErrorStream(true);
474
Process p = pb.start();
475
rdr = new BufferedReader(new InputStreamReader(p.getInputStream()));
476
String in = rdr.readLine();
477
while (in != null) {
478
outputList.add(in);
479
in = rdr.readLine();
480
}
481
p.waitFor();
482
p.destroy();
483
484
return new TestHelper.TestResult(cmdStr, p.exitValue(), outputList,
485
env, new Throwable("current stack of the test"));
486
} catch (Exception ex) {
487
ex.printStackTrace();
488
throw new RuntimeException(ex.getMessage());
489
}
490
}
491
492
static FileFilter createFilter(final String extension) {
493
return new FileFilter() {
494
@Override
495
public boolean accept(File pathname) {
496
String name = pathname.getName();
497
if (name.endsWith(extension)) {
498
return true;
499
}
500
return false;
501
}
502
};
503
}
504
505
static boolean isEnglishLocale() {
506
return Locale.getDefault().getLanguage().equals("en");
507
}
508
509
/*
510
* A class to encapsulate the test results and stuff, with some ease
511
* of use methods to check the test results.
512
*/
513
static class TestResult {
514
PrintWriter status;
515
StringWriter sw;
516
int exitValue;
517
List<String> testOutput;
518
Map<String, String> env;
519
Throwable t;
520
boolean testStatus;
521
522
public TestResult(String str, int rv, List<String> oList,
523
Map<String, String> env, Throwable t) {
524
sw = new StringWriter();
525
status = new PrintWriter(sw);
526
status.println("Executed command: " + str + "\n");
527
exitValue = rv;
528
testOutput = oList;
529
this.env = env;
530
this.t = t;
531
testStatus = true;
532
}
533
534
void appendError(String x) {
535
testStatus = false;
536
testExitValue++;
537
status.println(TEST_PREFIX + x);
538
}
539
540
void indentStatus(String x) {
541
status.println(" " + x);
542
}
543
544
void checkNegative() {
545
if (exitValue == 0) {
546
appendError("test must not return 0 exit value");
547
}
548
}
549
550
void checkPositive() {
551
if (exitValue != 0) {
552
appendError("test did not return 0 exit value");
553
}
554
}
555
556
boolean isOK() {
557
return exitValue == 0;
558
}
559
560
boolean isZeroOutput() {
561
if (!testOutput.isEmpty()) {
562
appendError("No message from cmd please");
563
return false;
564
}
565
return true;
566
}
567
568
boolean isNotZeroOutput() {
569
if (testOutput.isEmpty()) {
570
appendError("Missing message");
571
return false;
572
}
573
return true;
574
}
575
576
@Override
577
public String toString() {
578
status.println("++++Begin Test Info++++");
579
status.println("Test Status: " + (testStatus ? "PASS" : "FAIL"));
580
status.println("++++Test Environment++++");
581
for (String x : env.keySet()) {
582
indentStatus(x + "=" + env.get(x));
583
}
584
status.println("++++Test Output++++");
585
for (String x : testOutput) {
586
indentStatus(x);
587
}
588
status.println("++++Test Stack Trace++++");
589
status.println(t.toString());
590
for (StackTraceElement e : t.getStackTrace()) {
591
indentStatus(e.toString());
592
}
593
status.println("++++End of Test Info++++");
594
status.flush();
595
String out = sw.toString();
596
status.close();
597
return out;
598
}
599
600
boolean contains(String str) {
601
for (String x : testOutput) {
602
if (x.contains(str)) {
603
return true;
604
}
605
}
606
appendError("string <" + str + "> not found");
607
return false;
608
}
609
610
boolean notContains(String str) {
611
for (String x : testOutput) {
612
if (x.contains(str)) {
613
appendError("string <" + str + "> found");
614
return false;
615
}
616
}
617
return true;
618
}
619
620
boolean matches(String stringToMatch) {
621
for (String x : testOutput) {
622
if (x.matches(stringToMatch)) {
623
return true;
624
}
625
}
626
appendError("string <" + stringToMatch + "> not found");
627
return false;
628
}
629
630
boolean notMatches(String stringToMatch) {
631
for (String x : testOutput) {
632
if (!x.matches(stringToMatch)) {
633
return true;
634
}
635
}
636
appendError("string <" + stringToMatch + "> found");
637
return false;
638
}
639
}
640
/**
641
* Indicates that the annotated method is a test method.
642
*/
643
@Retention(RetentionPolicy.RUNTIME)
644
@Target(ElementType.METHOD)
645
public @interface Test {}
646
}
647
648