xref: /aosp_15_r20/external/bazelbuild-rules_java/toolchains/DumpPlatformClassPath.java (revision abe8e1b943c923005d847f1e3cf6637de4ed1a1f)
1 // Copyright 2017 The Bazel Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 import java.io.BufferedOutputStream;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStream;
20 import java.io.UncheckedIOException;
21 import java.lang.reflect.Method;
22 import java.net.URI;
23 import java.nio.file.DirectoryStream;
24 import java.nio.file.FileSystem;
25 import java.nio.file.FileSystems;
26 import java.nio.file.FileVisitResult;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.nio.file.SimpleFileVisitor;
31 import java.nio.file.attribute.BasicFileAttributes;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collection;
35 import java.util.GregorianCalendar;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.SortedMap;
39 import java.util.TreeMap;
40 import java.util.jar.JarEntry;
41 import java.util.jar.JarFile;
42 import java.util.jar.JarOutputStream;
43 import java.util.zip.CRC32;
44 import java.util.zip.ZipEntry;
45 
46 /**
47  * Output a jar file containing all classes on the platform classpath of the given JDK release.
48  *
49  * <p>usage: {@code DumpPlatformClassPath <output jar> <path to target JDK>}
50  */
51 public class DumpPlatformClassPath {
52 
main(String[] args)53   public static void main(String[] args) throws Exception {
54     if (args.length != 2) {
55       System.err.println("usage: DumpPlatformClassPath <output jar> <path to target JDK>");
56       System.exit(1);
57     }
58     Path output = Paths.get(args[0]);
59     Path targetJavabase = Paths.get(args[1]);
60 
61     int hostMajorVersion = hostMajorVersion();
62     boolean ok;
63     if (hostMajorVersion == 8) {
64       ok = dumpJDK8BootClassPath(output, targetJavabase);
65     } else {
66       ok = dumpJDK9AndNewerBootClassPath(hostMajorVersion, output, targetJavabase);
67     }
68     System.exit(ok ? 0 : 1);
69   }
70 
71   // JDK 8 bootclasspath handling.
72   // * JDK 8 represents a bootclasspath as a search path of jars (rt.jar, etc.).
73   // * It does not support --release or --system.
dumpJDK8BootClassPath(Path output, Path targetJavabase)74   static boolean dumpJDK8BootClassPath(Path output, Path targetJavabase) throws IOException {
75     List<Path> bootClassPathJars = getBootClassPathJars(targetJavabase);
76     writeClassPathJars(output, bootClassPathJars);
77     return true;
78   }
79 
80   // JDK > 8 --host_javabase bootclasspath handling.
81   // (The default --host_javabase is currently JDK 9.)
dumpJDK9AndNewerBootClassPath( int hostMajorVersion, Path output, Path targetJavabase)82   static boolean dumpJDK9AndNewerBootClassPath(
83       int hostMajorVersion, Path output, Path targetJavabase) throws IOException {
84 
85     // JDK 9 and newer support cross-compiling to older platform versions using the --system
86     // and --release flags.
87     // * --system takes the path to a JDK root for JDK 9 and up, and causes the compilation
88     //     to target the APIs from that JDK.
89     // * --release takes a language level (e.g. '9') and uses the API information baked in to
90     //     the host JDK (in lib/ct.sym).
91 
92     // Since --system only supports JDK >= 9, first check if the target JDK defines a JDK 8
93     // bootclasspath.
94     List<Path> bootClassPathJars = getBootClassPathJars(targetJavabase);
95     if (!bootClassPathJars.isEmpty()) {
96       writeClassPathJars(output, bootClassPathJars);
97       return true;
98     }
99 
100     // Read the bootclasspath data using the JRT filesystem
101     Map<String, byte[]> entries = new TreeMap<>();
102     Map<String, String> env = new TreeMap<>();
103     env.put("java.home", String.valueOf(targetJavabase));
104     try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), env)) {
105       Path modules = fileSystem.getPath("/modules");
106       try (DirectoryStream<Path> ms = Files.newDirectoryStream(modules)) {
107         for (Path m : ms) {
108           Files.walkFileTree(
109               m,
110               new SimpleFileVisitor<Path>() {
111                 @Override
112                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
113                     throws IOException {
114                   if (file.getFileName().toString().endsWith(".class")) {
115                     entries.put(m.relativize(file).toString(), Files.readAllBytes(file));
116                   }
117                   return super.visitFile(file, attrs);
118                 }
119               });
120         }
121       }
122       writeEntries(output, entries);
123     }
124     return true;
125   }
126 
127   /** Writes the given entry names and data to a jar archive at the given path. */
writeEntries(Path output, Map<String, byte[]> entries)128   private static void writeEntries(Path output, Map<String, byte[]> entries) throws IOException {
129     if (!entries.containsKey("java/lang/Object.class")) {
130       throw new AssertionError(
131           "\nCould not find java.lang.Object on bootclasspath; something has gone terribly wrong.\n"
132               + "Please file a bug: https://github.com/bazelbuild/bazel/issues");
133     }
134     try (OutputStream os = Files.newOutputStream(output);
135         BufferedOutputStream bos = new BufferedOutputStream(os, 65536);
136         JarOutputStream jos = new JarOutputStream(bos)) {
137       entries.entrySet().stream()
138           .forEachOrdered(
139               entry -> {
140                 try {
141                   addEntry(jos, entry.getKey(), entry.getValue());
142                 } catch (IOException e) {
143                   throw new UncheckedIOException(e);
144                 }
145               });
146     }
147   }
148 
149   /** Collects the entries of the given jar files into a map from jar entry names to their data. */
writeClassPathJars(Path output, Collection<Path> paths)150   private static void writeClassPathJars(Path output, Collection<Path> paths) throws IOException {
151     List<JarFile> jars = new ArrayList<>();
152     for (Path path : paths) {
153       jars.add(new JarFile(path.toFile()));
154     }
155     SortedMap<String, byte[]> entries = new TreeMap<>();
156     for (JarFile jar : jars) {
157       jar.stream()
158           .filter(p -> p.getName().endsWith(".class"))
159           .forEachOrdered(
160               entry -> {
161                 try {
162                   entries.put(entry.getName(), toByteArray(jar.getInputStream(entry)));
163                 } catch (IOException e) {
164                   throw new UncheckedIOException(e);
165                 }
166               });
167     }
168     writeEntries(output, entries);
169     for (JarFile jar : jars) {
170       jar.close();
171     }
172   }
173 
174   /** Returns paths to the entries of a JDK 8-style bootclasspath. */
getBootClassPathJars(Path javaHome)175   private static List<Path> getBootClassPathJars(Path javaHome) throws IOException {
176     List<Path> jars = new ArrayList<>();
177     Path extDir = javaHome.resolve("jre/lib/ext");
178     if (Files.exists(extDir)) {
179       for (Path extJar : Files.newDirectoryStream(extDir, "*.jar")) {
180         jars.add(extJar);
181       }
182     }
183     for (String jar :
184         Arrays.asList("rt.jar", "resources.jar", "jsse.jar", "jce.jar", "charsets.jar")) {
185       Path path = javaHome.resolve("jre/lib").resolve(jar);
186       if (Files.exists(path)) {
187         jars.add(path);
188       }
189     }
190     Path toolsJar = javaHome.resolve("lib/tools.jar");
191     if (Files.exists(toolsJar)) {
192       jars.add(toolsJar);
193     }
194     return jars;
195   }
196 
197   // Use a fixed timestamp for deterministic jar output.
198   private static final long FIXED_TIMESTAMP =
199       new GregorianCalendar(2010, 0, 1, 0, 0, 0).getTimeInMillis();
200 
201   /**
202    * Add a jar entry to the given {@link JarOutputStream}, normalizing the entry timestamps to
203    * ensure deterministic build output.
204    */
addEntry(JarOutputStream jos, String name, byte[] bytes)205   private static void addEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
206     JarEntry je = new JarEntry(name);
207     je.setTime(FIXED_TIMESTAMP);
208     je.setMethod(ZipEntry.STORED);
209     // When targeting JDK >= 10, patch the major version so it will be accepted by javac 9
210     // TODO(cushon): remove this after updating javac
211     if (bytes[7] > 53) {
212       bytes[7] = 53;
213     }
214     je.setSize(bytes.length);
215     CRC32 crc = new CRC32();
216     crc.update(bytes);
217     je.setCrc(crc.getValue());
218     jos.putNextEntry(je);
219     jos.write(bytes);
220   }
221 
toByteArray(InputStream is)222   private static byte[] toByteArray(InputStream is) throws IOException {
223     byte[] buffer = new byte[8192];
224     ByteArrayOutputStream boas = new ByteArrayOutputStream();
225     while (true) {
226       int r = is.read(buffer);
227       if (r == -1) {
228         break;
229       }
230       boas.write(buffer, 0, r);
231     }
232     return boas.toByteArray();
233   }
234 
235   /**
236    * Returns the major version of the host Java runtime (e.g. '8' for JDK 8), using {@link
237    * Runtime#version} if it is available, and otherwise falling back to the {@code
238    * java.class.version} system. property.
239    */
hostMajorVersion()240   static int hostMajorVersion() {
241     try {
242       Method versionMethod = Runtime.class.getMethod("version");
243       Object version = versionMethod.invoke(null);
244       return (int) version.getClass().getMethod("major").invoke(version);
245     } catch (ReflectiveOperationException e) {
246       // Runtime.version() isn't available on JDK 8; continue below
247     }
248     int version = (int) Double.parseDouble(System.getProperty("java.class.version"));
249     if (49 <= version && version <= 52) {
250       return version - (49 - 5);
251     }
252     throw new IllegalStateException(
253         "Unknown Java version: " + System.getProperty("java.specification.version"));
254   }
255 }