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