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