1 /*
   2  * Copyright (c) 1997, 2019, 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/perfData.hpp"
  31 #include "utilities/exceptions.hpp"
  32 #include "utilities/macros.hpp"
  33 
  34 // The VM class loader.
  35 #include <sys/stat.h>
  36 
  37 // Name of boot "modules" image
  38 #define  MODULES_IMAGE_NAME "modules"
  39 
  40 // Class path entry (directory or zip file)
  41 
  42 class JImageFile;
  43 class ClassFileStream;
  44 class PackageEntry;
  45 template <typename T> class GrowableArray;
  46 
  47 class ClassPathEntry : public CHeapObj<mtClass> {
  48 private:
  49   ClassPathEntry* volatile _next;
  50 protected:
  51   const char* copy_path(const char*path);
  52 public:
  53   ClassPathEntry* next() const;
  54   virtual ~ClassPathEntry() {}
  55   void set_next(ClassPathEntry* next);
  56   virtual bool is_modules_image() const { return false; }
  57   virtual bool is_jar_file() const { return false; }
  58   // Is this entry created from the "Class-path" attribute from a JAR Manifest?
  59   virtual bool from_class_path_attr() const { return false; }
  60   virtual const char* name() const = 0;
  61   virtual JImageFile* jimage() const { return NULL; }
  62   virtual void close_jimage() {}
  63   // Constructor
  64   ClassPathEntry() : _next(NULL) {}
  65   // Attempt to locate file_name through this class path entry.
  66   // Returns a class file parsing stream if successfull.
  67   virtual ClassFileStream* open_stream(const char* name, TRAPS) = 0;
  68   // Open the stream for a specific class loader
  69   virtual ClassFileStream* open_stream_for_loader(const char* name, ClassLoaderData* loader_data, TRAPS) {
  70     return open_stream(name, THREAD);
  71   }
  72 };
  73 
  74 class ClassPathDirEntry: public ClassPathEntry {
  75  private:
  76   const char* _dir;           // Name of directory
  77  public:
  78   const char* name() const { return _dir; }
  79   ClassPathDirEntry(const char* dir) {
  80     _dir = copy_path(dir);
  81   }
  82   virtual ~ClassPathDirEntry() {}
  83   ClassFileStream* open_stream(const char* name, TRAPS);
  84 };
  85 
  86 // Type definitions for zip file and zip file entry
  87 typedef void* jzfile;
  88 typedef struct {
  89   char *name;                   /* entry name */
  90   jlong time;                   /* modification time */
  91   jlong size;                   /* size of uncompressed data */
  92   jlong csize;                  /* size of compressed data (zero if uncompressed) */
  93   jint crc;                     /* crc of uncompressed data */
  94   char *comment;                /* optional zip file comment */
  95   jbyte *extra;                 /* optional extra data */
  96   jlong pos;                    /* position of LOC header (if negative) or data */
  97 } jzentry;
  98 
  99 class ClassPathZipEntry: public ClassPathEntry {
 100  private:
 101   jzfile* _zip;              // The zip archive
 102   const char*   _zip_name;   // Name of zip archive
 103   bool _from_class_path_attr; // From the "Class-path" attribute of a jar file
 104  public:
 105   bool is_jar_file() const { return true;  }
 106   bool from_class_path_attr() const { return _from_class_path_attr; }
 107   const char* name() const { return _zip_name; }
 108   ClassPathZipEntry(jzfile* zip, const char* zip_name, bool is_boot_append, bool from_class_path_attr);
 109   virtual ~ClassPathZipEntry();
 110   u1* open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS);
 111   ClassFileStream* open_stream(const char* name, TRAPS);
 112   void contents_do(void f(const char* name, void* context), void* context);
 113 };
 114 
 115 
 116 // For java image files
 117 class ClassPathImageEntry: public ClassPathEntry {
 118 private:
 119   JImageFile* _jimage;
 120   const char* _name;
 121   DEBUG_ONLY(static ClassPathImageEntry* _singleton;)
 122 public:
 123   bool is_modules_image() const;
 124   bool is_open() const { return _jimage != NULL; }
 125   const char* name() const { return _name == NULL ? "" : _name; }
 126   JImageFile* jimage() const { return _jimage; }
 127   void close_jimage();
 128   ClassPathImageEntry(JImageFile* jimage, const char* name);
 129   virtual ~ClassPathImageEntry();
 130   ClassFileStream* open_stream(const char* name, TRAPS);
 131   ClassFileStream* open_stream_for_loader(const char* name, ClassLoaderData* loader_data, TRAPS);
 132 };
 133 
 134 // ModuleClassPathList contains a linked list of ClassPathEntry's
 135 // that have been specified for a specific module.  Currently,
 136 // the only way to specify a module/path pair is via the --patch-module
 137 // command line option.
 138 class ModuleClassPathList : public CHeapObj<mtClass> {
 139 private:
 140   Symbol* _module_name;
 141   // First and last entries of class path entries for a specific module
 142   ClassPathEntry* _module_first_entry;
 143   ClassPathEntry* _module_last_entry;
 144 public:
 145   Symbol* module_name() const { return _module_name; }
 146   ClassPathEntry* module_first_entry() const { return _module_first_entry; }
 147   ModuleClassPathList(Symbol* module_name);
 148   ~ModuleClassPathList();
 149   void add_to_list(ClassPathEntry* new_entry);
 150 };
 151 
 152 class ClassLoader: AllStatic {
 153  public:
 154   enum ClassLoaderType {
 155     BOOT_LOADER = 1,      /* boot loader */
 156     PLATFORM_LOADER  = 2, /* PlatformClassLoader */
 157     APP_LOADER  = 3       /* AppClassLoader */
 158   };
 159  protected:
 160 
 161   // Performance counters
 162   static PerfCounter* _perf_accumulated_time;
 163   static PerfCounter* _perf_classes_inited;
 164   static PerfCounter* _perf_class_init_time;
 165   static PerfCounter* _perf_class_init_selftime;
 166   static PerfCounter* _perf_classes_verified;
 167   static PerfCounter* _perf_class_verify_time;
 168   static PerfCounter* _perf_class_verify_selftime;
 169   static PerfCounter* _perf_classes_linked;
 170   static PerfCounter* _perf_class_link_time;
 171   static PerfCounter* _perf_class_link_selftime;
 172   static PerfCounter* _perf_class_parse_time;
 173   static PerfCounter* _perf_class_parse_selftime;
 174   static PerfCounter* _perf_sys_class_lookup_time;
 175   static PerfCounter* _perf_shared_classload_time;
 176   static PerfCounter* _perf_sys_classload_time;
 177   static PerfCounter* _perf_app_classload_time;
 178   static PerfCounter* _perf_app_classload_selftime;
 179   static PerfCounter* _perf_app_classload_count;
 180   static PerfCounter* _perf_define_appclasses;
 181   static PerfCounter* _perf_define_appclass_time;
 182   static PerfCounter* _perf_define_appclass_selftime;
 183   static PerfCounter* _perf_app_classfile_bytes_read;
 184   static PerfCounter* _perf_sys_classfile_bytes_read;
 185 
 186   static PerfCounter* _sync_systemLoaderLockContentionRate;
 187   static PerfCounter* _sync_nonSystemLoaderLockContentionRate;
 188   static PerfCounter* _sync_JVMFindLoadedClassLockFreeCounter;
 189   static PerfCounter* _sync_JVMDefineClassLockFreeCounter;
 190   static PerfCounter* _sync_JNIDefineClassLockFreeCounter;
 191 
 192   static PerfCounter* _unsafe_defineClassCallCounter;
 193 
 194   // The boot class path consists of 3 ordered pieces:
 195   //  1. the module/path pairs specified to --patch-module
 196   //    --patch-module=<module>=<file>(<pathsep><file>)*
 197   //  2. the base piece
 198   //    [jimage | build with exploded modules]
 199   //  3. boot loader append path
 200   //    [-Xbootclasspath/a]; [jvmti appended entries]
 201   //
 202   // The boot loader must obey this order when attempting
 203   // to load a class.
 204 
 205   // 1. Contains the module/path pairs specified to --patch-module
 206   static GrowableArray<ModuleClassPathList*>* _patch_mod_entries;
 207 
 208   // 2. the base piece
 209   //    Contains the ClassPathEntry of the modular java runtime image.
 210   //    If no java runtime image is present, this indicates a
 211   //    build with exploded modules is being used instead.
 212   static ClassPathEntry* _jrt_entry;
 213   static GrowableArray<ModuleClassPathList*>* _exploded_entries;
 214   enum { EXPLODED_ENTRY_SIZE = 80 }; // Initial number of exploded modules
 215 
 216   // 3. the boot loader's append path
 217   //    [-Xbootclasspath/a]; [jvmti appended entries]
 218   //    Note: boot loader append path does not support named modules.
 219   static ClassPathEntry* _first_append_entry;
 220   // Last entry in linked list of appended ClassPathEntry instances
 221   static ClassPathEntry* _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(const char* class_path);)
 229   CDS_ONLY(static void setup_module_search_path(const char* path, TRAPS);)
 230   static void add_to_app_classpath_entries(const char* path,
 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  public:
 236   CDS_ONLY(static ClassPathEntry* app_classpath_entries() {return _app_classpath_entries;})
 237   CDS_ONLY(static ClassPathEntry* module_path_entries() {return _module_path_entries;})
 238 
 239  protected:
 240   // Initialization:
 241   //   - setup the boot loader's system class path
 242   //   - setup the boot loader's patch mod entries, if present
 243   //   - create the ModuleEntry for java.base
 244   static void setup_bootstrap_search_path();
 245   static void setup_boot_search_path(const char *class_path);
 246   static void setup_patch_mod_entries();
 247   static void create_javabase();
 248 
 249   static void load_zip_library();
 250   static void load_jimage_library();
 251 
 252  public:
 253   static ClassPathEntry* create_class_path_entry(const char *path, const struct stat* st,
 254                                                  bool throw_exception,
 255                                                  bool is_boot_append,
 256                                                  bool from_class_path_attr, TRAPS);
 257 
 258   // If the package for the fully qualified class name is in the boot
 259   // loader's package entry table then add_package() sets the classpath_index
 260   // field so that get_system_package() will know to return a non-null value
 261   // for the package's location.  And, so that the package will be added to
 262   // the list of packages returned by get_system_packages().
 263   // For packages whose classes are loaded from the boot loader class path, the
 264   // classpath_index indicates which entry on the boot loader class path.
 265   static bool add_package(const char *fullq_class_name, s2 classpath_index, TRAPS);
 266 
 267   // Canonicalizes path names, so strcmp will work properly. This is mainly
 268   // to avoid confusing the zip library
 269   static bool get_canonical_path(const char* orig, char* out, int len);
 270   static const char* file_name_for_class_name(const char* class_name,
 271                                               int class_name_len);
 272   static PackageEntry* get_package_entry(const char* class_name, ClassLoaderData* loader_data, TRAPS);
 273 
 274  public:
 275   static jboolean decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg);
 276   static int crc32(int crc, const char* buf, int len);
 277   static bool update_class_path_entry_list(const char *path,
 278                                            bool check_for_duplicates,
 279                                            bool is_boot_append,
 280                                            bool from_class_path_attr,
 281                                            bool throw_exception=true);
 282   CDS_ONLY(static void update_module_path_entry_list(const char *path, TRAPS);)
 283   static void print_bootclasspath();
 284 
 285   // Timing
 286   static PerfCounter* perf_accumulated_time()         { return _perf_accumulated_time; }
 287   static PerfCounter* perf_classes_inited()           { return _perf_classes_inited; }
 288   static PerfCounter* perf_class_init_time()          { return _perf_class_init_time; }
 289   static PerfCounter* perf_class_init_selftime()      { return _perf_class_init_selftime; }
 290   static PerfCounter* perf_classes_verified()         { return _perf_classes_verified; }
 291   static PerfCounter* perf_class_verify_time()        { return _perf_class_verify_time; }
 292   static PerfCounter* perf_class_verify_selftime()    { return _perf_class_verify_selftime; }
 293   static PerfCounter* perf_classes_linked()           { return _perf_classes_linked; }
 294   static PerfCounter* perf_class_link_time()          { return _perf_class_link_time; }
 295   static PerfCounter* perf_class_link_selftime()      { return _perf_class_link_selftime; }
 296   static PerfCounter* perf_class_parse_time()         { return _perf_class_parse_time; }
 297   static PerfCounter* perf_class_parse_selftime()     { return _perf_class_parse_selftime; }
 298   static PerfCounter* perf_sys_class_lookup_time()    { return _perf_sys_class_lookup_time; }
 299   static PerfCounter* perf_shared_classload_time()    { return _perf_shared_classload_time; }
 300   static PerfCounter* perf_sys_classload_time()       { return _perf_sys_classload_time; }
 301   static PerfCounter* perf_app_classload_time()       { return _perf_app_classload_time; }
 302   static PerfCounter* perf_app_classload_selftime()   { return _perf_app_classload_selftime; }
 303   static PerfCounter* perf_app_classload_count()      { return _perf_app_classload_count; }
 304   static PerfCounter* perf_define_appclasses()        { return _perf_define_appclasses; }
 305   static PerfCounter* perf_define_appclass_time()     { return _perf_define_appclass_time; }
 306   static PerfCounter* perf_define_appclass_selftime() { return _perf_define_appclass_selftime; }
 307   static PerfCounter* perf_app_classfile_bytes_read() { return _perf_app_classfile_bytes_read; }
 308   static PerfCounter* perf_sys_classfile_bytes_read() { return _perf_sys_classfile_bytes_read; }
 309 
 310   // Record how often system loader lock object is contended
 311   static PerfCounter* sync_systemLoaderLockContentionRate() {
 312     return _sync_systemLoaderLockContentionRate;
 313   }
 314 
 315   // Record how often non system loader lock object is contended
 316   static PerfCounter* sync_nonSystemLoaderLockContentionRate() {
 317     return _sync_nonSystemLoaderLockContentionRate;
 318   }
 319 
 320   // Record how many calls to JVM_FindLoadedClass w/o holding a lock
 321   static PerfCounter* sync_JVMFindLoadedClassLockFreeCounter() {
 322     return _sync_JVMFindLoadedClassLockFreeCounter;
 323   }
 324 
 325   // Record how many calls to JVM_DefineClass w/o holding a lock
 326   static PerfCounter* sync_JVMDefineClassLockFreeCounter() {
 327     return _sync_JVMDefineClassLockFreeCounter;
 328   }
 329 
 330   // Record how many calls to jni_DefineClass w/o holding a lock
 331   static PerfCounter* sync_JNIDefineClassLockFreeCounter() {
 332     return _sync_JNIDefineClassLockFreeCounter;
 333   }
 334 
 335   // Record how many calls to Unsafe_DefineClass
 336   static PerfCounter* unsafe_defineClassCallCounter() {
 337     return _unsafe_defineClassCallCounter;
 338   }
 339 
 340   // Modular java runtime image is present vs. a build with exploded modules
 341   static bool has_jrt_entry() { return (_jrt_entry != NULL); }
 342   static ClassPathEntry* get_jrt_entry() { return _jrt_entry; }
 343   static void close_jrt_image();
 344 
 345   // Add a module's exploded directory to the boot loader's exploded module build list
 346   static void add_to_exploded_build_list(Symbol* module_name, TRAPS);
 347 
 348   // Attempt load of individual class from either the patched or exploded modules build lists
 349   static ClassFileStream* search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list,
 350                                                 const char* const class_name,
 351                                                 const char* const file_name, TRAPS);
 352 
 353   // Load individual .class file
 354   static InstanceKlass* load_class(Symbol* class_name, bool search_append_only, TRAPS);
 355 
 356   // If the specified package has been loaded by the system, then returns
 357   // the name of the directory or ZIP file that the package was loaded from.
 358   // Returns null if the package was not loaded.
 359   // Note: The specified name can either be the name of a class or package.
 360   // If a package name is specified, then it must be "/"-separator and also
 361   // end with a trailing "/".
 362   static oop get_system_package(const char* name, TRAPS);
 363 
 364   // Returns an array of Java strings representing all of the currently
 365   // loaded system packages.
 366   // Note: The package names returned are "/"-separated and end with a
 367   // trailing "/".
 368   static objArrayOop get_system_packages(TRAPS);
 369 
 370   // Initialization
 371   static void initialize();
 372   static void classLoader_init2(TRAPS);
 373   CDS_ONLY(static void initialize_shared_path();)
 374   CDS_ONLY(static void initialize_module_path(TRAPS);)
 375 
 376   static int compute_Object_vtable();
 377 
 378   static ClassPathEntry* classpath_entry(int n);
 379 
 380   static bool is_in_patch_mod_entries(Symbol* module_name);
 381 
 382 #if INCLUDE_CDS
 383   // Sharing dump and restore
 384 
 385   // Helper function used by CDS code to get the number of boot classpath
 386   // entries during shared classpath setup time.
 387   static int num_boot_classpath_entries();
 388 
 389   static ClassPathEntry* get_next_boot_classpath_entry(ClassPathEntry* e);
 390 
 391   // Helper function used by CDS code to get the number of app classpath
 392   // entries during shared classpath setup time.
 393   static int num_app_classpath_entries();
 394 
 395   // Helper function used by CDS code to get the number of module path
 396   // entries during shared classpath setup time.
 397   static int num_module_path_entries() {
 398     assert(DumpSharedSpaces || DynamicDumpSharedSpaces,
 399            "Should only be called at CDS dump time");
 400     int num_entries = 0;
 401     ClassPathEntry* e= ClassLoader::_module_path_entries;
 402     while (e != NULL) {
 403       num_entries ++;
 404       e = e->next();
 405     }
 406     return num_entries;
 407   }
 408   static void  exit_with_path_failure(const char* error, const char* message);
 409   static char* skip_uri_protocol(char* source);
 410   static void  record_result(InstanceKlass* ik, const ClassFileStream* stream, TRAPS);
 411 #endif
 412   static JImageLocationRef jimage_find_resource(JImageFile* jf, const char* module_name,
 413                                                 const char* file_name, jlong &size);
 414 
 415   static void  trace_class_path(const char* msg, const char* name = NULL);
 416 
 417   // VM monitoring and management support
 418   static jlong classloader_time_ms();
 419   static jlong class_method_total_size();
 420   static jlong class_init_count();
 421   static jlong class_init_time_ms();
 422   static jlong class_verify_time_ms();
 423   static jlong class_link_count();
 424   static jlong class_link_time_ms();
 425 
 426   // indicates if class path already contains a entry (exact match by name)
 427   static bool contains_append_entry(const char* name);
 428 
 429   // adds a class path to the boot append entries
 430   static void add_to_boot_append_entries(ClassPathEntry* new_entry);
 431 
 432   // creates a class path zip entry (returns NULL if JAR file cannot be opened)
 433   static ClassPathZipEntry* create_class_path_zip_entry(const char *apath, bool is_boot_append);
 434 
 435   static bool string_ends_with(const char* str, const char* str_to_find);
 436 
 437   // obtain package name from a fully qualified class name
 438   // *bad_class_name is set to true if there's a problem with parsing class_name, to
 439   // distinguish from a class_name with no package name, as both cases have a NULL return value
 440   static const char* package_from_name(const char* const class_name, bool* bad_class_name = NULL);
 441 
 442   // Debugging
 443   static void verify()              PRODUCT_RETURN;
 444 };
 445 
 446 // PerfClassTraceTime is used to measure time for class loading related events.
 447 // This class tracks cumulative time and exclusive time for specific event types.
 448 // During the execution of one event, other event types (e.g. class loading and
 449 // resolution) as well as recursive calls of the same event type could happen.
 450 // Only one elapsed timer (cumulative) and one thread-local self timer (exclusive)
 451 // (i.e. only one event type) are active at a time even multiple PerfClassTraceTime
 452 // instances have been created as multiple events are happening.
 453 class PerfClassTraceTime {
 454  public:
 455   enum {
 456     CLASS_LOAD   = 0,
 457     PARSE_CLASS  = 1,
 458     CLASS_LINK   = 2,
 459     CLASS_VERIFY = 3,
 460     CLASS_CLINIT = 4,
 461     DEFINE_CLASS = 5,
 462     EVENT_TYPE_COUNT = 6
 463   };
 464  protected:
 465   // _t tracks time from initialization to destruction of this timer instance
 466   // including time for all other event types, and recursive calls of this type.
 467   // When a timer is called recursively, the elapsedTimer _t would not be used.
 468   elapsedTimer     _t;
 469   PerfLongCounter* _timep;
 470   PerfLongCounter* _selftimep;
 471   PerfLongCounter* _eventp;
 472   // pointer to thread-local recursion counter and timer array
 473   // The thread_local timers track cumulative time for specific event types
 474   // exclusive of time for other event types, but including recursive calls
 475   // of the same type.
 476   int*             _recursion_counters;
 477   elapsedTimer*    _timers;
 478   int              _event_type;
 479   int              _prev_active_event;
 480 
 481  public:
 482 
 483   inline PerfClassTraceTime(PerfLongCounter* timep,     /* counter incremented with inclusive time */
 484                             PerfLongCounter* selftimep, /* counter incremented with exclusive time */
 485                             PerfLongCounter* eventp,    /* event counter */
 486                             int* recursion_counters,    /* thread-local recursion counter array */
 487                             elapsedTimer* timers,       /* thread-local timer array */
 488                             int type                    /* event type */ ) :
 489       _timep(timep), _selftimep(selftimep), _eventp(eventp), _recursion_counters(recursion_counters), _timers(timers), _event_type(type) {
 490     initialize();
 491   }
 492 
 493   inline PerfClassTraceTime(PerfLongCounter* timep,     /* counter incremented with inclusive time */
 494                             elapsedTimer* timers,       /* thread-local timer array */
 495                             int type                    /* event type */ ) :
 496       _timep(timep), _selftimep(NULL), _eventp(NULL), _recursion_counters(NULL), _timers(timers), _event_type(type) {
 497     initialize();
 498   }
 499 
 500   inline void suspend() { _t.stop(); _timers[_event_type].stop(); }
 501   inline void resume()  { _t.start(); _timers[_event_type].start(); }
 502 
 503   ~PerfClassTraceTime();
 504   void initialize();
 505 };
 506 
 507 #endif // SHARE_CLASSFILE_CLASSLOADER_HPP