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 "runtime/vmThread.hpp"
 43 #include "utilities/defaultStream.hpp"
 44 #include "utilities/formatBuffer.hpp"
 45 
 46 bool CDSConfig::_is_dumping_static_archive = false;
 47 bool CDSConfig::_is_dumping_dynamic_archive = false;
 48 bool CDSConfig::_is_using_optimized_module_handling = true;
 49 bool CDSConfig::_is_dumping_full_module_graph = true;
 50 bool CDSConfig::_is_using_full_module_graph = true;
 51 bool CDSConfig::_has_aot_linked_classes = false;
 52 bool CDSConfig::_has_archived_invokedynamic = false;
 53 bool CDSConfig::_is_loading_packages = false;
 54 bool CDSConfig::_is_loading_protection_domains = false;
 55 bool CDSConfig::_is_security_manager_allowed = false;
 56 bool CDSConfig::_old_cds_flags_used = false;
 57 
 58 char* CDSConfig::_default_archive_path = nullptr;
 59 char* CDSConfig::_static_archive_path = nullptr;
 60 char* CDSConfig::_dynamic_archive_path = nullptr;
 61 
 62 JavaThread* CDSConfig::_dumper_thread = nullptr;
 63 
 64 int CDSConfig::get_status() {
 65   assert(Universe::is_fully_initialized(), "status is finalized only after Universe is initialized");
 66   return (is_dumping_archive()              ? IS_DUMPING_ARCHIVE : 0) |
 67          (is_dumping_static_archive()       ? IS_DUMPING_STATIC_ARCHIVE : 0) |
 68          (is_logging_lambda_form_invokers() ? IS_LOGGING_LAMBDA_FORM_INVOKERS : 0) |
 69          (is_using_archive()                ? IS_USING_ARCHIVE : 0) |
 70          (is_dumping_heap()                 ? IS_DUMPING_HEAP : 0) |
 71          (is_logging_dynamic_proxies()      ? IS_LOGGING_DYNAMIC_PROXIES : 0) |
 72          (is_dumping_packages()             ? IS_DUMPING_PACKAGES : 0) |
 73          (is_dumping_protection_domains()   ? IS_DUMPING_PROTECTION_DOMAINS : 0);
 74 }
 75 
 76 void CDSConfig::initialize() {
 77   if (is_dumping_static_archive() && !is_dumping_final_static_archive()) {



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