1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotClassLocation.hpp"
26 #include "cds/cds_globals.hpp"
27 #include "cds/cdsConfig.hpp"
28 #include "cds/dynamicArchive.hpp"
29 #include "cds/heapShared.hpp"
30 #include "classfile/classFileStream.hpp"
31 #include "classfile/classLoader.inline.hpp"
32 #include "classfile/classLoaderData.inline.hpp"
33 #include "classfile/classLoadInfo.hpp"
34 #include "classfile/javaClasses.hpp"
35 #include "classfile/klassFactory.hpp"
36 #include "classfile/moduleEntry.hpp"
37 #include "classfile/modules.hpp"
38 #include "classfile/packageEntry.hpp"
39 #include "classfile/symbolTable.hpp"
40 #include "classfile/systemDictionary.hpp"
41 #include "classfile/systemDictionaryShared.hpp"
42 #include "classfile/vmClasses.hpp"
43 #include "classfile/vmSymbols.hpp"
44 #include "compiler/compileBroker.hpp"
45 #include "cppstdlib/cstdlib.hpp"
46 #include "interpreter/bytecodeStream.hpp"
47 #include "interpreter/oopMapCache.hpp"
48 #include "jimage.hpp"
49 #include "jvm.h"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "logging/logTag.hpp"
53 #include "memory/allocation.inline.hpp"
54 #include "memory/oopFactory.hpp"
55 #include "memory/resourceArea.hpp"
56 #include "memory/universe.hpp"
57 #include "oops/instanceKlass.hpp"
58 #include "oops/instanceRefKlass.hpp"
59 #include "oops/klass.inline.hpp"
60 #include "oops/method.inline.hpp"
61 #include "oops/objArrayOop.inline.hpp"
62 #include "oops/oop.inline.hpp"
63 #include "oops/symbol.hpp"
64 #include "prims/jvm_misc.hpp"
65 #include "runtime/arguments.hpp"
66 #include "runtime/handles.inline.hpp"
67 #include "runtime/init.hpp"
68 #include "runtime/interfaceSupport.inline.hpp"
69 #include "runtime/java.hpp"
70 #include "runtime/javaCalls.hpp"
71 #include "runtime/os.hpp"
72 #include "runtime/perfData.inline.hpp"
73 #include "runtime/timer.hpp"
74 #include "runtime/vm_version.hpp"
75 #include "services/management.hpp"
76 #include "services/threadService.hpp"
77 #include "utilities/checkedCast.hpp"
78 #include "utilities/classpathStream.hpp"
79 #include "utilities/events.hpp"
80 #include "utilities/macros.hpp"
81 #include "utilities/ostream.hpp"
82 #include "utilities/utf8.hpp"
83
84 #include <ctype.h>
85
86 // Entry point in java.dll for path canonicalization
87
88 typedef int (*canonicalize_fn_t)(const char *orig, char *out, int len);
89
90 static canonicalize_fn_t CanonicalizeEntry = nullptr;
91
92 // Entry points for jimage.dll for loading jimage file entries
93
94 static JImageOpen_t JImageOpen = nullptr;
95 static JImageClose_t JImageClose = nullptr;
96 static JImageFindResource_t JImageFindResource = nullptr;
97 static JImageGetResource_t JImageGetResource = nullptr;
98
99 // JimageFile pointer, or null if exploded JDK build.
100 static JImageFile* JImage_file = nullptr;
101
102 // Globals
103
104 PerfCounter* ClassLoader::_perf_accumulated_time = nullptr;
105 PerfCounter* ClassLoader::_perf_classes_inited = nullptr;
106 PerfCounter* ClassLoader::_perf_class_init_time = nullptr;
107 PerfCounter* ClassLoader::_perf_class_init_selftime = nullptr;
108 PerfCounter* ClassLoader::_perf_class_init_bytecodes_count = nullptr;
109 PerfCounter* ClassLoader::_perf_classes_verified = nullptr;
110 PerfCounter* ClassLoader::_perf_class_verify_time = nullptr;
111 PerfCounter* ClassLoader::_perf_class_verify_selftime = nullptr;
112 PerfCounter* ClassLoader::_perf_classes_linked = nullptr;
113 PerfCounter* ClassLoader::_perf_class_link_time = nullptr;
114 PerfCounter* ClassLoader::_perf_class_link_selftime = nullptr;
115 PerfCounter* ClassLoader::_perf_shared_classload_time = nullptr;
116 PerfCounter* ClassLoader::_perf_sys_classload_time = nullptr;
117 PerfCounter* ClassLoader::_perf_app_classload_time = nullptr;
118 PerfCounter* ClassLoader::_perf_app_classload_selftime = nullptr;
119 PerfCounter* ClassLoader::_perf_app_classload_count = nullptr;
120 PerfCounter* ClassLoader::_perf_define_appclasses = nullptr;
121 PerfCounter* ClassLoader::_perf_define_appclass_time = nullptr;
122 PerfCounter* ClassLoader::_perf_define_appclass_selftime = nullptr;
123 PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = nullptr;
124 PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = nullptr;
125 PerfCounter* ClassLoader::_perf_preload_total_time = nullptr;
126 PerfCounter* ClassLoader::_perf_preload_time = nullptr;
127 PerfCounter* ClassLoader::_perf_prelink_time = nullptr;
128 PerfCounter* ClassLoader::_perf_preinit_time = nullptr;
129 PerfCounter* ClassLoader::_perf_preresolve_time = nullptr;
130 PerfCounter* ClassLoader::_perf_ik_link_methods_time = nullptr;
131 PerfCounter* ClassLoader::_perf_method_adapters_time = nullptr;
132 PerfCounter* ClassLoader::_perf_ik_link_methods_count = nullptr;
133 PerfCounter* ClassLoader::_perf_method_adapters_count = nullptr;
134 PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = nullptr;
135 PerfCounter* ClassLoader::_perf_secondary_hash_time = nullptr;
136
137 PerfTickCounters* ClassLoader::_perf_resolve_indy_time = nullptr;
138 PerfTickCounters* ClassLoader::_perf_resolve_invokehandle_time = nullptr;
139 PerfTickCounters* ClassLoader::_perf_resolve_mh_time = nullptr;
140 PerfTickCounters* ClassLoader::_perf_resolve_mt_time = nullptr;
141
142 PerfCounter* ClassLoader::_perf_resolve_indy_count = nullptr;
143 PerfCounter* ClassLoader::_perf_resolve_invokehandle_count = nullptr;
144 PerfCounter* ClassLoader::_perf_resolve_mh_count = nullptr;
145 PerfCounter* ClassLoader::_perf_resolve_mt_count = nullptr;
146
147 void ClassLoader::print_counters(outputStream *st) {
148 st->print_cr("ClassLoader:");
149 st->print_cr( " clinit: " JLONG_FORMAT_W(6) "us / " JLONG_FORMAT " events",
150 ClassLoader::class_init_time_ms(), ClassLoader::class_init_count());
151 st->print_cr(" link methods: " JLONG_FORMAT_W(6) "us / " JLONG_FORMAT " events",
152 Management::ticks_to_us(_perf_ik_link_methods_time->get_value()) , _perf_ik_link_methods_count->get_value());
153 st->print_cr(" method adapters: " JLONG_FORMAT_W(6) "us / " JLONG_FORMAT " events",
154 Management::ticks_to_us(_perf_method_adapters_time->get_value()) , _perf_method_adapters_count->get_value());
155 if (CountBytecodes || CountBytecodesPerThread) {
156 st->print_cr("; executed " JLONG_FORMAT " bytecodes", ClassLoader::class_init_bytecodes_count());
157 }
158 st->print_cr(" resolve...");
159 st->print_cr(" invokedynamic: " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) / " JLONG_FORMAT_W(5) " events",
160 _perf_resolve_indy_time->elapsed_counter_value_us(),
161 _perf_resolve_indy_time->thread_counter_value_us(),
162 _perf_resolve_indy_count->get_value());
163 st->print_cr(" invokehandle: " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) / " JLONG_FORMAT_W(5) " events",
164 _perf_resolve_invokehandle_time->elapsed_counter_value_us(),
165 _perf_resolve_invokehandle_time->thread_counter_value_us(),
166 _perf_resolve_invokehandle_count->get_value());
167 st->print_cr(" CP_MethodHandle: " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) / " JLONG_FORMAT_W(5) " events",
168 _perf_resolve_mh_time->elapsed_counter_value_us(),
169 _perf_resolve_mh_time->thread_counter_value_us(),
170 _perf_resolve_mh_count->get_value());
171 st->print_cr(" CP_MethodType: " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) / " JLONG_FORMAT_W(5) " events",
172 _perf_resolve_mt_time->elapsed_counter_value_us(),
173 _perf_resolve_mt_time->thread_counter_value_us(),
174 _perf_resolve_mt_count->get_value());
175 }
176
177 GrowableArray<ModuleClassPathList*>* ClassLoader::_patch_mod_entries = nullptr;
178 GrowableArray<ModuleClassPathList*>* ClassLoader::_exploded_entries = nullptr;
179 ClassPathEntry* ClassLoader::_jrt_entry = nullptr;
180
181 ClassPathEntry* volatile ClassLoader::_first_append_entry_list = nullptr;
182 ClassPathEntry* volatile ClassLoader::_last_append_entry = nullptr;
183
184 // helper routines
185 #if INCLUDE_CDS
186 static bool string_starts_with(const char* str, const char* str_to_find) {
187 size_t str_len = strlen(str);
188 size_t str_to_find_len = strlen(str_to_find);
189 if (str_to_find_len > str_len) {
190 return false;
191 }
192 return (strncmp(str, str_to_find, str_to_find_len) == 0);
193 }
194 #endif
195
196 static const char* get_jimage_version_string() {
197 static char version_string[10] = "";
198 if (version_string[0] == '\0') {
199 jio_snprintf(version_string, sizeof(version_string), "%d.%d",
200 VM_Version::vm_major_version(), VM_Version::vm_minor_version());
201 }
202 return (const char*)version_string;
203 }
204
205 bool ClassLoader::string_ends_with(const char* str, const char* str_to_find) {
206 size_t str_len = strlen(str);
207 size_t str_to_find_len = strlen(str_to_find);
208 if (str_to_find_len > str_len) {
209 return false;
210 }
211 return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0);
212 }
213
214 // Used to obtain the package name from a fully qualified class name.
215 Symbol* ClassLoader::package_from_class_name(const Symbol* name, bool* bad_class_name) {
216 if (name == nullptr) {
217 if (bad_class_name != nullptr) {
218 *bad_class_name = true;
219 }
220 return nullptr;
221 }
222
223 int utf_len = name->utf8_length();
224 const jbyte* base = (const jbyte*)name->base();
225 const jbyte* start = base;
226 const jbyte* end = UTF8::strrchr(start, utf_len, JVM_SIGNATURE_SLASH);
227 if (end == nullptr) {
228 return nullptr;
229 }
230 // Skip over '['s
231 if (*start == JVM_SIGNATURE_ARRAY) {
232 do {
233 start++;
234 } while (start < end && *start == JVM_SIGNATURE_ARRAY);
235
236 // Fully qualified class names should not contain a 'L'.
237 // Set bad_class_name to true to indicate that the package name
238 // could not be obtained due to an error condition.
239 // In this situation, is_same_class_package returns false.
240 if (*start == JVM_SIGNATURE_CLASS) {
241 if (bad_class_name != nullptr) {
242 *bad_class_name = true;
243 }
244 return nullptr;
245 }
246 }
247 // A class name could have just the slash character in the name,
248 // in which case start > end
249 if (start >= end) {
250 // No package name
251 if (bad_class_name != nullptr) {
252 *bad_class_name = true;
253 }
254 return nullptr;
255 }
256 return SymbolTable::new_symbol(name, pointer_delta_as_int(start, base), pointer_delta_as_int(end, base));
257 }
258
259 // Given a fully qualified package name, find its defining package in the class loader's
260 // package entry table.
261 PackageEntry* ClassLoader::get_package_entry(Symbol* pkg_name, ClassLoaderData* loader_data) {
262 if (pkg_name == nullptr) {
263 return nullptr;
264 }
265 PackageEntryTable* pkgEntryTable = loader_data->packages();
266 return pkgEntryTable->lookup_only(pkg_name);
267 }
268
269 const char* ClassPathEntry::copy_path(const char* path) {
270 char* copy = NEW_C_HEAP_ARRAY(char, strlen(path)+1, mtClass);
271 strcpy(copy, path);
272 return copy;
273 }
274
275 ClassPathDirEntry::~ClassPathDirEntry() {
276 FREE_C_HEAP_ARRAY(char, _dir);
277 }
278
279 ClassFileStream* ClassPathDirEntry::open_stream(JavaThread* current, const char* name) {
280 // construct full path name
281 assert((_dir != nullptr) && (name != nullptr), "sanity");
282 size_t path_len = strlen(_dir) + strlen(name) + strlen(os::file_separator()) + 1;
283 char* path = NEW_RESOURCE_ARRAY_IN_THREAD(current, char, path_len);
284 int len = jio_snprintf(path, path_len, "%s%s%s", _dir, os::file_separator(), name);
285 assert(len == (int)(path_len - 1), "sanity");
286 // check if file exists
287 struct stat st;
288 if (os::stat(path, &st) == 0) {
289 // found file, open it
290 int file_handle = os::open(path, 0, 0);
291 if (file_handle != -1) {
292 // read contents into resource array
293 u1* buffer = NEW_RESOURCE_ARRAY_IN_THREAD(current, u1, st.st_size);
294 size_t num_read = ::read(file_handle, (char*) buffer, st.st_size);
295 // close file
296 ::close(file_handle);
297 // construct ClassFileStream
298 if (num_read == (size_t)st.st_size) {
299 if (UsePerfData) {
300 ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);
301 }
302 #ifdef ASSERT
303 // Freeing path is a no-op here as buffer prevents it from being reclaimed. But we keep it for
304 // debug builds so that we guard against use-after-free bugs.
305 FREE_RESOURCE_ARRAY_IN_THREAD(current, char, path, path_len);
306 #endif
307 // We don't verify the length of the classfile stream fits in an int, but this is the
308 // bootloader so we have control of this.
309 // Resource allocated
310 return new ClassFileStream(buffer,
311 checked_cast<int>(st.st_size),
312 _dir);
313 }
314 }
315 }
316 FREE_RESOURCE_ARRAY_IN_THREAD(current, char, path, path_len);
317 return nullptr;
318 }
319
320 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name) : ClassPathEntry() {
321 _zip = zip;
322 _zip_name = copy_path(zip_name);
323 }
324
325 ClassPathZipEntry::~ClassPathZipEntry() {
326 ZipLibrary::close(_zip);
327 FREE_C_HEAP_ARRAY(char, _zip_name);
328 }
329
330 bool ClassPathZipEntry::has_entry(JavaThread* current, const char* name) {
331 ThreadToNativeFromVM ttn(current);
332 // check whether zip archive contains name
333 jint name_len;
334 jint filesize;
335 jzentry* entry = ZipLibrary::find_entry(_zip, name, &filesize, &name_len);
336 if (entry == nullptr) {
337 return false;
338 } else {
339 ZipLibrary::free_entry(_zip, entry);
340 return true;
341 }
342 }
343
344 u1* ClassPathZipEntry::open_entry(JavaThread* current, const char* name, jint* filesize, bool nul_terminate) {
345 // enable call to C land
346 ThreadToNativeFromVM ttn(current);
347 // check whether zip archive contains name
348 jint name_len;
349 jzentry* entry = ZipLibrary::find_entry(_zip, name, filesize, &name_len);
350 if (entry == nullptr) return nullptr;
351 u1* buffer;
352 char name_buf[128];
353 char* filename;
354 if (name_len < 128) {
355 filename = name_buf;
356 } else {
357 filename = NEW_RESOURCE_ARRAY(char, name_len + 1);
358 }
359
360 // read contents into resource array
361 size_t size = (uint32_t)(*filesize);
362 if (nul_terminate) {
363 if (sizeof(size) == sizeof(uint32_t) && size == UINT_MAX) {
364 return nullptr; // 32-bit integer overflow will occur.
365 }
366 size++;
367 }
368 buffer = NEW_RESOURCE_ARRAY(u1, size);
369 if (!ZipLibrary::read_entry(_zip, entry, buffer, filename)) {
370 return nullptr;
371 }
372
373 // return result
374 if (nul_terminate) {
375 buffer[size - 1] = 0;
376 }
377 return buffer;
378 }
379
380 ClassFileStream* ClassPathZipEntry::open_stream(JavaThread* current, const char* name) {
381 jint filesize;
382 u1* buffer = open_entry(current, name, &filesize, false);
383 if (buffer == nullptr) {
384 return nullptr;
385 }
386 if (UsePerfData) {
387 ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);
388 }
389 // Resource allocated
390 return new ClassFileStream(buffer,
391 filesize,
392 _zip_name);
393 }
394
395 DEBUG_ONLY(ClassPathImageEntry* ClassPathImageEntry::_singleton = nullptr;)
396
397 JImageFile* ClassPathImageEntry::jimage() const {
398 return JImage_file;
399 }
400
401 JImageFile* ClassPathImageEntry::jimage_non_null() const {
402 assert(ClassLoader::has_jrt_entry(), "must be");
403 assert(jimage() != nullptr, "should have been opened by ClassLoader::lookup_vm_options "
404 "and remained throughout normal JVM lifetime");
405 return jimage();
406 }
407
408 void ClassPathImageEntry::close_jimage() {
409 if (jimage() != nullptr) {
410 (*JImageClose)(jimage());
411 JImage_file = nullptr;
412 }
413 }
414
415 ClassPathImageEntry::ClassPathImageEntry(JImageFile* jimage, const char* name) :
416 ClassPathEntry() {
417 guarantee(jimage != nullptr, "jimage file is null");
418 guarantee(name != nullptr, "jimage file name is null");
419 assert(_singleton == nullptr, "VM supports only one jimage");
420 DEBUG_ONLY(_singleton = this);
421 size_t len = strlen(name) + 1;
422 _name = copy_path(name);
423 }
424
425 ClassFileStream* ClassPathImageEntry::open_stream(JavaThread* current, const char* name) {
426 return open_stream_for_loader(current, name, ClassLoaderData::the_null_class_loader_data());
427 }
428
429 // For a class in a named module, look it up in the jimage file using this syntax:
430 // /<module-name>/<package-name>/<base-class>
431 //
432 // Assumptions:
433 // 1. There are no unnamed modules in the jimage file.
434 // 2. A package is in at most one module in the jimage file.
435 //
436 ClassFileStream* ClassPathImageEntry::open_stream_for_loader(JavaThread* current, const char* name, ClassLoaderData* loader_data) {
437 jlong size;
438 JImageLocationRef location = 0;
439
440 TempNewSymbol class_name = SymbolTable::new_symbol(name);
441 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
442
443 if (pkg_name != nullptr) {
444 if (!Universe::is_module_initialized()) {
445 location = (*JImageFindResource)(jimage_non_null(), JAVA_BASE_NAME, get_jimage_version_string(), name, &size);
446 } else {
447 PackageEntry* package_entry = ClassLoader::get_package_entry(pkg_name, loader_data);
448 if (package_entry != nullptr) {
449 ResourceMark rm(current);
450 // Get the module name
451 ModuleEntry* module = package_entry->module();
452 assert(module != nullptr, "Boot classLoader package missing module");
453 assert(module->is_named(), "Boot classLoader package is in unnamed module");
454 const char* module_name = module->name()->as_C_string();
455 if (module_name != nullptr) {
456 location = (*JImageFindResource)(jimage_non_null(), module_name, get_jimage_version_string(), name, &size);
457 }
458 }
459 }
460 }
461
462 if (location != 0) {
463 if (UsePerfData) {
464 ClassLoader::perf_sys_classfile_bytes_read()->inc(size);
465 }
466 char* data = NEW_RESOURCE_ARRAY(char, size);
467 (*JImageGetResource)(jimage_non_null(), location, data, size);
468 // Resource allocated
469 assert(this == (ClassPathImageEntry*)ClassLoader::get_jrt_entry(), "must be");
470 return new ClassFileStream((u1*)data,
471 checked_cast<int>(size),
472 _name,
473 true); // from_boot_loader_modules_image
474 }
475
476 return nullptr;
477 }
478
479 JImageLocationRef ClassLoader::jimage_find_resource(JImageFile* jf,
480 const char* module_name,
481 const char* file_name,
482 jlong &size) {
483 return ((*JImageFindResource)(jf, module_name, get_jimage_version_string(), file_name, &size));
484 }
485
486 bool ClassPathImageEntry::is_modules_image() const {
487 assert(this == _singleton, "VM supports a single jimage");
488 assert(this == (ClassPathImageEntry*)ClassLoader::get_jrt_entry(), "must be used for jrt entry");
489 return true;
490 }
491
492 ModuleClassPathList::ModuleClassPathList(Symbol* module_name) {
493 _module_name = module_name;
494 _module_first_entry = nullptr;
495 _module_last_entry = nullptr;
496 }
497
498 ModuleClassPathList::~ModuleClassPathList() {
499 // Clean out each ClassPathEntry on list
500 ClassPathEntry* e = _module_first_entry;
501 while (e != nullptr) {
502 ClassPathEntry* next_entry = e->next();
503 delete e;
504 e = next_entry;
505 }
506 }
507
508 void ModuleClassPathList::add_to_list(ClassPathEntry* new_entry) {
509 if (new_entry != nullptr) {
510 if (_module_last_entry == nullptr) {
511 _module_first_entry = _module_last_entry = new_entry;
512 } else {
513 _module_last_entry->set_next(new_entry);
514 _module_last_entry = new_entry;
515 }
516 }
517 }
518
519 void ClassLoader::trace_class_path(const char* msg, const char* name) {
520 LogTarget(Info, class, path) lt;
521 if (lt.is_enabled()) {
522 LogStream ls(lt);
523 if (msg) {
524 ls.print("%s", msg);
525 }
526 if (name) {
527 if (strlen(name) < 256) {
528 ls.print("%s", name);
529 } else {
530 // For very long paths, we need to print each character separately,
531 // as print_cr() has a length limit
532 while (name[0] != '\0') {
533 ls.print("%c", name[0]);
534 name++;
535 }
536 }
537 }
538 ls.cr();
539 }
540 }
541
542 void ClassLoader::setup_bootstrap_search_path(JavaThread* current) {
543 const char* bootcp = Arguments::get_boot_class_path();
544 assert(bootcp != nullptr, "Boot class path must not be nullptr");
545 if (PrintSharedArchiveAndExit) {
546 // Don't print bootcp - this is the bootcp of this current VM process, not necessarily
547 // the same as the boot classpath of the shared archive.
548 } else {
549 trace_class_path("bootstrap loader class path=", bootcp);
550 }
551 setup_bootstrap_search_path_impl(current, bootcp);
552 }
553
554 void ClassLoader::close_jrt_image() {
555 // Not applicable for exploded builds
556 if (!ClassLoader::has_jrt_entry()) return;
557 _jrt_entry->close_jimage();
558 }
559
560 // Construct the array of module/path pairs as specified to --patch-module
561 // for the boot loader to search ahead of the jimage, if the class being
562 // loaded is defined to a module that has been specified to --patch-module.
563 void ClassLoader::setup_patch_mod_entries() {
564 JavaThread* current = JavaThread::current();
565 GrowableArray<ModulePatchPath*>* patch_mod_args = Arguments::get_patch_mod_prefix();
566 int num_of_entries = patch_mod_args->length();
567
568 // Set up the boot loader's _patch_mod_entries list
569 _patch_mod_entries = new (mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, mtModule);
570
571 for (int i = 0; i < num_of_entries; i++) {
572 const char* module_name = (patch_mod_args->at(i))->module_name();
573 Symbol* const module_sym = SymbolTable::new_symbol(module_name);
574 assert(module_sym != nullptr, "Failed to obtain Symbol for module name");
575 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
576
577 char* class_path = (patch_mod_args->at(i))->path_string();
578 ResourceMark rm(current);
579 ClasspathStream cp_stream(class_path);
580
581 while (cp_stream.has_next()) {
582 const char* path = cp_stream.get_next();
583 struct stat st;
584 if (os::stat(path, &st) == 0) {
585 // File or directory found
586 ClassPathEntry* new_entry = create_class_path_entry(current, path, &st);
587 // If the path specification is valid, enter it into this module's list
588 if (new_entry != nullptr) {
589 module_cpl->add_to_list(new_entry);
590 }
591 }
592 }
593
594 // Record the module into the list of --patch-module entries only if
595 // valid ClassPathEntrys have been created
596 if (module_cpl->module_first_entry() != nullptr) {
597 _patch_mod_entries->push(module_cpl);
598 }
599 }
600 }
601
602 // Determine whether the module has been patched via the command-line
603 // option --patch-module
604 bool ClassLoader::is_in_patch_mod_entries(Symbol* module_name) {
605 if (_patch_mod_entries != nullptr && _patch_mod_entries->is_nonempty()) {
606 int table_len = _patch_mod_entries->length();
607 for (int i = 0; i < table_len; i++) {
608 ModuleClassPathList* patch_mod = _patch_mod_entries->at(i);
609 if (module_name->fast_compare(patch_mod->module_name()) == 0) {
610 return true;
611 }
612 }
613 }
614 return false;
615 }
616
617 // Set up the _jrt_entry if present and boot append path
618 void ClassLoader::setup_bootstrap_search_path_impl(JavaThread* current, const char *class_path) {
619 ResourceMark rm(current);
620 ClasspathStream cp_stream(class_path);
621 bool set_base_piece = true;
622
623 #if INCLUDE_CDS
624 if (CDSConfig::is_dumping_archive()) {
625 if (!Arguments::has_jimage()) {
626 vm_exit_during_initialization("CDS is not supported in exploded JDK build", nullptr);
627 }
628 }
629 #endif
630
631 while (cp_stream.has_next()) {
632 const char* path = cp_stream.get_next();
633
634 if (set_base_piece) {
635 // The first time through the bootstrap_search setup, it must be determined
636 // what the base or core piece of the boot loader search is. Either a java runtime
637 // image is present or this is an exploded module build situation.
638 assert(string_ends_with(path, MODULES_IMAGE_NAME) || string_ends_with(path, JAVA_BASE_NAME),
639 "Incorrect boot loader search path, no java runtime image or " JAVA_BASE_NAME " exploded build");
640 struct stat st;
641 if (os::stat(path, &st) == 0) {
642 // Directory found
643 if (JImage_file != nullptr) {
644 assert(Arguments::has_jimage(), "sanity check");
645 const char* canonical_path = get_canonical_path(path, current);
646 assert(canonical_path != nullptr, "canonical_path issue");
647
648 _jrt_entry = new ClassPathImageEntry(JImage_file, canonical_path);
649 assert(_jrt_entry != nullptr && _jrt_entry->is_modules_image(), "No java runtime image present");
650 assert(_jrt_entry->jimage() != nullptr, "No java runtime image");
651 } // else it's an exploded build.
652 } else {
653 // If path does not exist, exit
654 vm_exit_during_initialization("Unable to establish the boot loader search path", path);
655 }
656 set_base_piece = false;
657 } else {
658 // Every entry on the boot class path after the initial base piece,
659 // which is set by os::set_boot_path(), is considered an appended entry.
660 update_class_path_entry_list(current, path);
661 }
662 }
663 }
664
665 // Gets the exploded path for the named module. The memory for the path
666 // is allocated on the C heap if `c_heap` is true otherwise in the resource area.
667 static const char* get_exploded_module_path(const char* module_name, bool c_heap) {
668 const char *home = Arguments::get_java_home();
669 const char file_sep = os::file_separator()[0];
670 // 10 represents the length of "modules" + 2 file separators + \0
671 size_t len = strlen(home) + strlen(module_name) + 10;
672 char *path = c_heap ? NEW_C_HEAP_ARRAY(char, len, mtModule) : NEW_RESOURCE_ARRAY(char, len);
673 jio_snprintf(path, len, "%s%cmodules%c%s", home, file_sep, file_sep, module_name);
674 return path;
675 }
676
677 // During an exploded modules build, each module defined to the boot loader
678 // will be added to the ClassLoader::_exploded_entries array.
679 void ClassLoader::add_to_exploded_build_list(JavaThread* current, Symbol* module_sym) {
680 assert(!ClassLoader::has_jrt_entry(), "Exploded build not applicable");
681 assert(_exploded_entries != nullptr, "_exploded_entries was not initialized");
682
683 // Find the module's symbol
684 ResourceMark rm(current);
685 const char *module_name = module_sym->as_C_string();
686 const char *path = get_exploded_module_path(module_name, false);
687
688 struct stat st;
689 if (os::stat(path, &st) == 0) {
690 // Directory found
691 ClassPathEntry* new_entry = create_class_path_entry(current, path, &st);
692
693 // If the path specification is valid, enter it into this module's list.
694 // There is no need to check for duplicate modules in the exploded entry list,
695 // since no two modules with the same name can be defined to the boot loader.
696 // This is checked at module definition time in Modules::define_module.
697 if (new_entry != nullptr) {
698 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
699 module_cpl->add_to_list(new_entry);
700 {
701 MutexLocker ml(current, Module_lock);
702 _exploded_entries->push(module_cpl);
703 }
704 log_info(class, load)("path: %s", path);
705 }
706 }
707 }
708
709 jzfile* ClassLoader::open_zip_file(const char* canonical_path, char** error_msg, JavaThread* thread) {
710 // enable call to C land
711 ThreadToNativeFromVM ttn(thread);
712 HandleMark hm(thread);
713 return ZipLibrary::open(canonical_path, error_msg);
714 }
715
716 ClassPathEntry* ClassLoader::create_class_path_entry(JavaThread* current,
717 const char *path, const struct stat* st) {
718 ClassPathEntry* new_entry = nullptr;
719 if ((st->st_mode & S_IFMT) == S_IFREG) {
720 ResourceMark rm(current);
721 // Regular file, should be a zip file
722 // Canonicalized filename
723 const char* canonical_path = get_canonical_path(path, current);
724 if (canonical_path == nullptr) {
725 return nullptr;
726 }
727 char* error_msg = nullptr;
728 jzfile* zip = open_zip_file(canonical_path, &error_msg, current);
729 if (zip != nullptr && error_msg == nullptr) {
730 new_entry = new ClassPathZipEntry(zip, path);
731 } else {
732 return nullptr;
733 }
734 log_info(class, path)("opened: %s", path);
735 log_info(class, load)("opened: %s", path);
736 } else {
737 // Directory
738 new_entry = new ClassPathDirEntry(path);
739 log_info(class, load)("path: %s", path);
740 }
741 return new_entry;
742 }
743
744
745 // Create a class path zip entry for a given path (return null if not found
746 // or zip/JAR file cannot be opened)
747 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {
748 // check for a regular file
749 struct stat st;
750 if (os::stat(path, &st) == 0) {
751 if ((st.st_mode & S_IFMT) == S_IFREG) {
752 JavaThread* thread = JavaThread::current();
753 ResourceMark rm(thread);
754 const char* canonical_path = get_canonical_path(path, thread);
755 if (canonical_path != nullptr) {
756 char* error_msg = nullptr;
757 jzfile* zip = open_zip_file(canonical_path, &error_msg, thread);
758 if (zip != nullptr && error_msg == nullptr) {
759 // create using canonical path
760 return new ClassPathZipEntry(zip, canonical_path);
761 }
762 }
763 }
764 }
765 return nullptr;
766 }
767
768 // The boot append entries are added with a lock, and read lock free.
769 void ClassLoader::add_to_boot_append_entries(ClassPathEntry *new_entry) {
770 if (new_entry != nullptr) {
771 MutexLocker ml(Bootclasspath_lock, Mutex::_no_safepoint_check_flag);
772 if (_last_append_entry == nullptr) {
773 _last_append_entry = new_entry;
774 assert(first_append_entry() == nullptr, "boot loader's append class path entry list not empty");
775 AtomicAccess::release_store(&_first_append_entry_list, new_entry);
776 } else {
777 _last_append_entry->set_next(new_entry);
778 _last_append_entry = new_entry;
779 }
780 }
781 }
782
783 // Returns true IFF the file/dir exists and the entry was successfully created.
784 bool ClassLoader::update_class_path_entry_list(JavaThread* current, const char *path) {
785 struct stat st;
786 if (os::stat(path, &st) == 0) {
787 // File or directory found
788 ClassPathEntry* new_entry = nullptr;
789 new_entry = create_class_path_entry(current, path, &st);
790 if (new_entry == nullptr) {
791 return false;
792 }
793
794 // Do not reorder the bootclasspath which would break get_system_package().
795 // Add new entry to linked list
796 add_to_boot_append_entries(new_entry);
797 return true;
798 } else {
799 return false;
800 }
801 }
802
803 static void print_module_entry_table(const GrowableArray<ModuleClassPathList*>* const module_list) {
804 ResourceMark rm;
805 int num_of_entries = module_list->length();
806 for (int i = 0; i < num_of_entries; i++) {
807 ClassPathEntry* e;
808 ModuleClassPathList* mpl = module_list->at(i);
809 tty->print("%s=", mpl->module_name()->as_C_string());
810 e = mpl->module_first_entry();
811 while (e != nullptr) {
812 tty->print("%s", e->name());
813 e = e->next();
814 if (e != nullptr) {
815 tty->print("%s", os::path_separator());
816 }
817 }
818 tty->print(" ;");
819 }
820 }
821
822 void ClassLoader::print_bootclasspath() {
823 ClassPathEntry* e;
824 tty->print("[bootclasspath= ");
825
826 // Print --patch-module module/path specifications first
827 if (_patch_mod_entries != nullptr) {
828 print_module_entry_table(_patch_mod_entries);
829 }
830
831 // [jimage | exploded modules build]
832 if (has_jrt_entry()) {
833 // Print the location of the java runtime image
834 tty->print("%s ;", _jrt_entry->name());
835 } else {
836 // Print exploded module build path specifications
837 if (_exploded_entries != nullptr) {
838 print_module_entry_table(_exploded_entries);
839 }
840 }
841
842 // appended entries
843 e = first_append_entry();
844 while (e != nullptr) {
845 tty->print("%s ;", e->name());
846 e = e->next();
847 }
848 tty->print_cr("]");
849 }
850
851 void* ClassLoader::dll_lookup(void* lib, const char* name, const char* path) {
852 void* func = os::dll_lookup(lib, name);
853 if (func == nullptr) {
854 char msg[256] = "";
855 jio_snprintf(msg, sizeof(msg), "Could not resolve \"%s\"", name);
856 vm_exit_during_initialization(msg, path);
857 }
858 return func;
859 }
860
861 void ClassLoader::load_java_library() {
862 assert(CanonicalizeEntry == nullptr, "should not load java library twice");
863 if (is_vm_statically_linked()) {
864 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::lookup_function("JDK_Canonicalize"));
865 assert(CanonicalizeEntry != nullptr, "could not lookup JDK_Canonicalize");
866 return;
867 }
868
869 void *javalib_handle = os::native_java_library();
870 if (javalib_handle == nullptr) {
871 vm_exit_during_initialization("Unable to load java library", nullptr);
872 }
873
874 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, dll_lookup(javalib_handle, "JDK_Canonicalize", nullptr));
875 assert(CanonicalizeEntry != nullptr, "could not lookup JDK_Canonicalize in java library");
876 }
877
878 void ClassLoader::load_jimage_library() {
879 assert(JImageOpen == nullptr, "should not load jimage library twice");
880
881 if (is_vm_statically_linked()) {
882 JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, os::lookup_function("JIMAGE_Open"));
883 JImageClose = CAST_TO_FN_PTR(JImageClose_t, os::lookup_function("JIMAGE_Close"));
884 JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, os::lookup_function("JIMAGE_FindResource"));
885 JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, os::lookup_function("JIMAGE_GetResource"));
886 assert(JImageOpen != nullptr && JImageClose != nullptr &&
887 JImageFindResource != nullptr && JImageGetResource != nullptr,
888 "could not lookup all jimage library functions");
889 return;
890 }
891
892 char path[JVM_MAXPATHLEN];
893 char ebuf[1024];
894 void* handle = nullptr;
895 if (os::dll_locate_lib(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) {
896 handle = os::dll_load(path, ebuf, sizeof ebuf);
897 }
898 if (handle == nullptr) {
899 vm_exit_during_initialization("Unable to load jimage library", path);
900 }
901
902 JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, dll_lookup(handle, "JIMAGE_Open", path));
903 JImageClose = CAST_TO_FN_PTR(JImageClose_t, dll_lookup(handle, "JIMAGE_Close", path));
904 JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, dll_lookup(handle, "JIMAGE_FindResource", path));
905 JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, dll_lookup(handle, "JIMAGE_GetResource", path));
906 assert(JImageOpen != nullptr && JImageClose != nullptr &&
907 JImageFindResource != nullptr && JImageGetResource != nullptr,
908 "could not lookup all jimage library functions in jimage library");
909 }
910
911 int ClassLoader::crc32(int crc, const char* buf, int len) {
912 return ZipLibrary::crc32(crc, (const jbyte*)buf, len);
913 }
914
915 oop ClassLoader::get_system_package(const char* name, TRAPS) {
916 // Look up the name in the boot loader's package entry table.
917 if (name != nullptr) {
918 TempNewSymbol package_sym = SymbolTable::new_symbol(name);
919 // Look for the package entry in the boot loader's package entry table.
920 PackageEntry* package =
921 ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym);
922
923 // Return null if package does not exist or if no classes in that package
924 // have been loaded.
925 if (package != nullptr && package->has_loaded_class()) {
926 ModuleEntry* module = package->module();
927 if (module->location() != nullptr) {
928 ResourceMark rm(THREAD);
929 Handle ml = java_lang_String::create_from_str(
930 module->location()->as_C_string(), THREAD);
931 return ml();
932 }
933 // Return entry on boot loader class path.
934 Handle cph = java_lang_String::create_from_str(
935 ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD);
936 return cph();
937 }
938 }
939 return nullptr;
940 }
941
942 objArrayOop ClassLoader::get_system_packages(TRAPS) {
943 ResourceMark rm(THREAD);
944 // List of pointers to PackageEntrys that have loaded classes.
945 PackageEntryTable* pe_table =
946 ClassLoaderData::the_null_class_loader_data()->packages();
947 GrowableArray<PackageEntry*>* loaded_class_pkgs = pe_table->get_system_packages();
948
949 // Allocate objArray and fill with java.lang.String
950 objArrayOop r = oopFactory::new_objArray(vmClasses::String_klass(),
951 loaded_class_pkgs->length(), CHECK_NULL);
952 objArrayHandle result(THREAD, r);
953 for (int x = 0; x < loaded_class_pkgs->length(); x++) {
954 PackageEntry* package_entry = loaded_class_pkgs->at(x);
955 Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL);
956 result->obj_at_put(x, str());
957 }
958 return result();
959 }
960
961 // caller needs ResourceMark
962 const char* ClassLoader::file_name_for_class_name(const char* class_name,
963 int class_name_len) {
964 assert(class_name != nullptr, "invariant");
965 assert((int)strlen(class_name) == class_name_len, "invariant");
966
967 static const char class_suffix[] = ".class";
968 size_t class_suffix_len = sizeof(class_suffix);
969
970 char* const file_name = NEW_RESOURCE_ARRAY(char,
971 class_name_len +
972 class_suffix_len); // includes term null
973
974 strncpy(file_name, class_name, class_name_len);
975 strncpy(&file_name[class_name_len], class_suffix, class_suffix_len);
976
977 return file_name;
978 }
979
980 static ClassPathEntry* find_first_module_cpe(ModuleEntry* mod_entry,
981 const GrowableArray<ModuleClassPathList*>* const module_list) {
982 int num_of_entries = module_list->length();
983 const Symbol* class_module_name = mod_entry->name();
984
985 // Loop through all the modules in either the patch-module or exploded entries looking for module
986 for (int i = 0; i < num_of_entries; i++) {
987 ModuleClassPathList* module_cpl = module_list->at(i);
988 Symbol* module_cpl_name = module_cpl->module_name();
989
990 if (module_cpl_name->fast_compare(class_module_name) == 0) {
991 // Class' module has been located.
992 return module_cpl->module_first_entry();
993 }
994 }
995 return nullptr;
996 }
997
998
999 // Search the module list for the class file stream based on the file name and java package
1000 ClassFileStream* ClassLoader::search_module_entries(JavaThread* current,
1001 const GrowableArray<ModuleClassPathList*>* const module_list,
1002 PackageEntry* pkg_entry, // Java package entry derived from the class name
1003 const char* const file_name) {
1004 ClassFileStream* stream = nullptr;
1005
1006 // Find the defining module in the boot loader's module entry table
1007 ModuleEntry* mod_entry = (pkg_entry != nullptr) ? pkg_entry->module() : nullptr;
1008
1009 // If the module system has not defined java.base yet, then
1010 // classes loaded are assumed to be defined to java.base.
1011 // When java.base is eventually defined by the module system,
1012 // all packages of classes that have been previously loaded
1013 // are verified in ModuleEntryTable::verify_javabase_packages().
1014 if (!Universe::is_module_initialized() &&
1015 !ModuleEntryTable::javabase_defined() &&
1016 mod_entry == nullptr) {
1017 mod_entry = ModuleEntryTable::javabase_moduleEntry();
1018 }
1019
1020 // The module must be a named module
1021 ClassPathEntry* e = nullptr;
1022 if (mod_entry != nullptr && mod_entry->is_named()) {
1023 if (module_list == _exploded_entries) {
1024 // The exploded build entries can be added to at any time so a lock is
1025 // needed when searching them.
1026 assert(!ClassLoader::has_jrt_entry(), "Must be exploded build");
1027 MutexLocker ml(current, Module_lock);
1028 e = find_first_module_cpe(mod_entry, module_list);
1029 } else {
1030 e = find_first_module_cpe(mod_entry, module_list);
1031 }
1032 }
1033
1034 // Try to load the class from the module's ClassPathEntry list.
1035 while (e != nullptr) {
1036 stream = e->open_stream(current, file_name);
1037 // No context.check is required since CDS is not supported
1038 // for an exploded modules build or if --patch-module is specified.
1039 if (nullptr != stream) {
1040 return stream;
1041 }
1042 e = e->next();
1043 }
1044 // If the module was located, break out even if the class was not
1045 // located successfully from that module's ClassPathEntry list.
1046 // There will not be another valid entry for that module.
1047 return nullptr;
1048 }
1049
1050 // Called by the boot classloader to load classes
1051 InstanceKlass* ClassLoader::load_class(Symbol* name, PackageEntry* pkg_entry, bool search_append_only, TRAPS) {
1052 assert(name != nullptr, "invariant");
1053
1054 ResourceMark rm(THREAD);
1055 HandleMark hm(THREAD);
1056
1057 const char* const class_name = name->as_C_string();
1058
1059 EventMarkClassLoading m("Loading class %s", class_name);
1060
1061 const char* const file_name = file_name_for_class_name(class_name,
1062 name->utf8_length());
1063 assert(file_name != nullptr, "invariant");
1064
1065 // Lookup stream for parsing .class file
1066 ClassFileStream* stream = nullptr;
1067 s2 classpath_index = 0;
1068 ClassPathEntry* e = nullptr;
1069
1070 // If search_append_only is true, boot loader visibility boundaries are
1071 // set to be _first_append_entry to the end. This includes:
1072 // [-Xbootclasspath/a]; [jvmti appended entries]
1073 //
1074 // If search_append_only is false, boot loader visibility boundaries are
1075 // set to be the --patch-module entries plus the base piece. This includes:
1076 // [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
1077 //
1078
1079 // Load Attempt #1: --patch-module
1080 // Determine the class' defining module. If it appears in the _patch_mod_entries,
1081 // attempt to load the class from those locations specific to the module.
1082 // Specifications to --patch-module can contain a partial number of classes
1083 // that are part of the overall module definition. So if a particular class is not
1084 // found within its module specification, the search should continue to Load Attempt #2.
1085 // Note: The --patch-module entries are never searched if the boot loader's
1086 // visibility boundary is limited to only searching the append entries.
1087 if (_patch_mod_entries != nullptr && !search_append_only) {
1088 assert(!CDSConfig::is_dumping_archive(), "CDS doesn't support --patch-module during dumping");
1089 stream = search_module_entries(THREAD, _patch_mod_entries, pkg_entry, file_name);
1090 }
1091
1092 // Load Attempt #2: [jimage | exploded build]
1093 if (!search_append_only && (nullptr == stream)) {
1094 if (has_jrt_entry()) {
1095 e = _jrt_entry;
1096 stream = _jrt_entry->open_stream(THREAD, file_name);
1097 } else {
1098 // Exploded build - attempt to locate class in its defining module's location.
1099 assert(_exploded_entries != nullptr, "No exploded build entries present");
1100 assert(!CDSConfig::is_dumping_archive(), "CDS dumping doesn't support exploded build");
1101 stream = search_module_entries(THREAD, _exploded_entries, pkg_entry, file_name);
1102 }
1103 }
1104
1105 // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries]
1106 if (search_append_only && (nullptr == stream)) {
1107 // For the boot loader append path search, the starting classpath_index
1108 // for the appended piece is always 1 to account for either the
1109 // _jrt_entry or the _exploded_entries.
1110 assert(classpath_index == 0, "The classpath_index has been incremented incorrectly");
1111 classpath_index = 1;
1112
1113 e = first_append_entry();
1114 while (e != nullptr) {
1115 stream = e->open_stream(THREAD, file_name);
1116 if (nullptr != stream) {
1117 break;
1118 }
1119 e = e->next();
1120 ++classpath_index;
1121 }
1122 }
1123
1124 if (nullptr == stream) {
1125 return nullptr;
1126 }
1127
1128 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1129 Handle protection_domain;
1130 ClassLoadInfo cl_info(protection_domain);
1131
1132 InstanceKlass* result = KlassFactory::create_from_stream(stream,
1133 name,
1134 loader_data,
1135 cl_info,
1136 CHECK_NULL);
1137 result->set_classpath_index(classpath_index);
1138 return result;
1139 }
1140
1141 #if INCLUDE_CDS
1142 static const char* skip_uri_protocol(const char* source) {
1143 if (strncmp(source, "file:", 5) == 0) {
1144 // file: protocol path could start with file:/ or file:///
1145 // locate the char after all the forward slashes
1146 int offset = 5;
1147 while (*(source + offset) == '/') {
1148 offset++;
1149 }
1150 source += offset;
1151 // for non-windows platforms, move back one char as the path begins with a '/'
1152 #ifndef _WINDOWS
1153 source -= 1;
1154 #endif
1155 } else if (strncmp(source, "jrt:/", 5) == 0) {
1156 source += 5;
1157 }
1158 return source;
1159 }
1160
1161 static char decode_percent_encoded(const char *str, size_t& index) {
1162 if (str[index] == '%'
1163 && isxdigit(str[index + 1])
1164 && isxdigit(str[index + 2])) {
1165 char hex[3];
1166 hex[0] = str[index + 1];
1167 hex[1] = str[index + 2];
1168 hex[2] = '\0';
1169 index += 2;
1170 return (char) strtol(hex, nullptr, 16);
1171 }
1172 return str[index];
1173 }
1174
1175 char* ClassLoader::uri_to_path(const char* uri) {
1176 const size_t len = strlen(uri) + 1;
1177 char* path = NEW_RESOURCE_ARRAY(char, len);
1178
1179 uri = skip_uri_protocol(uri);
1180
1181 if (strncmp(uri, "//", 2) == 0) {
1182 // Skip the empty "authority" part
1183 uri += 2;
1184 }
1185
1186 #ifdef _WINDOWS
1187 if (uri[0] == '/') {
1188 // Absolute path name on Windows does not begin with a slash
1189 uri += 1;
1190 }
1191 #endif
1192
1193 size_t path_index = 0;
1194 for (size_t i = 0; i < strlen(uri); ++i) {
1195 char decoded = decode_percent_encoded(uri, i);
1196 path[path_index++] = decoded;
1197 }
1198 path[path_index] = '\0';
1199 return path;
1200 }
1201
1202 // Record the shared classpath index and loader type for classes loaded
1203 // by the builtin loaders at dump time.
1204 void ClassLoader::record_result(JavaThread* current, InstanceKlass* ik,
1205 const ClassFileStream* stream, bool redefined) {
1206 assert(CDSConfig::is_dumping_archive(), "sanity");
1207 assert(stream != nullptr, "sanity");
1208
1209 if (ik->is_hidden()) {
1210 record_hidden_class(ik);
1211 return;
1212 }
1213
1214 oop loader = ik->class_loader();
1215 char* src = (char*)stream->source();
1216 if (src == nullptr) {
1217 ik->set_shared_classpath_index(-1); // unsupported location
1218 return;
1219 }
1220
1221 if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
1222 // A class loaded by a user-defined classloader.
1223 assert(ik->shared_classpath_index() < 0, "not assigned yet");
1224 ik->set_shared_classpath_index(UNREGISTERED_INDEX);
1225 SystemDictionaryShared::set_shared_class_misc_info(ik, (ClassFileStream*)stream);
1226 return;
1227 }
1228
1229 assert(has_jrt_entry(), "CDS dumping does not support exploded JDK build");
1230
1231 ResourceMark rm(current);
1232 int classpath_index = -1;
1233 bool found_invalid = false;
1234
1235 PackageEntry* pkg_entry = ik->package();
1236
1237 if (!AOTClassLocationConfig::dumptime_is_ready()) {
1238 // The shared path table is set up after module system initialization.
1239 // The path table contains no entry before that. Any classes loaded prior
1240 // to the setup of the shared path table must be from the modules image.
1241 assert(stream->from_boot_loader_modules_image(), "stream must be loaded by boot loader from modules image");
1242 classpath_index = 0;
1243 } else {
1244 // Save the path from the file: protocol or the module name from the jrt: protocol
1245 // if no protocol prefix is found, path is the same as stream->source(). This path
1246 // must be valid since the class has been successfully parsed.
1247 const char* path = ClassLoader::uri_to_path(src);
1248 assert(path != nullptr, "sanity");
1249 AOTClassLocationConfig::dumptime_iterate([&] (AOTClassLocation* cl) {
1250 int i = cl->index();
1251 // for index 0 and the stream->source() is the modules image or has the jrt: protocol.
1252 // The class must be from the runtime modules image.
1253 if (cl->is_modules_image() && (stream->from_boot_loader_modules_image() || string_starts_with(src, "jrt:"))) {
1254 classpath_index = i;
1255 } else if (os::same_files(cl->path(), path)) {
1256 // If the path (from the class stream source) is the same as the shared
1257 // class or module path, then we have a match.
1258 // src may come from the App/Platform class loaders, which would canonicalize
1259 // the file name. We cannot use strcmp to check for equality against cs->path().
1260 // We must use os::same_files (which is faster than canonicalizing cs->path()).
1261
1262 // null pkg_entry and pkg_entry in an unnamed module implies the class
1263 // is from the -cp or boot loader append path which consists of -Xbootclasspath/a
1264 // and jvmti appended entries.
1265 if ((pkg_entry == nullptr) || (pkg_entry->in_unnamed_module())) {
1266 // Ensure the index is within the -cp range before assigning
1267 // to the classpath_index.
1268 if (SystemDictionary::is_system_class_loader(loader) && cl->from_app_classpath()) {
1269 classpath_index = i;
1270 } else {
1271 if (cl->from_boot_classpath()) {
1272 if (loader != nullptr) {
1273 // Probably loaded by jdk/internal/loader/ClassLoaders$BootClassLoader. Don't archive
1274 // such classes.
1275 found_invalid = true;
1276 } else {
1277 classpath_index = i;
1278 }
1279 }
1280 }
1281 } else {
1282 // A class from a named module from the --module-path. Ensure the index is
1283 // within the --module-path range before assigning to the classpath_index.
1284 if ((pkg_entry != nullptr) && !(pkg_entry->in_unnamed_module()) && cl->from_module_path()) {
1285 classpath_index = i;
1286 }
1287 }
1288 }
1289 if (classpath_index >= 0 || found_invalid) {
1290 return false; // Break the AOTClassLocationConfig::dumptime_iterate() loop.
1291 } else {
1292 return true; // Keep iterating
1293 }
1294 });
1295 }
1296
1297 if (found_invalid) {
1298 assert(classpath_index == -1, "sanity");
1299 }
1300
1301 const char* const class_name = ik->name()->as_C_string();
1302 const char* const file_name = file_name_for_class_name(class_name,
1303 ik->name()->utf8_length());
1304 assert(file_name != nullptr, "invariant");
1305 record_result_for_builtin_loader(checked_cast<s2>(classpath_index), ik, redefined);
1306 }
1307
1308 void ClassLoader::record_result_for_builtin_loader(s2 classpath_index, InstanceKlass* result, bool redefined) {
1309 assert(CDSConfig::is_dumping_archive(), "sanity");
1310
1311 oop loader = result->class_loader();
1312 if (SystemDictionary::is_system_class_loader(loader)) {
1313 AOTClassLocationConfig::dumptime_set_has_app_classes();
1314 } else if (SystemDictionary::is_platform_class_loader(loader)) {
1315 AOTClassLocationConfig::dumptime_set_has_platform_classes();
1316 } else {
1317 precond(loader == nullptr);
1318 }
1319
1320 if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_dynamic_archive()) {
1321 if (!AOTClassLocationConfig::dumptime()->is_valid_classpath_index(classpath_index, result)) {
1322 classpath_index = -1;
1323 }
1324 }
1325
1326 AOTClassLocationConfig::dumptime_update_max_used_index(classpath_index);
1327 result->set_shared_classpath_index(classpath_index);
1328 }
1329
1330 void ClassLoader::record_hidden_class(InstanceKlass* ik) {
1331 assert(ik->is_hidden(), "must be");
1332
1333 if (ik->defined_by_other_loaders()) {
1334 // We don't archive hidden classes for non-builtin loaders.
1335 return;
1336 }
1337
1338 if (HeapShared::is_lambda_proxy_klass(ik)) {
1339 InstanceKlass* nest_host = ik->nest_host_not_null();
1340 ik->set_shared_classpath_index(nest_host->shared_classpath_index());
1341 } else if (HeapShared::is_lambda_form_klass(ik)) {
1342 ik->set_shared_classpath_index(0);
1343 } else {
1344 // Generated invoker classes.
1345 if (ik->defined_by_app_loader()) {
1346 ik->set_shared_classpath_index(AOTClassLocationConfig::dumptime()->app_cp_start_index());
1347 } else {
1348 ik->set_shared_classpath_index(0);
1349 }
1350 }
1351 }
1352
1353 void ClassLoader::append_boot_classpath(ClassPathEntry* new_entry) {
1354 if (CDSConfig::is_using_archive()) {
1355 warning("Sharing is only supported for boot loader classes because bootstrap classpath has been appended");
1356 FileMapInfo::current_info()->set_has_platform_or_app_classes(false);
1357 if (DynamicArchive::is_mapped()) {
1358 FileMapInfo::dynamic_info()->set_has_platform_or_app_classes(false);
1359 }
1360 }
1361 add_to_boot_append_entries(new_entry);
1362 }
1363 #endif // INCLUDE_CDS
1364
1365 // Initialize the class loader's access to methods in libzip. Parse and
1366 // process the boot classpath into a list ClassPathEntry objects. Once
1367 // this list has been created, it must not change order (see class PackageInfo)
1368 // it can be appended to and is by jvmti.
1369
1370 void ClassLoader::initialize(TRAPS) {
1371 if (UsePerfData) {
1372 // jvmstat performance counters
1373 NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1374 NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1375 NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1376 NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1377 NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1378 NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1379 NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1380 NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1381 NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1382 NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1383 NEWPERFEVENTCOUNTER(_perf_class_init_bytecodes_count, SUN_CLS, "clinitBytecodesCount");
1384
1385 NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1386 NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1387 NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1388 NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1389 NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1390 NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1391 NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1392 NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1393 NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1394 NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1395 NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS, "unsafeDefineClassCalls");
1396 NEWPERFTICKCOUNTER(_perf_secondary_hash_time, SUN_CLS, "secondarySuperHashTime");
1397
1398 if (log_is_enabled(Info, perf, class, link) || log_is_enabled(Info, init)) {
1399 NEWPERFTICKCOUNTER(_perf_preload_total_time, SUN_CLS, "preloadTotalTime");
1400 NEWPERFTICKCOUNTER(_perf_preload_time, SUN_CLS, "preloadTime");
1401 NEWPERFTICKCOUNTER(_perf_prelink_time, SUN_CLS, "prelinkTime");
1402 NEWPERFTICKCOUNTER(_perf_preinit_time, SUN_CLS, "preinitTime");
1403 NEWPERFTICKCOUNTER(_perf_preresolve_time, SUN_CLS, "preresolveTime");
1404
1405 NEWPERFTICKCOUNTER(_perf_ik_link_methods_time, SUN_CLS, "linkMethodsTime");
1406 NEWPERFTICKCOUNTER(_perf_method_adapters_time, SUN_CLS, "makeAdaptersTime");
1407 NEWPERFEVENTCOUNTER(_perf_ik_link_methods_count, SUN_CLS, "linkMethodsCount");
1408 NEWPERFEVENTCOUNTER(_perf_method_adapters_count, SUN_CLS, "makeAdaptersCount");
1409
1410 NEWPERFTICKCOUNTERS(_perf_resolve_indy_time, SUN_CLS, "resolve_invokedynamic_time");
1411 NEWPERFTICKCOUNTERS(_perf_resolve_invokehandle_time, SUN_CLS, "resolve_invokehandle_time");
1412 NEWPERFTICKCOUNTERS(_perf_resolve_mh_time, SUN_CLS, "resolve_MethodHandle_time");
1413 NEWPERFTICKCOUNTERS(_perf_resolve_mt_time, SUN_CLS, "resolve_MethodType_time");
1414
1415 NEWPERFEVENTCOUNTER(_perf_resolve_indy_count, SUN_CLS, "resolve_invokedynamic_count");
1416 NEWPERFEVENTCOUNTER(_perf_resolve_invokehandle_count, SUN_CLS, "resolve_invokehandle_count");
1417 NEWPERFEVENTCOUNTER(_perf_resolve_mh_count, SUN_CLS, "resolve_MethodHandle_count");
1418 NEWPERFEVENTCOUNTER(_perf_resolve_mt_count, SUN_CLS, "resolve_MethodType_count");
1419 }
1420 }
1421
1422 // lookup java library entry points
1423 load_java_library();
1424 // jimage library entry points are loaded below, in lookup_vm_options
1425 setup_bootstrap_search_path(THREAD);
1426 }
1427
1428 static char* lookup_vm_resource(JImageFile *jimage, const char *jimage_version, const char *path) {
1429 jlong size;
1430 JImageLocationRef location = (*JImageFindResource)(jimage, "java.base", jimage_version, path, &size);
1431 if (location == 0)
1432 return nullptr;
1433 char *val = NEW_C_HEAP_ARRAY(char, size+1, mtClass);
1434 (*JImageGetResource)(jimage, location, val, size);
1435 val[size] = '\0';
1436 return val;
1437 }
1438
1439 // Lookup VM options embedded in the modules jimage file
1440 char* ClassLoader::lookup_vm_options() {
1441 jint error;
1442 char modules_path[JVM_MAXPATHLEN];
1443 const char* fileSep = os::file_separator();
1444
1445 // Initialize jimage library entry points
1446 load_jimage_library();
1447
1448 jio_snprintf(modules_path, JVM_MAXPATHLEN, "%s%slib%smodules", Arguments::get_java_home(), fileSep, fileSep);
1449 JImage_file =(*JImageOpen)(modules_path, &error);
1450 if (JImage_file == nullptr) {
1451 return nullptr;
1452 }
1453
1454 const char *jimage_version = get_jimage_version_string();
1455 char *options = lookup_vm_resource(JImage_file, jimage_version, "jdk/internal/vm/options");
1456 return options;
1457 }
1458
1459 bool ClassLoader::is_module_observable(const char* module_name) {
1460 assert(JImageOpen != nullptr, "jimage library should have been opened");
1461 if (JImage_file == nullptr) {
1462 struct stat st;
1463 const char *path = get_exploded_module_path(module_name, true);
1464 bool res = os::stat(path, &st) == 0;
1465 FREE_C_HEAP_ARRAY(char, path);
1466 return res;
1467 }
1468 jlong size;
1469 const char *jimage_version = get_jimage_version_string();
1470 return (*JImageFindResource)(JImage_file, module_name, jimage_version, "module-info.class", &size) != 0;
1471 }
1472
1473 jlong ClassLoader::classloader_time_ms() {
1474 return UsePerfData ?
1475 Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1476 }
1477
1478 jlong ClassLoader::class_init_bytecodes_count() {
1479 return UsePerfData ? _perf_class_init_bytecodes_count->get_value() : -1;
1480 }
1481
1482 jlong ClassLoader::class_init_count() {
1483 return UsePerfData ? _perf_classes_inited->get_value() : -1;
1484 }
1485
1486 jlong ClassLoader::class_init_time_ms() {
1487 return UsePerfData ?
1488 Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1489 }
1490
1491 jlong ClassLoader::class_verify_time_ms() {
1492 return UsePerfData ?
1493 Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1494 }
1495
1496 jlong ClassLoader::class_link_count() {
1497 return UsePerfData ? _perf_classes_linked->get_value() : -1;
1498 }
1499
1500 jlong ClassLoader::class_link_time_ms() {
1501 return UsePerfData ?
1502 Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1503 }
1504
1505 int ClassLoader::compute_Object_vtable() {
1506 // hardwired for JDK1.2 -- would need to duplicate class file parsing
1507 // code to determine actual value from file
1508 // Would be value '11' if finals were in vtable
1509 int JDK_1_2_Object_vtable_size = 5;
1510 return JDK_1_2_Object_vtable_size * vtableEntry::size();
1511 }
1512
1513
1514 void classLoader_init1() {
1515 EXCEPTION_MARK;
1516 ClassLoader::initialize(THREAD);
1517 if (HAS_PENDING_EXCEPTION) {
1518 vm_exit_during_initialization("ClassLoader::initialize() failed unexpectedly");
1519 }
1520 }
1521
1522 // Complete the ClassPathEntry setup for the boot loader
1523 void ClassLoader::classLoader_init2(JavaThread* current) {
1524 // Setup the list of module/path pairs for --patch-module processing
1525 // This must be done after the SymbolTable is created in order
1526 // to use fast_compare on module names instead of a string compare.
1527 if (Arguments::get_patch_mod_prefix() != nullptr) {
1528 setup_patch_mod_entries();
1529 }
1530
1531 // Create the ModuleEntry for java.base (must occur after setup_patch_mod_entries
1532 // to successfully determine if java.base has been patched)
1533 create_javabase();
1534
1535 // Setup the initial java.base/path pair for the exploded build entries.
1536 // As more modules are defined during module system initialization, more
1537 // entries will be added to the exploded build array.
1538 if (!has_jrt_entry()) {
1539 assert(!CDSConfig::is_dumping_archive(), "not supported with exploded module builds");
1540 assert(!CDSConfig::is_using_archive(), "UsedSharedSpaces not supported with exploded module builds");
1541 // Set up the boot loader's _exploded_entries list. Note that this gets
1542 // done before loading any classes, by the same thread that will
1543 // subsequently do the first class load. So, no lock is needed for this.
1544 assert(_exploded_entries == nullptr, "Should only get initialized once");
1545 _exploded_entries = new (mtModule)
1546 GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, mtModule);
1547 add_to_exploded_build_list(current, vmSymbols::java_base());
1548 }
1549 }
1550
1551 char* ClassLoader::get_canonical_path(const char* orig, Thread* thread) {
1552 assert(orig != nullptr, "bad arguments");
1553 // caller needs to allocate ResourceMark for the following output buffer
1554 char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN);
1555 ResourceMark rm(thread);
1556 // os::native_path writes into orig_copy
1557 char* orig_copy = ResourceArea::strdup(thread, orig);
1558 if ((CanonicalizeEntry)(os::native_path(orig_copy), canonical_path, JVM_MAXPATHLEN) < 0) {
1559 return nullptr;
1560 }
1561 return canonical_path;
1562 }
1563
1564 void ClassLoader::create_javabase() {
1565 JavaThread* current = JavaThread::current();
1566
1567 // Create java.base's module entry for the boot
1568 // class loader prior to loading j.l.Object.
1569 ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
1570
1571 // Get module entry table
1572 ModuleEntryTable* null_cld_modules = null_cld->modules();
1573 if (null_cld_modules == nullptr) {
1574 vm_exit_during_initialization("No ModuleEntryTable for the boot class loader");
1575 }
1576
1577 {
1578 MutexLocker ml(current, Module_lock);
1579 if (ModuleEntryTable::javabase_moduleEntry() == nullptr) { // may have been inited by CDS.
1580 ModuleEntry* jb_module = null_cld_modules->locked_create_entry(Handle(),
1581 false, vmSymbols::java_base(), nullptr, nullptr, null_cld);
1582 if (jb_module == nullptr) {
1583 vm_exit_during_initialization("Unable to create ModuleEntry for " JAVA_BASE_NAME);
1584 }
1585 ModuleEntryTable::set_javabase_moduleEntry(jb_module);
1586 }
1587 }
1588 }
1589
1590 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1591 // they could get inlined by aggressive compiler, an unknown trick, see bug 6966589.
1592 void PerfClassTraceTime::initialize() {
1593 if (!UsePerfData) return;
1594
1595 if (_eventp != nullptr) {
1596 // increment the event counter
1597 _eventp->inc();
1598 }
1599
1600 // stop the current active thread-local timer to measure inclusive time
1601 _prev_active_event = -1;
1602 for (int i=0; i < EVENT_TYPE_COUNT; i++) {
1603 if (_timers[i].is_active()) {
1604 assert(_prev_active_event == -1, "should have only one active timer");
1605 _prev_active_event = i;
1606 _timers[i].stop();
1607 }
1608 }
1609
1610 if (_recursion_counters == nullptr || (_recursion_counters[_event_type])++ == 0) {
1611 // start the inclusive timer if not recursively called
1612 _t.start();
1613 }
1614
1615 // start thread-local timer of the given event type
1616 if (!_timers[_event_type].is_active()) {
1617 _timers[_event_type].start();
1618 }
1619 }
1620
1621 PerfClassTraceTime::~PerfClassTraceTime() {
1622 if (!UsePerfData) return;
1623
1624 // stop the thread-local timer as the event completes
1625 // and resume the thread-local timer of the event next on the stack
1626 _timers[_event_type].stop();
1627 jlong selftime = _timers[_event_type].ticks();
1628
1629 if (_prev_active_event >= 0) {
1630 _timers[_prev_active_event].start();
1631 }
1632
1633 if (_recursion_counters != nullptr && --(_recursion_counters[_event_type]) > 0) return;
1634
1635 // increment the counters only on the leaf call
1636 _t.stop();
1637 _timep->inc(_t.ticks());
1638 if (_selftimep != nullptr) {
1639 _selftimep->inc(selftime);
1640 }
1641 // add all class loading related event selftime to the accumulated time counter
1642 ClassLoader::perf_accumulated_time()->inc(selftime);
1643
1644 // reset the timer
1645 _timers[_event_type].reset();
1646 }