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