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