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