Fri, 01 Feb 2013 23:48:08 +0100
8005012: Add WB APIs to better support NMT testing
Summary: Add WB API functions to enable better NMT testing
Reviewed-by: dholmes, zgu
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();
379 const size_t BPW = BytesPerWord;
381 // Allocated size of each space (may not be all occupied)
382 const size_t ro_alloced = ro_space->capacity_words(Metaspace::NonClassType) * BPW;
383 const size_t rw_alloced = rw_space->capacity_words(Metaspace::NonClassType) * BPW;
384 const size_t md_alloced = md_end-md_low;
385 const size_t mc_alloced = mc_end-mc_low;
386 const size_t total_alloced = ro_alloced + rw_alloced + md_alloced + mc_alloced;
388 // Occupied size of each space.
389 const size_t ro_bytes = ro_space->used_words(Metaspace::NonClassType) * BPW;
390 const size_t rw_bytes = rw_space->used_words(Metaspace::NonClassType) * BPW;
391 const size_t md_bytes = size_t(md_top - md_low);
392 const size_t mc_bytes = size_t(mc_top - mc_low);
394 // Percent of total size
395 const size_t total_bytes = ro_bytes + rw_bytes + md_bytes + mc_bytes;
396 const double ro_t_perc = ro_bytes / double(total_bytes) * 100.0;
397 const double rw_t_perc = rw_bytes / double(total_bytes) * 100.0;
398 const double md_t_perc = md_bytes / double(total_bytes) * 100.0;
399 const double mc_t_perc = mc_bytes / double(total_bytes) * 100.0;
401 // Percent of fullness of each space
402 const double ro_u_perc = ro_bytes / double(ro_alloced) * 100.0;
403 const double rw_u_perc = rw_bytes / double(rw_alloced) * 100.0;
404 const double md_u_perc = md_bytes / double(md_alloced) * 100.0;
405 const double mc_u_perc = mc_bytes / double(mc_alloced) * 100.0;
406 const double total_u_perc = total_bytes / double(total_alloced) * 100.0;
408 tty->print_cr(fmt, "ro", ro_bytes, ro_t_perc, ro_alloced, ro_u_perc, ro_space->bottom());
409 tty->print_cr(fmt, "rw", rw_bytes, rw_t_perc, rw_alloced, rw_u_perc, rw_space->bottom());
410 tty->print_cr(fmt, "md", md_bytes, md_t_perc, md_alloced, md_u_perc, md_low);
411 tty->print_cr(fmt, "mc", mc_bytes, mc_t_perc, mc_alloced, mc_u_perc, mc_low);
412 tty->print_cr("total : %9d [100.0%% of total] out of %9d bytes [%4.1f%% used]",
413 total_bytes, total_alloced, total_u_perc);
415 // Update the vtable pointers in all of the Klass objects in the
416 // heap. They should point to newly generated vtable.
417 patch_klass_vtables(vtbl_list, vtable);
419 // dunno what this is for.
420 char* saved_vtbl = (char*)os::malloc(vtbl_list_size * sizeof(void*), mtClass);
421 memmove(saved_vtbl, vtbl_list, vtbl_list_size * sizeof(void*));
422 memset(vtbl_list, 0, vtbl_list_size * sizeof(void*));
424 // Create and write the archive file that maps the shared spaces.
426 FileMapInfo* mapinfo = new FileMapInfo();
427 mapinfo->populate_header(MetaspaceShared::max_alignment());
429 // Pass 1 - update file offsets in header.
430 mapinfo->write_header();
431 mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
432 mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
433 mapinfo->write_region(MetaspaceShared::md, _md_vs.low(),
434 pointer_delta(md_top, _md_vs.low(), sizeof(char)),
435 SharedMiscDataSize,
436 false, false);
437 mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(),
438 pointer_delta(mc_top, _mc_vs.low(), sizeof(char)),
439 SharedMiscCodeSize,
440 true, true);
442 // Pass 2 - write data.
443 mapinfo->open_for_write();
444 mapinfo->write_header();
445 mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true);
446 mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false);
447 mapinfo->write_region(MetaspaceShared::md, _md_vs.low(),
448 pointer_delta(md_top, _md_vs.low(), sizeof(char)),
449 SharedMiscDataSize,
450 false, false);
451 mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(),
452 pointer_delta(mc_top, _mc_vs.low(), sizeof(char)),
453 SharedMiscCodeSize,
454 true, true);
455 mapinfo->close();
457 memmove(vtbl_list, saved_vtbl, vtbl_list_size * sizeof(void*));
458 }
460 static void link_shared_classes(Klass* obj, TRAPS) {
461 Klass* k = obj;
462 if (k->oop_is_instance()) {
463 InstanceKlass* ik = (InstanceKlass*) k;
464 // Link the class to cause the bytecodes to be rewritten and the
465 // cpcache to be created.
466 if (ik->init_state() < InstanceKlass::linked) {
467 ik->link_class(THREAD);
468 guarantee(!HAS_PENDING_EXCEPTION, "exception in class rewriting");
469 }
470 }
471 }
474 // Support for a simple checksum of the contents of the class list
475 // file to prevent trivial tampering. The algorithm matches that in
476 // the MakeClassList program used by the J2SE build process.
477 #define JSUM_SEED ((jlong)CONST64(0xcafebabebabecafe))
478 static jlong
479 jsum(jlong start, const char *buf, const int len)
480 {
481 jlong h = start;
482 char *p = (char *)buf, *e = p + len;
483 while (p < e) {
484 char c = *p++;
485 if (c <= ' ') {
486 /* Skip spaces and control characters */
487 continue;
488 }
489 h = 31 * h + c;
490 }
491 return h;
492 }
494 // Preload classes from a list, populate the shared spaces and dump to a
495 // file.
496 void MetaspaceShared::preload_and_dump(TRAPS) {
497 TraceTime timer("Dump Shared Spaces", TraceStartupTime);
498 ResourceMark rm;
500 // Lock out GC - is it necessary? I don't think we care.
501 No_GC_Verifier no_gc;
503 // Preload classes to be shared.
504 // Should use some os:: method rather than fopen() here. aB.
505 // Construct the path to the class list (in jre/lib)
506 // Walk up two directories from the location of the VM and
507 // optionally tack on "lib" (depending on platform)
508 char class_list_path[JVM_MAXPATHLEN];
509 os::jvm_path(class_list_path, sizeof(class_list_path));
510 for (int i = 0; i < 3; i++) {
511 char *end = strrchr(class_list_path, *os::file_separator());
512 if (end != NULL) *end = '\0';
513 }
514 int class_list_path_len = (int)strlen(class_list_path);
515 if (class_list_path_len >= 3) {
516 if (strcmp(class_list_path + class_list_path_len - 3, "lib") != 0) {
517 strcat(class_list_path, os::file_separator());
518 strcat(class_list_path, "lib");
519 }
520 }
521 strcat(class_list_path, os::file_separator());
522 strcat(class_list_path, "classlist");
524 FILE* file = fopen(class_list_path, "r");
525 if (file != NULL) {
526 jlong computed_jsum = JSUM_SEED;
527 jlong file_jsum = 0;
529 char class_name[256];
530 int class_count = 0;
531 GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>();
533 // sun.io.Converters
534 static const char obj_array_sig[] = "[[Ljava/lang/Object;";
535 SymbolTable::new_permanent_symbol(obj_array_sig, THREAD);
537 // java.util.HashMap
538 static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;";
539 SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD);
541 tty->print("Loading classes to share ... ");
542 while ((fgets(class_name, sizeof class_name, file)) != NULL) {
543 if (*class_name == '#') {
544 jint fsh, fsl;
545 if (sscanf(class_name, "# %8x%8x\n", &fsh, &fsl) == 2) {
546 file_jsum = ((jlong)(fsh) << 32) | (fsl & 0xffffffff);
547 }
549 continue;
550 }
551 // Remove trailing newline
552 size_t name_len = strlen(class_name);
553 class_name[name_len-1] = '\0';
555 computed_jsum = jsum(computed_jsum, class_name, (const int)name_len - 1);
557 // Got a class name - load it.
558 TempNewSymbol class_name_symbol = SymbolTable::new_permanent_symbol(class_name, THREAD);
559 guarantee(!HAS_PENDING_EXCEPTION, "Exception creating a symbol.");
560 Klass* klass = SystemDictionary::resolve_or_null(class_name_symbol,
561 THREAD);
562 guarantee(!HAS_PENDING_EXCEPTION, "Exception resolving a class.");
563 if (klass != NULL) {
564 if (PrintSharedSpaces && Verbose && WizardMode) {
565 tty->print_cr("Shared spaces preloaded: %s", class_name);
566 }
569 InstanceKlass* ik = InstanceKlass::cast(klass);
571 // Should be class load order as per -XX:+TraceClassLoadingPreorder
572 class_promote_order->append(ik);
574 // Link the class to cause the bytecodes to be rewritten and the
575 // cpcache to be created. The linking is done as soon as classes
576 // are loaded in order that the related data structures (klass and
577 // cpCache) are located together.
579 if (ik->init_state() < InstanceKlass::linked) {
580 ik->link_class(THREAD);
581 guarantee(!(HAS_PENDING_EXCEPTION), "exception in class rewriting");
582 }
584 // TODO: Resolve klasses in constant pool
585 ik->constants()->resolve_class_constants(THREAD);
587 class_count++;
588 } else {
589 if (PrintSharedSpaces && Verbose && WizardMode) {
590 tty->cr();
591 tty->print_cr(" Preload failed: %s", class_name);
592 }
593 }
594 file_jsum = 0; // Checksum must be on last line of file
595 }
596 if (computed_jsum != file_jsum) {
597 tty->cr();
598 tty->print_cr("Preload failed: checksum of class list was incorrect.");
599 exit(1);
600 }
602 tty->print_cr("done. ");
604 if (PrintSharedSpaces) {
605 tty->print_cr("Shared spaces: preloaded %d classes", class_count);
606 }
608 // Rewrite and unlink classes.
609 tty->print("Rewriting and linking classes ... ");
611 // Link any classes which got missed. (It's not quite clear why
612 // they got missed.) This iteration would be unsafe if we weren't
613 // single-threaded at this point; however we can't do it on the VM
614 // thread because it requires object allocation.
615 SystemDictionary::classes_do(link_shared_classes, CATCH);
616 tty->print_cr("done. ");
618 // Create and dump the shared spaces. Everything so far is loaded
619 // with the null class loader.
620 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
621 VM_PopulateDumpSharedSpace op(loader_data, class_promote_order);
622 VMThread::execute(&op);
624 } else {
625 char errmsg[JVM_MAXPATHLEN];
626 os::lasterror(errmsg, JVM_MAXPATHLEN);
627 tty->print_cr("Loading classlist failed: %s", errmsg);
628 exit(1);
629 }
631 // Since various initialization steps have been undone by this process,
632 // it is not reasonable to continue running a java process.
633 exit(0);
634 }
637 // Closure for serializing initialization data in from a data area
638 // (ptr_array) read from the shared file.
640 class ReadClosure : public SerializeClosure {
641 private:
642 intptr_t** _ptr_array;
644 inline intptr_t nextPtr() {
645 return *(*_ptr_array)++;
646 }
648 public:
649 ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; }
651 void do_ptr(void** p) {
652 assert(*p == NULL, "initializing previous initialized pointer.");
653 intptr_t obj = nextPtr();
654 assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
655 "hit tag while initializing ptrs.");
656 *p = (void*)obj;
657 }
659 void do_tag(int tag) {
660 int old_tag;
661 old_tag = (int)(intptr_t)nextPtr();
662 // do_int(&old_tag);
663 assert(tag == old_tag, "old tag doesn't match");
664 FileMapInfo::assert_mark(tag == old_tag);
665 }
667 void do_region(u_char* start, size_t size) {
668 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
669 assert(size % sizeof(intptr_t) == 0, "bad size");
670 do_tag((int)size);
671 while (size > 0) {
672 *(intptr_t*)start = nextPtr();
673 start += sizeof(intptr_t);
674 size -= sizeof(intptr_t);
675 }
676 }
678 bool reading() const { return true; }
679 };
682 // Save bounds of shared spaces mapped in.
683 static char* _ro_base = NULL;
684 static char* _rw_base = NULL;
685 static char* _md_base = NULL;
686 static char* _mc_base = NULL;
688 // Return true if given address is in the mapped shared space.
689 bool MetaspaceShared::is_in_shared_space(const void* p) {
690 if (_ro_base == NULL || _rw_base == NULL) {
691 return false;
692 } else {
693 return ((p >= _ro_base && p < (_ro_base + SharedReadOnlySize)) ||
694 (p >= _rw_base && p < (_rw_base + SharedReadWriteSize)));
695 }
696 }
698 void MetaspaceShared::print_shared_spaces() {
699 gclog_or_tty->print_cr("Shared Spaces:");
700 gclog_or_tty->print(" read-only " INTPTR_FORMAT "-" INTPTR_FORMAT,
701 _ro_base, _ro_base + SharedReadOnlySize);
702 gclog_or_tty->print(" read-write " INTPTR_FORMAT "-" INTPTR_FORMAT,
703 _rw_base, _rw_base + SharedReadWriteSize);
704 gclog_or_tty->cr();
705 gclog_or_tty->print(" misc-data " INTPTR_FORMAT "-" INTPTR_FORMAT,
706 _md_base, _md_base + SharedMiscDataSize);
707 gclog_or_tty->print(" misc-code " INTPTR_FORMAT "-" INTPTR_FORMAT,
708 _mc_base, _mc_base + SharedMiscCodeSize);
709 gclog_or_tty->cr();
710 }
713 // Map shared spaces at requested addresses and return if succeeded.
714 // Need to keep the bounds of the ro and rw space for the Metaspace::contains
715 // call, or is_in_shared_space.
716 bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) {
717 size_t image_alignment = mapinfo->alignment();
719 #ifndef _WINDOWS
720 // Map in the shared memory and then map the regions on top of it.
721 // On Windows, don't map the memory here because it will cause the
722 // mappings of the regions to fail.
723 ReservedSpace shared_rs = mapinfo->reserve_shared_memory();
724 if (!shared_rs.is_reserved()) return false;
725 #endif
727 assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
729 // Map each shared region
730 if ((_ro_base = mapinfo->map_region(ro)) != NULL &&
731 (_rw_base = mapinfo->map_region(rw)) != NULL &&
732 (_md_base = mapinfo->map_region(md)) != NULL &&
733 (_mc_base = mapinfo->map_region(mc)) != NULL &&
734 (image_alignment == (size_t)max_alignment())) {
735 // Success (no need to do anything)
736 return true;
737 } else {
738 // If there was a failure in mapping any of the spaces, unmap the ones
739 // that succeeded
740 if (_ro_base != NULL) mapinfo->unmap_region(ro);
741 if (_rw_base != NULL) mapinfo->unmap_region(rw);
742 if (_md_base != NULL) mapinfo->unmap_region(md);
743 if (_mc_base != NULL) mapinfo->unmap_region(mc);
744 #ifndef _WINDOWS
745 // Release the entire mapped region
746 shared_rs.release();
747 #endif
748 // If -Xshare:on is specified, print out the error message and exit VM,
749 // otherwise, set UseSharedSpaces to false and continue.
750 if (RequireSharedSpaces) {
751 vm_exit_during_initialization("Unable to use shared archive.", NULL);
752 } else {
753 FLAG_SET_DEFAULT(UseSharedSpaces, false);
754 }
755 return false;
756 }
757 }
759 // Read the miscellaneous data from the shared file, and
760 // serialize it out to its various destinations.
762 void MetaspaceShared::initialize_shared_spaces() {
763 FileMapInfo *mapinfo = FileMapInfo::current_info();
765 char* buffer = mapinfo->region_base(md);
767 // Skip over (reserve space for) a list of addresses of C++ vtables
768 // for Klass objects. They get filled in later.
770 void** vtbl_list = (void**)buffer;
771 buffer += MetaspaceShared::vtbl_list_size * sizeof(void*);
772 Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size);
774 // Skip over (reserve space for) dummy C++ vtables Klass objects.
775 // They are used as is.
777 intptr_t vtable_size = *(intptr_t*)buffer;
778 buffer += sizeof(intptr_t);
779 buffer += vtable_size;
781 // Create the symbol table using the bucket array at this spot in the
782 // misc data space. Since the symbol table is often modified, this
783 // region (of mapped pages) will be copy-on-write.
785 int symbolTableLen = *(intptr_t*)buffer;
786 buffer += sizeof(intptr_t);
787 int number_of_entries = *(intptr_t*)buffer;
788 buffer += sizeof(intptr_t);
789 SymbolTable::create_table((HashtableBucket<mtSymbol>*)buffer, symbolTableLen,
790 number_of_entries);
791 buffer += symbolTableLen;
793 // Create the shared dictionary using the bucket array at this spot in
794 // the misc data space. Since the shared dictionary table is never
795 // modified, this region (of mapped pages) will be (effectively, if
796 // not explicitly) read-only.
798 int sharedDictionaryLen = *(intptr_t*)buffer;
799 buffer += sizeof(intptr_t);
800 number_of_entries = *(intptr_t*)buffer;
801 buffer += sizeof(intptr_t);
802 SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer,
803 sharedDictionaryLen,
804 number_of_entries);
805 buffer += sharedDictionaryLen;
807 // Create the package info table using the bucket array at this spot in
808 // the misc data space. Since the package info table is never
809 // modified, this region (of mapped pages) will be (effectively, if
810 // not explicitly) read-only.
812 int pkgInfoLen = *(intptr_t*)buffer;
813 buffer += sizeof(intptr_t);
814 number_of_entries = *(intptr_t*)buffer;
815 buffer += sizeof(intptr_t);
816 ClassLoader::create_package_info_table((HashtableBucket<mtClass>*)buffer, pkgInfoLen,
817 number_of_entries);
818 buffer += pkgInfoLen;
819 ClassLoader::verify();
821 // The following data in the shared misc data region are the linked
822 // list elements (HashtableEntry objects) for the symbol table, string
823 // table, and shared dictionary. The heap objects refered to by the
824 // symbol table, string table, and shared dictionary are permanent and
825 // unmovable. Since new entries added to the string and symbol tables
826 // are always added at the beginning of the linked lists, THESE LINKED
827 // LIST ELEMENTS ARE READ-ONLY.
829 int len = *(intptr_t*)buffer; // skip over symbol table entries
830 buffer += sizeof(intptr_t);
831 buffer += len;
833 len = *(intptr_t*)buffer; // skip over shared dictionary entries
834 buffer += sizeof(intptr_t);
835 buffer += len;
837 len = *(intptr_t*)buffer; // skip over package info table entries
838 buffer += sizeof(intptr_t);
839 buffer += len;
841 len = *(intptr_t*)buffer; // skip over package info table char[] arrays.
842 buffer += sizeof(intptr_t);
843 buffer += len;
845 intptr_t* array = (intptr_t*)buffer;
846 ReadClosure rc(&array);
847 serialize(&rc);
849 // Close the mapinfo file
850 mapinfo->close();
851 }
853 // JVM/TI RedefineClasses() support:
854 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
855 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
857 if (UseSharedSpaces) {
858 // remap the shared readonly space to shared readwrite, private
859 FileMapInfo* mapinfo = FileMapInfo::current_info();
860 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
861 return false;
862 }
863 }
864 return true;
865 }