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