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