1 /*
  2  * Copyright (c) 2020, 2024, 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.util.Arrays;
 35 import java.util.ArrayList;
 36 import java.util.List;
 37 import java.util.Map;
 38 import java.util.Objects;
 39 import java.util.stream.Stream;
 40 
 41 import jdk.internal.access.SharedSecrets;
 42 
 43 public class CDS {
 44     // Must be in sync with cdsConfig.hpp
 45     private static final int IS_DUMPING_ARCHIVE              = 1 << 0;
 46     private static final int IS_DUMPING_STATIC_ARCHIVE       = 1 << 1;
 47     private static final int IS_LOGGING_LAMBDA_FORM_INVOKERS = 1 << 2;
 48     private static final int IS_USING_ARCHIVE                = 1 << 3;
 49     private static final int configStatus = getCDSConfigStatus();
 50 
 51     /**
 52      * Should we log the use of lambda form invokers?
 53      */
 54     public static boolean isLoggingLambdaFormInvokers() {
 55         return (configStatus & IS_LOGGING_LAMBDA_FORM_INVOKERS) != 0;
 56     }
 57 
 58     /**
 59       * Is the VM writing to a (static or dynamic) CDS archive.
 60       */
 61     public static boolean isDumpingArchive() {
 62         return (configStatus & IS_DUMPING_ARCHIVE) != 0;
 63     }
 64 
 65     /**
 66       * Is the VM using at least one CDS archive?
 67       */
 68     public static boolean isUsingArchive() {
 69         return (configStatus & IS_USING_ARCHIVE) != 0;
 70     }
 71 
 72     /**
 73       * Is dumping static archive.
 74       */
 75     public static boolean isDumpingStaticArchive() {
 76         return (configStatus & IS_DUMPING_STATIC_ARCHIVE) != 0;
 77     }
 78 
 79     private static native int getCDSConfigStatus();
 80     private static native void logLambdaFormInvoker(String line);
 81 
 82     /**
 83      * Initialize archived static fields in the given Class using archived
 84      * values from CDS dump time. Also initialize the classes of objects in
 85      * the archived graph referenced by those fields.
 86      *
 87      * Those static fields remain as uninitialized if there is no mapped CDS
 88      * java heap data or there is any error during initialization of the
 89      * object class in the archived graph.
 90      */
 91     public static native void initializeFromArchive(Class<?> c);
 92 
 93     /**
 94      * Ensure that the native representation of all archived java.lang.Module objects
 95      * are properly restored.
 96      */
 97     public static native void defineArchivedModules(ClassLoader platformLoader, ClassLoader systemLoader);
 98 
 99     /**
100      * Returns a predictable "random" seed derived from the VM's build ID and version,
101      * to be used by java.util.ImmutableCollections to ensure that archived
102      * ImmutableCollections are always sorted the same order for the same VM build.
103      */
104     public static native long getRandomSeedForDumping();
105 
106     /**
107      * log lambda form invoker holder, name and method type
108      */
109     public static void logLambdaFormInvoker(String prefix, String holder, String name, String type) {
110         if (isLoggingLambdaFormInvokers()) {
111             logLambdaFormInvoker(prefix + " " + holder + " " + name + " " + type);
112         }
113     }
114 
115     /**
116       * log species
117       */
118     public static void logSpeciesType(String prefix, String cn) {
119         if (isLoggingLambdaFormInvokers()) {
120             logLambdaFormInvoker(prefix + " " + cn);
121         }
122     }
123 
124     static final String DIRECT_HOLDER_CLASS_NAME  = "java.lang.invoke.DirectMethodHandle$Holder";
125     static final String DELEGATING_HOLDER_CLASS_NAME = "java.lang.invoke.DelegatingMethodHandle$Holder";
126     static final String BASIC_FORMS_HOLDER_CLASS_NAME = "java.lang.invoke.LambdaForm$Holder";
127     static final String INVOKERS_HOLDER_CLASS_NAME = "java.lang.invoke.Invokers$Holder";
128 
129     private static boolean isValidHolderName(String name) {
130         return name.equals(DIRECT_HOLDER_CLASS_NAME)      ||
131                name.equals(DELEGATING_HOLDER_CLASS_NAME)  ||
132                name.equals(BASIC_FORMS_HOLDER_CLASS_NAME) ||
133                name.equals(INVOKERS_HOLDER_CLASS_NAME);
134     }
135 
136     private static boolean isBasicTypeChar(char c) {
137          return "LIJFDV".indexOf(c) >= 0;
138     }
139 
140     private static boolean isValidMethodType(String type) {
141         String[] typeParts = type.split("_");
142         // check return type (second part)
143         if (typeParts.length != 2 || typeParts[1].length() != 1
144                 || !isBasicTypeChar(typeParts[1].charAt(0))) {
145             return false;
146         }
147         // first part
148         if (!isBasicTypeChar(typeParts[0].charAt(0))) {
149             return false;
150         }
151         for (int i = 1; i < typeParts[0].length(); i++) {
152             char c = typeParts[0].charAt(i);
153             if (!isBasicTypeChar(c)) {
154                 if (!(c >= '0' && c <= '9')) {
155                     return false;
156                 }
157             }
158         }
159         return true;
160     }
161 
162     // Throw exception on invalid input
163     private static void validateInputLines(String[] lines) {
164         for (String s: lines) {
165             if (!s.startsWith("[LF_RESOLVE]") && !s.startsWith("[SPECIES_RESOLVE]")) {
166                 throw new IllegalArgumentException("Wrong prefix: " + s);
167             }
168 
169             String[] parts = s.split(" ");
170             boolean isLF = s.startsWith("[LF_RESOLVE]");
171 
172             if (isLF) {
173                 if (parts.length != 4) {
174                     throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
175                 }
176                 if (!isValidHolderName(parts[1])) {
177                     throw new IllegalArgumentException("Invalid holder class name: " + parts[1]);
178                 }
179                 if (!isValidMethodType(parts[3])) {
180                     throw new IllegalArgumentException("Invalid method type: " + parts[3]);
181                 }
182             } else {
183                 if (parts.length != 2) {
184                    throw new IllegalArgumentException("Incorrect number of items in the line: " + parts.length);
185                 }
186            }
187       }
188     }
189 
190     /**
191      * called from vm to generate MethodHandle holder classes
192      * @return {@code Object[]} if holder classes can be generated.
193      * @param lines in format of LF_RESOLVE or SPECIES_RESOLVE output
194      */
195     private static Object[] generateLambdaFormHolderClasses(String[] lines) {
196         Objects.requireNonNull(lines);
197         validateInputLines(lines);
198         Stream<String> lineStream = Arrays.stream(lines);
199         Map<String, byte[]> result = SharedSecrets.getJavaLangInvokeAccess().generateHolderClasses(lineStream);
200         int size = result.size();
201         Object[] retArray = new Object[size * 2];
202         int index = 0;
203         for (Map.Entry<String, byte[]> entry : result.entrySet()) {
204             retArray[index++] = entry.getKey();
205             retArray[index++] = entry.getValue();
206         };
207         return retArray;
208     }
209 
210     private static native void dumpClassList(String listFileName);
211     private static native void dumpDynamicArchive(String archiveFileName);
212 
213     private static String drainOutput(InputStream stream, long pid, String tail, List<String> cmds) {
214         String fileName  = "java_pid" + pid + "_" + tail;
215         new Thread( ()-> {
216             try (InputStreamReader isr = new InputStreamReader(stream);
217                  BufferedReader rdr = new BufferedReader(isr);
218                  PrintStream prt = new PrintStream(fileName)) {
219                 prt.println("Command:");
220                 for (String s : cmds) {
221                     prt.print(s + " ");
222                 }
223                 prt.println("");
224                 String line;
225                 while((line = rdr.readLine()) != null) {
226                     prt.println(line);
227                 }
228             } catch (IOException e) {
229                 throw new RuntimeException("IOException happens during drain stream to file " +
230                                            fileName + ": " + e.getMessage());
231             }}).start();
232         return fileName;
233     }
234 
235     private static String[] excludeFlags = {
236          "-XX:DumpLoadedClassList=",
237          "-XX:+RecordDynamicDumpInfo",
238          "-Xshare:",
239          "-XX:SharedClassListFile=",
240          "-XX:SharedArchiveFile=",
241          "-XX:ArchiveClassesAtExit="};
242     private static boolean containsExcludedFlags(String testStr) {
243        for (String e : excludeFlags) {
244            if (testStr.contains(e)) {
245                return true;
246            }
247        }
248        return false;
249     }
250 
251     /**
252     * called from jcmd VM.cds to dump static or dynamic shared archive
253     * @param isStatic true for dump static archive or false for dynnamic archive.
254     * @param fileName user input archive name, can be null.
255     * @return The archive name if successfully dumped.
256     */
257     private static String dumpSharedArchive(boolean isStatic, String fileName) throws Exception {
258         String cwd = new File("").getAbsolutePath(); // current dir used for printing message.
259         String currentPid = String.valueOf(ProcessHandle.current().pid());
260         String archiveFileName =  fileName != null ? fileName :
261             "java_pid" + currentPid + (isStatic ? "_static.jsa" : "_dynamic.jsa");
262 
263         String tempArchiveFileName = archiveFileName + ".temp";
264         File tempArchiveFile = new File(tempArchiveFileName);
265         // The operation below may cause exception if the file or its dir is protected.
266         if (!tempArchiveFile.exists()) {
267             tempArchiveFile.createNewFile();
268         }
269         tempArchiveFile.delete();
270 
271         if (isStatic) {
272             String listFileName = archiveFileName + ".classlist";
273             File listFile = new File(listFileName);
274             if (listFile.exists()) {
275                 listFile.delete();
276             }
277             dumpClassList(listFileName);
278             String jdkHome = System.getProperty("java.home");
279             String classPath = System.getProperty("java.class.path");
280             List<String> cmds = new ArrayList<String>();
281             cmds.add(jdkHome + File.separator + "bin" + File.separator + "java"); // java
282             cmds.add("-cp");
283             cmds.add(classPath);
284             cmds.add("-Xlog:cds");
285             cmds.add("-Xshare:dump");
286             cmds.add("-XX:SharedClassListFile=" + listFileName);
287             cmds.add("-XX:SharedArchiveFile=" + tempArchiveFileName);
288 
289             // All runtime args.
290             String[] vmArgs = VM.getRuntimeArguments();
291             if (vmArgs != null) {
292                 for (String arg : vmArgs) {
293                     if (arg != null && !containsExcludedFlags(arg)) {
294                         cmds.add(arg);
295                     }
296                 }
297             }
298 
299             Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[0]));
300 
301             // Drain stdout/stderr to files in new threads.
302             String stdOutFileName = drainOutput(proc.getInputStream(), proc.pid(), "stdout", cmds);
303             String stdErrFileName = drainOutput(proc.getErrorStream(), proc.pid(), "stderr", cmds);
304 
305             proc.waitFor();
306             // done, delete classlist file.
307             listFile.delete();
308 
309             // Check if archive has been successfully dumped. We won't reach here if exception happens.
310             // Throw exception if file is not created.
311             if (!tempArchiveFile.exists()) {
312                 throw new RuntimeException("Archive file " + tempArchiveFileName +
313                                            " is not created, please check stdout file " +
314                                             cwd + File.separator + stdOutFileName + " or stderr file " +
315                                             cwd + File.separator + stdErrFileName + " for more detail");
316             }
317         } else {
318             dumpDynamicArchive(tempArchiveFileName);
319             if (!tempArchiveFile.exists()) {
320                 throw new RuntimeException("Archive file " + tempArchiveFileName +
321                                            " is not created, please check current working directory " +
322                                            cwd  + " for process " +
323                                            currentPid + " output for more detail");
324             }
325         }
326         // Override the existing archive file
327         File archiveFile = new File(archiveFileName);
328         if (archiveFile.exists()) {
329             archiveFile.delete();
330         }
331         if (!tempArchiveFile.renameTo(archiveFile)) {
332             throw new RuntimeException("Cannot rename temp file " + tempArchiveFileName + " to archive file" + archiveFileName);
333         }
334         // Everything goes well, print out the file name.
335         String archiveFilePath = new File(archiveFileName).getAbsolutePath();
336         System.out.println("The process was attached by jcmd and dumped a " + (isStatic ? "static" : "dynamic") + " archive " + archiveFilePath);
337         return archiveFilePath;
338     }
339 }