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