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 #ifndef SHARE_CLASSFILE_CLASSLOADER_HPP
 26 #define SHARE_CLASSFILE_CLASSLOADER_HPP
 27 
 28 #include "jimage.hpp"
 29 #include "runtime/handles.hpp"
 30 #include "runtime/perfDataTypes.hpp"
 31 #include "utilities/exceptions.hpp"
 32 #include "utilities/macros.hpp"
 33 #include "utilities/ostream.hpp"
 34 #include "utilities/zipLibrary.hpp"
 35 
 36 // The VM class loader.
 37 #include <sys/stat.h>
 38 
 39 // Name of boot "modules" image
 40 #define  MODULES_IMAGE_NAME "modules"
 41 
 42 // Class path entry (directory or zip file)
 43 
 44 class JImageFile;
 45 class ClassFileStream;
 46 class PackageEntry;
 47 template <typename T> class GrowableArray;
 48 
 49 class ClassPathEntry : public CHeapObj<mtClass> {
 50 private:
 51   ClassPathEntry* volatile _next;
 52 protected:
 53   const char* copy_path(const char*path);
 54 public:
 55   ClassPathEntry* next() const;
 56   virtual ~ClassPathEntry() {}
 57   void set_next(ClassPathEntry* next);
 58 
 59   virtual bool is_modules_image() const { return false; }
 60   virtual bool is_jar_file() const { return false; }
 61   virtual const char* name() const = 0;
 62   virtual JImageFile* jimage() const { return nullptr; }
 63   virtual void close_jimage() {}
 64   // Constructor
 65   ClassPathEntry() : _next(nullptr) {}
 66   // Attempt to locate file_name through this class path entry.
 67   // Returns a class file parsing stream if successful.
 68   virtual ClassFileStream* open_stream(JavaThread* current, const char* name) = 0;
 69   // Open the stream for a specific class loader
 70   virtual ClassFileStream* open_stream_for_loader(JavaThread* current, const char* name, ClassLoaderData* loader_data) {
 71     return open_stream(current, name);
 72   }
 73 };
 74 
 75 class ClassPathDirEntry: public ClassPathEntry {
 76  private:
 77   const char* _dir;           // Name of directory
 78  public:
 79   const char* name() const { return _dir; }
 80   ClassPathDirEntry(const char* dir) {
 81     _dir = copy_path(dir);
 82   }
 83   virtual ~ClassPathDirEntry();
 84   ClassFileStream* open_stream(JavaThread* current, const char* name);
 85 };
 86 
 87 class ClassPathZipEntry: public ClassPathEntry {
 88  private:
 89   jzfile* _zip;              // The zip archive
 90   const char*   _zip_name;   // Name of zip archive
 91  public:
 92   bool is_jar_file() const { return true;  }
 93   const char* name() const { return _zip_name; }
 94   ClassPathZipEntry(jzfile* zip, const char* zip_name);
 95   virtual ~ClassPathZipEntry();
 96   bool has_entry(JavaThread* current, const char* name);
 97   u1* open_entry(JavaThread* current, const char* name, jint* filesize, bool nul_terminate);
 98   ClassFileStream* open_stream(JavaThread* current, const char* name);
 99 };
100 
101 
102 // For java image files
103 class ClassPathImageEntry: public ClassPathEntry {
104 private:
105   const char* _name;
106   DEBUG_ONLY(static ClassPathImageEntry* _singleton;)
107 public:
108   bool is_modules_image() const;
109   const char* name() const { return _name == nullptr ? "" : _name; }
110   JImageFile* jimage() const;
111   JImageFile* jimage_non_null() const;
112   void close_jimage();
113   ClassPathImageEntry(JImageFile* jimage, const char* name);
114   virtual ~ClassPathImageEntry() { ShouldNotReachHere(); }
115   ClassFileStream* open_stream(JavaThread* current, const char* name);
116   ClassFileStream* open_stream_for_loader(JavaThread* current, const char* name, ClassLoaderData* loader_data);
117 };
118 
119 // ModuleClassPathList contains a linked list of ClassPathEntry's
120 // that have been specified for a specific module.  Currently,
121 // the only way to specify a module/path pair is via the --patch-module
122 // command line option.
123 class ModuleClassPathList : public CHeapObj<mtClass> {
124 private:
125   Symbol* _module_name;
126   // First and last entries of class path entries for a specific module
127   ClassPathEntry* _module_first_entry;
128   ClassPathEntry* _module_last_entry;
129 public:
130   Symbol* module_name() const { return _module_name; }
131   ClassPathEntry* module_first_entry() const { return _module_first_entry; }
132   ModuleClassPathList(Symbol* module_name);
133   ~ModuleClassPathList();
134   void add_to_list(ClassPathEntry* new_entry);
135 };
136 
137 class ClassLoader: AllStatic {
138  public:
139   enum ClassLoaderType {
140     OTHER = 0,
141     BOOT_LOADER = 1,      /* boot loader */
142     PLATFORM_LOADER  = 2, /* PlatformClassLoader */
143     APP_LOADER  = 3       /* AppClassLoader */
144   };
145  protected:
146 
147   // Performance counters
148   static PerfCounter* _perf_accumulated_time;
149   static PerfCounter* _perf_classes_inited;
150   static PerfCounter* _perf_class_init_time;
151   static PerfCounter* _perf_class_init_selftime;
152   static PerfCounter* _perf_class_init_bytecodes_count;
153   static PerfCounter* _perf_classes_verified;
154   static PerfCounter* _perf_class_verify_time;
155   static PerfCounter* _perf_class_verify_selftime;
156   static PerfCounter* _perf_classes_linked;
157   static PerfCounter* _perf_class_link_time;
158   static PerfCounter* _perf_class_link_selftime;
159   static PerfCounter* _perf_shared_classload_time;
160   static PerfCounter* _perf_sys_classload_time;
161   static PerfCounter* _perf_app_classload_time;
162   static PerfCounter* _perf_app_classload_selftime;
163   static PerfCounter* _perf_app_classload_count;
164   static PerfCounter* _perf_define_appclasses;
165   static PerfCounter* _perf_define_appclass_time;
166   static PerfCounter* _perf_define_appclass_selftime;
167   static PerfCounter* _perf_app_classfile_bytes_read;
168   static PerfCounter* _perf_sys_classfile_bytes_read;
169   static PerfCounter* _perf_preload_total_time;
170   static PerfCounter* _perf_preload_time;
171   static PerfCounter* _perf_prelink_time;
172   static PerfCounter* _perf_preinit_time;
173   static PerfCounter* _perf_preresolve_time;
174   static PerfCounter* _perf_ik_link_methods_time;
175   static PerfCounter* _perf_method_adapters_time;
176   static PerfCounter* _perf_ik_link_methods_count;
177   static PerfCounter* _perf_method_adapters_count;
178 
179   static PerfTickCounters* _perf_resolve_indy_time;
180   static PerfTickCounters* _perf_resolve_invokehandle_time;
181   static PerfTickCounters* _perf_resolve_mh_time;
182   static PerfTickCounters* _perf_resolve_mt_time;
183 
184   static PerfCounter* _perf_resolve_indy_count;
185   static PerfCounter* _perf_resolve_invokehandle_count;
186   static PerfCounter* _perf_resolve_mh_count;
187   static PerfCounter* _perf_resolve_mt_count;
188 
189   static PerfCounter* _unsafe_defineClassCallCounter;
190 
191   // Count the time taken to hash the scondary superclass arrays.
192   static PerfCounter* _perf_secondary_hash_time;
193   static PerfCounter* _perf_change_wx_time;
194 
195   // The boot class path consists of 3 ordered pieces:
196   //  1. the module/path pairs specified to --patch-module
197   //    --patch-module=<module>=<file>(<pathsep><file>)*
198   //  2. the base piece
199   //    [jimage | build with exploded modules]
200   //  3. boot loader append path
201   //    [-Xbootclasspath/a]; [jvmti appended entries]
202   //
203   // The boot loader must obey this order when attempting
204   // to load a class.
205 
206   // 1. Contains the module/path pairs specified to --patch-module
207   static GrowableArray<ModuleClassPathList*>* _patch_mod_entries;
208 
209   // 2. the base piece
210   //    Contains the ClassPathEntry of the modular java runtime image.
211   //    If no java runtime image is present, this indicates a
212   //    build with exploded modules is being used instead.
213   static ClassPathEntry* _jrt_entry;
214   static GrowableArray<ModuleClassPathList*>* _exploded_entries;
215   enum { EXPLODED_ENTRY_SIZE = 80 }; // Initial number of exploded modules
216 
217   // 3. the boot loader's append path
218   //    [-Xbootclasspath/a]; [jvmti appended entries]
219   //    Note: boot loader append path does not support named modules.
220   static ClassPathEntry* volatile _first_append_entry_list;
221   static ClassPathEntry* first_append_entry() {
222     return AtomicAccess::load_acquire(&_first_append_entry_list);
223   }
224 
225   // Last entry in linked list of appended ClassPathEntry instances
226   static ClassPathEntry* volatile _last_append_entry;
227 
228  public:
229 
230   static bool has_bootclasspath_append() { return first_append_entry() != nullptr; }
231 
232  protected:
233   // Initialization:
234   //   - setup the boot loader's system class path
235   //   - setup the boot loader's patch mod entries, if present
236   //   - create the ModuleEntry for java.base
237   static void setup_bootstrap_search_path(JavaThread* current);
238   static void setup_bootstrap_search_path_impl(JavaThread* current, const char *class_path);
239   static void setup_patch_mod_entries();
240   static void create_javabase();
241 
242   static void* dll_lookup(void* lib, const char* name, const char* path);
243   static void load_java_library();
244   static void load_jimage_library();
245 
246  public:
247   static void* zip_library_handle();
248   static jzfile* open_zip_file(const char* canonical_path, char** error_msg, JavaThread* thread);
249   static ClassPathEntry* create_class_path_entry(JavaThread* current,
250                                                  const char *path, const struct stat* st);
251 
252   // Canonicalizes path names, so strcmp will work properly. This is mainly
253   // to avoid confusing the zip library
254   static char* get_canonical_path(const char* orig, Thread* thread);
255   static const char* file_name_for_class_name(const char* class_name,
256                                               int class_name_len);
257   static PackageEntry* get_package_entry(Symbol* pkg_name, ClassLoaderData* loader_data);
258   static int crc32(int crc, const char* buf, int len);
259   static bool update_class_path_entry_list(JavaThread* current,
260                                            const char *path);
261   static void print_bootclasspath();
262 
263   // Timing
264   static PerfCounter* perf_accumulated_time()         { return _perf_accumulated_time; }
265   static PerfCounter* perf_classes_inited()           { return _perf_classes_inited; }
266   static PerfCounter* perf_class_init_time()          { return _perf_class_init_time; }
267   static PerfCounter* perf_class_init_selftime()      { return _perf_class_init_selftime; }
268   static PerfCounter* perf_classes_verified()         { return _perf_classes_verified; }
269   static PerfCounter* perf_class_verify_time()        { return _perf_class_verify_time; }
270   static PerfCounter* perf_class_verify_selftime()    { return _perf_class_verify_selftime; }
271   static PerfCounter* perf_classes_linked()           { return _perf_classes_linked; }
272   static PerfCounter* perf_class_link_time()          { return _perf_class_link_time; }
273   static PerfCounter* perf_class_link_selftime()      { return _perf_class_link_selftime; }
274   static PerfCounter* perf_shared_classload_time()    { return _perf_shared_classload_time; }
275   static PerfCounter* perf_secondary_hash_time() {
276     return _perf_secondary_hash_time;
277   }
278   static PerfCounter* perf_change_wx_time() {
279     return _perf_change_wx_time;
280   }
281   static PerfCounter* perf_sys_classload_time()       { return _perf_sys_classload_time; }
282   static PerfCounter* perf_app_classload_time()       { return _perf_app_classload_time; }
283   static PerfCounter* perf_app_classload_selftime()   { return _perf_app_classload_selftime; }
284   static PerfCounter* perf_app_classload_count()      { return _perf_app_classload_count; }
285   static PerfCounter* perf_define_appclasses()        { return _perf_define_appclasses; }
286   static PerfCounter* perf_define_appclass_time()     { return _perf_define_appclass_time; }
287   static PerfCounter* perf_define_appclass_selftime() { return _perf_define_appclass_selftime; }
288   static PerfCounter* perf_app_classfile_bytes_read() { return _perf_app_classfile_bytes_read; }
289   static PerfCounter* perf_sys_classfile_bytes_read() { return _perf_sys_classfile_bytes_read; }
290 
291   static PerfCounter* perf_preload_total_time() { return _perf_preload_total_time; }
292   static PerfCounter* perf_preload_time() { return _perf_preload_time; }
293   static PerfCounter* perf_prelink_time() { return _perf_prelink_time; }
294   static PerfCounter* perf_preinit_time() { return _perf_preinit_time; }
295   static PerfCounter* perf_preresolve_time() { return _perf_preresolve_time; }
296   static PerfCounter* perf_ik_link_methods_time() { return _perf_ik_link_methods_time; }
297   static PerfCounter* perf_method_adapters_time() { return _perf_method_adapters_time; }
298   static PerfCounter* perf_ik_link_methods_count() { return _perf_ik_link_methods_count; }
299   static PerfCounter* perf_method_adapters_count() { return _perf_method_adapters_count; }
300 
301   static PerfTickCounters* perf_resolve_invokedynamic_time() { return _perf_resolve_indy_time; }
302   static PerfTickCounters* perf_resolve_invokehandle_time() { return _perf_resolve_invokehandle_time; }
303   static PerfTickCounters* perf_resolve_method_handle_time() { return _perf_resolve_mh_time; }
304   static PerfTickCounters* perf_resolve_method_type_time() { return _perf_resolve_mt_time; }
305 
306   static PerfCounter* perf_resolve_invokedynamic_count() { return _perf_resolve_indy_count; }
307   static PerfCounter* perf_resolve_invokehandle_count() { return _perf_resolve_invokehandle_count; }
308   static PerfCounter* perf_resolve_method_handle_count() { return _perf_resolve_mh_count; }
309   static PerfCounter* perf_resolve_method_type_count() { return _perf_resolve_mt_count; }
310 
311   static PerfCounter* perf_class_init_bytecodes_count() { return _perf_class_init_bytecodes_count; }
312 
313   static void print_counters(outputStream *st);
314 
315   // Record how many calls to Unsafe_DefineClass
316   static PerfCounter* unsafe_defineClassCallCounter() {
317     return _unsafe_defineClassCallCounter;
318   }
319 
320   // Modular java runtime image is present vs. a build with exploded modules
321   static bool has_jrt_entry() { return (_jrt_entry != nullptr); }
322   static ClassPathEntry* get_jrt_entry() { return _jrt_entry; }
323   static void close_jrt_image();
324 
325   // Add a module's exploded directory to the boot loader's exploded module build list
326   static void add_to_exploded_build_list(JavaThread* current, Symbol* module_name);
327 
328   // Search the module list for the class file stream based on the file name and java package
329   static ClassFileStream* search_module_entries(JavaThread* current,
330                                                 const GrowableArray<ModuleClassPathList*>* const module_list,
331                                                 PackageEntry* pkg_entry, // Java package entry derived from the class name
332                                                 const char* const file_name);
333 
334   // Load individual .class file
335   static InstanceKlass* load_class(Symbol* class_name, PackageEntry* pkg_entry, bool search_append_only, TRAPS);
336 
337   // If the specified package has been loaded by the system, then returns
338   // the name of the directory or ZIP file that the package was loaded from.
339   // Returns null if the package was not loaded.
340   // Note: The specified name can either be the name of a class or package.
341   // If a package name is specified, then it must be "/"-separator and also
342   // end with a trailing "/".
343   static oop get_system_package(const char* name, TRAPS);
344 
345   // Returns an array of Java strings representing all of the currently
346   // loaded system packages.
347   // Note: The package names returned are "/"-separated and end with a
348   // trailing "/".
349   static objArrayOop get_system_packages(TRAPS);
350 
351   // Initialization
352   static void initialize(TRAPS);
353   static void classLoader_init2(JavaThread* current);
354 
355   static int compute_Object_vtable();
356 
357   static ClassPathEntry* classpath_entry(int n);
358 
359   static bool is_in_patch_mod_entries(Symbol* module_name);
360 
361 #if INCLUDE_CDS
362   static char* uri_to_path(const char* uri);
363   static void  record_result(JavaThread* current, InstanceKlass* ik,
364                              const ClassFileStream* stream, bool redefined);
365   static void record_result_for_builtin_loader(s2 classpath_index, InstanceKlass* result, bool redefined);
366   static void record_hidden_class(InstanceKlass* ik);
367   static void append_boot_classpath(ClassPathEntry* new_entry);
368 #endif
369 
370   static char* lookup_vm_options();
371 
372   // Determines if the named module is present in the
373   // modules jimage file or in the exploded modules directory.
374   static bool is_module_observable(const char* module_name);
375 
376   static JImageLocationRef jimage_find_resource(JImageFile* jf, const char* module_name,
377                                                 const char* file_name, jlong &size);
378 
379   static void  trace_class_path(const char* msg, const char* name = nullptr);
380 
381   // VM monitoring and management support
382   static jlong classloader_time_ms();
383   static jlong class_method_total_size();
384   static jlong class_init_count();
385   static jlong class_init_time_ms();
386   static jlong class_verify_time_ms();
387   static jlong class_link_count();
388   static jlong class_link_time_ms();
389   static jlong class_init_bytecodes_count();
390 
391   // adds a class path to the boot append entries
392   static void add_to_boot_append_entries(ClassPathEntry* new_entry);
393 
394   // creates a class path zip entry (returns null if JAR file cannot be opened)
395   static ClassPathZipEntry* create_class_path_zip_entry(const char *path);
396 
397   static bool string_ends_with(const char* str, const char* str_to_find);
398 
399   // Extract package name from a fully qualified class name
400   // *bad_class_name is set to true if there's a problem with parsing class_name, to
401   // distinguish from a class_name with no package name, as both cases have a null return value
402   static Symbol* package_from_class_name(const Symbol* class_name, bool* bad_class_name = nullptr);
403 
404   // Debugging
405   static void verify()              PRODUCT_RETURN;
406 };
407 
408 // PerfClassTraceTime is used to measure time for class loading related events.
409 // This class tracks cumulative time and exclusive time for specific event types.
410 // During the execution of one event, other event types (e.g. class loading and
411 // resolution) as well as recursive calls of the same event type could happen.
412 // Only one elapsed timer (cumulative) and one thread-local self timer (exclusive)
413 // (i.e. only one event type) are active at a time even multiple PerfClassTraceTime
414 // instances have been created as multiple events are happening.
415 class PerfClassTraceTime {
416  public:
417   enum {
418     CLASS_LOAD   = 0,
419     CLASS_LINK   = 1,
420     CLASS_VERIFY = 2,
421     CLASS_CLINIT = 3,
422     DEFINE_CLASS = 4,
423     EVENT_TYPE_COUNT = 5
424   };
425  protected:
426   // _t tracks time from initialization to destruction of this timer instance
427   // including time for all other event types, and recursive calls of this type.
428   // When a timer is called recursively, the elapsedTimer _t would not be used.
429   elapsedTimer     _t;
430   PerfLongCounter* _timep;
431   PerfLongCounter* _selftimep;
432   PerfLongCounter* _eventp;
433   // pointer to thread-local recursion counter and timer array
434   // The thread_local timers track cumulative time for specific event types
435   // exclusive of time for other event types, but including recursive calls
436   // of the same type.
437   int*             _recursion_counters;
438   elapsedTimer*    _timers;
439   int              _event_type;
440   int              _prev_active_event;
441 
442  public:
443 
444   inline PerfClassTraceTime(PerfLongCounter* timep,     /* counter incremented with inclusive time */
445                             PerfLongCounter* selftimep, /* counter incremented with exclusive time */
446                             PerfLongCounter* eventp,    /* event counter */
447                             int* recursion_counters,    /* thread-local recursion counter array */
448                             elapsedTimer* timers,       /* thread-local timer array */
449                             int type                    /* event type */ ) :
450       _timep(timep), _selftimep(selftimep), _eventp(eventp), _recursion_counters(recursion_counters), _timers(timers), _event_type(type) {
451     initialize();
452   }
453 
454   inline PerfClassTraceTime(PerfLongCounter* timep,     /* counter incremented with inclusive time */
455                             elapsedTimer* timers,       /* thread-local timer array */
456                             int type                    /* event type */ ) :
457       _timep(timep), _selftimep(nullptr), _eventp(nullptr), _recursion_counters(nullptr), _timers(timers), _event_type(type) {
458     initialize();
459   }
460 
461   ~PerfClassTraceTime();
462   void initialize();
463 };
464 
465 #endif // SHARE_CLASSFILE_CLASSLOADER_HPP