1 /*
   2  * Copyright (c) 2019, 2020, 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 "jvm.h"
  27 #include "classfile/classLoaderData.inline.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/systemDictionaryShared.hpp"
  31 #include "logging/log.hpp"
  32 #include "memory/archiveUtils.inline.hpp"
  33 #include "memory/dynamicArchive.hpp"
  34 #include "memory/metadataFactory.hpp"
  35 #include "memory/metaspace.hpp"
  36 #include "memory/metaspaceClosure.hpp"
  37 #include "memory/metaspaceShared.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compressedOops.hpp"
  40 #include "oops/objArrayKlass.hpp"
  41 #include "prims/jvmtiRedefineClasses.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/os.inline.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/vmThread.hpp"
  46 #include "runtime/vmOperations.hpp"
  47 #include "utilities/bitMap.inline.hpp"
  48 
  49 #ifndef O_BINARY       // if defined (Win32) use binary files.
  50 #define O_BINARY 0     // otherwise do nothing.
  51 #endif
  52 
  53 class DynamicArchiveBuilder : ResourceObj {
  54   static unsigned my_hash(const address& a) {
  55     return primitive_hash<address>(a);
  56   }
  57   static bool my_equals(const address& a0, const address& a1) {
  58     return primitive_equals<address>(a0, a1);
  59   }
  60   typedef ResourceHashtable<
  61       address, address,
  62       DynamicArchiveBuilder::my_hash,   // solaris compiler doesn't like: primitive_hash<address>
  63       DynamicArchiveBuilder::my_equals, // solaris compiler doesn't like: primitive_equals<address>
  64       16384, ResourceObj::C_HEAP> RelocationTable;
  65   RelocationTable _new_loc_table;
  66 
  67   static intx _buffer_to_target_delta;
  68 
  69   DumpRegion* _current_dump_space;
  70 
  71   static size_t reserve_alignment() {
  72     return os::vm_allocation_granularity();
  73   }
  74 
  75   static const int _total_dump_regions = 3;
  76   int _num_dump_regions_used;
  77 
  78 public:
  79   void mark_pointer(address* ptr_loc) {
  80     ArchivePtrMarker::mark_pointer(ptr_loc);
  81   }
  82 
  83   DumpRegion* current_dump_space() const {
  84     return _current_dump_space;
  85   }
  86 
  87   bool is_in_buffer_space(address p) const {
  88     return (_alloc_bottom <= p && p < (address)current_dump_space()->top());
  89   }
  90 
  91   template <typename T> bool is_in_target_space(T target_obj) const {
  92     address buff_obj = address(target_obj) - _buffer_to_target_delta;
  93     return is_in_buffer_space(buff_obj);
  94   }
  95 
  96   template <typename T> bool is_in_buffer_space(T obj) const {
  97     return is_in_buffer_space(address(obj));
  98   }
  99 
 100   template <typename T> T to_target_no_check(T obj) const {
 101     return (T)(address(obj) + _buffer_to_target_delta);
 102   }
 103 
 104   template <typename T> T to_target(T obj) const {
 105     assert(is_in_buffer_space(obj), "must be");
 106     return (T)(address(obj) + _buffer_to_target_delta);
 107   }
 108 
 109   template <typename T> T get_new_loc(T obj) {
 110     address* pp = _new_loc_table.get((address)obj);
 111     if (pp == NULL) {
 112       // Excluded klasses are not copied
 113       return NULL;
 114     } else {
 115       return (T)*pp;
 116     }
 117   }
 118 
 119   address get_new_loc(MetaspaceClosure::Ref* ref) {
 120     return get_new_loc(ref->obj());
 121   }
 122 
 123   template <typename T> bool has_new_loc(T obj) {
 124     address* pp = _new_loc_table.get((address)obj);
 125     return pp != NULL;
 126   }
 127 
 128   static int dynamic_dump_method_comparator(Method* a, Method* b) {
 129     Symbol* a_name = a->name();
 130     Symbol* b_name = b->name();
 131 
 132     if (a_name == b_name) {
 133       return 0;
 134     }
 135 
 136     if (!MetaspaceShared::is_in_shared_metaspace(a_name)) {
 137       // a_name points to a Symbol in the top archive.
 138       // When this method is called, a_name is still pointing to the output space.
 139       // Translate it to point to the output space, so that it can be compared with
 140       // Symbols in the base archive.
 141       a_name = (Symbol*)(address(a_name) + _buffer_to_target_delta);
 142     }
 143     if (!MetaspaceShared::is_in_shared_metaspace(b_name)) {
 144       b_name = (Symbol*)(address(b_name) + _buffer_to_target_delta);
 145     }
 146 
 147     return a_name->fast_compare(b_name);
 148   }
 149 
 150 protected:
 151   enum FollowMode {
 152     make_a_copy, point_to_it, set_to_null
 153   };
 154 
 155 public:
 156   void copy(MetaspaceClosure::Ref* ref, bool read_only) {
 157     int bytes = ref->size() * BytesPerWord;
 158     address old_obj = ref->obj();
 159     address new_obj = copy_impl(ref, read_only, bytes);
 160 
 161     assert(new_obj != NULL, "must be");
 162     assert(new_obj != old_obj, "must be");
 163     bool isnew = _new_loc_table.put(old_obj, new_obj);
 164     assert(isnew, "must be");
 165   }
 166 
 167   // Make a shallow copy of each eligible MetaspaceObj into the buffer.
 168   class ShallowCopier: public UniqueMetaspaceClosure {
 169     DynamicArchiveBuilder* _builder;
 170     bool _read_only;
 171   public:
 172     ShallowCopier(DynamicArchiveBuilder* shuffler, bool read_only)
 173       : _builder(shuffler), _read_only(read_only) {}
 174 
 175     virtual bool do_unique_ref(Ref* orig_obj, bool read_only) {
 176       // This method gets called on each *original* object
 177       // reachable from _builder->iterate_roots(). Each orig_obj is
 178       // called exactly once.
 179       FollowMode mode = _builder->follow_ref(orig_obj);
 180 
 181       if (mode == point_to_it) {
 182         if (read_only == _read_only) {
 183           log_debug(cds, dynamic)("ptr : " PTR_FORMAT " %s", p2i(orig_obj->obj()),
 184                                   MetaspaceObj::type_name(orig_obj->msotype()));
 185           address p = orig_obj->obj();
 186           bool isnew = _builder->_new_loc_table.put(p, p);
 187           assert(isnew, "must be");
 188         }
 189         return false;
 190       }
 191 
 192       if (mode == set_to_null) {
 193         log_debug(cds, dynamic)("nul : " PTR_FORMAT " %s", p2i(orig_obj->obj()),
 194                                 MetaspaceObj::type_name(orig_obj->msotype()));
 195         return false;
 196       }
 197 
 198       if (read_only == _read_only) {
 199         // Make a shallow copy of orig_obj in a buffer (maintained
 200         // by copy_impl in a subclass of DynamicArchiveBuilder).
 201         _builder->copy(orig_obj, read_only);
 202       }
 203       return true;
 204     }
 205   };
 206 
 207   // Relocate all embedded pointer fields within a MetaspaceObj's shallow copy
 208   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
 209     DynamicArchiveBuilder* _builder;
 210   public:
 211     ShallowCopyEmbeddedRefRelocator(DynamicArchiveBuilder* shuffler)
 212       : _builder(shuffler) {}
 213 
 214     // This method gets called on each *original* object reachable
 215     // from _builder->iterate_roots(). Each orig_obj is
 216     // called exactly once.
 217     virtual bool do_unique_ref(Ref* orig_ref, bool read_only) {
 218       FollowMode mode = _builder->follow_ref(orig_ref);
 219 
 220       if (mode == point_to_it) {
 221         // We did not make a copy of this object
 222         // and we have nothing to update
 223         assert(_builder->get_new_loc(orig_ref) == NULL ||
 224                _builder->get_new_loc(orig_ref) == orig_ref->obj(), "must be");
 225         return false;
 226       }
 227 
 228       if (mode == set_to_null) {
 229         // We did not make a copy of this object
 230         // and we have nothing to update
 231         assert(!_builder->has_new_loc(orig_ref->obj()), "must not be copied or pointed to");
 232         return false;
 233       }
 234 
 235       // - orig_obj points to the original object.
 236       // - new_obj points to the shallow copy (created by ShallowCopier)
 237       //   of orig_obj. new_obj is NULL if the orig_obj is excluded
 238       address orig_obj = orig_ref->obj();
 239       address new_obj  = _builder->get_new_loc(orig_ref);
 240 
 241       assert(new_obj != orig_obj, "must be");
 242 #ifdef ASSERT
 243       if (new_obj == NULL) {
 244         if (orig_ref->msotype() == MetaspaceObj::ClassType) {
 245           Klass* k = (Klass*)orig_obj;
 246           assert(k->is_instance_klass() &&
 247                  SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k)),
 248                  "orig_obj must be excluded Class");
 249         }
 250       }
 251 #endif
 252 
 253       log_debug(cds, dynamic)("Relocating " PTR_FORMAT " %s", p2i(new_obj),
 254                               MetaspaceObj::type_name(orig_ref->msotype()));
 255       if (new_obj != NULL) {
 256         EmbeddedRefUpdater updater(_builder, orig_obj, new_obj);
 257         orig_ref->metaspace_pointers_do(&updater);
 258       }
 259 
 260       return true; // keep recursing until every object is visited exactly once.
 261     }
 262 
 263     virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
 264       // TODO:CDS - JDK-8234693 will consolidate this with an almost identical method in metaspaceShared.cpp
 265       assert_valid(type);
 266       address obj = ref->obj();
 267       address new_obj = _builder->get_new_loc(ref);
 268       size_t offset = pointer_delta(p, obj,  sizeof(u1));
 269       intptr_t* new_p = (intptr_t*)(new_obj + offset);
 270       switch (type) {
 271       case _method_entry_ref:
 272         assert(*p == *new_p, "must be a copy");
 273         break;
 274       case _internal_pointer_ref:
 275         {
 276           size_t off = pointer_delta(*((address*)p), obj, sizeof(u1));
 277           assert(0 <= intx(off) && intx(off) < ref->size() * BytesPerWord, "must point to internal address");
 278           *((address*)new_p) = new_obj + off;
 279         }
 280         break;
 281       default:
 282         ShouldNotReachHere();
 283       }
 284       ArchivePtrMarker::mark_pointer((address*)new_p);
 285     }
 286   };
 287 
 288   class EmbeddedRefUpdater: public MetaspaceClosure {
 289     DynamicArchiveBuilder* _builder;
 290     address _orig_obj;
 291     address _new_obj;
 292   public:
 293     EmbeddedRefUpdater(DynamicArchiveBuilder* shuffler, address orig_obj, address new_obj) :
 294       _builder(shuffler), _orig_obj(orig_obj), _new_obj(new_obj) {}
 295 
 296     // This method gets called once for each pointer field F of orig_obj.
 297     // We update new_obj->F to point to the new location of orig_obj->F.
 298     //
 299     // Example: Klass*  0x100 is copied to 0x400
 300     //          Symbol* 0x200 is copied to 0x500
 301     //
 302     // Let orig_obj == 0x100; and
 303     //     new_obj  == 0x400; and
 304     //     ((Klass*)orig_obj)->_name == 0x200;
 305     // Then this function effectively assigns
 306     //     ((Klass*)new_obj)->_name = 0x500;
 307     virtual bool do_ref(Ref* ref, bool read_only) {
 308       address new_pointee = NULL;
 309 
 310       if (ref->not_null()) {
 311         address old_pointee = ref->obj();
 312 
 313         FollowMode mode = _builder->follow_ref(ref);
 314         if (mode == point_to_it) {
 315           new_pointee = old_pointee;
 316         } else if (mode == set_to_null) {
 317           new_pointee = NULL;
 318         } else {
 319           new_pointee = _builder->get_new_loc(old_pointee);
 320         }
 321       }
 322 
 323       const char* kind = MetaspaceObj::type_name(ref->msotype());
 324       // offset of this field inside the original object
 325       intx offset = (address)ref->addr() - _orig_obj;
 326       _builder->update_pointer((address*)(_new_obj + offset), new_pointee, kind, offset);
 327 
 328       // We can't mark the pointer here, because DynamicArchiveBuilder::sort_methods
 329       // may re-layout the [iv]tables, which would change the offset(s) in an InstanceKlass
 330       // that would contain pointers. Therefore, we must mark the pointers after
 331       // sort_methods(), using PointerMarker.
 332       return false; // Do not recurse.
 333     }
 334   };
 335 
 336   class ExternalRefUpdater: public MetaspaceClosure {
 337     DynamicArchiveBuilder* _builder;
 338 
 339   public:
 340     ExternalRefUpdater(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 341 
 342     virtual bool do_ref(Ref* ref, bool read_only) {
 343       // ref is a pointer that lives OUTSIDE of the buffer, but points to an object inside the buffer
 344       if (ref->not_null()) {
 345         address new_loc = _builder->get_new_loc(ref);
 346         const char* kind = MetaspaceObj::type_name(ref->msotype());
 347         _builder->update_pointer(ref->addr(), new_loc, kind, 0);
 348         _builder->mark_pointer(ref->addr());
 349       }
 350       return false; // Do not recurse.
 351     }
 352   };
 353 
 354   class PointerMarker: public UniqueMetaspaceClosure {
 355     DynamicArchiveBuilder* _builder;
 356 
 357   public:
 358     PointerMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 359 
 360     virtual bool do_unique_ref(Ref* ref, bool read_only) {
 361       if (_builder->is_in_buffer_space(ref->obj())) {
 362         EmbeddedRefMarker ref_marker(_builder);
 363         ref->metaspace_pointers_do(&ref_marker);
 364         return true; // keep recursing until every buffered object is visited exactly once.
 365       } else {
 366         return false;
 367       }
 368     }
 369   };
 370 
 371   class EmbeddedRefMarker: public MetaspaceClosure {
 372     DynamicArchiveBuilder* _builder;
 373 
 374   public:
 375     EmbeddedRefMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 376     virtual bool do_ref(Ref* ref, bool read_only) {
 377       if (ref->not_null()) {
 378         _builder->mark_pointer(ref->addr());
 379       }
 380       return false; // Do not recurse.
 381     }
 382   };
 383 
 384   void update_pointer(address* addr, address value, const char* kind, uintx offset, bool is_mso_pointer=true) {
 385     // Propagate the the mask bits to the new value -- see comments above MetaspaceClosure::obj()
 386     if (is_mso_pointer) {
 387       const uintx FLAG_MASK = 0x03;
 388       uintx mask_bits = uintx(*addr) & FLAG_MASK;
 389       value = (address)(uintx(value) | mask_bits);
 390     }
 391 
 392     if (*addr != value) {
 393       log_debug(cds, dynamic)("Update (%18s*) %3d [" PTR_FORMAT "] " PTR_FORMAT " -> " PTR_FORMAT,
 394                               kind, int(offset), p2i(addr), p2i(*addr), p2i(value));
 395       *addr = value;
 396     }
 397   }
 398 
 399 private:
 400   GrowableArray<Symbol*>* _symbols; // symbols to dump
 401   GrowableArray<InstanceKlass*>* _klasses; // klasses to dump
 402 
 403   void append(InstanceKlass* k) { _klasses->append(k); }
 404   void append(Symbol* s)        { _symbols->append(s); }
 405 
 406   class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 407     DynamicArchiveBuilder* _builder;
 408     bool _read_only;
 409 
 410   public:
 411     GatherKlassesAndSymbols(DynamicArchiveBuilder* builder)
 412       : _builder(builder) {}
 413 
 414     virtual bool do_unique_ref(Ref* ref, bool read_only) {
 415       if (_builder->follow_ref(ref) != make_a_copy) {
 416         return false;
 417       }
 418       if (ref->msotype() == MetaspaceObj::ClassType) {
 419         Klass* klass = (Klass*)ref->obj();
 420         assert(klass->is_klass(), "must be");
 421         if (klass->is_instance_klass()) {
 422           InstanceKlass* ik = InstanceKlass::cast(klass);
 423           assert(!SystemDictionaryShared::is_excluded_class(ik), "must be");
 424           _builder->append(ik);
 425           _builder->_estimated_metsapceobj_bytes += BytesPerWord; // See RunTimeSharedClassInfo::get_for()
 426         }
 427       } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 428         _builder->append((Symbol*)ref->obj());
 429       }
 430 
 431       int bytes = ref->size() * BytesPerWord;
 432       _builder->_estimated_metsapceobj_bytes += bytes;
 433 
 434       return true;
 435     }
 436   };
 437 
 438   FollowMode follow_ref(MetaspaceClosure::Ref *ref) {
 439     address obj = ref->obj();
 440     if (MetaspaceShared::is_in_shared_metaspace(obj)) {
 441       // Don't dump existing shared metadata again.
 442       return point_to_it;
 443     } else if (ref->msotype() == MetaspaceObj::MethodDataType) {
 444       return set_to_null;
 445     } else {
 446       if (ref->msotype() == MetaspaceObj::ClassType) {
 447         Klass* klass = (Klass*)ref->obj();
 448         assert(klass->is_klass(), "must be");
 449         if (klass->is_instance_klass()) {
 450           InstanceKlass* ik = InstanceKlass::cast(klass);
 451           if (SystemDictionaryShared::is_excluded_class(ik)) {
 452             ResourceMark rm;
 453             log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 454             return set_to_null;
 455           }
 456         } else if (klass->is_array_klass()) {
 457           // Don't support archiving of array klasses for now.
 458           ResourceMark rm;
 459           log_debug(cds, dynamic)("Skipping class (array): %s", klass->external_name());
 460           return set_to_null;
 461         }
 462       }
 463 
 464       return make_a_copy;
 465     }
 466   }
 467 
 468   address copy_impl(MetaspaceClosure::Ref* ref, bool read_only, int bytes) {
 469     if (ref->msotype() == MetaspaceObj::ClassType) {
 470       // Save a pointer immediate in front of an InstanceKlass, so
 471       // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
 472       // without building another hashtable. See RunTimeSharedClassInfo::get_for()
 473       // in systemDictionaryShared.cpp.
 474       address obj = ref->obj();
 475       Klass* klass = (Klass*)obj;
 476       if (klass->is_instance_klass()) {
 477         SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 478         current_dump_space()->allocate(sizeof(address), BytesPerWord);
 479       }
 480     }
 481     address p = (address)current_dump_space()->allocate(bytes);
 482     address obj = ref->obj();
 483     log_debug(cds, dynamic)("COPY: " PTR_FORMAT " ==> " PTR_FORMAT " %5d %s",
 484                             p2i(obj), p2i(p), bytes,
 485                             MetaspaceObj::type_name(ref->msotype()));
 486     memcpy(p, obj, bytes);
 487     intptr_t* archived_vtable = MetaspaceShared::get_archived_cpp_vtable(ref->msotype(), p);
 488     if (archived_vtable != NULL) {
 489       update_pointer((address*)p, (address)archived_vtable, "vtb", 0, /*is_mso_pointer*/false);
 490       mark_pointer((address*)p);
 491     }
 492 
 493     return (address)p;
 494   }
 495 
 496   DynamicArchiveHeader *_header;
 497   address _alloc_bottom;
 498   address _last_verified_top;
 499   size_t _other_region_used_bytes;
 500 
 501   // Conservative estimate for number of bytes needed for:
 502   size_t _estimated_metsapceobj_bytes;   // all archived MetsapceObj's.
 503   size_t _estimated_hashtable_bytes;     // symbol table and dictionaries
 504   size_t _estimated_trampoline_bytes;    // method entry trampolines
 505 
 506   size_t estimate_archive_size();
 507   size_t estimate_trampoline_size();
 508   size_t estimate_class_file_size();
 509   address reserve_space_and_init_buffer_to_target_delta();
 510   void init_header(address addr);
 511   void release_header();
 512   void make_trampolines();
 513   void make_klasses_shareable();
 514   void sort_methods(InstanceKlass* ik) const;
 515   void set_symbols_permanent();
 516   void relocate_buffer_to_target();
 517   void write_archive(char* serialized_data);
 518 
 519   void init_first_dump_space(address reserved_bottom) {
 520     DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 521     DumpRegion* rw_space = MetaspaceShared::read_write_dump_space();
 522 
 523     // Use the same MC->RW->RO ordering as in the base archive.
 524     MetaspaceShared::init_shared_dump_space(mc_space);
 525     _current_dump_space = mc_space;
 526     _last_verified_top = reserved_bottom;
 527     _num_dump_regions_used = 1;
 528   }
 529 
 530   void reserve_buffers_for_trampolines() {
 531     size_t n = _estimated_trampoline_bytes;
 532     assert(n >= SharedRuntime::trampoline_size(), "dont want to be empty");
 533     MetaspaceShared::misc_code_space_alloc(n);
 534   }
 535 
 536 public:
 537   DynamicArchiveBuilder() {
 538     _klasses = new (ResourceObj::C_HEAP, mtClass) GrowableArray<InstanceKlass*>(100, mtClass);
 539     _symbols = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Symbol*>(1000, mtClass);
 540 
 541     _estimated_metsapceobj_bytes = 0;
 542     _estimated_hashtable_bytes = 0;
 543     _estimated_trampoline_bytes = 0;
 544 
 545     _num_dump_regions_used = 0;
 546   }
 547 
 548   void start_dump_space(DumpRegion* next) {
 549     address bottom = _last_verified_top;
 550     address top = (address)(current_dump_space()->top());
 551     _other_region_used_bytes += size_t(top - bottom);
 552 
 553     MetaspaceShared::pack_dump_space(current_dump_space(), next, MetaspaceShared::shared_rs());
 554     _current_dump_space = next;
 555     _num_dump_regions_used ++;
 556 
 557     _last_verified_top = (address)(current_dump_space()->top());
 558   }
 559 
 560   void verify_estimate_size(size_t estimate, const char* which) {
 561     address bottom = _last_verified_top;
 562     address top = (address)(current_dump_space()->top());
 563     size_t used = size_t(top - bottom) + _other_region_used_bytes;
 564     int diff = int(estimate) - int(used);
 565 
 566     log_info(cds)("%s estimate = " SIZE_FORMAT " used = " SIZE_FORMAT "; diff = %d bytes", which, estimate, used, diff);
 567     assert(diff >= 0, "Estimate is too small");
 568 
 569     _last_verified_top = top;
 570     _other_region_used_bytes = 0;
 571   }
 572 
 573   // Do this before and after the archive dump to see if any corruption
 574   // is caused by dynamic dumping.
 575   void verify_universe(const char* info) {
 576     if (VerifyBeforeExit) {
 577       log_info(cds)("Verify %s", info);
 578       HandleMark hm;
 579       // Among other things, this ensures that Eden top is correct.
 580       Universe::heap()->prepare_for_verify();
 581       Universe::verify(info);
 582     }
 583   }
 584 
 585   void doit() {
 586     verify_universe("Before CDS dynamic dump");
 587     DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 588     SystemDictionaryShared::check_excluded_classes();
 589 
 590     {
 591       ResourceMark rm;
 592       GatherKlassesAndSymbols gatherer(this);
 593 
 594       SystemDictionaryShared::dumptime_classes_do(&gatherer);
 595       SymbolTable::metaspace_pointers_do(&gatherer);
 596       FileMapInfo::metaspace_pointers_do(&gatherer);
 597 
 598       gatherer.finish();
 599     }
 600 
 601     // rw space starts ...
 602     address reserved_bottom = reserve_space_and_init_buffer_to_target_delta();
 603     init_header(reserved_bottom);
 604 
 605     CHeapBitMap ptrmap;
 606     ArchivePtrMarker::initialize(&ptrmap, (address*)reserved_bottom, (address*)current_dump_space()->top());
 607 
 608     reserve_buffers_for_trampolines();
 609     verify_estimate_size(_estimated_trampoline_bytes, "Trampolines");
 610 
 611     start_dump_space(MetaspaceShared::read_write_dump_space());
 612 
 613     log_info(cds, dynamic)("Copying %d klasses and %d symbols",
 614                            _klasses->length(), _symbols->length());
 615 
 616     {
 617       assert(current_dump_space() == MetaspaceShared::read_write_dump_space(),
 618              "Current dump space is not rw space");
 619       // shallow-copy RW objects, if necessary
 620       ResourceMark rm;
 621       ShallowCopier rw_copier(this, false);
 622       iterate_roots(&rw_copier);
 623     }
 624 
 625     // ro space starts ...
 626     DumpRegion* ro_space = MetaspaceShared::read_only_dump_space();
 627     {
 628       start_dump_space(ro_space);
 629 
 630       // shallow-copy RO objects, if necessary
 631       ResourceMark rm;
 632       ShallowCopier ro_copier(this, true);
 633       iterate_roots(&ro_copier);
 634     }
 635 
 636     {
 637       log_info(cds)("Relocating embedded pointers ... ");
 638       ResourceMark rm;
 639       ShallowCopyEmbeddedRefRelocator emb_reloc(this);
 640       iterate_roots(&emb_reloc);
 641     }
 642 
 643     {
 644       log_info(cds)("Relocating external roots ... ");
 645       ResourceMark rm;
 646       ExternalRefUpdater ext_reloc(this);
 647       iterate_roots(&ext_reloc);
 648     }
 649 
 650     verify_estimate_size(_estimated_metsapceobj_bytes, "MetaspaceObjs");
 651 
 652     char* serialized_data;
 653     {
 654       set_symbols_permanent();
 655 
 656       // Write the symbol table and system dictionaries to the RO space.
 657       // Note that these tables still point to the *original* objects
 658       // (because they were not processed by ExternalRefUpdater), so
 659       // they would need to call DynamicArchive::original_to_target() to
 660       // get the correct addresses.
 661       assert(current_dump_space() == ro_space, "Must be RO space");
 662       SymbolTable::write_to_archive(false);
 663       SystemDictionaryShared::write_to_archive(false);
 664 
 665       serialized_data = ro_space->top();
 666       WriteClosure wc(ro_space);
 667       SymbolTable::serialize_shared_table_header(&wc, false);
 668       SystemDictionaryShared::serialize_dictionary_headers(&wc, false);
 669     }
 670 
 671     verify_estimate_size(_estimated_hashtable_bytes, "Hashtables");
 672 
 673     make_trampolines();
 674     make_klasses_shareable();
 675 
 676     {
 677       log_info(cds)("Adjust lambda proxy class dictionary");
 678       SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 679     }
 680 
 681     {
 682       log_info(cds)("Final relocation of pointers ... ");
 683       ResourceMark rm;
 684       PointerMarker marker(this);
 685       iterate_roots(&marker);
 686       relocate_buffer_to_target();
 687     }
 688 
 689     write_archive(serialized_data);
 690     release_header();
 691 
 692     assert(_num_dump_regions_used == _total_dump_regions, "must be");
 693     verify_universe("After CDS dynamic dump");
 694   }
 695 
 696   void iterate_roots(MetaspaceClosure* it) {
 697     int i;
 698     int num_klasses = _klasses->length();
 699     for (i = 0; i < num_klasses; i++) {
 700       it->push(&_klasses->at(i));
 701     }
 702 
 703     int num_symbols = _symbols->length();
 704     for (i = 0; i < num_symbols; i++) {
 705       it->push(&_symbols->at(i));
 706     }
 707 
 708     FileMapInfo::metaspace_pointers_do(it);
 709 
 710     // Do not call these again, as we have already collected all the classes and symbols
 711     // that we want to archive. Also, these calls would corrupt the tables when
 712     // ExternalRefUpdater is used.
 713     //
 714     // SystemDictionaryShared::dumptime_classes_do(it);
 715     // SymbolTable::metaspace_pointers_do(it);
 716 
 717     it->finish();
 718   }
 719 };
 720 
 721 intx DynamicArchiveBuilder::_buffer_to_target_delta;
 722 
 723 
 724 size_t DynamicArchiveBuilder::estimate_archive_size() {
 725   // size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's
 726   _estimated_hashtable_bytes = 0;
 727   _estimated_hashtable_bytes += SymbolTable::estimate_size_for_archive();
 728   _estimated_hashtable_bytes += SystemDictionaryShared::estimate_size_for_archive();
 729 
 730   _estimated_trampoline_bytes = estimate_trampoline_size();
 731 
 732   size_t total = 0;
 733 
 734   total += _estimated_metsapceobj_bytes;
 735   total += _estimated_hashtable_bytes;
 736   total += _estimated_trampoline_bytes;
 737 
 738   // allow fragmentation at the end of each dump region
 739   total += _total_dump_regions * reserve_alignment();
 740 
 741   return align_up(total, reserve_alignment());
 742 }
 743 
 744 address DynamicArchiveBuilder::reserve_space_and_init_buffer_to_target_delta() {
 745   size_t total = estimate_archive_size();
 746   ReservedSpace rs(total);
 747   if (!rs.is_reserved()) {
 748     log_error(cds, dynamic)("Failed to reserve %d bytes of output buffer.", (int)total);
 749     vm_direct_exit(0);
 750   }
 751 
 752   address buffer_base = (address)rs.base();
 753   log_info(cds, dynamic)("Reserved output buffer space at    : " PTR_FORMAT " [%d bytes]",
 754                          p2i(buffer_base), (int)total);
 755   MetaspaceShared::set_shared_rs(rs);
 756 
 757   // At run time, we will mmap the dynamic archive at target_space_bottom.
 758   // However, at dump time, we may not be able to write into the target_space,
 759   // as it's occupied by dynamically loaded Klasses. So we allocate a buffer
 760   // at an arbitrary location chosen by the OS. We will write all the dynamically
 761   // archived classes into this buffer. At the final stage of dumping, we relocate
 762   // all pointers that are inside the buffer_space to point to their (runtime)
 763   // target location inside thetarget_space.
 764   address target_space_bottom =
 765     (address)align_up(MetaspaceShared::shared_metaspace_top(), reserve_alignment());
 766   _buffer_to_target_delta = intx(target_space_bottom) - intx(buffer_base);
 767 
 768   log_info(cds, dynamic)("Target archive space at            : " PTR_FORMAT, p2i(target_space_bottom));
 769   log_info(cds, dynamic)("Buffer-space to target-space delta : " PTR_FORMAT, p2i((address)_buffer_to_target_delta));
 770 
 771   return buffer_base;
 772 }
 773 
 774 void DynamicArchiveBuilder::init_header(address reserved_bottom) {
 775   _alloc_bottom = reserved_bottom;
 776   _last_verified_top = reserved_bottom;
 777   _other_region_used_bytes = 0;
 778 
 779   init_first_dump_space(reserved_bottom);
 780 
 781   FileMapInfo* mapinfo = new FileMapInfo(false);
 782   assert(FileMapInfo::dynamic_info() == mapinfo, "must be");
 783   _header = mapinfo->dynamic_header();
 784 
 785   Thread* THREAD = Thread::current();
 786   FileMapInfo* base_info = FileMapInfo::current_info();
 787   _header->set_base_header_crc(base_info->crc());
 788   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
 789     _header->set_base_region_crc(i, base_info->space_crc(i));
 790   }
 791   _header->populate(base_info, os::vm_allocation_granularity());
 792 }
 793 
 794 void DynamicArchiveBuilder::release_header() {
 795   // We temporarily allocated a dynamic FileMapInfo for dumping, which makes it appear we
 796   // have mapped a dynamic archive, but we actually have not. We are in a safepoint now.
 797   // Let's free it so that if class loading happens after we leave the safepoint, nothing
 798   // bad will happen.
 799   assert(SafepointSynchronize::is_at_safepoint(), "must be");
 800   FileMapInfo *mapinfo = FileMapInfo::dynamic_info();
 801   assert(mapinfo != NULL && _header == mapinfo->dynamic_header(), "must be");
 802   delete mapinfo;
 803   assert(!DynamicArchive::is_mapped(), "must be");
 804   _header = NULL;
 805 }
 806 
 807 size_t DynamicArchiveBuilder::estimate_trampoline_size() {
 808   size_t total = 0;
 809   size_t each_method_bytes =
 810     align_up(SharedRuntime::trampoline_size(), BytesPerWord) * 3 +
 811     align_up(sizeof(AdapterHandlerEntry*), BytesPerWord);
 812 
 813   for (int i = 0; i < _klasses->length(); i++) {
 814     InstanceKlass* ik = _klasses->at(i);
 815     Array<Method*>* methods = ik->methods();
 816     total += each_method_bytes * methods->length();
 817   }
 818   if (total == 0) {
 819     // We have nothing to archive, but let's avoid having an empty region.
 820     total = SharedRuntime::trampoline_size();
 821   }
 822   return total;
 823 }
 824 
 825 void DynamicArchiveBuilder::make_trampolines() {
 826   DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 827   char* p = mc_space->base();
 828   for (int i = 0; i < _klasses->length(); i++) {
 829     InstanceKlass* ik = _klasses->at(i);
 830     Array<Method*>* methods = ik->methods();
 831     for (int j = 0; j < methods->length(); j++) {
 832       Method* m = methods->at(j);
 833 
 834       // TODO:CDS - JDK-8234693 will consolidate this with Method::unlink()
 835       address c2i_entry_trampoline = (address)p;
 836       p += SharedRuntime::trampoline_size();
 837       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 838       m->set_from_compiled_entry(to_target(c2i_entry_trampoline));
 839 
 840       address c2i_inline_ro_entry_trampoline = (address)p;
 841       p += SharedRuntime::trampoline_size();
 842       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 843       m->set_from_compiled_inline_ro_entry(to_target(c2i_inline_ro_entry_trampoline));
 844 
 845       address c2i_inline_entry_trampoline = (address)p;
 846       p +=  SharedRuntime::trampoline_size();
 847       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 848       m->set_from_compiled_inline_entry(to_target(c2i_inline_entry_trampoline));
 849 
 850       AdapterHandlerEntry** adapter_trampoline =(AdapterHandlerEntry**)p;
 851       p += sizeof(AdapterHandlerEntry*);
 852       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 853       *adapter_trampoline = NULL;
 854       m->set_adapter_trampoline(to_target(adapter_trampoline));
 855     }
 856   }
 857 
 858   guarantee(p <= mc_space->top(), "Estimate of trampoline size is insufficient");
 859 }
 860 
 861 void DynamicArchiveBuilder::make_klasses_shareable() {
 862   int i, count = _klasses->length();
 863 
 864   InstanceKlass::disable_method_binary_search();
 865   for (i = 0; i < count; i++) {
 866     InstanceKlass* ik = _klasses->at(i);
 867     sort_methods(ik);
 868   }
 869 
 870   for (i = 0; i < count; i++) {
 871     InstanceKlass* ik = _klasses->at(i);
 872     ik->assign_class_loader_type();
 873 
 874     MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 875     ik->remove_unshareable_info();
 876 
 877     assert(ik->array_klasses() == NULL, "sanity");
 878 
 879     if (log_is_enabled(Debug, cds, dynamic)) {
 880       ResourceMark rm;
 881       log_debug(cds, dynamic)("klasses[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(ik)), ik->external_name());
 882     }
 883   }
 884 }
 885 
 886 // The address order of the copied Symbols may be different than when the original
 887 // klasses were created. Re-sort all the tables. See Method::sort_methods().
 888 void DynamicArchiveBuilder::sort_methods(InstanceKlass* ik) const {
 889   assert(ik != NULL, "DynamicArchiveBuilder currently doesn't support dumping the base archive");
 890   if (MetaspaceShared::is_in_shared_metaspace(ik)) {
 891     // We have reached a supertype that's already in the base archive
 892     return;
 893   }
 894 
 895   if (ik->java_mirror() == NULL) {
 896     // NULL mirror means this class has already been visited and methods are already sorted
 897     return;
 898   }
 899   ik->remove_java_mirror();
 900 
 901   if (log_is_enabled(Debug, cds, dynamic)) {
 902     ResourceMark rm;
 903     log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " %s", p2i(to_target(ik)), ik->external_name());
 904   }
 905 
 906   // Make sure all supertypes have been sorted
 907   sort_methods(ik->java_super());
 908   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 909   int len = interfaces->length();
 910   for (int i = 0; i < len; i++) {
 911     sort_methods(interfaces->at(i));
 912   }
 913 
 914 #ifdef ASSERT
 915   if (ik->methods() != NULL) {
 916     for (int m = 0; m < ik->methods()->length(); m++) {
 917       Symbol* name = ik->methods()->at(m)->name();
 918       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 919     }
 920   }
 921   if (ik->default_methods() != NULL) {
 922     for (int m = 0; m < ik->default_methods()->length(); m++) {
 923       Symbol* name = ik->default_methods()->at(m)->name();
 924       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 925     }
 926   }
 927 #endif
 928 
 929   Thread* THREAD = Thread::current();
 930   Method::sort_methods(ik->methods(), /*set_idnums=*/true, dynamic_dump_method_comparator);
 931   if (ik->default_methods() != NULL) {
 932     Method::sort_methods(ik->default_methods(), /*set_idnums=*/false, dynamic_dump_method_comparator);
 933   }
 934   ik->vtable().initialize_vtable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
 935   ik->itable().initialize_itable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
 936 }
 937 
 938 void DynamicArchiveBuilder::set_symbols_permanent() {
 939   int count = _symbols->length();
 940   for (int i=0; i<count; i++) {
 941     Symbol* s = _symbols->at(i);
 942     s->set_permanent();
 943 
 944     if (log_is_enabled(Trace, cds, dynamic)) {
 945       ResourceMark rm;
 946       log_trace(cds, dynamic)("symbols[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(s)), s->as_quoted_ascii());
 947     }
 948   }
 949 }
 950 
 951 class RelocateBufferToTarget: public BitMapClosure {
 952   DynamicArchiveBuilder *_builder;
 953   address* _buffer_bottom;
 954   intx _buffer_to_target_delta;
 955  public:
 956   RelocateBufferToTarget(DynamicArchiveBuilder* builder, address* bottom, intx delta) :
 957     _builder(builder), _buffer_bottom(bottom), _buffer_to_target_delta(delta) {}
 958 
 959   bool do_bit(size_t offset) {
 960     address* p = _buffer_bottom + offset;
 961     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
 962 
 963     address old_ptr = *p;
 964     if (_builder->is_in_buffer_space(old_ptr)) {
 965       address new_ptr = old_ptr + _buffer_to_target_delta;
 966       log_trace(cds, dynamic)("Final patch: @%6d [" PTR_FORMAT " -> " PTR_FORMAT "] " PTR_FORMAT " => " PTR_FORMAT,
 967                               (int)offset, p2i(p), p2i(_builder->to_target(p)),
 968                               p2i(old_ptr), p2i(new_ptr));
 969       *p = new_ptr;
 970     }
 971 
 972     return true; // keep iterating
 973   }
 974 };
 975 
 976 void DynamicArchiveBuilder::relocate_buffer_to_target() {
 977   RelocateBufferToTarget patcher(this, (address*)_alloc_bottom, _buffer_to_target_delta);
 978   ArchivePtrMarker::ptrmap()->iterate(&patcher);
 979 
 980   Array<u8>* table = FileMapInfo::saved_shared_path_table().table();
 981   SharedPathTable runtime_table(to_target(table), FileMapInfo::shared_path_table().size());
 982   _header->set_shared_path_table(runtime_table);
 983 
 984   address relocatable_base = (address)SharedBaseAddress;
 985   address relocatable_end = (address)(current_dump_space()->top()) + _buffer_to_target_delta;
 986 
 987   intx addr_delta = MetaspaceShared::final_delta();
 988   if (addr_delta == 0) {
 989     ArchivePtrMarker::compact(relocatable_base, relocatable_end);
 990   } else {
 991     // The base archive is NOT mapped at MetaspaceShared::requested_base_address() (due to ASLR).
 992     // This means that the current content of the dynamic archive is based on a random
 993     // address. Let's relocate all the pointers, so that it can be mapped to
 994     // MetaspaceShared::requested_base_address() without runtime relocation.
 995     //
 996     // Note: both the base and dynamic archive are written with
 997     // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
 998 
 999     // Patch all pointers that are marked by ptrmap within this region,
1000     // where we have just dumped all the metaspace data.
1001     address patch_base = (address)_alloc_bottom;
1002     address patch_end  = (address)current_dump_space()->top();
1003 
1004     // the current value of the pointers to be patched must be within this
1005     // range (i.e., must point to either the top archive (as currently mapped), or to the
1006     // (targeted address of) the top archive)
1007     address valid_old_base = relocatable_base;
1008     address valid_old_end  = relocatable_end;
1009     size_t base_plus_top_size = valid_old_end - valid_old_base;
1010     size_t top_size = patch_end - patch_base;
1011     size_t base_size = base_plus_top_size - top_size;
1012     assert(base_plus_top_size > base_size, "no overflow");
1013     assert(base_plus_top_size > top_size, "no overflow");
1014 
1015     // after patching, the pointers must point inside this range
1016     // (the requested location of the archive, as mapped at runtime).
1017     address valid_new_base = (address)MetaspaceShared::requested_base_address();
1018     address valid_new_end  = valid_new_base + base_plus_top_size;
1019 
1020     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
1021                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "], delta = " INTX_FORMAT " bytes",
1022                    p2i(patch_base + base_size), p2i(patch_end),
1023                    p2i(valid_new_base + base_size), p2i(valid_new_end), addr_delta);
1024 
1025     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1026                                       valid_new_base, valid_new_end, addr_delta, ArchivePtrMarker::ptrmap());
1027     ArchivePtrMarker::ptrmap()->iterate(&patcher);
1028     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1029   }
1030 }
1031 
1032 void DynamicArchiveBuilder::write_archive(char* serialized_data) {
1033   int num_klasses = _klasses->length();
1034   int num_symbols = _symbols->length();
1035 
1036   _header->set_serialized_data(to_target(serialized_data));
1037 
1038   FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
1039   assert(dynamic_info != NULL, "Sanity");
1040 
1041   // Now write the archived data including the file offsets.
1042   const char* archive_name = Arguments::GetSharedDynamicArchivePath();
1043   dynamic_info->open_for_write(archive_name);
1044   MetaspaceShared::write_core_archive_regions(dynamic_info, NULL, NULL);
1045   dynamic_info->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1046   dynamic_info->set_header_crc(dynamic_info->compute_header_crc());
1047   dynamic_info->write_header();
1048   dynamic_info->close();
1049 
1050   address base = to_target(_alloc_bottom);
1051   address top  = address(current_dump_space()->top()) + _buffer_to_target_delta;
1052   size_t file_size = pointer_delta(top, base, sizeof(char));
1053 
1054   base += MetaspaceShared::final_delta();
1055   top += MetaspaceShared::final_delta();
1056   log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
1057                          " [" SIZE_FORMAT " bytes header, " SIZE_FORMAT " bytes total]",
1058                          p2i(base), p2i(top), _header->header_size(), file_size);
1059   log_info(cds, dynamic)("%d klasses; %d symbols", num_klasses, num_symbols);
1060 }
1061 
1062 
1063 class VM_PopulateDynamicDumpSharedSpace: public VM_Operation {
1064   DynamicArchiveBuilder* _builder;
1065 public:
1066   VM_PopulateDynamicDumpSharedSpace(DynamicArchiveBuilder* builder) : _builder(builder) {}
1067   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1068   void doit() {
1069     ResourceMark rm;
1070     if (SystemDictionaryShared::empty_dumptime_table()) {
1071       log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
1072       return;
1073     }
1074     if (AllowArchivingWithJavaAgent) {
1075       warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1076               "for testing purposes only and should not be used in a production environment");
1077     }
1078     FileMapInfo::check_nonempty_dir_in_shared_path_table();
1079 
1080     _builder->doit();
1081   }
1082 };
1083 
1084 
1085 void DynamicArchive::dump() {
1086   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
1087     log_warning(cds, dynamic)("SharedDynamicArchivePath is not specified");
1088     return;
1089   }
1090 
1091   DynamicArchiveBuilder builder;
1092   _builder = &builder;
1093   VM_PopulateDynamicDumpSharedSpace op(&builder);
1094   VMThread::execute(&op);
1095   _builder = NULL;
1096 }
1097 
1098 address DynamicArchive::original_to_buffer_impl(address orig_obj) {
1099   assert(DynamicDumpSharedSpaces, "must be");
1100   address buff_obj = _builder->get_new_loc(orig_obj);
1101   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
1102   assert(buff_obj != orig_obj, "call this only when you know orig_obj must be copied and not just referenced");
1103   assert(_builder->is_in_buffer_space(buff_obj), "must be");
1104   return buff_obj;
1105 }
1106 
1107 address DynamicArchive::buffer_to_target_impl(address buff_obj) {
1108   assert(DynamicDumpSharedSpaces, "must be");
1109   assert(_builder->is_in_buffer_space(buff_obj), "must be");
1110   return _builder->to_target(buff_obj);
1111 }
1112 
1113 address DynamicArchive::original_to_target_impl(address orig_obj) {
1114   assert(DynamicDumpSharedSpaces, "must be");
1115   if (MetaspaceShared::is_in_shared_metaspace(orig_obj)) {
1116     // This happens when the top archive points to a Symbol* in the base archive.
1117     return orig_obj;
1118   }
1119   address buff_obj = _builder->get_new_loc(orig_obj);
1120   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
1121   if (buff_obj == orig_obj) {
1122     // We are storing a pointer to an original object into the dynamic buffer. E.g.,
1123     // a Symbol* that used by both the base and top archives.
1124     assert(MetaspaceShared::is_in_shared_metaspace(orig_obj), "must be");
1125     return orig_obj;
1126   } else {
1127     return _builder->to_target(buff_obj);
1128   }
1129 }
1130 
1131 uintx DynamicArchive::object_delta_uintx(void* buff_obj) {
1132   assert(DynamicDumpSharedSpaces, "must be");
1133   address target_obj = _builder->to_target_no_check(address(buff_obj));
1134   assert(uintx(target_obj) >= SharedBaseAddress, "must be");
1135   return uintx(target_obj) - SharedBaseAddress;
1136 }
1137 
1138 bool DynamicArchive::is_in_target_space(void *obj) {
1139   assert(DynamicDumpSharedSpaces, "must be");
1140   return _builder->is_in_target_space(obj);
1141 }
1142 
1143 
1144 DynamicArchiveBuilder* DynamicArchive::_builder = NULL;
1145 
1146 
1147 bool DynamicArchive::validate(FileMapInfo* dynamic_info) {
1148   assert(!dynamic_info->is_static(), "must be");
1149   // Check if the recorded base archive matches with the current one
1150   FileMapInfo* base_info = FileMapInfo::current_info();
1151   DynamicArchiveHeader* dynamic_header = dynamic_info->dynamic_header();
1152 
1153   // Check the header crc
1154   if (dynamic_header->base_header_crc() != base_info->crc()) {
1155     FileMapInfo::fail_continue("Dynamic archive cannot be used: static archive header checksum verification failed.");
1156     return false;
1157   }
1158 
1159   // Check each space's crc
1160   for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1161     if (dynamic_header->base_region_crc(i) != base_info->space_crc(i)) {
1162       FileMapInfo::fail_continue("Dynamic archive cannot be used: static archive region #%d checksum verification failed.", i);
1163       return false;
1164     }
1165   }
1166 
1167   return true;
1168 }