1 /* 2 * Copyright (c) 1999, 2013, 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 // no precompiled headers 26 #include "classfile/classLoader.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "classfile/vmSymbols.hpp" 29 #include "code/icBuffer.hpp" 30 #include "code/vtableStubs.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "interpreter/interpreter.hpp" 33 #include "jvm_bsd.h" 34 #include "memory/allocation.inline.hpp" 35 #include "memory/filemap.hpp" 36 #include "mutex_bsd.inline.hpp" 37 #include "oops/oop.inline.hpp" 38 #include "os_share_bsd.hpp" 39 #include "prims/jniFastGetField.hpp" 40 #include "prims/jvm.h" 41 #include "prims/jvm_misc.hpp" 42 #include "runtime/arguments.hpp" 43 #include "runtime/extendedPC.hpp" 44 #include "runtime/globals.hpp" 45 #include "runtime/interfaceSupport.hpp" 46 #include "runtime/java.hpp" 47 #include "runtime/javaCalls.hpp" 48 #include "runtime/mutexLocker.hpp" 49 #include "runtime/objectMonitor.hpp" 50 #include "runtime/osThread.hpp" 51 #include "runtime/perfMemory.hpp" 52 #include "runtime/sharedRuntime.hpp" 53 #include "runtime/statSampler.hpp" 54 #include "runtime/stubRoutines.hpp" 55 #include "runtime/threadCritical.hpp" 56 #include "runtime/timer.hpp" 57 #include "services/attachListener.hpp" 58 #include "services/memTracker.hpp" 59 #include "services/runtimeService.hpp" 60 #include "thread_bsd.inline.hpp" 61 #include "utilities/decoder.hpp" 62 #include "utilities/defaultStream.hpp" 63 #include "utilities/events.hpp" 64 #include "utilities/growableArray.hpp" 65 #include "utilities/vmError.hpp" 66 #ifdef TARGET_ARCH_x86 67 # include "assembler_x86.inline.hpp" 68 # include "nativeInst_x86.hpp" 69 #endif 70 #ifdef TARGET_ARCH_sparc 71 # include "assembler_sparc.inline.hpp" 72 # include "nativeInst_sparc.hpp" 73 #endif 74 #ifdef TARGET_ARCH_zero 75 # include "assembler_zero.inline.hpp" 76 # include "nativeInst_zero.hpp" 77 #endif 78 #ifdef TARGET_ARCH_arm 79 # include "assembler_arm.inline.hpp" 80 # include "nativeInst_arm.hpp" 81 #endif 82 #ifdef TARGET_ARCH_ppc 83 # include "assembler_ppc.inline.hpp" 84 # include "nativeInst_ppc.hpp" 85 #endif 86 87 // put OS-includes here 88 # include <sys/types.h> 89 # include <sys/mman.h> 90 # include <sys/stat.h> 91 # include <sys/select.h> 92 # include <pthread.h> 93 # include <signal.h> 94 # include <errno.h> 95 # include <dlfcn.h> 96 # include <stdio.h> 97 # include <unistd.h> 98 # include <sys/resource.h> 99 # include <pthread.h> 100 # include <sys/stat.h> 101 # include <sys/time.h> 102 # include <sys/times.h> 103 # include <sys/utsname.h> 104 # include <sys/socket.h> 105 # include <sys/wait.h> 106 # include <time.h> 107 # include <pwd.h> 108 # include <poll.h> 109 # include <semaphore.h> 110 # include <fcntl.h> 111 # include <string.h> 112 #ifdef _ALLBSD_SOURCE 113 # include <sys/param.h> 114 # include <sys/sysctl.h> 115 #else 116 # include <syscall.h> 117 # include <sys/sysinfo.h> 118 # include <gnu/libc-version.h> 119 #endif 120 # include <sys/ipc.h> 121 # include <sys/shm.h> 122 #ifndef __APPLE__ 123 # include <link.h> 124 #endif 125 # include <stdint.h> 126 # include <inttypes.h> 127 # include <sys/ioctl.h> 128 129 #if defined(__FreeBSD__) || defined(__NetBSD__) 130 # include <elf.h> 131 #endif 132 133 #ifdef __APPLE__ 134 # include <mach/mach.h> // semaphore_* API 135 # include <mach-o/dyld.h> 136 # include <sys/proc_info.h> 137 # include <objc/objc-auto.h> 138 #endif 139 140 #ifndef MAP_ANONYMOUS 141 #define MAP_ANONYMOUS MAP_ANON 142 #endif 143 144 #define MAX_PATH (2 * K) 145 146 // for timer info max values which include all bits 147 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 148 149 #define LARGEPAGES_BIT (1 << 6) 150 //////////////////////////////////////////////////////////////////////////////// 151 // global variables 152 julong os::Bsd::_physical_memory = 0; 153 154 #ifndef _ALLBSD_SOURCE 155 address os::Bsd::_initial_thread_stack_bottom = NULL; 156 uintptr_t os::Bsd::_initial_thread_stack_size = 0; 157 #endif 158 159 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL; 160 #ifndef _ALLBSD_SOURCE 161 int (*os::Bsd::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; 162 Mutex* os::Bsd::_createThread_lock = NULL; 163 #endif 164 pthread_t os::Bsd::_main_thread; 165 int os::Bsd::_page_size = -1; 166 #ifndef _ALLBSD_SOURCE 167 bool os::Bsd::_is_floating_stack = false; 168 bool os::Bsd::_is_NPTL = false; 169 bool os::Bsd::_supports_fast_thread_cpu_time = false; 170 const char * os::Bsd::_glibc_version = NULL; 171 const char * os::Bsd::_libpthread_version = NULL; 172 #endif 173 174 static jlong initial_time_count=0; 175 176 static int clock_tics_per_sec = 100; 177 178 // For diagnostics to print a message once. see run_periodic_checks 179 static sigset_t check_signal_done; 180 static bool check_signals = true;; 181 182 static pid_t _initial_pid = 0; 183 184 /* Signal number used to suspend/resume a thread */ 185 186 /* do not use any signal number less than SIGSEGV, see 4355769 */ 187 static int SR_signum = SIGUSR2; 188 sigset_t SR_sigset; 189 190 191 //////////////////////////////////////////////////////////////////////////////// 192 // utility functions 193 194 static int SR_initialize(); 195 static int SR_finalize(); 196 197 julong os::available_memory() { 198 return Bsd::available_memory(); 199 } 200 201 julong os::Bsd::available_memory() { 202 #ifdef _ALLBSD_SOURCE 203 // XXXBSD: this is just a stopgap implementation 204 return physical_memory() >> 2; 205 #else 206 // values in struct sysinfo are "unsigned long" 207 struct sysinfo si; 208 sysinfo(&si); 209 210 return (julong)si.freeram * si.mem_unit; 211 #endif 212 } 213 214 julong os::physical_memory() { 215 return Bsd::physical_memory(); 216 } 217 218 julong os::allocatable_physical_memory(julong size) { 219 #ifdef _LP64 220 return size; 221 #else 222 julong result = MIN2(size, (julong)3800*M); 223 if (!is_allocatable(result)) { 224 // See comments under solaris for alignment considerations 225 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); 226 result = MIN2(size, reasonable_size); 227 } 228 return result; 229 #endif // _LP64 230 } 231 232 //////////////////////////////////////////////////////////////////////////////// 233 // environment support 234 235 bool os::getenv(const char* name, char* buf, int len) { 236 const char* val = ::getenv(name); 237 if (val != NULL && strlen(val) < (size_t)len) { 238 strcpy(buf, val); 239 return true; 240 } 241 if (len > 0) buf[0] = 0; // return a null string 242 return false; 243 } 244 245 246 // Return true if user is running as root. 247 248 bool os::have_special_privileges() { 249 static bool init = false; 250 static bool privileges = false; 251 if (!init) { 252 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 253 init = true; 254 } 255 return privileges; 256 } 257 258 259 #ifndef _ALLBSD_SOURCE 260 #ifndef SYS_gettid 261 // i386: 224, ia64: 1105, amd64: 186, sparc 143 262 #ifdef __ia64__ 263 #define SYS_gettid 1105 264 #elif __i386__ 265 #define SYS_gettid 224 266 #elif __amd64__ 267 #define SYS_gettid 186 268 #elif __sparc__ 269 #define SYS_gettid 143 270 #else 271 #error define gettid for the arch 272 #endif 273 #endif 274 #endif 275 276 // Cpu architecture string 277 #if defined(ZERO) 278 static char cpu_arch[] = ZERO_LIBARCH; 279 #elif defined(IA64) 280 static char cpu_arch[] = "ia64"; 281 #elif defined(IA32) 282 static char cpu_arch[] = "i386"; 283 #elif defined(AMD64) 284 static char cpu_arch[] = "amd64"; 285 #elif defined(ARM) 286 static char cpu_arch[] = "arm"; 287 #elif defined(PPC) 288 static char cpu_arch[] = "ppc"; 289 #elif defined(SPARC) 290 # ifdef _LP64 291 static char cpu_arch[] = "sparcv9"; 292 # else 293 static char cpu_arch[] = "sparc"; 294 # endif 295 #else 296 #error Add appropriate cpu_arch setting 297 #endif 298 299 // Compiler variant 300 #ifdef COMPILER2 301 #define COMPILER_VARIANT "server" 302 #else 303 #define COMPILER_VARIANT "client" 304 #endif 305 306 #ifndef _ALLBSD_SOURCE 307 // pid_t gettid() 308 // 309 // Returns the kernel thread id of the currently running thread. Kernel 310 // thread id is used to access /proc. 311 // 312 // (Note that getpid() on BsdThreads returns kernel thread id too; but 313 // on NPTL, it returns the same pid for all threads, as required by POSIX.) 314 // 315 pid_t os::Bsd::gettid() { 316 int rslt = syscall(SYS_gettid); 317 if (rslt == -1) { 318 // old kernel, no NPTL support 319 return getpid(); 320 } else { 321 return (pid_t)rslt; 322 } 323 } 324 325 // Most versions of bsd have a bug where the number of processors are 326 // determined by looking at the /proc file system. In a chroot environment, 327 // the system call returns 1. This causes the VM to act as if it is 328 // a single processor and elide locking (see is_MP() call). 329 static bool unsafe_chroot_detected = false; 330 static const char *unstable_chroot_error = "/proc file system not found.\n" 331 "Java may be unstable running multithreaded in a chroot " 332 "environment on Bsd when /proc filesystem is not mounted."; 333 #endif 334 335 #ifdef _ALLBSD_SOURCE 336 void os::Bsd::initialize_system_info() { 337 int mib[2]; 338 size_t len; 339 int cpu_val; 340 julong mem_val; 341 342 /* get processors count via hw.ncpus sysctl */ 343 mib[0] = CTL_HW; 344 mib[1] = HW_NCPU; 345 len = sizeof(cpu_val); 346 if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) { 347 assert(len == sizeof(cpu_val), "unexpected data size"); 348 set_processor_count(cpu_val); 349 } 350 else { 351 set_processor_count(1); // fallback 352 } 353 354 /* get physical memory via hw.memsize sysctl (hw.memsize is used 355 * since it returns a 64 bit value) 356 */ 357 mib[0] = CTL_HW; 358 mib[1] = HW_MEMSIZE; 359 len = sizeof(mem_val); 360 if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) { 361 assert(len == sizeof(mem_val), "unexpected data size"); 362 _physical_memory = mem_val; 363 } else { 364 _physical_memory = 256*1024*1024; // fallback (XXXBSD?) 365 } 366 367 #ifdef __OpenBSD__ 368 { 369 // limit _physical_memory memory view on OpenBSD since 370 // datasize rlimit restricts us anyway. 371 struct rlimit limits; 372 getrlimit(RLIMIT_DATA, &limits); 373 _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur); 374 } 375 #endif 376 } 377 #else 378 void os::Bsd::initialize_system_info() { 379 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); 380 if (processor_count() == 1) { 381 pid_t pid = os::Bsd::gettid(); 382 char fname[32]; 383 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); 384 FILE *fp = fopen(fname, "r"); 385 if (fp == NULL) { 386 unsafe_chroot_detected = true; 387 } else { 388 fclose(fp); 389 } 390 } 391 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); 392 assert(processor_count() > 0, "bsd error"); 393 } 394 #endif 395 396 #ifdef __APPLE__ 397 static const char *get_home() { 398 const char *home_dir = ::getenv("HOME"); 399 if ((home_dir == NULL) || (*home_dir == '\0')) { 400 struct passwd *passwd_info = getpwuid(geteuid()); 401 if (passwd_info != NULL) { 402 home_dir = passwd_info->pw_dir; 403 } 404 } 405 406 return home_dir; 407 } 408 #endif 409 410 void os::init_system_properties_values() { 411 // char arch[12]; 412 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch)); 413 414 // The next steps are taken in the product version: 415 // 416 // Obtain the JAVA_HOME value from the location of libjvm[_g].so. 417 // This library should be located at: 418 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so. 419 // 420 // If "/jre/lib/" appears at the right place in the path, then we 421 // assume libjvm[_g].so is installed in a JDK and we use this path. 422 // 423 // Otherwise exit with message: "Could not create the Java virtual machine." 424 // 425 // The following extra steps are taken in the debugging version: 426 // 427 // If "/jre/lib/" does NOT appear at the right place in the path 428 // instead of exit check for $JAVA_HOME environment variable. 429 // 430 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 431 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so 432 // it looks like libjvm[_g].so is installed there 433 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so. 434 // 435 // Otherwise exit. 436 // 437 // Important note: if the location of libjvm.so changes this 438 // code needs to be changed accordingly. 439 440 // The next few definitions allow the code to be verbatim: 441 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal) 442 #define getenv(n) ::getenv(n) 443 444 /* 445 * See ld(1): 446 * The linker uses the following search paths to locate required 447 * shared libraries: 448 * 1: ... 449 * ... 450 * 7: The default directories, normally /lib and /usr/lib. 451 */ 452 #ifndef DEFAULT_LIBPATH 453 #define DEFAULT_LIBPATH "/lib:/usr/lib" 454 #endif 455 456 #define EXTENSIONS_DIR "/lib/ext" 457 #define ENDORSED_DIR "/lib/endorsed" 458 #define REG_DIR "/usr/java/packages" 459 460 #ifdef __APPLE__ 461 #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions" 462 #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java" 463 const char *user_home_dir = get_home(); 464 // the null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir 465 int system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) + 466 sizeof(SYS_EXTENSIONS_DIRS); 467 #endif 468 469 { 470 /* sysclasspath, java_home, dll_dir */ 471 { 472 char *home_path; 473 char *dll_path; 474 char *pslash; 475 char buf[MAXPATHLEN]; 476 os::jvm_path(buf, sizeof(buf)); 477 478 // Found the full path to libjvm.so. 479 // Now cut the path to <java_home>/jre if we can. 480 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */ 481 pslash = strrchr(buf, '/'); 482 if (pslash != NULL) 483 *pslash = '\0'; /* get rid of /{client|server|hotspot} */ 484 dll_path = malloc(strlen(buf) + 1); 485 if (dll_path == NULL) 486 return; 487 strcpy(dll_path, buf); 488 Arguments::set_dll_dir(dll_path); 489 490 if (pslash != NULL) { 491 pslash = strrchr(buf, '/'); 492 if (pslash != NULL) { 493 *pslash = '\0'; /* get rid of /<arch> (/lib on macosx) */ 494 #ifndef __APPLE__ 495 pslash = strrchr(buf, '/'); 496 if (pslash != NULL) 497 *pslash = '\0'; /* get rid of /lib */ 498 #endif 499 } 500 } 501 502 home_path = malloc(strlen(buf) + 1); 503 if (home_path == NULL) 504 return; 505 strcpy(home_path, buf); 506 Arguments::set_java_home(home_path); 507 508 if (!set_boot_path('/', ':')) 509 return; 510 } 511 512 /* 513 * Where to look for native libraries 514 * 515 * Note: Due to a legacy implementation, most of the library path 516 * is set in the launcher. This was to accomodate linking restrictions 517 * on legacy Bsd implementations (which are no longer supported). 518 * Eventually, all the library path setting will be done here. 519 * 520 * However, to prevent the proliferation of improperly built native 521 * libraries, the new path component /usr/java/packages is added here. 522 * Eventually, all the library path setting will be done here. 523 */ 524 { 525 char *ld_library_path; 526 527 /* 528 * Construct the invariant part of ld_library_path. Note that the 529 * space for the colon and the trailing null are provided by the 530 * nulls included by the sizeof operator (so actually we allocate 531 * a byte more than necessary). 532 */ 533 #ifdef __APPLE__ 534 ld_library_path = (char *) malloc(system_ext_size); 535 sprintf(ld_library_path, "%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, user_home_dir); 536 #else 537 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") + 538 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH)); 539 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch); 540 #endif 541 542 /* 543 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It 544 * should always exist (until the legacy problem cited above is 545 * addressed). 546 */ 547 #ifdef __APPLE__ 548 // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code can specify a directory inside an app wrapper 549 char *l = getenv("JAVA_LIBRARY_PATH"); 550 if (l != NULL) { 551 char *t = ld_library_path; 552 /* That's +1 for the colon and +1 for the trailing '\0' */ 553 ld_library_path = (char *) malloc(strlen(l) + 1 + strlen(t) + 1); 554 sprintf(ld_library_path, "%s:%s", l, t); 555 free(t); 556 } 557 558 char *v = getenv("DYLD_LIBRARY_PATH"); 559 #else 560 char *v = getenv("LD_LIBRARY_PATH"); 561 #endif 562 if (v != NULL) { 563 char *t = ld_library_path; 564 /* That's +1 for the colon and +1 for the trailing '\0' */ 565 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); 566 sprintf(ld_library_path, "%s:%s", v, t); 567 free(t); 568 } 569 570 #ifdef __APPLE__ 571 // Apple's Java6 has "." at the beginning of java.library.path. 572 // OpenJDK on Windows has "." at the end of java.library.path. 573 // OpenJDK on Linux and Solaris don't have "." in java.library.path 574 // at all. To ease the transition from Apple's Java6 to OpenJDK7, 575 // "." is appended to the end of java.library.path. Yes, this 576 // could cause a change in behavior, but Apple's Java6 behavior 577 // can be achieved by putting "." at the beginning of the 578 // JAVA_LIBRARY_PATH environment variable. 579 { 580 char *t = ld_library_path; 581 // that's +3 for appending ":." and the trailing '\0' 582 ld_library_path = (char *) malloc(strlen(t) + 3); 583 sprintf(ld_library_path, "%s:%s", t, "."); 584 free(t); 585 } 586 #endif 587 588 Arguments::set_library_path(ld_library_path); 589 } 590 591 /* 592 * Extensions directories. 593 * 594 * Note that the space for the colon and the trailing null are provided 595 * by the nulls included by the sizeof operator (so actually one byte more 596 * than necessary is allocated). 597 */ 598 { 599 #ifdef __APPLE__ 600 char *buf = malloc(strlen(Arguments::get_java_home()) + 601 sizeof(EXTENSIONS_DIR) + system_ext_size); 602 sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" 603 SYS_EXTENSIONS_DIRS, user_home_dir, Arguments::get_java_home()); 604 #else 605 char *buf = malloc(strlen(Arguments::get_java_home()) + 606 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR)); 607 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR, 608 Arguments::get_java_home()); 609 #endif 610 611 Arguments::set_ext_dirs(buf); 612 } 613 614 /* Endorsed standards default directory. */ 615 { 616 char * buf; 617 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); 618 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 619 Arguments::set_endorsed_dirs(buf); 620 } 621 } 622 623 #ifdef __APPLE__ 624 #undef SYS_EXTENSIONS_DIR 625 #endif 626 #undef malloc 627 #undef getenv 628 #undef EXTENSIONS_DIR 629 #undef ENDORSED_DIR 630 631 // Done 632 return; 633 } 634 635 //////////////////////////////////////////////////////////////////////////////// 636 // breakpoint support 637 638 void os::breakpoint() { 639 BREAKPOINT; 640 } 641 642 extern "C" void breakpoint() { 643 // use debugger to set breakpoint here 644 } 645 646 //////////////////////////////////////////////////////////////////////////////// 647 // signal support 648 649 debug_only(static bool signal_sets_initialized = false); 650 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 651 652 bool os::Bsd::is_sig_ignored(int sig) { 653 struct sigaction oact; 654 sigaction(sig, (struct sigaction*)NULL, &oact); 655 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 656 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 657 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) 658 return true; 659 else 660 return false; 661 } 662 663 void os::Bsd::signal_sets_init() { 664 // Should also have an assertion stating we are still single-threaded. 665 assert(!signal_sets_initialized, "Already initialized"); 666 // Fill in signals that are necessarily unblocked for all threads in 667 // the VM. Currently, we unblock the following signals: 668 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 669 // by -Xrs (=ReduceSignalUsage)); 670 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 671 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 672 // the dispositions or masks wrt these signals. 673 // Programs embedding the VM that want to use the above signals for their 674 // own purposes must, at this time, use the "-Xrs" option to prevent 675 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 676 // (See bug 4345157, and other related bugs). 677 // In reality, though, unblocking these signals is really a nop, since 678 // these signals are not blocked by default. 679 sigemptyset(&unblocked_sigs); 680 sigemptyset(&allowdebug_blocked_sigs); 681 sigaddset(&unblocked_sigs, SIGILL); 682 sigaddset(&unblocked_sigs, SIGSEGV); 683 sigaddset(&unblocked_sigs, SIGBUS); 684 sigaddset(&unblocked_sigs, SIGFPE); 685 sigaddset(&unblocked_sigs, SR_signum); 686 687 if (!ReduceSignalUsage) { 688 if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 689 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 690 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 691 } 692 if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 693 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 694 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 695 } 696 if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 697 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 698 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 699 } 700 } 701 // Fill in signals that are blocked by all but the VM thread. 702 sigemptyset(&vm_sigs); 703 if (!ReduceSignalUsage) 704 sigaddset(&vm_sigs, BREAK_SIGNAL); 705 debug_only(signal_sets_initialized = true); 706 707 } 708 709 // These are signals that are unblocked while a thread is running Java. 710 // (For some reason, they get blocked by default.) 711 sigset_t* os::Bsd::unblocked_signals() { 712 assert(signal_sets_initialized, "Not initialized"); 713 return &unblocked_sigs; 714 } 715 716 // These are the signals that are blocked while a (non-VM) thread is 717 // running Java. Only the VM thread handles these signals. 718 sigset_t* os::Bsd::vm_signals() { 719 assert(signal_sets_initialized, "Not initialized"); 720 return &vm_sigs; 721 } 722 723 // These are signals that are blocked during cond_wait to allow debugger in 724 sigset_t* os::Bsd::allowdebug_blocked_signals() { 725 assert(signal_sets_initialized, "Not initialized"); 726 return &allowdebug_blocked_sigs; 727 } 728 729 void os::Bsd::hotspot_sigmask(Thread* thread) { 730 731 //Save caller's signal mask before setting VM signal mask 732 sigset_t caller_sigmask; 733 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 734 735 OSThread* osthread = thread->osthread(); 736 osthread->set_caller_sigmask(caller_sigmask); 737 738 pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL); 739 740 if (!ReduceSignalUsage) { 741 if (thread->is_VM_thread()) { 742 // Only the VM thread handles BREAK_SIGNAL ... 743 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 744 } else { 745 // ... all other threads block BREAK_SIGNAL 746 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 747 } 748 } 749 } 750 751 #ifndef _ALLBSD_SOURCE 752 ////////////////////////////////////////////////////////////////////////////// 753 // detecting pthread library 754 755 void os::Bsd::libpthread_init() { 756 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION 757 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a 758 // generic name for earlier versions. 759 // Define macros here so we can build HotSpot on old systems. 760 # ifndef _CS_GNU_LIBC_VERSION 761 # define _CS_GNU_LIBC_VERSION 2 762 # endif 763 # ifndef _CS_GNU_LIBPTHREAD_VERSION 764 # define _CS_GNU_LIBPTHREAD_VERSION 3 765 # endif 766 767 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); 768 if (n > 0) { 769 char *str = (char *)malloc(n); 770 confstr(_CS_GNU_LIBC_VERSION, str, n); 771 os::Bsd::set_glibc_version(str); 772 } else { 773 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() 774 static char _gnu_libc_version[32]; 775 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), 776 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); 777 os::Bsd::set_glibc_version(_gnu_libc_version); 778 } 779 780 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); 781 if (n > 0) { 782 char *str = (char *)malloc(n); 783 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); 784 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells 785 // us "NPTL-0.29" even we are running with BsdThreads. Check if this 786 // is the case. BsdThreads has a hard limit on max number of threads. 787 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. 788 // On the other hand, NPTL does not have such a limit, sysconf() 789 // will return -1 and errno is not changed. Check if it is really NPTL. 790 if (strcmp(os::Bsd::glibc_version(), "glibc 2.3.2") == 0 && 791 strstr(str, "NPTL") && 792 sysconf(_SC_THREAD_THREADS_MAX) > 0) { 793 free(str); 794 os::Bsd::set_libpthread_version("bsdthreads"); 795 } else { 796 os::Bsd::set_libpthread_version(str); 797 } 798 } else { 799 // glibc before 2.3.2 only has BsdThreads. 800 os::Bsd::set_libpthread_version("bsdthreads"); 801 } 802 803 if (strstr(libpthread_version(), "NPTL")) { 804 os::Bsd::set_is_NPTL(); 805 } else { 806 os::Bsd::set_is_BsdThreads(); 807 } 808 809 // BsdThreads have two flavors: floating-stack mode, which allows variable 810 // stack size; and fixed-stack mode. NPTL is always floating-stack. 811 if (os::Bsd::is_NPTL() || os::Bsd::supports_variable_stack_size()) { 812 os::Bsd::set_is_floating_stack(); 813 } 814 } 815 816 ///////////////////////////////////////////////////////////////////////////// 817 // thread stack 818 819 // Force Bsd kernel to expand current thread stack. If "bottom" is close 820 // to the stack guard, caller should block all signals. 821 // 822 // MAP_GROWSDOWN: 823 // A special mmap() flag that is used to implement thread stacks. It tells 824 // kernel that the memory region should extend downwards when needed. This 825 // allows early versions of BsdThreads to only mmap the first few pages 826 // when creating a new thread. Bsd kernel will automatically expand thread 827 // stack as needed (on page faults). 828 // 829 // However, because the memory region of a MAP_GROWSDOWN stack can grow on 830 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN 831 // region, it's hard to tell if the fault is due to a legitimate stack 832 // access or because of reading/writing non-exist memory (e.g. buffer 833 // overrun). As a rule, if the fault happens below current stack pointer, 834 // Bsd kernel does not expand stack, instead a SIGSEGV is sent to the 835 // application (see Bsd kernel fault.c). 836 // 837 // This Bsd feature can cause SIGSEGV when VM bangs thread stack for 838 // stack overflow detection. 839 // 840 // Newer version of BsdThreads (since glibc-2.2, or, RH-7.x) and NPTL do 841 // not use this flag. However, the stack of initial thread is not created 842 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though 843 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack 844 // and then attach the thread to JVM. 845 // 846 // To get around the problem and allow stack banging on Bsd, we need to 847 // manually expand thread stack after receiving the SIGSEGV. 848 // 849 // There are two ways to expand thread stack to address "bottom", we used 850 // both of them in JVM before 1.5: 851 // 1. adjust stack pointer first so that it is below "bottom", and then 852 // touch "bottom" 853 // 2. mmap() the page in question 854 // 855 // Now alternate signal stack is gone, it's harder to use 2. For instance, 856 // if current sp is already near the lower end of page 101, and we need to 857 // call mmap() to map page 100, it is possible that part of the mmap() frame 858 // will be placed in page 100. When page 100 is mapped, it is zero-filled. 859 // That will destroy the mmap() frame and cause VM to crash. 860 // 861 // The following code works by adjusting sp first, then accessing the "bottom" 862 // page to force a page fault. Bsd kernel will then automatically expand the 863 // stack mapping. 864 // 865 // _expand_stack_to() assumes its frame size is less than page size, which 866 // should always be true if the function is not inlined. 867 868 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute 869 #define NOINLINE 870 #else 871 #define NOINLINE __attribute__ ((noinline)) 872 #endif 873 874 static void _expand_stack_to(address bottom) NOINLINE; 875 876 static void _expand_stack_to(address bottom) { 877 address sp; 878 size_t size; 879 volatile char *p; 880 881 // Adjust bottom to point to the largest address within the same page, it 882 // gives us a one-page buffer if alloca() allocates slightly more memory. 883 bottom = (address)align_size_down((uintptr_t)bottom, os::Bsd::page_size()); 884 bottom += os::Bsd::page_size() - 1; 885 886 // sp might be slightly above current stack pointer; if that's the case, we 887 // will alloca() a little more space than necessary, which is OK. Don't use 888 // os::current_stack_pointer(), as its result can be slightly below current 889 // stack pointer, causing us to not alloca enough to reach "bottom". 890 sp = (address)&sp; 891 892 if (sp > bottom) { 893 size = sp - bottom; 894 p = (volatile char *)alloca(size); 895 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); 896 p[0] = '\0'; 897 } 898 } 899 900 bool os::Bsd::manually_expand_stack(JavaThread * t, address addr) { 901 assert(t!=NULL, "just checking"); 902 assert(t->osthread()->expanding_stack(), "expand should be set"); 903 assert(t->stack_base() != NULL, "stack_base was not initialized"); 904 905 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { 906 sigset_t mask_all, old_sigset; 907 sigfillset(&mask_all); 908 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); 909 _expand_stack_to(addr); 910 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); 911 return true; 912 } 913 return false; 914 } 915 #endif 916 917 ////////////////////////////////////////////////////////////////////////////// 918 // create new thread 919 920 static address highest_vm_reserved_address(); 921 922 // check if it's safe to start a new thread 923 static bool _thread_safety_check(Thread* thread) { 924 #ifdef _ALLBSD_SOURCE 925 return true; 926 #else 927 if (os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack()) { 928 // Fixed stack BsdThreads (SuSE Bsd/x86, and some versions of Redhat) 929 // Heap is mmap'ed at lower end of memory space. Thread stacks are 930 // allocated (MAP_FIXED) from high address space. Every thread stack 931 // occupies a fixed size slot (usually 2Mbytes, but user can change 932 // it to other values if they rebuild BsdThreads). 933 // 934 // Problem with MAP_FIXED is that mmap() can still succeed even part of 935 // the memory region has already been mmap'ed. That means if we have too 936 // many threads and/or very large heap, eventually thread stack will 937 // collide with heap. 938 // 939 // Here we try to prevent heap/stack collision by comparing current 940 // stack bottom with the highest address that has been mmap'ed by JVM 941 // plus a safety margin for memory maps created by native code. 942 // 943 // This feature can be disabled by setting ThreadSafetyMargin to 0 944 // 945 if (ThreadSafetyMargin > 0) { 946 address stack_bottom = os::current_stack_base() - os::current_stack_size(); 947 948 // not safe if our stack extends below the safety margin 949 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); 950 } else { 951 return true; 952 } 953 } else { 954 // Floating stack BsdThreads or NPTL: 955 // Unlike fixed stack BsdThreads, thread stacks are not MAP_FIXED. When 956 // there's not enough space left, pthread_create() will fail. If we come 957 // here, that means enough space has been reserved for stack. 958 return true; 959 } 960 #endif 961 } 962 963 #ifdef __APPLE__ 964 // library handle for calling objc_registerThreadWithCollector() 965 // without static linking to the libobjc library 966 #define OBJC_LIB "/usr/lib/libobjc.dylib" 967 #define OBJC_GCREGISTER "objc_registerThreadWithCollector" 968 typedef void (*objc_registerThreadWithCollector_t)(); 969 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction; 970 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL; 971 #endif 972 973 #ifdef __APPLE__ 974 static uint64_t locate_unique_thread_id() { 975 // Additional thread_id used to correlate threads in SA 976 thread_identifier_info_data_t m_ident_info; 977 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT; 978 979 thread_info(::mach_thread_self(), THREAD_IDENTIFIER_INFO, 980 (thread_info_t) &m_ident_info, &count); 981 return m_ident_info.thread_id; 982 } 983 #endif 984 985 // Thread start routine for all newly created threads 986 static void *java_start(Thread *thread) { 987 // Try to randomize the cache line index of hot stack frames. 988 // This helps when threads of the same stack traces evict each other's 989 // cache lines. The threads can be either from the same JVM instance, or 990 // from different JVM instances. The benefit is especially true for 991 // processors with hyperthreading technology. 992 static int counter = 0; 993 int pid = os::current_process_id(); 994 alloca(((pid ^ counter++) & 7) * 128); 995 996 ThreadLocalStorage::set_thread(thread); 997 998 OSThread* osthread = thread->osthread(); 999 Monitor* sync = osthread->startThread_lock(); 1000 1001 // non floating stack BsdThreads needs extra check, see above 1002 if (!_thread_safety_check(thread)) { 1003 // notify parent thread 1004 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 1005 osthread->set_state(ZOMBIE); 1006 sync->notify_all(); 1007 return NULL; 1008 } 1009 1010 #ifdef _ALLBSD_SOURCE 1011 #ifdef __APPLE__ 1012 // thread_id is mach thread on macos 1013 osthread->set_thread_id(::mach_thread_self()); 1014 osthread->set_unique_thread_id(locate_unique_thread_id()); 1015 #else 1016 // thread_id is pthread_id on BSD 1017 osthread->set_thread_id(::pthread_self()); 1018 #endif 1019 #else 1020 // thread_id is kernel thread id (similar to Solaris LWP id) 1021 osthread->set_thread_id(os::Bsd::gettid()); 1022 1023 if (UseNUMA) { 1024 int lgrp_id = os::numa_get_group_id(); 1025 if (lgrp_id != -1) { 1026 thread->set_lgrp_id(lgrp_id); 1027 } 1028 } 1029 #endif 1030 // initialize signal mask for this thread 1031 os::Bsd::hotspot_sigmask(thread); 1032 1033 // initialize floating point control register 1034 os::Bsd::init_thread_fpu_state(); 1035 1036 #ifdef __APPLE__ 1037 // register thread with objc gc 1038 if (objc_registerThreadWithCollectorFunction != NULL) { 1039 objc_registerThreadWithCollectorFunction(); 1040 } 1041 #endif 1042 1043 // handshaking with parent thread 1044 { 1045 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 1046 1047 // notify parent thread 1048 osthread->set_state(INITIALIZED); 1049 sync->notify_all(); 1050 1051 // wait until os::start_thread() 1052 while (osthread->get_state() == INITIALIZED) { 1053 sync->wait(Mutex::_no_safepoint_check_flag); 1054 } 1055 } 1056 1057 // call one more level start routine 1058 thread->run(); 1059 1060 return 0; 1061 } 1062 1063 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 1064 assert(thread->osthread() == NULL, "caller responsible"); 1065 1066 // Allocate the OSThread object 1067 OSThread* osthread = new OSThread(NULL, NULL); 1068 if (osthread == NULL) { 1069 return false; 1070 } 1071 1072 // set the correct thread state 1073 osthread->set_thread_type(thr_type); 1074 1075 // Initial state is ALLOCATED but not INITIALIZED 1076 osthread->set_state(ALLOCATED); 1077 1078 thread->set_osthread(osthread); 1079 1080 // init thread attributes 1081 pthread_attr_t attr; 1082 pthread_attr_init(&attr); 1083 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 1084 1085 // stack size 1086 if (os::Bsd::supports_variable_stack_size()) { 1087 // calculate stack size if it's not specified by caller 1088 if (stack_size == 0) { 1089 stack_size = os::Bsd::default_stack_size(thr_type); 1090 1091 switch (thr_type) { 1092 case os::java_thread: 1093 // Java threads use ThreadStackSize which default value can be 1094 // changed with the flag -Xss 1095 assert (JavaThread::stack_size_at_create() > 0, "this should be set"); 1096 stack_size = JavaThread::stack_size_at_create(); 1097 break; 1098 case os::compiler_thread: 1099 if (CompilerThreadStackSize > 0) { 1100 stack_size = (size_t)(CompilerThreadStackSize * K); 1101 break; 1102 } // else fall through: 1103 // use VMThreadStackSize if CompilerThreadStackSize is not defined 1104 case os::vm_thread: 1105 case os::pgc_thread: 1106 case os::cgc_thread: 1107 case os::watcher_thread: 1108 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 1109 break; 1110 } 1111 } 1112 1113 stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed); 1114 pthread_attr_setstacksize(&attr, stack_size); 1115 } else { 1116 // let pthread_create() pick the default value. 1117 } 1118 1119 #ifndef _ALLBSD_SOURCE 1120 // glibc guard page 1121 pthread_attr_setguardsize(&attr, os::Bsd::default_guard_size(thr_type)); 1122 #endif 1123 1124 ThreadState state; 1125 1126 { 1127 1128 #ifndef _ALLBSD_SOURCE 1129 // Serialize thread creation if we are running with fixed stack BsdThreads 1130 bool lock = os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack(); 1131 if (lock) { 1132 os::Bsd::createThread_lock()->lock_without_safepoint_check(); 1133 } 1134 #endif 1135 1136 pthread_t tid; 1137 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 1138 1139 pthread_attr_destroy(&attr); 1140 1141 if (ret != 0) { 1142 if (PrintMiscellaneous && (Verbose || WizardMode)) { 1143 perror("pthread_create()"); 1144 } 1145 // Need to clean up stuff we've allocated so far 1146 thread->set_osthread(NULL); 1147 delete osthread; 1148 #ifndef _ALLBSD_SOURCE 1149 if (lock) os::Bsd::createThread_lock()->unlock(); 1150 #endif 1151 return false; 1152 } 1153 1154 // Store pthread info into the OSThread 1155 osthread->set_pthread_id(tid); 1156 1157 // Wait until child thread is either initialized or aborted 1158 { 1159 Monitor* sync_with_child = osthread->startThread_lock(); 1160 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 1161 while ((state = osthread->get_state()) == ALLOCATED) { 1162 sync_with_child->wait(Mutex::_no_safepoint_check_flag); 1163 } 1164 } 1165 1166 #ifndef _ALLBSD_SOURCE 1167 if (lock) { 1168 os::Bsd::createThread_lock()->unlock(); 1169 } 1170 #endif 1171 } 1172 1173 // Aborted due to thread limit being reached 1174 if (state == ZOMBIE) { 1175 thread->set_osthread(NULL); 1176 delete osthread; 1177 return false; 1178 } 1179 1180 // The thread is returned suspended (in state INITIALIZED), 1181 // and is started higher up in the call chain 1182 assert(state == INITIALIZED, "race condition"); 1183 return true; 1184 } 1185 1186 ///////////////////////////////////////////////////////////////////////////// 1187 // attach existing thread 1188 1189 // bootstrap the main thread 1190 bool os::create_main_thread(JavaThread* thread) { 1191 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread"); 1192 return create_attached_thread(thread); 1193 } 1194 1195 bool os::create_attached_thread(JavaThread* thread) { 1196 #ifdef ASSERT 1197 thread->verify_not_published(); 1198 #endif 1199 1200 // Allocate the OSThread object 1201 OSThread* osthread = new OSThread(NULL, NULL); 1202 1203 if (osthread == NULL) { 1204 return false; 1205 } 1206 1207 // Store pthread info into the OSThread 1208 #ifdef _ALLBSD_SOURCE 1209 #ifdef __APPLE__ 1210 osthread->set_thread_id(::mach_thread_self()); 1211 osthread->set_unique_thread_id(locate_unique_thread_id()); 1212 #else 1213 osthread->set_thread_id(::pthread_self()); 1214 #endif 1215 #else 1216 osthread->set_thread_id(os::Bsd::gettid()); 1217 #endif 1218 osthread->set_pthread_id(::pthread_self()); 1219 1220 // initialize floating point control register 1221 os::Bsd::init_thread_fpu_state(); 1222 1223 // Initial thread state is RUNNABLE 1224 osthread->set_state(RUNNABLE); 1225 1226 thread->set_osthread(osthread); 1227 1228 #ifndef _ALLBSD_SOURCE 1229 if (UseNUMA) { 1230 int lgrp_id = os::numa_get_group_id(); 1231 if (lgrp_id != -1) { 1232 thread->set_lgrp_id(lgrp_id); 1233 } 1234 } 1235 1236 if (os::Bsd::is_initial_thread()) { 1237 // If current thread is initial thread, its stack is mapped on demand, 1238 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map 1239 // the entire stack region to avoid SEGV in stack banging. 1240 // It is also useful to get around the heap-stack-gap problem on SuSE 1241 // kernel (see 4821821 for details). We first expand stack to the top 1242 // of yellow zone, then enable stack yellow zone (order is significant, 1243 // enabling yellow zone first will crash JVM on SuSE Bsd), so there 1244 // is no gap between the last two virtual memory regions. 1245 1246 JavaThread *jt = (JavaThread *)thread; 1247 address addr = jt->stack_yellow_zone_base(); 1248 assert(addr != NULL, "initialization problem?"); 1249 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); 1250 1251 osthread->set_expanding_stack(); 1252 os::Bsd::manually_expand_stack(jt, addr); 1253 osthread->clear_expanding_stack(); 1254 } 1255 #endif 1256 1257 // initialize signal mask for this thread 1258 // and save the caller's signal mask 1259 os::Bsd::hotspot_sigmask(thread); 1260 1261 return true; 1262 } 1263 1264 void os::pd_start_thread(Thread* thread) { 1265 OSThread * osthread = thread->osthread(); 1266 assert(osthread->get_state() != INITIALIZED, "just checking"); 1267 Monitor* sync_with_child = osthread->startThread_lock(); 1268 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 1269 sync_with_child->notify(); 1270 } 1271 1272 // Free Bsd resources related to the OSThread 1273 void os::free_thread(OSThread* osthread) { 1274 assert(osthread != NULL, "osthread not set"); 1275 1276 if (Thread::current()->osthread() == osthread) { 1277 // Restore caller's signal mask 1278 sigset_t sigmask = osthread->caller_sigmask(); 1279 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 1280 } 1281 1282 delete osthread; 1283 } 1284 1285 ////////////////////////////////////////////////////////////////////////////// 1286 // thread local storage 1287 1288 int os::allocate_thread_local_storage() { 1289 pthread_key_t key; 1290 int rslt = pthread_key_create(&key, NULL); 1291 assert(rslt == 0, "cannot allocate thread local storage"); 1292 return (int)key; 1293 } 1294 1295 // Note: This is currently not used by VM, as we don't destroy TLS key 1296 // on VM exit. 1297 void os::free_thread_local_storage(int index) { 1298 int rslt = pthread_key_delete((pthread_key_t)index); 1299 assert(rslt == 0, "invalid index"); 1300 } 1301 1302 void os::thread_local_storage_at_put(int index, void* value) { 1303 int rslt = pthread_setspecific((pthread_key_t)index, value); 1304 assert(rslt == 0, "pthread_setspecific failed"); 1305 } 1306 1307 extern "C" Thread* get_thread() { 1308 return ThreadLocalStorage::thread(); 1309 } 1310 1311 ////////////////////////////////////////////////////////////////////////////// 1312 // initial thread 1313 1314 #ifndef _ALLBSD_SOURCE 1315 // Check if current thread is the initial thread, similar to Solaris thr_main. 1316 bool os::Bsd::is_initial_thread(void) { 1317 char dummy; 1318 // If called before init complete, thread stack bottom will be null. 1319 // Can be called if fatal error occurs before initialization. 1320 if (initial_thread_stack_bottom() == NULL) return false; 1321 assert(initial_thread_stack_bottom() != NULL && 1322 initial_thread_stack_size() != 0, 1323 "os::init did not locate initial thread's stack region"); 1324 if ((address)&dummy >= initial_thread_stack_bottom() && 1325 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) 1326 return true; 1327 else return false; 1328 } 1329 1330 // Find the virtual memory area that contains addr 1331 static bool find_vma(address addr, address* vma_low, address* vma_high) { 1332 FILE *fp = fopen("/proc/self/maps", "r"); 1333 if (fp) { 1334 address low, high; 1335 while (!feof(fp)) { 1336 if (fscanf(fp, "%p-%p", &low, &high) == 2) { 1337 if (low <= addr && addr < high) { 1338 if (vma_low) *vma_low = low; 1339 if (vma_high) *vma_high = high; 1340 fclose (fp); 1341 return true; 1342 } 1343 } 1344 for (;;) { 1345 int ch = fgetc(fp); 1346 if (ch == EOF || ch == (int)'\n') break; 1347 } 1348 } 1349 fclose(fp); 1350 } 1351 return false; 1352 } 1353 1354 // Locate initial thread stack. This special handling of initial thread stack 1355 // is needed because pthread_getattr_np() on most (all?) Bsd distros returns 1356 // bogus value for initial thread. 1357 void os::Bsd::capture_initial_stack(size_t max_size) { 1358 // stack size is the easy part, get it from RLIMIT_STACK 1359 size_t stack_size; 1360 struct rlimit rlim; 1361 getrlimit(RLIMIT_STACK, &rlim); 1362 stack_size = rlim.rlim_cur; 1363 1364 // 6308388: a bug in ld.so will relocate its own .data section to the 1365 // lower end of primordial stack; reduce ulimit -s value a little bit 1366 // so we won't install guard page on ld.so's data section. 1367 stack_size -= 2 * page_size(); 1368 1369 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat 1370 // 7.1, in both cases we will get 2G in return value. 1371 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, 1372 // SuSE 7.2, Debian) can not handle alternate signal stack correctly 1373 // for initial thread if its stack size exceeds 6M. Cap it at 2M, 1374 // in case other parts in glibc still assumes 2M max stack size. 1375 // FIXME: alt signal stack is gone, maybe we can relax this constraint? 1376 #ifndef IA64 1377 if (stack_size > 2 * K * K) stack_size = 2 * K * K; 1378 #else 1379 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small 1380 if (stack_size > 4 * K * K) stack_size = 4 * K * K; 1381 #endif 1382 1383 // Try to figure out where the stack base (top) is. This is harder. 1384 // 1385 // When an application is started, glibc saves the initial stack pointer in 1386 // a global variable "__libc_stack_end", which is then used by system 1387 // libraries. __libc_stack_end should be pretty close to stack top. The 1388 // variable is available since the very early days. However, because it is 1389 // a private interface, it could disappear in the future. 1390 // 1391 // Bsd kernel saves start_stack information in /proc/<pid>/stat. Similar 1392 // to __libc_stack_end, it is very close to stack top, but isn't the real 1393 // stack top. Note that /proc may not exist if VM is running as a chroot 1394 // program, so reading /proc/<pid>/stat could fail. Also the contents of 1395 // /proc/<pid>/stat could change in the future (though unlikely). 1396 // 1397 // We try __libc_stack_end first. If that doesn't work, look for 1398 // /proc/<pid>/stat. If neither of them works, we use current stack pointer 1399 // as a hint, which should work well in most cases. 1400 1401 uintptr_t stack_start; 1402 1403 // try __libc_stack_end first 1404 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); 1405 if (p && *p) { 1406 stack_start = *p; 1407 } else { 1408 // see if we can get the start_stack field from /proc/self/stat 1409 FILE *fp; 1410 int pid; 1411 char state; 1412 int ppid; 1413 int pgrp; 1414 int session; 1415 int nr; 1416 int tpgrp; 1417 unsigned long flags; 1418 unsigned long minflt; 1419 unsigned long cminflt; 1420 unsigned long majflt; 1421 unsigned long cmajflt; 1422 unsigned long utime; 1423 unsigned long stime; 1424 long cutime; 1425 long cstime; 1426 long prio; 1427 long nice; 1428 long junk; 1429 long it_real; 1430 uintptr_t start; 1431 uintptr_t vsize; 1432 intptr_t rss; 1433 uintptr_t rsslim; 1434 uintptr_t scodes; 1435 uintptr_t ecode; 1436 int i; 1437 1438 // Figure what the primordial thread stack base is. Code is inspired 1439 // by email from Hans Boehm. /proc/self/stat begins with current pid, 1440 // followed by command name surrounded by parentheses, state, etc. 1441 char stat[2048]; 1442 int statlen; 1443 1444 fp = fopen("/proc/self/stat", "r"); 1445 if (fp) { 1446 statlen = fread(stat, 1, 2047, fp); 1447 stat[statlen] = '\0'; 1448 fclose(fp); 1449 1450 // Skip pid and the command string. Note that we could be dealing with 1451 // weird command names, e.g. user could decide to rename java launcher 1452 // to "java 1.4.2 :)", then the stat file would look like 1453 // 1234 (java 1.4.2 :)) R ... ... 1454 // We don't really need to know the command string, just find the last 1455 // occurrence of ")" and then start parsing from there. See bug 4726580. 1456 char * s = strrchr(stat, ')'); 1457 1458 i = 0; 1459 if (s) { 1460 // Skip blank chars 1461 do s++; while (isspace(*s)); 1462 1463 #define _UFM UINTX_FORMAT 1464 #define _DFM INTX_FORMAT 1465 1466 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ 1467 /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */ 1468 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM, 1469 &state, /* 3 %c */ 1470 &ppid, /* 4 %d */ 1471 &pgrp, /* 5 %d */ 1472 &session, /* 6 %d */ 1473 &nr, /* 7 %d */ 1474 &tpgrp, /* 8 %d */ 1475 &flags, /* 9 %lu */ 1476 &minflt, /* 10 %lu */ 1477 &cminflt, /* 11 %lu */ 1478 &majflt, /* 12 %lu */ 1479 &cmajflt, /* 13 %lu */ 1480 &utime, /* 14 %lu */ 1481 &stime, /* 15 %lu */ 1482 &cutime, /* 16 %ld */ 1483 &cstime, /* 17 %ld */ 1484 &prio, /* 18 %ld */ 1485 &nice, /* 19 %ld */ 1486 &junk, /* 20 %ld */ 1487 &it_real, /* 21 %ld */ 1488 &start, /* 22 UINTX_FORMAT */ 1489 &vsize, /* 23 UINTX_FORMAT */ 1490 &rss, /* 24 INTX_FORMAT */ 1491 &rsslim, /* 25 UINTX_FORMAT */ 1492 &scodes, /* 26 UINTX_FORMAT */ 1493 &ecode, /* 27 UINTX_FORMAT */ 1494 &stack_start); /* 28 UINTX_FORMAT */ 1495 } 1496 1497 #undef _UFM 1498 #undef _DFM 1499 1500 if (i != 28 - 2) { 1501 assert(false, "Bad conversion from /proc/self/stat"); 1502 // product mode - assume we are the initial thread, good luck in the 1503 // embedded case. 1504 warning("Can't detect initial thread stack location - bad conversion"); 1505 stack_start = (uintptr_t) &rlim; 1506 } 1507 } else { 1508 // For some reason we can't open /proc/self/stat (for example, running on 1509 // FreeBSD with a Bsd emulator, or inside chroot), this should work for 1510 // most cases, so don't abort: 1511 warning("Can't detect initial thread stack location - no /proc/self/stat"); 1512 stack_start = (uintptr_t) &rlim; 1513 } 1514 } 1515 1516 // Now we have a pointer (stack_start) very close to the stack top, the 1517 // next thing to do is to figure out the exact location of stack top. We 1518 // can find out the virtual memory area that contains stack_start by 1519 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, 1520 // and its upper limit is the real stack top. (again, this would fail if 1521 // running inside chroot, because /proc may not exist.) 1522 1523 uintptr_t stack_top; 1524 address low, high; 1525 if (find_vma((address)stack_start, &low, &high)) { 1526 // success, "high" is the true stack top. (ignore "low", because initial 1527 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) 1528 stack_top = (uintptr_t)high; 1529 } else { 1530 // failed, likely because /proc/self/maps does not exist 1531 warning("Can't detect initial thread stack location - find_vma failed"); 1532 // best effort: stack_start is normally within a few pages below the real 1533 // stack top, use it as stack top, and reduce stack size so we won't put 1534 // guard page outside stack. 1535 stack_top = stack_start; 1536 stack_size -= 16 * page_size(); 1537 } 1538 1539 // stack_top could be partially down the page so align it 1540 stack_top = align_size_up(stack_top, page_size()); 1541 1542 if (max_size && stack_size > max_size) { 1543 _initial_thread_stack_size = max_size; 1544 } else { 1545 _initial_thread_stack_size = stack_size; 1546 } 1547 1548 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); 1549 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; 1550 } 1551 #endif 1552 1553 //////////////////////////////////////////////////////////////////////////////// 1554 // time support 1555 1556 // Time since start-up in seconds to a fine granularity. 1557 // Used by VMSelfDestructTimer and the MemProfiler. 1558 double os::elapsedTime() { 1559 1560 return (double)(os::elapsed_counter()) * 0.000001; 1561 } 1562 1563 jlong os::elapsed_counter() { 1564 timeval time; 1565 int status = gettimeofday(&time, NULL); 1566 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; 1567 } 1568 1569 jlong os::elapsed_frequency() { 1570 return (1000 * 1000); 1571 } 1572 1573 // XXX: For now, code this as if BSD does not support vtime. 1574 bool os::supports_vtime() { return false; } 1575 bool os::enable_vtime() { return false; } 1576 bool os::vtime_enabled() { return false; } 1577 double os::elapsedVTime() { 1578 // better than nothing, but not much 1579 return elapsedTime(); 1580 } 1581 1582 jlong os::javaTimeMillis() { 1583 timeval time; 1584 int status = gettimeofday(&time, NULL); 1585 assert(status != -1, "bsd error"); 1586 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 1587 } 1588 1589 #ifndef CLOCK_MONOTONIC 1590 #define CLOCK_MONOTONIC (1) 1591 #endif 1592 1593 #ifdef __APPLE__ 1594 void os::Bsd::clock_init() { 1595 // XXXDARWIN: Investigate replacement monotonic clock 1596 } 1597 #elif defined(_ALLBSD_SOURCE) 1598 void os::Bsd::clock_init() { 1599 struct timespec res; 1600 struct timespec tp; 1601 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 && 1602 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { 1603 // yes, monotonic clock is supported 1604 _clock_gettime = ::clock_gettime; 1605 } 1606 } 1607 #else 1608 void os::Bsd::clock_init() { 1609 // we do dlopen's in this particular order due to bug in bsd 1610 // dynamical loader (see 6348968) leading to crash on exit 1611 void* handle = dlopen("librt.so.1", RTLD_LAZY); 1612 if (handle == NULL) { 1613 handle = dlopen("librt.so", RTLD_LAZY); 1614 } 1615 1616 if (handle) { 1617 int (*clock_getres_func)(clockid_t, struct timespec*) = 1618 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1619 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1620 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1621 if (clock_getres_func && clock_gettime_func) { 1622 // See if monotonic clock is supported by the kernel. Note that some 1623 // early implementations simply return kernel jiffies (updated every 1624 // 1/100 or 1/1000 second). It would be bad to use such a low res clock 1625 // for nano time (though the monotonic property is still nice to have). 1626 // It's fixed in newer kernels, however clock_getres() still returns 1627 // 1/HZ. We check if clock_getres() works, but will ignore its reported 1628 // resolution for now. Hopefully as people move to new kernels, this 1629 // won't be a problem. 1630 struct timespec res; 1631 struct timespec tp; 1632 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && 1633 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1634 // yes, monotonic clock is supported 1635 _clock_gettime = clock_gettime_func; 1636 } else { 1637 // close librt if there is no monotonic clock 1638 dlclose(handle); 1639 } 1640 } 1641 } 1642 } 1643 #endif 1644 1645 #ifndef _ALLBSD_SOURCE 1646 #ifndef SYS_clock_getres 1647 1648 #if defined(IA32) || defined(AMD64) 1649 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) 1650 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1651 #else 1652 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time" 1653 #define sys_clock_getres(x,y) -1 1654 #endif 1655 1656 #else 1657 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1658 #endif 1659 1660 void os::Bsd::fast_thread_clock_init() { 1661 if (!UseBsdPosixThreadCPUClocks) { 1662 return; 1663 } 1664 clockid_t clockid; 1665 struct timespec tp; 1666 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = 1667 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); 1668 1669 // Switch to using fast clocks for thread cpu time if 1670 // the sys_clock_getres() returns 0 error code. 1671 // Note, that some kernels may support the current thread 1672 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks 1673 // returned by the pthread_getcpuclockid(). 1674 // If the fast Posix clocks are supported then the sys_clock_getres() 1675 // must return at least tp.tv_sec == 0 which means a resolution 1676 // better than 1 sec. This is extra check for reliability. 1677 1678 if(pthread_getcpuclockid_func && 1679 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && 1680 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { 1681 1682 _supports_fast_thread_cpu_time = true; 1683 _pthread_getcpuclockid = pthread_getcpuclockid_func; 1684 } 1685 } 1686 #endif 1687 1688 jlong os::javaTimeNanos() { 1689 if (Bsd::supports_monotonic_clock()) { 1690 struct timespec tp; 1691 int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp); 1692 assert(status == 0, "gettime error"); 1693 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 1694 return result; 1695 } else { 1696 timeval time; 1697 int status = gettimeofday(&time, NULL); 1698 assert(status != -1, "bsd error"); 1699 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1700 return 1000 * usecs; 1701 } 1702 } 1703 1704 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1705 if (Bsd::supports_monotonic_clock()) { 1706 info_ptr->max_value = ALL_64_BITS; 1707 1708 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 1709 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1710 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1711 } else { 1712 // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1713 info_ptr->max_value = ALL_64_BITS; 1714 1715 // gettimeofday is a real time clock so it skips 1716 info_ptr->may_skip_backward = true; 1717 info_ptr->may_skip_forward = true; 1718 } 1719 1720 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1721 } 1722 1723 // Return the real, user, and system times in seconds from an 1724 // arbitrary fixed point in the past. 1725 bool os::getTimesSecs(double* process_real_time, 1726 double* process_user_time, 1727 double* process_system_time) { 1728 struct tms ticks; 1729 clock_t real_ticks = times(&ticks); 1730 1731 if (real_ticks == (clock_t) (-1)) { 1732 return false; 1733 } else { 1734 double ticks_per_second = (double) clock_tics_per_sec; 1735 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1736 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1737 *process_real_time = ((double) real_ticks) / ticks_per_second; 1738 1739 return true; 1740 } 1741 } 1742 1743 1744 char * os::local_time_string(char *buf, size_t buflen) { 1745 struct tm t; 1746 time_t long_time; 1747 time(&long_time); 1748 localtime_r(&long_time, &t); 1749 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1750 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1751 t.tm_hour, t.tm_min, t.tm_sec); 1752 return buf; 1753 } 1754 1755 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1756 return localtime_r(clock, res); 1757 } 1758 1759 //////////////////////////////////////////////////////////////////////////////// 1760 // runtime exit support 1761 1762 // Note: os::shutdown() might be called very early during initialization, or 1763 // called from signal handler. Before adding something to os::shutdown(), make 1764 // sure it is async-safe and can handle partially initialized VM. 1765 void os::shutdown() { 1766 1767 // allow PerfMemory to attempt cleanup of any persistent resources 1768 perfMemory_exit(); 1769 1770 // needs to remove object in file system 1771 AttachListener::abort(); 1772 1773 // flush buffered output, finish log files 1774 ostream_abort(); 1775 1776 // Check for abort hook 1777 abort_hook_t abort_hook = Arguments::abort_hook(); 1778 if (abort_hook != NULL) { 1779 abort_hook(); 1780 } 1781 1782 } 1783 1784 // Note: os::abort() might be called very early during initialization, or 1785 // called from signal handler. Before adding something to os::abort(), make 1786 // sure it is async-safe and can handle partially initialized VM. 1787 void os::abort(bool dump_core) { 1788 os::shutdown(); 1789 if (dump_core) { 1790 #ifndef PRODUCT 1791 fdStream out(defaultStream::output_fd()); 1792 out.print_raw("Current thread is "); 1793 char buf[16]; 1794 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1795 out.print_raw_cr(buf); 1796 out.print_raw_cr("Dumping core ..."); 1797 #endif 1798 ::abort(); // dump core 1799 } 1800 1801 ::exit(1); 1802 } 1803 1804 // Die immediately, no exit hook, no abort hook, no cleanup. 1805 void os::die() { 1806 // _exit() on BsdThreads only kills current thread 1807 ::abort(); 1808 } 1809 1810 // unused on bsd for now. 1811 void os::set_error_file(const char *logfile) {} 1812 1813 1814 // This method is a copy of JDK's sysGetLastErrorString 1815 // from src/solaris/hpi/src/system_md.c 1816 1817 size_t os::lasterror(char *buf, size_t len) { 1818 1819 if (errno == 0) return 0; 1820 1821 const char *s = ::strerror(errno); 1822 size_t n = ::strlen(s); 1823 if (n >= len) { 1824 n = len - 1; 1825 } 1826 ::strncpy(buf, s, n); 1827 buf[n] = '\0'; 1828 return n; 1829 } 1830 1831 intx os::current_thread_id() { 1832 #ifdef __APPLE__ 1833 return (intx)::mach_thread_self(); 1834 #else 1835 return (intx)::pthread_self(); 1836 #endif 1837 } 1838 int os::current_process_id() { 1839 1840 // Under the old bsd thread library, bsd gives each thread 1841 // its own process id. Because of this each thread will return 1842 // a different pid if this method were to return the result 1843 // of getpid(2). Bsd provides no api that returns the pid 1844 // of the launcher thread for the vm. This implementation 1845 // returns a unique pid, the pid of the launcher thread 1846 // that starts the vm 'process'. 1847 1848 // Under the NPTL, getpid() returns the same pid as the 1849 // launcher thread rather than a unique pid per thread. 1850 // Use gettid() if you want the old pre NPTL behaviour. 1851 1852 // if you are looking for the result of a call to getpid() that 1853 // returns a unique pid for the calling thread, then look at the 1854 // OSThread::thread_id() method in osThread_bsd.hpp file 1855 1856 return (int)(_initial_pid ? _initial_pid : getpid()); 1857 } 1858 1859 // DLL functions 1860 1861 #define JNI_LIB_PREFIX "lib" 1862 #ifdef __APPLE__ 1863 #define JNI_LIB_SUFFIX ".dylib" 1864 #else 1865 #define JNI_LIB_SUFFIX ".so" 1866 #endif 1867 1868 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; } 1869 1870 // This must be hard coded because it's the system's temporary 1871 // directory not the java application's temp directory, ala java.io.tmpdir. 1872 #ifdef __APPLE__ 1873 // macosx has a secure per-user temporary directory 1874 char temp_path_storage[PATH_MAX]; 1875 const char* os::get_temp_directory() { 1876 static char *temp_path = NULL; 1877 if (temp_path == NULL) { 1878 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX); 1879 if (pathSize == 0 || pathSize > PATH_MAX) { 1880 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage)); 1881 } 1882 temp_path = temp_path_storage; 1883 } 1884 return temp_path; 1885 } 1886 #else /* __APPLE__ */ 1887 const char* os::get_temp_directory() { return "/tmp"; } 1888 #endif /* __APPLE__ */ 1889 1890 static bool file_exists(const char* filename) { 1891 struct stat statbuf; 1892 if (filename == NULL || strlen(filename) == 0) { 1893 return false; 1894 } 1895 return os::stat(filename, &statbuf) == 0; 1896 } 1897 1898 void os::dll_build_name(char* buffer, size_t buflen, 1899 const char* pname, const char* fname) { 1900 // Copied from libhpi 1901 const size_t pnamelen = pname ? strlen(pname) : 0; 1902 1903 // Quietly truncate on buffer overflow. Should be an error. 1904 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) { 1905 *buffer = '\0'; 1906 return; 1907 } 1908 1909 if (pnamelen == 0) { 1910 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname); 1911 } else if (strchr(pname, *os::path_separator()) != NULL) { 1912 int n; 1913 char** pelements = split_path(pname, &n); 1914 for (int i = 0 ; i < n ; i++) { 1915 // Really shouldn't be NULL, but check can't hurt 1916 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1917 continue; // skip the empty path values 1918 } 1919 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, 1920 pelements[i], fname); 1921 if (file_exists(buffer)) { 1922 break; 1923 } 1924 } 1925 // release the storage 1926 for (int i = 0 ; i < n ; i++) { 1927 if (pelements[i] != NULL) { 1928 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); 1929 } 1930 } 1931 if (pelements != NULL) { 1932 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal); 1933 } 1934 } else { 1935 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname); 1936 } 1937 } 1938 1939 const char* os::get_current_directory(char *buf, int buflen) { 1940 return getcwd(buf, buflen); 1941 } 1942 1943 // check if addr is inside libjvm[_g].so 1944 bool os::address_is_in_vm(address addr) { 1945 static address libjvm_base_addr; 1946 Dl_info dlinfo; 1947 1948 if (libjvm_base_addr == NULL) { 1949 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); 1950 libjvm_base_addr = (address)dlinfo.dli_fbase; 1951 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1952 } 1953 1954 if (dladdr((void *)addr, &dlinfo)) { 1955 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1956 } 1957 1958 return false; 1959 } 1960 1961 1962 #define MACH_MAXSYMLEN 256 1963 1964 bool os::dll_address_to_function_name(address addr, char *buf, 1965 int buflen, int *offset) { 1966 Dl_info dlinfo; 1967 char localbuf[MACH_MAXSYMLEN]; 1968 1969 // dladdr will find names of dynamic functions only, but does 1970 // it set dli_fbase with mach_header address when it "fails" ? 1971 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { 1972 if (buf != NULL) { 1973 if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { 1974 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1975 } 1976 } 1977 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1978 return true; 1979 } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { 1980 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1981 buf, buflen, offset, dlinfo.dli_fname)) { 1982 return true; 1983 } 1984 } 1985 1986 // Handle non-dymanic manually: 1987 if (dlinfo.dli_fbase != NULL && 1988 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) { 1989 if(!Decoder::demangle(localbuf, buf, buflen)) { 1990 jio_snprintf(buf, buflen, "%s", localbuf); 1991 } 1992 return true; 1993 } 1994 if (buf != NULL) buf[0] = '\0'; 1995 if (offset != NULL) *offset = -1; 1996 return false; 1997 } 1998 1999 #ifdef _ALLBSD_SOURCE 2000 // ported from solaris version 2001 bool os::dll_address_to_library_name(address addr, char* buf, 2002 int buflen, int* offset) { 2003 Dl_info dlinfo; 2004 2005 if (dladdr((void*)addr, &dlinfo)){ 2006 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 2007 if (offset) *offset = addr - (address)dlinfo.dli_fbase; 2008 return true; 2009 } else { 2010 if (buf) buf[0] = '\0'; 2011 if (offset) *offset = -1; 2012 return false; 2013 } 2014 } 2015 #else 2016 struct _address_to_library_name { 2017 address addr; // input : memory address 2018 size_t buflen; // size of fname 2019 char* fname; // output: library name 2020 address base; // library base addr 2021 }; 2022 2023 static int address_to_library_name_callback(struct dl_phdr_info *info, 2024 size_t size, void *data) { 2025 int i; 2026 bool found = false; 2027 address libbase = NULL; 2028 struct _address_to_library_name * d = (struct _address_to_library_name *)data; 2029 2030 // iterate through all loadable segments 2031 for (i = 0; i < info->dlpi_phnum; i++) { 2032 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); 2033 if (info->dlpi_phdr[i].p_type == PT_LOAD) { 2034 // base address of a library is the lowest address of its loaded 2035 // segments. 2036 if (libbase == NULL || libbase > segbase) { 2037 libbase = segbase; 2038 } 2039 // see if 'addr' is within current segment 2040 if (segbase <= d->addr && 2041 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { 2042 found = true; 2043 } 2044 } 2045 } 2046 2047 // dlpi_name is NULL or empty if the ELF file is executable, return 0 2048 // so dll_address_to_library_name() can fall through to use dladdr() which 2049 // can figure out executable name from argv[0]. 2050 if (found && info->dlpi_name && info->dlpi_name[0]) { 2051 d->base = libbase; 2052 if (d->fname) { 2053 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); 2054 } 2055 return 1; 2056 } 2057 return 0; 2058 } 2059 2060 bool os::dll_address_to_library_name(address addr, char* buf, 2061 int buflen, int* offset) { 2062 Dl_info dlinfo; 2063 struct _address_to_library_name data; 2064 2065 // There is a bug in old glibc dladdr() implementation that it could resolve 2066 // to wrong library name if the .so file has a base address != NULL. Here 2067 // we iterate through the program headers of all loaded libraries to find 2068 // out which library 'addr' really belongs to. This workaround can be 2069 // removed once the minimum requirement for glibc is moved to 2.3.x. 2070 data.addr = addr; 2071 data.fname = buf; 2072 data.buflen = buflen; 2073 data.base = NULL; 2074 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); 2075 2076 if (rslt) { 2077 // buf already contains library name 2078 if (offset) *offset = addr - data.base; 2079 return true; 2080 } else if (dladdr((void*)addr, &dlinfo)){ 2081 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 2082 if (offset) *offset = addr - (address)dlinfo.dli_fbase; 2083 return true; 2084 } else { 2085 if (buf) buf[0] = '\0'; 2086 if (offset) *offset = -1; 2087 return false; 2088 } 2089 } 2090 #endif 2091 2092 // Loads .dll/.so and 2093 // in case of error it checks if .dll/.so was built for the 2094 // same architecture as Hotspot is running on 2095 2096 #ifdef __APPLE__ 2097 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 2098 void * result= ::dlopen(filename, RTLD_LAZY); 2099 if (result != NULL) { 2100 // Successful loading 2101 return result; 2102 } 2103 2104 // Read system error message into ebuf 2105 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 2106 ebuf[ebuflen-1]='\0'; 2107 2108 return NULL; 2109 } 2110 #else 2111 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) 2112 { 2113 void * result= ::dlopen(filename, RTLD_LAZY); 2114 if (result != NULL) { 2115 // Successful loading 2116 return result; 2117 } 2118 2119 Elf32_Ehdr elf_head; 2120 2121 // Read system error message into ebuf 2122 // It may or may not be overwritten below 2123 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 2124 ebuf[ebuflen-1]='\0'; 2125 int diag_msg_max_length=ebuflen-strlen(ebuf); 2126 char* diag_msg_buf=ebuf+strlen(ebuf); 2127 2128 if (diag_msg_max_length==0) { 2129 // No more space in ebuf for additional diagnostics message 2130 return NULL; 2131 } 2132 2133 2134 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 2135 2136 if (file_descriptor < 0) { 2137 // Can't open library, report dlerror() message 2138 return NULL; 2139 } 2140 2141 bool failed_to_read_elf_head= 2142 (sizeof(elf_head)!= 2143 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; 2144 2145 ::close(file_descriptor); 2146 if (failed_to_read_elf_head) { 2147 // file i/o error - report dlerror() msg 2148 return NULL; 2149 } 2150 2151 typedef struct { 2152 Elf32_Half code; // Actual value as defined in elf.h 2153 Elf32_Half compat_class; // Compatibility of archs at VM's sense 2154 char elf_class; // 32 or 64 bit 2155 char endianess; // MSB or LSB 2156 char* name; // String representation 2157 } arch_t; 2158 2159 #ifndef EM_486 2160 #define EM_486 6 /* Intel 80486 */ 2161 #endif 2162 2163 #ifndef EM_MIPS_RS3_LE 2164 #define EM_MIPS_RS3_LE 10 /* MIPS */ 2165 #endif 2166 2167 #ifndef EM_PPC64 2168 #define EM_PPC64 21 /* PowerPC64 */ 2169 #endif 2170 2171 #ifndef EM_S390 2172 #define EM_S390 22 /* IBM System/390 */ 2173 #endif 2174 2175 #ifndef EM_IA_64 2176 #define EM_IA_64 50 /* HP/Intel IA-64 */ 2177 #endif 2178 2179 #ifndef EM_X86_64 2180 #define EM_X86_64 62 /* AMD x86-64 */ 2181 #endif 2182 2183 static const arch_t arch_array[]={ 2184 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 2185 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 2186 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 2187 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 2188 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 2189 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 2190 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 2191 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 2192 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 2193 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 2194 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, 2195 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, 2196 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, 2197 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, 2198 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, 2199 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} 2200 }; 2201 2202 #if (defined IA32) 2203 static Elf32_Half running_arch_code=EM_386; 2204 #elif (defined AMD64) 2205 static Elf32_Half running_arch_code=EM_X86_64; 2206 #elif (defined IA64) 2207 static Elf32_Half running_arch_code=EM_IA_64; 2208 #elif (defined __sparc) && (defined _LP64) 2209 static Elf32_Half running_arch_code=EM_SPARCV9; 2210 #elif (defined __sparc) && (!defined _LP64) 2211 static Elf32_Half running_arch_code=EM_SPARC; 2212 #elif (defined __powerpc64__) 2213 static Elf32_Half running_arch_code=EM_PPC64; 2214 #elif (defined __powerpc__) 2215 static Elf32_Half running_arch_code=EM_PPC; 2216 #elif (defined ARM) 2217 static Elf32_Half running_arch_code=EM_ARM; 2218 #elif (defined S390) 2219 static Elf32_Half running_arch_code=EM_S390; 2220 #elif (defined ALPHA) 2221 static Elf32_Half running_arch_code=EM_ALPHA; 2222 #elif (defined MIPSEL) 2223 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; 2224 #elif (defined PARISC) 2225 static Elf32_Half running_arch_code=EM_PARISC; 2226 #elif (defined MIPS) 2227 static Elf32_Half running_arch_code=EM_MIPS; 2228 #elif (defined M68K) 2229 static Elf32_Half running_arch_code=EM_68K; 2230 #else 2231 #error Method os::dll_load requires that one of following is defined:\ 2232 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K 2233 #endif 2234 2235 // Identify compatability class for VM's architecture and library's architecture 2236 // Obtain string descriptions for architectures 2237 2238 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 2239 int running_arch_index=-1; 2240 2241 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { 2242 if (running_arch_code == arch_array[i].code) { 2243 running_arch_index = i; 2244 } 2245 if (lib_arch.code == arch_array[i].code) { 2246 lib_arch.compat_class = arch_array[i].compat_class; 2247 lib_arch.name = arch_array[i].name; 2248 } 2249 } 2250 2251 assert(running_arch_index != -1, 2252 "Didn't find running architecture code (running_arch_code) in arch_array"); 2253 if (running_arch_index == -1) { 2254 // Even though running architecture detection failed 2255 // we may still continue with reporting dlerror() message 2256 return NULL; 2257 } 2258 2259 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 2260 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 2261 return NULL; 2262 } 2263 2264 #ifndef S390 2265 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 2266 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 2267 return NULL; 2268 } 2269 #endif // !S390 2270 2271 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 2272 if ( lib_arch.name!=NULL ) { 2273 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 2274 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 2275 lib_arch.name, arch_array[running_arch_index].name); 2276 } else { 2277 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 2278 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 2279 lib_arch.code, 2280 arch_array[running_arch_index].name); 2281 } 2282 } 2283 2284 return NULL; 2285 } 2286 #endif /* !__APPLE__ */ 2287 2288 // XXX: Do we need a lock around this as per Linux? 2289 void* os::dll_lookup(void* handle, const char* name) { 2290 return dlsym(handle, name); 2291 } 2292 2293 2294 static bool _print_ascii_file(const char* filename, outputStream* st) { 2295 int fd = ::open(filename, O_RDONLY); 2296 if (fd == -1) { 2297 return false; 2298 } 2299 2300 char buf[32]; 2301 int bytes; 2302 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 2303 st->print_raw(buf, bytes); 2304 } 2305 2306 ::close(fd); 2307 2308 return true; 2309 } 2310 2311 void os::print_dll_info(outputStream *st) { 2312 st->print_cr("Dynamic libraries:"); 2313 #ifdef _ALLBSD_SOURCE 2314 #ifdef RTLD_DI_LINKMAP 2315 Dl_info dli; 2316 void *handle; 2317 Link_map *map; 2318 Link_map *p; 2319 2320 if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) { 2321 st->print_cr("Error: Cannot print dynamic libraries."); 2322 return; 2323 } 2324 handle = dlopen(dli.dli_fname, RTLD_LAZY); 2325 if (handle == NULL) { 2326 st->print_cr("Error: Cannot print dynamic libraries."); 2327 return; 2328 } 2329 dlinfo(handle, RTLD_DI_LINKMAP, &map); 2330 if (map == NULL) { 2331 st->print_cr("Error: Cannot print dynamic libraries."); 2332 return; 2333 } 2334 2335 while (map->l_prev != NULL) 2336 map = map->l_prev; 2337 2338 while (map != NULL) { 2339 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); 2340 map = map->l_next; 2341 } 2342 2343 dlclose(handle); 2344 #elif defined(__APPLE__) 2345 uint32_t count; 2346 uint32_t i; 2347 2348 count = _dyld_image_count(); 2349 for (i = 1; i < count; i++) { 2350 const char *name = _dyld_get_image_name(i); 2351 intptr_t slide = _dyld_get_image_vmaddr_slide(i); 2352 st->print_cr(PTR_FORMAT " \t%s", slide, name); 2353 } 2354 #else 2355 st->print_cr("Error: Cannot print dynamic libraries."); 2356 #endif 2357 #else 2358 char fname[32]; 2359 pid_t pid = os::Bsd::gettid(); 2360 2361 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); 2362 2363 if (!_print_ascii_file(fname, st)) { 2364 st->print("Can not get library information for pid = %d\n", pid); 2365 } 2366 #endif 2367 } 2368 2369 void os::print_os_info_brief(outputStream* st) { 2370 st->print("Bsd"); 2371 2372 os::Posix::print_uname_info(st); 2373 } 2374 2375 void os::print_os_info(outputStream* st) { 2376 st->print("OS:"); 2377 st->print("Bsd"); 2378 2379 os::Posix::print_uname_info(st); 2380 2381 os::Posix::print_rlimit_info(st); 2382 2383 os::Posix::print_load_average(st); 2384 } 2385 2386 void os::pd_print_cpu_info(outputStream* st) { 2387 // Nothing to do for now. 2388 } 2389 2390 void os::print_memory_info(outputStream* st) { 2391 2392 st->print("Memory:"); 2393 st->print(" %dk page", os::vm_page_size()>>10); 2394 2395 #ifndef _ALLBSD_SOURCE 2396 // values in struct sysinfo are "unsigned long" 2397 struct sysinfo si; 2398 sysinfo(&si); 2399 #endif 2400 2401 st->print(", physical " UINT64_FORMAT "k", 2402 os::physical_memory() >> 10); 2403 st->print("(" UINT64_FORMAT "k free)", 2404 os::available_memory() >> 10); 2405 #ifndef _ALLBSD_SOURCE 2406 st->print(", swap " UINT64_FORMAT "k", 2407 ((jlong)si.totalswap * si.mem_unit) >> 10); 2408 st->print("(" UINT64_FORMAT "k free)", 2409 ((jlong)si.freeswap * si.mem_unit) >> 10); 2410 #endif 2411 st->cr(); 2412 2413 // meminfo 2414 st->print("\n/proc/meminfo:\n"); 2415 _print_ascii_file("/proc/meminfo", st); 2416 st->cr(); 2417 } 2418 2419 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific 2420 // but they're the same for all the bsd arch that we support 2421 // and they're the same for solaris but there's no common place to put this. 2422 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR", 2423 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG", 2424 "ILL_COPROC", "ILL_BADSTK" }; 2425 2426 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV", 2427 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES", 2428 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" }; 2429 2430 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" }; 2431 2432 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" }; 2433 2434 void os::print_siginfo(outputStream* st, void* siginfo) { 2435 st->print("siginfo:"); 2436 2437 const int buflen = 100; 2438 char buf[buflen]; 2439 siginfo_t *si = (siginfo_t*)siginfo; 2440 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen)); 2441 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) { 2442 st->print("si_errno=%s", buf); 2443 } else { 2444 st->print("si_errno=%d", si->si_errno); 2445 } 2446 const int c = si->si_code; 2447 assert(c > 0, "unexpected si_code"); 2448 switch (si->si_signo) { 2449 case SIGILL: 2450 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]); 2451 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2452 break; 2453 case SIGFPE: 2454 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]); 2455 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2456 break; 2457 case SIGSEGV: 2458 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]); 2459 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2460 break; 2461 case SIGBUS: 2462 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]); 2463 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2464 break; 2465 default: 2466 st->print(", si_code=%d", si->si_code); 2467 // no si_addr 2468 } 2469 2470 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 2471 UseSharedSpaces) { 2472 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2473 if (mapinfo->is_in_shared_space(si->si_addr)) { 2474 st->print("\n\nError accessing class data sharing archive." \ 2475 " Mapped file inaccessible during execution, " \ 2476 " possible disk/network problem."); 2477 } 2478 } 2479 st->cr(); 2480 } 2481 2482 2483 static void print_signal_handler(outputStream* st, int sig, 2484 char* buf, size_t buflen); 2485 2486 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 2487 st->print_cr("Signal Handlers:"); 2488 print_signal_handler(st, SIGSEGV, buf, buflen); 2489 print_signal_handler(st, SIGBUS , buf, buflen); 2490 print_signal_handler(st, SIGFPE , buf, buflen); 2491 print_signal_handler(st, SIGPIPE, buf, buflen); 2492 print_signal_handler(st, SIGXFSZ, buf, buflen); 2493 print_signal_handler(st, SIGILL , buf, buflen); 2494 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 2495 print_signal_handler(st, SR_signum, buf, buflen); 2496 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 2497 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 2498 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 2499 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 2500 } 2501 2502 static char saved_jvm_path[MAXPATHLEN] = {0}; 2503 2504 // Find the full path to the current module, libjvm or libjvm_g 2505 void os::jvm_path(char *buf, jint buflen) { 2506 // Error checking. 2507 if (buflen < MAXPATHLEN) { 2508 assert(false, "must use a large-enough buffer"); 2509 buf[0] = '\0'; 2510 return; 2511 } 2512 // Lazy resolve the path to current module. 2513 if (saved_jvm_path[0] != 0) { 2514 strcpy(buf, saved_jvm_path); 2515 return; 2516 } 2517 2518 char dli_fname[MAXPATHLEN]; 2519 bool ret = dll_address_to_library_name( 2520 CAST_FROM_FN_PTR(address, os::jvm_path), 2521 dli_fname, sizeof(dli_fname), NULL); 2522 assert(ret != 0, "cannot locate libjvm"); 2523 char *rp = realpath(dli_fname, buf); 2524 if (rp == NULL) 2525 return; 2526 2527 if (Arguments::created_by_gamma_launcher()) { 2528 // Support for the gamma launcher. Typical value for buf is 2529 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm". If "/jre/lib/" appears at 2530 // the right place in the string, then assume we are installed in a JDK and 2531 // we're done. Otherwise, check for a JAVA_HOME environment variable and 2532 // construct a path to the JVM being overridden. 2533 2534 const char *p = buf + strlen(buf) - 1; 2535 for (int count = 0; p > buf && count < 5; ++count) { 2536 for (--p; p > buf && *p != '/'; --p) 2537 /* empty */ ; 2538 } 2539 2540 if (strncmp(p, "/jre/lib/", 9) != 0) { 2541 // Look for JAVA_HOME in the environment. 2542 char* java_home_var = ::getenv("JAVA_HOME"); 2543 if (java_home_var != NULL && java_home_var[0] != 0) { 2544 char* jrelib_p; 2545 int len; 2546 2547 // Check the current module name "libjvm" or "libjvm_g". 2548 p = strrchr(buf, '/'); 2549 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2550 p = strstr(p, "_g") ? "_g" : ""; 2551 2552 rp = realpath(java_home_var, buf); 2553 if (rp == NULL) 2554 return; 2555 2556 // determine if this is a legacy image or modules image 2557 // modules image doesn't have "jre" subdirectory 2558 len = strlen(buf); 2559 jrelib_p = buf + len; 2560 2561 // Add the appropriate library subdir 2562 snprintf(jrelib_p, buflen-len, "/jre/lib"); 2563 if (0 != access(buf, F_OK)) { 2564 snprintf(jrelib_p, buflen-len, "/lib"); 2565 } 2566 2567 // Add the appropriate client or server subdir 2568 len = strlen(buf); 2569 jrelib_p = buf + len; 2570 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT); 2571 if (0 != access(buf, F_OK)) { 2572 snprintf(jrelib_p, buflen-len, ""); 2573 } 2574 2575 // If the path exists within JAVA_HOME, add the JVM library name 2576 // to complete the path to JVM being overridden. Otherwise fallback 2577 // to the path to the current library. 2578 if (0 == access(buf, F_OK)) { 2579 // Use current module name "libjvm[_g]" instead of 2580 // "libjvm"debug_only("_g")"" since for fastdebug version 2581 // we should have "libjvm" but debug_only("_g") adds "_g"! 2582 len = strlen(buf); 2583 snprintf(buf + len, buflen-len, "/libjvm%s%s", p, JNI_LIB_SUFFIX); 2584 } else { 2585 // Fall back to path of current library 2586 rp = realpath(dli_fname, buf); 2587 if (rp == NULL) 2588 return; 2589 } 2590 } 2591 } 2592 } 2593 2594 strcpy(saved_jvm_path, buf); 2595 } 2596 2597 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2598 // no prefix required, not even "_" 2599 } 2600 2601 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2602 // no suffix required 2603 } 2604 2605 //////////////////////////////////////////////////////////////////////////////// 2606 // sun.misc.Signal support 2607 2608 static volatile jint sigint_count = 0; 2609 2610 static void 2611 UserHandler(int sig, void *siginfo, void *context) { 2612 // 4511530 - sem_post is serialized and handled by the manager thread. When 2613 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 2614 // don't want to flood the manager thread with sem_post requests. 2615 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) 2616 return; 2617 2618 // Ctrl-C is pressed during error reporting, likely because the error 2619 // handler fails to abort. Let VM die immediately. 2620 if (sig == SIGINT && is_error_reported()) { 2621 os::die(); 2622 } 2623 2624 os::signal_notify(sig); 2625 } 2626 2627 void* os::user_handler() { 2628 return CAST_FROM_FN_PTR(void*, UserHandler); 2629 } 2630 2631 extern "C" { 2632 typedef void (*sa_handler_t)(int); 2633 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2634 } 2635 2636 void* os::signal(int signal_number, void* handler) { 2637 struct sigaction sigAct, oldSigAct; 2638 2639 sigfillset(&(sigAct.sa_mask)); 2640 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 2641 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2642 2643 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2644 // -1 means registration failed 2645 return (void *)-1; 2646 } 2647 2648 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2649 } 2650 2651 void os::signal_raise(int signal_number) { 2652 ::raise(signal_number); 2653 } 2654 2655 /* 2656 * The following code is moved from os.cpp for making this 2657 * code platform specific, which it is by its very nature. 2658 */ 2659 2660 // Will be modified when max signal is changed to be dynamic 2661 int os::sigexitnum_pd() { 2662 return NSIG; 2663 } 2664 2665 // a counter for each possible signal value 2666 static volatile jint pending_signals[NSIG+1] = { 0 }; 2667 2668 // Bsd(POSIX) specific hand shaking semaphore. 2669 #ifdef __APPLE__ 2670 typedef semaphore_t os_semaphore_t; 2671 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value) 2672 #define SEM_WAIT(sem) semaphore_wait(sem) 2673 #define SEM_POST(sem) semaphore_signal(sem) 2674 #define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem) 2675 #else 2676 typedef sem_t os_semaphore_t; 2677 #define SEM_INIT(sem, value) sem_init(&sem, 0, value) 2678 #define SEM_WAIT(sem) sem_wait(&sem) 2679 #define SEM_POST(sem) sem_post(&sem) 2680 #define SEM_DESTROY(sem) sem_destroy(&sem) 2681 #endif 2682 2683 class Semaphore : public StackObj { 2684 public: 2685 Semaphore(); 2686 ~Semaphore(); 2687 void signal(); 2688 void wait(); 2689 bool trywait(); 2690 bool timedwait(unsigned int sec, int nsec); 2691 private: 2692 jlong currenttime() const; 2693 semaphore_t _semaphore; 2694 }; 2695 2696 Semaphore::Semaphore() : _semaphore(0) { 2697 SEM_INIT(_semaphore, 0); 2698 } 2699 2700 Semaphore::~Semaphore() { 2701 SEM_DESTROY(_semaphore); 2702 } 2703 2704 void Semaphore::signal() { 2705 SEM_POST(_semaphore); 2706 } 2707 2708 void Semaphore::wait() { 2709 SEM_WAIT(_semaphore); 2710 } 2711 2712 jlong Semaphore::currenttime() const { 2713 struct timeval tv; 2714 gettimeofday(&tv, NULL); 2715 return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000); 2716 } 2717 2718 #ifdef __APPLE__ 2719 bool Semaphore::trywait() { 2720 return timedwait(0, 0); 2721 } 2722 2723 bool Semaphore::timedwait(unsigned int sec, int nsec) { 2724 kern_return_t kr = KERN_ABORTED; 2725 mach_timespec_t waitspec; 2726 waitspec.tv_sec = sec; 2727 waitspec.tv_nsec = nsec; 2728 2729 jlong starttime = currenttime(); 2730 2731 kr = semaphore_timedwait(_semaphore, waitspec); 2732 while (kr == KERN_ABORTED) { 2733 jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec; 2734 2735 jlong current = currenttime(); 2736 jlong passedtime = current - starttime; 2737 2738 if (passedtime >= totalwait) { 2739 waitspec.tv_sec = 0; 2740 waitspec.tv_nsec = 0; 2741 } else { 2742 jlong waittime = totalwait - (current - starttime); 2743 waitspec.tv_sec = waittime / NANOSECS_PER_SEC; 2744 waitspec.tv_nsec = waittime % NANOSECS_PER_SEC; 2745 } 2746 2747 kr = semaphore_timedwait(_semaphore, waitspec); 2748 } 2749 2750 return kr == KERN_SUCCESS; 2751 } 2752 2753 #else 2754 2755 bool Semaphore::trywait() { 2756 return sem_trywait(&_semaphore) == 0; 2757 } 2758 2759 bool Semaphore::timedwait(unsigned int sec, int nsec) { 2760 struct timespec ts; 2761 jlong endtime = unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec); 2762 2763 while (1) { 2764 int result = sem_timedwait(&_semaphore, &ts); 2765 if (result == 0) { 2766 return true; 2767 } else if (errno == EINTR) { 2768 continue; 2769 } else if (errno == ETIMEDOUT) { 2770 return false; 2771 } else { 2772 return false; 2773 } 2774 } 2775 } 2776 2777 #endif // __APPLE__ 2778 2779 static os_semaphore_t sig_sem; 2780 static Semaphore sr_semaphore; 2781 2782 void os::signal_init_pd() { 2783 // Initialize signal structures 2784 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2785 2786 // Initialize signal semaphore 2787 ::SEM_INIT(sig_sem, 0); 2788 } 2789 2790 void os::signal_notify(int sig) { 2791 Atomic::inc(&pending_signals[sig]); 2792 ::SEM_POST(sig_sem); 2793 } 2794 2795 static int check_pending_signals(bool wait) { 2796 Atomic::store(0, &sigint_count); 2797 for (;;) { 2798 for (int i = 0; i < NSIG + 1; i++) { 2799 jint n = pending_signals[i]; 2800 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2801 return i; 2802 } 2803 } 2804 if (!wait) { 2805 return -1; 2806 } 2807 JavaThread *thread = JavaThread::current(); 2808 ThreadBlockInVM tbivm(thread); 2809 2810 bool threadIsSuspended; 2811 do { 2812 thread->set_suspend_equivalent(); 2813 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2814 ::SEM_WAIT(sig_sem); 2815 2816 // were we externally suspended while we were waiting? 2817 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2818 if (threadIsSuspended) { 2819 // 2820 // The semaphore has been incremented, but while we were waiting 2821 // another thread suspended us. We don't want to continue running 2822 // while suspended because that would surprise the thread that 2823 // suspended us. 2824 // 2825 ::SEM_POST(sig_sem); 2826 2827 thread->java_suspend_self(); 2828 } 2829 } while (threadIsSuspended); 2830 } 2831 } 2832 2833 int os::signal_lookup() { 2834 return check_pending_signals(false); 2835 } 2836 2837 int os::signal_wait() { 2838 return check_pending_signals(true); 2839 } 2840 2841 //////////////////////////////////////////////////////////////////////////////// 2842 // Virtual Memory 2843 2844 int os::vm_page_size() { 2845 // Seems redundant as all get out 2846 assert(os::Bsd::page_size() != -1, "must call os::init"); 2847 return os::Bsd::page_size(); 2848 } 2849 2850 // Solaris allocates memory by pages. 2851 int os::vm_allocation_granularity() { 2852 assert(os::Bsd::page_size() != -1, "must call os::init"); 2853 return os::Bsd::page_size(); 2854 } 2855 2856 // Rationale behind this function: 2857 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2858 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2859 // samples for JITted code. Here we create private executable mapping over the code cache 2860 // and then we can use standard (well, almost, as mapping can change) way to provide 2861 // info for the reporting script by storing timestamp and location of symbol 2862 void bsd_wrap_code(char* base, size_t size) { 2863 static volatile jint cnt = 0; 2864 2865 if (!UseOprofile) { 2866 return; 2867 } 2868 2869 char buf[PATH_MAX + 1]; 2870 int num = Atomic::add(1, &cnt); 2871 2872 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d", 2873 os::get_temp_directory(), os::current_process_id(), num); 2874 unlink(buf); 2875 2876 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); 2877 2878 if (fd != -1) { 2879 off_t rv = ::lseek(fd, size-2, SEEK_SET); 2880 if (rv != (off_t)-1) { 2881 if (::write(fd, "", 1) == 1) { 2882 mmap(base, size, 2883 PROT_READ|PROT_WRITE|PROT_EXEC, 2884 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2885 } 2886 } 2887 ::close(fd); 2888 unlink(buf); 2889 } 2890 } 2891 2892 static void warn_fail_commit_memory(char* addr, size_t size, bool exec, 2893 int err) { 2894 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2895 ", %d) failed; error='%s' (errno=%d)", addr, size, exec, 2896 strerror(err), err); 2897 } 2898 2899 // NOTE: Bsd kernel does not really reserve the pages for us. 2900 // All it does is to check if there are enough free pages 2901 // left at the time of mmap(). This could be a potential 2902 // problem. 2903 bool os::pd_commit_memory(char* addr, size_t size, bool exec) { 2904 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2905 #ifdef __OpenBSD__ 2906 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 2907 if (::mprotect(addr, size, prot) == 0) { 2908 return true; 2909 } 2910 #else 2911 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, 2912 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2913 if (res != (uintptr_t) MAP_FAILED) { 2914 return true; 2915 } 2916 #endif 2917 2918 // Warn about any commit errors we see in non-product builds just 2919 // in case mmap() doesn't work as described on the man page. 2920 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);) 2921 2922 return false; 2923 } 2924 2925 #ifndef _ALLBSD_SOURCE 2926 // Define MAP_HUGETLB here so we can build HotSpot on old systems. 2927 #ifndef MAP_HUGETLB 2928 #define MAP_HUGETLB 0x40000 2929 #endif 2930 2931 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems. 2932 #ifndef MADV_HUGEPAGE 2933 #define MADV_HUGEPAGE 14 2934 #endif 2935 #endif 2936 2937 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 2938 bool exec) { 2939 #ifndef _ALLBSD_SOURCE 2940 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) { 2941 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2942 uintptr_t res = 2943 (uintptr_t) ::mmap(addr, size, prot, 2944 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS|MAP_HUGETLB, 2945 -1, 0); 2946 return res != (uintptr_t) MAP_FAILED; 2947 } 2948 #endif 2949 2950 // alignment_hint is ignored on this OS 2951 return pd_commit_memory(addr, size, exec); 2952 } 2953 2954 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, 2955 const char* mesg) { 2956 assert(mesg != NULL, "mesg must be specified"); 2957 if (!pd_commit_memory(addr, size, exec)) { 2958 // add extra info in product mode for vm_exit_out_of_memory(): 2959 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);) 2960 vm_exit_out_of_memory(size, mesg); 2961 } 2962 } 2963 2964 void os::pd_commit_memory_or_exit(char* addr, size_t size, 2965 size_t alignment_hint, bool exec, 2966 const char* mesg) { 2967 // alignment_hint is ignored on this OS 2968 pd_commit_memory_or_exit(addr, size, exec, mesg); 2969 } 2970 2971 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2972 #ifndef _ALLBSD_SOURCE 2973 if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) { 2974 // We don't check the return value: madvise(MADV_HUGEPAGE) may not 2975 // be supported or the memory may already be backed by huge pages. 2976 ::madvise(addr, bytes, MADV_HUGEPAGE); 2977 } 2978 #endif 2979 } 2980 2981 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { 2982 ::madvise(addr, bytes, MADV_DONTNEED); 2983 } 2984 2985 void os::numa_make_global(char *addr, size_t bytes) { 2986 } 2987 2988 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2989 } 2990 2991 bool os::numa_topology_changed() { return false; } 2992 2993 size_t os::numa_get_groups_num() { 2994 return 1; 2995 } 2996 2997 int os::numa_get_group_id() { 2998 return 0; 2999 } 3000 3001 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 3002 if (size > 0) { 3003 ids[0] = 0; 3004 return 1; 3005 } 3006 return 0; 3007 } 3008 3009 bool os::get_page_info(char *start, page_info* info) { 3010 return false; 3011 } 3012 3013 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 3014 return end; 3015 } 3016 3017 #ifndef _ALLBSD_SOURCE 3018 // Something to do with the numa-aware allocator needs these symbols 3019 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { } 3020 extern "C" JNIEXPORT void numa_error(char *where) { } 3021 extern "C" JNIEXPORT int fork1() { return fork(); } 3022 3023 3024 // If we are running with libnuma version > 2, then we should 3025 // be trying to use symbols with versions 1.1 3026 // If we are running with earlier version, which did not have symbol versions, 3027 // we should use the base version. 3028 void* os::Bsd::libnuma_dlsym(void* handle, const char *name) { 3029 void *f = dlvsym(handle, name, "libnuma_1.1"); 3030 if (f == NULL) { 3031 f = dlsym(handle, name); 3032 } 3033 return f; 3034 } 3035 3036 bool os::Bsd::libnuma_init() { 3037 // sched_getcpu() should be in libc. 3038 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 3039 dlsym(RTLD_DEFAULT, "sched_getcpu"))); 3040 3041 if (sched_getcpu() != -1) { // Does it work? 3042 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); 3043 if (handle != NULL) { 3044 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, 3045 libnuma_dlsym(handle, "numa_node_to_cpus"))); 3046 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, 3047 libnuma_dlsym(handle, "numa_max_node"))); 3048 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, 3049 libnuma_dlsym(handle, "numa_available"))); 3050 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, 3051 libnuma_dlsym(handle, "numa_tonode_memory"))); 3052 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, 3053 libnuma_dlsym(handle, "numa_interleave_memory"))); 3054 3055 3056 if (numa_available() != -1) { 3057 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes")); 3058 // Create a cpu -> node mapping 3059 _cpu_to_node = new (ResourceObj::C_HEAP) GrowableArray<int>(0, true); 3060 rebuild_cpu_to_node_map(); 3061 return true; 3062 } 3063 } 3064 } 3065 return false; 3066 } 3067 3068 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. 3069 // The table is later used in get_node_by_cpu(). 3070 void os::Bsd::rebuild_cpu_to_node_map() { 3071 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure 3072 // in libnuma (possible values are starting from 16, 3073 // and continuing up with every other power of 2, but less 3074 // than the maximum number of CPUs supported by kernel), and 3075 // is a subject to change (in libnuma version 2 the requirements 3076 // are more reasonable) we'll just hardcode the number they use 3077 // in the library. 3078 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; 3079 3080 size_t cpu_num = os::active_processor_count(); 3081 size_t cpu_map_size = NCPUS / BitsPerCLong; 3082 size_t cpu_map_valid_size = 3083 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); 3084 3085 cpu_to_node()->clear(); 3086 cpu_to_node()->at_grow(cpu_num - 1); 3087 size_t node_num = numa_get_groups_num(); 3088 3089 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size); 3090 for (size_t i = 0; i < node_num; i++) { 3091 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { 3092 for (size_t j = 0; j < cpu_map_valid_size; j++) { 3093 if (cpu_map[j] != 0) { 3094 for (size_t k = 0; k < BitsPerCLong; k++) { 3095 if (cpu_map[j] & (1UL << k)) { 3096 cpu_to_node()->at_put(j * BitsPerCLong + k, i); 3097 } 3098 } 3099 } 3100 } 3101 } 3102 } 3103 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); 3104 } 3105 3106 int os::Bsd::get_node_by_cpu(int cpu_id) { 3107 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { 3108 return cpu_to_node()->at(cpu_id); 3109 } 3110 return -1; 3111 } 3112 3113 GrowableArray<int>* os::Bsd::_cpu_to_node; 3114 os::Bsd::sched_getcpu_func_t os::Bsd::_sched_getcpu; 3115 os::Bsd::numa_node_to_cpus_func_t os::Bsd::_numa_node_to_cpus; 3116 os::Bsd::numa_max_node_func_t os::Bsd::_numa_max_node; 3117 os::Bsd::numa_available_func_t os::Bsd::_numa_available; 3118 os::Bsd::numa_tonode_memory_func_t os::Bsd::_numa_tonode_memory; 3119 os::Bsd::numa_interleave_memory_func_t os::Bsd::_numa_interleave_memory; 3120 unsigned long* os::Bsd::_numa_all_nodes; 3121 #endif 3122 3123 bool os::pd_uncommit_memory(char* addr, size_t size) { 3124 #ifdef __OpenBSD__ 3125 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 3126 return ::mprotect(addr, size, PROT_NONE) == 0; 3127 #else 3128 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, 3129 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); 3130 return res != (uintptr_t) MAP_FAILED; 3131 #endif 3132 } 3133 3134 bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 3135 return os::commit_memory(addr, size, !ExecMem); 3136 } 3137 3138 // If this is a growable mapping, remove the guard pages entirely by 3139 // munmap()ping them. If not, just call uncommit_memory(). 3140 bool os::remove_stack_guard_pages(char* addr, size_t size) { 3141 return os::uncommit_memory(addr, size); 3142 } 3143 3144 static address _highest_vm_reserved_address = NULL; 3145 3146 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 3147 // at 'requested_addr'. If there are existing memory mappings at the same 3148 // location, however, they will be overwritten. If 'fixed' is false, 3149 // 'requested_addr' is only treated as a hint, the return value may or 3150 // may not start from the requested address. Unlike Bsd mmap(), this 3151 // function returns NULL to indicate failure. 3152 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 3153 char * addr; 3154 int flags; 3155 3156 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 3157 if (fixed) { 3158 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address"); 3159 flags |= MAP_FIXED; 3160 } 3161 3162 // Map uncommitted pages PROT_READ and PROT_WRITE, change access 3163 // to PROT_EXEC if executable when we commit the page. 3164 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE, 3165 flags, -1, 0); 3166 3167 if (addr != MAP_FAILED) { 3168 // anon_mmap() should only get called during VM initialization, 3169 // don't need lock (actually we can skip locking even it can be called 3170 // from multiple threads, because _highest_vm_reserved_address is just a 3171 // hint about the upper limit of non-stack memory regions.) 3172 if ((address)addr + bytes > _highest_vm_reserved_address) { 3173 _highest_vm_reserved_address = (address)addr + bytes; 3174 } 3175 } 3176 3177 return addr == MAP_FAILED ? NULL : addr; 3178 } 3179 3180 // Don't update _highest_vm_reserved_address, because there might be memory 3181 // regions above addr + size. If so, releasing a memory region only creates 3182 // a hole in the address space, it doesn't help prevent heap-stack collision. 3183 // 3184 static int anon_munmap(char * addr, size_t size) { 3185 return ::munmap(addr, size) == 0; 3186 } 3187 3188 char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 3189 size_t alignment_hint) { 3190 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 3191 } 3192 3193 bool os::pd_release_memory(char* addr, size_t size) { 3194 return anon_munmap(addr, size); 3195 } 3196 3197 static address highest_vm_reserved_address() { 3198 return _highest_vm_reserved_address; 3199 } 3200 3201 static bool bsd_mprotect(char* addr, size_t size, int prot) { 3202 // Bsd wants the mprotect address argument to be page aligned. 3203 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size()); 3204 3205 // According to SUSv3, mprotect() should only be used with mappings 3206 // established by mmap(), and mmap() always maps whole pages. Unaligned 3207 // 'addr' likely indicates problem in the VM (e.g. trying to change 3208 // protection of malloc'ed or statically allocated memory). Check the 3209 // caller if you hit this assert. 3210 assert(addr == bottom, "sanity check"); 3211 3212 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size()); 3213 return ::mprotect(bottom, size, prot) == 0; 3214 } 3215 3216 // Set protections specified 3217 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 3218 bool is_committed) { 3219 unsigned int p = 0; 3220 switch (prot) { 3221 case MEM_PROT_NONE: p = PROT_NONE; break; 3222 case MEM_PROT_READ: p = PROT_READ; break; 3223 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 3224 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 3225 default: 3226 ShouldNotReachHere(); 3227 } 3228 // is_committed is unused. 3229 return bsd_mprotect(addr, bytes, p); 3230 } 3231 3232 bool os::guard_memory(char* addr, size_t size) { 3233 return bsd_mprotect(addr, size, PROT_NONE); 3234 } 3235 3236 bool os::unguard_memory(char* addr, size_t size) { 3237 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE); 3238 } 3239 3240 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) { 3241 bool result = false; 3242 #ifndef _ALLBSD_SOURCE 3243 void *p = mmap (NULL, page_size, PROT_READ|PROT_WRITE, 3244 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB, 3245 -1, 0); 3246 3247 if (p != (void *) -1) { 3248 // We don't know if this really is a huge page or not. 3249 FILE *fp = fopen("/proc/self/maps", "r"); 3250 if (fp) { 3251 while (!feof(fp)) { 3252 char chars[257]; 3253 long x = 0; 3254 if (fgets(chars, sizeof(chars), fp)) { 3255 if (sscanf(chars, "%lx-%*x", &x) == 1 3256 && x == (long)p) { 3257 if (strstr (chars, "hugepage")) { 3258 result = true; 3259 break; 3260 } 3261 } 3262 } 3263 } 3264 fclose(fp); 3265 } 3266 munmap (p, page_size); 3267 if (result) 3268 return true; 3269 } 3270 3271 if (warn) { 3272 warning("HugeTLBFS is not supported by the operating system."); 3273 } 3274 #endif 3275 3276 return result; 3277 } 3278 3279 /* 3280 * Set the coredump_filter bits to include largepages in core dump (bit 6) 3281 * 3282 * From the coredump_filter documentation: 3283 * 3284 * - (bit 0) anonymous private memory 3285 * - (bit 1) anonymous shared memory 3286 * - (bit 2) file-backed private memory 3287 * - (bit 3) file-backed shared memory 3288 * - (bit 4) ELF header pages in file-backed private memory areas (it is 3289 * effective only if the bit 2 is cleared) 3290 * - (bit 5) hugetlb private memory 3291 * - (bit 6) hugetlb shared memory 3292 */ 3293 static void set_coredump_filter(void) { 3294 FILE *f; 3295 long cdm; 3296 3297 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) { 3298 return; 3299 } 3300 3301 if (fscanf(f, "%lx", &cdm) != 1) { 3302 fclose(f); 3303 return; 3304 } 3305 3306 rewind(f); 3307 3308 if ((cdm & LARGEPAGES_BIT) == 0) { 3309 cdm |= LARGEPAGES_BIT; 3310 fprintf(f, "%#lx", cdm); 3311 } 3312 3313 fclose(f); 3314 } 3315 3316 // Large page support 3317 3318 static size_t _large_page_size = 0; 3319 3320 void os::large_page_init() { 3321 #ifndef _ALLBSD_SOURCE 3322 if (!UseLargePages) { 3323 UseHugeTLBFS = false; 3324 UseSHM = false; 3325 return; 3326 } 3327 3328 if (FLAG_IS_DEFAULT(UseHugeTLBFS) && FLAG_IS_DEFAULT(UseSHM)) { 3329 // If UseLargePages is specified on the command line try both methods, 3330 // if it's default, then try only HugeTLBFS. 3331 if (FLAG_IS_DEFAULT(UseLargePages)) { 3332 UseHugeTLBFS = true; 3333 } else { 3334 UseHugeTLBFS = UseSHM = true; 3335 } 3336 } 3337 3338 if (LargePageSizeInBytes) { 3339 _large_page_size = LargePageSizeInBytes; 3340 } else { 3341 // large_page_size on Bsd is used to round up heap size. x86 uses either 3342 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) 3343 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use 3344 // page as large as 256M. 3345 // 3346 // Here we try to figure out page size by parsing /proc/meminfo and looking 3347 // for a line with the following format: 3348 // Hugepagesize: 2048 kB 3349 // 3350 // If we can't determine the value (e.g. /proc is not mounted, or the text 3351 // format has been changed), we'll use the largest page size supported by 3352 // the processor. 3353 3354 #ifndef ZERO 3355 _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M) 3356 ARM_ONLY(2 * M) PPC_ONLY(4 * M); 3357 #endif // ZERO 3358 3359 FILE *fp = fopen("/proc/meminfo", "r"); 3360 if (fp) { 3361 while (!feof(fp)) { 3362 int x = 0; 3363 char buf[16]; 3364 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { 3365 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { 3366 _large_page_size = x * K; 3367 break; 3368 } 3369 } else { 3370 // skip to next line 3371 for (;;) { 3372 int ch = fgetc(fp); 3373 if (ch == EOF || ch == (int)'\n') break; 3374 } 3375 } 3376 } 3377 fclose(fp); 3378 } 3379 } 3380 3381 // print a warning if any large page related flag is specified on command line 3382 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS); 3383 3384 const size_t default_page_size = (size_t)Bsd::page_size(); 3385 if (_large_page_size > default_page_size) { 3386 _page_sizes[0] = _large_page_size; 3387 _page_sizes[1] = default_page_size; 3388 _page_sizes[2] = 0; 3389 } 3390 UseHugeTLBFS = UseHugeTLBFS && 3391 Bsd::hugetlbfs_sanity_check(warn_on_failure, _large_page_size); 3392 3393 if (UseHugeTLBFS) 3394 UseSHM = false; 3395 3396 UseLargePages = UseHugeTLBFS || UseSHM; 3397 3398 set_coredump_filter(); 3399 #endif 3400 } 3401 3402 #ifndef _ALLBSD_SOURCE 3403 #ifndef SHM_HUGETLB 3404 #define SHM_HUGETLB 04000 3405 #endif 3406 #endif 3407 3408 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) { 3409 fatal("This code is not used or maintained."); 3410 3411 // "exec" is passed in but not used. Creating the shared image for 3412 // the code cache doesn't have an SHM_X executable permission to check. 3413 assert(UseLargePages && UseSHM, "only for SHM large pages"); 3414 3415 key_t key = IPC_PRIVATE; 3416 char *addr; 3417 3418 bool warn_on_failure = UseLargePages && 3419 (!FLAG_IS_DEFAULT(UseLargePages) || 3420 !FLAG_IS_DEFAULT(LargePageSizeInBytes) 3421 ); 3422 char msg[128]; 3423 3424 // Create a large shared memory region to attach to based on size. 3425 // Currently, size is the total size of the heap 3426 #ifndef _ALLBSD_SOURCE 3427 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); 3428 #else 3429 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W); 3430 #endif 3431 if (shmid == -1) { 3432 // Possible reasons for shmget failure: 3433 // 1. shmmax is too small for Java heap. 3434 // > check shmmax value: cat /proc/sys/kernel/shmmax 3435 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 3436 // 2. not enough large page memory. 3437 // > check available large pages: cat /proc/meminfo 3438 // > increase amount of large pages: 3439 // echo new_value > /proc/sys/vm/nr_hugepages 3440 // Note 1: different Bsd may use different name for this property, 3441 // e.g. on Redhat AS-3 it is "hugetlb_pool". 3442 // Note 2: it's possible there's enough physical memory available but 3443 // they are so fragmented after a long run that they can't 3444 // coalesce into large pages. Try to reserve large pages when 3445 // the system is still "fresh". 3446 if (warn_on_failure) { 3447 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); 3448 warning(msg); 3449 } 3450 return NULL; 3451 } 3452 3453 // attach to the region 3454 addr = (char*)shmat(shmid, req_addr, 0); 3455 int err = errno; 3456 3457 // Remove shmid. If shmat() is successful, the actual shared memory segment 3458 // will be deleted when it's detached by shmdt() or when the process 3459 // terminates. If shmat() is not successful this will remove the shared 3460 // segment immediately. 3461 shmctl(shmid, IPC_RMID, NULL); 3462 3463 if ((intptr_t)addr == -1) { 3464 if (warn_on_failure) { 3465 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); 3466 warning(msg); 3467 } 3468 return NULL; 3469 } 3470 3471 // The memory is committed 3472 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC); 3473 3474 return addr; 3475 } 3476 3477 bool os::release_memory_special(char* base, size_t bytes) { 3478 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 3479 // detaching the SHM segment will also delete it, see reserve_memory_special() 3480 int rslt = shmdt(base); 3481 if (rslt == 0) { 3482 tkr.record((address)base, bytes); 3483 return true; 3484 } else { 3485 tkr.discard(); 3486 return false; 3487 } 3488 3489 } 3490 3491 size_t os::large_page_size() { 3492 return _large_page_size; 3493 } 3494 3495 // HugeTLBFS allows application to commit large page memory on demand; 3496 // with SysV SHM the entire memory region must be allocated as shared 3497 // memory. 3498 bool os::can_commit_large_page_memory() { 3499 return UseHugeTLBFS; 3500 } 3501 3502 bool os::can_execute_large_page_memory() { 3503 return UseHugeTLBFS; 3504 } 3505 3506 // Reserve memory at an arbitrary address, only if that area is 3507 // available (and not reserved for something else). 3508 3509 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 3510 const int max_tries = 10; 3511 char* base[max_tries]; 3512 size_t size[max_tries]; 3513 const size_t gap = 0x000000; 3514 3515 // Assert only that the size is a multiple of the page size, since 3516 // that's all that mmap requires, and since that's all we really know 3517 // about at this low abstraction level. If we need higher alignment, 3518 // we can either pass an alignment to this method or verify alignment 3519 // in one of the methods further up the call chain. See bug 5044738. 3520 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 3521 3522 // Repeatedly allocate blocks until the block is allocated at the 3523 // right spot. Give up after max_tries. Note that reserve_memory() will 3524 // automatically update _highest_vm_reserved_address if the call is 3525 // successful. The variable tracks the highest memory address every reserved 3526 // by JVM. It is used to detect heap-stack collision if running with 3527 // fixed-stack BsdThreads. Because here we may attempt to reserve more 3528 // space than needed, it could confuse the collision detecting code. To 3529 // solve the problem, save current _highest_vm_reserved_address and 3530 // calculate the correct value before return. 3531 address old_highest = _highest_vm_reserved_address; 3532 3533 // Bsd mmap allows caller to pass an address as hint; give it a try first, 3534 // if kernel honors the hint then we can return immediately. 3535 char * addr = anon_mmap(requested_addr, bytes, false); 3536 if (addr == requested_addr) { 3537 return requested_addr; 3538 } 3539 3540 if (addr != NULL) { 3541 // mmap() is successful but it fails to reserve at the requested address 3542 anon_munmap(addr, bytes); 3543 } 3544 3545 int i; 3546 for (i = 0; i < max_tries; ++i) { 3547 base[i] = reserve_memory(bytes); 3548 3549 if (base[i] != NULL) { 3550 // Is this the block we wanted? 3551 if (base[i] == requested_addr) { 3552 size[i] = bytes; 3553 break; 3554 } 3555 3556 // Does this overlap the block we wanted? Give back the overlapped 3557 // parts and try again. 3558 3559 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 3560 if (top_overlap >= 0 && top_overlap < bytes) { 3561 unmap_memory(base[i], top_overlap); 3562 base[i] += top_overlap; 3563 size[i] = bytes - top_overlap; 3564 } else { 3565 size_t bottom_overlap = base[i] + bytes - requested_addr; 3566 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 3567 unmap_memory(requested_addr, bottom_overlap); 3568 size[i] = bytes - bottom_overlap; 3569 } else { 3570 size[i] = bytes; 3571 } 3572 } 3573 } 3574 } 3575 3576 // Give back the unused reserved pieces. 3577 3578 for (int j = 0; j < i; ++j) { 3579 if (base[j] != NULL) { 3580 unmap_memory(base[j], size[j]); 3581 } 3582 } 3583 3584 if (i < max_tries) { 3585 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 3586 return requested_addr; 3587 } else { 3588 _highest_vm_reserved_address = old_highest; 3589 return NULL; 3590 } 3591 } 3592 3593 size_t os::read(int fd, void *buf, unsigned int nBytes) { 3594 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes)); 3595 } 3596 3597 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation. 3598 // Solaris uses poll(), bsd uses park(). 3599 // Poll() is likely a better choice, assuming that Thread.interrupt() 3600 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with 3601 // SIGSEGV, see 4355769. 3602 3603 int os::sleep(Thread* thread, jlong millis, bool interruptible) { 3604 assert(thread == Thread::current(), "thread consistency check"); 3605 3606 ParkEvent * const slp = thread->_SleepEvent ; 3607 slp->reset() ; 3608 OrderAccess::fence() ; 3609 3610 if (interruptible) { 3611 jlong prevtime = javaTimeNanos(); 3612 3613 for (;;) { 3614 if (os::is_interrupted(thread, true)) { 3615 return OS_INTRPT; 3616 } 3617 3618 jlong newtime = javaTimeNanos(); 3619 3620 if (newtime - prevtime < 0) { 3621 // time moving backwards, should only happen if no monotonic clock 3622 // not a guarantee() because JVM should not abort on kernel/glibc bugs 3623 assert(!Bsd::supports_monotonic_clock(), "time moving backwards"); 3624 } else { 3625 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 3626 } 3627 3628 if(millis <= 0) { 3629 return OS_OK; 3630 } 3631 3632 prevtime = newtime; 3633 3634 { 3635 assert(thread->is_Java_thread(), "sanity check"); 3636 JavaThread *jt = (JavaThread *) thread; 3637 ThreadBlockInVM tbivm(jt); 3638 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); 3639 3640 jt->set_suspend_equivalent(); 3641 // cleared by handle_special_suspend_equivalent_condition() or 3642 // java_suspend_self() via check_and_wait_while_suspended() 3643 3644 slp->park(millis); 3645 3646 // were we externally suspended while we were waiting? 3647 jt->check_and_wait_while_suspended(); 3648 } 3649 } 3650 } else { 3651 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 3652 jlong prevtime = javaTimeNanos(); 3653 3654 for (;;) { 3655 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on 3656 // the 1st iteration ... 3657 jlong newtime = javaTimeNanos(); 3658 3659 if (newtime - prevtime < 0) { 3660 // time moving backwards, should only happen if no monotonic clock 3661 // not a guarantee() because JVM should not abort on kernel/glibc bugs 3662 assert(!Bsd::supports_monotonic_clock(), "time moving backwards"); 3663 } else { 3664 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 3665 } 3666 3667 if(millis <= 0) break ; 3668 3669 prevtime = newtime; 3670 slp->park(millis); 3671 } 3672 return OS_OK ; 3673 } 3674 } 3675 3676 int os::naked_sleep() { 3677 // %% make the sleep time an integer flag. for now use 1 millisec. 3678 return os::sleep(Thread::current(), 1, false); 3679 } 3680 3681 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 3682 void os::infinite_sleep() { 3683 while (true) { // sleep forever ... 3684 ::sleep(100); // ... 100 seconds at a time 3685 } 3686 } 3687 3688 // Used to convert frequent JVM_Yield() to nops 3689 bool os::dont_yield() { 3690 return DontYieldALot; 3691 } 3692 3693 void os::yield() { 3694 sched_yield(); 3695 } 3696 3697 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} 3698 3699 void os::yield_all(int attempts) { 3700 // Yields to all threads, including threads with lower priorities 3701 // Threads on Bsd are all with same priority. The Solaris style 3702 // os::yield_all() with nanosleep(1ms) is not necessary. 3703 sched_yield(); 3704 } 3705 3706 // Called from the tight loops to possibly influence time-sharing heuristics 3707 void os::loop_breaker(int attempts) { 3708 os::yield_all(attempts); 3709 } 3710 3711 //////////////////////////////////////////////////////////////////////////////// 3712 // thread priority support 3713 3714 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER 3715 // only supports dynamic priority, static priority must be zero. For real-time 3716 // applications, Bsd supports SCHED_RR which allows static priority (1-99). 3717 // However, for large multi-threaded applications, SCHED_RR is not only slower 3718 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 3719 // of 5 runs - Sep 2005). 3720 // 3721 // The following code actually changes the niceness of kernel-thread/LWP. It 3722 // has an assumption that setpriority() only modifies one kernel-thread/LWP, 3723 // not the entire user process, and user level threads are 1:1 mapped to kernel 3724 // threads. It has always been the case, but could change in the future. For 3725 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). 3726 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. 3727 3728 #if defined(_ALLBSD_SOURCE) && !defined(__APPLE__) 3729 int os::java_to_os_priority[CriticalPriority + 1] = { 3730 19, // 0 Entry should never be used 3731 3732 0, // 1 MinPriority 3733 3, // 2 3734 6, // 3 3735 3736 10, // 4 3737 15, // 5 NormPriority 3738 18, // 6 3739 3740 21, // 7 3741 25, // 8 3742 28, // 9 NearMaxPriority 3743 3744 31, // 10 MaxPriority 3745 3746 31 // 11 CriticalPriority 3747 }; 3748 #elif defined(__APPLE__) 3749 /* Using Mach high-level priority assignments */ 3750 int os::java_to_os_priority[CriticalPriority + 1] = { 3751 0, // 0 Entry should never be used (MINPRI_USER) 3752 3753 27, // 1 MinPriority 3754 28, // 2 3755 29, // 3 3756 3757 30, // 4 3758 31, // 5 NormPriority (BASEPRI_DEFAULT) 3759 32, // 6 3760 3761 33, // 7 3762 34, // 8 3763 35, // 9 NearMaxPriority 3764 3765 36, // 10 MaxPriority 3766 3767 36 // 11 CriticalPriority 3768 }; 3769 #else 3770 int os::java_to_os_priority[CriticalPriority + 1] = { 3771 19, // 0 Entry should never be used 3772 3773 4, // 1 MinPriority 3774 3, // 2 3775 2, // 3 3776 3777 1, // 4 3778 0, // 5 NormPriority 3779 -1, // 6 3780 3781 -2, // 7 3782 -3, // 8 3783 -4, // 9 NearMaxPriority 3784 3785 -5, // 10 MaxPriority 3786 3787 -5 // 11 CriticalPriority 3788 }; 3789 #endif 3790 3791 static int prio_init() { 3792 if (ThreadPriorityPolicy == 1) { 3793 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 3794 // if effective uid is not root. Perhaps, a more elegant way of doing 3795 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 3796 if (geteuid() != 0) { 3797 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 3798 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd"); 3799 } 3800 ThreadPriorityPolicy = 0; 3801 } 3802 } 3803 if (UseCriticalJavaThreadPriority) { 3804 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; 3805 } 3806 return 0; 3807 } 3808 3809 OSReturn os::set_native_priority(Thread* thread, int newpri) { 3810 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; 3811 3812 #ifdef __OpenBSD__ 3813 // OpenBSD pthread_setprio starves low priority threads 3814 return OS_OK; 3815 #elif defined(__FreeBSD__) 3816 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri); 3817 #elif defined(__APPLE__) || defined(__NetBSD__) 3818 struct sched_param sp; 3819 int policy; 3820 pthread_t self = pthread_self(); 3821 3822 if (pthread_getschedparam(self, &policy, &sp) != 0) 3823 return OS_ERR; 3824 3825 sp.sched_priority = newpri; 3826 if (pthread_setschedparam(self, policy, &sp) != 0) 3827 return OS_ERR; 3828 3829 return OS_OK; 3830 #else 3831 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 3832 return (ret == 0) ? OS_OK : OS_ERR; 3833 #endif 3834 } 3835 3836 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { 3837 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { 3838 *priority_ptr = java_to_os_priority[NormPriority]; 3839 return OS_OK; 3840 } 3841 3842 errno = 0; 3843 #if defined(__OpenBSD__) || defined(__FreeBSD__) 3844 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id()); 3845 #elif defined(__APPLE__) || defined(__NetBSD__) 3846 int policy; 3847 struct sched_param sp; 3848 3849 pthread_getschedparam(pthread_self(), &policy, &sp); 3850 *priority_ptr = sp.sched_priority; 3851 #else 3852 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 3853 #endif 3854 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 3855 } 3856 3857 // Hint to the underlying OS that a task switch would not be good. 3858 // Void return because it's a hint and can fail. 3859 void os::hint_no_preempt() {} 3860 3861 //////////////////////////////////////////////////////////////////////////////// 3862 // suspend/resume support 3863 3864 // the low-level signal-based suspend/resume support is a remnant from the 3865 // old VM-suspension that used to be for java-suspension, safepoints etc, 3866 // within hotspot. Now there is a single use-case for this: 3867 // - calling get_thread_pc() on the VMThread by the flat-profiler task 3868 // that runs in the watcher thread. 3869 // The remaining code is greatly simplified from the more general suspension 3870 // code that used to be used. 3871 // 3872 // The protocol is quite simple: 3873 // - suspend: 3874 // - sends a signal to the target thread 3875 // - polls the suspend state of the osthread using a yield loop 3876 // - target thread signal handler (SR_handler) sets suspend state 3877 // and blocks in sigsuspend until continued 3878 // - resume: 3879 // - sets target osthread state to continue 3880 // - sends signal to end the sigsuspend loop in the SR_handler 3881 // 3882 // Note that the SR_lock plays no role in this suspend/resume protocol. 3883 // 3884 3885 static void resume_clear_context(OSThread *osthread) { 3886 osthread->set_ucontext(NULL); 3887 osthread->set_siginfo(NULL); 3888 } 3889 3890 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { 3891 osthread->set_ucontext(context); 3892 osthread->set_siginfo(siginfo); 3893 } 3894 3895 // 3896 // Handler function invoked when a thread's execution is suspended or 3897 // resumed. We have to be careful that only async-safe functions are 3898 // called here (Note: most pthread functions are not async safe and 3899 // should be avoided.) 3900 // 3901 // Note: sigwait() is a more natural fit than sigsuspend() from an 3902 // interface point of view, but sigwait() prevents the signal hander 3903 // from being run. libpthread would get very confused by not having 3904 // its signal handlers run and prevents sigwait()'s use with the 3905 // mutex granting granting signal. 3906 // 3907 // Currently only ever called on the VMThread or JavaThread 3908 // 3909 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 3910 // Save and restore errno to avoid confusing native code with EINTR 3911 // after sigsuspend. 3912 int old_errno = errno; 3913 3914 Thread* thread = Thread::current(); 3915 OSThread* osthread = thread->osthread(); 3916 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 3917 3918 os::SuspendResume::State current = osthread->sr.state(); 3919 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 3920 suspend_save_context(osthread, siginfo, context); 3921 3922 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 3923 os::SuspendResume::State state = osthread->sr.suspended(); 3924 if (state == os::SuspendResume::SR_SUSPENDED) { 3925 sigset_t suspend_set; // signals for sigsuspend() 3926 3927 // get current set of blocked signals and unblock resume signal 3928 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3929 sigdelset(&suspend_set, SR_signum); 3930 3931 sr_semaphore.signal(); 3932 // wait here until we are resumed 3933 while (1) { 3934 sigsuspend(&suspend_set); 3935 3936 os::SuspendResume::State result = osthread->sr.running(); 3937 if (result == os::SuspendResume::SR_RUNNING) { 3938 sr_semaphore.signal(); 3939 break; 3940 } else if (result != os::SuspendResume::SR_SUSPENDED) { 3941 ShouldNotReachHere(); 3942 } 3943 } 3944 3945 } else if (state == os::SuspendResume::SR_RUNNING) { 3946 // request was cancelled, continue 3947 } else { 3948 ShouldNotReachHere(); 3949 } 3950 3951 resume_clear_context(osthread); 3952 } else if (current == os::SuspendResume::SR_RUNNING) { 3953 // request was cancelled, continue 3954 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 3955 // ignore 3956 } else { 3957 // ignore 3958 } 3959 3960 errno = old_errno; 3961 } 3962 3963 3964 static int SR_initialize() { 3965 struct sigaction act; 3966 char *s; 3967 /* Get signal number to use for suspend/resume */ 3968 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 3969 int sig = ::strtol(s, 0, 10); 3970 if (sig > 0 || sig < NSIG) { 3971 SR_signum = sig; 3972 } 3973 } 3974 3975 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 3976 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 3977 3978 sigemptyset(&SR_sigset); 3979 sigaddset(&SR_sigset, SR_signum); 3980 3981 /* Set up signal handler for suspend/resume */ 3982 act.sa_flags = SA_RESTART|SA_SIGINFO; 3983 act.sa_handler = (void (*)(int)) SR_handler; 3984 3985 // SR_signum is blocked by default. 3986 // 4528190 - We also need to block pthread restart signal (32 on all 3987 // supported Bsd platforms). Note that BsdThreads need to block 3988 // this signal for all threads to work properly. So we don't have 3989 // to use hard-coded signal number when setting up the mask. 3990 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 3991 3992 if (sigaction(SR_signum, &act, 0) == -1) { 3993 return -1; 3994 } 3995 3996 // Save signal flag 3997 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags); 3998 return 0; 3999 } 4000 4001 static int SR_finalize() { 4002 return 0; 4003 } 4004 4005 static int sr_notify(OSThread* osthread) { 4006 int status = pthread_kill(osthread->pthread_id(), SR_signum); 4007 assert_status(status == 0, status, "pthread_kill"); 4008 return status; 4009 } 4010 4011 // "Randomly" selected value for how long we want to spin 4012 // before bailing out on suspending a thread, also how often 4013 // we send a signal to a thread we want to resume 4014 static const int RANDOMLY_LARGE_INTEGER = 1000000; 4015 static const int RANDOMLY_LARGE_INTEGER2 = 100; 4016 4017 // returns true on success and false on error - really an error is fatal 4018 // but this seems the normal response to library errors 4019 static bool do_suspend(OSThread* osthread) { 4020 assert(osthread->sr.is_running(), "thread should be running"); 4021 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 4022 4023 // mark as suspended and send signal 4024 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 4025 // failed to switch, state wasn't running? 4026 ShouldNotReachHere(); 4027 return false; 4028 } 4029 4030 if (sr_notify(osthread) != 0) { 4031 ShouldNotReachHere(); 4032 } 4033 4034 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 4035 while (true) { 4036 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4037 break; 4038 } else { 4039 // timeout 4040 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 4041 if (cancelled == os::SuspendResume::SR_RUNNING) { 4042 return false; 4043 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 4044 // make sure that we consume the signal on the semaphore as well 4045 sr_semaphore.wait(); 4046 break; 4047 } else { 4048 ShouldNotReachHere(); 4049 return false; 4050 } 4051 } 4052 } 4053 4054 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 4055 return true; 4056 } 4057 4058 static void do_resume(OSThread* osthread) { 4059 assert(osthread->sr.is_suspended(), "thread should be suspended"); 4060 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 4061 4062 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 4063 // failed to switch to WAKEUP_REQUEST 4064 ShouldNotReachHere(); 4065 return; 4066 } 4067 4068 while (true) { 4069 if (sr_notify(osthread) == 0) { 4070 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 4071 if (osthread->sr.is_running()) { 4072 return; 4073 } 4074 } 4075 } else { 4076 ShouldNotReachHere(); 4077 } 4078 } 4079 4080 guarantee(osthread->sr.is_running(), "Must be running!"); 4081 } 4082 4083 //////////////////////////////////////////////////////////////////////////////// 4084 // interrupt support 4085 4086 void os::interrupt(Thread* thread) { 4087 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 4088 "possibility of dangling Thread pointer"); 4089 4090 OSThread* osthread = thread->osthread(); 4091 4092 if (!osthread->interrupted()) { 4093 osthread->set_interrupted(true); 4094 // More than one thread can get here with the same value of osthread, 4095 // resulting in multiple notifications. We do, however, want the store 4096 // to interrupted() to be visible to other threads before we execute unpark(). 4097 OrderAccess::fence(); 4098 ParkEvent * const slp = thread->_SleepEvent ; 4099 if (slp != NULL) slp->unpark() ; 4100 } 4101 4102 // For JSR166. Unpark even if interrupt status already was set 4103 if (thread->is_Java_thread()) 4104 ((JavaThread*)thread)->parker()->unpark(); 4105 4106 ParkEvent * ev = thread->_ParkEvent ; 4107 if (ev != NULL) ev->unpark() ; 4108 4109 } 4110 4111 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 4112 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 4113 "possibility of dangling Thread pointer"); 4114 4115 OSThread* osthread = thread->osthread(); 4116 4117 bool interrupted = osthread->interrupted(); 4118 4119 if (interrupted && clear_interrupted) { 4120 osthread->set_interrupted(false); 4121 // consider thread->_SleepEvent->reset() ... optional optimization 4122 } 4123 4124 return interrupted; 4125 } 4126 4127 /////////////////////////////////////////////////////////////////////////////////// 4128 // signal handling (except suspend/resume) 4129 4130 // This routine may be used by user applications as a "hook" to catch signals. 4131 // The user-defined signal handler must pass unrecognized signals to this 4132 // routine, and if it returns true (non-zero), then the signal handler must 4133 // return immediately. If the flag "abort_if_unrecognized" is true, then this 4134 // routine will never retun false (zero), but instead will execute a VM panic 4135 // routine kill the process. 4136 // 4137 // If this routine returns false, it is OK to call it again. This allows 4138 // the user-defined signal handler to perform checks either before or after 4139 // the VM performs its own checks. Naturally, the user code would be making 4140 // a serious error if it tried to handle an exception (such as a null check 4141 // or breakpoint) that the VM was generating for its own correct operation. 4142 // 4143 // This routine may recognize any of the following kinds of signals: 4144 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 4145 // It should be consulted by handlers for any of those signals. 4146 // 4147 // The caller of this routine must pass in the three arguments supplied 4148 // to the function referred to in the "sa_sigaction" (not the "sa_handler") 4149 // field of the structure passed to sigaction(). This routine assumes that 4150 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 4151 // 4152 // Note that the VM will print warnings if it detects conflicting signal 4153 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 4154 // 4155 extern "C" JNIEXPORT int 4156 JVM_handle_bsd_signal(int signo, siginfo_t* siginfo, 4157 void* ucontext, int abort_if_unrecognized); 4158 4159 void signalHandler(int sig, siginfo_t* info, void* uc) { 4160 assert(info != NULL && uc != NULL, "it must be old kernel"); 4161 JVM_handle_bsd_signal(sig, info, uc, true); 4162 } 4163 4164 4165 // This boolean allows users to forward their own non-matching signals 4166 // to JVM_handle_bsd_signal, harmlessly. 4167 bool os::Bsd::signal_handlers_are_installed = false; 4168 4169 // For signal-chaining 4170 struct sigaction os::Bsd::sigact[MAXSIGNUM]; 4171 unsigned int os::Bsd::sigs = 0; 4172 bool os::Bsd::libjsig_is_loaded = false; 4173 typedef struct sigaction *(*get_signal_t)(int); 4174 get_signal_t os::Bsd::get_signal_action = NULL; 4175 4176 struct sigaction* os::Bsd::get_chained_signal_action(int sig) { 4177 struct sigaction *actp = NULL; 4178 4179 if (libjsig_is_loaded) { 4180 // Retrieve the old signal handler from libjsig 4181 actp = (*get_signal_action)(sig); 4182 } 4183 if (actp == NULL) { 4184 // Retrieve the preinstalled signal handler from jvm 4185 actp = get_preinstalled_handler(sig); 4186 } 4187 4188 return actp; 4189 } 4190 4191 static bool call_chained_handler(struct sigaction *actp, int sig, 4192 siginfo_t *siginfo, void *context) { 4193 // Call the old signal handler 4194 if (actp->sa_handler == SIG_DFL) { 4195 // It's more reasonable to let jvm treat it as an unexpected exception 4196 // instead of taking the default action. 4197 return false; 4198 } else if (actp->sa_handler != SIG_IGN) { 4199 if ((actp->sa_flags & SA_NODEFER) == 0) { 4200 // automaticlly block the signal 4201 sigaddset(&(actp->sa_mask), sig); 4202 } 4203 4204 sa_handler_t hand; 4205 sa_sigaction_t sa; 4206 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 4207 // retrieve the chained handler 4208 if (siginfo_flag_set) { 4209 sa = actp->sa_sigaction; 4210 } else { 4211 hand = actp->sa_handler; 4212 } 4213 4214 if ((actp->sa_flags & SA_RESETHAND) != 0) { 4215 actp->sa_handler = SIG_DFL; 4216 } 4217 4218 // try to honor the signal mask 4219 sigset_t oset; 4220 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 4221 4222 // call into the chained handler 4223 if (siginfo_flag_set) { 4224 (*sa)(sig, siginfo, context); 4225 } else { 4226 (*hand)(sig); 4227 } 4228 4229 // restore the signal mask 4230 pthread_sigmask(SIG_SETMASK, &oset, 0); 4231 } 4232 // Tell jvm's signal handler the signal is taken care of. 4233 return true; 4234 } 4235 4236 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) { 4237 bool chained = false; 4238 // signal-chaining 4239 if (UseSignalChaining) { 4240 struct sigaction *actp = get_chained_signal_action(sig); 4241 if (actp != NULL) { 4242 chained = call_chained_handler(actp, sig, siginfo, context); 4243 } 4244 } 4245 return chained; 4246 } 4247 4248 struct sigaction* os::Bsd::get_preinstalled_handler(int sig) { 4249 if ((( (unsigned int)1 << sig ) & sigs) != 0) { 4250 return &sigact[sig]; 4251 } 4252 return NULL; 4253 } 4254 4255 void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 4256 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4257 sigact[sig] = oldAct; 4258 sigs |= (unsigned int)1 << sig; 4259 } 4260 4261 // for diagnostic 4262 int os::Bsd::sigflags[MAXSIGNUM]; 4263 4264 int os::Bsd::get_our_sigflags(int sig) { 4265 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4266 return sigflags[sig]; 4267 } 4268 4269 void os::Bsd::set_our_sigflags(int sig, int flags) { 4270 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4271 sigflags[sig] = flags; 4272 } 4273 4274 void os::Bsd::set_signal_handler(int sig, bool set_installed) { 4275 // Check for overwrite. 4276 struct sigaction oldAct; 4277 sigaction(sig, (struct sigaction*)NULL, &oldAct); 4278 4279 void* oldhand = oldAct.sa_sigaction 4280 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4281 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4282 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 4283 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 4284 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 4285 if (AllowUserSignalHandlers || !set_installed) { 4286 // Do not overwrite; user takes responsibility to forward to us. 4287 return; 4288 } else if (UseSignalChaining) { 4289 // save the old handler in jvm 4290 save_preinstalled_handler(sig, oldAct); 4291 // libjsig also interposes the sigaction() call below and saves the 4292 // old sigaction on it own. 4293 } else { 4294 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " 4295 "%#lx for signal %d.", (long)oldhand, sig)); 4296 } 4297 } 4298 4299 struct sigaction sigAct; 4300 sigfillset(&(sigAct.sa_mask)); 4301 sigAct.sa_handler = SIG_DFL; 4302 if (!set_installed) { 4303 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4304 } else { 4305 sigAct.sa_sigaction = signalHandler; 4306 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 4307 } 4308 #if __APPLE__ 4309 // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV 4310 // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages" 4311 // if the signal handler declares it will handle it on alternate stack. 4312 // Notice we only declare we will handle it on alt stack, but we are not 4313 // actually going to use real alt stack - this is just a workaround. 4314 // Please see ux_exception.c, method catch_mach_exception_raise for details 4315 // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c 4316 if (sig == SIGSEGV) { 4317 sigAct.sa_flags |= SA_ONSTACK; 4318 } 4319 #endif 4320 4321 // Save flags, which are set by ours 4322 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 4323 sigflags[sig] = sigAct.sa_flags; 4324 4325 int ret = sigaction(sig, &sigAct, &oldAct); 4326 assert(ret == 0, "check"); 4327 4328 void* oldhand2 = oldAct.sa_sigaction 4329 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 4330 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 4331 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 4332 } 4333 4334 // install signal handlers for signals that HotSpot needs to 4335 // handle in order to support Java-level exception handling. 4336 4337 void os::Bsd::install_signal_handlers() { 4338 if (!signal_handlers_are_installed) { 4339 signal_handlers_are_installed = true; 4340 4341 // signal-chaining 4342 typedef void (*signal_setting_t)(); 4343 signal_setting_t begin_signal_setting = NULL; 4344 signal_setting_t end_signal_setting = NULL; 4345 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4346 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 4347 if (begin_signal_setting != NULL) { 4348 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4349 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 4350 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 4351 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 4352 libjsig_is_loaded = true; 4353 assert(UseSignalChaining, "should enable signal-chaining"); 4354 } 4355 if (libjsig_is_loaded) { 4356 // Tell libjsig jvm is setting signal handlers 4357 (*begin_signal_setting)(); 4358 } 4359 4360 set_signal_handler(SIGSEGV, true); 4361 set_signal_handler(SIGPIPE, true); 4362 set_signal_handler(SIGBUS, true); 4363 set_signal_handler(SIGILL, true); 4364 set_signal_handler(SIGFPE, true); 4365 set_signal_handler(SIGXFSZ, true); 4366 4367 #if defined(__APPLE__) 4368 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including 4369 // signals caught and handled by the JVM. To work around this, we reset the mach task 4370 // signal handler that's placed on our process by CrashReporter. This disables 4371 // CrashReporter-based reporting. 4372 // 4373 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes 4374 // on caught fatal signals. 4375 // 4376 // Additionally, gdb installs both standard BSD signal handlers, and mach exception 4377 // handlers. By replacing the existing task exception handler, we disable gdb's mach 4378 // exception handling, while leaving the standard BSD signal handlers functional. 4379 kern_return_t kr; 4380 kr = task_set_exception_ports(mach_task_self(), 4381 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC, 4382 MACH_PORT_NULL, 4383 EXCEPTION_STATE_IDENTITY, 4384 MACHINE_THREAD_STATE); 4385 4386 assert(kr == KERN_SUCCESS, "could not set mach task signal handler"); 4387 #endif 4388 4389 if (libjsig_is_loaded) { 4390 // Tell libjsig jvm finishes setting signal handlers 4391 (*end_signal_setting)(); 4392 } 4393 4394 // We don't activate signal checker if libjsig is in place, we trust ourselves 4395 // and if UserSignalHandler is installed all bets are off 4396 if (CheckJNICalls) { 4397 if (libjsig_is_loaded) { 4398 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 4399 check_signals = false; 4400 } 4401 if (AllowUserSignalHandlers) { 4402 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 4403 check_signals = false; 4404 } 4405 } 4406 } 4407 } 4408 4409 #ifndef _ALLBSD_SOURCE 4410 // This is the fastest way to get thread cpu time on Bsd. 4411 // Returns cpu time (user+sys) for any thread, not only for current. 4412 // POSIX compliant clocks are implemented in the kernels 2.6.16+. 4413 // It might work on 2.6.10+ with a special kernel/glibc patch. 4414 // For reference, please, see IEEE Std 1003.1-2004: 4415 // http://www.unix.org/single_unix_specification 4416 4417 jlong os::Bsd::fast_thread_cpu_time(clockid_t clockid) { 4418 struct timespec tp; 4419 int rc = os::Bsd::clock_gettime(clockid, &tp); 4420 assert(rc == 0, "clock_gettime is expected to return 0 code"); 4421 4422 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec; 4423 } 4424 #endif 4425 4426 ///// 4427 // glibc on Bsd platform uses non-documented flag 4428 // to indicate, that some special sort of signal 4429 // trampoline is used. 4430 // We will never set this flag, and we should 4431 // ignore this flag in our diagnostic 4432 #ifdef SIGNIFICANT_SIGNAL_MASK 4433 #undef SIGNIFICANT_SIGNAL_MASK 4434 #endif 4435 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 4436 4437 static const char* get_signal_handler_name(address handler, 4438 char* buf, int buflen) { 4439 int offset; 4440 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 4441 if (found) { 4442 // skip directory names 4443 const char *p1, *p2; 4444 p1 = buf; 4445 size_t len = strlen(os::file_separator()); 4446 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 4447 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 4448 } else { 4449 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 4450 } 4451 return buf; 4452 } 4453 4454 static void print_signal_handler(outputStream* st, int sig, 4455 char* buf, size_t buflen) { 4456 struct sigaction sa; 4457 4458 sigaction(sig, NULL, &sa); 4459 4460 // See comment for SIGNIFICANT_SIGNAL_MASK define 4461 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4462 4463 st->print("%s: ", os::exception_name(sig, buf, buflen)); 4464 4465 address handler = (sa.sa_flags & SA_SIGINFO) 4466 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 4467 : CAST_FROM_FN_PTR(address, sa.sa_handler); 4468 4469 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 4470 st->print("SIG_DFL"); 4471 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 4472 st->print("SIG_IGN"); 4473 } else { 4474 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 4475 } 4476 4477 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask); 4478 4479 address rh = VMError::get_resetted_sighandler(sig); 4480 // May be, handler was resetted by VMError? 4481 if(rh != NULL) { 4482 handler = rh; 4483 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 4484 } 4485 4486 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags); 4487 4488 // Check: is it our handler? 4489 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 4490 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 4491 // It is our signal handler 4492 // check for flags, reset system-used one! 4493 if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { 4494 st->print( 4495 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 4496 os::Bsd::get_our_sigflags(sig)); 4497 } 4498 } 4499 st->cr(); 4500 } 4501 4502 4503 #define DO_SIGNAL_CHECK(sig) \ 4504 if (!sigismember(&check_signal_done, sig)) \ 4505 os::Bsd::check_signal_handler(sig) 4506 4507 // This method is a periodic task to check for misbehaving JNI applications 4508 // under CheckJNI, we can add any periodic checks here 4509 4510 void os::run_periodic_checks() { 4511 4512 if (check_signals == false) return; 4513 4514 // SEGV and BUS if overridden could potentially prevent 4515 // generation of hs*.log in the event of a crash, debugging 4516 // such a case can be very challenging, so we absolutely 4517 // check the following for a good measure: 4518 DO_SIGNAL_CHECK(SIGSEGV); 4519 DO_SIGNAL_CHECK(SIGILL); 4520 DO_SIGNAL_CHECK(SIGFPE); 4521 DO_SIGNAL_CHECK(SIGBUS); 4522 DO_SIGNAL_CHECK(SIGPIPE); 4523 DO_SIGNAL_CHECK(SIGXFSZ); 4524 4525 4526 // ReduceSignalUsage allows the user to override these handlers 4527 // see comments at the very top and jvm_solaris.h 4528 if (!ReduceSignalUsage) { 4529 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 4530 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 4531 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 4532 DO_SIGNAL_CHECK(BREAK_SIGNAL); 4533 } 4534 4535 DO_SIGNAL_CHECK(SR_signum); 4536 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 4537 } 4538 4539 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 4540 4541 static os_sigaction_t os_sigaction = NULL; 4542 4543 void os::Bsd::check_signal_handler(int sig) { 4544 char buf[O_BUFLEN]; 4545 address jvmHandler = NULL; 4546 4547 4548 struct sigaction act; 4549 if (os_sigaction == NULL) { 4550 // only trust the default sigaction, in case it has been interposed 4551 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 4552 if (os_sigaction == NULL) return; 4553 } 4554 4555 os_sigaction(sig, (struct sigaction*)NULL, &act); 4556 4557 4558 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 4559 4560 address thisHandler = (act.sa_flags & SA_SIGINFO) 4561 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 4562 : CAST_FROM_FN_PTR(address, act.sa_handler) ; 4563 4564 4565 switch(sig) { 4566 case SIGSEGV: 4567 case SIGBUS: 4568 case SIGFPE: 4569 case SIGPIPE: 4570 case SIGILL: 4571 case SIGXFSZ: 4572 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 4573 break; 4574 4575 case SHUTDOWN1_SIGNAL: 4576 case SHUTDOWN2_SIGNAL: 4577 case SHUTDOWN3_SIGNAL: 4578 case BREAK_SIGNAL: 4579 jvmHandler = (address)user_handler(); 4580 break; 4581 4582 case INTERRUPT_SIGNAL: 4583 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 4584 break; 4585 4586 default: 4587 if (sig == SR_signum) { 4588 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 4589 } else { 4590 return; 4591 } 4592 break; 4593 } 4594 4595 if (thisHandler != jvmHandler) { 4596 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 4597 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 4598 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 4599 // No need to check this sig any longer 4600 sigaddset(&check_signal_done, sig); 4601 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) { 4602 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 4603 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig)); 4604 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 4605 // No need to check this sig any longer 4606 sigaddset(&check_signal_done, sig); 4607 } 4608 4609 // Dump all the signal 4610 if (sigismember(&check_signal_done, sig)) { 4611 print_signal_handlers(tty, buf, O_BUFLEN); 4612 } 4613 } 4614 4615 extern void report_error(char* file_name, int line_no, char* title, char* format, ...); 4616 4617 extern bool signal_name(int signo, char* buf, size_t len); 4618 4619 const char* os::exception_name(int exception_code, char* buf, size_t size) { 4620 if (0 < exception_code && exception_code <= SIGRTMAX) { 4621 // signal 4622 if (!signal_name(exception_code, buf, size)) { 4623 jio_snprintf(buf, size, "SIG%d", exception_code); 4624 } 4625 return buf; 4626 } else { 4627 return NULL; 4628 } 4629 } 4630 4631 // this is called _before_ the most of global arguments have been parsed 4632 void os::init(void) { 4633 char dummy; /* used to get a guess on initial stack address */ 4634 // first_hrtime = gethrtime(); 4635 4636 // With BsdThreads the JavaMain thread pid (primordial thread) 4637 // is different than the pid of the java launcher thread. 4638 // So, on Bsd, the launcher thread pid is passed to the VM 4639 // via the sun.java.launcher.pid property. 4640 // Use this property instead of getpid() if it was correctly passed. 4641 // See bug 6351349. 4642 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 4643 4644 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 4645 4646 clock_tics_per_sec = CLK_TCK; 4647 4648 init_random(1234567); 4649 4650 ThreadCritical::initialize(); 4651 4652 Bsd::set_page_size(getpagesize()); 4653 if (Bsd::page_size() == -1) { 4654 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)", 4655 strerror(errno))); 4656 } 4657 init_page_sizes((size_t) Bsd::page_size()); 4658 4659 Bsd::initialize_system_info(); 4660 4661 // main_thread points to the aboriginal thread 4662 Bsd::_main_thread = pthread_self(); 4663 4664 Bsd::clock_init(); 4665 initial_time_count = os::elapsed_counter(); 4666 4667 #ifdef __APPLE__ 4668 // XXXDARWIN 4669 // Work around the unaligned VM callbacks in hotspot's 4670 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on 4671 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces 4672 // alignment when doing symbol lookup. To work around this, we force early 4673 // binding of all symbols now, thus binding when alignment is known-good. 4674 _dyld_bind_fully_image_containing_address((const void *) &os::init); 4675 #endif 4676 } 4677 4678 // To install functions for atexit system call 4679 extern "C" { 4680 static void perfMemory_exit_helper() { 4681 perfMemory_exit(); 4682 } 4683 } 4684 4685 // this is called _after_ the global arguments have been parsed 4686 jint os::init_2(void) 4687 { 4688 #ifndef _ALLBSD_SOURCE 4689 Bsd::fast_thread_clock_init(); 4690 #endif 4691 4692 // Allocate a single page and mark it as readable for safepoint polling 4693 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4694 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); 4695 4696 os::set_polling_page( polling_page ); 4697 4698 #ifndef PRODUCT 4699 if(Verbose && PrintMiscellaneous) 4700 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); 4701 #endif 4702 4703 if (!UseMembar) { 4704 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 4705 guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); 4706 os::set_memory_serialize_page( mem_serialize_page ); 4707 4708 #ifndef PRODUCT 4709 if(Verbose && PrintMiscellaneous) 4710 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); 4711 #endif 4712 } 4713 4714 os::large_page_init(); 4715 4716 // initialize suspend/resume support - must do this before signal_sets_init() 4717 if (SR_initialize() != 0) { 4718 perror("SR_initialize failed"); 4719 return JNI_ERR; 4720 } 4721 4722 Bsd::signal_sets_init(); 4723 Bsd::install_signal_handlers(); 4724 4725 // Check minimum allowable stack size for thread creation and to initialize 4726 // the java system classes, including StackOverflowError - depends on page 4727 // size. Add a page for compiler2 recursion in main thread. 4728 // Add in 2*BytesPerWord times page size to account for VM stack during 4729 // class initialization depending on 32 or 64 bit VM. 4730 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed, 4731 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+ 4732 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size()); 4733 4734 size_t threadStackSizeInBytes = ThreadStackSize * K; 4735 if (threadStackSizeInBytes != 0 && 4736 threadStackSizeInBytes < os::Bsd::min_stack_allowed) { 4737 tty->print_cr("\nThe stack size specified is too small, " 4738 "Specify at least %dk", 4739 os::Bsd::min_stack_allowed/ K); 4740 return JNI_ERR; 4741 } 4742 4743 // Make the stack size a multiple of the page size so that 4744 // the yellow/red zones can be guarded. 4745 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 4746 vm_page_size())); 4747 4748 #ifndef _ALLBSD_SOURCE 4749 Bsd::capture_initial_stack(JavaThread::stack_size_at_create()); 4750 4751 Bsd::libpthread_init(); 4752 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4753 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", 4754 Bsd::glibc_version(), Bsd::libpthread_version(), 4755 Bsd::is_floating_stack() ? "floating stack" : "fixed stack"); 4756 } 4757 4758 if (UseNUMA) { 4759 if (!Bsd::libnuma_init()) { 4760 UseNUMA = false; 4761 } else { 4762 if ((Bsd::numa_max_node() < 1)) { 4763 // There's only one node(they start from 0), disable NUMA. 4764 UseNUMA = false; 4765 } 4766 } 4767 // With SHM large pages we cannot uncommit a page, so there's not way 4768 // we can make the adaptive lgrp chunk resizing work. If the user specified 4769 // both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and 4770 // disable adaptive resizing. 4771 if (UseNUMA && UseLargePages && UseSHM) { 4772 if (!FLAG_IS_DEFAULT(UseNUMA)) { 4773 if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseSHM)) { 4774 UseLargePages = false; 4775 } else { 4776 warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing"); 4777 UseAdaptiveSizePolicy = false; 4778 UseAdaptiveNUMAChunkSizing = false; 4779 } 4780 } else { 4781 UseNUMA = false; 4782 } 4783 } 4784 if (!UseNUMA && ForceNUMA) { 4785 UseNUMA = true; 4786 } 4787 } 4788 #endif 4789 4790 if (MaxFDLimit) { 4791 // set the number of file descriptors to max. print out error 4792 // if getrlimit/setrlimit fails but continue regardless. 4793 struct rlimit nbr_files; 4794 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 4795 if (status != 0) { 4796 if (PrintMiscellaneous && (Verbose || WizardMode)) 4797 perror("os::init_2 getrlimit failed"); 4798 } else { 4799 nbr_files.rlim_cur = nbr_files.rlim_max; 4800 4801 #ifdef __APPLE__ 4802 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if 4803 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must 4804 // be used instead 4805 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur); 4806 #endif 4807 4808 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 4809 if (status != 0) { 4810 if (PrintMiscellaneous && (Verbose || WizardMode)) 4811 perror("os::init_2 setrlimit failed"); 4812 } 4813 } 4814 } 4815 4816 #ifndef _ALLBSD_SOURCE 4817 // Initialize lock used to serialize thread creation (see os::create_thread) 4818 Bsd::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); 4819 #endif 4820 4821 // at-exit methods are called in the reverse order of their registration. 4822 // atexit functions are called on return from main or as a result of a 4823 // call to exit(3C). There can be only 32 of these functions registered 4824 // and atexit() does not set errno. 4825 4826 if (PerfAllowAtExitRegistration) { 4827 // only register atexit functions if PerfAllowAtExitRegistration is set. 4828 // atexit functions can be delayed until process exit time, which 4829 // can be problematic for embedded VM situations. Embedded VMs should 4830 // call DestroyJavaVM() to assure that VM resources are released. 4831 4832 // note: perfMemory_exit_helper atexit function may be removed in 4833 // the future if the appropriate cleanup code can be added to the 4834 // VM_Exit VMOperation's doit method. 4835 if (atexit(perfMemory_exit_helper) != 0) { 4836 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 4837 } 4838 } 4839 4840 // initialize thread priority policy 4841 prio_init(); 4842 4843 #ifdef __APPLE__ 4844 // dynamically link to objective c gc registration 4845 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY); 4846 if (handleLibObjc != NULL) { 4847 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER); 4848 } 4849 #endif 4850 4851 return JNI_OK; 4852 } 4853 4854 // this is called at the end of vm_initialization 4855 void os::init_3(void) { } 4856 4857 // Mark the polling page as unreadable 4858 void os::make_polling_page_unreadable(void) { 4859 if( !guard_memory((char*)_polling_page, Bsd::page_size()) ) 4860 fatal("Could not disable polling page"); 4861 }; 4862 4863 // Mark the polling page as readable 4864 void os::make_polling_page_readable(void) { 4865 if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { 4866 fatal("Could not enable polling page"); 4867 } 4868 }; 4869 4870 int os::active_processor_count() { 4871 #ifdef _ALLBSD_SOURCE 4872 return _processor_count; 4873 #else 4874 // Bsd doesn't yet have a (official) notion of processor sets, 4875 // so just return the number of online processors. 4876 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); 4877 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); 4878 return online_cpus; 4879 #endif 4880 } 4881 4882 void os::set_native_thread_name(const char *name) { 4883 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 4884 // This is only supported in Snow Leopard and beyond 4885 if (name != NULL) { 4886 // Add a "Java: " prefix to the name 4887 char buf[MAXTHREADNAMESIZE]; 4888 snprintf(buf, sizeof(buf), "Java: %s", name); 4889 pthread_setname_np(buf); 4890 } 4891 #endif 4892 } 4893 4894 bool os::distribute_processes(uint length, uint* distribution) { 4895 // Not yet implemented. 4896 return false; 4897 } 4898 4899 bool os::bind_to_processor(uint processor_id) { 4900 // Not yet implemented. 4901 return false; 4902 } 4903 4904 void os::SuspendedThreadTask::internal_do_task() { 4905 if (do_suspend(_thread->osthread())) { 4906 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 4907 do_task(context); 4908 do_resume(_thread->osthread()); 4909 } 4910 } 4911 4912 /// 4913 class PcFetcher : public os::SuspendedThreadTask { 4914 public: 4915 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 4916 ExtendedPC result(); 4917 protected: 4918 void do_task(const os::SuspendedThreadTaskContext& context); 4919 private: 4920 ExtendedPC _epc; 4921 }; 4922 4923 ExtendedPC PcFetcher::result() { 4924 guarantee(is_done(), "task is not done yet."); 4925 return _epc; 4926 } 4927 4928 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 4929 Thread* thread = context.thread(); 4930 OSThread* osthread = thread->osthread(); 4931 if (osthread->ucontext() != NULL) { 4932 _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext()); 4933 } else { 4934 // NULL context is unexpected, double-check this is the VMThread 4935 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 4936 } 4937 } 4938 4939 // Suspends the target using the signal mechanism and then grabs the PC before 4940 // resuming the target. Used by the flat-profiler only 4941 ExtendedPC os::get_thread_pc(Thread* thread) { 4942 // Make sure that it is called by the watcher for the VMThread 4943 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 4944 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 4945 4946 PcFetcher fetcher(thread); 4947 fetcher.run(); 4948 return fetcher.result(); 4949 } 4950 4951 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) 4952 { 4953 #ifdef _ALLBSD_SOURCE 4954 return pthread_cond_timedwait(_cond, _mutex, _abstime); 4955 #else 4956 if (is_NPTL()) { 4957 return pthread_cond_timedwait(_cond, _mutex, _abstime); 4958 } else { 4959 #ifndef IA64 4960 // 6292965: BsdThreads pthread_cond_timedwait() resets FPU control 4961 // word back to default 64bit precision if condvar is signaled. Java 4962 // wants 53bit precision. Save and restore current value. 4963 int fpu = get_fpu_control_word(); 4964 #endif // IA64 4965 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); 4966 #ifndef IA64 4967 set_fpu_control_word(fpu); 4968 #endif // IA64 4969 return status; 4970 } 4971 #endif 4972 } 4973 4974 //////////////////////////////////////////////////////////////////////////////// 4975 // debug support 4976 4977 static address same_page(address x, address y) { 4978 int page_bits = -os::vm_page_size(); 4979 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) 4980 return x; 4981 else if (x > y) 4982 return (address)(intptr_t(y) | ~page_bits) + 1; 4983 else 4984 return (address)(intptr_t(y) & page_bits); 4985 } 4986 4987 bool os::find(address addr, outputStream* st) { 4988 Dl_info dlinfo; 4989 memset(&dlinfo, 0, sizeof(dlinfo)); 4990 if (dladdr(addr, &dlinfo)) { 4991 st->print(PTR_FORMAT ": ", addr); 4992 if (dlinfo.dli_sname != NULL) { 4993 st->print("%s+%#x", dlinfo.dli_sname, 4994 addr - (intptr_t)dlinfo.dli_saddr); 4995 } else if (dlinfo.dli_fname) { 4996 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 4997 } else { 4998 st->print("<absolute address>"); 4999 } 5000 if (dlinfo.dli_fname) { 5001 st->print(" in %s", dlinfo.dli_fname); 5002 } 5003 if (dlinfo.dli_fbase) { 5004 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 5005 } 5006 st->cr(); 5007 5008 if (Verbose) { 5009 // decode some bytes around the PC 5010 address begin = same_page(addr-40, addr); 5011 address end = same_page(addr+40, addr); 5012 address lowest = (address) dlinfo.dli_sname; 5013 if (!lowest) lowest = (address) dlinfo.dli_fbase; 5014 if (begin < lowest) begin = lowest; 5015 Dl_info dlinfo2; 5016 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr 5017 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) 5018 end = (address) dlinfo2.dli_saddr; 5019 Disassembler::decode(begin, end, st); 5020 } 5021 return true; 5022 } 5023 return false; 5024 } 5025 5026 //////////////////////////////////////////////////////////////////////////////// 5027 // misc 5028 5029 // This does not do anything on Bsd. This is basically a hook for being 5030 // able to use structured exception handling (thread-local exception filters) 5031 // on, e.g., Win32. 5032 void 5033 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, 5034 JavaCallArguments* args, Thread* thread) { 5035 f(value, method, args, thread); 5036 } 5037 5038 void os::print_statistics() { 5039 } 5040 5041 int os::message_box(const char* title, const char* message) { 5042 int i; 5043 fdStream err(defaultStream::error_fd()); 5044 for (i = 0; i < 78; i++) err.print_raw("="); 5045 err.cr(); 5046 err.print_raw_cr(title); 5047 for (i = 0; i < 78; i++) err.print_raw("-"); 5048 err.cr(); 5049 err.print_raw_cr(message); 5050 for (i = 0; i < 78; i++) err.print_raw("="); 5051 err.cr(); 5052 5053 char buf[16]; 5054 // Prevent process from exiting upon "read error" without consuming all CPU 5055 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 5056 5057 return buf[0] == 'y' || buf[0] == 'Y'; 5058 } 5059 5060 int os::stat(const char *path, struct stat *sbuf) { 5061 char pathbuf[MAX_PATH]; 5062 if (strlen(path) > MAX_PATH - 1) { 5063 errno = ENAMETOOLONG; 5064 return -1; 5065 } 5066 os::native_path(strcpy(pathbuf, path)); 5067 return ::stat(pathbuf, sbuf); 5068 } 5069 5070 bool os::check_heap(bool force) { 5071 return true; 5072 } 5073 5074 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { 5075 return ::vsnprintf(buf, count, format, args); 5076 } 5077 5078 // Is a (classpath) directory empty? 5079 bool os::dir_is_empty(const char* path) { 5080 DIR *dir = NULL; 5081 struct dirent *ptr; 5082 5083 dir = opendir(path); 5084 if (dir == NULL) return true; 5085 5086 /* Scan the directory */ 5087 bool result = true; 5088 char buf[sizeof(struct dirent) + MAX_PATH]; 5089 while (result && (ptr = ::readdir(dir)) != NULL) { 5090 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 5091 result = false; 5092 } 5093 } 5094 closedir(dir); 5095 return result; 5096 } 5097 5098 // This code originates from JDK's sysOpen and open64_w 5099 // from src/solaris/hpi/src/system_md.c 5100 5101 #ifndef O_DELETE 5102 #define O_DELETE 0x10000 5103 #endif 5104 5105 // Open a file. Unlink the file immediately after open returns 5106 // if the specified oflag has the O_DELETE flag set. 5107 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c 5108 5109 int os::open(const char *path, int oflag, int mode) { 5110 5111 if (strlen(path) > MAX_PATH - 1) { 5112 errno = ENAMETOOLONG; 5113 return -1; 5114 } 5115 int fd; 5116 int o_delete = (oflag & O_DELETE); 5117 oflag = oflag & ~O_DELETE; 5118 5119 fd = ::open(path, oflag, mode); 5120 if (fd == -1) return -1; 5121 5122 //If the open succeeded, the file might still be a directory 5123 { 5124 struct stat buf; 5125 int ret = ::fstat(fd, &buf); 5126 int st_mode = buf.st_mode; 5127 5128 if (ret != -1) { 5129 if ((st_mode & S_IFMT) == S_IFDIR) { 5130 errno = EISDIR; 5131 ::close(fd); 5132 return -1; 5133 } 5134 } else { 5135 ::close(fd); 5136 return -1; 5137 } 5138 } 5139 5140 /* 5141 * All file descriptors that are opened in the JVM and not 5142 * specifically destined for a subprocess should have the 5143 * close-on-exec flag set. If we don't set it, then careless 3rd 5144 * party native code might fork and exec without closing all 5145 * appropriate file descriptors (e.g. as we do in closeDescriptors in 5146 * UNIXProcess.c), and this in turn might: 5147 * 5148 * - cause end-of-file to fail to be detected on some file 5149 * descriptors, resulting in mysterious hangs, or 5150 * 5151 * - might cause an fopen in the subprocess to fail on a system 5152 * suffering from bug 1085341. 5153 * 5154 * (Yes, the default setting of the close-on-exec flag is a Unix 5155 * design flaw) 5156 * 5157 * See: 5158 * 1085341: 32-bit stdio routines should support file descriptors >255 5159 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed 5160 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 5161 */ 5162 #ifdef FD_CLOEXEC 5163 { 5164 int flags = ::fcntl(fd, F_GETFD); 5165 if (flags != -1) 5166 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 5167 } 5168 #endif 5169 5170 if (o_delete != 0) { 5171 ::unlink(path); 5172 } 5173 return fd; 5174 } 5175 5176 5177 // create binary file, rewriting existing file if required 5178 int os::create_binary_file(const char* path, bool rewrite_existing) { 5179 int oflags = O_WRONLY | O_CREAT; 5180 if (!rewrite_existing) { 5181 oflags |= O_EXCL; 5182 } 5183 return ::open(path, oflags, S_IREAD | S_IWRITE); 5184 } 5185 5186 // return current position of file pointer 5187 jlong os::current_file_offset(int fd) { 5188 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR); 5189 } 5190 5191 // move file pointer to the specified offset 5192 jlong os::seek_to_file_offset(int fd, jlong offset) { 5193 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET); 5194 } 5195 5196 // This code originates from JDK's sysAvailable 5197 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c 5198 5199 int os::available(int fd, jlong *bytes) { 5200 jlong cur, end; 5201 int mode; 5202 struct stat buf; 5203 5204 if (::fstat(fd, &buf) >= 0) { 5205 mode = buf.st_mode; 5206 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 5207 /* 5208 * XXX: is the following call interruptible? If so, this might 5209 * need to go through the INTERRUPT_IO() wrapper as for other 5210 * blocking, interruptible calls in this file. 5211 */ 5212 int n; 5213 if (::ioctl(fd, FIONREAD, &n) >= 0) { 5214 *bytes = n; 5215 return 1; 5216 } 5217 } 5218 } 5219 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) { 5220 return 0; 5221 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) { 5222 return 0; 5223 } else if (::lseek(fd, cur, SEEK_SET) == -1) { 5224 return 0; 5225 } 5226 *bytes = end - cur; 5227 return 1; 5228 } 5229 5230 int os::socket_available(int fd, jint *pbytes) { 5231 if (fd < 0) 5232 return OS_OK; 5233 5234 int ret; 5235 5236 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret); 5237 5238 //%% note ioctl can return 0 when successful, JVM_SocketAvailable 5239 // is expected to return 0 on failure and 1 on success to the jdk. 5240 5241 return (ret == OS_ERR) ? 0 : 1; 5242 } 5243 5244 // Map a block of memory. 5245 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 5246 char *addr, size_t bytes, bool read_only, 5247 bool allow_exec) { 5248 int prot; 5249 int flags; 5250 5251 if (read_only) { 5252 prot = PROT_READ; 5253 flags = MAP_SHARED; 5254 } else { 5255 prot = PROT_READ | PROT_WRITE; 5256 flags = MAP_PRIVATE; 5257 } 5258 5259 if (allow_exec) { 5260 prot |= PROT_EXEC; 5261 } 5262 5263 if (addr != NULL) { 5264 flags |= MAP_FIXED; 5265 } 5266 5267 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 5268 fd, file_offset); 5269 if (mapped_address == MAP_FAILED) { 5270 return NULL; 5271 } 5272 return mapped_address; 5273 } 5274 5275 5276 // Remap a block of memory. 5277 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 5278 char *addr, size_t bytes, bool read_only, 5279 bool allow_exec) { 5280 // same as map_memory() on this OS 5281 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 5282 allow_exec); 5283 } 5284 5285 5286 // Unmap a block of memory. 5287 bool os::pd_unmap_memory(char* addr, size_t bytes) { 5288 return munmap(addr, bytes) == 0; 5289 } 5290 5291 #ifndef _ALLBSD_SOURCE 5292 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); 5293 5294 static clockid_t thread_cpu_clockid(Thread* thread) { 5295 pthread_t tid = thread->osthread()->pthread_id(); 5296 clockid_t clockid; 5297 5298 // Get thread clockid 5299 int rc = os::Bsd::pthread_getcpuclockid(tid, &clockid); 5300 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); 5301 return clockid; 5302 } 5303 #endif 5304 5305 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 5306 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 5307 // of a thread. 5308 // 5309 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 5310 // the fast estimate available on the platform. 5311 5312 jlong os::current_thread_cpu_time() { 5313 #ifdef __APPLE__ 5314 return os::thread_cpu_time(Thread::current(), true /* user + sys */); 5315 #elif !defined(_ALLBSD_SOURCE) 5316 if (os::Bsd::supports_fast_thread_cpu_time()) { 5317 return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5318 } else { 5319 // return user + sys since the cost is the same 5320 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); 5321 } 5322 #endif 5323 } 5324 5325 jlong os::thread_cpu_time(Thread* thread) { 5326 #ifndef _ALLBSD_SOURCE 5327 // consistent with what current_thread_cpu_time() returns 5328 if (os::Bsd::supports_fast_thread_cpu_time()) { 5329 return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5330 } else { 5331 return slow_thread_cpu_time(thread, true /* user + sys */); 5332 } 5333 #endif 5334 } 5335 5336 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 5337 #ifdef __APPLE__ 5338 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 5339 #elif !defined(_ALLBSD_SOURCE) 5340 if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) { 5341 return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 5342 } else { 5343 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); 5344 } 5345 #endif 5346 } 5347 5348 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5349 #ifdef __APPLE__ 5350 struct thread_basic_info tinfo; 5351 mach_msg_type_number_t tcount = THREAD_INFO_MAX; 5352 kern_return_t kr; 5353 thread_t mach_thread; 5354 5355 mach_thread = thread->osthread()->thread_id(); 5356 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount); 5357 if (kr != KERN_SUCCESS) 5358 return -1; 5359 5360 if (user_sys_cpu_time) { 5361 jlong nanos; 5362 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000; 5363 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000; 5364 return nanos; 5365 } else { 5366 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000); 5367 } 5368 #elif !defined(_ALLBSD_SOURCE) 5369 if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) { 5370 return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread)); 5371 } else { 5372 return slow_thread_cpu_time(thread, user_sys_cpu_time); 5373 } 5374 #endif 5375 } 5376 5377 #ifndef _ALLBSD_SOURCE 5378 // 5379 // -1 on error. 5380 // 5381 5382 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5383 static bool proc_pid_cpu_avail = true; 5384 static bool proc_task_unchecked = true; 5385 static const char *proc_stat_path = "/proc/%d/stat"; 5386 pid_t tid = thread->osthread()->thread_id(); 5387 int i; 5388 char *s; 5389 char stat[2048]; 5390 int statlen; 5391 char proc_name[64]; 5392 int count; 5393 long sys_time, user_time; 5394 char string[64]; 5395 char cdummy; 5396 int idummy; 5397 long ldummy; 5398 FILE *fp; 5399 5400 // We first try accessing /proc/<pid>/cpu since this is faster to 5401 // process. If this file is not present (bsd kernels 2.5 and above) 5402 // then we open /proc/<pid>/stat. 5403 if ( proc_pid_cpu_avail ) { 5404 sprintf(proc_name, "/proc/%d/cpu", tid); 5405 fp = fopen(proc_name, "r"); 5406 if ( fp != NULL ) { 5407 count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time); 5408 fclose(fp); 5409 if ( count != 3 ) return -1; 5410 5411 if (user_sys_cpu_time) { 5412 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 5413 } else { 5414 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 5415 } 5416 } 5417 else proc_pid_cpu_avail = false; 5418 } 5419 5420 // The /proc/<tid>/stat aggregates per-process usage on 5421 // new Bsd kernels 2.6+ where NPTL is supported. 5422 // The /proc/self/task/<tid>/stat still has the per-thread usage. 5423 // See bug 6328462. 5424 // There can be no directory /proc/self/task on kernels 2.4 with NPTL 5425 // and possibly in some other cases, so we check its availability. 5426 if (proc_task_unchecked && os::Bsd::is_NPTL()) { 5427 // This is executed only once 5428 proc_task_unchecked = false; 5429 fp = fopen("/proc/self/task", "r"); 5430 if (fp != NULL) { 5431 proc_stat_path = "/proc/self/task/%d/stat"; 5432 fclose(fp); 5433 } 5434 } 5435 5436 sprintf(proc_name, proc_stat_path, tid); 5437 fp = fopen(proc_name, "r"); 5438 if ( fp == NULL ) return -1; 5439 statlen = fread(stat, 1, 2047, fp); 5440 stat[statlen] = '\0'; 5441 fclose(fp); 5442 5443 // Skip pid and the command string. Note that we could be dealing with 5444 // weird command names, e.g. user could decide to rename java launcher 5445 // to "java 1.4.2 :)", then the stat file would look like 5446 // 1234 (java 1.4.2 :)) R ... ... 5447 // We don't really need to know the command string, just find the last 5448 // occurrence of ")" and then start parsing from there. See bug 4726580. 5449 s = strrchr(stat, ')'); 5450 i = 0; 5451 if (s == NULL ) return -1; 5452 5453 // Skip blank chars 5454 do s++; while (isspace(*s)); 5455 5456 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", 5457 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, 5458 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, 5459 &user_time, &sys_time); 5460 if ( count != 13 ) return -1; 5461 if (user_sys_cpu_time) { 5462 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 5463 } else { 5464 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 5465 } 5466 } 5467 #endif 5468 5469 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5470 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5471 info_ptr->may_skip_backward = false; // elapsed time not wall time 5472 info_ptr->may_skip_forward = false; // elapsed time not wall time 5473 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5474 } 5475 5476 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5477 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5478 info_ptr->may_skip_backward = false; // elapsed time not wall time 5479 info_ptr->may_skip_forward = false; // elapsed time not wall time 5480 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 5481 } 5482 5483 bool os::is_thread_cpu_time_supported() { 5484 #ifdef __APPLE__ 5485 return true; 5486 #elif defined(_ALLBSD_SOURCE) 5487 return false; 5488 #else 5489 return true; 5490 #endif 5491 } 5492 5493 // System loadavg support. Returns -1 if load average cannot be obtained. 5494 // Bsd doesn't yet have a (official) notion of processor sets, 5495 // so just return the system wide load average. 5496 int os::loadavg(double loadavg[], int nelem) { 5497 return ::getloadavg(loadavg, nelem); 5498 } 5499 5500 void os::pause() { 5501 char filename[MAX_PATH]; 5502 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 5503 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 5504 } else { 5505 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 5506 } 5507 5508 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 5509 if (fd != -1) { 5510 struct stat buf; 5511 ::close(fd); 5512 while (::stat(filename, &buf) == 0) { 5513 (void)::poll(NULL, 0, 100); 5514 } 5515 } else { 5516 jio_fprintf(stderr, 5517 "Could not open pause file '%s', continuing immediately.\n", filename); 5518 } 5519 } 5520 5521 5522 // Refer to the comments in os_solaris.cpp park-unpark. 5523 // 5524 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 5525 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 5526 // For specifics regarding the bug see GLIBC BUGID 261237 : 5527 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 5528 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 5529 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 5530 // is used. (The simple C test-case provided in the GLIBC bug report manifests the 5531 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 5532 // and monitorenter when we're using 1-0 locking. All those operations may result in 5533 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 5534 // of libpthread avoids the problem, but isn't practical. 5535 // 5536 // Possible remedies: 5537 // 5538 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 5539 // This is palliative and probabilistic, however. If the thread is preempted 5540 // between the call to compute_abstime() and pthread_cond_timedwait(), more 5541 // than the minimum period may have passed, and the abstime may be stale (in the 5542 // past) resultin in a hang. Using this technique reduces the odds of a hang 5543 // but the JVM is still vulnerable, particularly on heavily loaded systems. 5544 // 5545 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 5546 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set 5547 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 5548 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant 5549 // thread. 5550 // 5551 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 5552 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 5553 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). 5554 // This also works well. In fact it avoids kernel-level scalability impediments 5555 // on certain platforms that don't handle lots of active pthread_cond_timedwait() 5556 // timers in a graceful fashion. 5557 // 5558 // 4. When the abstime value is in the past it appears that control returns 5559 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 5560 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we 5561 // can avoid the problem by reinitializing the condvar -- by cond_destroy() 5562 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). 5563 // It may be possible to avoid reinitialization by checking the return 5564 // value from pthread_cond_timedwait(). In addition to reinitializing the 5565 // condvar we must establish the invariant that cond_signal() is only called 5566 // within critical sections protected by the adjunct mutex. This prevents 5567 // cond_signal() from "seeing" a condvar that's in the midst of being 5568 // reinitialized or that is corrupt. Sadly, this invariant obviates the 5569 // desirable signal-after-unlock optimization that avoids futile context switching. 5570 // 5571 // I'm also concerned that some versions of NTPL might allocate an auxilliary 5572 // structure when a condvar is used or initialized. cond_destroy() would 5573 // release the helper structure. Our reinitialize-after-timedwait fix 5574 // put excessive stress on malloc/free and locks protecting the c-heap. 5575 // 5576 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 5577 // It may be possible to refine (4) by checking the kernel and NTPL verisons 5578 // and only enabling the work-around for vulnerable environments. 5579 5580 // utility to compute the abstime argument to timedwait: 5581 // millis is the relative timeout time 5582 // abstime will be the absolute timeout time 5583 // TODO: replace compute_abstime() with unpackTime() 5584 5585 static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) { 5586 if (millis < 0) millis = 0; 5587 struct timeval now; 5588 int status = gettimeofday(&now, NULL); 5589 assert(status == 0, "gettimeofday"); 5590 jlong seconds = millis / 1000; 5591 millis %= 1000; 5592 if (seconds > 50000000) { // see man cond_timedwait(3T) 5593 seconds = 50000000; 5594 } 5595 abstime->tv_sec = now.tv_sec + seconds; 5596 long usec = now.tv_usec + millis * 1000; 5597 if (usec >= 1000000) { 5598 abstime->tv_sec += 1; 5599 usec -= 1000000; 5600 } 5601 abstime->tv_nsec = usec * 1000; 5602 return abstime; 5603 } 5604 5605 5606 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. 5607 // Conceptually TryPark() should be equivalent to park(0). 5608 5609 int os::PlatformEvent::TryPark() { 5610 for (;;) { 5611 const int v = _Event ; 5612 guarantee ((v == 0) || (v == 1), "invariant") ; 5613 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; 5614 } 5615 } 5616 5617 void os::PlatformEvent::park() { // AKA "down()" 5618 // Invariant: Only the thread associated with the Event/PlatformEvent 5619 // may call park(). 5620 // TODO: assert that _Assoc != NULL or _Assoc == Self 5621 int v ; 5622 for (;;) { 5623 v = _Event ; 5624 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 5625 } 5626 guarantee (v >= 0, "invariant") ; 5627 if (v == 0) { 5628 // Do this the hard way by blocking ... 5629 int status = pthread_mutex_lock(_mutex); 5630 assert_status(status == 0, status, "mutex_lock"); 5631 guarantee (_nParked == 0, "invariant") ; 5632 ++ _nParked ; 5633 while (_Event < 0) { 5634 status = pthread_cond_wait(_cond, _mutex); 5635 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 5636 // Treat this the same as if the wait was interrupted 5637 if (status == ETIMEDOUT) { status = EINTR; } 5638 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 5639 } 5640 -- _nParked ; 5641 5642 _Event = 0 ; 5643 status = pthread_mutex_unlock(_mutex); 5644 assert_status(status == 0, status, "mutex_unlock"); 5645 // Paranoia to ensure our locked and lock-free paths interact 5646 // correctly with each other. 5647 OrderAccess::fence(); 5648 } 5649 guarantee (_Event >= 0, "invariant") ; 5650 } 5651 5652 int os::PlatformEvent::park(jlong millis) { 5653 guarantee (_nParked == 0, "invariant") ; 5654 5655 int v ; 5656 for (;;) { 5657 v = _Event ; 5658 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 5659 } 5660 guarantee (v >= 0, "invariant") ; 5661 if (v != 0) return OS_OK ; 5662 5663 // We do this the hard way, by blocking the thread. 5664 // Consider enforcing a minimum timeout value. 5665 struct timespec abst; 5666 compute_abstime(&abst, millis); 5667 5668 int ret = OS_TIMEOUT; 5669 int status = pthread_mutex_lock(_mutex); 5670 assert_status(status == 0, status, "mutex_lock"); 5671 guarantee (_nParked == 0, "invariant") ; 5672 ++_nParked ; 5673 5674 // Object.wait(timo) will return because of 5675 // (a) notification 5676 // (b) timeout 5677 // (c) thread.interrupt 5678 // 5679 // Thread.interrupt and object.notify{All} both call Event::set. 5680 // That is, we treat thread.interrupt as a special case of notification. 5681 // The underlying Solaris implementation, cond_timedwait, admits 5682 // spurious/premature wakeups, but the JLS/JVM spec prevents the 5683 // JVM from making those visible to Java code. As such, we must 5684 // filter out spurious wakeups. We assume all ETIME returns are valid. 5685 // 5686 // TODO: properly differentiate simultaneous notify+interrupt. 5687 // In that case, we should propagate the notify to another waiter. 5688 5689 while (_Event < 0) { 5690 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst); 5691 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5692 pthread_cond_destroy (_cond); 5693 pthread_cond_init (_cond, NULL) ; 5694 } 5695 assert_status(status == 0 || status == EINTR || 5696 status == ETIMEDOUT, 5697 status, "cond_timedwait"); 5698 if (!FilterSpuriousWakeups) break ; // previous semantics 5699 if (status == ETIMEDOUT) break ; 5700 // We consume and ignore EINTR and spurious wakeups. 5701 } 5702 --_nParked ; 5703 if (_Event >= 0) { 5704 ret = OS_OK; 5705 } 5706 _Event = 0 ; 5707 status = pthread_mutex_unlock(_mutex); 5708 assert_status(status == 0, status, "mutex_unlock"); 5709 assert (_nParked == 0, "invariant") ; 5710 // Paranoia to ensure our locked and lock-free paths interact 5711 // correctly with each other. 5712 OrderAccess::fence(); 5713 return ret; 5714 } 5715 5716 void os::PlatformEvent::unpark() { 5717 // Transitions for _Event: 5718 // 0 :=> 1 5719 // 1 :=> 1 5720 // -1 :=> either 0 or 1; must signal target thread 5721 // That is, we can safely transition _Event from -1 to either 5722 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back 5723 // unpark() calls. 5724 // See also: "Semaphores in Plan 9" by Mullender & Cox 5725 // 5726 // Note: Forcing a transition from "-1" to "1" on an unpark() means 5727 // that it will take two back-to-back park() calls for the owning 5728 // thread to block. This has the benefit of forcing a spurious return 5729 // from the first park() call after an unpark() call which will help 5730 // shake out uses of park() and unpark() without condition variables. 5731 5732 if (Atomic::xchg(1, &_Event) >= 0) return; 5733 5734 // Wait for the thread associated with the event to vacate 5735 int status = pthread_mutex_lock(_mutex); 5736 assert_status(status == 0, status, "mutex_lock"); 5737 int AnyWaiters = _nParked; 5738 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 5739 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 5740 AnyWaiters = 0; 5741 pthread_cond_signal(_cond); 5742 } 5743 status = pthread_mutex_unlock(_mutex); 5744 assert_status(status == 0, status, "mutex_unlock"); 5745 if (AnyWaiters != 0) { 5746 status = pthread_cond_signal(_cond); 5747 assert_status(status == 0, status, "cond_signal"); 5748 } 5749 5750 // Note that we signal() _after dropping the lock for "immortal" Events. 5751 // This is safe and avoids a common class of futile wakeups. In rare 5752 // circumstances this can cause a thread to return prematurely from 5753 // cond_{timed}wait() but the spurious wakeup is benign and the victim will 5754 // simply re-test the condition and re-park itself. 5755 } 5756 5757 5758 // JSR166 5759 // ------------------------------------------------------- 5760 5761 /* 5762 * The solaris and bsd implementations of park/unpark are fairly 5763 * conservative for now, but can be improved. They currently use a 5764 * mutex/condvar pair, plus a a count. 5765 * Park decrements count if > 0, else does a condvar wait. Unpark 5766 * sets count to 1 and signals condvar. Only one thread ever waits 5767 * on the condvar. Contention seen when trying to park implies that someone 5768 * is unparking you, so don't wait. And spurious returns are fine, so there 5769 * is no need to track notifications. 5770 */ 5771 5772 #define MAX_SECS 100000000 5773 /* 5774 * This code is common to bsd and solaris and will be moved to a 5775 * common place in dolphin. 5776 * 5777 * The passed in time value is either a relative time in nanoseconds 5778 * or an absolute time in milliseconds. Either way it has to be unpacked 5779 * into suitable seconds and nanoseconds components and stored in the 5780 * given timespec structure. 5781 * Given time is a 64-bit value and the time_t used in the timespec is only 5782 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for 5783 * overflow if times way in the future are given. Further on Solaris versions 5784 * prior to 10 there is a restriction (see cond_timedwait) that the specified 5785 * number of seconds, in abstime, is less than current_time + 100,000,000. 5786 * As it will be 28 years before "now + 100000000" will overflow we can 5787 * ignore overflow and just impose a hard-limit on seconds using the value 5788 * of "now + 100,000,000". This places a limit on the timeout of about 3.17 5789 * years from "now". 5790 */ 5791 5792 static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) { 5793 assert (time > 0, "convertTime"); 5794 5795 struct timeval now; 5796 int status = gettimeofday(&now, NULL); 5797 assert(status == 0, "gettimeofday"); 5798 5799 time_t max_secs = now.tv_sec + MAX_SECS; 5800 5801 if (isAbsolute) { 5802 jlong secs = time / 1000; 5803 if (secs > max_secs) { 5804 absTime->tv_sec = max_secs; 5805 } 5806 else { 5807 absTime->tv_sec = secs; 5808 } 5809 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 5810 } 5811 else { 5812 jlong secs = time / NANOSECS_PER_SEC; 5813 if (secs >= MAX_SECS) { 5814 absTime->tv_sec = max_secs; 5815 absTime->tv_nsec = 0; 5816 } 5817 else { 5818 absTime->tv_sec = now.tv_sec + secs; 5819 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 5820 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5821 absTime->tv_nsec -= NANOSECS_PER_SEC; 5822 ++absTime->tv_sec; // note: this must be <= max_secs 5823 } 5824 } 5825 } 5826 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 5827 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 5828 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 5829 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 5830 } 5831 5832 void Parker::park(bool isAbsolute, jlong time) { 5833 // Ideally we'd do something useful while spinning, such 5834 // as calling unpackTime(). 5835 5836 // Optional fast-path check: 5837 // Return immediately if a permit is available. 5838 // We depend on Atomic::xchg() having full barrier semantics 5839 // since we are doing a lock-free update to _counter. 5840 if (Atomic::xchg(0, &_counter) > 0) return; 5841 5842 Thread* thread = Thread::current(); 5843 assert(thread->is_Java_thread(), "Must be JavaThread"); 5844 JavaThread *jt = (JavaThread *)thread; 5845 5846 // Optional optimization -- avoid state transitions if there's an interrupt pending. 5847 // Check interrupt before trying to wait 5848 if (Thread::is_interrupted(thread, false)) { 5849 return; 5850 } 5851 5852 // Next, demultiplex/decode time arguments 5853 struct timespec absTime; 5854 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all 5855 return; 5856 } 5857 if (time > 0) { 5858 unpackTime(&absTime, isAbsolute, time); 5859 } 5860 5861 5862 // Enter safepoint region 5863 // Beware of deadlocks such as 6317397. 5864 // The per-thread Parker:: mutex is a classic leaf-lock. 5865 // In particular a thread must never block on the Threads_lock while 5866 // holding the Parker:: mutex. If safepoints are pending both the 5867 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 5868 ThreadBlockInVM tbivm(jt); 5869 5870 // Don't wait if cannot get lock since interference arises from 5871 // unblocking. Also. check interrupt before trying wait 5872 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 5873 return; 5874 } 5875 5876 int status ; 5877 if (_counter > 0) { // no wait needed 5878 _counter = 0; 5879 status = pthread_mutex_unlock(_mutex); 5880 assert (status == 0, "invariant") ; 5881 // Paranoia to ensure our locked and lock-free paths interact 5882 // correctly with each other and Java-level accesses. 5883 OrderAccess::fence(); 5884 return; 5885 } 5886 5887 #ifdef ASSERT 5888 // Don't catch signals while blocked; let the running threads have the signals. 5889 // (This allows a debugger to break into the running thread.) 5890 sigset_t oldsigs; 5891 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals(); 5892 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 5893 #endif 5894 5895 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 5896 jt->set_suspend_equivalent(); 5897 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 5898 5899 if (time == 0) { 5900 status = pthread_cond_wait (_cond, _mutex) ; 5901 } else { 5902 status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ; 5903 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 5904 pthread_cond_destroy (_cond) ; 5905 pthread_cond_init (_cond, NULL); 5906 } 5907 } 5908 assert_status(status == 0 || status == EINTR || 5909 status == ETIMEDOUT, 5910 status, "cond_timedwait"); 5911 5912 #ifdef ASSERT 5913 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 5914 #endif 5915 5916 _counter = 0 ; 5917 status = pthread_mutex_unlock(_mutex) ; 5918 assert_status(status == 0, status, "invariant") ; 5919 // Paranoia to ensure our locked and lock-free paths interact 5920 // correctly with each other and Java-level accesses. 5921 OrderAccess::fence(); 5922 5923 // If externally suspended while waiting, re-suspend 5924 if (jt->handle_special_suspend_equivalent_condition()) { 5925 jt->java_suspend_self(); 5926 } 5927 } 5928 5929 void Parker::unpark() { 5930 int s, status ; 5931 status = pthread_mutex_lock(_mutex); 5932 assert (status == 0, "invariant") ; 5933 s = _counter; 5934 _counter = 1; 5935 if (s < 1) { 5936 if (WorkAroundNPTLTimedWaitHang) { 5937 status = pthread_cond_signal (_cond) ; 5938 assert (status == 0, "invariant") ; 5939 status = pthread_mutex_unlock(_mutex); 5940 assert (status == 0, "invariant") ; 5941 } else { 5942 status = pthread_mutex_unlock(_mutex); 5943 assert (status == 0, "invariant") ; 5944 status = pthread_cond_signal (_cond) ; 5945 assert (status == 0, "invariant") ; 5946 } 5947 } else { 5948 pthread_mutex_unlock(_mutex); 5949 assert (status == 0, "invariant") ; 5950 } 5951 } 5952 5953 5954 /* Darwin has no "environ" in a dynamic library. */ 5955 #ifdef __APPLE__ 5956 #include <crt_externs.h> 5957 #define environ (*_NSGetEnviron()) 5958 #else 5959 extern char** environ; 5960 #endif 5961 5962 // Run the specified command in a separate process. Return its exit value, 5963 // or -1 on failure (e.g. can't fork a new process). 5964 // Unlike system(), this function can be called from signal handler. It 5965 // doesn't block SIGINT et al. 5966 int os::fork_and_exec(char* cmd) { 5967 const char * argv[4] = {"sh", "-c", cmd, NULL}; 5968 5969 // fork() in BsdThreads/NPTL is not async-safe. It needs to run 5970 // pthread_atfork handlers and reset pthread library. All we need is a 5971 // separate process to execve. Make a direct syscall to fork process. 5972 // On IA64 there's no fork syscall, we have to use fork() and hope for 5973 // the best... 5974 pid_t pid = fork(); 5975 5976 if (pid < 0) { 5977 // fork failed 5978 return -1; 5979 5980 } else if (pid == 0) { 5981 // child process 5982 5983 // execve() in BsdThreads will call pthread_kill_other_threads_np() 5984 // first to kill every thread on the thread list. Because this list is 5985 // not reset by fork() (see notes above), execve() will instead kill 5986 // every thread in the parent process. We know this is the only thread 5987 // in the new process, so make a system call directly. 5988 // IA64 should use normal execve() from glibc to match the glibc fork() 5989 // above. 5990 execve("/bin/sh", (char* const*)argv, environ); 5991 5992 // execve failed 5993 _exit(-1); 5994 5995 } else { 5996 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 5997 // care about the actual exit code, for now. 5998 5999 int status; 6000 6001 // Wait for the child process to exit. This returns immediately if 6002 // the child has already exited. */ 6003 while (waitpid(pid, &status, 0) < 0) { 6004 switch (errno) { 6005 case ECHILD: return 0; 6006 case EINTR: break; 6007 default: return -1; 6008 } 6009 } 6010 6011 if (WIFEXITED(status)) { 6012 // The child exited normally; get its exit code. 6013 return WEXITSTATUS(status); 6014 } else if (WIFSIGNALED(status)) { 6015 // The child exited because of a signal 6016 // The best value to return is 0x80 + signal number, 6017 // because that is what all Unix shells do, and because 6018 // it allows callers to distinguish between process exit and 6019 // process death by signal. 6020 return 0x80 + WTERMSIG(status); 6021 } else { 6022 // Unknown exit code; pass it through 6023 return status; 6024 } 6025 } 6026 } 6027 6028 // is_headless_jre() 6029 // 6030 // Test for the existence of xawt/libmawt.so or libawt_xawt.so 6031 // in order to report if we are running in a headless jre 6032 // 6033 // Since JDK8 xawt/libmawt.so was moved into the same directory 6034 // as libawt.so, and renamed libawt_xawt.so 6035 // 6036 bool os::is_headless_jre() { 6037 struct stat statbuf; 6038 char buf[MAXPATHLEN]; 6039 char libmawtpath[MAXPATHLEN]; 6040 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX; 6041 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX; 6042 char *p; 6043 6044 // Get path to libjvm.so 6045 os::jvm_path(buf, sizeof(buf)); 6046 6047 // Get rid of libjvm.so 6048 p = strrchr(buf, '/'); 6049 if (p == NULL) return false; 6050 else *p = '\0'; 6051 6052 // Get rid of client or server 6053 p = strrchr(buf, '/'); 6054 if (p == NULL) return false; 6055 else *p = '\0'; 6056 6057 // check xawt/libmawt.so 6058 strcpy(libmawtpath, buf); 6059 strcat(libmawtpath, xawtstr); 6060 if (::stat(libmawtpath, &statbuf) == 0) return false; 6061 6062 // check libawt_xawt.so 6063 strcpy(libmawtpath, buf); 6064 strcat(libmawtpath, new_xawtstr); 6065 if (::stat(libmawtpath, &statbuf) == 0) return false; 6066 6067 return true; 6068 } 6069 6070 // Get the default path to the core file 6071 // Returns the length of the string 6072 int os::get_core_path(char* buffer, size_t bufferSize) { 6073 int n = jio_snprintf(buffer, bufferSize, "/cores"); 6074 6075 // Truncate if theoretical string was longer than bufferSize 6076 n = MIN2(n, (int)bufferSize); 6077 6078 return n; 6079 } 6080 6081 #ifndef PRODUCT 6082 void TestReserveMemorySpecial_test() { 6083 // No tests available for this platform 6084 } 6085 #endif 6086