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