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