< prev index next >

src/hotspot/share/memory/dynamicArchive.cpp

Print this page


   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       assert(type == _method_entry_ref, "only special type allowed for now");
 265       address obj = ref->obj();
 266       address new_obj = _builder->get_new_loc(ref);
 267       size_t offset = pointer_delta(p, obj,  sizeof(u1));
 268       intptr_t* new_p = (intptr_t*)(new_obj + offset);
 269       assert(*p == *new_p, "must be a copy");
 270       ArchivePtrMarker::mark_pointer((address*)new_p);
 271     }
 272   };
 273 
 274   class EmbeddedRefUpdater: public MetaspaceClosure {
 275     DynamicArchiveBuilder* _builder;
 276     address _orig_obj;
 277     address _new_obj;
 278   public:
 279     EmbeddedRefUpdater(DynamicArchiveBuilder* shuffler, address orig_obj, address new_obj) :
 280       _builder(shuffler), _orig_obj(orig_obj), _new_obj(new_obj) {}
 281 
 282     // This method gets called once for each pointer field F of orig_obj.
 283     // We update new_obj->F to point to the new location of orig_obj->F.
 284     //
 285     // Example: Klass*  0x100 is copied to 0x400
 286     //          Symbol* 0x200 is copied to 0x500
 287     //
 288     // Let orig_obj == 0x100; and
 289     //     new_obj  == 0x400; and
 290     //     ((Klass*)orig_obj)->_name == 0x200;
 291     // Then this function effectively assigns
 292     //     ((Klass*)new_obj)->_name = 0x500;
 293     virtual bool do_ref(Ref* ref, bool read_only) {
 294       address new_pointee = NULL;
 295 
 296       if (ref->not_null()) {
 297         address old_pointee = ref->obj();
 298 
 299         FollowMode mode = _builder->follow_ref(ref);
 300         if (mode == point_to_it) {
 301           new_pointee = old_pointee;
 302         } else if (mode == set_to_null) {
 303           new_pointee = NULL;
 304         } else {
 305           new_pointee = _builder->get_new_loc(old_pointee);
 306         }
 307       }
 308 
 309       const char* kind = MetaspaceObj::type_name(ref->msotype());
 310       // offset of this field inside the original object
 311       intx offset = (address)ref->addr() - _orig_obj;
 312       _builder->update_pointer((address*)(_new_obj + offset), new_pointee, kind, offset);
 313 
 314       // We can't mark the pointer here, because DynamicArchiveBuilder::sort_methods
 315       // may re-layout the [iv]tables, which would change the offset(s) in an InstanceKlass
 316       // that would contain pointers. Therefore, we must mark the pointers after
 317       // sort_methods(), using PointerMarker.
 318       return false; // Do not recurse.
 319     }
 320   };
 321 
 322   class ExternalRefUpdater: public MetaspaceClosure {
 323     DynamicArchiveBuilder* _builder;
 324 
 325   public:
 326     ExternalRefUpdater(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 327 
 328     virtual bool do_ref(Ref* ref, bool read_only) {
 329       // ref is a pointer that lives OUTSIDE of the buffer, but points to an object inside the buffer
 330       if (ref->not_null()) {
 331         address new_loc = _builder->get_new_loc(ref);
 332         const char* kind = MetaspaceObj::type_name(ref->msotype());
 333         _builder->update_pointer(ref->addr(), new_loc, kind, 0);
 334         _builder->mark_pointer(ref->addr());
 335       }
 336       return false; // Do not recurse.
 337     }
 338   };
 339 
 340   class PointerMarker: public UniqueMetaspaceClosure {
 341     DynamicArchiveBuilder* _builder;
 342 
 343   public:
 344     PointerMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 345 
 346     virtual bool do_unique_ref(Ref* ref, bool read_only) {
 347       if (_builder->is_in_buffer_space(ref->obj())) {
 348         EmbeddedRefMarker ref_marker(_builder);
 349         ref->metaspace_pointers_do(&ref_marker);
 350         return true; // keep recursing until every buffered object is visited exactly once.
 351       } else {
 352         return false;
 353       }
 354     }
 355   };
 356 
 357   class EmbeddedRefMarker: public MetaspaceClosure {
 358     DynamicArchiveBuilder* _builder;
 359 
 360   public:
 361     EmbeddedRefMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
 362     virtual bool do_ref(Ref* ref, bool read_only) {
 363       if (ref->not_null()) {
 364         _builder->mark_pointer(ref->addr());
 365       }
 366       return false; // Do not recurse.
 367     }
 368   };
 369 
 370   void update_pointer(address* addr, address value, const char* kind, uintx offset, bool is_mso_pointer=true) {
 371     // Propagate the the mask bits to the new value -- see comments above MetaspaceClosure::obj()
 372     if (is_mso_pointer) {
 373       const uintx FLAG_MASK = 0x03;
 374       uintx mask_bits = uintx(*addr) & FLAG_MASK;
 375       value = (address)(uintx(value) | mask_bits);
 376     }
 377 
 378     if (*addr != value) {
 379       log_debug(cds, dynamic)("Update (%18s*) %3d [" PTR_FORMAT "] " PTR_FORMAT " -> " PTR_FORMAT,
 380                               kind, int(offset), p2i(addr), p2i(*addr), p2i(value));
 381       *addr = value;
 382     }
 383   }
 384 
 385 private:
 386   GrowableArray<Symbol*>* _symbols; // symbols to dump
 387   GrowableArray<InstanceKlass*>* _klasses; // klasses to dump
 388 
 389   void append(InstanceKlass* k) { _klasses->append(k); }
 390   void append(Symbol* s)        { _symbols->append(s); }
 391 
 392   class GatherKlassesAndSymbols : public UniqueMetaspaceClosure {
 393     DynamicArchiveBuilder* _builder;
 394     bool _read_only;
 395 
 396   public:
 397     GatherKlassesAndSymbols(DynamicArchiveBuilder* builder)
 398       : _builder(builder) {}
 399 
 400     virtual bool do_unique_ref(Ref* ref, bool read_only) {
 401       if (_builder->follow_ref(ref) != make_a_copy) {
 402         return false;
 403       }
 404       if (ref->msotype() == MetaspaceObj::ClassType) {
 405         Klass* klass = (Klass*)ref->obj();
 406         assert(klass->is_klass(), "must be");
 407         if (klass->is_instance_klass()) {
 408           InstanceKlass* ik = InstanceKlass::cast(klass);
 409           assert(!SystemDictionaryShared::is_excluded_class(ik), "must be");
 410           _builder->append(ik);
 411           _builder->_estimated_metsapceobj_bytes += BytesPerWord; // See RunTimeSharedClassInfo::get_for()
 412         }
 413       } else if (ref->msotype() == MetaspaceObj::SymbolType) {
 414         _builder->append((Symbol*)ref->obj());
 415       }
 416 
 417       int bytes = ref->size() * BytesPerWord;
 418       _builder->_estimated_metsapceobj_bytes += bytes;
 419 
 420       return true;
 421     }
 422   };
 423 
 424   FollowMode follow_ref(MetaspaceClosure::Ref *ref) {
 425     address obj = ref->obj();
 426     if (MetaspaceShared::is_in_shared_metaspace(obj)) {
 427       // Don't dump existing shared metadata again.
 428       return point_to_it;
 429     } else if (ref->msotype() == MetaspaceObj::MethodDataType) {
 430       return set_to_null;
 431     } else {
 432       if (ref->msotype() == MetaspaceObj::ClassType) {
 433         Klass* klass = (Klass*)ref->obj();
 434         assert(klass->is_klass(), "must be");
 435         if (klass->is_instance_klass()) {
 436           InstanceKlass* ik = InstanceKlass::cast(klass);
 437           if (SystemDictionaryShared::is_excluded_class(ik)) {
 438             ResourceMark rm;
 439             log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
 440             return set_to_null;
 441           }
 442         } else if (klass->is_array_klass()) {
 443           // Don't support archiving of array klasses for now.
 444           ResourceMark rm;
 445           log_debug(cds, dynamic)("Skipping class (array): %s", klass->external_name());
 446           return set_to_null;
 447         }
 448       }
 449 
 450       return make_a_copy;
 451     }
 452   }
 453 
 454   address copy_impl(MetaspaceClosure::Ref* ref, bool read_only, int bytes) {
 455     if (ref->msotype() == MetaspaceObj::ClassType) {
 456       // Save a pointer immediate in front of an InstanceKlass, so
 457       // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
 458       // without building another hashtable. See RunTimeSharedClassInfo::get_for()
 459       // in systemDictionaryShared.cpp.
 460       address obj = ref->obj();
 461       Klass* klass = (Klass*)obj;
 462       if (klass->is_instance_klass()) {
 463         SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
 464         current_dump_space()->allocate(sizeof(address), BytesPerWord);
 465       }
 466     }
 467     address p = (address)current_dump_space()->allocate(bytes);
 468     address obj = ref->obj();
 469     log_debug(cds, dynamic)("COPY: " PTR_FORMAT " ==> " PTR_FORMAT " %5d %s",
 470                             p2i(obj), p2i(p), bytes,
 471                             MetaspaceObj::type_name(ref->msotype()));
 472     memcpy(p, obj, bytes);
 473     intptr_t* archived_vtable = MetaspaceShared::get_archived_cpp_vtable(ref->msotype(), p);
 474     if (archived_vtable != NULL) {
 475       update_pointer((address*)p, (address)archived_vtable, "vtb", 0, /*is_mso_pointer*/false);
 476       mark_pointer((address*)p);
 477     }
 478 
 479     return (address)p;
 480   }
 481 
 482   DynamicArchiveHeader *_header;
 483   address _alloc_bottom;
 484   address _last_verified_top;
 485   size_t _other_region_used_bytes;
 486 
 487   // Conservative estimate for number of bytes needed for:
 488   size_t _estimated_metsapceobj_bytes;   // all archived MetsapceObj's.
 489   size_t _estimated_hashtable_bytes;     // symbol table and dictionaries
 490   size_t _estimated_trampoline_bytes;    // method entry trampolines
 491 
 492   size_t estimate_archive_size();
 493   size_t estimate_trampoline_size();
 494   size_t estimate_class_file_size();
 495   address reserve_space_and_init_buffer_to_target_delta();
 496   void init_header(address addr);
 497   void release_header();
 498   void make_trampolines();
 499   void make_klasses_shareable();
 500   void sort_methods(InstanceKlass* ik) const;
 501   void set_symbols_permanent();
 502   void relocate_buffer_to_target();
 503   void write_archive(char* serialized_data);
 504 
 505   void init_first_dump_space(address reserved_bottom) {
 506     DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 507     DumpRegion* rw_space = MetaspaceShared::read_write_dump_space();
 508 
 509     // Use the same MC->RW->RO ordering as in the base archive.
 510     MetaspaceShared::init_shared_dump_space(mc_space);
 511     _current_dump_space = mc_space;
 512     _last_verified_top = reserved_bottom;
 513     _num_dump_regions_used = 1;
 514   }
 515 
 516   void reserve_buffers_for_trampolines() {
 517     size_t n = _estimated_trampoline_bytes;
 518     assert(n >= SharedRuntime::trampoline_size(), "dont want to be empty");
 519     MetaspaceShared::misc_code_space_alloc(n);
 520   }
 521 
 522 public:
 523   DynamicArchiveBuilder() {
 524     _klasses = new (ResourceObj::C_HEAP, mtClass) GrowableArray<InstanceKlass*>(100, mtClass);
 525     _symbols = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Symbol*>(1000, mtClass);
 526 
 527     _estimated_metsapceobj_bytes = 0;
 528     _estimated_hashtable_bytes = 0;
 529     _estimated_trampoline_bytes = 0;
 530 
 531     _num_dump_regions_used = 0;
 532   }
 533 
 534   void start_dump_space(DumpRegion* next) {
 535     address bottom = _last_verified_top;
 536     address top = (address)(current_dump_space()->top());
 537     _other_region_used_bytes += size_t(top - bottom);
 538 
 539     MetaspaceShared::pack_dump_space(current_dump_space(), next, MetaspaceShared::shared_rs());
 540     _current_dump_space = next;
 541     _num_dump_regions_used ++;
 542 
 543     _last_verified_top = (address)(current_dump_space()->top());
 544   }
 545 
 546   void verify_estimate_size(size_t estimate, const char* which) {
 547     address bottom = _last_verified_top;


 555     _last_verified_top = top;
 556     _other_region_used_bytes = 0;
 557   }
 558 
 559   // Do this before and after the archive dump to see if any corruption
 560   // is caused by dynamic dumping.
 561   void verify_universe(const char* info) {
 562     if (VerifyBeforeExit) {
 563       log_info(cds)("Verify %s", info);
 564       // Among other things, this ensures that Eden top is correct.
 565       Universe::heap()->prepare_for_verify();
 566       Universe::verify(info);
 567     }
 568   }
 569 
 570   void doit() {
 571     verify_universe("Before CDS dynamic dump");
 572     DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 573     SystemDictionaryShared::check_excluded_classes();
 574 
 575     {
 576       ResourceMark rm;
 577       GatherKlassesAndSymbols gatherer(this);
 578 
 579       SystemDictionaryShared::dumptime_classes_do(&gatherer);
 580       SymbolTable::metaspace_pointers_do(&gatherer);
 581       FileMapInfo::metaspace_pointers_do(&gatherer);
 582 
 583       gatherer.finish();
 584     }
 585 
 586     // rw space starts ...
 587     address reserved_bottom = reserve_space_and_init_buffer_to_target_delta();

 588     init_header(reserved_bottom);
 589 
 590     CHeapBitMap ptrmap;
 591     ArchivePtrMarker::initialize(&ptrmap, (address*)reserved_bottom, (address*)current_dump_space()->top());
 592 
 593     reserve_buffers_for_trampolines();
 594     verify_estimate_size(_estimated_trampoline_bytes, "Trampolines");
 595 

 596     start_dump_space(MetaspaceShared::read_write_dump_space());
 597 
 598     log_info(cds, dynamic)("Copying %d klasses and %d symbols",
 599                            _klasses->length(), _symbols->length());
 600 
 601     {
 602       assert(current_dump_space() == MetaspaceShared::read_write_dump_space(),
 603              "Current dump space is not rw space");
 604       // shallow-copy RW objects, if necessary
 605       ResourceMark rm;
 606       ShallowCopier rw_copier(this, false);
 607       iterate_roots(&rw_copier);
 608     }
 609 
 610     // ro space starts ...
 611     DumpRegion* ro_space = MetaspaceShared::read_only_dump_space();
 612     {
 613       start_dump_space(ro_space);
 614 
 615       // shallow-copy RO objects, if necessary
 616       ResourceMark rm;
 617       ShallowCopier ro_copier(this, true);
 618       iterate_roots(&ro_copier);
 619     }
 620 
 621     {
 622       log_info(cds)("Relocating embedded pointers ... ");
 623       ResourceMark rm;
 624       ShallowCopyEmbeddedRefRelocator emb_reloc(this);
 625       iterate_roots(&emb_reloc);
 626     }
 627 
 628     {
 629       log_info(cds)("Relocating external roots ... ");
 630       ResourceMark rm;
 631       ExternalRefUpdater ext_reloc(this);
 632       iterate_roots(&ext_reloc);
 633     }
 634 
 635     verify_estimate_size(_estimated_metsapceobj_bytes, "MetaspaceObjs");
 636 
 637     char* serialized_data;
 638     {
 639       set_symbols_permanent();
 640 
 641       // Write the symbol table and system dictionaries to the RO space.
 642       // Note that these tables still point to the *original* objects
 643       // (because they were not processed by ExternalRefUpdater), so
 644       // they would need to call DynamicArchive::original_to_target() to
 645       // get the correct addresses.
 646       assert(current_dump_space() == ro_space, "Must be RO space");
 647       SymbolTable::write_to_archive(false);
 648       SystemDictionaryShared::write_to_archive(false);
 649 
 650       serialized_data = ro_space->top();
 651       WriteClosure wc(ro_space);
 652       SymbolTable::serialize_shared_table_header(&wc, false);
 653       SystemDictionaryShared::serialize_dictionary_headers(&wc, false);
 654     }
 655 
 656     verify_estimate_size(_estimated_hashtable_bytes, "Hashtables");
 657 
 658     make_trampolines();


 659     make_klasses_shareable();
 660 
 661     {
 662       log_info(cds)("Adjust lambda proxy class dictionary");
 663       SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 664     }
 665 
 666     {
 667       log_info(cds)("Final relocation of pointers ... ");
 668       ResourceMark rm;
 669       PointerMarker marker(this);
 670       iterate_roots(&marker);
 671       relocate_buffer_to_target();
 672     }
 673 
 674     write_archive(serialized_data);
 675     release_header();
 676 
 677     assert(_num_dump_regions_used == _total_dump_regions, "must be");
 678     verify_universe("After CDS dynamic dump");
 679   }
 680 
 681   void iterate_roots(MetaspaceClosure* it) {
 682     int i;
 683     int num_klasses = _klasses->length();
 684     for (i = 0; i < num_klasses; i++) {
 685       it->push(&_klasses->at(i));
 686     }
 687 
 688     int num_symbols = _symbols->length();
 689     for (i = 0; i < num_symbols; i++) {
 690       it->push(&_symbols->at(i));
 691     }
 692 
 693     FileMapInfo::metaspace_pointers_do(it);
 694 
 695     // Do not call these again, as we have already collected all the classes and symbols
 696     // that we want to archive. Also, these calls would corrupt the tables when
 697     // ExternalRefUpdater is used.
 698     //
 699     // SystemDictionaryShared::dumptime_classes_do(it);
 700     // SymbolTable::metaspace_pointers_do(it);
 701 
 702     it->finish();
 703   }
 704 };
 705 
 706 intx DynamicArchiveBuilder::_buffer_to_target_delta;
 707 
 708 
 709 size_t DynamicArchiveBuilder::estimate_archive_size() {
 710   // size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's
 711   _estimated_hashtable_bytes = 0;
 712   _estimated_hashtable_bytes += SymbolTable::estimate_size_for_archive();
 713   _estimated_hashtable_bytes += SystemDictionaryShared::estimate_size_for_archive();
 714 
 715   _estimated_trampoline_bytes = estimate_trampoline_size();
 716 
 717   size_t total = 0;
 718 
 719   total += _estimated_metsapceobj_bytes;
 720   total += _estimated_hashtable_bytes;
 721   total += _estimated_trampoline_bytes;
 722 
 723   // allow fragmentation at the end of each dump region
 724   total += _total_dump_regions * reserve_alignment();
 725 
 726   return align_up(total, reserve_alignment());
 727 }
 728 


 778 
 779 void DynamicArchiveBuilder::release_header() {
 780   // We temporarily allocated a dynamic FileMapInfo for dumping, which makes it appear we
 781   // have mapped a dynamic archive, but we actually have not. We are in a safepoint now.
 782   // Let's free it so that if class loading happens after we leave the safepoint, nothing
 783   // bad will happen.
 784   assert(SafepointSynchronize::is_at_safepoint(), "must be");
 785   FileMapInfo *mapinfo = FileMapInfo::dynamic_info();
 786   assert(mapinfo != NULL && _header == mapinfo->dynamic_header(), "must be");
 787   delete mapinfo;
 788   assert(!DynamicArchive::is_mapped(), "must be");
 789   _header = NULL;
 790 }
 791 
 792 size_t DynamicArchiveBuilder::estimate_trampoline_size() {
 793   size_t total = 0;
 794   size_t each_method_bytes =
 795     align_up(SharedRuntime::trampoline_size(), BytesPerWord) +
 796     align_up(sizeof(AdapterHandlerEntry*), BytesPerWord);
 797 
 798   for (int i = 0; i < _klasses->length(); i++) {
 799     InstanceKlass* ik = _klasses->at(i);
 800     Array<Method*>* methods = ik->methods();

 801     total += each_method_bytes * methods->length();
 802   }

 803   if (total == 0) {
 804     // We have nothing to archive, but let's avoid having an empty region.
 805     total = SharedRuntime::trampoline_size();
 806   }
 807   return total;
 808 }
 809 
 810 void DynamicArchiveBuilder::make_trampolines() {
 811   DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 812   char* p = mc_space->base();
 813   for (int i = 0; i < _klasses->length(); i++) {
 814     InstanceKlass* ik = _klasses->at(i);




 815     Array<Method*>* methods = ik->methods();
 816     for (int j = 0; j < methods->length(); j++) {
 817       Method* m = methods->at(j);
 818       address c2i_entry_trampoline = (address)p;
 819       p += SharedRuntime::trampoline_size();
 820       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 821       m->set_from_compiled_entry(to_target(c2i_entry_trampoline));
 822 
 823       AdapterHandlerEntry** adapter_trampoline =(AdapterHandlerEntry**)p;
 824       p += sizeof(AdapterHandlerEntry*);
 825       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 826       *adapter_trampoline = NULL;
 827       m->set_adapter_trampoline(to_target(adapter_trampoline));
 828     }
 829   }
 830 
 831   guarantee(p <= mc_space->top(), "Estimate of trampoline size is insufficient");
 832 }
 833 
 834 void DynamicArchiveBuilder::make_klasses_shareable() {
 835   int i, count = _klasses->length();
 836 
 837   InstanceKlass::disable_method_binary_search();
 838   for (i = 0; i < count; i++) {
 839     InstanceKlass* ik = _klasses->at(i);
 840     sort_methods(ik);


 841   }
 842 
 843   for (i = 0; i < count; i++) {
 844     InstanceKlass* ik = _klasses->at(i);




 845     ik->assign_class_loader_type();
 846 
 847     MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 848     ik->remove_unshareable_info();
 849 
 850     assert(ik->array_klasses() == NULL, "sanity");
 851 
 852     if (log_is_enabled(Debug, cds, dynamic)) {
 853       ResourceMark rm;
 854       log_debug(cds, dynamic)("klasses[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(ik)), ik->external_name());
 855     }
 856   }
 857 }
 858 
 859 // The address order of the copied Symbols may be different than when the original
 860 // klasses were created. Re-sort all the tables. See Method::sort_methods().
 861 void DynamicArchiveBuilder::sort_methods(InstanceKlass* ik) const {
 862   assert(ik != NULL, "DynamicArchiveBuilder currently doesn't support dumping the base archive");
 863   if (MetaspaceShared::is_in_shared_metaspace(ik)) {
 864     // We have reached a supertype that's already in the base archive
 865     return;
 866   }
 867 
 868   if (ik->java_mirror() == NULL) {
 869     // NULL mirror means this class has already been visited and methods are already sorted
 870     return;
 871   }
 872   ik->remove_java_mirror();
 873 
 874   if (log_is_enabled(Debug, cds, dynamic)) {
 875     ResourceMark rm;
 876     log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " %s", p2i(to_target(ik)), ik->external_name());
 877   }
 878 





 879   // Make sure all supertypes have been sorted
 880   sort_methods(ik->java_super());
 881   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 882   int len = interfaces->length();
 883   for (int i = 0; i < len; i++) {
 884     sort_methods(interfaces->at(i));
 885   }
 886 
 887 #ifdef ASSERT
 888   if (ik->methods() != NULL) {
 889     for (int m = 0; m < ik->methods()->length(); m++) {
 890       Symbol* name = ik->methods()->at(m)->name();
 891       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 892     }
 893   }
 894   if (ik->default_methods() != NULL) {
 895     for (int m = 0; m < ik->default_methods()->length(); m++) {
 896       Symbol* name = ik->default_methods()->at(m)->name();
 897       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 898     }
 899   }
 900 #endif
 901 
 902   Thread* THREAD = Thread::current();
 903   Method::sort_methods(ik->methods(), /*set_idnums=*/true, dynamic_dump_method_comparator);
 904   if (ik->default_methods() != NULL) {
 905     Method::sort_methods(ik->default_methods(), /*set_idnums=*/false, dynamic_dump_method_comparator);
 906   }
 907   ik->vtable().initialize_vtable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
 908   ik->itable().initialize_itable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
 909 }
 910 
 911 void DynamicArchiveBuilder::set_symbols_permanent() {
 912   int count = _symbols->length();
 913   for (int i=0; i<count; i++) {
 914     Symbol* s = _symbols->at(i);
 915     s->set_permanent();
 916 
 917     if (log_is_enabled(Trace, cds, dynamic)) {
 918       ResourceMark rm;
 919       log_trace(cds, dynamic)("symbols[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(s)), s->as_quoted_ascii());





 920     }













 921   }
 922 }
 923 
 924 class RelocateBufferToTarget: public BitMapClosure {
 925   DynamicArchiveBuilder *_builder;
 926   address* _buffer_bottom;
 927   intx _buffer_to_target_delta;
 928  public:
 929   RelocateBufferToTarget(DynamicArchiveBuilder* builder, address* bottom, intx delta) :
 930     _builder(builder), _buffer_bottom(bottom), _buffer_to_target_delta(delta) {}
 931 
 932   bool do_bit(size_t offset) {
 933     address* p = _buffer_bottom + offset;
 934     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
 935 
 936     address old_ptr = *p;
 937     if (_builder->is_in_buffer_space(old_ptr)) {
 938       address new_ptr = old_ptr + _buffer_to_target_delta;
 939       log_trace(cds, dynamic)("Final patch: @%6d [" PTR_FORMAT " -> " PTR_FORMAT "] " PTR_FORMAT " => " PTR_FORMAT,
 940                               (int)offset, p2i(p), p2i(_builder->to_target(p)),


 986     assert(base_plus_top_size > top_size, "no overflow");
 987 
 988     // after patching, the pointers must point inside this range
 989     // (the requested location of the archive, as mapped at runtime).
 990     address valid_new_base = (address)MetaspaceShared::requested_base_address();
 991     address valid_new_end  = valid_new_base + base_plus_top_size;
 992 
 993     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
 994                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "], delta = " INTX_FORMAT " bytes",
 995                    p2i(patch_base + base_size), p2i(patch_end),
 996                    p2i(valid_new_base + base_size), p2i(valid_new_end), addr_delta);
 997 
 998     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
 999                                       valid_new_base, valid_new_end, addr_delta, ArchivePtrMarker::ptrmap());
1000     ArchivePtrMarker::ptrmap()->iterate(&patcher);
1001     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1002   }
1003 }
1004 
1005 void DynamicArchiveBuilder::write_archive(char* serialized_data) {
1006   int num_klasses = _klasses->length();
1007   int num_symbols = _symbols->length();
1008 
1009   _header->set_serialized_data(to_target(serialized_data));
1010 
1011   FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
1012   assert(dynamic_info != NULL, "Sanity");
1013 
1014   // Now write the archived data including the file offsets.
1015   const char* archive_name = Arguments::GetSharedDynamicArchivePath();
1016   dynamic_info->open_for_write(archive_name);
1017   MetaspaceShared::write_core_archive_regions(dynamic_info, NULL, NULL);
1018   dynamic_info->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1019   dynamic_info->set_header_crc(dynamic_info->compute_header_crc());
1020   dynamic_info->write_header();
1021   dynamic_info->close();
1022 
1023   address base = to_target(_alloc_bottom);
1024   address top  = address(current_dump_space()->top()) + _buffer_to_target_delta;
1025   size_t file_size = pointer_delta(top, base, sizeof(char));
1026 
1027   base += MetaspaceShared::final_delta();
1028   top += MetaspaceShared::final_delta();
1029   log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
1030                          " [" SIZE_FORMAT " bytes header, " SIZE_FORMAT " bytes total]",
1031                          p2i(base), p2i(top), _header->header_size(), file_size);
1032   log_info(cds, dynamic)("%d klasses; %d symbols", num_klasses, num_symbols);
1033 }
1034 
1035 
1036 class VM_PopulateDynamicDumpSharedSpace: public VM_Operation {
1037   DynamicArchiveBuilder* _builder;
1038 public:
1039   VM_PopulateDynamicDumpSharedSpace(DynamicArchiveBuilder* builder) : _builder(builder) {}
1040   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1041   void doit() {
1042     ResourceMark rm;
1043     if (SystemDictionaryShared::empty_dumptime_table()) {
1044       log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
1045       return;
1046     }
1047     if (AllowArchivingWithJavaAgent) {
1048       warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1049               "for testing purposes only and should not be used in a production environment");
1050     }
1051     FileMapInfo::check_nonempty_dir_in_shared_path_table();
1052 
1053     _builder->doit();
1054   }
1055 };
1056 
1057 
1058 void DynamicArchive::dump() {
1059   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
1060     log_warning(cds, dynamic)("SharedDynamicArchivePath is not specified");
1061     return;
1062   }
1063 
1064   DynamicArchiveBuilder builder;
1065   _builder = &builder;
1066   VM_PopulateDynamicDumpSharedSpace op(&builder);
1067   VMThread::execute(&op);
1068   _builder = NULL;
1069 }
1070 
1071 address DynamicArchive::original_to_buffer_impl(address orig_obj) {
1072   assert(DynamicDumpSharedSpaces, "must be");
1073   address buff_obj = _builder->get_new_loc(orig_obj);
1074   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
1075   assert(buff_obj != orig_obj, "call this only when you know orig_obj must be copied and not just referenced");
1076   assert(_builder->is_in_buffer_space(buff_obj), "must be");
1077   return buff_obj;
1078 }
1079 
1080 address DynamicArchive::buffer_to_target_impl(address buff_obj) {
1081   assert(DynamicDumpSharedSpaces, "must be");
1082   assert(_builder->is_in_buffer_space(buff_obj), "must be");
1083   return _builder->to_target(buff_obj);
1084 }
1085 
1086 address DynamicArchive::original_to_target_impl(address orig_obj) {
1087   assert(DynamicDumpSharedSpaces, "must be");
1088   if (MetaspaceShared::is_in_shared_metaspace(orig_obj)) {
1089     // This happens when the top archive points to a Symbol* in the base archive.
1090     return orig_obj;
1091   }
1092   address buff_obj = _builder->get_new_loc(orig_obj);
1093   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
1094   if (buff_obj == orig_obj) {
1095     // We are storing a pointer to an original object into the dynamic buffer. E.g.,
1096     // a Symbol* that used by both the base and top archives.
1097     assert(MetaspaceShared::is_in_shared_metaspace(orig_obj), "must be");
1098     return orig_obj;
1099   } else {
1100     return _builder->to_target(buff_obj);
1101   }
1102 }
1103 
1104 uintx DynamicArchive::object_delta_uintx(void* buff_obj) {
1105   assert(DynamicDumpSharedSpaces, "must be");
1106   address target_obj = _builder->to_target_no_check(address(buff_obj));
1107   assert(uintx(target_obj) >= SharedBaseAddress, "must be");
1108   return uintx(target_obj) - SharedBaseAddress;
1109 }
1110 
1111 bool DynamicArchive::is_in_target_space(void *obj) {
1112   assert(DynamicDumpSharedSpaces, "must be");




   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/systemDictionaryShared.hpp"
  30 #include "logging/log.hpp"
  31 #include "memory/archiveBuilder.hpp"
  32 #include "memory/archiveUtils.inline.hpp"
  33 #include "memory/dynamicArchive.hpp"


  34 #include "memory/metaspaceClosure.hpp"
  35 #include "memory/metaspaceShared.hpp"
  36 #include "memory/resourceArea.hpp"




  37 #include "runtime/os.inline.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 #include "runtime/vmThread.hpp"
  40 #include "runtime/vmOperations.hpp"
  41 #include "utilities/align.hpp"
  42 #include "utilities/bitMap.inline.hpp"
  43 

















  44 
  45 class DynamicArchiveBuilder : public ArchiveBuilder {
  46 public:
  47   static intx _buffer_to_target_delta;

  48   DumpRegion* _current_dump_space;
  49 
  50   static size_t reserve_alignment() {
  51     return os::vm_allocation_granularity();
  52   }
  53 
  54   static const int _total_dump_regions = 3;
  55   int _num_dump_regions_used;
  56 
  57 public:
  58   void mark_pointer(address* ptr_loc) {
  59     ArchivePtrMarker::mark_pointer(ptr_loc);
  60   }
  61 
  62   DumpRegion* current_dump_space() const {
  63     return _current_dump_space;
  64   }
  65 
  66   bool is_in_buffer_space(address p) const {
  67     return (_alloc_bottom <= p && p < (address)current_dump_space()->top());
  68   }
  69 
  70   template <typename T> bool is_in_target_space(T target_obj) const {
  71     address buff_obj = address(target_obj) - _buffer_to_target_delta;
  72     return is_in_buffer_space(buff_obj);
  73   }
  74 
  75   template <typename T> bool is_in_buffer_space(T obj) const {
  76     return is_in_buffer_space(address(obj));
  77   }
  78 
  79   template <typename T> T to_target_no_check(T obj) const {
  80     return (T)(address(obj) + _buffer_to_target_delta);
  81   }
  82 
  83   template <typename T> T to_target(T obj) const {
  84     assert(is_in_buffer_space(obj), "must be");
  85     return (T)(address(obj) + _buffer_to_target_delta);
  86   }
  87 
  88   template <typename T> T get_dumped_addr(T obj) {
  89     return (T)ArchiveBuilder::get_dumped_addr((address)obj);















  90   }
  91 
  92   static int dynamic_dump_method_comparator(Method* a, Method* b) {
  93     Symbol* a_name = a->name();
  94     Symbol* b_name = b->name();
  95 
  96     if (a_name == b_name) {
  97       return 0;
  98     }
  99 
 100     if (!MetaspaceShared::is_in_shared_metaspace(a_name)) {
 101       // a_name points to a Symbol in the top archive.
 102       // When this method is called, a_name is still pointing to the output space.
 103       // Translate it to point to the output space, so that it can be compared with
 104       // Symbols in the base archive.
 105       a_name = (Symbol*)(address(a_name) + _buffer_to_target_delta);
 106     }
 107     if (!MetaspaceShared::is_in_shared_metaspace(b_name)) {
 108       b_name = (Symbol*)(address(b_name) + _buffer_to_target_delta);
 109     }
 110 
 111     return a_name->fast_compare(b_name);
 112   }
 113 





 114 public:






































































































































































































































































































































 115   DynamicArchiveHeader *_header;
 116   address _alloc_bottom;
 117   address _last_verified_top;
 118   size_t _other_region_used_bytes;
 119 
 120   // Conservative estimate for number of bytes needed for:

 121   size_t _estimated_hashtable_bytes;     // symbol table and dictionaries
 122   size_t _estimated_trampoline_bytes;    // method entry trampolines
 123 
 124   size_t estimate_archive_size();
 125   size_t estimate_trampoline_size();
 126   size_t estimate_class_file_size();
 127   address reserve_space_and_init_buffer_to_target_delta();
 128   void init_header(address addr);
 129   void release_header();
 130   void make_trampolines();
 131   void make_klasses_shareable();
 132   void sort_methods(InstanceKlass* ik) const;
 133   void remark_pointers_for_instance_klass(InstanceKlass* k, bool should_mark) const;
 134   void relocate_buffer_to_target();
 135   void write_archive(char* serialized_data);
 136 
 137   void init_first_dump_space(address reserved_bottom) {
 138     DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 139     DumpRegion* rw_space = MetaspaceShared::read_write_dump_space();
 140 
 141     // Use the same MC->RW->RO ordering as in the base archive.
 142     MetaspaceShared::init_shared_dump_space(mc_space);
 143     _current_dump_space = mc_space;
 144     _last_verified_top = reserved_bottom;
 145     _num_dump_regions_used = 1;
 146   }
 147 
 148   void reserve_buffers_for_trampolines() {
 149     size_t n = _estimated_trampoline_bytes;
 150     assert(n >= SharedRuntime::trampoline_size(), "dont want to be empty");
 151     MetaspaceShared::misc_code_space_alloc(n);
 152   }
 153 
 154 public:
 155   DynamicArchiveBuilder() : ArchiveBuilder(NULL, NULL) {




 156     _estimated_hashtable_bytes = 0;
 157     _estimated_trampoline_bytes = 0;
 158 
 159     _num_dump_regions_used = 0;
 160   }
 161 
 162   void start_dump_space(DumpRegion* next) {
 163     address bottom = _last_verified_top;
 164     address top = (address)(current_dump_space()->top());
 165     _other_region_used_bytes += size_t(top - bottom);
 166 
 167     MetaspaceShared::pack_dump_space(current_dump_space(), next, MetaspaceShared::shared_rs());
 168     _current_dump_space = next;
 169     _num_dump_regions_used ++;
 170 
 171     _last_verified_top = (address)(current_dump_space()->top());
 172   }
 173 
 174   void verify_estimate_size(size_t estimate, const char* which) {
 175     address bottom = _last_verified_top;


 183     _last_verified_top = top;
 184     _other_region_used_bytes = 0;
 185   }
 186 
 187   // Do this before and after the archive dump to see if any corruption
 188   // is caused by dynamic dumping.
 189   void verify_universe(const char* info) {
 190     if (VerifyBeforeExit) {
 191       log_info(cds)("Verify %s", info);
 192       // Among other things, this ensures that Eden top is correct.
 193       Universe::heap()->prepare_for_verify();
 194       Universe::verify(info);
 195     }
 196   }
 197 
 198   void doit() {
 199     verify_universe("Before CDS dynamic dump");
 200     DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 201     SystemDictionaryShared::check_excluded_classes();
 202 
 203     gather_klasses_and_symbols();









 204 
 205     // rw space starts ...
 206     address reserved_bottom = reserve_space_and_init_buffer_to_target_delta();
 207     set_dump_regions(MetaspaceShared::read_write_dump_space(), MetaspaceShared::read_only_dump_space());
 208     init_header(reserved_bottom);
 209 
 210     CHeapBitMap ptrmap;
 211     ArchivePtrMarker::initialize(&ptrmap, (address*)reserved_bottom, (address*)current_dump_space()->top());
 212 
 213     reserve_buffers_for_trampolines();
 214     verify_estimate_size(_estimated_trampoline_bytes, "Trampolines");
 215 
 216     gather_source_objs();
 217     start_dump_space(MetaspaceShared::read_write_dump_space());
 218 
 219     log_info(cds, dynamic)("Copying %d klasses and %d symbols",
 220                            klasses()->length(), symbols()->length());
 221 
 222     dump_rw_region();







 223 
 224     // ro space starts ...
 225     DumpRegion* ro_space = MetaspaceShared::read_only_dump_space();

 226     start_dump_space(ro_space);
 227     dump_ro_region();
 228     relocate_pointers();


















 229 
 230     verify_estimate_size(_estimated_metsapceobj_bytes, "MetaspaceObjs");
 231 
 232     char* serialized_data;
 233     {


 234       // Write the symbol table and system dictionaries to the RO space.
 235       // Note that these tables still point to the *original* objects, so

 236       // they would need to call DynamicArchive::original_to_target() to
 237       // get the correct addresses.
 238       assert(current_dump_space() == ro_space, "Must be RO space");
 239       SymbolTable::write_to_archive(false);
 240       SystemDictionaryShared::write_to_archive(false);
 241 
 242       serialized_data = ro_space->top();
 243       WriteClosure wc(ro_space);
 244       SymbolTable::serialize_shared_table_header(&wc, false);
 245       SystemDictionaryShared::serialize_dictionary_headers(&wc, false);
 246     }
 247 
 248     verify_estimate_size(_estimated_hashtable_bytes, "Hashtables");
 249 
 250     make_trampolines();
 251 
 252     log_info(cds)("Make classes shareable");
 253     make_klasses_shareable();
 254 

 255     log_info(cds)("Adjust lambda proxy class dictionary");
 256     SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();

 257 

 258     log_info(cds)("Final relocation of pointers ... ");



 259     relocate_buffer_to_target();

 260 
 261     write_archive(serialized_data);
 262     release_header();
 263 
 264     assert(_num_dump_regions_used == _total_dump_regions, "must be");
 265     verify_universe("After CDS dynamic dump");
 266   }
 267 
 268   virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
 269     if (!is_relocating_pointers) {
 270       SystemDictionaryShared::dumptime_classes_do(it);
 271       SymbolTable::metaspace_pointers_do(it);

 272     }






 273     FileMapInfo::metaspace_pointers_do(it);









 274   }
 275 };
 276 
 277 intx DynamicArchiveBuilder::_buffer_to_target_delta;
 278 

 279 size_t DynamicArchiveBuilder::estimate_archive_size() {
 280   // size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's
 281   _estimated_hashtable_bytes = 0;
 282   _estimated_hashtable_bytes += SymbolTable::estimate_size_for_archive();
 283   _estimated_hashtable_bytes += SystemDictionaryShared::estimate_size_for_archive();
 284 
 285   _estimated_trampoline_bytes = estimate_trampoline_size();
 286 
 287   size_t total = 0;
 288 
 289   total += _estimated_metsapceobj_bytes;
 290   total += _estimated_hashtable_bytes;
 291   total += _estimated_trampoline_bytes;
 292 
 293   // allow fragmentation at the end of each dump region
 294   total += _total_dump_regions * reserve_alignment();
 295 
 296   return align_up(total, reserve_alignment());
 297 }
 298 


 348 
 349 void DynamicArchiveBuilder::release_header() {
 350   // We temporarily allocated a dynamic FileMapInfo for dumping, which makes it appear we
 351   // have mapped a dynamic archive, but we actually have not. We are in a safepoint now.
 352   // Let's free it so that if class loading happens after we leave the safepoint, nothing
 353   // bad will happen.
 354   assert(SafepointSynchronize::is_at_safepoint(), "must be");
 355   FileMapInfo *mapinfo = FileMapInfo::dynamic_info();
 356   assert(mapinfo != NULL && _header == mapinfo->dynamic_header(), "must be");
 357   delete mapinfo;
 358   assert(!DynamicArchive::is_mapped(), "must be");
 359   _header = NULL;
 360 }
 361 
 362 size_t DynamicArchiveBuilder::estimate_trampoline_size() {
 363   size_t total = 0;
 364   size_t each_method_bytes =
 365     align_up(SharedRuntime::trampoline_size(), BytesPerWord) +
 366     align_up(sizeof(AdapterHandlerEntry*), BytesPerWord);
 367 
 368   for (int i = 0; i < klasses()->length(); i++) {
 369     Klass* k = klasses()->at(i);
 370     if (k->is_instance_klass()) {
 371       Array<Method*>* methods = InstanceKlass::cast(k)->methods();
 372       total += each_method_bytes * methods->length();
 373     }
 374   }
 375   if (total == 0) {
 376     // We have nothing to archive, but let's avoid having an empty region.
 377     total = SharedRuntime::trampoline_size();
 378   }
 379   return total;
 380 }
 381 
 382 void DynamicArchiveBuilder::make_trampolines() {
 383   DumpRegion* mc_space = MetaspaceShared::misc_code_dump_space();
 384   char* p = mc_space->base();
 385   for (int i = 0; i < klasses()->length(); i++) {
 386     Klass* k = klasses()->at(i);
 387     if (!k->is_instance_klass()) {
 388       continue;
 389     }
 390     InstanceKlass* ik = InstanceKlass::cast(k);
 391     Array<Method*>* methods = ik->methods();
 392     for (int j = 0; j < methods->length(); j++) {
 393       Method* m = methods->at(j);
 394       address c2i_entry_trampoline = (address)p;
 395       p += SharedRuntime::trampoline_size();
 396       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 397       m->set_from_compiled_entry(to_target(c2i_entry_trampoline));
 398 
 399       AdapterHandlerEntry** adapter_trampoline =(AdapterHandlerEntry**)p;
 400       p += sizeof(AdapterHandlerEntry*);
 401       assert(p >= mc_space->base() && p <= mc_space->top(), "must be");
 402       *adapter_trampoline = NULL;
 403       m->set_adapter_trampoline(to_target(adapter_trampoline));
 404     }
 405   }
 406 
 407   guarantee(p <= mc_space->top(), "Estimate of trampoline size is insufficient");
 408 }
 409 
 410 void DynamicArchiveBuilder::make_klasses_shareable() {
 411   int i, count = klasses()->length();
 412 
 413   InstanceKlass::disable_method_binary_search();
 414   for (i = 0; i < count; i++) {
 415     Klass* k = klasses()->at(i);
 416     if (k->is_instance_klass()) {
 417       sort_methods(InstanceKlass::cast(k));
 418     }
 419   }
 420 
 421   for (i = 0; i < count; i++) {
 422     Klass* k = klasses()->at(i);
 423     if (!k->is_instance_klass()) {
 424       continue;
 425     }
 426     InstanceKlass* ik = InstanceKlass::cast(k);
 427     ik->assign_class_loader_type();
 428 
 429     MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
 430     ik->remove_unshareable_info();
 431 
 432     assert(ik->array_klasses() == NULL, "sanity");
 433 
 434     if (log_is_enabled(Debug, cds, dynamic)) {
 435       ResourceMark rm;
 436       log_debug(cds, dynamic)("klasses[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(ik)), ik->external_name());
 437     }
 438   }
 439 }
 440 
 441 // The address order of the copied Symbols may be different than when the original
 442 // klasses were created. Re-sort all the tables. See Method::sort_methods().
 443 void DynamicArchiveBuilder::sort_methods(InstanceKlass* ik) const {
 444   assert(ik != NULL, "DynamicArchiveBuilder currently doesn't support dumping the base archive");
 445   if (MetaspaceShared::is_in_shared_metaspace(ik)) {
 446     // We have reached a supertype that's already in the base archive
 447     return;
 448   }
 449 
 450   if (ik->java_mirror() == NULL) {
 451     // NULL mirror means this class has already been visited and methods are already sorted
 452     return;
 453   }
 454   ik->remove_java_mirror();
 455 
 456   if (log_is_enabled(Debug, cds, dynamic)) {
 457     ResourceMark rm;
 458     log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " %s", p2i(to_target(ik)), ik->external_name());
 459   }
 460 
 461   // Method sorting may re-layout the [iv]tables, which would change the offset(s)
 462   // of the locations in an InstanceKlass that would contain pointers. Let's clear
 463   // all the existing pointer marking bits, and re-mark the pointers after sorting.
 464   remark_pointers_for_instance_klass(ik, false);
 465 
 466   // Make sure all supertypes have been sorted
 467   sort_methods(ik->java_super());
 468   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 469   int len = interfaces->length();
 470   for (int i = 0; i < len; i++) {
 471     sort_methods(interfaces->at(i));
 472   }
 473 
 474 #ifdef ASSERT
 475   if (ik->methods() != NULL) {
 476     for (int m = 0; m < ik->methods()->length(); m++) {
 477       Symbol* name = ik->methods()->at(m)->name();
 478       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 479     }
 480   }
 481   if (ik->default_methods() != NULL) {
 482     for (int m = 0; m < ik->default_methods()->length(); m++) {
 483       Symbol* name = ik->default_methods()->at(m)->name();
 484       assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
 485     }
 486   }
 487 #endif
 488 
 489   Thread* THREAD = Thread::current();
 490   Method::sort_methods(ik->methods(), /*set_idnums=*/true, dynamic_dump_method_comparator);
 491   if (ik->default_methods() != NULL) {
 492     Method::sort_methods(ik->default_methods(), /*set_idnums=*/false, dynamic_dump_method_comparator);
 493   }
 494   ik->vtable().initialize_vtable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
 495   ik->itable().initialize_itable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");

 496 
 497   // Set all the pointer marking bits after sorting.
 498   remark_pointers_for_instance_klass(ik, true);
 499 }


 500 
 501 template<bool should_mark>
 502 class PointerRemarker: public MetaspaceClosure {
 503 public:
 504   virtual bool do_ref(Ref* ref, bool read_only) {
 505     if (should_mark) {
 506       ArchivePtrMarker::mark_pointer(ref->addr());
 507     } else {
 508       ArchivePtrMarker::clear_pointer(ref->addr());
 509     }
 510     return false; // don't recurse
 511   }
 512 };
 513 
 514 void DynamicArchiveBuilder::remark_pointers_for_instance_klass(InstanceKlass* k, bool should_mark) const {
 515   if (should_mark) {
 516     PointerRemarker<true> marker;
 517     k->metaspace_pointers_do(&marker);
 518     marker.finish();
 519   } else {
 520     PointerRemarker<false> marker;
 521     k->metaspace_pointers_do(&marker);
 522     marker.finish();
 523   }
 524 }
 525 
 526 class RelocateBufferToTarget: public BitMapClosure {
 527   DynamicArchiveBuilder *_builder;
 528   address* _buffer_bottom;
 529   intx _buffer_to_target_delta;
 530  public:
 531   RelocateBufferToTarget(DynamicArchiveBuilder* builder, address* bottom, intx delta) :
 532     _builder(builder), _buffer_bottom(bottom), _buffer_to_target_delta(delta) {}
 533 
 534   bool do_bit(size_t offset) {
 535     address* p = _buffer_bottom + offset;
 536     assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
 537 
 538     address old_ptr = *p;
 539     if (_builder->is_in_buffer_space(old_ptr)) {
 540       address new_ptr = old_ptr + _buffer_to_target_delta;
 541       log_trace(cds, dynamic)("Final patch: @%6d [" PTR_FORMAT " -> " PTR_FORMAT "] " PTR_FORMAT " => " PTR_FORMAT,
 542                               (int)offset, p2i(p), p2i(_builder->to_target(p)),


 588     assert(base_plus_top_size > top_size, "no overflow");
 589 
 590     // after patching, the pointers must point inside this range
 591     // (the requested location of the archive, as mapped at runtime).
 592     address valid_new_base = (address)MetaspaceShared::requested_base_address();
 593     address valid_new_end  = valid_new_base + base_plus_top_size;
 594 
 595     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
 596                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT "], delta = " INTX_FORMAT " bytes",
 597                    p2i(patch_base + base_size), p2i(patch_end),
 598                    p2i(valid_new_base + base_size), p2i(valid_new_end), addr_delta);
 599 
 600     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
 601                                       valid_new_base, valid_new_end, addr_delta, ArchivePtrMarker::ptrmap());
 602     ArchivePtrMarker::ptrmap()->iterate(&patcher);
 603     ArchivePtrMarker::compact(patcher.max_non_null_offset());
 604   }
 605 }
 606 
 607 void DynamicArchiveBuilder::write_archive(char* serialized_data) {
 608   int num_klasses = klasses()->length();
 609   int num_symbols = symbols()->length();
 610 
 611   _header->set_serialized_data(to_target(serialized_data));
 612 
 613   FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
 614   assert(dynamic_info != NULL, "Sanity");
 615 
 616   // Now write the archived data including the file offsets.
 617   const char* archive_name = Arguments::GetSharedDynamicArchivePath();
 618   dynamic_info->open_for_write(archive_name);
 619   MetaspaceShared::write_core_archive_regions(dynamic_info, NULL, NULL);
 620   dynamic_info->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
 621   dynamic_info->set_header_crc(dynamic_info->compute_header_crc());
 622   dynamic_info->write_header();
 623   dynamic_info->close();
 624 
 625   address base = to_target(_alloc_bottom);
 626   address top  = address(current_dump_space()->top()) + _buffer_to_target_delta;
 627   size_t file_size = pointer_delta(top, base, sizeof(char));
 628 
 629   base += MetaspaceShared::final_delta();
 630   top += MetaspaceShared::final_delta();
 631   log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
 632                          " [" SIZE_FORMAT " bytes header, " SIZE_FORMAT " bytes total]",
 633                          p2i(base), p2i(top), _header->header_size(), file_size);
 634   log_info(cds, dynamic)("%d klasses; %d symbols", num_klasses, num_symbols);
 635 }
 636 

 637 class VM_PopulateDynamicDumpSharedSpace: public VM_Operation {
 638   DynamicArchiveBuilder* _builder;
 639 public:
 640   VM_PopulateDynamicDumpSharedSpace(DynamicArchiveBuilder* builder) : _builder(builder) {}
 641   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 642   void doit() {
 643     ResourceMark rm;
 644     if (SystemDictionaryShared::empty_dumptime_table()) {
 645       log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
 646       return;
 647     }
 648     if (AllowArchivingWithJavaAgent) {
 649       warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 650               "for testing purposes only and should not be used in a production environment");
 651     }
 652     FileMapInfo::check_nonempty_dir_in_shared_path_table();
 653 
 654     _builder->doit();
 655   }
 656 };
 657 
 658 
 659 void DynamicArchive::dump() {
 660   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
 661     log_warning(cds, dynamic)("SharedDynamicArchivePath is not specified");
 662     return;
 663   }
 664 
 665   DynamicArchiveBuilder builder;
 666   _builder = &builder;
 667   VM_PopulateDynamicDumpSharedSpace op(&builder);
 668   VMThread::execute(&op);
 669   _builder = NULL;
 670 }
 671 
 672 address DynamicArchive::original_to_buffer_impl(address orig_obj) {
 673   assert(DynamicDumpSharedSpaces, "must be");
 674   address buff_obj = _builder->get_dumped_addr(orig_obj);
 675   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
 676   assert(buff_obj != orig_obj, "call this only when you know orig_obj must be copied and not just referenced");
 677   assert(_builder->is_in_buffer_space(buff_obj), "must be");
 678   return buff_obj;
 679 }
 680 
 681 address DynamicArchive::buffer_to_target_impl(address buff_obj) {
 682   assert(DynamicDumpSharedSpaces, "must be");
 683   assert(_builder->is_in_buffer_space(buff_obj), "must be");
 684   return _builder->to_target(buff_obj);
 685 }
 686 
 687 address DynamicArchive::original_to_target_impl(address orig_obj) {
 688   assert(DynamicDumpSharedSpaces, "must be");
 689   if (MetaspaceShared::is_in_shared_metaspace(orig_obj)) {
 690     // This happens when the top archive points to a Symbol* in the base archive.
 691     return orig_obj;
 692   }
 693   address buff_obj = _builder->get_dumped_addr(orig_obj);
 694   assert(buff_obj != NULL, "orig_obj must be used by the dynamic archive");
 695   if (buff_obj == orig_obj) {
 696     // We are storing a pointer to an original object into the dynamic buffer. E.g.,
 697     // a Symbol* that used by both the base and top archives.
 698     assert(MetaspaceShared::is_in_shared_metaspace(orig_obj), "must be");
 699     return orig_obj;
 700   } else {
 701     return _builder->to_target(buff_obj);
 702   }
 703 }
 704 
 705 uintx DynamicArchive::object_delta_uintx(void* buff_obj) {
 706   assert(DynamicDumpSharedSpaces, "must be");
 707   address target_obj = _builder->to_target_no_check(address(buff_obj));
 708   assert(uintx(target_obj) >= SharedBaseAddress, "must be");
 709   return uintx(target_obj) - SharedBaseAddress;
 710 }
 711 
 712 bool DynamicArchive::is_in_target_space(void *obj) {
 713   assert(DynamicDumpSharedSpaces, "must be");


< prev index next >