1 /*
   2  * Copyright (c) 2018, 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 "classfile/javaClasses.inline.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "logging/log.hpp"
  29 #include "logging/logMessage.hpp"
  30 #include "logging/logStream.hpp"
  31 #include "memory/heapShared.hpp"
  32 #include "memory/iterator.inline.hpp"
  33 #include "memory/metadataFactory.hpp"
  34 #include "memory/metaspaceClosure.hpp"
  35 #include "memory/metaspaceShared.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/compressedOops.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 
  40 #if INCLUDE_CDS_JAVA_HEAP
  41 KlassSubGraphInfo* HeapShared::_subgraph_info_list = NULL;
  42 int HeapShared::_num_archived_subgraph_info_records = 0;
  43 Array<ArchivedKlassSubGraphInfoRecord>* HeapShared::_archived_subgraph_info_records = NULL;
  44 
  45 // Currently there is only one class mirror (ArchivedModuleGraph) with archived
  46 // sub-graphs.
  47 KlassSubGraphInfo* HeapShared::find_subgraph_info(Klass* k) {
  48   KlassSubGraphInfo* info = _subgraph_info_list;
  49   while (info != NULL) {
  50     if (info->klass() == k) {
  51       return info;
  52     }
  53     info = info->next();
  54   }
  55   return NULL; 
  56 }
  57 
  58 // Get the subgraph_info for Klass k. A new subgraph_info is created if
  59 // there is no existing one for k. The subgraph_info records the relocated
  60 // Klass* of the original k.
  61 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
  62   Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
  63   KlassSubGraphInfo* info = find_subgraph_info(relocated_k);
  64   if (info != NULL) {
  65     return info;
  66   }
  67 
  68   info = new KlassSubGraphInfo(relocated_k, _subgraph_info_list);
  69   _subgraph_info_list = info; 
  70   return info;
  71 }
  72 
  73 int HeapShared::num_of_subgraph_infos() {
  74   int num = 0;
  75   KlassSubGraphInfo* info = _subgraph_info_list;
  76   while (info != NULL) {
  77     num ++;
  78     info = info->next();
  79   }
  80   return num; 
  81 }
  82 
  83 // Add an entry field to the current KlassSubGraphInfo.
  84 void KlassSubGraphInfo::add_subgraph_entry_field(int field_offset, oop v) {
  85   assert(DumpSharedSpaces, "dump time only");
  86   if (_subgraph_entry_fields == NULL) {
  87     _subgraph_entry_fields =
  88       new(ResourceObj::C_HEAP, mtClass) GrowableArray<juint>(10, true);
  89   }
  90   _subgraph_entry_fields->append((juint)field_offset);
  91   _subgraph_entry_fields->append(CompressedOops::encode(v));
  92 }
  93 
  94 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
  95 // Only objects of boot classes can be included in sub-graph.
  96 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k, Klass *relocated_k) {
  97   assert(DumpSharedSpaces, "dump time only");
  98 
  99   if (_subgraph_object_klasses == NULL) {
 100     _subgraph_object_klasses =
 101       new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, true);
 102   }
 103 
 104   assert(relocated_k->is_shared(), "must be a shared class");
 105   if (relocated_k->is_instance_klass()) {
 106     assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
 107           "must be boot class");
 108     // SystemDictionary::xxx_klass() are not updated, need to check
 109     // the original Klass*
 110     if (orig_k == SystemDictionary::String_klass() ||
 111         orig_k == SystemDictionary::Object_klass()) {
 112       // Initialized early during VM initialization. No need to be added
 113       // to the sub-graph object class list.
 114       return;
 115     }
 116   } else if (relocated_k->is_objArray_klass()) {
 117     Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
 118     if (abk->is_instance_klass()) {
 119       assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
 120             "must be boot class");
 121     }
 122     if (relocated_k == Universe::objectArrayKlassObj()) {
 123       // Initialized early during Universe::genesis. No need to be added
 124       // to the list.
 125       return;
 126     }
 127   } else {
 128     assert(relocated_k->is_typeArray_klass(), "must be");
 129     // Primitive type arrays are created early during Universe::genesis. 
 130     return;
 131   }
 132 
 133   _subgraph_object_klasses->append_if_missing(relocated_k);
 134 }
 135 
 136 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
 137 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
 138   _k = info->klass();
 139   _next = NULL;
 140   _entry_field_records = NULL;
 141   _subgraph_klasses = NULL;
 142 
 143   // populate the entry fields
 144   GrowableArray<juint>* entry_fields = info->subgraph_entry_fields();
 145   if (entry_fields != NULL) {
 146     int num_entry_fields = entry_fields->length();
 147     assert(num_entry_fields % 2 == 0, "sanity");
 148     _entry_field_records =
 149       MetaspaceShared::new_ro_array<juint>(num_entry_fields);
 150     for (int i = 0 ; i < num_entry_fields; i++) {
 151       _entry_field_records->at_put(i, entry_fields->at(i)); 
 152     }
 153   }
 154 
 155   // the Klasses of the objects in the sub-graphs
 156   GrowableArray<Klass*>* subgraph_klasses = info->subgraph_object_klasses();
 157   if (subgraph_klasses != NULL) {
 158     int num_subgraphs_klasses = subgraph_klasses->length();
 159     _subgraph_klasses =
 160       MetaspaceShared::new_ro_array<Klass*>(num_subgraphs_klasses);
 161     for (int i = 0; i < num_subgraphs_klasses; i++) {
 162       Klass* subgraph_k = subgraph_klasses->at(i);
 163       if (log_is_enabled(Info, cds, heap)) {
 164         ResourceMark rm;
 165         log_info(cds, heap)(
 166           "Archived object klass (%d): %s in %s sub-graphs",
 167           i, subgraph_k->external_name(), _k->external_name());
 168       }
 169       _subgraph_klasses->at_put(i, subgraph_k);
 170     }
 171   }
 172 }
 173 
 174 // Build the records of archived subgraph infos, which include:
 175 // - Entry points to all subgraphs from the containing class mirror. The entry
 176 //   points are static fields in the mirror. For each entry point, the field
 177 //   offset and value are recorded in the sub-graph info. The value are stored
 178 //   back to the corresponding field at runtime.
 179 // - A list of klasses that need to be loaded/initialized before archived
 180 //   java object sub-graph can be accessed at runtime.
 181 //
 182 // The records are saved in the archive file and reloaded at runtime. Currently
 183 // there is only one class mirror (ArchivedModuleGraph) with archived sub-graphs.
 184 //
 185 // Layout of the archived subgraph info records:
 186 // 
 187 // records_size | num_records | records*
 188 // ArchivedKlassSubGraphInfoRecord | entry_fields | subgraph_object_klasses
 189 size_t HeapShared::build_archived_subgraph_info_records(int num_records) {
 190   // remember the start address
 191   char* start_p = MetaspaceShared::read_only_space_top();
 192 
 193   // now populate the archived subgraph infos, which will be saved in the
 194   // archive file
 195   _archived_subgraph_info_records =
 196     MetaspaceShared::new_ro_array<ArchivedKlassSubGraphInfoRecord>(num_records);
 197   KlassSubGraphInfo* info = _subgraph_info_list;
 198   int i = 0;
 199   while (info != NULL) {
 200     assert(i < _archived_subgraph_info_records->length(), "sanity");
 201     ArchivedKlassSubGraphInfoRecord* record =
 202       _archived_subgraph_info_records->adr_at(i);
 203     record->init(info);
 204     info = info->next();
 205     i ++;
 206   }
 207 
 208   // _subgraph_info_list is no longer needed
 209   delete _subgraph_info_list;
 210   _subgraph_info_list = NULL;
 211 
 212   char* end_p = MetaspaceShared::read_only_space_top();
 213   size_t records_size = end_p - start_p; 
 214   return records_size;
 215 }
 216 
 217 // Write the subgraph info records in the shared _ro region
 218 void HeapShared::write_archived_subgraph_infos() {
 219   assert(DumpSharedSpaces, "dump time only");
 220 
 221   Array<intptr_t>* records_header = MetaspaceShared::new_ro_array<intptr_t>(3);
 222 
 223   _num_archived_subgraph_info_records = num_of_subgraph_infos();
 224   size_t records_size = build_archived_subgraph_info_records(
 225                              _num_archived_subgraph_info_records);
 226 
 227   // Now write the header information:
 228   // records_size, num_records, _archived_subgraph_info_records 
 229   assert(records_header != NULL, "sanity");
 230   intptr_t* p = (intptr_t*)(records_header->data());
 231   *p = (intptr_t)records_size;
 232   p ++;
 233   *p = (intptr_t)_num_archived_subgraph_info_records;
 234   p ++;
 235   *p = (intptr_t)_archived_subgraph_info_records;
 236 }
 237 
 238 char* HeapShared::read_archived_subgraph_infos(char* buffer) {
 239   Array<intptr_t>* records_header = (Array<intptr_t>*)buffer;
 240   intptr_t* p = (intptr_t*)(records_header->data());
 241   size_t records_size = (size_t)(*p);
 242   p ++;
 243   _num_archived_subgraph_info_records = *p;
 244   p ++;
 245   _archived_subgraph_info_records =
 246     (Array<ArchivedKlassSubGraphInfoRecord>*)(*p);
 247   
 248   buffer = (char*)_archived_subgraph_info_records + records_size;
 249   return buffer;
 250 }
 251 
 252 void HeapShared::initialize_from_archived_subgraph(Klass* k) {
 253   if (!MetaspaceShared::open_archive_heap_region_mapped()) {
 254     return; // nothing to do
 255   }
 256 
 257   if (_num_archived_subgraph_info_records == 0) {
 258     return; // no subgraph info records
 259   }
 260 
 261   // Initialize from archived data. Currently only ArchivedModuleGraph
 262   // has archived object subgraphs, which is used during VM initialization
 263   // time when bootstraping the system modules. No lock is needed.
 264   Thread* THREAD = Thread::current();
 265   for (int i = 0; i < _archived_subgraph_info_records->length(); i++) {
 266     ArchivedKlassSubGraphInfoRecord* record = _archived_subgraph_info_records->adr_at(i);
 267     if (record->klass() == k) {
 268       int i;
 269       // Found the archived subgraph info record for the requesting klass.
 270       // Load/link/initialize the klasses of the objects in the subgraph.
 271       // NULL class loader is used.
 272       Array<Klass*>* klasses = record->subgraph_klasses();
 273       if (klasses != NULL) {
 274         for (i = 0; i < klasses->length(); i++) {
 275           Klass* obj_k = klasses->at(i);
 276           Klass* resolved_k = SystemDictionary::resolve_or_null(
 277                                                 (obj_k)->name(), THREAD);
 278           if (resolved_k != obj_k) {
 279             return;
 280           }
 281           if ((obj_k)->is_instance_klass()) {
 282             InstanceKlass* ik = InstanceKlass::cast(obj_k);
 283             ik->initialize(THREAD);
 284           } else if ((obj_k)->is_objArray_klass()) {
 285             ObjArrayKlass* oak = ObjArrayKlass::cast(obj_k);
 286             oak->initialize(THREAD);
 287           }
 288         }
 289       }
 290 
 291       if (HAS_PENDING_EXCEPTION) {
 292         CLEAR_PENDING_EXCEPTION;
 293         // None of the field value will be set if there was an exception.
 294         // The java code will not see any of the archived objects in the
 295         // subgraphs referenced from k in this case.
 296         return;
 297       }
 298 
 299       // Load the subgraph entry fields from the record and store them back to
 300       // the corresponding fields within the mirror.
 301       oop m = k->java_mirror();
 302       Array<juint>* entry_field_records = record->entry_field_records();
 303       if (entry_field_records != NULL) {
 304         int efr_len = entry_field_records->length();
 305         assert(efr_len % 2 == 0, "sanity");
 306         for (i = 0; i < efr_len;) {
 307           int field_offset = entry_field_records->at(i);
 308           // The object refereced by the field becomes 'known' by GC from this
 309           // point. All objects in the subgraph reachable from the object are
 310           // also 'known' by GC.
 311           oop v = MetaspaceShared::materialize_archived_object(
 312             CompressedOops::decode(entry_field_records->at(i+1)));
 313           m->obj_field_put(field_offset, v);
 314           i += 2;
 315         }
 316       }
 317 
 318       // Done. Java code can see the archived sub-graphs referenced from k's
 319       // mirror after this point.
 320       return;
 321     } 
 322   }
 323 }
 324 
 325 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
 326   int _level;
 327   KlassSubGraphInfo* _subgraph_info;
 328   oop _orig_referencing_obj;
 329   oop _archived_referencing_obj;
 330  public:
 331   WalkOopAndArchiveClosure(int level, KlassSubGraphInfo* subgraph_info,
 332            oop orig, oop archived) : _level(level),
 333                                      _subgraph_info(subgraph_info),
 334                                      _orig_referencing_obj(orig),
 335                                      _archived_referencing_obj(archived) {}
 336   void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 337   void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
 338 
 339  protected:
 340   template <class T> void do_oop_work(T *p) {
 341     oop obj = RawAccess<>::oop_load(p);
 342     if (!CompressedOops::is_null(obj)) {
 343       // A java.lang.Class instance can not be included in an archived
 344       // object sub-graph.
 345       if (java_lang_Class::is_instance(obj)) {
 346         tty->print("Unknown java.lang.Class object is in the archived sub-graph\n");
 347         vm_exit(1); 
 348       }
 349 
 350       LogTarget(Debug, cds, heap) log;
 351       LogStream ls(log);
 352       outputStream* out = &ls;
 353       {
 354         ResourceMark rm;
 355         log.print("(%d) %s <--- referenced from:  %s",
 356                   _level, obj->klass()->external_name(),
 357                   CompressedOops::is_null(_orig_referencing_obj) ?
 358                          "" : _orig_referencing_obj->klass()->external_name());
 359         obj->print_on(out);
 360       }
 361 
 362       if (MetaspaceShared::is_archive_object(obj)) {
 363         // The current oop is an archived oop, nothing needs to be done
 364         log.print("--- object is already archived ---");
 365         return;
 366       }
 367 
 368       size_t delta = pointer_delta((HeapWord*)_archived_referencing_obj,
 369                                    (HeapWord*)_orig_referencing_obj);
 370       T* new_p = (T*)((HeapWord*)p + delta);
 371       oop archived = MetaspaceShared::find_archived_heap_object(obj);
 372       if (archived != NULL) {
 373         // There is an archived copy existing, update reference to point
 374         // to the archived copy
 375         RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
 376         log.print("--- archived copy existing, store archived " PTR_FORMAT " in " PTR_FORMAT,
 377                   p2i(archived), p2i(new_p));
 378         return;
 379       }
 380 
 381       int l = _level + 1;
 382       Thread* THREAD = Thread::current();
 383       // Archive the current oop before iterating through its references
 384       archived = MetaspaceShared::archive_heap_object(obj, THREAD);
 385       assert(MetaspaceShared::is_archive_object(archived), "must be archived");
 386       log.print("=== archiving oop " PTR_FORMAT " ==> " PTR_FORMAT,
 387                  p2i(obj), p2i(archived));
 388 
 389       // Following the references in the current oop and archive any
 390       // encountered objects during the process
 391       WalkOopAndArchiveClosure walker(l, _subgraph_info, obj, archived);
 392       obj->oop_iterate(&walker);
 393 
 394       // Update the reference in the archived copy of the referencing object
 395       RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
 396       log.print("=== store archived " PTR_FORMAT " in " PTR_FORMAT,
 397                 p2i(archived), p2i(new_p));
 398 
 399       // Add the klass to the list of classes that need to be loaded before
 400       // module system initialization
 401       Klass *orig_k = obj->klass();
 402       Klass *relocated_k = archived->klass();
 403       assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
 404              "must be the relocated Klass in the shared space");
 405       _subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
 406     }
 407   }
 408 };
 409 
 410 //
 411 // Start from the given static field in a java mirror and archive the
 412 // complete sub-graph of java heap objects that are reached directly
 413 // or indirectly from the starting object by following references.
 414 // Currently, only ArchivedModuleGraph class instance (mirror) has archived
 415 // object subgraphs. Sub-graph archiving restrictions (current):
 416 //
 417 // - All classes of objects in the archived sub-graph (including the
 418 //   entry class) must be boot class only.
 419 // - No java.lang.Class instance (java mirror) can be included inside
 420 //   an archived sub-graph. Mirror can only be the sub-graph entry object.
 421 //
 422 // The Java heap object sub-graph archiving process (see
 423 // WalkOopAndArchiveClosure):
 424 // 
 425 // 1) Java object sub-graph archiving starts from a given static field
 426 // within a Class instance (java mirror). If the static field is a
 427 // refererence field and points to a non-null java object, proceed to
 428 // the next step.
 429 //
 430 // 2) Archives the referenced java object. If an archived copy of the
 431 // current object already exists, updates the pointer in the archived
 432 // copy of the referencing object to point to the current archived object.
 433 // Otherwise, proceed to the next step.
 434 //
 435 // 3) Follows all references within the current java object and recursively
 436 // archive the sub-graph of objects starting from each reference. 
 437 //
 438 // 4) Updates the pointer in the archived copy of referencing object to
 439 //    point to the current archived object.
 440 //
 441 // 5) The Klass of the current java object is added to the list of Klasses
 442 // for loading and initialzing before any object in the archived graph can
 443 // be accessed at runtime.
 444 // 
 445 void HeapShared::walk_from_field_and_archiving(Klass *k,
 446                                                int field_offset,
 447                                                BasicType field_type,
 448                                                TRAPS) {
 449   assert(DumpSharedSpaces, "dump time only");
 450   assert(k->is_instance_klass(), "sanity");
 451   assert(InstanceKlass::cast(k)->is_shared_boot_class(),
 452          "must be boot class");
 453 
 454   oop m = k->java_mirror();
 455   oop archived_m = MetaspaceShared::find_archived_heap_object(m);
 456   if (CompressedOops::is_null(archived_m)) {
 457     return;
 458   }
 459 
 460   if (field_type == T_OBJECT) {
 461     // obtain k's subGraph Info
 462     KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
 463 
 464     // get the object referenced by the field
 465     oop f = m->obj_field(field_offset);
 466     if (!CompressedOops::is_null(f)) {
 467       LogTarget(Debug, cds, heap) log;
 468       LogStream ls(log);
 469       outputStream* out = &ls;
 470       log.print("Start from: ");
 471       f->print_on(out);
 472 
 473       // get the archived copy of the field referenced object 
 474       oop af = MetaspaceShared::archive_heap_object(f, THREAD);
 475       WalkOopAndArchiveClosure walker(1, subgraph_info, f, af);
 476       f->oop_iterate(&walker);
 477 
 478       // The field value is not preserved in the archived mirror.
 479       // Record the field as a new subGraph entry point. The recorded
 480       // information is restored from the archive at runtime. 
 481       subgraph_info->add_subgraph_entry_field(field_offset, af);
 482       Klass *relocated_k = af->klass();
 483       Klass *orig_k = f->klass();
 484       assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
 485              "must be the relocated Klass in the shared space");
 486       subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
 487     } else {
 488       // The field contains null, we still need to record the entry point,
 489       // so it can be restored at runtime.
 490       subgraph_info->add_subgraph_entry_field(field_offset, NULL);
 491     }
 492   } else {
 493     ShouldNotReachHere();
 494   }
 495 }
 496 
 497 #define do_module_object_graph(archive_object_graph_do) \
 498   archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedSystemModules_offset(), T_OBJECT, CHECK); \
 499   archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedModuleFinder_offset(), T_OBJECT, CHECK); \
 500   archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedMainModule_offset(), T_OBJECT, CHECK)
 501 
 502 void HeapShared::archive_module_graph_objects(Thread* THREAD) {
 503   do_module_object_graph(walk_from_field_and_archiving);
 504 }
 505 #endif // INCLUDE_CDS_JAVA_HEAP