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