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