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