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