src/share/vm/memory/metaspaceShared.cpp

Print this page
rev 9227 : [mq] cds


   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/dictionary.hpp"
  27 #include "classfile/loaderConstraints.hpp"
  28 #include "classfile/placeholders.hpp"
  29 #include "classfile/sharedClassUtil.hpp"
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/bytecodeStream.hpp"
  35 #include "interpreter/bytecodes.hpp"
  36 #include "memory/filemap.hpp"
  37 #include "memory/metaspace.hpp"
  38 #include "memory/metaspaceShared.hpp"
  39 #include "oops/objArrayOop.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/signature.hpp"
  43 #include "runtime/vmThread.hpp"
  44 #include "runtime/vm_operations.hpp"

  45 #include "utilities/hashtable.inline.hpp"
  46 
  47 int MetaspaceShared::_max_alignment = 0;
  48 
  49 ReservedSpace* MetaspaceShared::_shared_rs = NULL;
  50 
  51 MetaspaceSharedStats MetaspaceShared::_stats;
  52 
  53 bool MetaspaceShared::_link_classes_made_progress;
  54 bool MetaspaceShared::_check_classes_made_progress;
  55 bool MetaspaceShared::_has_error_classes;
  56 bool MetaspaceShared::_archive_loading_failed = false;
  57 // Read/write a data stream for restoring/preserving metadata pointers and
  58 // miscellaneous data from/to the shared archive file.
  59 
  60 void MetaspaceShared::serialize(SerializeClosure* soc) {
  61   int tag = 0;
  62   soc->do_tag(--tag);
  63 
  64   // Verify the sizes of various metadata in the system.


  80   soc->do_tag(--tag);
  81 
  82   soc->do_tag(666);
  83 }
  84 
  85 
  86 // CDS code for dumping shared archive.
  87 
  88 // Global object for holding classes that have been loaded.  Since this
  89 // is run at a safepoint just before exit, this is the entire set of classes.
  90 static GrowableArray<Klass*>* _global_klass_objects;
  91 static void collect_classes(Klass* k) {
  92   _global_klass_objects->append_if_missing(k);
  93   if (k->is_instance_klass()) {
  94     // Add in the array classes too
  95     InstanceKlass* ik = InstanceKlass::cast(k);
  96     ik->array_klasses_do(collect_classes);
  97   }
  98 }
  99 




 100 static void remove_unshareable_in_classes() {
 101   for (int i = 0; i < _global_klass_objects->length(); i++) {
 102     Klass* k = _global_klass_objects->at(i);
 103     k->remove_unshareable_info();
 104   }
 105 }
 106 
 107 static void rewrite_nofast_bytecode(Method* method) {
 108   RawBytecodeStream bcs(method);
 109   while (!bcs.is_last_bytecode()) {
 110     Bytecodes::Code opcode = bcs.raw_next();
 111     switch (opcode) {
 112     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 113     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 114     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 115     case Bytecodes::_iload:         *bcs.bcp() = Bytecodes::_nofast_iload;         break;
 116     default: break;
 117     }
 118   }
 119 }


 405   tty->print_cr(fmt_stats, "Total",
 406                 all_ro_count, all_ro_bytes, all_ro_perc,
 407                 all_rw_count, all_rw_bytes, all_rw_perc,
 408                 all_count, all_bytes, all_perc);
 409 
 410   assert(all_ro_bytes == ro_all, "everything should have been counted");
 411   assert(all_rw_bytes == rw_all, "everything should have been counted");
 412 #undef fmt_stats
 413 }
 414 
 415 // Populate the shared space.
 416 
 417 class VM_PopulateDumpSharedSpace: public VM_Operation {
 418 private:
 419   ClassLoaderData* _loader_data;
 420   GrowableArray<Klass*> *_class_promote_order;
 421   VirtualSpace _md_vs;
 422   VirtualSpace _mc_vs;
 423   CompactHashtableWriter* _string_cht;
 424   GrowableArray<MemRegion> *_string_regions;




 425 
 426 public:
 427   VM_PopulateDumpSharedSpace(ClassLoaderData* loader_data,
 428                              GrowableArray<Klass*> *class_promote_order) :
 429     _loader_data(loader_data) {
 430 
 431     // Split up and initialize the misc code and data spaces
 432     ReservedSpace* shared_rs = MetaspaceShared::shared_rs();
 433     size_t metadata_size = SharedReadOnlySize + SharedReadWriteSize;
 434     ReservedSpace shared_ro_rw = shared_rs->first_part(metadata_size);
 435     ReservedSpace misc_section = shared_rs->last_part(metadata_size);
 436 
 437     // Now split into misc sections.
 438     ReservedSpace md_rs   = misc_section.first_part(SharedMiscDataSize);
 439     ReservedSpace mc_rs   = misc_section.last_part(SharedMiscDataSize);
 440     _md_vs.initialize(md_rs, SharedMiscDataSize);
 441     _mc_vs.initialize(mc_rs, SharedMiscCodeSize);
 442     _class_promote_order = class_promote_order;

















 443   }
 444 
 445   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 446   void doit();   // outline because gdb sucks
 447 















 448 private:
 449   void handle_misc_data_space_failure(bool success) {
 450     if (!success) {
 451       report_out_of_shared_space(SharedMiscData);
 452     }
 453   }
 454 }; // class VM_PopulateDumpSharedSpace
 455 

 456 
 457 void VM_PopulateDumpSharedSpace::doit() {
 458   Thread* THREAD = VMThread::vm_thread();
 459   NOT_PRODUCT(SystemDictionary::verify();)
 460   // The following guarantee is meant to ensure that no loader constraints
 461   // exist yet, since the constraints table is not shared.  This becomes
 462   // more important now that we don't re-initialize vtables/itables for
 463   // shared classes at runtime, where constraints were previously created.
 464   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
 465             "loader constraints are not saved");
 466   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
 467           "placeholders are not saved");
 468   // Revisit and implement this if we prelink method handle call sites:
 469   guarantee(SystemDictionary::invoke_method_table() == NULL ||
 470             SystemDictionary::invoke_method_table()->number_of_entries() == 0,
 471             "invoke method table is not saved");
 472 
 473   // At this point, many classes have been loaded.
 474   // Gather systemDictionary classes in a global array and do everything to
 475   // that so we don't have to walk the SystemDictionary again.
 476   _global_klass_objects = new GrowableArray<Klass*>(1000);
 477   Universe::basic_type_classes_do(collect_classes);
 478   SystemDictionary::classes_do(collect_classes);




 479 
 480   tty->print_cr("Number of classes %d", _global_klass_objects->length());
 481   {
 482     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
 483     for (int i = 0; i < _global_klass_objects->length(); i++) {
 484       Klass* k = _global_klass_objects->at(i);
 485       if (k->is_instance_klass()) {
 486         num_inst ++;
 487       } else if (k->is_objArray_klass()) {
 488         num_obj_array ++;
 489       } else {
 490         assert(k->is_typeArray_klass(), "sanity");
 491         num_type_array ++;
 492       }
 493     }
 494     tty->print_cr("    instance classes   = %5d", num_inst);
 495     tty->print_cr("    obj array classes  = %5d", num_obj_array);
 496     tty->print_cr("    type array classes = %5d", num_type_array);
 497   }
 498 
 499 
 500   // Ensure the ConstMethods won't be modified at run-time
 501   tty->print("Updating ConstMethods ... ");
 502   rewrite_nofast_bytecodes_and_calculate_fingerprints();
 503   tty->print_cr("done. ");
 504 
 505   // Remove all references outside the metadata
 506   tty->print("Removing unshareable information ... ");
 507   remove_unshareable_in_classes();
 508   tty->print_cr("done. ");
 509 
 510   // Set up the share data and shared code segments.
 511   char* md_low = _md_vs.low();
 512   char* md_top = md_low;
 513   char* md_end = _md_vs.high();
 514   char* mc_low = _mc_vs.low();
 515   char* mc_top = mc_low;
 516   char* mc_end = _mc_vs.high();
 517 




 518   // Reserve space for the list of Klass*s whose vtables are used
 519   // for patching others as needed.
 520 
 521   void** vtbl_list = (void**)md_top;
 522   int vtbl_list_size = MetaspaceShared::vtbl_list_size;
 523   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
 524 
 525   md_top += vtbl_list_size * sizeof(void*);
 526   void* vtable = md_top;
 527 
 528   // Reserve space for a new dummy vtable for klass objects in the
 529   // heap.  Generate self-patching vtable entries.
 530 
 531   MetaspaceShared::generate_vtable_methods(vtbl_list, &vtable,
 532                                      &md_top, md_end,
 533                                      &mc_top, mc_end);
 534 
 535   // Reorder the system dictionary.  (Moving the symbols affects
 536   // how the hash table indices are calculated.)
 537   // Not doing this either.


 718       // This is useful when running JCK or SQE tests. You should not
 719       // enable this when running real apps.
 720       SystemDictionary::remove_classes_in_error_state();
 721     } else {
 722       tty->print_cr("Please remove the unverifiable classes from your class list and try again");
 723       exit(1);
 724     }
 725   }
 726 }
 727 
 728 void MetaspaceShared::prepare_for_dumping() {
 729   ClassLoader::initialize_shared_path();
 730   FileMapInfo::allocate_classpath_entry_table();
 731 }
 732 
 733 // Preload classes from a list, populate the shared spaces and dump to a
 734 // file.
 735 void MetaspaceShared::preload_and_dump(TRAPS) {
 736   TraceTime timer("Dump Shared Spaces", TraceStartupTime);
 737   ResourceMark rm;

 738 
 739   tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 740                 MetaspaceShared::shared_rs()->size(),
 741                 p2i(MetaspaceShared::shared_rs()->base()));
 742 
 743   // Preload classes to be shared.
 744   // Should use some os:: method rather than fopen() here. aB.
 745   const char* class_list_path;
 746   if (SharedClassListFile == NULL) {
 747     // Construct the path to the class list (in jre/lib)
 748     // Walk up two directories from the location of the VM and
 749     // optionally tack on "lib" (depending on platform)
 750     char class_list_path_str[JVM_MAXPATHLEN];
 751     os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
 752     for (int i = 0; i < 3; i++) {
 753       char *end = strrchr(class_list_path_str, *os::file_separator());
 754       if (end != NULL) *end = '\0';
 755     }
 756     int class_list_path_len = (int)strlen(class_list_path_str);
 757     if (class_list_path_len >= 3) {
 758       if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
 759         if (class_list_path_len < JVM_MAXPATHLEN - 4) {
 760           jio_snprintf(class_list_path_str + class_list_path_len,
 761                        sizeof(class_list_path_str) - class_list_path_len,
 762                        "%slib", os::file_separator());
 763           class_list_path_len += 4;
 764         }
 765       }
 766     }
 767     if (class_list_path_len < JVM_MAXPATHLEN - 10) {
 768       jio_snprintf(class_list_path_str + class_list_path_len,
 769                    sizeof(class_list_path_str) - class_list_path_len,
 770                    "%sclasslist", os::file_separator());
 771     }
 772     class_list_path = class_list_path_str;
 773   } else {
 774     class_list_path = SharedClassListFile;
 775   }
 776 
 777   int class_count = 0;
 778   GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>();
 779 
 780   // sun.io.Converters
 781   static const char obj_array_sig[] = "[[Ljava/lang/Object;";
 782   SymbolTable::new_permanent_symbol(obj_array_sig, THREAD);
 783 
 784   // java.util.HashMap
 785   static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;";
 786   SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD);
 787 





 788   tty->print_cr("Loading classes to share ...");
 789   _has_error_classes = false;
 790   class_count += preload_and_dump(class_list_path, class_promote_order,
 791                                   THREAD);
 792   if (ExtraSharedClassListFile) {
 793     class_count += preload_and_dump(ExtraSharedClassListFile, class_promote_order,
 794                                     THREAD);
 795   }
 796   tty->print_cr("Loading classes to share: done.");
 797 
 798   if (PrintSharedSpaces) {
 799     tty->print_cr("Shared spaces: preloaded %d classes", class_count);
 800   }
 801 
 802   // Rewrite and link classes
 803   tty->print_cr("Rewriting and linking classes ...");
 804 
 805   // Link any classes which got missed. This would happen if we have loaded classes that
 806   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 807   // fails verification, all other interfaces that were not specified in the classlist but
 808   // are implemented by K are not verified.
 809   link_and_cleanup_shared_classes(CATCH);
 810   tty->print_cr("Rewriting and linking classes: done");
 811 
 812   // Create and dump the shared spaces.   Everything so far is loaded
 813   // with the null class loader.
 814   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 815   VM_PopulateDumpSharedSpace op(loader_data, class_promote_order);
 816   VMThread::execute(&op);
 817 
 818   // Since various initialization steps have been undone by this process,
 819   // it is not reasonable to continue running a java process.
 820   exit(0);
 821 }
 822 
 823 int MetaspaceShared::preload_and_dump(const char * class_list_path,

 824                                       GrowableArray<Klass*>* class_promote_order,
 825                                       TRAPS) {
 826   FILE* file = fopen(class_list_path, "r");
 827   char class_name[256];
 828   int class_count = 0;
 829 
 830   if (file != NULL) {
 831     while ((fgets(class_name, sizeof class_name, file)) != NULL) {
 832       if (*class_name == '#') { // comment
 833         continue;
 834       }
 835       // Remove trailing newline
 836       size_t name_len = strlen(class_name);
 837       if (class_name[name_len-1] == '\n') {
 838         class_name[name_len-1] = '\0';
 839       }
 840 
 841       // Got a class name - load it.
 842       TempNewSymbol class_name_symbol = SymbolTable::new_permanent_symbol(class_name, THREAD);
 843       guarantee(!HAS_PENDING_EXCEPTION, "Exception creating a symbol.");
 844       Klass* klass = SystemDictionary::resolve_or_null(class_name_symbol,
 845                                                          THREAD);
 846       CLEAR_PENDING_EXCEPTION;
 847       if (klass != NULL) {
 848         if (PrintSharedSpaces && Verbose && WizardMode) {
 849           tty->print_cr("Shared spaces preloaded: %s", class_name);

 850         }
 851 
 852         InstanceKlass* ik = InstanceKlass::cast(klass);
 853 
 854         // Should be class load order as per -XX:+TraceClassLoadingPreorder
 855         class_promote_order->append(ik);
 856 
 857         // Link the class to cause the bytecodes to be rewritten and the
 858         // cpcache to be created. The linking is done as soon as classes
 859         // are loaded in order that the related data structures (klass and
 860         // cpCache) are located together.
 861         try_link_class(ik, THREAD);
 862         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
 863 
 864         class_count++;
 865       } else {
 866         //tty->print_cr("Preload failed: %s", class_name);
 867       }
 868     }
 869     fclose(file);
 870   } else {
 871     char errmsg[JVM_MAXPATHLEN];
 872     os::lasterror(errmsg, JVM_MAXPATHLEN);
 873     tty->print_cr("Loading classlist failed: %s", errmsg);
 874     exit(1);
 875   }
 876 
 877   return class_count;
 878 }
 879 
 880 // Returns true if the class's status has changed
 881 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
 882   assert(DumpSharedSpaces, "should only be called during dumping");
 883   if (ik->init_state() < InstanceKlass::linked) {
 884     bool saved = BytecodeVerificationLocal;
 885     if (!SharedClassUtil::is_shared_boot_class(ik)) {
 886       // The verification decision is based on BytecodeVerificationRemote
 887       // for non-system classes. Since we are using the NULL classloader
 888       // to load non-system classes during dumping, we need to temporarily
 889       // change BytecodeVerificationLocal to be the same as
 890       // BytecodeVerificationRemote. Note this can cause the parent system
 891       // classes also being verified. The extra overhead is acceptable during
 892       // dumping.
 893       BytecodeVerificationLocal = BytecodeVerificationRemote;
 894     }
 895     ik->link_class(THREAD);
 896     if (HAS_PENDING_EXCEPTION) {
 897       ResourceMark rm;
 898       tty->print_cr("Preload Warning: Verification failed for %s",
 899                     ik->external_name());
 900       CLEAR_PENDING_EXCEPTION;
 901       ik->set_in_error_state();
 902       _has_error_classes = true;
 903     }
 904     BytecodeVerificationLocal = saved;
 905     return true;
 906   } else {
 907     return false;
 908   }
 909 }
 910 





 911 // Closure for serializing initialization data in from a data area
 912 // (ptr_array) read from the shared file.
 913 
 914 class ReadClosure : public SerializeClosure {
 915 private:
 916   intptr_t** _ptr_array;
 917 
 918   inline intptr_t nextPtr() {
 919     return *(*_ptr_array)++;
 920   }
 921 
 922 public:
 923   ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
 924 
 925   void do_ptr(void** p) {
 926     assert(*p == NULL, "initializing previous initialized pointer.");
 927     intptr_t obj = nextPtr();
 928     assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
 929            "hit tag while initializing ptrs.");
 930     *p = (void*)obj;


1015     shared_rs.release();
1016 #endif
1017     // If -Xshare:on is specified, print out the error message and exit VM,
1018     // otherwise, set UseSharedSpaces to false and continue.
1019     if (RequireSharedSpaces || PrintSharedArchiveAndExit) {
1020       vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on.");
1021     } else {
1022       FLAG_SET_DEFAULT(UseSharedSpaces, false);
1023     }
1024     return false;
1025   }
1026 }
1027 
1028 // Read the miscellaneous data from the shared file, and
1029 // serialize it out to its various destinations.
1030 
1031 void MetaspaceShared::initialize_shared_spaces() {
1032   FileMapInfo *mapinfo = FileMapInfo::current_info();
1033 
1034   char* buffer = mapinfo->header()->region_addr(md);


1035 
1036   // Skip over (reserve space for) a list of addresses of C++ vtables
1037   // for Klass objects.  They get filled in later.
1038 
1039   void** vtbl_list = (void**)buffer;
1040   buffer += MetaspaceShared::vtbl_list_size * sizeof(void*);
1041   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
1042 
1043   // Skip over (reserve space for) dummy C++ vtables Klass objects.
1044   // They are used as is.
1045 
1046   intptr_t vtable_size = *(intptr_t*)buffer;
1047   buffer += sizeof(intptr_t);
1048   buffer += vtable_size;
1049 
1050   // Create the shared symbol table using the compact table at this spot in the
1051   // misc data space. (Todo: move this to read-only space. Currently
1052   // this is mapped copy-on-write but will never be written into).
1053 
1054   buffer = (char*)SymbolTable::init_shared_table(buffer);




   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/classListParser.hpp"
  27 #include "classfile/classLoaderExt.hpp"
  28 #include "classfile/dictionary.hpp"
  29 #include "classfile/loaderConstraints.hpp"
  30 #include "classfile/placeholders.hpp"
  31 #include "classfile/sharedClassUtil.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "code/codeCache.hpp"
  35 #include "gc/shared/gcLocker.hpp"
  36 #include "interpreter/bytecodeStream.hpp"
  37 #include "interpreter/bytecodes.hpp"
  38 #include "memory/filemap.hpp"
  39 #include "memory/metaspace.hpp"
  40 #include "memory/metaspaceShared.hpp"
  41 #include "oops/objArrayOop.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/signature.hpp"
  45 #include "runtime/vmThread.hpp"
  46 #include "runtime/vm_operations.hpp"
  47 #include "utilities/defaultStream.hpp"
  48 #include "utilities/hashtable.inline.hpp"
  49 
  50 int MetaspaceShared::_max_alignment = 0;
  51 
  52 ReservedSpace* MetaspaceShared::_shared_rs = NULL;
  53 
  54 MetaspaceSharedStats MetaspaceShared::_stats;
  55 
  56 bool MetaspaceShared::_link_classes_made_progress;
  57 bool MetaspaceShared::_check_classes_made_progress;
  58 bool MetaspaceShared::_has_error_classes;
  59 bool MetaspaceShared::_archive_loading_failed = false;
  60 // Read/write a data stream for restoring/preserving metadata pointers and
  61 // miscellaneous data from/to the shared archive file.
  62 
  63 void MetaspaceShared::serialize(SerializeClosure* soc) {
  64   int tag = 0;
  65   soc->do_tag(--tag);
  66 
  67   // Verify the sizes of various metadata in the system.


  83   soc->do_tag(--tag);
  84 
  85   soc->do_tag(666);
  86 }
  87 
  88 
  89 // CDS code for dumping shared archive.
  90 
  91 // Global object for holding classes that have been loaded.  Since this
  92 // is run at a safepoint just before exit, this is the entire set of classes.
  93 static GrowableArray<Klass*>* _global_klass_objects;
  94 static void collect_classes(Klass* k) {
  95   _global_klass_objects->append_if_missing(k);
  96   if (k->is_instance_klass()) {
  97     // Add in the array classes too
  98     InstanceKlass* ik = InstanceKlass::cast(k);
  99     ik->array_klasses_do(collect_classes);
 100   }
 101 }
 102  
 103 static void collect_classes2(Klass* k, ClassLoaderData* class_data) {
 104   collect_classes(k);
 105 }
 106 
 107 static void remove_unshareable_in_classes() {
 108   for (int i = 0; i < _global_klass_objects->length(); i++) {
 109     Klass* k = _global_klass_objects->at(i);
 110     k->remove_unshareable_info();
 111   }
 112 }
 113 
 114 static void rewrite_nofast_bytecode(Method* method) {
 115   RawBytecodeStream bcs(method);
 116   while (!bcs.is_last_bytecode()) {
 117     Bytecodes::Code opcode = bcs.raw_next();
 118     switch (opcode) {
 119     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 120     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 121     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 122     case Bytecodes::_iload:         *bcs.bcp() = Bytecodes::_nofast_iload;         break;
 123     default: break;
 124     }
 125   }
 126 }


 412   tty->print_cr(fmt_stats, "Total",
 413                 all_ro_count, all_ro_bytes, all_ro_perc,
 414                 all_rw_count, all_rw_bytes, all_rw_perc,
 415                 all_count, all_bytes, all_perc);
 416 
 417   assert(all_ro_bytes == ro_all, "everything should have been counted");
 418   assert(all_rw_bytes == rw_all, "everything should have been counted");
 419 #undef fmt_stats
 420 }
 421 
 422 // Populate the shared space.
 423 
 424 class VM_PopulateDumpSharedSpace: public VM_Operation {
 425 private:
 426   ClassLoaderData* _loader_data;
 427   GrowableArray<Klass*> *_class_promote_order;
 428   VirtualSpace _md_vs;
 429   VirtualSpace _mc_vs;
 430   CompactHashtableWriter* _string_cht;
 431   GrowableArray<MemRegion> *_string_regions;
 432   char* _md_alloc_low;
 433   char* _md_alloc_top;
 434   char* _md_alloc_max;
 435   static VM_PopulateDumpSharedSpace* _instance;
 436 
 437 public:
 438   VM_PopulateDumpSharedSpace(ClassLoaderData* loader_data,
 439                              GrowableArray<Klass*> *class_promote_order) :
 440     _loader_data(loader_data) {

 441     // Split up and initialize the misc code and data spaces
 442     ReservedSpace* shared_rs = MetaspaceShared::shared_rs();
 443     size_t metadata_size = SharedReadOnlySize + SharedReadWriteSize;
 444     ReservedSpace shared_ro_rw = shared_rs->first_part(metadata_size);
 445     ReservedSpace misc_section = shared_rs->last_part(metadata_size);
 446 
 447     // Now split into misc sections.
 448     ReservedSpace md_rs   = misc_section.first_part(SharedMiscDataSize);
 449     ReservedSpace mc_rs   = misc_section.last_part(SharedMiscDataSize);
 450     _md_vs.initialize(md_rs, SharedMiscDataSize);
 451     _mc_vs.initialize(mc_rs, SharedMiscCodeSize);
 452     _class_promote_order = class_promote_order;
 453 
 454     _md_alloc_low = _md_vs.low();
 455     _md_alloc_top = _md_alloc_low + sizeof(char*);
 456     _md_alloc_max = _md_vs.low() + SharedMiscDataSize;
 457 
 458     assert(_instance == NULL, "must be singleton");
 459     _instance = this;
 460   }
 461 
 462   ~VM_PopulateDumpSharedSpace() {
 463     assert(_instance == this, "must be singleton");
 464     _instance = NULL;
 465   }
 466 
 467   static VM_PopulateDumpSharedSpace* instance() {
 468     assert(_instance != NULL, "sanity");
 469     return _instance;
 470   }
 471 
 472   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 473   void doit();   // outline because gdb sucks
 474 
 475   char* misc_data_space_alloc(size_t num_bytes) {
 476     size_t alignment = sizeof(char*);
 477     num_bytes = align_size_up(num_bytes, alignment);
 478     _md_alloc_top = (char*)align_ptr_up(_md_alloc_top, alignment);
 479     if (_md_alloc_top + num_bytes > _md_alloc_max) {
 480       report_out_of_shared_space(SharedMiscData);
 481     }
 482 
 483     char* p = _md_alloc_top;
 484     _md_alloc_top += num_bytes;
 485 
 486     memset(p, 0, num_bytes);
 487     return p;
 488   }
 489 
 490 private:
 491   void handle_misc_data_space_failure(bool success) {
 492     if (!success) {
 493       report_out_of_shared_space(SharedMiscData);
 494     }
 495   }
 496 }; // class VM_PopulateDumpSharedSpace
 497 
 498 VM_PopulateDumpSharedSpace* VM_PopulateDumpSharedSpace::_instance;
 499 
 500 void VM_PopulateDumpSharedSpace::doit() {
 501   Thread* THREAD = VMThread::vm_thread();
 502   NOT_PRODUCT(SystemDictionary::verify();)
 503   // The following guarantee is meant to ensure that no loader constraints
 504   // exist yet, since the constraints table is not shared.  This becomes
 505   // more important now that we don't re-initialize vtables/itables for
 506   // shared classes at runtime, where constraints were previously created.
 507   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
 508             "loader constraints are not saved");
 509   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
 510           "placeholders are not saved");
 511   // Revisit and implement this if we prelink method handle call sites:
 512   guarantee(SystemDictionary::invoke_method_table() == NULL ||
 513             SystemDictionary::invoke_method_table()->number_of_entries() == 0,
 514             "invoke method table is not saved");
 515 
 516   // At this point, many classes have been loaded.
 517   // Gather systemDictionary classes in a global array and do everything to
 518   // that so we don't have to walk the SystemDictionary again.
 519   _global_klass_objects = new GrowableArray<Klass*>(1000);
 520   Universe::basic_type_classes_do(collect_classes);
 521 
 522   // Need to call SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*))
 523   // as we may have some classes with NULL ClassLoaderData* in the dictionary. Other
 524   // variants of SystemDictionary::classes_do will skip those classes.
 525   SystemDictionary::classes_do(collect_classes2);
 526 
 527   tty->print_cr("Number of classes %d", _global_klass_objects->length());
 528   {
 529     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
 530     for (int i = 0; i < _global_klass_objects->length(); i++) {
 531       Klass* k = _global_klass_objects->at(i);
 532       if (k->is_instance_klass()) {
 533         num_inst ++;
 534       } else if (k->is_objArray_klass()) {
 535         num_obj_array ++;
 536       } else {
 537         assert(k->is_typeArray_klass(), "sanity");
 538         num_type_array ++;
 539       }
 540     }
 541     tty->print_cr("    instance classes   = %5d", num_inst);
 542     tty->print_cr("    obj array classes  = %5d", num_obj_array);
 543     tty->print_cr("    type array classes = %5d", num_type_array);
 544   }
 545 
 546 
 547   // Ensure the ConstMethods won't be modified at run-time
 548   tty->print("Updating ConstMethods ... ");
 549   rewrite_nofast_bytecodes_and_calculate_fingerprints();
 550   tty->print_cr("done. ");
 551 
 552   // Remove all references outside the metadata
 553   tty->print("Removing unshareable information ... ");
 554   remove_unshareable_in_classes();
 555   tty->print_cr("done. ");
 556 
 557   // Set up the share data and shared code segments.
 558   char* md_low = _md_vs.low();
 559   char* md_top = md_low;
 560   char* md_end = _md_vs.high();
 561   char* mc_low = _mc_vs.low();
 562   char* mc_top = mc_low;
 563   char* mc_end = _mc_vs.high();
 564 
 565   assert(_md_alloc_top != NULL, "sanity");
 566   *(char**)_md_alloc_low = _md_alloc_top;
 567   md_top = _md_alloc_top;
 568 
 569   // Reserve space for the list of Klass*s whose vtables are used
 570   // for patching others as needed.
 571 
 572   void** vtbl_list = (void**)md_top;
 573   int vtbl_list_size = MetaspaceShared::vtbl_list_size;
 574   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
 575 
 576   md_top += vtbl_list_size * sizeof(void*);
 577   void* vtable = md_top;
 578 
 579   // Reserve space for a new dummy vtable for klass objects in the
 580   // heap.  Generate self-patching vtable entries.
 581 
 582   MetaspaceShared::generate_vtable_methods(vtbl_list, &vtable,
 583                                      &md_top, md_end,
 584                                      &mc_top, mc_end);
 585 
 586   // Reorder the system dictionary.  (Moving the symbols affects
 587   // how the hash table indices are calculated.)
 588   // Not doing this either.


 769       // This is useful when running JCK or SQE tests. You should not
 770       // enable this when running real apps.
 771       SystemDictionary::remove_classes_in_error_state();
 772     } else {
 773       tty->print_cr("Please remove the unverifiable classes from your class list and try again");
 774       exit(1);
 775     }
 776   }
 777 }
 778 
 779 void MetaspaceShared::prepare_for_dumping() {
 780   ClassLoader::initialize_shared_path();
 781   FileMapInfo::allocate_classpath_entry_table();
 782 }
 783 
 784 // Preload classes from a list, populate the shared spaces and dump to a
 785 // file.
 786 void MetaspaceShared::preload_and_dump(TRAPS) {
 787   TraceTime timer("Dump Shared Spaces", TraceStartupTime);
 788   ResourceMark rm;
 789   char class_list_path_str[JVM_MAXPATHLEN];
 790 
 791   tty->print_cr("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
 792                 MetaspaceShared::shared_rs()->size(),
 793                 p2i(MetaspaceShared::shared_rs()->base()));
 794 
 795   // Preload classes to be shared.
 796   // Should use some os:: method rather than fopen() here. aB.
 797   const char* class_list_path;
 798   if (SharedClassListFile == NULL) {
 799     // Construct the path to the class list (in jre/lib)
 800     // Walk up two directories from the location of the VM and
 801     // optionally tack on "lib" (depending on platform)

 802     os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
 803     for (int i = 0; i < 3; i++) {
 804       char *end = strrchr(class_list_path_str, *os::file_separator());
 805       if (end != NULL) *end = '\0';
 806     }
 807     int class_list_path_len = (int)strlen(class_list_path_str);
 808     if (class_list_path_len >= 3) {
 809       if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
 810         if (class_list_path_len < JVM_MAXPATHLEN - 4) {
 811           jio_snprintf(class_list_path_str + class_list_path_len,
 812                        sizeof(class_list_path_str) - class_list_path_len,
 813                        "%slib", os::file_separator());
 814           class_list_path_len += 4;
 815         }
 816       }
 817     }
 818     if (class_list_path_len < JVM_MAXPATHLEN - 10) {
 819       jio_snprintf(class_list_path_str + class_list_path_len,
 820                    sizeof(class_list_path_str) - class_list_path_len,
 821                    "%sclasslist", os::file_separator());
 822     }
 823     class_list_path = class_list_path_str;
 824   } else {
 825     class_list_path = SharedClassListFile;
 826   }
 827 
 828   int class_count = 0;
 829   GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>();
 830 
 831   // sun.io.Converters
 832   static const char obj_array_sig[] = "[[Ljava/lang/Object;";
 833   SymbolTable::new_permanent_symbol(obj_array_sig, THREAD);
 834 
 835   // java.util.HashMap
 836   static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;";
 837   SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD);
 838 
 839   // Need to allocate the op here:
 840   // op.misc_data_space_alloc() will be called during preload_and_dump().
 841   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 842   VM_PopulateDumpSharedSpace op(loader_data, class_promote_order);
 843 
 844   tty->print_cr("Loading classes to share ...");
 845   _has_error_classes = false;
 846   class_count += preload_and_dump(class_list_path, class_promote_order,
 847                                   THREAD);
 848   if (ExtraSharedClassListFile) {
 849     class_count += preload_and_dump(ExtraSharedClassListFile, class_promote_order,
 850                                     THREAD);
 851   }
 852   tty->print_cr("Loading classes to share: done.");
 853 
 854   if (PrintSharedSpaces) {
 855     tty->print_cr("Shared spaces: preloaded %d classes", class_count);
 856   }
 857 
 858   // Rewrite and link classes
 859   tty->print_cr("Rewriting and linking classes ...");
 860 
 861   // Link any classes which got missed. This would happen if we have loaded classes that
 862   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 863   // fails verification, all other interfaces that were not specified in the classlist but
 864   // are implemented by K are not verified.
 865   link_and_cleanup_shared_classes(CATCH);
 866   tty->print_cr("Rewriting and linking classes: done");
 867 




 868   VMThread::execute(&op);

 869   // Since various initialization steps have been undone by this process,
 870   // it is not reasonable to continue running a java process.
 871   exit(0);
 872 }
 873 
 874 
 875 int MetaspaceShared::preload_and_dump(const char* class_list_path,
 876                                       GrowableArray<Klass*>* class_promote_order,
 877                                       TRAPS) {
 878   ClassListParser parser(class_list_path);

 879   int class_count = 0;
 880 
 881     while (parser.parse_one_line()) {
 882       Klass* klass = ClassLoaderExt::load_one_class(&parser, THREAD);








 883 





 884       CLEAR_PENDING_EXCEPTION;
 885       if (klass != NULL) {
 886         if (PrintSharedSpaces && Verbose && WizardMode) {
 887           ResourceMark rm;
 888           tty->print_cr("Shared spaces preloaded: %s", klass->external_name());
 889         }
 890 
 891         InstanceKlass* ik = InstanceKlass::cast(klass);
 892 
 893         // Should be class load order as per -XX:+TraceClassLoadingPreorder
 894         class_promote_order->append(ik);
 895 
 896         // Link the class to cause the bytecodes to be rewritten and the
 897         // cpcache to be created. The linking is done as soon as classes
 898         // are loaded in order that the related data structures (klass and
 899         // cpCache) are located together.
 900         try_link_class(ik, THREAD);
 901         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
 902 
 903         class_count++;


 904       }
 905     }







 906 
 907   return class_count;
 908 }
 909 
 910 // Returns true if the class's status has changed
 911 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
 912   assert(DumpSharedSpaces, "should only be called during dumping");
 913   if (ik->init_state() < InstanceKlass::linked) {
 914     bool saved = BytecodeVerificationLocal;
 915     if (!SharedClassUtil::is_shared_boot_class(ik)) {
 916       // The verification decision is based on BytecodeVerificationRemote
 917       // for non-system classes. Since we are using the NULL classloader
 918       // to load non-system classes during dumping, we need to temporarily
 919       // change BytecodeVerificationLocal to be the same as
 920       // BytecodeVerificationRemote. Note this can cause the parent system
 921       // classes also being verified. The extra overhead is acceptable during
 922       // dumping.
 923       BytecodeVerificationLocal = BytecodeVerificationRemote;
 924     }
 925     ik->link_class(THREAD);
 926     if (HAS_PENDING_EXCEPTION) {
 927       ResourceMark rm;
 928       tty->print_cr("Preload Warning: Verification failed for %s",
 929                     ik->external_name());
 930       CLEAR_PENDING_EXCEPTION;
 931       ik->set_in_error_state();
 932       _has_error_classes = true;
 933     }
 934     BytecodeVerificationLocal = saved;
 935     return true;
 936   } else {
 937     return false;
 938   }
 939 }
 940 
 941 // Allocate misc data blocks during dumping.
 942 char* MetaspaceShared::misc_data_space_alloc(size_t num_bytes) {
 943   return VM_PopulateDumpSharedSpace::instance()->misc_data_space_alloc(num_bytes);
 944 }
 945 
 946 // Closure for serializing initialization data in from a data area
 947 // (ptr_array) read from the shared file.
 948 
 949 class ReadClosure : public SerializeClosure {
 950 private:
 951   intptr_t** _ptr_array;
 952 
 953   inline intptr_t nextPtr() {
 954     return *(*_ptr_array)++;
 955   }
 956 
 957 public:
 958   ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
 959 
 960   void do_ptr(void** p) {
 961     assert(*p == NULL, "initializing previous initialized pointer.");
 962     intptr_t obj = nextPtr();
 963     assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
 964            "hit tag while initializing ptrs.");
 965     *p = (void*)obj;


1050     shared_rs.release();
1051 #endif
1052     // If -Xshare:on is specified, print out the error message and exit VM,
1053     // otherwise, set UseSharedSpaces to false and continue.
1054     if (RequireSharedSpaces || PrintSharedArchiveAndExit) {
1055       vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on.");
1056     } else {
1057       FLAG_SET_DEFAULT(UseSharedSpaces, false);
1058     }
1059     return false;
1060   }
1061 }
1062 
1063 // Read the miscellaneous data from the shared file, and
1064 // serialize it out to its various destinations.
1065 
1066 void MetaspaceShared::initialize_shared_spaces() {
1067   FileMapInfo *mapinfo = FileMapInfo::current_info();
1068 
1069   char* buffer = mapinfo->header()->region_addr(md);
1070 
1071   buffer = *((char**)buffer); // skip over the md_alloc'ed blocks
1072 
1073   // Skip over (reserve space for) a list of addresses of C++ vtables
1074   // for Klass objects.  They get filled in later.
1075 
1076   void** vtbl_list = (void**)buffer;
1077   buffer += MetaspaceShared::vtbl_list_size * sizeof(void*);
1078   Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
1079 
1080   // Skip over (reserve space for) dummy C++ vtables Klass objects.
1081   // They are used as is.
1082 
1083   intptr_t vtable_size = *(intptr_t*)buffer;
1084   buffer += sizeof(intptr_t);
1085   buffer += vtable_size;
1086 
1087   // Create the shared symbol table using the compact table at this spot in the
1088   // misc data space. (Todo: move this to read-only space. Currently
1089   // this is mapped copy-on-write but will never be written into).
1090 
1091   buffer = (char*)SymbolTable::init_shared_table(buffer);