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