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