jdk

Форк
0
/
ExecDriver.java 
212 строк · 8.2 Кб
1
/*
2
 * Copyright (c) 2017, 2020, 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.File;
25
import java.io.IOException;
26
import java.io.InputStream;
27
import java.io.OutputStream;
28
import java.nio.file.Path;
29
import java.nio.file.Paths;
30
import java.util.ArrayList;
31
import java.util.Arrays;
32
import java.util.Collections;
33
import java.util.List;
34

35
/**
36
 * Starts a new process to execute a command.
37
 * <p>Usage: --java|--cmd|--launcher <arg>+
38
 * <p>If {@code --cmd} flag is specified, the arguments are treated as
39
 * a program to run and its arguments. Non-zero exit code of the created process
40
 * will be reported as an {@link AssertionError}.
41
 * <p>If {@code --java} flag is specified, the arguments are passed to {@code java}
42
 * from JDK under test. If exit code doesn't equal to 0 or 95, {@link AssertionError}
43
 * will be thrown.
44
 * <p>If {@code --launcher} flag is specified, the arguments treated similar as
45
 * for {@code --cmd}, but the started process will have the directory which
46
 * contains {@code jvm.so} in dynamic library path, and {@code test.class.path}
47
 * as CLASSPATH environment variable. Exit codes are checked as in
48
 * {@code --java}, i.e. 0 or 95 means pass.
49
 */
50
public class ExecDriver {
51
    // copied from jdk.test.lib.Utils.TEST_CLASS_PATH
52
    private static final String TEST_CLASS_PATH = System.getProperty("test.class.path", ".");
53
    // copied from jdk.test.lib.Utils.TEST_CLASS_PATH
54
    private static final String TEST_JDK = System.getProperty("test.jdk");
55
    public static void main(String[] args) throws IOException, InterruptedException {
56
        boolean java = false;
57
        boolean launcher = false;
58

59
        String type = args[0];
60
        switch (type) {
61
            case "--java":
62
                String[] oldArgs = args;
63
                int count;
64
                String libraryPath = System.getProperty("test.nativepath");
65
                if (libraryPath != null && !libraryPath.isEmpty()) {
66
                    count = 4;
67
                    args = new String[args.length + 3];
68
                    args[3] = "-Djava.library.path=" + libraryPath;
69
                } else {
70
                    count = 3;
71
                    args = new String[args.length + 2];
72
                }
73
                args[0] = javaBin();
74
                args[1] = "-cp";
75
                args[2] = TEST_CLASS_PATH;
76
                System.arraycopy(oldArgs, 1, args, count, oldArgs.length - 1);
77
                java = true;
78
                break;
79
            case "--launcher":
80
                java = true;
81
                launcher = true;
82
            case "--cmd":
83
                args = Arrays.copyOfRange(args, 1, args.length);
84
                break;
85
            default:
86
                throw new Error("unknown type: " + type);
87
        }
88
        // adding 'test.vm.opts' and 'test.java.opts'
89
        if (java) {
90
            String[] oldArgs = args;
91
            String[] testJavaOpts = getTestJavaOpts();
92
            if (testJavaOpts.length > 0) {
93
                args = new String[args.length + testJavaOpts.length];
94
                // bin/java goes before options
95
                args[0] = oldArgs[0];
96
                // then external java options
97
                System.arraycopy(testJavaOpts, 0, args, 1, testJavaOpts.length);
98
                // and then options and args from a test
99
                System.arraycopy(oldArgs, 1, args, 1 + testJavaOpts.length, oldArgs.length - 1);
100
            }
101
        }
102
        String command = Arrays.toString(args);
103
        System.out.println("exec " + command);
104

105
        ProcessBuilder pb = new ProcessBuilder(args);
106
        // adding jvm.so to library path
107
        if (launcher) {
108
            Path dir = Paths.get(TEST_JDK);
109
            String value;
110
            String name = sharedLibraryPathVariableName();
111
            // if (jdk.test.lib.Platform.isWindows()) {
112
            if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
113
                value = dir.resolve("bin")
114
                           .resolve(variant())
115
                           .toAbsolutePath()
116
                           .toString();
117
                value += File.pathSeparator;
118
                value += dir.resolve("bin")
119
                            .toAbsolutePath()
120
                            .toString();
121
            } else {
122
                value = dir.resolve("lib")
123
                           .resolve(variant())
124
                           .toAbsolutePath()
125
                           .toString();
126
            }
127

128
            System.out.println("  with " + name + " = " +
129
                    pb.environment()
130
                      .merge(name, value, (x, y) -> y + File.pathSeparator + x));
131
            System.out.println("  with CLASSPATH = " +
132
                    pb.environment()
133
                      .put("CLASSPATH", TEST_CLASS_PATH));
134
        }
135
        Process p = pb.start();
136
        // inheritIO does not work as expected for @run driver
137
        new Thread(() -> copy(p.getInputStream(), System.out)).start();
138
        new Thread(() -> copy(p.getErrorStream(), System.out)).start();
139
        int exitCode = p.waitFor();
140

141
        if (exitCode != 0 && (!java || exitCode != 95)) {
142
            throw new AssertionError(command + " exit code is " + exitCode);
143
        }
144
    }
145

146
    // copied from jdk.test.lib.Platform::sharedLibraryPathVariableName
147
    private static String sharedLibraryPathVariableName() {
148
        String osName = System.getProperty("os.name").toLowerCase();
149
        if (osName.startsWith("win")) {
150
            return "PATH";
151
        } else if (osName.startsWith("mac")) {
152
            return "DYLD_LIBRARY_PATH";
153
        } else if (osName.startsWith("aix")) {
154
            return "LIBPATH";
155
        } else {
156
            return "LD_LIBRARY_PATH";
157
        }
158
    }
159

160
    // copied from jdk.test.lib.Utils::getTestJavaOpts()
161
    private static String[] getTestJavaOpts() {
162
        List<String> opts = new ArrayList<String>();
163
        {
164
            String v = System.getProperty("test.vm.opts", "").trim();
165
            if (!v.isEmpty()) {
166
                Collections.addAll(opts, v.split("\\s+"));
167
            }
168
        }
169
        {
170
            String v = System.getProperty("test.java.opts", "").trim();
171
            if (!v.isEmpty()) {
172
                Collections.addAll(opts, v.split("\\s+"));
173
            }
174
        }
175
        return opts.toArray(new String[0]);
176
    }
177

178
    // copied jdk.test.lib.Platform::variant
179
    private static String variant() {
180
        String vmName = System.getProperty("java.vm.name");
181
        if (vmName.endsWith(" Server VM")) {
182
            return "server";
183
        } else if (vmName.endsWith(" Client VM")) {
184
            return "client";
185
        } else if (vmName.endsWith(" Minimal VM")) {
186
            return "minimal";
187
        } else {
188
            throw new Error("TESTBUG: unsuppported vm variant");
189
        }
190
    }
191

192
    private static void copy(InputStream is, OutputStream os) {
193
        byte[] buffer = new byte[1024];
194
        int n;
195
        try (InputStream close = is) {
196
            while ((n = is.read(buffer)) != -1) {
197
                os.write(buffer, 0, n);
198
            }
199
            os.flush();
200
        } catch (IOException e) {
201
            e.printStackTrace();
202
        }
203
    }
204

205
    private static String javaBin() {
206
        return Paths.get(TEST_JDK)
207
                    .resolve("bin")
208
                    .resolve("java")
209
                    .toAbsolutePath()
210
                    .toString();
211
    }
212
}
213

214

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.