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