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