1 /*
  2  * Copyright (c) 2023, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "cds/archiveHeapLoader.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/cds_globals.hpp"
 29 #include "cds/classListWriter.hpp"
 30 #include "cds/heapShared.hpp"
 31 #include "cds/metaspaceShared.hpp"
 32 #include "classfile/classLoaderDataShared.hpp"
 33 #include "classfile/moduleEntry.hpp"
 34 #include "classfile/systemDictionaryShared.hpp"
 35 #include "include/jvm_io.h"
 36 #include "logging/log.hpp"
 37 #include "prims/jvmtiExport.hpp"
 38 #include "memory/universe.hpp"
 39 #include "runtime/arguments.hpp"
 40 #include "runtime/globals_extension.hpp"
 41 #include "runtime/java.hpp"
 42 #include "utilities/defaultStream.hpp"
 43 #include "utilities/formatBuffer.hpp"
 44 
 45 bool CDSConfig::_is_dumping_static_archive = false;
 46 bool CDSConfig::_is_dumping_dynamic_archive = false;
 47 bool CDSConfig::_is_using_optimized_module_handling = true;
 48 bool CDSConfig::_is_dumping_full_module_graph = true;
 49 bool CDSConfig::_is_using_full_module_graph = true;
 50 bool CDSConfig::_has_preloaded_classes = false;
 51 bool CDSConfig::_is_loading_invokedynamic = false;
 52 bool CDSConfig::_is_loading_packages = false;
 53 bool CDSConfig::_is_loading_protection_domains = false;
 54 bool CDSConfig::_is_security_manager_allowed = false;
 55 bool CDSConfig::_old_cds_flags_used = false;
 56 
 57 char* CDSConfig::_default_archive_path = nullptr;
 58 char* CDSConfig::_static_archive_path = nullptr;
 59 char* CDSConfig::_dynamic_archive_path = nullptr;
 60 
 61 int CDSConfig::get_status() {
 62   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
 63   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
 64          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
 65          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
 66          (is_using_archive()                ? IS_USING_ARCHIVE : 0) |
 67          (is_dumping_heap()                 ? IS_DUMPING_HEAP : 0) |
 68          (is_tracing_dynamic_proxy()        ? IS_LOGGING_DYNAMIC_PROXIES : 0) |
 69          (is_dumping_packages()             ? IS_DUMPING_PACKAGES : 0) |
 70          (is_dumping_protection_domains()   ? IS_DUMPING_PROTECTION_DOMAINS : 0);
 71 }
 72 

 73 void CDSConfig::initialize() {
 74   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {



 75     UseSharedSpaces = false;
 76   }
 77 
 78   // Initialize shared archive paths which could include both base and dynamic archive paths
 79   // This must be after set_ergonomics_flags() called so flag UseCompressedOops is set properly.
 80   //
 81   // UseSharedSpaces may be disabled if -XX:SharedArchiveFile is invalid.
 82   if (is_dumping_static_archive() || is_using_archive()) {
 83     init_shared_archive_paths();
 84   }
 85 
 86   if (!is_dumping_heap()) {
 87     _is_dumping_full_module_graph = false;
 88   }
 89 }
 90 
 91 char* CDSConfig::default_archive_path() {
 92   if (_default_archive_path == nullptr) {
 93     char jvm_path[JVM_MAXPATHLEN];
 94     os::jvm_path(jvm_path, sizeof(jvm_path));
 95     char *end = strrchr(jvm_path, *os::file_separator());
 96     if (end != nullptr) *end = '\0';
 97     size_t jvm_path_len = strlen(jvm_path);
 98     size_t file_sep_len = strlen(os::file_separator());
 99     const size_t len = jvm_path_len + file_sep_len + 20;
100     _default_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
101     jio_snprintf(_default_archive_path, len,
102                 LP64_ONLY(!UseCompressedOops ? "%s%sclasses_nocoops.jsa":) "%s%sclasses.jsa",
103                 jvm_path, os::file_separator());
104   }
105   return _default_archive_path;
106 }
107 
108 int CDSConfig::num_archives(const char* archive_path) {
109   if (archive_path == nullptr) {
110     return 0;
111   }
112   int npaths = 1;
113   char* p = (char*)archive_path;
114   while (*p != '\0') {
115     if (*p == os::path_separator()[0]) {
116       npaths++;
117     }
118     p++;
119   }
120   return npaths;
121 }
122 
123 void CDSConfig::extract_shared_archive_paths(const char* archive_path,
124                                              char** base_archive_path,
125                                              char** top_archive_path) {
126   char* begin_ptr = (char*)archive_path;
127   char* end_ptr = strchr((char*)archive_path, os::path_separator()[0]);
128   if (end_ptr == nullptr || end_ptr == begin_ptr) {
129     vm_exit_during_initialization("Base archive was not specified", archive_path);
130   }
131   size_t len = end_ptr - begin_ptr;
132   char* cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
133   strncpy(cur_path, begin_ptr, len);
134   cur_path[len] = '\0';
135   *base_archive_path = cur_path;
136 
137   begin_ptr = ++end_ptr;
138   if (*begin_ptr == '\0') {
139     vm_exit_during_initialization("Top archive was not specified", archive_path);
140   }
141   end_ptr = strchr(begin_ptr, '\0');
142   assert(end_ptr != nullptr, "sanity");
143   len = end_ptr - begin_ptr;
144   cur_path = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
145   strncpy(cur_path, begin_ptr, len + 1);
146   *top_archive_path = cur_path;
147 }
148 
149 static void set_new_workflow_default_CachedCodeFile() {
150   size_t len = strlen(CacheDataStore) + 6;
151   char* file = AllocateHeap(len, mtArguments);
152   jio_snprintf(file, len, "%s.code", CacheDataStore);
153   FLAG_SET_ERGO(CachedCodeFile, file);
154 }
155 
156 void CDSConfig::init_shared_archive_paths() {
157   if (ArchiveClassesAtExit != nullptr) {
158     assert(!RecordDynamicDumpInfo, "already checked");
159     if (is_dumping_static_archive()) {
160       vm_exit_during_initialization("-XX:ArchiveClassesAtExit cannot be used with -Xshare:dump");
161     }
162     check_unsupported_dumping_module_options();
163 
164     if (os::same_files(default_archive_path(), ArchiveClassesAtExit)) {
165       vm_exit_during_initialization(
166         "Cannot specify the default CDS archive for -XX:ArchiveClassesAtExit", default_archive_path());
167     }
168   }
169 
170   if (SharedArchiveFile == nullptr) {
171     _static_archive_path = default_archive_path();
172   } else {
173     int archives = num_archives(SharedArchiveFile);
174     assert(archives > 0, "must be");
175 
176     if (is_dumping_archive() && archives > 1) {
177       vm_exit_during_initialization(
178         "Cannot have more than 1 archive file specified in -XX:SharedArchiveFile during CDS dumping");
179     }
180 
181     if (CDSPreimage != nullptr && archives > 1) {
182       vm_exit_during_initialization("CDSPreimage must point to a single file", CDSPreimage);
183     }
184 
185     if (is_dumping_static_archive()) {
186       assert(archives == 1, "must be");
187       // Static dump is simple: only one archive is allowed in SharedArchiveFile. This file
188       // will be overwritten no matter regardless of its contents
189       _static_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
190     } else {
191       // SharedArchiveFile may specify one or two files. In case (c), the path for base.jsa
192       // is read from top.jsa
193       //    (a) 1 file:  -XX:SharedArchiveFile=base.jsa
194       //    (b) 2 files: -XX:SharedArchiveFile=base.jsa:top.jsa
195       //    (c) 2 files: -XX:SharedArchiveFile=top.jsa
196       //
197       // However, if either RecordDynamicDumpInfo or ArchiveClassesAtExit is used, we do not
198       // allow cases (b) and (c). Case (b) is already checked above.
199 
200       if (archives > 2) {
201         vm_exit_during_initialization(
202           "Cannot have more than 2 archive files specified in the -XX:SharedArchiveFile option");
203       }
204       if (archives == 1) {
205         char* base_archive_path = nullptr;
206         bool success =
207           FileMapInfo::get_base_archive_name_from_header(SharedArchiveFile, &base_archive_path);
208         if (!success) {
209           if (CDSPreimage != nullptr) {
210             vm_exit_during_initialization("Unable to map shared spaces from CDSPreimage", CDSPreimage);
211           }
212 
213           // If +AutoCreateSharedArchive and the specified shared archive does not exist,
214           // regenerate the dynamic archive base on default archive.
215           if (AutoCreateSharedArchive && !os::file_exists(SharedArchiveFile)) {
216             enable_dumping_dynamic_archive();
217             ArchiveClassesAtExit = const_cast<char *>(SharedArchiveFile);
218             _static_archive_path = default_archive_path();
219             SharedArchiveFile = nullptr;
220           } else {
221             if (AutoCreateSharedArchive) {
222               warning("-XX:+AutoCreateSharedArchive is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
223               AutoCreateSharedArchive = false;
224             }
225             Arguments::no_shared_spaces("invalid archive");
226           }
227         } else if (base_archive_path == nullptr) {
228           // User has specified a single archive, which is a static archive.
229           _static_archive_path = const_cast<char *>(SharedArchiveFile);
230         } else {
231           // User has specified a single archive, which is a dynamic archive.
232           _dynamic_archive_path = const_cast<char *>(SharedArchiveFile);
233           _static_archive_path = base_archive_path; // has been c-heap allocated.
234         }
235       } else {
236         extract_shared_archive_paths((const char*)SharedArchiveFile,
237                                       &_static_archive_path, &_dynamic_archive_path);
238         if (_static_archive_path == nullptr) {
239           assert(_dynamic_archive_path == nullptr, "must be");
240           Arguments::no_shared_spaces("invalid archive");
241         }
242       }
243 
244       if (_dynamic_archive_path != nullptr) {
245         // Check for case (c)
246         if (RecordDynamicDumpInfo) {
247           vm_exit_during_initialization("-XX:+RecordDynamicDumpInfo is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
248                                         SharedArchiveFile);
249         }
250         if (ArchiveClassesAtExit != nullptr) {
251           vm_exit_during_initialization("-XX:ArchiveClassesAtExit is unsupported when a dynamic CDS archive is specified in -XX:SharedArchiveFile",
252                                         SharedArchiveFile);
253         }
254       }
255 
256       if (ArchiveClassesAtExit != nullptr && os::same_files(SharedArchiveFile, ArchiveClassesAtExit)) {
257           vm_exit_during_initialization(
258             "Cannot have the same archive file specified for -XX:SharedArchiveFile and -XX:ArchiveClassesAtExit",
259             SharedArchiveFile);
260       }
261     }
262   }
263 }
264 
265 static char* bad_module_prop_key   = nullptr;
266 static char* bad_module_prop_value = nullptr;
267 
268 void CDSConfig::check_internal_module_property(const char* key, const char* value) {
269   if (Arguments::is_internal_module_property(key)) {
270     stop_using_optimized_module_handling();
271     if (bad_module_prop_key == nullptr) {
272       // We don't want to print an unconditional warning here, as we are still processing the command line.
273       // A later argument may specify something like -Xshare:off, which makes such a warning irrelevant.
274       //
275       // Instead, we save the info so we can warn when necessary: we are doing it only during CacheDataStore
276       // creation for now, but could add it to other places.
277       bad_module_prop_key   = os::strdup(key);
278       bad_module_prop_value = os::strdup(value);
279     }
280     log_info(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s", key, value);
281   }
282 }
283 
284 void CDSConfig::check_incompatible_property(const char* key, const char* value) {
285   static const char* incompatible_properties[] = {
286     "java.system.class.loader",
287     "jdk.module.showModuleResolution",
288     "jdk.module.validation"
289   };
290 
291   for (const char* property : incompatible_properties) {
292     if (strcmp(key, property) == 0) {
293       stop_dumping_full_module_graph();
294       stop_using_full_module_graph();
295       log_info(cds)("full module graph: disabled due to incompatible property: %s=%s", key, value);
296       break;
297     }
298   }
299 
300   // Match the logic in java/lang/System.java, but we need to know this before the System class is initialized.
301   if (strcmp(key, "java.security.manager") == 0) {
302     if (strcmp(value, "disallowed") != 0) {
303       _is_security_manager_allowed = true;
304     }
305   }
306 }
307 
308 // Returns any JVM command-line option, such as "--patch-module", that's not supported by CDS.
309 static const char* find_any_unsupported_module_option() {
310   // Note that arguments.cpp has translated the command-line options into properties. If we find an
311   // unsupported property, translate it back to its command-line option for better error reporting.
312 
313   // The following properties are checked by Arguments::is_internal_module_property() and cannot be
314   // directly specified in the command-line.
315   static const char* unsupported_module_properties[] = {
316     "jdk.module.limitmods",
317     "jdk.module.upgrade.path",
318     "jdk.module.patch.0"
319   };
320   static const char* unsupported_module_options[] = {
321     "--limit-modules",
322     "--upgrade-module-path",
323     "--patch-module"
324   };
325 
326   assert(ARRAY_SIZE(unsupported_module_properties) == ARRAY_SIZE(unsupported_module_options), "must be");
327   SystemProperty* sp = Arguments::system_properties();
328   while (sp != nullptr) {
329     for (uint i = 0; i < ARRAY_SIZE(unsupported_module_properties); i++) {
330       if (strcmp(sp->key(), unsupported_module_properties[i]) == 0) {
331         return unsupported_module_options[i];
332       }
333     }
334     sp = sp->next();
335   }
336 
337   return nullptr; // not found
338 }
339 
340 void CDSConfig::check_unsupported_dumping_module_options() {
341   assert(is_dumping_archive(), "this function is only used with CDS dump time");
342   const char* option = find_any_unsupported_module_option();
343   if (option != nullptr) {
344     vm_exit_during_initialization("Cannot use the following option when dumping the shared archive", option);
345   }
346   // Check for an exploded module build in use with -Xshare:dump.
347   if (!Arguments::has_jimage()) {
348     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
349   }
350 }
351 
352 bool CDSConfig::has_unsupported_runtime_module_options() {
353   assert(is_using_archive(), "this function is only used with -Xshare:{on,auto}");
354   if (ArchiveClassesAtExit != nullptr) {
355     // dynamic dumping, just return false for now.
356     // check_unsupported_dumping_properties() will be called later to check the same set of
357     // properties, and will exit the VM with the correct error message if the unsupported properties
358     // are used.
359     return false;
360   }
361   const char* option = find_any_unsupported_module_option();
362   if (option != nullptr) {
363     if (RequireSharedSpaces) {
364       warning("CDS is disabled when the %s option is specified.", option);
365     } else {
366       log_info(cds)("CDS is disabled when the %s option is specified.", option);
367     }
368     return true;
369   }
370   return false;
371 }
372 
373 #define CHECK_ALIAS(f) check_flag_alias(FLAG_IS_DEFAULT(f), #f)
374 
375 void CDSConfig::check_flag_alias(bool alias_is_default, const char* alias_name) {
376   if (_old_cds_flags_used && !alias_is_default) {
377     vm_exit_during_initialization(err_msg("Option %s cannot be used at the same time with "
378                                           "-Xshare:on, -Xshare:auto, -Xshare:off, -Xshare:dump, "
379                                           "DumpLoadedClassList, SharedClassListFile, or SharedArchiveFile",
380                                           alias_name));
381   }
382 }
383 
384 void CDSConfig::check_flag_aliases() {
385   if (!FLAG_IS_DEFAULT(DumpLoadedClassList) ||
386       !FLAG_IS_DEFAULT(SharedClassListFile) ||
387       !FLAG_IS_DEFAULT(SharedArchiveFile)) {
388     _old_cds_flags_used = true;
389   }
390 
391   CHECK_ALIAS(AOTCache);
392   CHECK_ALIAS(AOTConfiguration);
393   CHECK_ALIAS(AOTMode);
394 
395   if (FLAG_IS_DEFAULT(AOTMode)) {
396     if (!FLAG_IS_DEFAULT(AOTConfiguration)) {
397       vm_exit_during_initialization("AOTConfiguration cannot be used without setting AOTMode");
398     }
399 
400     if (!FLAG_IS_DEFAULT(AOTCache)) {
401       // -XX:AOTCache=<value> (without AOTMode/AOTConfiguration) is alias for -Xshare:auto -XX:SharedArchiveFile=<value>
402       assert(FLAG_IS_DEFAULT(SharedArchiveFile), "already checked");
403       FLAG_SET_ERGO(SharedArchiveFile, AOTCache);
404       UseSharedSpaces = true;
405       RequireSharedSpaces = false;
406     }
407   } else {
408     // AOTMode has been set
409     if (FLAG_IS_DEFAULT(AOTConfiguration)) {
410       vm_exit_during_initialization("AOTMode cannot be used without setting AOTConfiguration");
411     }
412 
413     if (strcmp(AOTMode, "record") == 0) {
414       if (!FLAG_IS_DEFAULT(AOTCache)) {
415         vm_exit_during_initialization("AOTCache must not be specified when using -XX:AOTMode=record");
416       }
417 
418       assert(FLAG_IS_DEFAULT(DumpLoadedClassList), "already checked");
419       FLAG_SET_ERGO(DumpLoadedClassList, AOTConfiguration);
420       UseSharedSpaces = false;
421       RequireSharedSpaces = false;
422     } else if (strcmp(AOTMode, "create") == 0) {
423       if (FLAG_IS_DEFAULT(AOTCache)) {
424         vm_exit_during_initialization("AOTCache must be specified when using -XX:AOTMode=create");
425       }
426 
427       assert(FLAG_IS_DEFAULT(SharedClassListFile), "already checked");
428       FLAG_SET_ERGO(SharedClassListFile, AOTConfiguration);
429       assert(FLAG_IS_DEFAULT(SharedArchiveFile), "already checked");
430       FLAG_SET_ERGO(SharedArchiveFile, AOTCache);
431 
432       CDSConfig::enable_dumping_static_archive();
433     } else {
434       vm_exit_during_initialization(err_msg("Unrecognized AOTMode %s: must be record or create", AOTMode));
435     }
436   }
437 }
438 
439 bool CDSConfig::check_vm_args_consistency(bool patch_mod_javabase, bool mode_flag_cmd_line, bool xshare_auto_cmd_line) {
440   check_flag_aliases();
441 
442   if (CacheDataStore != nullptr) {
443     // Leyden temp work-around:
444     //
445     // By default, when using CacheDataStore, use the HeapBasedNarrowOop mode so that
446     // AOT code can be always work regardless of runtime heap range.
447     //
448     // If you are *absolutely sure* that the CompressedOops::mode() will be the same
449     // between training and production runs (e.g., if you specify -Xmx128m
450     // for both training and production runs, and you know the OS will always reserve
451     // the heap under 4GB), you can explicitly disable this with:
452     //     java -XX:-UseCompatibleCompressedOops -XX:CacheDataStore=...
453     // However, this is risky and there's a chance that the production run will be slower
454     // because it is unable to load the AOT code cache.
455     FLAG_SET_ERGO_IF_DEFAULT(UseCompatibleCompressedOops, true);
456 
457     // Leyden temp: make sure the user knows if CDS archive somehow fails to load.
458     if (UseSharedSpaces && !xshare_auto_cmd_line) {
459       log_info(cds)("Enabled -Xshare:on by default for troubleshooting Leyden prototype");
460       RequireSharedSpaces = true;
461     }
462 
463     if (FLAG_IS_DEFAULT(PreloadSharedClasses)) {
464       // New workflow - enable PreloadSharedClasses by default.
465       // TODO: make new workflow work, even when PreloadSharedClasses is false.
466       //
467       // NOTE: in old workflow, we cannot enable PreloadSharedClasses by default. That
468       // should be an opt-in option, per JEP nnn.
469       FLAG_SET_ERGO(PreloadSharedClasses, true);
470     }
471 
472     if (SharedArchiveFile != nullptr) {
473       vm_exit_during_initialization("CacheDataStore and SharedArchiveFile cannot be both specified");
474     }
475     if (!PreloadSharedClasses) {
476       // TODO: in the forked JVM, we should ensure all classes are loaded from the hotspot.cds.preimage.
477       // PreloadSharedClasses only loads the classes for built-in loaders. We need to load the classes
478       // for custom loaders as well.
479       vm_exit_during_initialization("CacheDataStore requires PreloadSharedClasses");
480     }
481 
482     if (CDSPreimage == nullptr) {
483       if (os::file_exists(CacheDataStore) /* && TODO: CDS file is valid*/) {
484         // The CacheDataStore is already up to date. Use it. Also turn on cached code by default.
485         SharedArchiveFile = CacheDataStore;
486         FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
487         FLAG_SET_ERGO_IF_DEFAULT(LoadCachedCode, true);
488         if (LoadCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
489           set_new_workflow_default_CachedCodeFile();
490         }
491       } else {
492         // The preimage dumping phase -- run the app and write the preimage file
493         size_t len = strlen(CacheDataStore) + 10;
494         char* preimage = AllocateHeap(len, mtArguments);
495         jio_snprintf(preimage, len, "%s.preimage", CacheDataStore);
496 
497         UseSharedSpaces = false;
498         enable_dumping_static_archive();
499         SharedArchiveFile = preimage;
500         log_info(cds)("CacheDataStore needs to be updated. Writing %s file", SharedArchiveFile);
501 
502         // At VM exit, the module graph may be contaminated with program states. We should rebuild the
503         // module graph when dumping the CDS final image.
504         log_info(cds)("full module graph: disabled when writing CDS preimage");
505         HeapShared::disable_writing();
506         stop_dumping_full_module_graph();
507         FLAG_SET_ERGO(ArchivePackages, false);
508         FLAG_SET_ERGO(ArchiveProtectionDomains, false);
509 
510         FLAG_SET_ERGO_IF_DEFAULT(RecordTraining, true);
511       }
512     } else {
513       // The final image dumping phase -- load the preimage and write the final image file
514       SharedArchiveFile = CDSPreimage;
515       UseSharedSpaces = true;
516       log_info(cds)("Generate CacheDataStore %s from CDSPreimage %s", CacheDataStore, CDSPreimage);
517       // Force -Xbatch for AOT compilation.
518       if (FLAG_SET_CMDLINE(BackgroundCompilation, false) != JVMFlag::SUCCESS) {
519         return false;
520       }
521       RecordTraining = false; // This will be updated inside MetaspaceShared::preload_and_dump()
522 
523       FLAG_SET_ERGO_IF_DEFAULT(ReplayTraining, true);
524       // Settings for AOT
525       FLAG_SET_ERGO_IF_DEFAULT(StoreCachedCode, true);
526       if (StoreCachedCode && FLAG_IS_DEFAULT(CachedCodeFile)) {
527         set_new_workflow_default_CachedCodeFile();
528         // Cannot dump cached code until metadata and heap are dumped.
529         disable_dumping_cached_code();
530       }
531     }
532   } else {
533     // Old workflow
534     if (CDSPreimage != nullptr) {
535       vm_exit_during_initialization("CDSPreimage must be specified only when CacheDataStore is specified");
536     }
537   }
538 
539   if (FLAG_IS_DEFAULT(UsePermanentHeapObjects)) {
540     if (StoreCachedCode || PreloadSharedClasses) {
541       FLAG_SET_ERGO(UsePermanentHeapObjects, true);
542     }
543   }
544 
545   if (LoadCachedCode) {
546     // This must be true. Cached code is hard-wired to use permanent objects.
547     UsePermanentHeapObjects = true;
548   }
549 
550   if (PreloadSharedClasses) {
551     // If PreloadSharedClasses is specified, enable all these optimizations by default.
552     FLAG_SET_ERGO_IF_DEFAULT(ArchiveDynamicProxies, true);
553     FLAG_SET_ERGO_IF_DEFAULT(ArchiveFieldReferences, true);
554     FLAG_SET_ERGO_IF_DEFAULT(ArchiveInvokeDynamic, true);
555     FLAG_SET_ERGO_IF_DEFAULT(ArchiveLoaderLookupCache, true);
556     FLAG_SET_ERGO_IF_DEFAULT(ArchiveMethodReferences, true);
557     FLAG_SET_ERGO_IF_DEFAULT(ArchivePackages, true);
558     FLAG_SET_ERGO_IF_DEFAULT(ArchiveProtectionDomains, true);
559     FLAG_SET_ERGO_IF_DEFAULT(ArchiveReflectionData, true);
560   } else {
561     // All of these *might* depend on PreloadSharedClasses. Better be safe than sorry.
562     // TODO: more fine-grained handling.
563     FLAG_SET_ERGO(ArchiveDynamicProxies, false);
564     FLAG_SET_ERGO(ArchiveFieldReferences, false);
565     FLAG_SET_ERGO(ArchiveInvokeDynamic, false);
566     FLAG_SET_ERGO(ArchiveLoaderLookupCache, false);
567     FLAG_SET_ERGO(ArchiveMethodReferences, false);
568     FLAG_SET_ERGO(ArchivePackages, false);
569     FLAG_SET_ERGO(ArchiveProtectionDomains, false);
570     FLAG_SET_ERGO(ArchiveReflectionData, false);
571   }
572 
573   if (is_dumping_static_archive()) {
574     if (is_dumping_preimage_static_archive() || is_dumping_final_static_archive()) {
575       // Don't tweak execution mode
576     } else if (!mode_flag_cmd_line) {
577       // By default, -Xshare:dump runs in interpreter-only mode, which is required for deterministic archive.
578       //
579       // If your classlist is large and you don't care about deterministic dumping, you can use
580       // -Xshare:dump -Xmixed to improve dumping speed.
581       Arguments::set_mode_flags(Arguments::_int);
582     } else if (Arguments::mode() == Arguments::_comp) {
583       // -Xcomp may use excessive CPU for the test tiers. Also, -Xshare:dump runs a small and fixed set of
584       // Java code, so there's not much benefit in running -Xcomp.
585       log_info(cds)("reduced -Xcomp to -Xmixed for static dumping");
586       Arguments::set_mode_flags(Arguments::_mixed);
587     }
588 
589     // String deduplication may cause CDS to iterate the strings in different order from one
590     // run to another which resulting in non-determinstic CDS archives.
591     // Disable UseStringDeduplication while dumping CDS archive.
592     UseStringDeduplication = false;
593 
594     Arguments::PropertyList_add(new SystemProperty("java.lang.invoke.MethodHandle.NO_SOFT_CACHE", "true", false));
595   }
596 
597   // RecordDynamicDumpInfo is not compatible with ArchiveClassesAtExit
598   if (ArchiveClassesAtExit != nullptr && RecordDynamicDumpInfo) {
599     jio_fprintf(defaultStream::output_stream(),
600                 "-XX:+RecordDynamicDumpInfo cannot be used with -XX:ArchiveClassesAtExit.\n");
601     return false;
602   }
603 
604   if (ArchiveClassesAtExit == nullptr && !RecordDynamicDumpInfo) {
605     disable_dumping_dynamic_archive();
606   } else {
607     enable_dumping_dynamic_archive();
608   }
609 
610   if (AutoCreateSharedArchive) {
611     if (SharedArchiveFile == nullptr) {
612       log_warning(cds)("-XX:+AutoCreateSharedArchive requires -XX:SharedArchiveFile");
613       return false;
614     }
615     if (ArchiveClassesAtExit != nullptr) {
616       log_warning(cds)("-XX:+AutoCreateSharedArchive does not work with ArchiveClassesAtExit");
617       return false;
618     }
619   }
620 
621   if (is_using_archive() && patch_mod_javabase) {
622     Arguments::no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
623   }
624   if (is_using_archive() && has_unsupported_runtime_module_options()) {
625     UseSharedSpaces = false;
626   }
627 
628   if (is_dumping_archive()) {
629     // Always verify non-system classes during CDS dump
630     if (!BytecodeVerificationRemote) {
631       BytecodeVerificationRemote = true;
632       log_info(cds)("All non-system classes will be verified (-Xverify:remote) during CDS dump time.");
633     }
634   }
635 
636   if (PreloadSharedClasses) {
637     if ((is_dumping_preimage_static_archive() && !is_using_optimized_module_handling()) ||
638         (is_dumping_final_static_archive()    && !is_dumping_full_module_graph())) {
639       if (bad_module_prop_key != nullptr) {
640         log_warning(cds)("optimized module handling/full module graph: disabled due to incompatible property: %s=%s",
641                          bad_module_prop_key, bad_module_prop_value);
642       }
643       vm_exit_during_initialization("CacheDataStore cannot be created because PreloadSharedClasses is enabled but full module graph is disabled");
644     }
645   }
646 
647   return true;
648 }
649 
650 bool CDSConfig::is_dumping_classic_static_archive() {
651   return _is_dumping_static_archive && CacheDataStore == nullptr && CDSPreimage == nullptr;
652 }
653 
654 bool CDSConfig::is_dumping_preimage_static_archive() {
655   return _is_dumping_static_archive && CacheDataStore != nullptr && CDSPreimage == nullptr;
656 }
657 
658 bool CDSConfig::is_dumping_final_static_archive() {
659   if (CDSPreimage != nullptr) {
660     assert(CacheDataStore != nullptr, "must be"); // should have been properly initialized by arguments.cpp
661   }
662 
663   // Note: _is_dumping_static_archive is false! // FIXME -- refactor this so it makes more sense!
664   return CacheDataStore != nullptr && CDSPreimage != nullptr;
665 }
666 
667 bool CDSConfig::is_dumping_regenerated_lambdaform_invokers() {
668   if (is_dumping_final_static_archive()) {
669     // Not yet supported in new workflow -- the training data may point
670     // to a method in a lambdaform holder class that was not regenerated
671     // due to JDK-8318064.
672     return false;
673   } else {
674     return is_dumping_archive();
675   }
676 }
677 
678 bool CDSConfig::is_tracing_dynamic_proxy() {
679   return ClassListWriter::is_enabled() || is_dumping_preimage_static_archive();
680 }
681 
682 // Preserve all states that were examined used during dumptime verification, such
683 // that the verification result (pass or fail) cannot be changed at runtime.
684 //
685 // For example, if the verification of ik requires that class A must be a subtype of B,
686 // then this relationship between A and B cannot be changed at runtime. I.e., the app
687 // cannot load alternative versions of A and B such that A is not a subtype of B.
688 bool CDSConfig::preserve_all_dumptime_verification_states(const InstanceKlass* ik) {
689   return PreloadSharedClasses && SystemDictionaryShared::is_builtin(ik);
690 }
691 
692 bool CDSConfig::is_using_archive() {
693   return UseSharedSpaces;
694 }
695 
696 bool CDSConfig::is_logging_lambda_form_invokers() {
697   return ClassListWriter::is_enabled() || is_dumping_dynamic_archive() || is_dumping_preimage_static_archive();
698 }
699 
700 void CDSConfig::stop_using_optimized_module_handling() {
701   _is_using_optimized_module_handling = false;
702   _is_dumping_full_module_graph = false; // This requires is_using_optimized_module_handling()
703   _is_using_full_module_graph = false; // This requires is_using_optimized_module_handling()
704 }
705 
706 #if INCLUDE_CDS_JAVA_HEAP
707 bool CDSConfig::is_dumping_heap() {
708   return is_dumping_static_archive() && !is_dumping_preimage_static_archive()
709     && HeapShared::can_write();
710 }
711 
712 bool CDSConfig::is_loading_heap() {
713   return ArchiveHeapLoader::is_in_use();
714 }
715 
716 bool CDSConfig::is_using_full_module_graph() {
717   if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
718     return true;
719   }
720 
721   if (!_is_using_full_module_graph) {
722     return false;
723   }
724 
725   if (is_using_archive() && ArchiveHeapLoader::can_use()) {
726     // Classes used by the archived full module graph are loaded in JVMTI early phase.
727     assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
728            "CDS should be disabled if early class hooks are enabled");
729     return true;
730   } else {
731     _is_using_full_module_graph = false;
732     return false;
733   }
734 }
735 
736 void CDSConfig::stop_dumping_full_module_graph(const char* reason) {
737   if (_is_dumping_full_module_graph) {
738     _is_dumping_full_module_graph = false;
739     if (reason != nullptr) {
740       log_info(cds)("full module graph cannot be dumped: %s", reason);
741     }
742   }
743 }
744 
745 void CDSConfig::stop_using_full_module_graph(const char* reason) {
746   assert(!ClassLoaderDataShared::is_full_module_graph_loaded(), "you call this function too late!");
747   if (_is_using_full_module_graph) {
748     _is_using_full_module_graph = false;
749     if (reason != nullptr) {
750       log_info(cds)("full module graph cannot be loaded: %s", reason);
751     }
752   }
753 }
754 
755 bool CDSConfig::is_loading_invokedynamic() {
756   return UseSharedSpaces && is_loading_heap() && _is_loading_invokedynamic;
757 }
758 
759 bool CDSConfig::is_dumping_dynamic_proxy() {
760   return is_dumping_full_module_graph() && is_dumping_invokedynamic();
761 }
762 
763 bool CDSConfig::is_initing_classes_at_dump_time() {
764   return is_dumping_heap() && PreloadSharedClasses;
765 }
766 
767 bool CDSConfig::is_dumping_invokedynamic() {
768   // Requires PreloadSharedClasses, or else the classes of some archived heap
769   // objects used by the archive indy callsites may be replaced at runtime.
770   return ArchiveInvokeDynamic && PreloadSharedClasses && is_dumping_heap();
771 }
772 
773 bool CDSConfig::is_dumping_packages() {
774   return ArchivePackages && is_dumping_heap();
775 }
776 
777 bool CDSConfig::is_loading_packages() {
778   return UseSharedSpaces && is_loading_heap() && _is_loading_packages;
779 }
780 
781 bool CDSConfig::is_dumping_protection_domains() {
782   if (_is_security_manager_allowed) {
783     // For sanity, don't archive PDs. TODO: can this be relaxed?
784     return false;
785   }
786   // Archived PDs for the modules will reference their java.lang.Module, which must
787   // also be archived.
788   return ArchiveProtectionDomains && is_dumping_full_module_graph();
789 }
790 
791 bool CDSConfig::is_loading_protection_domains() {
792   if (_is_security_manager_allowed) {
793     // For sanity, don't used any archived PDs. TODO: can this be relaxed?
794     return false;
795   }
796   return UseSharedSpaces && is_using_full_module_graph() && _is_loading_protection_domains;
797 }
798 
799 bool CDSConfig::is_dumping_reflection_data() {
800   // reflection data use LambdaForm classes
801   return ArchiveReflectionData && is_dumping_invokedynamic();
802 }
803 
804 #endif // INCLUDE_CDS_JAVA_HEAP
805 
806 // This is allowed by default. We disable it only in the final image dump before the
807 // metadata and heap are dumped.
808 static bool _is_dumping_cached_code = true;
809 
810 bool CDSConfig::is_dumping_cached_code() {
811   return _is_dumping_cached_code;
812 }
813 
814 void CDSConfig::disable_dumping_cached_code() {
815   _is_dumping_cached_code = false;
816 }
817 
818 void CDSConfig::enable_dumping_cached_code() {
819   _is_dumping_cached_code = true;
820 }
--- EOF ---