classLoader.cpp 59.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28
#include "precompiled.hpp"
#include "classfile/classFileParser.hpp"
#include "classfile/classFileStream.hpp"
#include "classfile/classLoader.hpp"
29
#include "classfile/classLoaderExt.hpp"
30
#include "classfile/classLoaderData.inline.hpp"
31
#include "classfile/javaClasses.hpp"
32 33 34 35
#if INCLUDE_CDS
#include "classfile/sharedPathsMiscInfo.hpp"
#include "classfile/sharedClassUtil.hpp"
#endif
36 37 38 39 40 41 42
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "compiler/compileBroker.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "interpreter/bytecodeStream.hpp"
#include "interpreter/oopMapCache.hpp"
#include "memory/allocation.inline.hpp"
43
#include "memory/filemap.hpp"
44 45 46 47 48 49
#include "memory/generation.hpp"
#include "memory/oopFactory.hpp"
#include "memory/universe.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/instanceRefKlass.hpp"
#include "oops/oop.inline.hpp"
50
#include "oops/symbol.hpp"
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include "prims/jvm_misc.hpp"
#include "runtime/arguments.hpp"
#include "runtime/compilationPolicy.hpp"
#include "runtime/fprofiler.hpp"
#include "runtime/handles.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/timer.hpp"
#include "services/management.hpp"
#include "services/threadService.hpp"
#include "utilities/events.hpp"
#include "utilities/hashtable.hpp"
#include "utilities/hashtable.inline.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
77 78 79
#ifdef TARGET_OS_FAMILY_aix
# include "os_aix.inline.hpp"
#endif
N
never 已提交
80 81 82
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
D
duke 已提交
83 84 85 86 87 88 89 90 91 92


// Entry points in zip.dll for loading zip/jar file entries

typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
typedef void (JNICALL *ZipClose_t)(jzfile *zip);
typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
J
jiangli 已提交
93
typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
D
duke 已提交
94 95 96 97 98 99 100 101

static ZipOpen_t         ZipOpen            = NULL;
static ZipClose_t        ZipClose           = NULL;
static FindEntry_t       FindEntry          = NULL;
static ReadEntry_t       ReadEntry          = NULL;
static ReadMappedEntry_t ReadMappedEntry    = NULL;
static GetNextEntry_t    GetNextEntry       = NULL;
static canonicalize_fn_t CanonicalizeEntry  = NULL;
J
jiangli 已提交
102
static Crc32_t           Crc32              = NULL;
D
duke 已提交
103 104 105 106 107 108

// Globals

PerfCounter*    ClassLoader::_perf_accumulated_time = NULL;
PerfCounter*    ClassLoader::_perf_classes_inited = NULL;
PerfCounter*    ClassLoader::_perf_class_init_time = NULL;
109 110
PerfCounter*    ClassLoader::_perf_class_init_selftime = NULL;
PerfCounter*    ClassLoader::_perf_classes_verified = NULL;
D
duke 已提交
111
PerfCounter*    ClassLoader::_perf_class_verify_time = NULL;
112
PerfCounter*    ClassLoader::_perf_class_verify_selftime = NULL;
D
duke 已提交
113 114
PerfCounter*    ClassLoader::_perf_classes_linked = NULL;
PerfCounter*    ClassLoader::_perf_class_link_time = NULL;
115 116 117 118 119 120 121 122 123 124 125 126 127 128
PerfCounter*    ClassLoader::_perf_class_link_selftime = NULL;
PerfCounter*    ClassLoader::_perf_class_parse_time = NULL;
PerfCounter*    ClassLoader::_perf_class_parse_selftime = NULL;
PerfCounter*    ClassLoader::_perf_sys_class_lookup_time = NULL;
PerfCounter*    ClassLoader::_perf_shared_classload_time = NULL;
PerfCounter*    ClassLoader::_perf_sys_classload_time = NULL;
PerfCounter*    ClassLoader::_perf_app_classload_time = NULL;
PerfCounter*    ClassLoader::_perf_app_classload_selftime = NULL;
PerfCounter*    ClassLoader::_perf_app_classload_count = NULL;
PerfCounter*    ClassLoader::_perf_define_appclasses = NULL;
PerfCounter*    ClassLoader::_perf_define_appclass_time = NULL;
PerfCounter*    ClassLoader::_perf_define_appclass_selftime = NULL;
PerfCounter*    ClassLoader::_perf_app_classfile_bytes_read = NULL;
PerfCounter*    ClassLoader::_perf_sys_classfile_bytes_read = NULL;
D
duke 已提交
129 130 131 132 133 134 135 136 137 138 139
PerfCounter*    ClassLoader::_sync_systemLoaderLockContentionRate = NULL;
PerfCounter*    ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL;
PerfCounter*    ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL;
PerfCounter*    ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL;
PerfCounter*    ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL;
PerfCounter*    ClassLoader::_unsafe_defineClassCallCounter = NULL;
PerfCounter*    ClassLoader::_isUnsyncloadClass = NULL;
PerfCounter*    ClassLoader::_load_instance_class_failCounter = NULL;

ClassPathEntry* ClassLoader::_first_entry         = NULL;
ClassPathEntry* ClassLoader::_last_entry          = NULL;
140
int             ClassLoader::_num_entries         = 0;
D
duke 已提交
141 142
PackageHashtable* ClassLoader::_package_hash_table = NULL;

143 144 145
#if INCLUDE_CDS
SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL;
#endif
D
duke 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
// helper routines
bool string_starts_with(const char* str, const char* str_to_find) {
  size_t str_len = strlen(str);
  size_t str_to_find_len = strlen(str_to_find);
  if (str_to_find_len > str_len) {
    return false;
  }
  return (strncmp(str, str_to_find, str_to_find_len) == 0);
}

bool string_ends_with(const char* str, const char* str_to_find) {
  size_t str_len = strlen(str);
  size_t str_to_find_len = strlen(str_to_find);
  if (str_to_find_len > str_len) {
    return false;
  }
  return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0);
}


MetaIndex::MetaIndex(char** meta_package_names, int num_meta_package_names) {
  if (num_meta_package_names == 0) {
    _meta_package_names = NULL;
    _num_meta_package_names = 0;
  } else {
Z
zgu 已提交
171
    _meta_package_names = NEW_C_HEAP_ARRAY(char*, num_meta_package_names, mtClass);
D
duke 已提交
172 173 174 175 176 177 178
    _num_meta_package_names = num_meta_package_names;
    memcpy(_meta_package_names, meta_package_names, num_meta_package_names * sizeof(char*));
  }
}


MetaIndex::~MetaIndex() {
Z
zgu 已提交
179
  FREE_C_HEAP_ARRAY(char*, _meta_package_names, mtClass);
D
duke 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}


bool MetaIndex::may_contain(const char* class_name) {
  if ( _num_meta_package_names == 0) {
    return false;
  }
  size_t class_name_len = strlen(class_name);
  for (int i = 0; i < _num_meta_package_names; i++) {
    char* pkg = _meta_package_names[i];
    size_t pkg_len = strlen(pkg);
    size_t min_len = MIN2(class_name_len, pkg_len);
    if (!strncmp(class_name, pkg, min_len)) {
      return true;
    }
  }
  return false;
}


ClassPathEntry::ClassPathEntry() {
  set_next(NULL);
}


bool ClassPathEntry::is_lazy() {
  return false;
}

I
iklam 已提交
209 210 211 212
ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() {
  char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass);
  strcpy(copy, dir);
  _dir = copy;
D
duke 已提交
213 214 215
}


216
ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) {
D
duke 已提交
217 218 219 220 221 222 223 224
  // construct full path name
  char path[JVM_MAXPATHLEN];
  if (jio_snprintf(path, sizeof(path), "%s%s%s", _dir, os::file_separator(), name) == -1) {
    return NULL;
  }
  // check if file exists
  struct stat st;
  if (os::stat(path, &st) == 0) {
225 226 227 228 229 230 231 232
#if INCLUDE_CDS
    if (DumpSharedSpaces) {
      // We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so
      // we should never find a file underneath it -- unless user has added a new file while we are running
      // the dump, in which case let's quit!
      ShouldNotReachHere();
    }
#endif
D
duke 已提交
233
    // found file, open it
234
    int file_handle = os::open(path, 0, 0);
D
duke 已提交
235 236 237 238 239
    if (file_handle != -1) {
      // read contents into resource array
      u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size);
      size_t num_read = os::read(file_handle, (char*) buffer, st.st_size);
      // close file
240
      os::close(file_handle);
D
duke 已提交
241 242
      // construct ClassFileStream
      if (num_read == (size_t)st.st_size) {
243 244 245
        if (UsePerfData) {
          ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);
        }
D
duke 已提交
246 247 248 249 250 251 252 253 254 255
        return new ClassFileStream(buffer, st.st_size, _dir);    // Resource allocated
      }
    }
  }
  return NULL;
}


ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name) : ClassPathEntry() {
  _zip = zip;
I
iklam 已提交
256 257 258
  char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass);
  strcpy(copy, zip_name);
  _zip_name = copy;
D
duke 已提交
259 260 261 262 263 264
}

ClassPathZipEntry::~ClassPathZipEntry() {
  if (ZipClose != NULL) {
    (*ZipClose)(_zip);
  }
Z
zgu 已提交
265
  FREE_C_HEAP_ARRAY(char, _zip_name, mtClass);
D
duke 已提交
266 267
}

268 269
u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
    // enable call to C land
D
duke 已提交
270 271 272
  JavaThread* thread = JavaThread::current();
  ThreadToNativeFromVM ttn(thread);
  // check whether zip archive contains name
273 274
  jint name_len;
  jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len);
D
duke 已提交
275 276 277 278 279 280 281 282 283 284
  if (entry == NULL) return NULL;
  u1* buffer;
  char name_buf[128];
  char* filename;
  if (name_len < 128) {
    filename = name_buf;
  } else {
    filename = NEW_RESOURCE_ARRAY(char, name_len + 1);
  }

285
  // file found, get pointer to the entry in mmapped jar file.
D
duke 已提交
286 287
  if (ReadMappedEntry == NULL ||
      !(*ReadMappedEntry)(_zip, entry, &buffer, filename)) {
288
      // mmapped access not available, perhaps due to compression,
D
duke 已提交
289
      // read contents into resource array
290 291
      int size = (*filesize) + ((nul_terminate) ? 1 : 0);
      buffer = NEW_RESOURCE_ARRAY(u1, size);
D
duke 已提交
292 293
      if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
  }
294 295 296 297 298 299 300 301 302 303 304 305 306 307

  // return result
  if (nul_terminate) {
    buffer[*filesize] = 0;
  }
  return buffer;
}

ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) {
  jint filesize;
  u1* buffer = open_entry(name, &filesize, false, CHECK_NULL);
  if (buffer == NULL) {
    return NULL;
  }
308 309 310
  if (UsePerfData) {
    ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);
  }
311
  return new ClassFileStream(buffer, filesize, _zip_name); // Resource allocated
D
duke 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325
}

// invoke function for each entry in the zip file
void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) {
  JavaThread* thread = JavaThread::current();
  HandleMark  handle_mark(thread);
  ThreadToNativeFromVM ttn(thread);
  for (int n = 0; ; n++) {
    jzentry * ze = ((*GetNextEntry)(_zip, n));
    if (ze == NULL) break;
    (*f)(ze->name, context);
  }
}

I
iklam 已提交
326
LazyClassPathEntry::LazyClassPathEntry(const char* path, const struct stat* st, bool throw_exception) : ClassPathEntry() {
D
duke 已提交
327
  _path = strdup(path);
328
  _st = *st;
D
duke 已提交
329 330
  _meta_index = NULL;
  _resolved_entry = NULL;
331
  _has_error = false;
332
  _throw_exception = throw_exception;
D
duke 已提交
333 334 335 336 337 338
}

bool LazyClassPathEntry::is_jar_file() {
  return ((_st.st_mode & S_IFREG) == S_IFREG);
}

339
ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) {
D
duke 已提交
340 341 342 343
  if (_resolved_entry != NULL) {
    return (ClassPathEntry*) _resolved_entry;
  }
  ClassPathEntry* new_entry = NULL;
344 345 346 347 348
  new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, _throw_exception, CHECK_NULL);
  if (!_throw_exception && new_entry == NULL) {
    assert(!HAS_PENDING_EXCEPTION, "must be");
    return NULL;
  }
D
duke 已提交
349 350 351 352 353 354 355 356 357 358 359 360
  {
    ThreadCritical tc;
    if (_resolved_entry == NULL) {
      _resolved_entry = new_entry;
      return new_entry;
    }
  }
  assert(_resolved_entry != NULL, "bug in MT-safe resolution logic");
  delete new_entry;
  return (ClassPathEntry*) _resolved_entry;
}

361
ClassFileStream* LazyClassPathEntry::open_stream(const char* name, TRAPS) {
D
duke 已提交
362 363 364 365
  if (_meta_index != NULL &&
      !_meta_index->may_contain(name)) {
    return NULL;
  }
366 367 368 369 370 371 372 373 374 375
  if (_has_error) {
    return NULL;
  }
  ClassPathEntry* cpe = resolve_entry(THREAD);
  if (cpe == NULL) {
    _has_error = true;
    return NULL;
  } else {
    return cpe->open_stream(name, THREAD);
  }
D
duke 已提交
376 377 378 379 380 381
}

bool LazyClassPathEntry::is_lazy() {
  return true;
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
u1* LazyClassPathEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
  if (_has_error) {
    return NULL;
  }
  ClassPathEntry* cpe = resolve_entry(THREAD);
  if (cpe == NULL) {
    _has_error = true;
    return NULL;
  } else if (cpe->is_jar_file()) {
    return ((ClassPathZipEntry*)cpe)->open_entry(name, filesize, nul_terminate,THREAD);
  } else {
    ShouldNotReachHere();
    *filesize = 0;
    return NULL;
  }
}

D
duke 已提交
399 400 401 402 403
static void print_meta_index(LazyClassPathEntry* entry,
                             GrowableArray<char*>& meta_packages) {
  tty->print("[Meta index for %s=", entry->name());
  for (int i = 0; i < meta_packages.length(); i++) {
    if (i > 0) tty->print(" ");
404
    tty->print("%s", meta_packages.at(i));
D
duke 已提交
405 406 407 408
  }
  tty->print_cr("]");
}

409 410 411 412 413 414 415 416
#if INCLUDE_CDS
void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
  assert(DumpSharedSpaces, "only called at dump time");
  tty->print_cr("Hint: enable -XX:+TraceClassPaths to diagnose the failure");
  vm_exit_during_initialization(error, message);
}
#endif

417
void ClassLoader::trace_class_path(outputStream* out, const char* msg, const char* name) {
418 419 420 421 422
  if (!TraceClassPaths) {
    return;
  }

  if (msg) {
423
    out->print("%s", msg);
424 425 426
  }
  if (name) {
    if (strlen(name) < 256) {
427
      out->print("%s", name);
428 429 430 431
    } else {
      // For very long paths, we need to print each character separately,
      // as print_cr() has a length limit
      while (name[0] != '\0') {
432
        out->print("%c", name[0]);
433 434 435 436 437
        name++;
      }
    }
  }
  if (msg && msg[0] == '[') {
438
    out->print_cr("]");
439
  } else {
440
    out->cr();
441 442
  }
}
D
duke 已提交
443

444
void ClassLoader::setup_bootstrap_meta_index() {
D
duke 已提交
445 446
  // Set up meta index which allows us to open boot jars lazily if
  // class data sharing is enabled
447 448 449 450 451 452
  const char* meta_index_path = Arguments::get_meta_index_path();
  const char* meta_index_dir  = Arguments::get_meta_index_dir();
  setup_meta_index(meta_index_path, meta_index_dir, 0);
}

void ClassLoader::setup_meta_index(const char* meta_index_path, const char* meta_index_dir, int start_index) {
D
duke 已提交
453 454 455
  const char* known_version = "% VERSION 2";
  FILE* file = fopen(meta_index_path, "r");
  int line_no = 0;
456 457 458 459 460 461 462 463 464
#if INCLUDE_CDS
  if (DumpSharedSpaces) {
    if (file != NULL) {
      _shared_paths_misc_info->add_required_file(meta_index_path);
    } else {
      _shared_paths_misc_info->add_nonexist_path(meta_index_path);
    }
  }
#endif
D
duke 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  if (file != NULL) {
    ResourceMark rm;
    LazyClassPathEntry* cur_entry = NULL;
    GrowableArray<char*> boot_class_path_packages(10);
    char package_name[256];
    bool skipCurrentJar = false;
    while (fgets(package_name, sizeof(package_name), file) != NULL) {
      ++line_no;
      // Remove trailing newline
      package_name[strlen(package_name) - 1] = '\0';
      switch(package_name[0]) {
        case '%':
        {
          if ((line_no == 1) && (strcmp(package_name, known_version) != 0)) {
            if (TraceClassLoading && Verbose) {
              tty->print("[Unsupported meta index version]");
            }
            fclose(file);
            return;
          }
        }

        // These directives indicate jar files which contain only
        // classes, only non-classfile resources, or a combination of
        // the two. See src/share/classes/sun/misc/MetaIndex.java and
        // make/tools/MetaIndex/BuildMetaIndex.java in the J2SE
        // workspace.
        case '#':
        case '!':
        case '@':
        {
          // Hand off current packages to current lazy entry (if any)
          if ((cur_entry != NULL) &&
              (boot_class_path_packages.length() > 0)) {
499
            if ((TraceClassLoading || TraceClassPaths) && Verbose) {
D
duke 已提交
500 501 502 503 504 505 506 507 508 509
              print_meta_index(cur_entry, boot_class_path_packages);
            }
            MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),
                                             boot_class_path_packages.length());
            cur_entry->set_meta_index(index);
          }
          cur_entry = NULL;
          boot_class_path_packages.clear();

          // Find lazy entry corresponding to this jar file
510 511 512 513
          int count = 0;
          for (ClassPathEntry* entry = _first_entry; entry != NULL; entry = entry->next(), count++) {
            if (count >= start_index &&
                entry->is_lazy() &&
D
duke 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
                string_starts_with(entry->name(), meta_index_dir) &&
                string_ends_with(entry->name(), &package_name[2])) {
              cur_entry = (LazyClassPathEntry*) entry;
              break;
            }
          }

          // If the first character is '@', it indicates the following jar
          // file is a resource only jar file in which case, we should skip
          // reading the subsequent entries since the resource loading is
          // totally handled by J2SE side.
          if (package_name[0] == '@') {
            if (cur_entry != NULL) {
              cur_entry->set_meta_index(new MetaIndex(NULL, 0));
            }
            cur_entry = NULL;
            skipCurrentJar = true;
          } else {
            skipCurrentJar = false;
          }

          break;
        }

        default:
        {
          if (!skipCurrentJar && cur_entry != NULL) {
            char* new_name = strdup(package_name);
            boot_class_path_packages.append(new_name);
          }
        }
      }
    }
    // Hand off current packages to current lazy entry (if any)
    if ((cur_entry != NULL) &&
        (boot_class_path_packages.length() > 0)) {
550
      if ((TraceClassLoading || TraceClassPaths) && Verbose) {
D
duke 已提交
551 552 553 554 555 556 557 558 559 560
        print_meta_index(cur_entry, boot_class_path_packages);
      }
      MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),
                                       boot_class_path_packages.length());
      cur_entry->set_meta_index(index);
    }
    fclose(file);
  }
}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
#if INCLUDE_CDS
void ClassLoader::check_shared_classpath(const char *path) {
  if (strcmp(path, "") == 0) {
    exit_with_path_failure("Cannot have empty path in archived classpaths", NULL);
  }

  struct stat st;
  if (os::stat(path, &st) == 0) {
    if ((st.st_mode & S_IFREG) != S_IFREG) { // is directory
      if (!os::dir_is_empty(path)) {
        tty->print_cr("Error: non-empty directory '%s'", path);
        exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL);
      }
    }
  }
}
#endif

D
duke 已提交
579 580
void ClassLoader::setup_bootstrap_search_path() {
  assert(_first_entry == NULL, "should not setup bootstrap class search path twice");
I
iklam 已提交
581 582 583 584 585
  const char* sys_class_path = Arguments::get_sysclasspath();
  if (PrintSharedArchiveAndExit) {
    // Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily
    // the same as the bootcp of the shared archive.
  } else {
586
    trace_class_path(tty, "[Bootstrap loader class path=", sys_class_path);
587 588 589
  }
#if INCLUDE_CDS
  if (DumpSharedSpaces) {
I
iklam 已提交
590
    _shared_paths_misc_info->add_boot_classpath(sys_class_path);
D
duke 已提交
591
  }
592 593 594 595 596 597 598 599 600 601 602 603
#endif
  setup_search_path(sys_class_path);
}

#if INCLUDE_CDS
int ClassLoader::get_shared_paths_misc_info_size() {
  return _shared_paths_misc_info->get_used_bytes();
}

void* ClassLoader::get_shared_paths_misc_info() {
  return _shared_paths_misc_info->buffer();
}
D
duke 已提交
604

605 606 607 608 609 610 611 612
bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) {
  SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size);
  bool result = checker->check();
  delete checker;
  return result;
}
#endif

613
void ClassLoader::setup_search_path(const char *class_path, bool canonicalize) {
614 615
  int offset = 0;
  int len = (int)strlen(class_path);
D
duke 已提交
616 617 618 619
  int end = 0;

  // Iterate over class path entries
  for (int start = 0; start < len; start = end) {
620
    while (class_path[end] && class_path[end] != os::path_separator()[0]) {
D
duke 已提交
621 622
      end++;
    }
623 624 625 626 627
    EXCEPTION_MARK;
    ResourceMark rm(THREAD);
    char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
    strncpy(path, &class_path[start], end - start);
    path[end - start] = '\0';
628 629 630 631 632 633 634
    if (canonicalize) {
      char* canonical_path = NEW_RESOURCE_ARRAY(char, JVM_MAXPATHLEN + 1);
      if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
        path = canonical_path;
      }
    }
    update_class_path_entry_list(path, /*check_for_duplicates=*/canonicalize);
635 636 637 638 639 640
#if INCLUDE_CDS
    if (DumpSharedSpaces) {
      check_shared_classpath(path);
    }
#endif
    while (class_path[end] == os::path_separator()[0]) {
D
duke 已提交
641 642 643 644 645
      end++;
    }
  }
}

I
iklam 已提交
646
ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
647
                                                     bool lazy, bool throw_exception, TRAPS) {
D
duke 已提交
648 649
  JavaThread* thread = JavaThread::current();
  if (lazy) {
650
    return new LazyClassPathEntry(path, st, throw_exception);
D
duke 已提交
651
  }
652 653
  ClassPathEntry* new_entry = NULL;
  if ((st->st_mode & S_IFREG) == S_IFREG) {
D
duke 已提交
654 655 656 657 658
    // Regular file, should be a zip file
    // Canonicalized filename
    char canonical_path[JVM_MAXPATHLEN];
    if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
      // This matches the classic VM
659 660 661 662 663
      if (throw_exception) {
        THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
      } else {
        return NULL;
      }
D
duke 已提交
664 665 666 667 668 669 670 671 672 673
    }
    char* error_msg = NULL;
    jzfile* zip;
    {
      // enable call to C land
      ThreadToNativeFromVM ttn(thread);
      HandleMark hm(thread);
      zip = (*ZipOpen)(canonical_path, &error_msg);
    }
    if (zip != NULL && error_msg == NULL) {
674
      new_entry = new ClassPathZipEntry(zip, path);
675
      if (TraceClassLoading || TraceClassPaths) {
D
duke 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688
        tty->print_cr("[Opened %s]", path);
      }
    } else {
      ResourceMark rm(thread);
      char *msg;
      if (error_msg == NULL) {
        msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;
        jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
      } else {
        int len = (int)(strlen(path) + strlen(error_msg) + 128);
        msg = NEW_RESOURCE_ARRAY(char, len); ;
        jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
      }
689 690 691 692 693
      if (throw_exception) {
        THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
      } else {
        return NULL;
      }
D
duke 已提交
694 695 696
    }
  } else {
    // Directory
697
    new_entry = new ClassPathDirEntry(path);
698
    if (TraceClassLoading || TraceClassPaths) {
D
duke 已提交
699 700 701
      tty->print_cr("[Path %s]", path);
    }
  }
702
  return new_entry;
D
duke 已提交
703 704 705 706 707 708 709 710 711 712 713
}


// Create a class path zip entry for a given path (return NULL if not found
// or zip/JAR file cannot be opened)
ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {
  // check for a regular file
  struct stat st;
  if (os::stat(path, &st) == 0) {
    if ((st.st_mode & S_IFREG) == S_IFREG) {
      char canonical_path[JVM_MAXPATHLEN];
I
iklam 已提交
714
      if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
D
duke 已提交
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        char* error_msg = NULL;
        jzfile* zip;
        {
          // enable call to C land
          JavaThread* thread = JavaThread::current();
          ThreadToNativeFromVM ttn(thread);
          HandleMark hm(thread);
          zip = (*ZipOpen)(canonical_path, &error_msg);
        }
        if (zip != NULL && error_msg == NULL) {
          // create using canonical path
          return new ClassPathZipEntry(zip, canonical_path);
        }
      }
    }
  }
  return NULL;
}

// returns true if entry already on class path
bool ClassLoader::contains_entry(ClassPathEntry *entry) {
  ClassPathEntry* e = _first_entry;
  while (e != NULL) {
    // assume zip entries have been canonicalized
    if (strcmp(entry->name(), e->name()) == 0) {
      return true;
    }
    e = e->next();
  }
  return false;
}

void ClassLoader::add_to_list(ClassPathEntry *new_entry) {
  if (new_entry != NULL) {
    if (_last_entry == NULL) {
      _first_entry = _last_entry = new_entry;
    } else {
      _last_entry->set_next(new_entry);
      _last_entry = new_entry;
    }
  }
756
  _num_entries ++;
D
duke 已提交
757 758
}

759
// Returns true IFF the file/dir exists and the entry was successfully created.
I
iklam 已提交
760
bool ClassLoader::update_class_path_entry_list(const char *path,
761 762
                                               bool check_for_duplicates,
                                               bool throw_exception) {
D
duke 已提交
763
  struct stat st;
764
  if (os::stat(path, &st) == 0) {
D
duke 已提交
765 766
    // File or directory found
    ClassPathEntry* new_entry = NULL;
767
    Thread* THREAD = Thread::current();
768 769 770 771
    new_entry = create_class_path_entry(path, &st, LazyBootClassLoader, throw_exception, CHECK_(false));
    if (new_entry == NULL) {
      return false;
    }
D
duke 已提交
772 773 774 775 776
    // The kernel VM adds dynamically to the end of the classloader path and
    // doesn't reorder the bootclasspath which would break java.lang.Package
    // (see PackageInfo).
    // Add new entry to linked list
    if (!check_for_duplicates || !contains_entry(new_entry)) {
777
      ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry);
D
duke 已提交
778
    }
779 780 781 782 783 784 785
    return true;
  } else {
#if INCLUDE_CDS
    if (DumpSharedSpaces) {
      _shared_paths_misc_info->add_nonexist_path(path);
    }
#endif
I
iklam 已提交
786
    return false;
D
duke 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
  }
}

void ClassLoader::print_bootclasspath() {
  ClassPathEntry* e = _first_entry;
  tty->print("[bootclasspath= ");
  while (e != NULL) {
    tty->print("%s ;", e->name());
    e = e->next();
  }
  tty->print_cr("]");
}

void ClassLoader::load_zip_library() {
  assert(ZipOpen == NULL, "should not load zip library twice");
  // First make sure native library is loaded
  os::native_java_library();
  // Load zip library
  char path[JVM_MAXPATHLEN];
  char ebuf[1024];
807 808 809 810
  void* handle = NULL;
  if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
    handle = os::dll_load(path, ebuf, sizeof ebuf);
  }
D
duke 已提交
811 812 813 814
  if (handle == NULL) {
    vm_exit_during_initialization("Unable to load ZIP library", path);
  }
  // Lookup zip entry points
815 816 817 818 819 820
  ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
  ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
  FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
  ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
  ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
  GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
J
jiangli 已提交
821
  Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
D
duke 已提交
822 823

  // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
J
jiangli 已提交
824 825
  if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
      GetNextEntry == NULL || Crc32 == NULL) {
D
duke 已提交
826 827 828 829 830
    vm_exit_during_initialization("Corrupted ZIP library", path);
  }

  // Lookup canonicalize entry in libjava.dll
  void *javalib_handle = os::native_java_library();
831
  CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
D
duke 已提交
832 833 834
  // This lookup only works on 1.3. Do not check for non-null here
}

J
jiangli 已提交
835 836 837 838 839
int ClassLoader::crc32(int crc, const char* buf, int len) {
  assert(Crc32 != NULL, "ZIP_CRC32 is not found");
  return (*Crc32)(crc, (const jbyte*)buf, len);
}

D
duke 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
// PackageInfo data exists in order to support the java.lang.Package
// class.  A Package object provides information about a java package
// (version, vendor, etc.) which originates in the manifest of the jar
// file supplying the package.  For application classes, the ClassLoader
// object takes care of this.

// For system (boot) classes, the Java code in the Package class needs
// to be able to identify which source jar file contained the boot
// class, so that it can extract the manifest from it.  This table
// identifies java packages with jar files in the boot classpath.

// Because the boot classpath cannot change, the classpath index is
// sufficient to identify the source jar file or directory.  (Since
// directories have no manifests, the directory name is not required,
// but is available.)

// When using sharing -- the pathnames of entries in the boot classpath
// may not be the same at runtime as they were when the archive was
// created (NFS, Samba, etc.).  The actual files and directories named
// in the classpath must be the same files, in the same order, even
// though the exact name is not the same.

Z
zgu 已提交
862
class PackageInfo: public BasicHashtableEntry<mtClass> {
D
duke 已提交
863 864 865 866 867
public:
  const char* _pkgname;       // Package name
  int _classpath_index;       // Index of directory or JAR file loaded from

  PackageInfo* next() {
Z
zgu 已提交
868
    return (PackageInfo*)BasicHashtableEntry<mtClass>::next();
D
duke 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  }

  const char* pkgname()           { return _pkgname; }
  void set_pkgname(char* pkgname) { _pkgname = pkgname; }

  const char* filename() {
    return ClassLoader::classpath_entry(_classpath_index)->name();
  }

  void set_index(int index) {
    _classpath_index = index;
  }
};


Z
zgu 已提交
884
class PackageHashtable : public BasicHashtable<mtClass> {
D
duke 已提交
885 886 887 888 889 890 891 892 893 894
private:
  inline unsigned int compute_hash(const char *s, int n) {
    unsigned int val = 0;
    while (--n >= 0) {
      val = *s++ + 31 * val;
    }
    return val;
  }

  PackageInfo* bucket(int index) {
Z
zgu 已提交
895
    return (PackageInfo*)BasicHashtable<mtClass>::bucket(index);
D
duke 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
  }

  PackageInfo* get_entry(int index, unsigned int hash,
                         const char* pkgname, size_t n) {
    for (PackageInfo* pp = bucket(index); pp != NULL; pp = pp->next()) {
      if (pp->hash() == hash &&
          strncmp(pkgname, pp->pkgname(), n) == 0 &&
          pp->pkgname()[n] == '\0') {
        return pp;
      }
    }
    return NULL;
  }

public:
  PackageHashtable(int table_size)
Z
zgu 已提交
912
    : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo)) {}
D
duke 已提交
913

Z
zgu 已提交
914 915
  PackageHashtable(int table_size, HashtableBucket<mtClass>* t, int number_of_entries)
    : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo), t, number_of_entries) {}
D
duke 已提交
916 917 918 919 920 921 922 923 924

  PackageInfo* get_entry(const char* pkgname, int n) {
    unsigned int hash = compute_hash(pkgname, n);
    return get_entry(hash_to_index(hash), hash, pkgname, n);
  }

  PackageInfo* new_entry(char* pkgname, int n) {
    unsigned int hash = compute_hash(pkgname, n);
    PackageInfo* pp;
Z
zgu 已提交
925
    pp = (PackageInfo*)BasicHashtable<mtClass>::new_entry(hash);
D
duke 已提交
926 927 928 929 930 931
    pp->set_pkgname(pkgname);
    return pp;
  }

  void add_entry(PackageInfo* pp) {
    int index = hash_to_index(pp->hash());
Z
zgu 已提交
932
    BasicHashtable<mtClass>::add_entry(index, pp);
D
duke 已提交
933 934 935 936 937 938 939 940 941 942 943 944
  }

  void copy_pkgnames(const char** packages) {
    int n = 0;
    for (int i = 0; i < table_size(); ++i) {
      for (PackageInfo* pp = bucket(i); pp != NULL; pp = pp->next()) {
        packages[n++] = pp->pkgname();
      }
    }
    assert(n == number_of_entries(), "just checking");
  }

945
  CDS_ONLY(void copy_table(char** top, char* end, PackageHashtable* table);)
D
duke 已提交
946 947
};

948
#if INCLUDE_CDS
D
duke 已提交
949 950 951
void PackageHashtable::copy_table(char** top, char* end,
                                  PackageHashtable* table) {
  // Copy (relocate) the table to the shared space.
Z
zgu 已提交
952
  BasicHashtable<mtClass>::copy_table(top, end);
D
duke 已提交
953 954 955

  // Calculate the space needed for the package name strings.
  int i;
956 957 958
  intptr_t* tableSize = (intptr_t*)(*top);
  *top += sizeof(intptr_t);  // For table size
  char* tableStart = *top;
D
duke 已提交
959 960 961 962 963 964

  for (i = 0; i < table_size(); ++i) {
    for (PackageInfo* pp = table->bucket(i);
                      pp != NULL;
                      pp = pp->next()) {
      int n1 = (int)(strlen(pp->pkgname()) + 1);
965 966 967
      if (*top + n1 >= end) {
        report_out_of_shared_space(SharedMiscData);
      }
D
duke 已提交
968 969 970 971 972
      pp->set_pkgname((char*)memcpy(*top, pp->pkgname(), n1));
      *top += n1;
    }
  }
  *top = (char*)align_size_up((intptr_t)*top, sizeof(HeapWord));
973 974 975 976 977 978 979
  if (*top >= end) {
    report_out_of_shared_space(SharedMiscData);
  }

  // Write table size
  intptr_t len = *top - (char*)tableStart;
  *tableSize = len;
D
duke 已提交
980 981 982 983 984 985 986 987 988 989
}


void ClassLoader::copy_package_info_buckets(char** top, char* end) {
  _package_hash_table->copy_buckets(top, end);
}

void ClassLoader::copy_package_info_table(char** top, char* end) {
  _package_hash_table->copy_table(top, end, _package_hash_table);
}
990
#endif
D
duke 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

PackageInfo* ClassLoader::lookup_package(const char *pkgname) {
  const char *cp = strrchr(pkgname, '/');
  if (cp != NULL) {
    // Package prefix found
    int n = cp - pkgname + 1;
    return _package_hash_table->get_entry(pkgname, n);
  }
  return NULL;
}


bool ClassLoader::add_package(const char *pkgname, int classpath_index, TRAPS) {
  assert(pkgname != NULL, "just checking");
  // Bootstrap loader no longer holds system loader lock obj serializing
  // load_instance_class and thereby add_package
  {
    MutexLocker ml(PackageTable_lock, THREAD);
    // First check for previously loaded entry
    PackageInfo* pp = lookup_package(pkgname);
    if (pp != NULL) {
      // Existing entry found, check source of package
      pp->set_index(classpath_index);
      return true;
    }

    const char *cp = strrchr(pkgname, '/');
    if (cp != NULL) {
      // Package prefix found
      int n = cp - pkgname + 1;

Z
zgu 已提交
1022
      char* new_pkgname = NEW_C_HEAP_ARRAY(char, n + 1, mtClass);
D
duke 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      if (new_pkgname == NULL) {
        return false;
      }

      memcpy(new_pkgname, pkgname, n);
      new_pkgname[n] = '\0';
      pp = _package_hash_table->new_entry(new_pkgname, n);
      pp->set_index(classpath_index);

      // Insert into hash table
      _package_hash_table->add_entry(pp);
    }
    return true;
  }
}


oop ClassLoader::get_system_package(const char* name, TRAPS) {
  PackageInfo* pp;
  {
    MutexLocker ml(PackageTable_lock, THREAD);
    pp = lookup_package(name);
  }
  if (pp == NULL) {
    return NULL;
  } else {
    Handle p = java_lang_String::create_from_str(pp->filename(), THREAD);
    return p();
  }
}


objArrayOop ClassLoader::get_system_packages(TRAPS) {
  ResourceMark rm(THREAD);
  int nof_entries;
  const char** packages;
  {
    MutexLocker ml(PackageTable_lock, THREAD);
    // Allocate resource char* array containing package names
    nof_entries = _package_hash_table->number_of_entries();
    if ((packages = NEW_RESOURCE_ARRAY(const char*, nof_entries)) == NULL) {
      return NULL;
    }
    _package_hash_table->copy_pkgnames(packages);
  }
  // Allocate objArray and fill with java.lang.String
1069
  objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
D
duke 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
                                           nof_entries, CHECK_0);
  objArrayHandle result(THREAD, r);
  for (int i = 0; i < nof_entries; i++) {
    Handle str = java_lang_String::create_from_str(packages[i], CHECK_0);
    result->obj_at_put(i, str());
  }

  return result();
}


1081
instanceKlassHandle ClassLoader::load_classfile(Symbol* h_name, TRAPS) {
D
duke 已提交
1082
  ResourceMark rm(THREAD);
1083 1084
  const char* class_name = h_name->as_C_string();
  EventMark m("loading class %s", class_name);
D
duke 已提交
1085 1086 1087 1088 1089 1090 1091
  ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);

  stringStream st;
  // st.print() uses too much stack space while handling a StackOverflowError
  // st.print("%s.class", h_name->as_utf8());
  st.print_raw(h_name->as_utf8());
  st.print_raw(".class");
1092 1093
  const char* file_name = st.as_string();
  ClassLoaderExt::Context context(class_name, file_name, THREAD);
D
duke 已提交
1094 1095 1096 1097

  // Lookup stream for parsing .class file
  ClassFileStream* stream = NULL;
  int classpath_index = 0;
1098 1099
  ClassPathEntry* e = NULL;
  instanceKlassHandle h;
D
duke 已提交
1100
  {
1101 1102 1103
    PerfClassTraceTime vmtimer(perf_sys_class_lookup_time(),
                               ((JavaThread*) THREAD)->get_thread_stat()->perf_timers_addr(),
                               PerfClassTraceTime::CLASS_LOAD);
1104
    e = _first_entry;
D
duke 已提交
1105
    while (e != NULL) {
1106 1107 1108 1109
      stream = e->open_stream(file_name, CHECK_NULL);
      if (!context.check(stream, classpath_index)) {
        return h; // NULL
      }
D
duke 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
      if (stream != NULL) {
        break;
      }
      e = e->next();
      ++classpath_index;
    }
  }

  if (stream != NULL) {
    // class file found, parse it
    ClassFileParser parser(stream);
1121
    ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
D
duke 已提交
1122
    Handle protection_domain;
1123
    TempNewSymbol parsed_name = NULL;
D
duke 已提交
1124
    instanceKlassHandle result = parser.parseClassFile(h_name,
1125
                                                       loader_data,
D
duke 已提交
1126 1127
                                                       protection_domain,
                                                       parsed_name,
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
                                                       context.should_verify(classpath_index),
                                                       THREAD);
    if (HAS_PENDING_EXCEPTION) {
      ResourceMark rm;
      if (DumpSharedSpaces) {
        tty->print_cr("Preload Error: Failed to load %s", class_name);
      }
      return h;
    }
    h = context.record_result(classpath_index, e, result, THREAD);
  } else {
    if (DumpSharedSpaces) {
1140
      tty->print_cr("Preload Warning: Cannot find %s", class_name);
D
duke 已提交
1141 1142 1143 1144 1145 1146 1147
    }
  }

  return h;
}


Z
zgu 已提交
1148
void ClassLoader::create_package_info_table(HashtableBucket<mtClass> *t, int length,
D
duke 已提交
1149 1150
                                            int number_of_entries) {
  assert(_package_hash_table == NULL, "One package info table allowed.");
Z
zgu 已提交
1151
  assert(length == package_hash_table_size * sizeof(HashtableBucket<mtClass>),
D
duke 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
         "bad shared package info size.");
  _package_hash_table = new PackageHashtable(package_hash_table_size, t,
                                             number_of_entries);
}


void ClassLoader::create_package_info_table() {
    assert(_package_hash_table == NULL, "shouldn't have one yet");
    _package_hash_table = new PackageHashtable(package_hash_table_size);
}


// Initialize the class loader's access to methods in libzip.  Parse and
// process the boot classpath into a list ClassPathEntry objects.  Once
// this list has been created, it must not change order (see class PackageInfo)
// it can be appended to and is by jvmti and the kernel vm.

void ClassLoader::initialize() {
  assert(_package_hash_table == NULL, "should have been initialized by now.");
  EXCEPTION_MARK;

  if (UsePerfData) {
    // jvmstat performance counters
    NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
    NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1177
    NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
D
duke 已提交
1178
    NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1179
    NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
D
duke 已提交
1180
    NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1181
    NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
D
duke 已提交
1182 1183
    NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
    NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");

    NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
    NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
    NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
    NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
    NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
    NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
    NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
    NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
    NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
    NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
    NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
    NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
    NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");

D
duke 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

    // The following performance counters are added for measuring the impact
    // of the bug fix of 6365597. They are mainly focused on finding out
    // the behavior of system & user-defined classloader lock, whether
    // ClassLoader.loadClass/findClass is being called synchronized or not.
    // Also two additional counters are created to see whether 'UnsyncloadClass'
    // flag is being set or not and how many times load_instance_class call
    // fails with linkageError etc.
    NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
                        "systemLoaderLockContentionRate");
    NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
                        "nonSystemLoaderLockContentionRate");
    NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
                        "jvmFindLoadedClassNoLockCalls");
    NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
                        "jvmDefineClassNoLockCalls");

    NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
                        "jniDefineClassNoLockCalls");

    NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
                        "unsafeDefineClassCalls");

    NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
    NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
                        "loadInstanceClassFailRate");

    // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
    if (UnsyncloadClass) {
      _isUnsyncloadClass->inc();
    }
  }

  // lookup zip library entry points
  load_zip_library();
1235
#if INCLUDE_CDS
D
duke 已提交
1236
  // initialize search path
1237 1238 1239 1240
  if (DumpSharedSpaces) {
    _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();
  }
#endif
D
duke 已提交
1241 1242 1243
  setup_bootstrap_search_path();
  if (LazyBootClassLoader) {
    // set up meta index which makes boot classpath initialization lazier
1244
    setup_bootstrap_meta_index();
D
duke 已提交
1245 1246 1247
  }
}

1248 1249 1250 1251 1252 1253 1254 1255
#if INCLUDE_CDS
void ClassLoader::initialize_shared_path() {
  if (DumpSharedSpaces) {
    ClassLoaderExt::setup_search_paths();
    _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()
  }
}
#endif
D
duke 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

jlong ClassLoader::classloader_time_ms() {
  return UsePerfData ?
    Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
}

jlong ClassLoader::class_init_count() {
  return UsePerfData ? _perf_classes_inited->get_value() : -1;
}

jlong ClassLoader::class_init_time_ms() {
  return UsePerfData ?
    Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
}

jlong ClassLoader::class_verify_time_ms() {
  return UsePerfData ?
    Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
}

jlong ClassLoader::class_link_count() {
  return UsePerfData ? _perf_classes_linked->get_value() : -1;
}

jlong ClassLoader::class_link_time_ms() {
  return UsePerfData ?
    Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
}

int ClassLoader::compute_Object_vtable() {
  // hardwired for JDK1.2 -- would need to duplicate class file parsing
  // code to determine actual value from file
  // Would be value '11' if finals were in vtable
  int JDK_1_2_Object_vtable_size = 5;
  return JDK_1_2_Object_vtable_size * vtableEntry::size();
}


void classLoader_init() {
  ClassLoader::initialize();
}


I
iklam 已提交
1299
bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {
D
duke 已提交
1300 1301
  assert(orig != NULL && out != NULL && len > 0, "bad arguments");
  if (CanonicalizeEntry != NULL) {
I
iklam 已提交
1302 1303 1304 1305 1306 1307 1308 1309
    JavaThread* THREAD = JavaThread::current();
    JNIEnv* env = THREAD->jni_environment();
    ResourceMark rm(THREAD);

    // os::native_path writes into orig_copy
    char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);
    strcpy(orig_copy, orig);
    if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {
D
duke 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
      return false;
    }
  } else {
    // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
    strncpy(out, orig, len);
    out[len - 1] = '\0';
  }
  return true;
}

#ifndef PRODUCT

void ClassLoader::verify() {
  _package_hash_table->verify();
}


// CompileTheWorld
//
// Iterates over all class path entries and forces compilation of all methods
// in all classes found. Currently, only zip/jar archives are searched.
//
// The classes are loaded by the Java level bootstrap class loader, and the
// initializer is called. If DelayCompilationDuringStartup is true (default),
// the interpreter will run the initialization code. Note that forcing
// initialization in this way could potentially lead to initialization order
// problems, in which case we could just force the initialization bit to be set.


// We need to iterate over the contents of a zip/jar file, so we replicate the
// jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
// since jzfile already has a void* definition.
//
// Note that this is only used in debug mode.
//
// HotSpot integration note:
// Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build


// JDK 1.3 version
typedef struct real_jzentry13 {         /* Zip file entry */
    char *name;                 /* entry name */
    jint time;                  /* modification time */
    jint size;                  /* size of uncompressed data */
    jint csize;                 /* size of compressed data (zero if uncompressed) */
    jint crc;                   /* crc of uncompressed data */
    char *comment;              /* optional zip file comment */
    jbyte *extra;               /* optional extra data */
    jint pos;                   /* position of LOC header (if negative) or data */
} real_jzentry13;

typedef struct real_jzfile13 {  /* Zip file */
    char *name;                 /* zip file name */
    jint refs;                  /* number of active references */
    jint fd;                    /* open file descriptor */
    void *lock;                 /* read lock */
    char *comment;              /* zip file comment */
    char *msg;                  /* zip error message */
    void *entries;              /* array of hash cells */
    jint total;                 /* total number of entries */
    unsigned short *table;      /* Hash chain heads: indexes into entries */
    jint tablelen;              /* number of hash eads */
    real_jzfile13 *next;        /* next zip file in search list */
    jzentry *cache;             /* we cache the most recently freed jzentry */
    /* Information on metadata names in META-INF directory */
    char **metanames;           /* array of meta names (may have null names) */
    jint metacount;             /* number of slots in metanames array */
    /* If there are any per-entry comments, they are in the comments array */
    char **comments;
} real_jzfile13;

// JDK 1.2 version
typedef struct real_jzentry12 {  /* Zip file entry */
    char *name;                  /* entry name */
    jint time;                   /* modification time */
    jint size;                   /* size of uncompressed data */
    jint csize;                  /* size of compressed data (zero if uncompressed) */
    jint crc;                    /* crc of uncompressed data */
    char *comment;               /* optional zip file comment */
    jbyte *extra;                /* optional extra data */
    jint pos;                    /* position of LOC header (if negative) or data */
    struct real_jzentry12 *next; /* next entry in hash table */
} real_jzentry12;

typedef struct real_jzfile12 {  /* Zip file */
    char *name;                 /* zip file name */
    jint refs;                  /* number of active references */
    jint fd;                    /* open file descriptor */
    void *lock;                 /* read lock */
    char *comment;              /* zip file comment */
    char *msg;                  /* zip error message */
    real_jzentry12 *entries;    /* array of zip entries */
    jint total;                 /* total number of entries */
    real_jzentry12 **table;     /* hash table of entries */
    jint tablelen;              /* number of buckets */
    jzfile *next;               /* next zip file in search list */
} real_jzfile12;


void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
  // For now we only compile all methods in all classes in zip/jar files
  tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
  tty->cr();
}


bool ClassPathDirEntry::is_rt_jar() {
  return false;
}

void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
  if (JDK_Version::is_jdk12x_version()) {
    compile_the_world12(loader, THREAD);
  } else {
    compile_the_world13(loader, THREAD);
  }
  if (HAS_PENDING_EXCEPTION) {
    if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
      CLEAR_PENDING_EXCEPTION;
      tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1430
      tty->print_cr("Increase class metadata storage if a limit was set");
D
duke 已提交
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    } else {
      tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
    }
  }
}

// Version that works for JDK 1.3.x
void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) {
  real_jzfile13* zip = (real_jzfile13*) _zip;
  tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
  tty->cr();
  // Iterate over all entries in zip file
  for (int n = 0; ; n++) {
    real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n));
    if (ze == NULL) break;
    ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
  }
}


// Version that works for JDK 1.2.x
void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) {
  real_jzfile12* zip = (real_jzfile12*) _zip;
  tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
  tty->cr();
  // Iterate over all entries in zip file
  for (int n = 0; ; n++) {
    real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n));
    if (ze == NULL) break;
    ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
  }
}

bool ClassPathZipEntry::is_rt_jar() {
  if (JDK_Version::is_jdk12x_version()) {
    return is_rt_jar12();
  } else {
    return is_rt_jar13();
  }
}

// JDK 1.3 version
bool ClassPathZipEntry::is_rt_jar13() {
  real_jzfile13* zip = (real_jzfile13*) _zip;
  int len = (int)strlen(zip->name);
  // Check whether zip name ends in "rt.jar"
  // This will match other archives named rt.jar as well, but this is
  // only used for debugging.
  return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
}

// JDK 1.2 version
bool ClassPathZipEntry::is_rt_jar12() {
  real_jzfile12* zip = (real_jzfile12*) _zip;
  int len = (int)strlen(zip->name);
  // Check whether zip name ends in "rt.jar"
  // This will match other archives named rt.jar as well, but this is
  // only used for debugging.
  return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
}

void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {
1493 1494 1495 1496
  ClassPathEntry* cpe = resolve_entry(THREAD);
  if (cpe != NULL) {
    cpe->compile_the_world(loader, CHECK);
  }
D
duke 已提交
1497 1498 1499
}

bool LazyClassPathEntry::is_rt_jar() {
1500 1501 1502
  Thread* THREAD = Thread::current();
  ClassPathEntry* cpe = resolve_entry(THREAD);
  return (cpe != NULL) ? cpe->is_jar_file() : false;
D
duke 已提交
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
}

void ClassLoader::compile_the_world() {
  EXCEPTION_MARK;
  HandleMark hm(THREAD);
  ResourceMark rm(THREAD);
  // Make sure we don't run with background compilation
  BackgroundCompilation = false;
  // Find bootstrap loader
  Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
  // Iterate over all bootstrap class path entries
  ClassPathEntry* e = _first_entry;
1515
  jlong start = os::javaTimeMillis();
D
duke 已提交
1516 1517 1518 1519 1520 1521
  while (e != NULL) {
    // We stop at rt.jar, unless it is the first bootstrap path entry
    if (e->is_rt_jar() && e != _first_entry) break;
    e->compile_the_world(system_class_loader, CATCH);
    e = e->next();
  }
1522
  jlong end = os::javaTimeMillis();
1523
  tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1524
                _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
D
duke 已提交
1525 1526 1527 1528 1529 1530 1531 1532
  {
    // Print statistics as if before normal exit:
    extern void print_statistics();
    print_statistics();
  }
  vm_exit(0);
}

1533 1534
int ClassLoader::_compile_the_world_class_counter = 0;
int ClassLoader::_compile_the_world_method_counter = 0;
1535
static int _codecache_sweep_counter = 0;
D
duke 已提交
1536

1537 1538 1539 1540 1541 1542 1543 1544 1545
// Filter out all exceptions except OOMs
static void clear_pending_exception_if_not_oom(TRAPS) {
  if (HAS_PENDING_EXCEPTION &&
      !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
    CLEAR_PENDING_EXCEPTION;
  }
  // The CHECK at the caller will propagate the exception out
}

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
/**
 * Returns if the given method should be compiled when doing compile-the-world.
 *
 * TODO:  This should be a private method in a CompileTheWorld class.
 */
static bool can_be_compiled(methodHandle m, int comp_level) {
  assert(CompileTheWorld, "must be");

  // It's not valid to compile a native wrapper for MethodHandle methods
  // that take a MemberName appendix since the bytecode signature is not
  // correct.
  vmIntrinsics::ID iid = m->intrinsic_id();
  if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
    return false;
  }

  return CompilationPolicy::can_be_compiled(m, comp_level);
}

D
duke 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
  int len = (int)strlen(name);
  if (len > 6 && strcmp(".class", name + len - 6) == 0) {
    // We have a .class file
    char buffer[2048];
    strncpy(buffer, name, len - 6);
    buffer[len-6] = 0;
    // If the file has a period after removing .class, it's not really a
    // valid class file.  The class loader will check everything else.
    if (strchr(buffer, '.') == NULL) {
1575 1576
      _compile_the_world_class_counter++;
      if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
N
never 已提交
1577 1578

      // Construct name without extension
1579
      TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
N
never 已提交
1580
      // Use loader to load and initialize class
1581
      Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
N
never 已提交
1582 1583 1584 1585 1586
      instanceKlassHandle k (THREAD, ik);
      if (k.not_null() && !HAS_PENDING_EXCEPTION) {
        k->initialize(THREAD);
      }
      bool exception_occurred = HAS_PENDING_EXCEPTION;
1587
      clear_pending_exception_if_not_oom(CHECK);
N
never 已提交
1588
      if (CompileTheWorldPreloadClasses && k.not_null()) {
1589
        ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);
N
never 已提交
1590 1591
        if (HAS_PENDING_EXCEPTION) {
          // If something went wrong in preloading we just ignore it
1592
          clear_pending_exception_if_not_oom(CHECK);
1593
          tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
D
duke 已提交
1594
        }
N
never 已提交
1595 1596
      }

1597
      if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
1598
        if (k.is_null() || exception_occurred) {
D
duke 已提交
1599
          // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
1600
          tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
D
duke 已提交
1601
        } else {
1602
          tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
D
duke 已提交
1603 1604
          // Preload all classes to get around uncommon traps
          // Iterate over all methods in class
1605
          int comp_level = CompilationPolicy::policy()->initial_compile_level();
D
duke 已提交
1606
          for (int n = 0; n < k->methods()->length(); n++) {
1607
            methodHandle m (THREAD, k->methods()->at(n));
1608
            if (can_be_compiled(m, comp_level)) {
1609 1610 1611 1612 1613 1614
              if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
                // Give sweeper a chance to keep up with CTW
                VM_ForceSafepoint op;
                VMThread::execute(&op);
                _codecache_sweep_counter = 0;
              }
D
duke 已提交
1615
              // Force compilation
1616
              CompileBroker::compile_method(m, InvocationEntryBci, comp_level,
D
duke 已提交
1617 1618
                                            methodHandle(), 0, "CTW", THREAD);
              if (HAS_PENDING_EXCEPTION) {
1619
                clear_pending_exception_if_not_oom(CHECK);
1620
                tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1621 1622
              } else {
                _compile_the_world_method_counter++;
D
duke 已提交
1623
              }
1624
              if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
N
never 已提交
1625 1626
                // Clobber the first compile and force second tier compilation
                nmethod* nm = m->code();
1627
                if (nm != NULL && !m->is_method_handle_intrinsic()) {
N
never 已提交
1628 1629 1630
                  // Throw out the code so that the code cache doesn't fill up
                  nm->make_not_entrant();
                }
I
iveresov 已提交
1631
                CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
N
never 已提交
1632 1633
                                              methodHandle(), 0, "CTW", THREAD);
                if (HAS_PENDING_EXCEPTION) {
1634
                  clear_pending_exception_if_not_oom(CHECK);
1635
                  tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1636 1637
                } else {
                  _compile_the_world_method_counter++;
N
never 已提交
1638
                }
D
duke 已提交
1639
              }
1640 1641
            } else {
              tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
D
duke 已提交
1642
            }
N
never 已提交
1643 1644

            nmethod* nm = m->code();
1645
            if (nm != NULL && !m->is_method_handle_intrinsic()) {
N
never 已提交
1646 1647
              // Throw out the code so that the code cache doesn't fill up
              nm->make_not_entrant();
D
duke 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656
            }
          }
        }
      }
    }
  }
}

#endif //PRODUCT
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714

// Please keep following two functions at end of this file. With them placed at top or in middle of the file,
// they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
void PerfClassTraceTime::initialize() {
  if (!UsePerfData) return;

  if (_eventp != NULL) {
    // increment the event counter
    _eventp->inc();
  }

  // stop the current active thread-local timer to measure inclusive time
  _prev_active_event = -1;
  for (int i=0; i < EVENT_TYPE_COUNT; i++) {
     if (_timers[i].is_active()) {
       assert(_prev_active_event == -1, "should have only one active timer");
       _prev_active_event = i;
       _timers[i].stop();
     }
  }

  if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
    // start the inclusive timer if not recursively called
    _t.start();
  }

  // start thread-local timer of the given event type
   if (!_timers[_event_type].is_active()) {
    _timers[_event_type].start();
  }
}

PerfClassTraceTime::~PerfClassTraceTime() {
  if (!UsePerfData) return;

  // stop the thread-local timer as the event completes
  // and resume the thread-local timer of the event next on the stack
  _timers[_event_type].stop();
  jlong selftime = _timers[_event_type].ticks();

  if (_prev_active_event >= 0) {
    _timers[_prev_active_event].start();
  }

  if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;

  // increment the counters only on the leaf call
  _t.stop();
  _timep->inc(_t.ticks());
  if (_selftimep != NULL) {
    _selftimep->inc(selftime);
  }
  // add all class loading related event selftime to the accumulated time counter
  ClassLoader::perf_accumulated_time()->inc(selftime);

  // reset the timer
  _timers[_event_type].reset();
}