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