1 /*
  2  * Copyright (c) 2020, 2025, 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package jdk.internal.misc;
 27 
 28 import java.io.BufferedReader;
 29 import java.io.File;
 30 import java.io.InputStreamReader;
 31 import java.io.InputStream;
 32 import java.io.IOException;
 33 import java.io.PrintStream;
 34 import java.nio.file.Files;
 35 import java.nio.file.Path;
 36 import java.util.Arrays;
 37 import java.util.ArrayList;
 38 import java.util.HashMap;
 39 import java.util.List;
 40 import java.util.Map;
 41 import java.util.Objects;
 42 import java.util.jar.JarFile;
 43 import java.util.stream.Stream;
 44 
 45 import jdk.internal.access.SharedSecrets;
 46 import jdk.internal.util.StaticProperty;
 47 
 48 public class CDS {
 49     // Must be in sync with cdsConfig.hpp
 50     private static final int IS_DUMPING_ARCHIVE              = 1 << 0;
 51     private static final int IS_DUMPING_METHOD_HANDLES       = 1 << 1;
 52     private static final int IS_DUMPING_STATIC_ARCHIVE       = 1 << 2;
 53     private static final int IS_LOGGING_LAMBDA_FORM_INVOKERS = 1 << 3;
 54     private static final int IS_USING_ARCHIVE                = 1 << 4;
 55     private static final int configStatus = getCDSConfigStatus();
 56 
 57     /**
 58      * Should we log the use of lambda form invokers?
 59      */
 60     public static boolean isLoggingLambdaFormInvokers() {
 61         return (configStatus & IS_LOGGING_LAMBDA_FORM_INVOKERS) != 0;
 62     }
 63 
 64     /**
 65       * Is the VM writing to a (static or dynamic) CDS archive.
 66       */
 67     public static boolean isDumpingArchive() {
 68         return (configStatus & IS_DUMPING_ARCHIVE) != 0;
 69     }
 70 
 71     /**
 72       * Is the VM using at least one CDS archive?
 73       */
 74     public static boolean isUsingArchive() {
 75         return (configStatus & IS_USING_ARCHIVE) != 0;
 76     }
 77 
 78     /**
 79       * Is dumping static archive.
 80       */
 81     public static boolean isDumpingStaticArchive() {
 82         return (configStatus & IS_DUMPING_STATIC_ARCHIVE) != 0;
 83     }
 84 
 85     public static boolean isSingleThreadVM() {
 86         return isDumpingStaticArchive();
 87     }
 88 
 89     private static native int getCDSConfigStatus();
 90     private static native void logLambdaFormInvoker(String line);
 91 
 92 
 93     // Used only when dumping static archive to keep weak references alive to
 94     // ensure that Soft/Weak Reference objects can be reliably archived.
 95     private static ArrayList<Object> keepAliveList;
 96 
 97     public static void keepAlive(Object s) {
 98         assert isSingleThreadVM(); // no need for synchronization
 99         assert isDumpingStaticArchive();
100         if (keepAliveList == null) {
101             keepAliveList = new ArrayList<>();
102         }
103         keepAliveList.add(s);
104     }
105 
106     // This is called by native JVM code at the very end of Java execution before
107     // dumping the static archive.
108     // It collects the objects from keepAliveList so that they can be easily processed
109     // by the native JVM code to check that any Reference objects that need special
110     // clean up must have been registed with keepAlive()
111     private static Object[] getKeepAliveObjects() {
112         return keepAliveList.toArray();
113     }
114 
115     /**
116      * Initialize archived static fields in the given Class using archived
117      * values from CDS dump time. Also initialize the classes of objects in
118      * the archived graph referenced by those fields.
119      *
120      * Those static fields remain as uninitialized if there is no mapped CDS
121      * java heap data or there is any error during initialization of the
122      * object class in the archived graph.
123      */
124     public static native void initializeFromArchive(Class<?> c);
125 
126     /**
127      * Ensure that the native representation of all archived java.lang.Module objects
128      * are properly restored.
129      */
130     public static native void defineArchivedModules(ClassLoader platformLoader, ClassLoader systemLoader);
131 
132     /**
133      * Returns a predictable "random" seed derived from the VM's build ID and version,
134      * to be used by java.util.ImmutableCollections to ensure that archived
135      * ImmutableCollections are always sorted the same order for the same VM build.
136      */
137     public static native long getRandomSeedForDumping();
138 
139     /**
140      * log lambda form invoker holder, name and method type
141      */
142     public static void logLambdaFormInvoker(String prefix, String holder, String name, String type) {
143         if (isLoggingLambdaFormInvokers()) {
144             logLambdaFormInvoker(prefix + " " + holder + " " + name + " " + type);
145         }
146     }
147 
148     /**
149       * log species
150       */
151     public static void logSpeciesType(String prefix, String cn) {
152         if (isLoggingLambdaFormInvokers()) {
153             logLambdaFormInvoker(prefix + " " + cn);
154         }
155     }
156 
157     static final String DIRECT_HOLDER_CLASS_NAME  = "java.lang.invoke.DirectMethodHandle$Holder";
158     static final String DELEGATING_HOLDER_CLASS_NAME = "java.lang.invoke.DelegatingMethodHandle$Holder";
159     static final String BASIC_FORMS_HOLDER_CLASS_NAME = "java.lang.invoke.LambdaForm$Holder";
160     static final String INVOKERS_HOLDER_CLASS_NAME = "java.lang.invoke.Invokers$Holder";
161 
162     private static boolean isValidHolderName(String name) {
163         return name.equals(DIRECT_HOLDER_CLASS_NAME)      ||
164                name.equals(DELEGATING_HOLDER_CLASS_NAME)  ||
165                name.equals(BASIC_FORMS_HOLDER_CLASS_NAME) ||
166                name.equals(INVOKERS_HOLDER_CLASS_NAME);
167     }
168 
169     private static boolean isBasicTypeChar(char c) {
170          return "LIJFDV".indexOf(c) >= 0;
171     }
172 
173     private static boolean isValidMethodType(String type) {
174         String[] typeParts = type.split("_");
175         // check return type (second part)
176         if (typeParts.length != 2 || typeParts[1].length() != 1
177                 || !isBasicTypeChar(typeParts[1].charAt(0))) {
178             return false;
179         }
180         // first part
181         if (!isBasicTypeChar(typeParts[0].charAt(0))) {
182             return false;
183         }
184         for (int i = 1; i < typeParts[0].length(); i++) {
185             char c = typeParts[0].charAt(i);
186             if (!isBasicTypeChar(c)) {
187                 if (!(c >= '0' && c <= '9')) {
188                     return false;
189                 }
190             }
191         }
192         return true;
193     }
194 
195     // Throw exception on invalid input
196     private static void validateInputLines(String[] lines) {
197         for (String s: lines) {
198             if (!s.startsWith("[LF_RESOLVE]") && !s.startsWith("[SPECIES_RESOLVE]")) {
199                 throw new IllegalArgumentException("Wrong prefix: " + s);
200             }
201 
202             String[] parts = s.split(" ");
203             boolean isLF = s.startsWith("[LF_RESOLVE]");
204 
205             if (isLF) {
206                 if (parts.length != 4) {
207                     throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
208                 }
209                 if (!isValidHolderName(parts[1])) {
210                     throw new IllegalArgumentException("Invalid holder class name: " + parts[1]);
211                 }
212                 if (!isValidMethodType(parts[3])) {
213                     throw new IllegalArgumentException("Invalid method type: " + parts[3]);
214                 }
215             } else {
216                 if (parts.length != 2) {
217                    throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
218                 }
219            }
220       }
221     }
222 
223     /**
224      * called from vm to generate MethodHandle holder classes
225      * @return {@code Object[]} if holder classes can be generated.
226      * @param lines in format of LF_RESOLVE or SPECIES_RESOLVE output
227      */
228     private static Object[] generateLambdaFormHolderClasses(String[] lines) {
229         Objects.requireNonNull(lines);
230         validateInputLines(lines);
231         Stream<String> lineStream = Arrays.stream(lines);
232         Map<String, byte[]> result = SharedSecrets.getJavaLangInvokeAccess().generateHolderClasses(lineStream);
233         int size = result.size();
234         Object[] retArray = new Object[size * 2];
235         int index = 0;
236         for (Map.Entry<String, byte[]> entry : result.entrySet()) {
237             retArray[index++] = entry.getKey();
238             retArray[index++] = entry.getValue();
239         };
240         return retArray;
241     }
242 
243     private static native void dumpClassList(String listFileName);
244     private static native void dumpDynamicArchive(String archiveFileName);
245 
246     private static String drainOutput(InputStream stream, long pid, String tail, List<String> cmds) {
247         String fileName  = "java_pid" + pid + "_" + tail;
248         new Thread( ()-> {
249             try (InputStreamReader isr = new InputStreamReader(stream);
250                  BufferedReader rdr = new BufferedReader(isr);
251                  PrintStream prt = new PrintStream(fileName)) {
252                 prt.println("Command:");
253                 for (String s : cmds) {
254                     prt.print(s + " ");
255                 }
256                 prt.println("");
257                 String line;
258                 while((line = rdr.readLine()) != null) {
259                     prt.println(line);
260                 }
261             } catch (IOException e) {
262                 throw new RuntimeException("IOException happens during drain stream to file " +
263                                            fileName + ": " + e.getMessage());
264             }}).start();
265         return fileName;
266     }
267 
268     private static String[] excludeFlags = {
269          "-XX:DumpLoadedClassList=",
270          "-XX:+RecordDynamicDumpInfo",
271          "-Xshare:",
272          "-XX:SharedClassListFile=",
273          "-XX:SharedArchiveFile=",
274          "-XX:ArchiveClassesAtExit="};
275     private static boolean containsExcludedFlags(String testStr) {
276        for (String e : excludeFlags) {
277            if (testStr.contains(e)) {
278                return true;
279            }
280        }
281        return false;
282     }
283 
284     /**
285     * called from jcmd VM.cds to dump static or dynamic shared archive
286     * @param isStatic true for dump static archive or false for dynnamic archive.
287     * @param fileName user input archive name, can be null.
288     * @return The archive name if successfully dumped.
289     */
290     private static String dumpSharedArchive(boolean isStatic, String fileName) throws Exception {
291         String cwd = new File("").getAbsolutePath(); // current dir used for printing message.
292         String currentPid = String.valueOf(ProcessHandle.current().pid());
293         String archiveFileName =  fileName != null ? fileName :
294             "java_pid" + currentPid + (isStatic ? "_static.jsa" : "_dynamic.jsa");
295 
296         String tempArchiveFileName = archiveFileName + ".temp";
297         File tempArchiveFile = new File(tempArchiveFileName);
298         // The operation below may cause exception if the file or its dir is protected.
299         if (!tempArchiveFile.exists()) {
300             tempArchiveFile.createNewFile();
301         }
302         tempArchiveFile.delete();
303 
304         if (isStatic) {
305             String listFileName = archiveFileName + ".classlist";
306             File listFile = new File(listFileName);
307             if (listFile.exists()) {
308                 listFile.delete();
309             }
310             dumpClassList(listFileName);
311             String jdkHome = StaticProperty.javaHome();
312             String classPath = System.getProperty("java.class.path");
313             List<String> cmds = new ArrayList<String>();
314             cmds.add(jdkHome + File.separator + "bin" + File.separator + "java"); // java
315             cmds.add("-cp");
316             cmds.add(classPath);
317             cmds.add("-Xlog:cds");
318             cmds.add("-Xshare:dump");
319             cmds.add("-XX:SharedClassListFile=" + listFileName);
320             cmds.add("-XX:SharedArchiveFile=" + tempArchiveFileName);
321 
322             // All runtime args.
323             String[] vmArgs = VM.getRuntimeArguments();
324             if (vmArgs != null) {
325                 for (String arg : vmArgs) {
326                     if (arg != null && !containsExcludedFlags(arg)) {
327                         cmds.add(arg);
328                     }
329                 }
330             }
331 
332             Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[0]));
333 
334             // Drain stdout/stderr to files in new threads.
335             String stdOutFileName = drainOutput(proc.getInputStream(), proc.pid(), "stdout", cmds);
336             String stdErrFileName = drainOutput(proc.getErrorStream(), proc.pid(), "stderr", cmds);
337 
338             proc.waitFor();
339             // done, delete classlist file.
340             listFile.delete();
341 
342             // Check if archive has been successfully dumped. We won't reach here if exception happens.
343             // Throw exception if file is not created.
344             if (!tempArchiveFile.exists()) {
345                 throw new RuntimeException("Archive file " + tempArchiveFileName +
346                                            " is not created, please check stdout file " +
347                                             cwd + File.separator + stdOutFileName + " or stderr file " +
348                                             cwd + File.separator + stdErrFileName + " for more detail");
349             }
350         } else {
351             dumpDynamicArchive(tempArchiveFileName);
352             if (!tempArchiveFile.exists()) {
353                 throw new RuntimeException("Archive file " + tempArchiveFileName +
354                                            " is not created, please check current working directory " +
355                                            cwd  + " for process " +
356                                            currentPid + " output for more detail");
357             }
358         }
359         // Override the existing archive file
360         File archiveFile = new File(archiveFileName);
361         if (archiveFile.exists()) {
362             archiveFile.delete();
363         }
364         if (!tempArchiveFile.renameTo(archiveFile)) {
365             throw new RuntimeException("Cannot rename temp file " + tempArchiveFileName + " to archive file" + archiveFileName);
366         }
367         // Everything goes well, print out the file name.
368         String archiveFilePath = new File(archiveFileName).getAbsolutePath();
369         System.out.println("The process was attached by jcmd and dumped a " + (isStatic ? "static" : "dynamic") + " archive " + archiveFilePath);
370         return archiveFilePath;
371     }
372 
373     /**
374      * Detects if we need to emit explicit class initialization checks in
375      * AOT-cached MethodHandles and VarHandles before accessing static fields
376      * and methods.
377      * @see jdk.internal.misc.Unsafe::shouldBeInitialized
378      *
379      * @return false only if a call to {@code ensureClassInitialized} would have
380      * no effect during the application's production run.
381      */
382     public static boolean needsClassInitBarrier(Class<?> c) {
383         if (c == null) {
384             throw new NullPointerException();
385         }
386 
387         if ((configStatus & IS_DUMPING_METHOD_HANDLES) == 0) {
388             return false;
389         } else {
390             return needsClassInitBarrier0(c);
391         }
392     }
393 
394     private static native boolean needsClassInitBarrier0(Class<?> c);
395 
396     /**
397      * This class is used only by native JVM code at CDS dump time for loading
398      * "unregistered classes", which are archived classes that are intended to
399      * be loaded by custom class loaders during runtime.
400      * See src/hotspot/share/cds/unregisteredClasses.cpp.
401      */
402     private static class UnregisteredClassLoader extends ClassLoader {
403         static {
404             registerAsParallelCapable();
405         }
406 
407         static interface Source {
408             public byte[] readClassFile(String className) throws IOException;
409         }
410 
411         static class JarSource implements Source {
412             private final JarFile jar;
413 
414             JarSource(File file) throws IOException {
415                 jar = new JarFile(file);
416             }
417 
418             @Override
419             public byte[] readClassFile(String className) throws IOException {
420                 final var entryName = className.replace('.', '/').concat(".class");
421                 final var entry = jar.getEntry(entryName);
422                 if (entry == null) {
423                     throw new IOException("No such entry: " + entryName + " in " + jar.getName());
424                 }
425                 try (final var in = jar.getInputStream(entry)) {
426                     return in.readAllBytes();
427                 }
428             }
429         }
430 
431         static class DirSource implements Source {
432             private final String basePath;
433 
434             DirSource(File dir) {
435                 assert dir.isDirectory();
436                 basePath = dir.toString();
437             }
438 
439             @Override
440             public byte[] readClassFile(String className) throws IOException {
441                 final var subPath = className.replace('.', File.separatorChar).concat(".class");
442                 final var fullPath = Path.of(basePath, subPath);
443                 return Files.readAllBytes(fullPath);
444             }
445         }
446 
447         private final HashMap<String, Source> sources = new HashMap<>();
448 
449         private Source resolveSource(String path) throws IOException {
450             Source source = sources.get(path);
451             if (source != null) {
452                 return source;
453             }
454 
455             final var file = new File(path);
456             if (!file.exists()) {
457                 throw new IOException("No such file: " + path);
458             }
459             if (file.isFile()) {
460                 source = new JarSource(file);
461             } else if (file.isDirectory()) {
462                 source = new DirSource(file);
463             } else {
464                 throw new IOException("Not a normal file: " + path);
465             }
466             sources.put(path, source);
467 
468             return source;
469         }
470 
471         /**
472          * Load the class of the given <code>name</code> from the given <code>source</code>.
473          * <p>
474          * All super classes and interfaces of the named class must have already been loaded:
475          * either defined by this class loader (unregistered ones) or loaded, possibly indirectly,
476          * by the system class loader (registered ones).
477          * <p>
478          * If the named class has a registered super class or interface named N there should be no
479          * unregistered class or interface named N loaded yet.
480          *
481          * @param name the name of the class to be loaded.
482          * @param source path to a directory or a JAR file from which the named class should be
483          *               loaded.
484          */
485         private Class<?> load(String name, String source) throws IOException {
486             final Source resolvedSource = resolveSource(source);
487             final byte[] bytes = resolvedSource.readClassFile(name);
488             // 'defineClass()' may cause loading of supertypes of this unregistered class by VM
489             // calling 'this.loadClass()'.
490             //
491             // For any supertype S named SN specified in the classlist the following is ensured by
492             // the CDS implementation:
493             // - if S is an unregistered class it must have already been defined by this class
494             //   loader and thus will be found by 'this.findLoadedClass(SN)',
495             // - if S is not an unregistered class there should be no unregistered class named SN
496             //   loaded yet so either S has previously been (indirectly) loaded by this class loader
497             //   and thus it will be found when calling 'this.findLoadedClass(SN)' or it will be
498             //   found when delegating to the system class loader, which must have already loaded S,
499             //   by calling 'this.getParent().loadClass(SN, false)'.
500             // See the implementation of 'ClassLoader.loadClass()' for details.
501             //
502             // Therefore, we should resolve all supertypes to the expected ones as specified by the
503             // "super:" and "interfaces:" attributes in the classlist. This invariant is validated
504             // by the C++ function 'ClassListParser::load_class_from_source()'.
505             assert getParent() == getSystemClassLoader();
506             return defineClass(name, bytes, 0, bytes.length);
507         }
508     }
509 
510     /**
511      * This class is used only by native JVM code to spawn a child JVM process to assemble
512      * the AOT cache. <code>args[]</code> are passed in the <code>JAVA_TOOL_OPTIONS</code>
513      * environment variable.
514      */
515     private static class ProcessLauncher {
516         static int execWithJavaToolOptions(String javaLauncher, String args[]) throws IOException, InterruptedException {
517             ProcessBuilder pb = new ProcessBuilder().inheritIO().command(javaLauncher);
518             StringBuilder sb = new StringBuilder();
519 
520             // Encode the args as described in
521             // https://docs.oracle.com/en/java/javase/24/docs/specs/jvmti.html#tooloptions
522             String prefix = "";
523             for (String arg : args) {
524                 sb.append(prefix);
525 
526                 for (int i = 0; i < arg.length(); i++) {
527                     char c = arg.charAt(i);
528                     if (c == '"' || Character.isWhitespace(c)) {
529                         sb.append('\'');
530                         sb.append(c);
531                         sb.append('\'');
532                     } else if (c == '\'') {
533                         sb.append('"');
534                         sb.append(c);
535                         sb.append('"');
536                     } else {
537                         sb.append(c);
538                     }
539                 }
540 
541                 prefix = " ";
542             }
543 
544             Map<String, String> env = pb.environment();
545             env.put("JAVA_TOOL_OPTIONS", sb.toString());
546             env.remove("_JAVA_OPTIONS");
547             env.remove("CLASSPATH");
548             Process process = pb.start();
549             return process.waitFor();
550         }
551     }
552 }