Thu, 23 May 2013 12:44:18 +0100
Merge
1 /*
2 * Copyright (c) 2012, 2013, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/dictionary.hpp"
27 #include "classfile/loaderConstraints.hpp"
28 #include "classfile/placeholders.hpp"
29 #include "classfile/symbolTable.hpp"
30 #include "classfile/systemDictionary.hpp"
31 #include "code/codeCache.hpp"
32 #include "memory/filemap.hpp"
33 #include "memory/gcLocker.hpp"
34 #include "memory/metaspace.hpp"
35 #include "memory/metaspaceShared.hpp"
36 #include "oops/objArrayOop.hpp"
37 #include "oops/oop.inline.hpp"
38 #include "runtime/signature.hpp"
39 #include "runtime/vm_operations.hpp"
40 #include "runtime/vmThread.hpp"
41 #include "utilities/hashtable.inline.hpp"
44 int MetaspaceShared::_max_alignment = 0;
46 ReservedSpace* MetaspaceShared::_shared_rs = NULL;
48 // Read/write a data stream for restoring/preserving metadata pointers and
49 // miscellaneous data from/to the shared archive file.
51 void MetaspaceShared::serialize(SerializeClosure* soc) {
52 int tag = 0;
53 soc->do_tag(--tag);
55 assert(!UseCompressedOops, "UseCompressedOops doesn't work with shared archive");
56 // Verify the sizes of various metadata in the system.
57 soc->do_tag(sizeof(Method));
58 soc->do_tag(sizeof(ConstMethod));
59 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
60 soc->do_tag(sizeof(ConstantPool));
61 soc->do_tag(sizeof(ConstantPoolCache));
62 soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
63 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
64 soc->do_tag(sizeof(Symbol));
66 // Dump/restore miscellaneous metadata.
67 Universe::serialize(soc, true);
68 soc->do_tag(--tag);
70 // Dump/restore references to commonly used names and signatures.
71 vmSymbols::serialize(soc);
72 soc->do_tag(--tag);
74 soc->do_tag(666);
75 }
78 // CDS code for dumping shared archive.
80 // Global object for holding classes that have been loaded. Since this
81 // is run at a safepoint just before exit, this is the entire set of classes.
82 static GrowableArray<Klass*>* _global_klass_objects;
83 static void collect_classes(Klass* k) {
84 _global_klass_objects->append_if_missing(k);
85 if (k->oop_is_instance()) {
86 // Add in the array classes too
87 InstanceKlass* ik = InstanceKlass::cast(k);
88 ik->array_klasses_do(collect_classes);
89 }
90 }
92 static void remove_unshareable_in_classes() {
93 for (int i = 0; i < _global_klass_objects->length(); i++) {
94 Klass* k = _global_klass_objects->at(i);
95 k->remove_unshareable_info();
96 }
97 }
99 // Walk all methods in the class list and assign a fingerprint.
100 // so that this part of the ConstMethod* is read only.
101 static void calculate_fingerprints() {
102 for (int i = 0; i < _global_klass_objects->length(); i++) {
103 Klass* k = _global_klass_objects->at(i);
104 if (k->oop_is_instance()) {
105 InstanceKlass* ik = InstanceKlass::cast(k);
106 for (int i = 0; i < ik->methods()->length(); i++) {
107 ResourceMark rm;
108 Method* m = ik->methods()->at(i);
109 (new Fingerprinter(m))->fingerprint();
110 }
111 }
112 }
113 }
115 // Patch C++ vtable pointer in metadata.
117 // Klass and other metadata objects contain references to c++ vtables in the
118 // JVM library.
119 // Fix them to point to our constructed vtables. However, don't iterate
120 // across the space while doing this, as that causes the vtables to be
121 // patched, undoing our useful work. Instead, iterate to make a list,
122 // then use the list to do the fixing.
123 //
124 // Our constructed vtables:
125 // Dump time:
126 // 1. init_self_patching_vtbl_list: table of pointers to current virtual method addrs
127 // 2. generate_vtable_methods: create jump table, appended to above vtbl_list
128 // 3. patch_klass_vtables: for Klass list, patch the vtable entry in klass and
129 // associated metadata to point to jump table rather than to current vtbl
130 // Table layout: NOTE FIXED SIZE
131 // 1. vtbl pointers
132 // 2. #Klass X #virtual methods per Klass
133 // 1 entry for each, in the order:
134 // Klass1:method1 entry, Klass1:method2 entry, ... Klass1:method<num_virtuals> entry
135 // Klass2:method1 entry, Klass2:method2 entry, ... Klass2:method<num_virtuals> entry
136 // ...
137 // Klass<vtbl_list_size>:method1 entry, Klass<vtbl_list_size>:method2 entry,
138 // ... Klass<vtbl_list_size>:method<num_virtuals> entry
139 // Sample entry: (Sparc):
140 // save(sp, -256, sp)
141 // ba,pt common_code
142 // mov XXX, %L0 %L0 gets: Klass index <<8 + method index (note: max method index 255)
143 //
144 // Restore time:
145 // 1. initialize_shared_space: reserve space for table
146 // 2. init_self_patching_vtbl_list: update pointers to NEW virtual method addrs in text
147 //
148 // Execution time:
149 // First virtual method call for any object of these metadata types:
150 // 1. object->klass
151 // 2. vtable entry for that klass points to the jump table entries
152 // 3. branches to common_code with %O0/klass, %L0: Klass index <<8 + method index
153 // 4. common_code:
154 // Get address of new vtbl pointer for this Klass from updated table
155 // Update new vtbl pointer in the Klass: future virtual calls go direct
156 // Jump to method, using new vtbl pointer and method index
159 static void* find_matching_vtbl_ptr(void** vtbl_list, void* new_vtable_start, void* obj) {
160 void* old_vtbl_ptr = *(void**)obj;
161 for (int i = 0; i < MetaspaceShared::vtbl_list_size; i++) {
162 if (vtbl_list[i] == old_vtbl_ptr) {
163 return (void**)new_vtable_start + i * MetaspaceShared::num_virtuals;
164 }
165 }
166 ShouldNotReachHere();
167 return NULL;
168 }
170 // Assumes the vtable is in first slot in object.
171 static void patch_klass_vtables(void** vtbl_list, void* new_vtable_start) {
172 int n = _global_klass_objects->length();
173 for (int i = 0; i < n; i++) {
174 Klass* obj = _global_klass_objects->at(i);
175 // Note oop_is_instance() is a virtual call. After patching vtables
176 // all virtual calls on the dummy vtables will restore the original!
177 if (obj->oop_is_instance()) {
178 InstanceKlass* ik = InstanceKlass::cast(obj);
179 *(void**)ik = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, ik);
180 ConstantPool* cp = ik->constants();
181 *(void**)cp = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, cp);
182 for (int j = 0; j < ik->methods()->length(); j++) {
183 Method* m = ik->methods()->at(j);
184 *(void**)m = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, m);
185 }
186 } else {
187 // Array klasses
188 Klass* k = obj;
189 *(void**)k = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, k);
190 }
191 }
192 }
194 // Closure for serializing initialization data out to a data area to be
195 // written to the shared file.
197 class WriteClosure : public SerializeClosure {
198 private:
199 intptr_t* top;
200 char* end;
202 inline void check_space() {
203 if ((char*)top + sizeof(intptr_t) > end) {
204 report_out_of_shared_space(SharedMiscData);
205 }
206 }
208 public:
209 WriteClosure(char* md_top, char* md_end) {
210 top = (intptr_t*)md_top;
211 end = md_end;
212 }
214 char* get_top() { return (char*)top; }
216 void do_ptr(void** p) {
217 check_space();
218 *top = (intptr_t)*p;
219 ++top;
220 }
222 void do_tag(int tag) {
223 check_space();
224 *top = (intptr_t)tag;
225 ++top;
226 }
228 void do_region(u_char* start, size_t size) {
229 if ((char*)top + size > end) {
230 report_out_of_shared_space(SharedMiscData);
231 }
232 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
233 assert(size % sizeof(intptr_t) == 0, "bad size");
234 do_tag((int)size);
235 while (size > 0) {
236 *top = *(intptr_t*)start;
237 ++top;
238 start += sizeof(intptr_t);
239 size -= sizeof(intptr_t);
240 }
241 }
243 bool reading() const { return false; }
244 };
247 // Populate the shared space.
249 class VM_PopulateDumpSharedSpace: public VM_Operation {
250 private:
251 ClassLoaderData* _loader_data;
252 GrowableArray<Klass*> *_class_promote_order;
253 VirtualSpace _md_vs;
254 VirtualSpace _mc_vs;
256 public:
257 VM_PopulateDumpSharedSpace(ClassLoaderData* loader_data,
258 GrowableArray<Klass*> *class_promote_order) :
259 _loader_data(loader_data) {
261 // Split up and initialize the misc code and data spaces
262 ReservedSpace* shared_rs = MetaspaceShared::shared_rs();
263 int metadata_size = SharedReadOnlySize+SharedReadWriteSize;
264 ReservedSpace shared_ro_rw = shared_rs->first_part(metadata_size);
265 ReservedSpace misc_section = shared_rs->last_part(metadata_size);
267 // Now split into misc sections.
268 ReservedSpace md_rs = misc_section.first_part(SharedMiscDataSize);
269 ReservedSpace mc_rs = misc_section.last_part(SharedMiscDataSize);
270 _md_vs.initialize(md_rs, SharedMiscDataSize);
271 _mc_vs.initialize(mc_rs, SharedMiscCodeSize);
272 _class_promote_order = class_promote_order;
273 }
275 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
276 void doit(); // outline because gdb sucks
277 }; // class VM_PopulateDumpSharedSpace
280 void VM_PopulateDumpSharedSpace::doit() {
281 Thread* THREAD = VMThread::vm_thread();
282 NOT_PRODUCT(SystemDictionary::verify();)
283 // The following guarantee is meant to ensure that no loader constraints
284 // exist yet, since the constraints table is not shared. This becomes
285 // more important now that we don't re-initialize vtables/itables for
286 // shared classes at runtime, where constraints were previously created.
287 guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
288 "loader constraints are not saved");
289 guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
290 "placeholders are not saved");
291 // Revisit and implement this if we prelink method handle call sites:
292 guarantee(SystemDictionary::invoke_method_table() == NULL ||
293 SystemDictionary::invoke_method_table()->number_of_entries() == 0,
294 "invoke method table is not saved");
296 // At this point, many classes have been loaded.
297 // Gather systemDictionary classes in a global array and do everything to
298 // that so we don't have to walk the SystemDictionary again.
299 _global_klass_objects = new GrowableArray<Klass*>(1000);
300 Universe::basic_type_classes_do(collect_classes);
301 SystemDictionary::classes_do(collect_classes);
303 tty->print_cr("Number of classes %d", _global_klass_objects->length());
305 // Update all the fingerprints in the shared methods.
306 tty->print("Calculating fingerprints ... ");
307 calculate_fingerprints();
308 tty->print_cr("done. ");
310 // Remove all references outside the metadata
311 tty->print("Removing unshareable information ... ");
312 remove_unshareable_in_classes();
313 tty->print_cr("done. ");
315 // Set up the share data and shared code segments.
316 char* md_low = _md_vs.low();
317 char* md_top = md_low;
318 char* md_end = _md_vs.high();
319 char* mc_low = _mc_vs.low();
320 char* mc_top = mc_low;
321 char* mc_end = _mc_vs.high();
323 // Reserve space for the list of Klass*s whose vtables are used
324 // for patching others as needed.
326 void** vtbl_list = (void**)md_top;
327 int vtbl_list_size = MetaspaceShared::vtbl_list_size;
328 Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
330 md_top += vtbl_list_size * sizeof(void*);
331 void* vtable = md_top;
333 // Reserve space for a new dummy vtable for klass objects in the
334 // heap. Generate self-patching vtable entries.
336 MetaspaceShared::generate_vtable_methods(vtbl_list, &vtable,
337 &md_top, md_end,
338 &mc_top, mc_end);
340 // Reorder the system dictionary. (Moving the symbols affects
341 // how the hash table indices are calculated.)
342 // Not doing this either.
344 SystemDictionary::reorder_dictionary();
346 NOT_PRODUCT(SystemDictionary::verify();)
348 // Copy the the symbol table, and the system dictionary to the shared
349 // space in usable form. Copy the hastable
350 // buckets first [read-write], then copy the linked lists of entries
351 // [read-only].
353 SymbolTable::reverse(md_top);
354 NOT_PRODUCT(SymbolTable::verify());
355 SymbolTable::copy_buckets(&md_top, md_end);
357 SystemDictionary::reverse();
358 SystemDictionary::copy_buckets(&md_top, md_end);
360 ClassLoader::verify();
361 ClassLoader::copy_package_info_buckets(&md_top, md_end);
362 ClassLoader::verify();
364 SymbolTable::copy_table(&md_top, md_end);
365 SystemDictionary::copy_table(&md_top, md_end);
366 ClassLoader::verify();
367 ClassLoader::copy_package_info_table(&md_top, md_end);
368 ClassLoader::verify();
370 // Write the other data to the output array.
371 WriteClosure wc(md_top, md_end);
372 MetaspaceShared::serialize(&wc);
373 md_top = wc.get_top();
375 // Print shared spaces all the time
376 const char* fmt = "%s space: %9d [ %4.1f%% of total] out of %9d bytes [%4.1f%% used] at " PTR_FORMAT;
377 Metaspace* ro_space = _loader_data->ro_metaspace();
378 Metaspace* rw_space = _loader_data->rw_metaspace();
380 // Allocated size of each space (may not be all occupied)
381 const size_t ro_alloced = ro_space->capacity_bytes_slow(Metaspace::NonClassType);
382 const size_t rw_alloced = rw_space->capacity_bytes_slow(Metaspace::NonClassType);
383 const size_t md_alloced = md_end-md_low;
384 const size_t mc_alloced = mc_end-mc_low;
385 const size_t total_alloced = ro_alloced + rw_alloced + md_alloced + mc_alloced;
387 // Occupied size of each space.
388 const size_t ro_bytes = ro_space->used_bytes_slow(Metaspace::NonClassType);
389 const size_t rw_bytes = rw_space->used_bytes_slow(Metaspace::NonClassType);
390 const size_t md_bytes = size_t(md_top - md_low);
391 const size_t mc_bytes = size_t(mc_top - mc_low);
393 // Percent of total size
394 const size_t total_bytes = ro_bytes + rw_bytes + md_bytes + mc_bytes;
395 const double ro_t_perc = ro_bytes / double(total_bytes) * 100.0;
396 const double rw_t_perc = rw_bytes / double(total_bytes) * 100.0;
397 const double md_t_perc = md_bytes / double(total_bytes) * 100.0;
398 const double mc_t_perc = mc_bytes / double(total_bytes) * 100.0;
400 // Percent of fullness of each space
401 const double ro_u_perc = ro_bytes / double(ro_alloced) * 100.0;
402 const double rw_u_perc = rw_bytes / double(rw_alloced) * 100.0;
403 const double md_u_perc = md_bytes / double(md_alloced) * 100.0;
404 const double mc_u_perc = mc_bytes / double(mc_alloced) * 100.0;
405 const double total_u_perc = total_bytes / double(total_alloced) * 100.0;
407 tty->print_cr(fmt, "ro", ro_bytes, ro_t_perc, ro_alloced, ro_u_perc, ro_space->bottom());
408 tty->print_cr(fmt, "rw", rw_bytes, rw_t_perc, rw_alloced, rw_u_perc, rw_space->bottom());
409 tty->print_cr(fmt, "md", md_bytes, md_t_perc, md_alloced, md_u_perc, md_low);
410 tty->print_cr(fmt, "mc", mc_bytes, mc_t_perc, mc_alloced, mc_u_perc, mc_low);
411 tty->print_cr("total : %9d [100.0%% of total] out of %9d bytes [%4.1f%% used]",
412 total_bytes, total_alloced, total_u_perc);
414 // Update the vtable pointers in all of the Klass objects in the
415 // heap. They should point to newly generated vtable.
416 patch_klass_vtables(vtbl_list, vtable);
418 // dunno what this is for.
419 char* saved_vtbl = (char*)os::malloc(vtbl_list_size * sizeof(void*), mtClass);
420 memmove(saved_vtbl, vtbl_list, vtbl_list_size * sizeof(void*));
421 memset(vtbl_list, 0, vtbl_list_size * sizeof(void*));
423 // Create and write the archive file that maps the shared spaces.
425 FileMapInfo* mapinfo = new FileMapInfo();
426 mapinfo->populate_header(MetaspaceShared::max_alignment());
428 // Pass 1 - update file offsets in header.
429 mapinfo->write_header();
430 mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
431 mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
432 mapinfo->write_region(MetaspaceShared::md, _md_vs.low(),
433 pointer_delta(md_top, _md_vs.low(), sizeof(char)),
434 SharedMiscDataSize,
435 false, false);
436 mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(),
437 pointer_delta(mc_top, _mc_vs.low(), sizeof(char)),
438 SharedMiscCodeSize,
439 true, true);
441 // Pass 2 - write data.
442 mapinfo->open_for_write();
443 mapinfo->write_header();
444 mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
445 mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
446 mapinfo->write_region(MetaspaceShared::md, _md_vs.low(),
447 pointer_delta(md_top, _md_vs.low(), sizeof(char)),
448 SharedMiscDataSize,
449 false, false);
450 mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(),
451 pointer_delta(mc_top, _mc_vs.low(), sizeof(char)),
452 SharedMiscCodeSize,
453 true, true);
454 mapinfo->close();
456 memmove(vtbl_list, saved_vtbl, vtbl_list_size * sizeof(void*));
457 }
459 static void link_shared_classes(Klass* obj, TRAPS) {
460 Klass* k = obj;
461 if (k->oop_is_instance()) {
462 InstanceKlass* ik = (InstanceKlass*) k;
463 // Link the class to cause the bytecodes to be rewritten and the
464 // cpcache to be created.
465 if (ik->init_state() < InstanceKlass::linked) {
466 ik->link_class(THREAD);
467 guarantee(!HAS_PENDING_EXCEPTION, "exception in class rewriting");
468 }
469 }
470 }
473 // Support for a simple checksum of the contents of the class list
474 // file to prevent trivial tampering. The algorithm matches that in
475 // the MakeClassList program used by the J2SE build process.
476 #define JSUM_SEED ((jlong)CONST64(0xcafebabebabecafe))
477 static jlong
478 jsum(jlong start, const char *buf, const int len)
479 {
480 jlong h = start;
481 char *p = (char *)buf, *e = p + len;
482 while (p < e) {
483 char c = *p++;
484 if (c <= ' ') {
485 /* Skip spaces and control characters */
486 continue;
487 }
488 h = 31 * h + c;
489 }
490 return h;
491 }
493 // Preload classes from a list, populate the shared spaces and dump to a
494 // file.
495 void MetaspaceShared::preload_and_dump(TRAPS) {
496 TraceTime timer("Dump Shared Spaces", TraceStartupTime);
497 ResourceMark rm;
499 // Lock out GC - is it necessary? I don't think we care.
500 No_GC_Verifier no_gc;
502 // Preload classes to be shared.
503 // Should use some os:: method rather than fopen() here. aB.
504 // Construct the path to the class list (in jre/lib)
505 // Walk up two directories from the location of the VM and
506 // optionally tack on "lib" (depending on platform)
507 char class_list_path[JVM_MAXPATHLEN];
508 os::jvm_path(class_list_path, sizeof(class_list_path));
509 for (int i = 0; i < 3; i++) {
510 char *end = strrchr(class_list_path, *os::file_separator());
511 if (end != NULL) *end = '\0';
512 }
513 int class_list_path_len = (int)strlen(class_list_path);
514 if (class_list_path_len >= 3) {
515 if (strcmp(class_list_path + class_list_path_len - 3, "lib") != 0) {
516 strcat(class_list_path, os::file_separator());
517 strcat(class_list_path, "lib");
518 }
519 }
520 strcat(class_list_path, os::file_separator());
521 strcat(class_list_path, "classlist");
523 FILE* file = fopen(class_list_path, "r");
524 if (file != NULL) {
525 jlong computed_jsum = JSUM_SEED;
526 jlong file_jsum = 0;
528 char class_name[256];
529 int class_count = 0;
530 GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>();
532 // sun.io.Converters
533 static const char obj_array_sig[] = "[[Ljava/lang/Object;";
534 SymbolTable::new_permanent_symbol(obj_array_sig, THREAD);
536 // java.util.HashMap
537 static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;";
538 SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD);
540 tty->print("Loading classes to share ... ");
541 while ((fgets(class_name, sizeof class_name, file)) != NULL) {
542 if (*class_name == '#') {
543 jint fsh, fsl;
544 if (sscanf(class_name, "# %8x%8x\n", &fsh, &fsl) == 2) {
545 file_jsum = ((jlong)(fsh) << 32) | (fsl & 0xffffffff);
546 }
548 continue;
549 }
550 // Remove trailing newline
551 size_t name_len = strlen(class_name);
552 class_name[name_len-1] = '\0';
554 computed_jsum = jsum(computed_jsum, class_name, (const int)name_len - 1);
556 // Got a class name - load it.
557 TempNewSymbol class_name_symbol = SymbolTable::new_permanent_symbol(class_name, THREAD);
558 guarantee(!HAS_PENDING_EXCEPTION, "Exception creating a symbol.");
559 Klass* klass = SystemDictionary::resolve_or_null(class_name_symbol,
560 THREAD);
561 guarantee(!HAS_PENDING_EXCEPTION, "Exception resolving a class.");
562 if (klass != NULL) {
563 if (PrintSharedSpaces && Verbose && WizardMode) {
564 tty->print_cr("Shared spaces preloaded: %s", class_name);
565 }
568 InstanceKlass* ik = InstanceKlass::cast(klass);
570 // Should be class load order as per -XX:+TraceClassLoadingPreorder
571 class_promote_order->append(ik);
573 // Link the class to cause the bytecodes to be rewritten and the
574 // cpcache to be created. The linking is done as soon as classes
575 // are loaded in order that the related data structures (klass and
576 // cpCache) are located together.
578 if (ik->init_state() < InstanceKlass::linked) {
579 ik->link_class(THREAD);
580 guarantee(!(HAS_PENDING_EXCEPTION), "exception in class rewriting");
581 }
583 // TODO: Resolve klasses in constant pool
584 ik->constants()->resolve_class_constants(THREAD);
586 class_count++;
587 } else {
588 if (PrintSharedSpaces && Verbose && WizardMode) {
589 tty->cr();
590 tty->print_cr(" Preload failed: %s", class_name);
591 }
592 }
593 file_jsum = 0; // Checksum must be on last line of file
594 }
595 if (computed_jsum != file_jsum) {
596 tty->cr();
597 tty->print_cr("Preload failed: checksum of class list was incorrect.");
598 exit(1);
599 }
601 tty->print_cr("done. ");
603 if (PrintSharedSpaces) {
604 tty->print_cr("Shared spaces: preloaded %d classes", class_count);
605 }
607 // Rewrite and unlink classes.
608 tty->print("Rewriting and linking classes ... ");
610 // Link any classes which got missed. (It's not quite clear why
611 // they got missed.) This iteration would be unsafe if we weren't
612 // single-threaded at this point; however we can't do it on the VM
613 // thread because it requires object allocation.
614 SystemDictionary::classes_do(link_shared_classes, CATCH);
615 tty->print_cr("done. ");
617 // Create and dump the shared spaces. Everything so far is loaded
618 // with the null class loader.
619 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
620 VM_PopulateDumpSharedSpace op(loader_data, class_promote_order);
621 VMThread::execute(&op);
623 } else {
624 char errmsg[JVM_MAXPATHLEN];
625 os::lasterror(errmsg, JVM_MAXPATHLEN);
626 tty->print_cr("Loading classlist failed: %s", errmsg);
627 exit(1);
628 }
630 // Since various initialization steps have been undone by this process,
631 // it is not reasonable to continue running a java process.
632 exit(0);
633 }
636 // Closure for serializing initialization data in from a data area
637 // (ptr_array) read from the shared file.
639 class ReadClosure : public SerializeClosure {
640 private:
641 intptr_t** _ptr_array;
643 inline intptr_t nextPtr() {
644 return *(*_ptr_array)++;
645 }
647 public:
648 ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
650 void do_ptr(void** p) {
651 assert(*p == NULL, "initializing previous initialized pointer.");
652 intptr_t obj = nextPtr();
653 assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
654 "hit tag while initializing ptrs.");
655 *p = (void*)obj;
656 }
658 void do_tag(int tag) {
659 int old_tag;
660 old_tag = (int)(intptr_t)nextPtr();
661 // do_int(&old_tag);
662 assert(tag == old_tag, "old tag doesn't match");
663 FileMapInfo::assert_mark(tag == old_tag);
664 }
666 void do_region(u_char* start, size_t size) {
667 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
668 assert(size % sizeof(intptr_t) == 0, "bad size");
669 do_tag((int)size);
670 while (size > 0) {
671 *(intptr_t*)start = nextPtr();
672 start += sizeof(intptr_t);
673 size -= sizeof(intptr_t);
674 }
675 }
677 bool reading() const { return true; }
678 };
681 // Save bounds of shared spaces mapped in.
682 static char* _ro_base = NULL;
683 static char* _rw_base = NULL;
684 static char* _md_base = NULL;
685 static char* _mc_base = NULL;
687 // Return true if given address is in the mapped shared space.
688 bool MetaspaceShared::is_in_shared_space(const void* p) {
689 if (_ro_base == NULL || _rw_base == NULL) {
690 return false;
691 } else {
692 return ((p >= _ro_base && p < (_ro_base + SharedReadOnlySize)) ||
693 (p >= _rw_base && p < (_rw_base + SharedReadWriteSize)));
694 }
695 }
697 void MetaspaceShared::print_shared_spaces() {
698 gclog_or_tty->print_cr("Shared Spaces:");
699 gclog_or_tty->print(" read-only " INTPTR_FORMAT "-" INTPTR_FORMAT,
700 _ro_base, _ro_base + SharedReadOnlySize);
701 gclog_or_tty->print(" read-write " INTPTR_FORMAT "-" INTPTR_FORMAT,
702 _rw_base, _rw_base + SharedReadWriteSize);
703 gclog_or_tty->cr();
704 gclog_or_tty->print(" misc-data " INTPTR_FORMAT "-" INTPTR_FORMAT,
705 _md_base, _md_base + SharedMiscDataSize);
706 gclog_or_tty->print(" misc-code " INTPTR_FORMAT "-" INTPTR_FORMAT,
707 _mc_base, _mc_base + SharedMiscCodeSize);
708 gclog_or_tty->cr();
709 }
712 // Map shared spaces at requested addresses and return if succeeded.
713 // Need to keep the bounds of the ro and rw space for the Metaspace::contains
714 // call, or is_in_shared_space.
715 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) {
716 size_t image_alignment = mapinfo->alignment();
718 #ifndef _WINDOWS
719 // Map in the shared memory and then map the regions on top of it.
720 // On Windows, don't map the memory here because it will cause the
721 // mappings of the regions to fail.
722 ReservedSpace shared_rs = mapinfo->reserve_shared_memory();
723 if (!shared_rs.is_reserved()) return false;
724 #endif
726 assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
728 // Map each shared region
729 if ((_ro_base = mapinfo->map_region(ro)) != NULL &&
730 (_rw_base = mapinfo->map_region(rw)) != NULL &&
731 (_md_base = mapinfo->map_region(md)) != NULL &&
732 (_mc_base = mapinfo->map_region(mc)) != NULL &&
733 (image_alignment == (size_t)max_alignment())) {
734 // Success (no need to do anything)
735 return true;
736 } else {
737 // If there was a failure in mapping any of the spaces, unmap the ones
738 // that succeeded
739 if (_ro_base != NULL) mapinfo->unmap_region(ro);
740 if (_rw_base != NULL) mapinfo->unmap_region(rw);
741 if (_md_base != NULL) mapinfo->unmap_region(md);
742 if (_mc_base != NULL) mapinfo->unmap_region(mc);
743 #ifndef _WINDOWS
744 // Release the entire mapped region
745 shared_rs.release();
746 #endif
747 // If -Xshare:on is specified, print out the error message and exit VM,
748 // otherwise, set UseSharedSpaces to false and continue.
749 if (RequireSharedSpaces) {
750 vm_exit_during_initialization("Unable to use shared archive.", NULL);
751 } else {
752 FLAG_SET_DEFAULT(UseSharedSpaces, false);
753 }
754 return false;
755 }
756 }
758 // Read the miscellaneous data from the shared file, and
759 // serialize it out to its various destinations.
761 void MetaspaceShared::initialize_shared_spaces() {
762 FileMapInfo *mapinfo = FileMapInfo::current_info();
764 char* buffer = mapinfo->region_base(md);
766 // Skip over (reserve space for) a list of addresses of C++ vtables
767 // for Klass objects. They get filled in later.
769 void** vtbl_list = (void**)buffer;
770 buffer += MetaspaceShared::vtbl_list_size * sizeof(void*);
771 Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
773 // Skip over (reserve space for) dummy C++ vtables Klass objects.
774 // They are used as is.
776 intptr_t vtable_size = *(intptr_t*)buffer;
777 buffer += sizeof(intptr_t);
778 buffer += vtable_size;
780 // Create the symbol table using the bucket array at this spot in the
781 // misc data space. Since the symbol table is often modified, this
782 // region (of mapped pages) will be copy-on-write.
784 int symbolTableLen = *(intptr_t*)buffer;
785 buffer += sizeof(intptr_t);
786 int number_of_entries = *(intptr_t*)buffer;
787 buffer += sizeof(intptr_t);
788 SymbolTable::create_table((HashtableBucket<mtSymbol>*)buffer, symbolTableLen,
789 number_of_entries);
790 buffer += symbolTableLen;
792 // Create the shared dictionary using the bucket array at this spot in
793 // the misc data space. Since the shared dictionary table is never
794 // modified, this region (of mapped pages) will be (effectively, if
795 // not explicitly) read-only.
797 int sharedDictionaryLen = *(intptr_t*)buffer;
798 buffer += sizeof(intptr_t);
799 number_of_entries = *(intptr_t*)buffer;
800 buffer += sizeof(intptr_t);
801 SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer,
802 sharedDictionaryLen,
803 number_of_entries);
804 buffer += sharedDictionaryLen;
806 // Create the package info table using the bucket array at this spot in
807 // the misc data space. Since the package info table is never
808 // modified, this region (of mapped pages) will be (effectively, if
809 // not explicitly) read-only.
811 int pkgInfoLen = *(intptr_t*)buffer;
812 buffer += sizeof(intptr_t);
813 number_of_entries = *(intptr_t*)buffer;
814 buffer += sizeof(intptr_t);
815 ClassLoader::create_package_info_table((HashtableBucket<mtClass>*)buffer, pkgInfoLen,
816 number_of_entries);
817 buffer += pkgInfoLen;
818 ClassLoader::verify();
820 // The following data in the shared misc data region are the linked
821 // list elements (HashtableEntry objects) for the symbol table, string
822 // table, and shared dictionary. The heap objects refered to by the
823 // symbol table, string table, and shared dictionary are permanent and
824 // unmovable. Since new entries added to the string and symbol tables
825 // are always added at the beginning of the linked lists, THESE LINKED
826 // LIST ELEMENTS ARE READ-ONLY.
828 int len = *(intptr_t*)buffer; // skip over symbol table entries
829 buffer += sizeof(intptr_t);
830 buffer += len;
832 len = *(intptr_t*)buffer; // skip over shared dictionary entries
833 buffer += sizeof(intptr_t);
834 buffer += len;
836 len = *(intptr_t*)buffer; // skip over package info table entries
837 buffer += sizeof(intptr_t);
838 buffer += len;
840 len = *(intptr_t*)buffer; // skip over package info table char[] arrays.
841 buffer += sizeof(intptr_t);
842 buffer += len;
844 intptr_t* array = (intptr_t*)buffer;
845 ReadClosure rc(&array);
846 serialize(&rc);
848 // Close the mapinfo file
849 mapinfo->close();
850 }
852 // JVM/TI RedefineClasses() support:
853 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
854 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
856 if (UseSharedSpaces) {
857 // remap the shared readonly space to shared readwrite, private
858 FileMapInfo* mapinfo = FileMapInfo::current_info();
859 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
860 return false;
861 }
862 }
863 return true;
864 }