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