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