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