1 /*
  2  * Copyright (c) 2019, 2025, 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 "cds/aotArtifactFinder.hpp"
 26 #include "cds/aotClassLinker.hpp"
 27 #include "cds/aotClassLocation.hpp"
 28 #include "cds/aotLogging.hpp"
 29 #include "cds/archiveBuilder.hpp"
 30 #include "cds/archiveHeapWriter.hpp"
 31 #include "cds/archiveUtils.inline.hpp"
 32 #include "cds/cds_globals.hpp"
 33 #include "cds/cdsConfig.hpp"
 34 #include "cds/dynamicArchive.hpp"
 35 #include "cds/lambdaFormInvokers.hpp"
 36 #include "cds/lambdaProxyClassDictionary.hpp"
 37 #include "cds/metaspaceShared.hpp"
 38 #include "cds/regeneratedClasses.hpp"
 39 #include "classfile/classLoader.hpp"
 40 #include "classfile/classLoaderData.inline.hpp"
 41 #include "classfile/symbolTable.hpp"
 42 #include "classfile/systemDictionaryShared.hpp"
 43 #include "classfile/vmSymbols.hpp"
 44 #include "gc/shared/collectedHeap.hpp"
 45 #include "gc/shared/gcVMOperations.hpp"
 46 #include "gc/shared/gc_globals.hpp"
 47 #include "jvm.h"
 48 #include "logging/log.hpp"
 49 #include "memory/metaspaceClosure.hpp"
 50 #include "memory/resourceArea.hpp"
 51 #include "oops/klass.inline.hpp"
 52 #include "runtime/arguments.hpp"
 53 #include "runtime/os.hpp"
 54 #include "runtime/sharedRuntime.hpp"
 55 #include "runtime/vmOperations.hpp"
 56 #include "runtime/vmThread.hpp"
 57 #include "utilities/align.hpp"
 58 #include "utilities/bitMap.inline.hpp"
 59 
 60 
 61 class DynamicArchiveBuilder : public ArchiveBuilder {
 62   const char* _archive_name;
 63 public:
 64   DynamicArchiveBuilder(const char* archive_name) : _archive_name(archive_name) {}
 65   void mark_pointer(address* ptr_loc) {
 66     ArchivePtrMarker::mark_pointer(ptr_loc);
 67   }
 68 
 69   static int dynamic_dump_method_comparator(Method* a, Method* b) {
 70     Symbol* a_name = a->name();
 71     Symbol* b_name = b->name();
 72 
 73     if (a_name == b_name) {
 74       return 0;
 75     }
 76 
 77     u4 a_offset = ArchiveBuilder::current()->any_to_offset_u4(a_name);
 78     u4 b_offset = ArchiveBuilder::current()->any_to_offset_u4(b_name);
 79 
 80     if (a_offset < b_offset) {
 81       return -1;
 82     } else {
 83       assert(a_offset > b_offset, "must be");
 84       return 1;
 85     }
 86   }
 87 
 88 public:
 89   DynamicArchiveHeader *_header;
 90 
 91   void init_header();
 92   void release_header();
 93   void post_dump();
 94   void sort_methods();
 95   void sort_methods(InstanceKlass* ik) const;
 96   void remark_pointers_for_instance_klass(InstanceKlass* k, bool should_mark) const;
 97   void write_archive(char* serialized_data, AOTClassLocationConfig* cl_config);
 98   void gather_array_klasses();
 99 
100 public:
101   // Do this before and after the archive dump to see if any corruption
102   // is caused by dynamic dumping.
103   void verify_universe(const char* info) {
104     if (VerifyBeforeExit) {
105       log_info(aot)("Verify %s", info);
106       // Among other things, this ensures that Eden top is correct.
107       Universe::heap()->prepare_for_verify();
108       Universe::verify(info);
109     }
110   }
111 
112   void doit() {
113     verify_universe("Before CDS dynamic dump");
114     DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
115 
116     // Block concurrent class unloading from changing the _dumptime_table
117     MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
118 
119     if (SystemDictionaryShared::is_dumptime_table_empty()) {
120       log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
121       return;
122     }
123 
124     log_info(cds, dynamic)("CDS dynamic dump: clinit = " JLONG_FORMAT "ms)",
125                            ClassLoader::class_init_time_ms());
126 
127     init_header();
128     gather_source_objs();
129     gather_array_klasses();
130     reserve_buffer();
131 
132     log_info(cds, dynamic)("Copying %d klasses and %d symbols",
133                            klasses()->length(), symbols()->length());
134     dump_rw_metadata();
135     dump_ro_metadata();
136     relocate_metaspaceobj_embedded_pointers();
137 
138     sort_methods();
139 
140     log_info(aot)("Make classes shareable");
141     make_klasses_shareable();
142 
143     char* serialized_data;
144     AOTClassLocationConfig* cl_config;
145     {
146       // Write the symbol table and system dictionaries to the RO space.
147       // Note that these tables still point to the *original* objects, so
148       // they would need to call DynamicArchive::original_to_target() to
149       // get the correct addresses.
150       assert(current_dump_region() == ro_region(), "Must be RO space");
151       SymbolTable::write_to_archive(symbols());
152 
153       ArchiveBuilder::OtherROAllocMark mark;
154       SystemDictionaryShared::write_to_archive(false);
155       cl_config = AOTClassLocationConfig::dumptime()->write_to_archive();
156       DynamicArchive::dump_array_klasses();
157       AOTClassLinker::write_to_archive();
158 
159       serialized_data = ro_region()->top();
160       WriteClosure wc(ro_region());
161       ArchiveBuilder::serialize_dynamic_archivable_items(&wc);
162     }
163 
164     if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
165       log_info(aot)("Adjust lambda proxy class dictionary");
166       LambdaProxyClassDictionary::adjust_dumptime_table();
167     }
168 
169     relocate_to_requested();
170 
171     write_archive(serialized_data, cl_config);
172     release_header();
173     DynamicArchive::post_dump();
174 
175     post_dump();
176 
177     verify_universe("After CDS dynamic dump");
178   }
179 
180   virtual void iterate_roots(MetaspaceClosure* it) {
181     AOTArtifactFinder::all_cached_classes_do(it);
182     SystemDictionaryShared::dumptime_classes_do(it);
183     iterate_primitive_array_klasses(it);
184   }
185 
186   void iterate_primitive_array_klasses(MetaspaceClosure* it) {
187     for (int i = T_BOOLEAN; i <= T_LONG; i++) {
188       assert(is_java_primitive((BasicType)i), "sanity");
189       Klass* k = Universe::typeArrayKlass((BasicType)i);  // this give you "[I", etc
190       assert(MetaspaceShared::is_shared_static((void*)k),
191         "one-dimensional primitive array should be in static archive");
192       ArrayKlass* ak = ArrayKlass::cast(k);
193       while (ak != nullptr && ak->is_shared()) {
194         Klass* next_k = ak->array_klass_or_null();
195         if (next_k != nullptr) {
196           ak = ArrayKlass::cast(next_k);
197         } else {
198           ak = nullptr;
199         }
200       }
201       if (ak != nullptr) {
202         assert(ak->dimension() > 1, "sanity");
203         // this is the lowest dimension that's not in the static archive
204         it->push(&ak);
205       }
206     }
207   }
208 };
209 
210 void DynamicArchiveBuilder::init_header() {
211   FileMapInfo* mapinfo = new FileMapInfo(_archive_name, false);
212   assert(FileMapInfo::dynamic_info() == mapinfo, "must be");
213   FileMapInfo* base_info = FileMapInfo::current_info();
214   // header only be available after populate_header
215   mapinfo->populate_header(base_info->core_region_alignment());
216   _header = mapinfo->dynamic_header();
217 
218   _header->set_base_header_crc(base_info->crc());
219   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
220     _header->set_base_region_crc(i, base_info->region_crc(i));
221   }
222 }
223 
224 void DynamicArchiveBuilder::release_header() {
225   // We temporarily allocated a dynamic FileMapInfo for dumping, which makes it appear we
226   // have mapped a dynamic archive, but we actually have not. We are in a safepoint now.
227   // Let's free it so that if class loading happens after we leave the safepoint, nothing
228   // bad will happen.
229   assert(SafepointSynchronize::is_at_safepoint(), "must be");
230   FileMapInfo *mapinfo = FileMapInfo::dynamic_info();
231   assert(mapinfo != nullptr && _header == mapinfo->dynamic_header(), "must be");
232   delete mapinfo;
233   assert(!DynamicArchive::is_mapped(), "must be");
234   _header = nullptr;
235 }
236 
237 void DynamicArchiveBuilder::post_dump() {
238   ArchivePtrMarker::reset_map_and_vs();
239   AOTClassLinker::dispose();
240 }
241 
242 void DynamicArchiveBuilder::sort_methods() {
243   InstanceKlass::disable_method_binary_search();
244   for (int i = 0; i < klasses()->length(); i++) {
245     Klass* k = get_buffered_addr(klasses()->at(i));
246     if (k->is_instance_klass()) {
247       sort_methods(InstanceKlass::cast(k));
248     }
249   }
250 }
251 
252 // The address order of the copied Symbols may be different than when the original
253 // klasses were created. Re-sort all the tables. See Method::sort_methods().
254 void DynamicArchiveBuilder::sort_methods(InstanceKlass* ik) const {
255   assert(ik != nullptr, "DynamicArchiveBuilder currently doesn't support dumping the base archive");
256   if (MetaspaceShared::is_in_shared_metaspace(ik)) {
257     // We have reached a supertype that's already in the base archive
258     return;
259   }
260   assert(is_in_buffer_space(ik), "method sorting must be done on buffered class, not original class");
261   if (ik->java_mirror() == nullptr) {
262     // null mirror means this class has already been visited and methods are already sorted
263     return;
264   }
265   ik->remove_java_mirror();
266 
267   if (log_is_enabled(Debug, cds, dynamic)) {
268     ResourceMark rm;
269     log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " (" PTR_FORMAT ") %s",
270                             p2i(ik), p2i(to_requested(ik)), ik->external_name());
271   }
272 
273   // Method sorting may re-layout the [iv]tables, which would change the offset(s)
274   // of the locations in an InstanceKlass that would contain pointers. Let's clear
275   // all the existing pointer marking bits, and re-mark the pointers after sorting.
276   remark_pointers_for_instance_klass(ik, false);
277 
278   // Make sure all supertypes have been sorted
279   sort_methods(ik->java_super());
280   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
281   int len = interfaces->length();
282   for (int i = 0; i < len; i++) {
283     sort_methods(interfaces->at(i));
284   }
285 
286 #ifdef ASSERT
287   if (ik->methods() != nullptr) {
288     for (int m = 0; m < ik->methods()->length(); m++) {
289       Symbol* name = ik->methods()->at(m)->name();
290       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
291     }
292   }
293   if (ik->default_methods() != nullptr) {
294     for (int m = 0; m < ik->default_methods()->length(); m++) {
295       Symbol* name = ik->default_methods()->at(m)->name();
296       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
297     }
298   }
299 #endif
300 
301   Method::sort_methods(ik->methods(), /*set_idnums=*/true, dynamic_dump_method_comparator);
302   if (ik->default_methods() != nullptr) {
303     Method::sort_methods(ik->default_methods(), /*set_idnums=*/false, dynamic_dump_method_comparator);
304   }
305   if (ik->is_linked()) {
306     // If the class has already been linked, we must relayout the i/v tables, whose order depends
307     // on the method sorting order.
308     // If the class is unlinked, we cannot layout the i/v tables yet. This is OK, as the
309     // i/v tables will be initialized at runtime after bytecode verification.
310     ik->vtable().initialize_vtable();
311     ik->itable().initialize_itable();
312   }
313 
314   // Set all the pointer marking bits after sorting.
315   remark_pointers_for_instance_klass(ik, true);
316 }
317 
318 template<bool should_mark>
319 class PointerRemarker: public MetaspaceClosure {
320 public:
321   virtual bool do_ref(Ref* ref, bool read_only) {
322     if (should_mark) {
323       ArchivePtrMarker::mark_pointer(ref->addr());
324     } else {
325       ArchivePtrMarker::clear_pointer(ref->addr());
326     }
327     return false; // don't recurse
328   }
329 };
330 
331 void DynamicArchiveBuilder::remark_pointers_for_instance_klass(InstanceKlass* k, bool should_mark) const {
332   if (should_mark) {
333     PointerRemarker<true> marker;
334     k->metaspace_pointers_do(&marker);
335     marker.finish();
336   } else {
337     PointerRemarker<false> marker;
338     k->metaspace_pointers_do(&marker);
339     marker.finish();
340   }
341 }
342 
343 void DynamicArchiveBuilder::write_archive(char* serialized_data, AOTClassLocationConfig* cl_config) {
344   _header->set_class_location_config(cl_config);
345   _header->set_serialized_data(serialized_data);
346 
347   FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
348   assert(dynamic_info != nullptr, "Sanity");
349 
350   dynamic_info->open_as_output();
351   ArchiveHeapInfo no_heap_for_dynamic_dump;
352   ArchiveBuilder::write_archive(dynamic_info, &no_heap_for_dynamic_dump);
353 
354   address base = _requested_dynamic_archive_bottom;
355   address top  = _requested_dynamic_archive_top;
356   size_t file_size = pointer_delta(top, base, sizeof(char));
357 
358   log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
359                          " [" UINT32_FORMAT " bytes header, %zu bytes total]",
360                          p2i(base), p2i(top), _header->header_size(), file_size);
361 
362   log_info(cds, dynamic)("%d klasses; %d symbols", klasses()->length(), symbols()->length());
363 }
364 
365 void DynamicArchiveBuilder::gather_array_klasses() {
366   for (int i = 0; i < klasses()->length(); i++) {
367     if (klasses()->at(i)->is_objArray_klass()) {
368       ObjArrayKlass* oak = ObjArrayKlass::cast(klasses()->at(i));
369       Klass* elem = oak->element_klass();
370       if (MetaspaceShared::is_shared_static(elem)) {
371         // Only capture the array klass whose element_klass is in the static archive.
372         // During run time, setup (see DynamicArchive::setup_array_klasses()) is needed
373         // so that the element_klass can find its array klasses from the dynamic archive.
374         DynamicArchive::append_array_klass(oak);
375       } else {
376         // The element_klass and its array klasses are in the same archive.
377         assert(!MetaspaceShared::is_shared_static(oak),
378           "we should not gather klasses that are already in the static archive");
379       }
380     }
381   }
382   log_debug(aot)("Total array klasses gathered for dynamic archive: %d", DynamicArchive::num_array_klasses());
383 }
384 
385 class VM_PopulateDynamicDumpSharedSpace: public VM_GC_Sync_Operation {
386   DynamicArchiveBuilder _builder;
387 public:
388   VM_PopulateDynamicDumpSharedSpace(const char* archive_name)
389   : VM_GC_Sync_Operation(), _builder(archive_name) {}
390   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
391   void doit() {
392     ResourceMark rm;
393     if (AllowArchivingWithJavaAgent) {
394       aot_log_warning(aot)("This %s was created with AllowArchivingWithJavaAgent. It should be used "
395                        "for testing purposes only and should not be used in a production environment",
396                        CDSConfig::type_of_archive_being_loaded());
397     }
398     AOTClassLocationConfig::dumptime_check_nonempty_dirs();
399     _builder.doit();
400   }
401   ~VM_PopulateDynamicDumpSharedSpace() {
402     RegeneratedClasses::cleanup();
403   }
404 };
405 
406 // _array_klasses and _dynamic_archive_array_klasses only hold the array klasses
407 // which have element klass in the static archive.
408 GrowableArray<ObjArrayKlass*>* DynamicArchive::_array_klasses = nullptr;
409 Array<ObjArrayKlass*>* DynamicArchive::_dynamic_archive_array_klasses = nullptr;
410 
411 void DynamicArchive::append_array_klass(ObjArrayKlass* ak) {
412   if (_array_klasses == nullptr) {
413     _array_klasses = new (mtClassShared) GrowableArray<ObjArrayKlass*>(50, mtClassShared);
414   }
415   _array_klasses->append(ak);
416 }
417 
418 void DynamicArchive::dump_array_klasses() {
419   assert(CDSConfig::is_dumping_dynamic_archive(), "sanity");
420   if (_array_klasses != nullptr) {
421     ArchiveBuilder* builder = ArchiveBuilder::current();
422     int num_array_klasses = _array_klasses->length();
423     _dynamic_archive_array_klasses =
424         ArchiveBuilder::new_ro_array<ObjArrayKlass*>(num_array_klasses);
425     for (int i = 0; i < num_array_klasses; i++) {
426       builder->write_pointer_in_buffer(_dynamic_archive_array_klasses->adr_at(i), _array_klasses->at(i));
427     }
428   }
429 }
430 
431 void DynamicArchive::setup_array_klasses() {
432   if (_dynamic_archive_array_klasses != nullptr) {
433     for (int i = 0; i < _dynamic_archive_array_klasses->length(); i++) {
434       ObjArrayKlass* oak = _dynamic_archive_array_klasses->at(i);
435       assert(!oak->is_typeArray_klass(), "all type array classes must be in static archive");
436 
437       Klass* elm = oak->element_klass();
438       assert(MetaspaceShared::is_shared_static((void*)elm), "must be");
439 
440       if (elm->is_instance_klass()) {
441         assert(InstanceKlass::cast(elm)->array_klasses() == nullptr, "must be");
442         InstanceKlass::cast(elm)->set_array_klasses(oak);
443       } else {
444         assert(elm->is_array_klass(), "sanity");
445         assert(ArrayKlass::cast(elm)->higher_dimension() == nullptr, "must be");
446         ArrayKlass::cast(elm)->set_higher_dimension(oak);
447       }
448     }
449     log_debug(aot)("Total array klasses read from dynamic archive: %d", _dynamic_archive_array_klasses->length());
450   }
451 }
452 
453 void DynamicArchive::serialize_array_klasses(SerializeClosure* soc) {
454   soc->do_ptr(&_dynamic_archive_array_klasses);
455 }
456 
457 void DynamicArchive::make_array_klasses_shareable() {
458   if (_array_klasses != nullptr) {
459     int num_array_klasses = _array_klasses->length();
460     for (int i = 0; i < num_array_klasses; i++) {
461       ObjArrayKlass* k = ArchiveBuilder::current()->get_buffered_addr(_array_klasses->at(i));
462       k->remove_unshareable_info();
463     }
464   }
465 }
466 
467 void DynamicArchive::post_dump() {
468   if (_array_klasses != nullptr) {
469     delete _array_klasses;
470     _array_klasses = nullptr;
471   }
472 }
473 
474 int DynamicArchive::num_array_klasses() {
475   return _array_klasses != nullptr ? _array_klasses->length() : 0;
476 }
477 
478 void DynamicArchive::dump_impl(bool jcmd_request, const char* archive_name, TRAPS) {
479   MetaspaceShared::link_shared_classes(CHECK);
480   if (!jcmd_request && CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
481     LambdaFormInvokers::regenerate_holder_classes(CHECK);
482   }
483 
484   VM_PopulateDynamicDumpSharedSpace op(archive_name);
485   VMThread::execute(&op);
486 }
487 
488 void DynamicArchive::dump_at_exit(JavaThread* current) {
489   ExceptionMark em(current);
490   ResourceMark rm(current);
491   CDSConfig::DumperThreadMark dumper_thread_mark(current);
492 
493   const char* archive_name = CDSConfig::output_archive_path();
494   if (!CDSConfig::is_dumping_dynamic_archive() || archive_name == nullptr) {
495     return;
496   }
497 
498   log_info(cds, dynamic)("Preparing for dynamic dump at exit in thread %s", current->name());
499 
500   JavaThread* THREAD = current; // For TRAPS processing related to link_shared_classes
501   dump_impl(/*jcmd_request=*/false, archive_name, THREAD);
502   if (HAS_PENDING_EXCEPTION) {
503     // One of the prepatory steps failed
504     oop ex = current->pending_exception();
505     aot_log_error(aot)("Dynamic dump has failed");
506     aot_log_error(aot)("%s: %s", ex->klass()->external_name(),
507                    java_lang_String::as_utf8_string(java_lang_Throwable::message(ex)));
508     CLEAR_PENDING_EXCEPTION;
509     CDSConfig::disable_dumping_dynamic_archive();  // Just for good measure
510   }
511 }
512 
513 // This is called by "jcmd VM.cds dynamic_dump"
514 void DynamicArchive::dump_for_jcmd(const char* archive_name, TRAPS) {
515   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
516   assert(CDSConfig::is_using_archive() && RecordDynamicDumpInfo, "already checked in arguments.cpp");
517   assert(ArchiveClassesAtExit == nullptr, "already checked in arguments.cpp");
518   assert(CDSConfig::is_dumping_dynamic_archive(), "already checked by check_for_dynamic_dump() during VM startup");
519   dump_impl(/*jcmd_request=*/true, archive_name, CHECK);
520 }
521 
522 bool DynamicArchive::validate(FileMapInfo* dynamic_info) {
523   assert(!dynamic_info->is_static(), "must be");
524   // Check if the recorded base archive matches with the current one
525   FileMapInfo* base_info = FileMapInfo::current_info();
526   DynamicArchiveHeader* dynamic_header = dynamic_info->dynamic_header();
527 
528   // Check the header crc
529   if (dynamic_header->base_header_crc() != base_info->crc()) {
530     aot_log_warning(aot)("Dynamic archive cannot be used: static archive header checksum verification failed.");
531     return false;
532   }
533 
534   // Check each space's crc
535   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
536     if (dynamic_header->base_region_crc(i) != base_info->region_crc(i)) {
537       aot_log_warning(aot)("Dynamic archive cannot be used: static archive region #%d checksum verification failed.", i);
538       return false;
539     }
540   }
541 
542   return true;
543 }
544 
545 void DynamicArchiveHeader::print(outputStream* st) {
546   ResourceMark rm;
547 
548   st->print_cr("- base_header_crc:                0x%08x", base_header_crc());
549   for (int i = 0; i < NUM_CDS_REGIONS; i++) {
550     st->print_cr("- base_region_crc[%d]:             0x%08x", i, base_region_crc(i));
551   }
552 }