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