os_bsd.cpp revision 7051:0420e825bb3c
1145357Ssuz/* 262655Skris * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. 356668Sshin * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 456668Sshin * 556668Sshin * This code is free software; you can redistribute it and/or modify it 662655Skris * under the terms of the GNU General Public License version 2 only, as 756668Sshin * published by the Free Software Foundation. 856668Sshin * 956668Sshin * This code is distributed in the hope that it will be useful, but WITHOUT 1056668Sshin * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1156668Sshin * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1256668Sshin * version 2 for more details (a copy is included in the LICENSE file that 1356668Sshin * accompanied this code). 1456668Sshin * 1556668Sshin * You should have received a copy of the GNU General Public License version 1656668Sshin * 2 along with this work; if not, write to the Free Software Foundation, 1756668Sshin * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1862655Skris * 1956668Sshin * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2056668Sshin * or visit www.oracle.com if you need additional information or have any 2156668Sshin * questions. 2256668Sshin * 2356668Sshin */ 2456668Sshin 2556668Sshin// no precompiled headers 2656668Sshin#include "classfile/classLoader.hpp" 2756668Sshin#include "classfile/systemDictionary.hpp" 2856668Sshin#include "classfile/vmSymbols.hpp" 2956668Sshin#include "code/icBuffer.hpp" 3056668Sshin#include "code/vtableStubs.hpp" 3156668Sshin#include "compiler/compileBroker.hpp" 3256668Sshin#include "compiler/disassembler.hpp" 3356668Sshin#include "interpreter/interpreter.hpp" 3456668Sshin#include "jvm_bsd.h" 3556668Sshin#include "memory/allocation.inline.hpp" 3656668Sshin#include "memory/filemap.hpp" 3756668Sshin#include "mutex_bsd.inline.hpp" 3856668Sshin#include "oops/oop.inline.hpp" 3956668Sshin#include "os_bsd.inline.hpp" 4056668Sshin#include "os_share_bsd.hpp" 4156668Sshin#include "prims/jniFastGetField.hpp" 4256668Sshin#include "prims/jvm.h" 4356668Sshin#include "prims/jvm_misc.hpp" 4456668Sshin#include "runtime/arguments.hpp" 45122679Sume#include "runtime/atomic.inline.hpp" 46122679Sume#include "runtime/extendedPC.hpp" 47122679Sume#include "runtime/globals.hpp" 4856668Sshin#include "runtime/interfaceSupport.hpp" 4956668Sshin#include "runtime/java.hpp" 5056668Sshin#include "runtime/javaCalls.hpp" 5156668Sshin#include "runtime/mutexLocker.hpp" 5256668Sshin#include "runtime/objectMonitor.hpp" 5356668Sshin#include "runtime/orderAccess.inline.hpp" 5456668Sshin#include "runtime/osThread.hpp" 5556668Sshin#include "runtime/perfMemory.hpp" 5656668Sshin#include "runtime/sharedRuntime.hpp" 5756668Sshin#include "runtime/statSampler.hpp" 5856668Sshin#include "runtime/stubRoutines.hpp" 5956668Sshin#include "runtime/thread.inline.hpp" 6056668Sshin#include "runtime/threadCritical.hpp" 6156668Sshin#include "runtime/timer.hpp" 6256668Sshin#include "services/attachListener.hpp" 6356668Sshin#include "services/memTracker.hpp" 6456668Sshin#include "services/runtimeService.hpp" 6556668Sshin#include "utilities/decoder.hpp" 6656668Sshin#include "utilities/defaultStream.hpp" 6756668Sshin#include "utilities/events.hpp" 6856668Sshin#include "utilities/growableArray.hpp" 6956668Sshin#include "utilities/vmError.hpp" 70173412Skevlo 71173412Skevlo// put OS-includes here 72173412Skevlo# include <sys/types.h> 73173412Skevlo# include <sys/mman.h> 74173412Skevlo# include <sys/stat.h> 7556668Sshin# include <sys/select.h> 7656668Sshin# include <pthread.h> 7756668Sshin# include <signal.h> 7856668Sshin# include <errno.h> 79122679Sume# include <dlfcn.h> 80122679Sume# include <stdio.h> 81122679Sume# include <unistd.h> 8256668Sshin# include <sys/resource.h> 83122679Sume# include <pthread.h> 8456668Sshin# include <sys/stat.h> 8556668Sshin# include <sys/time.h> 8656668Sshin# include <sys/times.h> 8756668Sshin# include <sys/utsname.h> 8856668Sshin# include <sys/socket.h> 8956668Sshin# include <sys/wait.h> 9056668Sshin# include <time.h> 91122679Sume# include <pwd.h> 92122679Sume# include <poll.h> 93122679Sume# include <semaphore.h> 94122679Sume# include <fcntl.h> 95122679Sume# include <string.h> 96122679Sume# include <sys/param.h> 97122679Sume# include <sys/sysctl.h> 98122679Sume# include <sys/ipc.h> 99122679Sume# include <sys/shm.h> 100122679Sume#ifndef __APPLE__ 101122679Sume# include <link.h> 102122679Sume#endif 103122679Sume# include <stdint.h> 104122679Sume# include <inttypes.h> 105122679Sume# include <sys/ioctl.h> 106122679Sume# include <sys/syscall.h> 107122679Sume 108122679Sume#if defined(__FreeBSD__) || defined(__NetBSD__) 109122679Sume #include <elf.h> 110122679Sume#endif 111122679Sume 112122679Sume#ifdef __APPLE__ 113122679Sume #include <mach/mach.h> // semaphore_* API 114122679Sume #include <mach-o/dyld.h> 115122679Sume #include <sys/proc_info.h> 116122679Sume #include <objc/objc-auto.h> 117122679Sume#endif 118122679Sume 119122679Sume#ifndef MAP_ANONYMOUS 120122679Sume #define MAP_ANONYMOUS MAP_ANON 121122679Sume#endif 122122679Sume 123122679Sume#define MAX_PATH (2 * K) 12456668Sshin 125122679Sume// for timer info max values which include all bits 126122679Sume#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 12756668Sshin 128122679Sume#define LARGEPAGES_BIT (1 << 6) 129122679Sume 130122679SumePRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 13156668Sshin 132122679Sume//////////////////////////////////////////////////////////////////////////////// 133122679Sume// global variables 134122679Sumejulong os::Bsd::_physical_memory = 0; 135122679Sume 13656668Sshin#ifdef __APPLE__ 137122679Sumemach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0}; 138122679Sumevolatile uint64_t os::Bsd::_max_abstime = 0; 139122679Sume#else 140122679Sumeint (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL; 141122679Sume#endif 14256668Sshinpthread_t os::Bsd::_main_thread; 143122679Sumeint os::Bsd::_page_size = -1; 144122679Sume 14556668Sshinstatic jlong initial_time_count=0; 146122679Sume 147122679Sumestatic int clock_tics_per_sec = 100; 148122679Sume 14956668Sshin// For diagnostics to print a message once. see run_periodic_checks 150122679Sumestatic sigset_t check_signal_done; 151122679Sumestatic bool check_signals = true; 152122679Sume 153122679Sumestatic pid_t _initial_pid = 0; 154122679Sume 15556668Sshin// Signal number used to suspend/resume a thread 156122679Sume 157122679Sume// do not use any signal number less than SIGSEGV, see 4355769 15856668Sshinstatic int SR_signum = SIGUSR2; 159122679Sumesigset_t SR_sigset; 16056668Sshin 16156668Sshin 16256668Sshin//////////////////////////////////////////////////////////////////////////////// 163122679Sume// utility functions 164122679Sume 165122679Sumestatic int SR_initialize(); 166122679Sumestatic void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 167122679Sume 168122679Sumejulong os::available_memory() { 169122679Sume return Bsd::available_memory(); 170122679Sume} 171122679Sume 17295023Ssuz// available here means free 173122679Sumejulong os::Bsd::available_memory() { 174122679Sume uint64_t available = physical_memory() >> 2; 17556668Sshin#ifdef __APPLE__ 17656668Sshin mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; 17756668Sshin vm_statistics64_data_t vmstat; 17856668Sshin kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64, 17956668Sshin (host_info64_t)&vmstat, &count); 18056668Sshin assert(kerr == KERN_SUCCESS, 18156668Sshin "host_statistics64 failed - check mach_host_self() and count"); 18256668Sshin if (kerr == KERN_SUCCESS) { 18356668Sshin available = vmstat.free_count * os::vm_page_size(); 184122679Sume } 185122679Sume#endif 186122679Sume return available; 187122679Sume} 188122679Sume 189122679Sumejulong os::physical_memory() { 19056668Sshin return Bsd::physical_memory(); 19156668Sshin} 19256668Sshin 19356668Sshin//////////////////////////////////////////////////////////////////////////////// 19456668Sshin// environment support 19556668Sshin 19681981Sbrianbool os::getenv(const char* name, char* buf, int len) { 19756668Sshin const char* val = ::getenv(name); 19881981Sbrian if (val != NULL && strlen(val) < (size_t)len) { 19956668Sshin strcpy(buf, val); 20056668Sshin return true; 20156668Sshin } 202122679Sume if (len > 0) buf[0] = 0; // return a null string 20356668Sshin return false; 20456668Sshin} 205122679Sume 206122679Sume 207122679Sume// Return true if user is running as root. 208122679Sume 209122679Sumebool os::have_special_privileges() { 210122679Sume static bool init = false; 21156668Sshin static bool privileges = false; 21256668Sshin if (!init) { 21356668Sshin privileges = (getuid() != geteuid()) || (getgid() != getegid()); 21456668Sshin init = true; 21556668Sshin } 21656668Sshin return privileges; 21781981Sbrian} 21856668Sshin 21981981Sbrian 22056668Sshin 22156668Sshin// Cpu architecture string 22256668Sshin#if defined(ZERO) 223122679Sumestatic char cpu_arch[] = ZERO_LIBARCH; 22456668Sshin#elif defined(IA64) 22556668Sshinstatic char cpu_arch[] = "ia64"; 226122679Sume#elif defined(IA32) 227122679Sumestatic char cpu_arch[] = "i386"; 228122679Sume#elif defined(AMD64) 229122679Sumestatic char cpu_arch[] = "amd64"; 230122679Sume#elif defined(ARM) 231122679Sumestatic char cpu_arch[] = "arm"; 23256668Sshin#elif defined(PPC32) 23356668Sshinstatic char cpu_arch[] = "ppc"; 23456668Sshin#elif defined(SPARC) 23556668Sshin #ifdef _LP64 236122679Sumestatic char cpu_arch[] = "sparcv9"; 237122679Sume #else 238122679Sumestatic char cpu_arch[] = "sparc"; 23956668Sshin #endif 240122679Sume#else 24156668Sshin #error Add appropriate cpu_arch setting 24256668Sshin#endif 24356668Sshin 24456668Sshin// Compiler variant 24556668Sshin#ifdef COMPILER2 24656668Sshin #define COMPILER_VARIANT "server" 24756668Sshin#else 24856668Sshin #define COMPILER_VARIANT "client" 24956668Sshin#endif 25056668Sshin 25156668Sshin 25256668Sshinvoid os::Bsd::initialize_system_info() { 25356668Sshin int mib[2]; 25456668Sshin size_t len; 255122679Sume int cpu_val; 256122679Sume julong mem_val; 257122679Sume 258122679Sume // get processors count via hw.ncpus sysctl 259122679Sume mib[0] = CTL_HW; 260122679Sume mib[1] = HW_NCPU; 26156668Sshin len = sizeof(cpu_val); 26256668Sshin if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) { 26356668Sshin assert(len == sizeof(cpu_val), "unexpected data size"); 26456668Sshin set_processor_count(cpu_val); 265122679Sume } else { 266122679Sume set_processor_count(1); // fallback 267122679Sume } 26856668Sshin 269122679Sume // get physical memory via hw.memsize sysctl (hw.memsize is used 27056668Sshin // since it returns a 64 bit value) 27156668Sshin mib[0] = CTL_HW; 27256668Sshin 27356668Sshin#if defined (HW_MEMSIZE) // Apple 27456668Sshin mib[1] = HW_MEMSIZE; 27556668Sshin#elif defined(HW_PHYSMEM) // Most of BSD 27656668Sshin mib[1] = HW_PHYSMEM; 27756668Sshin#elif defined(HW_REALMEM) // Old FreeBSD 27856668Sshin mib[1] = HW_REALMEM; 27956668Sshin#else 28056668Sshin #error No ways to get physmem 28156668Sshin#endif 28256668Sshin 28356668Sshin len = sizeof(mem_val); 28456668Sshin if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) { 285122679Sume assert(len == sizeof(mem_val), "unexpected data size"); 286122679Sume _physical_memory = mem_val; 287122679Sume } else { 288122679Sume _physical_memory = 256 * 1024 * 1024; // fallback (XXXBSD?) 289122679Sume } 290122679Sume 29156668Sshin#ifdef __OpenBSD__ 29256668Sshin { 29356668Sshin // limit _physical_memory memory view on OpenBSD since 29456668Sshin // datasize rlimit restricts us anyway. 29556668Sshin struct rlimit limits; 296122679Sume getrlimit(RLIMIT_DATA, &limits); 297122679Sume _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur); 298122679Sume } 299122679Sume#endif 300122679Sume} 301122679Sume 30256668Sshin#ifdef __APPLE__ 30356668Sshinstatic const char *get_home() { 30456668Sshin const char *home_dir = ::getenv("HOME"); 30556668Sshin if ((home_dir == NULL) || (*home_dir == '\0')) { 30656668Sshin struct passwd *passwd_info = getpwuid(geteuid()); 30756668Sshin if (passwd_info != NULL) { 30856668Sshin home_dir = passwd_info->pw_dir; 30956668Sshin } 31056668Sshin } 31195023Ssuz 31256668Sshin return home_dir; 31356668Sshin} 31456668Sshin#endif 31556668Sshin 31656668Sshinvoid os::init_system_properties_values() { 317122679Sume // The next steps are taken in the product version: 31856668Sshin // 319122679Sume // Obtain the JAVA_HOME value from the location of libjvm.so. 320122679Sume // This library should be located at: 321122679Sume // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 32256668Sshin // 323122679Sume // If "/jre/lib/" appears at the right place in the path, then we 32456668Sshin // assume libjvm.so is installed in a JDK and we use this path. 32556668Sshin // 32656668Sshin // Otherwise exit with message: "Could not create the Java virtual machine." 32756668Sshin // 328122679Sume // The following extra steps are taken in the debugging version: 329122679Sume // 330122679Sume // If "/jre/lib/" does NOT appear at the right place in the path 331122679Sume // instead of exit check for $JAVA_HOME environment variable. 33256668Sshin // 333122679Sume // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 334122679Sume // then we append a fake suffix "hotspot/libjvm.so" to this path so 33556668Sshin // it looks like libjvm.so is installed there 336122679Sume // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 33756668Sshin // 338122679Sume // Otherwise exit. 33956668Sshin // 340122679Sume // Important note: if the location of libjvm.so changes this 341122679Sume // code needs to be changed accordingly. 342122679Sume 343122679Sume // See ld(1): 344122679Sume // The linker uses the following search paths to locate required 345122679Sume // shared libraries: 346122679Sume // 1: ... 347122679Sume // ... 34856668Sshin // 7: The default directories, normally /lib and /usr/lib. 34956668Sshin#ifndef DEFAULT_LIBPATH 35056668Sshin #define DEFAULT_LIBPATH "/lib:/usr/lib" 35156668Sshin#endif 35256668Sshin 35356668Sshin// Base path of extensions installed on the system. 35456668Sshin#define SYS_EXT_DIR "/usr/java/packages" 35556668Sshin#define EXTENSIONS_DIR "/lib/ext" 35656668Sshin#define ENDORSED_DIR "/lib/endorsed" 35756668Sshin 35856668Sshin#ifndef __APPLE__ 35956668Sshin 36056668Sshin // Buffer that fits several sprintfs. 36156668Sshin // Note that the space for the colon and the trailing null are provided 36256668Sshin // by the nulls included by the sizeof operator. 36356668Sshin const size_t bufsize = 36456668Sshin MAX3((size_t)MAXPATHLEN, // For dll_dir & friends. 36595355Sume (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir 36656668Sshin (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir 36756668Sshin char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 36856668Sshin 36956668Sshin // sysclasspath, java_home, dll_dir 37056668Sshin { 37156668Sshin char *pslash; 37256668Sshin os::jvm_path(buf, bufsize); 37356668Sshin 37456668Sshin // Found the full path to libjvm.so. 37556668Sshin // Now cut the path to <java_home>/jre if we can. 37656668Sshin *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 37756668Sshin pslash = strrchr(buf, '/'); 37856668Sshin if (pslash != NULL) { 37956668Sshin *pslash = '\0'; // Get rid of /{client|server|hotspot}. 38056668Sshin } 381122679Sume Arguments::set_dll_dir(buf); 38256668Sshin 383122679Sume if (pslash != NULL) { 384122679Sume pslash = strrchr(buf, '/'); 385122679Sume if (pslash != NULL) { 38656668Sshin *pslash = '\0'; // Get rid of /<arch>. 387122679Sume pslash = strrchr(buf, '/'); 38856668Sshin if (pslash != NULL) { 38956668Sshin *pslash = '\0'; // Get rid of /lib. 39056668Sshin } 39156668Sshin } 392122679Sume } 393122679Sume Arguments::set_java_home(buf); 394122679Sume set_boot_path('/', ':'); 395122679Sume } 39656668Sshin 397122679Sume // Where to look for native libraries. 398122679Sume // 39956668Sshin // Note: Due to a legacy implementation, most of the library path 400122679Sume // is set in the launcher. This was to accomodate linking restrictions 40156668Sshin // on legacy Bsd implementations (which are no longer supported). 40256668Sshin // Eventually, all the library path setting will be done here. 403122679Sume // 404122679Sume // However, to prevent the proliferation of improperly built native 405122679Sume // libraries, the new path component /usr/java/packages is added here. 406122679Sume // Eventually, all the library path setting will be done here. 407122679Sume { 408122679Sume // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 409122679Sume // should always exist (until the legacy problem cited above is 410122679Sume // addressed). 411122679Sume const char *v = ::getenv("LD_LIBRARY_PATH"); 41256668Sshin const char *v_colon = ":"; 41356668Sshin if (v == NULL) { v = ""; v_colon = ""; } 41456668Sshin // That's +1 for the colon and +1 for the trailing '\0'. 41556668Sshin char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 41656668Sshin strlen(v) + 1 + 41756668Sshin sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1, 41856668Sshin mtInternal); 41956668Sshin sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch); 42056668Sshin Arguments::set_library_path(ld_library_path); 42156668Sshin FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal); 42256668Sshin } 42356668Sshin 42456668Sshin // Extensions directories. 42556668Sshin sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 42656668Sshin Arguments::set_ext_dirs(buf); 42756668Sshin 42856668Sshin // Endorsed standards default directory. 42995355Sume sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 43056668Sshin Arguments::set_endorsed_dirs(buf); 43156668Sshin 43256668Sshin FREE_C_HEAP_ARRAY(char, buf, mtInternal); 43356668Sshin 43456668Sshin#else // __APPLE__ 43556668Sshin 43656668Sshin #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions" 43756668Sshin #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java" 43856668Sshin 43956668Sshin const char *user_home_dir = get_home(); 44056668Sshin // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir. 44156668Sshin size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) + 44256668Sshin sizeof(SYS_EXTENSIONS_DIRS); 44356668Sshin 44456668Sshin // Buffer that fits several sprintfs. 445122679Sume // Note that the space for the colon and the trailing null are provided 44656668Sshin // by the nulls included by the sizeof operator. 44756668Sshin const size_t bufsize = 44856668Sshin MAX3((size_t)MAXPATHLEN, // for dll_dir & friends. 44956668Sshin (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir 45056668Sshin (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir 45156668Sshin char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 45256668Sshin 45356668Sshin // sysclasspath, java_home, dll_dir 45456668Sshin { 45556668Sshin char *pslash; 45656668Sshin os::jvm_path(buf, bufsize); 45756668Sshin 45856668Sshin // Found the full path to libjvm.so. 45956668Sshin // Now cut the path to <java_home>/jre if we can. 46056668Sshin *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 46156668Sshin pslash = strrchr(buf, '/'); 46256668Sshin if (pslash != NULL) { 46356668Sshin *pslash = '\0'; // Get rid of /{client|server|hotspot}. 46456668Sshin } 46556668Sshin Arguments::set_dll_dir(buf); 46656668Sshin 46756668Sshin if (pslash != NULL) { 46856668Sshin pslash = strrchr(buf, '/'); 46956668Sshin if (pslash != NULL) { 47056668Sshin *pslash = '\0'; // Get rid of /lib. 47156668Sshin } 47256668Sshin } 47356668Sshin Arguments::set_java_home(buf); 47495023Ssuz set_boot_path('/', ':'); 47556668Sshin } 47656668Sshin 47756668Sshin // Where to look for native libraries. 47856668Sshin // 47956668Sshin // Note: Due to a legacy implementation, most of the library path 48056668Sshin // is set in the launcher. This was to accomodate linking restrictions 48156668Sshin // on legacy Bsd implementations (which are no longer supported). 482122679Sume // Eventually, all the library path setting will be done here. 483122679Sume // 48456668Sshin // However, to prevent the proliferation of improperly built native 48556668Sshin // libraries, the new path component /usr/java/packages is added here. 486122679Sume // Eventually, all the library path setting will be done here. 487122679Sume { 48856668Sshin // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 48956668Sshin // should always exist (until the legacy problem cited above is 49056668Sshin // addressed). 49156668Sshin // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code 49256668Sshin // can specify a directory inside an app wrapper 49356668Sshin const char *l = ::getenv("JAVA_LIBRARY_PATH"); 49456668Sshin const char *l_colon = ":"; 49556668Sshin if (l == NULL) { l = ""; l_colon = ""; } 49656668Sshin 49756668Sshin const char *v = ::getenv("DYLD_LIBRARY_PATH"); 49856668Sshin const char *v_colon = ":"; 49956668Sshin if (v == NULL) { v = ""; v_colon = ""; } 50056668Sshin 50156668Sshin // Apple's Java6 has "." at the beginning of java.library.path. 50256668Sshin // OpenJDK on Windows has "." at the end of java.library.path. 50356668Sshin // OpenJDK on Linux and Solaris don't have "." in java.library.path 50456668Sshin // at all. To ease the transition from Apple's Java6 to OpenJDK7, 50556668Sshin // "." is appended to the end of java.library.path. Yes, this 50656668Sshin // could cause a change in behavior, but Apple's Java6 behavior 50756668Sshin // can be achieved by putting "." at the beginning of the 50856668Sshin // JAVA_LIBRARY_PATH environment variable. 50956668Sshin char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 51056668Sshin strlen(v) + 1 + strlen(l) + 1 + 51156668Sshin system_ext_size + 3, 51256668Sshin mtInternal); 51356668Sshin sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.", 51456668Sshin v, v_colon, l, l_colon, user_home_dir); 51556668Sshin Arguments::set_library_path(ld_library_path); 51656668Sshin FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal); 51756668Sshin } 51856668Sshin 51956668Sshin // Extensions directories. 52056668Sshin // 52156668Sshin // Note that the space for the colon and the trailing null are provided 52256668Sshin // by the nulls included by the sizeof operator (so actually one byte more 52356668Sshin // than necessary is allocated). 52456668Sshin sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, 52556668Sshin user_home_dir, Arguments::get_java_home()); 52656668Sshin Arguments::set_ext_dirs(buf); 52756668Sshin 52856668Sshin // Endorsed standards default directory. 52956668Sshin sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 53056668Sshin Arguments::set_endorsed_dirs(buf); 53156668Sshin 53256668Sshin FREE_C_HEAP_ARRAY(char, buf, mtInternal); 53356668Sshin 53456668Sshin#undef SYS_EXTENSIONS_DIR 53556668Sshin#undef SYS_EXTENSIONS_DIRS 53656668Sshin 53756668Sshin#endif // __APPLE__ 53856668Sshin 53956668Sshin#undef SYS_EXT_DIR 54062655Skris#undef EXTENSIONS_DIR 541122679Sume#undef ENDORSED_DIR 542122679Sume} 54356668Sshin 54456668Sshin//////////////////////////////////////////////////////////////////////////////// 545122679Sume// breakpoint support 546122679Sume 547122679Sumevoid os::breakpoint() { 54856668Sshin BREAKPOINT; 54956668Sshin} 55056668Sshin 55156668Sshinextern "C" void breakpoint() { 55256668Sshin // use debugger to set breakpoint here 55356668Sshin} 55456668Sshin 55556668Sshin//////////////////////////////////////////////////////////////////////////////// 55656668Sshin// signal support 55756668Sshin 55856668Sshindebug_only(static bool signal_sets_initialized = false); 55956668Sshinstatic sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 56056668Sshin 56156668Sshinbool os::Bsd::is_sig_ignored(int sig) { 56256668Sshin struct sigaction oact; 56356668Sshin sigaction(sig, (struct sigaction*)NULL, &oact); 56456668Sshin void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 56565994Sume : CAST_FROM_FN_PTR(void*, oact.sa_handler); 56665994Sume if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) { 56765994Sume return true; 56865994Sume } else { 56956668Sshin return false; 57056668Sshin } 57156668Sshin} 57256668Sshin 57356668Sshinvoid os::Bsd::signal_sets_init() { 57456668Sshin // Should also have an assertion stating we are still single-threaded. 57556668Sshin assert(!signal_sets_initialized, "Already initialized"); 57656668Sshin // Fill in signals that are necessarily unblocked for all threads in 57756668Sshin // the VM. Currently, we unblock the following signals: 57856668Sshin // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 57956668Sshin // by -Xrs (=ReduceSignalUsage)); 58056668Sshin // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 58156668Sshin // other threads. The "ReduceSignalUsage" boolean tells us not to alter 58256668Sshin // the dispositions or masks wrt these signals. 58356668Sshin // Programs embedding the VM that want to use the above signals for their 58456668Sshin // own purposes must, at this time, use the "-Xrs" option to prevent 58556668Sshin // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 58656668Sshin // (See bug 4345157, and other related bugs). 58765994Sume // In reality, though, unblocking these signals is really a nop, since 58856668Sshin // these signals are not blocked by default. 58956668Sshin sigemptyset(&unblocked_sigs); 59056668Sshin sigemptyset(&allowdebug_blocked_sigs); 59165994Sume sigaddset(&unblocked_sigs, SIGILL); 59265994Sume sigaddset(&unblocked_sigs, SIGSEGV); 59356668Sshin sigaddset(&unblocked_sigs, SIGBUS); 59456668Sshin sigaddset(&unblocked_sigs, SIGFPE); 59556668Sshin sigaddset(&unblocked_sigs, SR_signum); 59656668Sshin 59756668Sshin if (!ReduceSignalUsage) { 59856668Sshin if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 59956668Sshin sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 60056668Sshin sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 60156668Sshin } 60256668Sshin if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 60356668Sshin sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 60456668Sshin sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 60556668Sshin } 60656668Sshin if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 60756668Sshin sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 60856668Sshin sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 60956668Sshin } 61056668Sshin } 61156668Sshin // Fill in signals that are blocked by all but the VM thread. 61256668Sshin sigemptyset(&vm_sigs); 61356668Sshin if (!ReduceSignalUsage) { 61456668Sshin sigaddset(&vm_sigs, BREAK_SIGNAL); 61556668Sshin } 61656668Sshin debug_only(signal_sets_initialized = true); 61756668Sshin 61856668Sshin} 61956668Sshin 620122679Sume// These are signals that are unblocked while a thread is running Java. 621122679Sume// (For some reason, they get blocked by default.) 622122679Sumesigset_t* os::Bsd::unblocked_signals() { 623122679Sume assert(signal_sets_initialized, "Not initialized"); 624122679Sume return &unblocked_sigs; 62556668Sshin} 62656668Sshin 62756668Sshin// These are the signals that are blocked while a (non-VM) thread is 62856668Sshin// running Java. Only the VM thread handles these signals. 62956668Sshinsigset_t* os::Bsd::vm_signals() { 63056668Sshin assert(signal_sets_initialized, "Not initialized"); 63156668Sshin return &vm_sigs; 63295023Ssuz} 63356668Sshin 63456668Sshin// These are signals that are blocked during cond_wait to allow debugger in 63556668Sshinsigset_t* os::Bsd::allowdebug_blocked_signals() { 63656668Sshin assert(signal_sets_initialized, "Not initialized"); 63756668Sshin return &allowdebug_blocked_sigs; 63856668Sshin} 63956668Sshin 64056668Sshinvoid os::Bsd::hotspot_sigmask(Thread* thread) { 64156668Sshin 64256668Sshin //Save caller's signal mask before setting VM signal mask 64356668Sshin sigset_t caller_sigmask; 64456668Sshin pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 64556668Sshin 64656668Sshin OSThread* osthread = thread->osthread(); 64756668Sshin osthread->set_caller_sigmask(caller_sigmask); 64856668Sshin 64956668Sshin pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL); 65056668Sshin 65156668Sshin if (!ReduceSignalUsage) { 652122679Sume if (thread->is_VM_thread()) { 653122679Sume // Only the VM thread handles BREAK_SIGNAL ... 65456668Sshin pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 65556668Sshin } else { 65656668Sshin // ... all other threads block BREAK_SIGNAL 65756668Sshin pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 65856668Sshin } 65956668Sshin } 66056668Sshin} 66156668Sshin 662122679Sume 663122679Sume////////////////////////////////////////////////////////////////////////////// 66456668Sshin// create new thread 66556668Sshin 66656668Sshin// check if it's safe to start a new thread 66756668Sshinstatic bool _thread_safety_check(Thread* thread) { 66856668Sshin return true; 66956668Sshin} 67056668Sshin 67156668Sshin#ifdef __APPLE__ 67256668Sshin// library handle for calling objc_registerThreadWithCollector() 67356668Sshin// without static linking to the libobjc library 67456668Sshin #define OBJC_LIB "/usr/lib/libobjc.dylib" 67556668Sshin #define OBJC_GCREGISTER "objc_registerThreadWithCollector" 67656668Sshintypedef void (*objc_registerThreadWithCollector_t)(); 67762655Skrisextern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction; 67862655Skrisobjc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL; 67962655Skris#endif 68062655Skris 68156668Sshin#ifdef __APPLE__ 682122679Sumestatic uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) { 683122679Sume // Additional thread_id used to correlate threads in SA 684122679Sume thread_identifier_info_data_t m_ident_info; 685122679Sume mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT; 68656668Sshin 68756668Sshin thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO, 68856668Sshin (thread_info_t) &m_ident_info, &count); 68956668Sshin 69056668Sshin return m_ident_info.thread_id; 69156668Sshin} 692122679Sume#endif 693122679Sume 694122679Sume// Thread start routine for all newly created threads 695122679Sumestatic void *java_start(Thread *thread) { 69656668Sshin // Try to randomize the cache line index of hot stack frames. 69756668Sshin // This helps when threads of the same stack traces evict each other's 69856668Sshin // cache lines. The threads can be either from the same JVM instance, or 69956668Sshin // from different JVM instances. The benefit is especially true for 70056668Sshin // processors with hyperthreading technology. 70156668Sshin static int counter = 0; 70256668Sshin int pid = os::current_process_id(); 70395023Ssuz alloca(((pid ^ counter++) & 7) * 128); 70456668Sshin 70556668Sshin ThreadLocalStorage::set_thread(thread); 70656668Sshin 70756668Sshin OSThread* osthread = thread->osthread(); 70856668Sshin Monitor* sync = osthread->startThread_lock(); 70956668Sshin 71056668Sshin // non floating stack BsdThreads needs extra check, see above 711122679Sume if (!_thread_safety_check(thread)) { 712122679Sume // notify parent thread 71356668Sshin MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 714122679Sume osthread->set_state(ZOMBIE); 71556668Sshin sync->notify_all(); 71656668Sshin return NULL; 71756668Sshin } 71856668Sshin 71956668Sshin osthread->set_thread_id(os::Bsd::gettid()); 720122679Sume 72156668Sshin#ifdef __APPLE__ 72256668Sshin uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id()); 72356668Sshin guarantee(unique_thread_id != 0, "unique thread id was not found"); 72456668Sshin osthread->set_unique_thread_id(unique_thread_id); 72556668Sshin#endif 72656668Sshin // initialize signal mask for this thread 72756668Sshin os::Bsd::hotspot_sigmask(thread); 72856668Sshin 72956668Sshin // initialize floating point control register 73056668Sshin os::Bsd::init_thread_fpu_state(); 73156668Sshin 73256668Sshin#ifdef __APPLE__ 73356668Sshin // register thread with objc gc 73456668Sshin if (objc_registerThreadWithCollectorFunction != NULL) { 73556668Sshin objc_registerThreadWithCollectorFunction(); 73656668Sshin } 73756668Sshin#endif 73856668Sshin 73956668Sshin // handshaking with parent thread 74056668Sshin { 74156668Sshin MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 74256668Sshin 74356668Sshin // notify parent thread 74456668Sshin osthread->set_state(INITIALIZED); 74556668Sshin sync->notify_all(); 74656668Sshin 74756668Sshin // wait until os::start_thread() 74856668Sshin while (osthread->get_state() == INITIALIZED) { 74956668Sshin sync->wait(Mutex::_no_safepoint_check_flag); 75056668Sshin } 75156668Sshin } 75256668Sshin 75356668Sshin // call one more level start routine 75456668Sshin thread->run(); 75556668Sshin 75656668Sshin return 0; 75756668Sshin} 75856668Sshin 75956668Sshinbool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 76056668Sshin assert(thread->osthread() == NULL, "caller responsible"); 76156668Sshin 76256668Sshin // Allocate the OSThread object 76356668Sshin OSThread* osthread = new OSThread(NULL, NULL); 76456668Sshin if (osthread == NULL) { 76556668Sshin return false; 76656668Sshin } 76756668Sshin 76856668Sshin // set the correct thread state 76956668Sshin osthread->set_thread_type(thr_type); 77056668Sshin 77156668Sshin // Initial state is ALLOCATED but not INITIALIZED 77256668Sshin osthread->set_state(ALLOCATED); 77356668Sshin 77456668Sshin thread->set_osthread(osthread); 77556668Sshin 77656668Sshin // init thread attributes 77756668Sshin pthread_attr_t attr; 77856668Sshin pthread_attr_init(&attr); 77956668Sshin pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 78056668Sshin 78156668Sshin // stack size 78256668Sshin if (os::Bsd::supports_variable_stack_size()) { 78356668Sshin // calculate stack size if it's not specified by caller 78456668Sshin if (stack_size == 0) { 78556668Sshin stack_size = os::Bsd::default_stack_size(thr_type); 78656668Sshin 78756668Sshin switch (thr_type) { 78856668Sshin case os::java_thread: 78956668Sshin // Java threads use ThreadStackSize which default value can be 79056668Sshin // changed with the flag -Xss 79156668Sshin assert(JavaThread::stack_size_at_create() > 0, "this should be set"); 792122679Sume stack_size = JavaThread::stack_size_at_create(); 793122679Sume break; 794122679Sume case os::compiler_thread: 795122679Sume if (CompilerThreadStackSize > 0) { 796122679Sume stack_size = (size_t)(CompilerThreadStackSize * K); 79756668Sshin break; 79856668Sshin } // else fall through: 79956668Sshin // use VMThreadStackSize if CompilerThreadStackSize is not defined 80056668Sshin case os::vm_thread: 80156668Sshin case os::pgc_thread: 80256668Sshin case os::cgc_thread: 80356668Sshin case os::watcher_thread: 80456668Sshin if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 80556668Sshin break; 80656668Sshin } 80756668Sshin } 80856668Sshin 809122679Sume stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed); 810122679Sume pthread_attr_setstacksize(&attr, stack_size); 811122679Sume } else { 812122679Sume // let pthread_create() pick the default value. 813122679Sume } 81456668Sshin 81556668Sshin ThreadState state; 81656668Sshin 81756668Sshin { 81856668Sshin pthread_t tid; 81956668Sshin int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 82056668Sshin 82156668Sshin pthread_attr_destroy(&attr); 82256668Sshin 82356668Sshin if (ret != 0) { 82456668Sshin if (PrintMiscellaneous && (Verbose || WizardMode)) { 82556668Sshin perror("pthread_create()"); 82656668Sshin } 827122679Sume // Need to clean up stuff we've allocated so far 828122679Sume thread->set_osthread(NULL); 82956668Sshin delete osthread; 83056668Sshin return false; 83156668Sshin } 83256668Sshin 833122679Sume // Store pthread info into the OSThread 834122679Sume osthread->set_pthread_id(tid); 835122679Sume 836122679Sume // Wait until child thread is either initialized or aborted 837122679Sume { 83856668Sshin Monitor* sync_with_child = osthread->startThread_lock(); 83956668Sshin MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 84056668Sshin while ((state = osthread->get_state()) == ALLOCATED) { 84156668Sshin sync_with_child->wait(Mutex::_no_safepoint_check_flag); 84256668Sshin } 84356668Sshin } 84456668Sshin 84556668Sshin } 84656668Sshin 84756668Sshin // Aborted due to thread limit being reached 84856668Sshin if (state == ZOMBIE) { 84956668Sshin thread->set_osthread(NULL); 85056668Sshin delete osthread; 85156668Sshin return false; 85256668Sshin } 85356668Sshin 85456668Sshin // The thread is returned suspended (in state INITIALIZED), 85556668Sshin // and is started higher up in the call chain 85656668Sshin assert(state == INITIALIZED, "race condition"); 85756668Sshin return true; 85856668Sshin} 85956668Sshin 860122679Sume///////////////////////////////////////////////////////////////////////////// 861122679Sume// attach existing thread 86256668Sshin 86356668Sshin// bootstrap the main thread 86456668Sshinbool os::create_main_thread(JavaThread* thread) { 86556668Sshin assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread"); 86656668Sshin return create_attached_thread(thread); 86756668Sshin} 86856668Sshin 86956668Sshinbool os::create_attached_thread(JavaThread* thread) { 87056668Sshin#ifdef ASSERT 87156668Sshin thread->verify_not_published(); 87256668Sshin#endif 87356668Sshin 87456668Sshin // Allocate the OSThread object 87556668Sshin OSThread* osthread = new OSThread(NULL, NULL); 87656668Sshin 87756668Sshin if (osthread == NULL) { 878122679Sume return false; 879122679Sume } 880122679Sume 881122679Sume osthread->set_thread_id(os::Bsd::gettid()); 88256668Sshin 88356668Sshin // Store pthread info into the OSThread 88456668Sshin#ifdef __APPLE__ 88556668Sshin uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id()); 88656668Sshin guarantee(unique_thread_id != 0, "just checking"); 88756668Sshin osthread->set_unique_thread_id(unique_thread_id); 88856668Sshin#endif 88956668Sshin osthread->set_pthread_id(::pthread_self()); 89056668Sshin 89156668Sshin // initialize floating point control register 89256668Sshin os::Bsd::init_thread_fpu_state(); 89356668Sshin 89456668Sshin // Initial thread state is RUNNABLE 89556668Sshin osthread->set_state(RUNNABLE); 89656668Sshin 89756668Sshin thread->set_osthread(osthread); 89856668Sshin 89956668Sshin // initialize signal mask for this thread 90056668Sshin // and save the caller's signal mask 90156668Sshin os::Bsd::hotspot_sigmask(thread); 90256668Sshin 903122679Sume return true; 904122679Sume} 905122679Sume 906122679Sumevoid os::pd_start_thread(Thread* thread) { 907122679Sume OSThread * osthread = thread->osthread(); 90856668Sshin assert(osthread->get_state() != INITIALIZED, "just checking"); 90956668Sshin Monitor* sync_with_child = osthread->startThread_lock(); 91056668Sshin MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 91156668Sshin sync_with_child->notify(); 91256668Sshin} 91356668Sshin 91456668Sshin// Free Bsd resources related to the OSThread 91556668Sshinvoid os::free_thread(OSThread* osthread) { 91656668Sshin assert(osthread != NULL, "osthread not set"); 91756668Sshin 91856668Sshin if (Thread::current()->osthread() == osthread) { 919122679Sume // Restore caller's signal mask 920122679Sume sigset_t sigmask = osthread->caller_sigmask(); 921122679Sume pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 922122679Sume } 923122679Sume 92456668Sshin delete osthread; 92556668Sshin} 92656668Sshin 92756668Sshin////////////////////////////////////////////////////////////////////////////// 92856668Sshin// thread local storage 92956668Sshin 93056668Sshin// Restore the thread pointer if the destructor is called. This is in case 93156668Sshin// someone from JNI code sets up a destructor with pthread_key_create to run 93256668Sshin// detachCurrentThread on thread death. Unless we restore the thread pointer we 93356668Sshin// will hang or crash. When detachCurrentThread is called the key will be set 93456668Sshin// to null and we will not be called again. If detachCurrentThread is never 93556668Sshin// called we could loop forever depending on the pthread implementation. 93656668Sshinstatic void restore_thread_pointer(void* p) { 93756668Sshin Thread* thread = (Thread*) p; 93856668Sshin os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread); 93956668Sshin} 94056668Sshin 94156668Sshinint os::allocate_thread_local_storage() { 94256668Sshin pthread_key_t key; 943122679Sume int rslt = pthread_key_create(&key, restore_thread_pointer); 944122679Sume assert(rslt == 0, "cannot allocate thread local storage"); 945122679Sume return (int)key; 946122679Sume} 947122679Sume 94856668Sshin// Note: This is currently not used by VM, as we don't destroy TLS key 94956668Sshin// on VM exit. 95056668Sshinvoid os::free_thread_local_storage(int index) { 95178064Sume int rslt = pthread_key_delete((pthread_key_t)index); 952122679Sume assert(rslt == 0, "invalid index"); 95356668Sshin} 95456668Sshin 95556668Sshinvoid os::thread_local_storage_at_put(int index, void* value) { 95662655Skris int rslt = pthread_setspecific((pthread_key_t)index, value); 957122679Sume assert(rslt == 0, "pthread_setspecific failed"); 958122679Sume} 959122679Sume 960122679Sumeextern "C" Thread* get_thread() { 961122679Sume return ThreadLocalStorage::thread(); 96256668Sshin} 96356668Sshin 96456668Sshin 96556668Sshin//////////////////////////////////////////////////////////////////////////////// 966122679Sume// time support 967122679Sume 968122679Sume// Time since start-up in seconds to a fine granularity. 969122679Sume// Used by VMSelfDestructTimer and the MemProfiler. 970145357Ssuzdouble os::elapsedTime() { 971122679Sume 97256668Sshin return ((double)os::elapsed_counter()) / os::elapsed_frequency(); 97356668Sshin} 97456668Sshin 97556668Sshinjlong os::elapsed_counter() { 976145791Ssuz return javaTimeNanos() - initial_time_count; 97756668Sshin} 97856668Sshin 97956668Sshinjlong os::elapsed_frequency() { 98056668Sshin return NANOSECS_PER_SEC; // nanosecond resolution 98156668Sshin} 98256668Sshin 98356668Sshinbool os::supports_vtime() { return true; } 98456668Sshinbool os::enable_vtime() { return false; } 98556668Sshinbool os::vtime_enabled() { return false; } 98656668Sshin 98756668Sshindouble os::elapsedVTime() { 98856668Sshin // better than nothing, but not much 98956668Sshin return elapsedTime(); 99056668Sshin} 99156668Sshin 99256668Sshinjlong os::javaTimeMillis() { 993122679Sume timeval time; 994122679Sume int status = gettimeofday(&time, NULL); 995122679Sume assert(status != -1, "bsd error"); 996122679Sume return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 997122679Sume} 99856668Sshin 99956668Sshin#ifndef __APPLE__ 100056668Sshin #ifndef CLOCK_MONOTONIC 100156668Sshin #define CLOCK_MONOTONIC (1) 1002122679Sume #endif 1003122679Sume#endif 1004122679Sume 1005122679Sume#ifdef __APPLE__ 100656668Sshinvoid os::Bsd::clock_init() { 100756668Sshin mach_timebase_info(&_timebase_info); 100856668Sshin} 100956668Sshin#else 101056668Sshinvoid os::Bsd::clock_init() { 101156668Sshin struct timespec res; 101256668Sshin struct timespec tp; 101356668Sshin if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 && 101456668Sshin ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { 101556668Sshin // yes, monotonic clock is supported 101656668Sshin _clock_gettime = ::clock_gettime; 101756668Sshin } 101856668Sshin} 101956668Sshin#endif 1020122679Sume 1021122679Sume 1022122679Sume 1023122679Sume#ifdef __APPLE__ 102456668Sshin 102556668Sshinjlong os::javaTimeNanos() { 102656668Sshin const uint64_t tm = mach_absolute_time(); 102756668Sshin const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom; 102856668Sshin const uint64_t prev = Bsd::_max_abstime; 102956668Sshin if (now <= prev) { 103056668Sshin return prev; // same or retrograde time; 103156668Sshin } 103256668Sshin const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev); 103356668Sshin assert(obsv >= prev, "invariant"); // Monotonicity 1034122679Sume // If the CAS succeeded then we're done and return "now". 1035122679Sume // If the CAS failed and the observed value "obsv" is >= now then 1036122679Sume // we should return "obsv". If the CAS failed and now > obsv > prv then 1037122679Sume // some other thread raced this thread and installed a new value, in which case 103856668Sshin // we could either (a) retry the entire operation, (b) retry trying to install now 103956668Sshin // or (c) just return obsv. We use (c). No loop is required although in some cases 104056668Sshin // we might discard a higher "now" value in deference to a slightly lower but freshly 104156668Sshin // installed obsv value. That's entirely benign -- it admits no new orderings compared 104256668Sshin // to (a) or (b) -- and greatly reduces coherence traffic. 104356668Sshin // We might also condition (c) on the magnitude of the delta between obsv and now. 1044122679Sume // Avoiding excessive CAS operations to hot RW locations is critical. 1045122679Sume // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate 1046122679Sume return (prev == obsv) ? now : obsv; 1047122679Sume} 1048122679Sume 104956668Sshin#else // __APPLE__ 105056668Sshin 105156668Sshinjlong os::javaTimeNanos() { 105256668Sshin if (os::supports_monotonic_clock()) { 105356668Sshin struct timespec tp; 105456668Sshin int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp); 105556668Sshin assert(status == 0, "gettime error"); 105656668Sshin jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 105756668Sshin return result; 105856668Sshin } else { 105956668Sshin timeval time; 106056668Sshin int status = gettimeofday(&time, NULL); 106156668Sshin assert(status != -1, "bsd error"); 106256668Sshin jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1063122679Sume return 1000 * usecs; 1064122679Sume } 1065122679Sume} 1066122679Sume 106756668Sshin#endif // __APPLE__ 106856668Sshin 106956668Sshinvoid os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 107056668Sshin if (os::supports_monotonic_clock()) { 107156668Sshin info_ptr->max_value = ALL_64_BITS; 107256668Sshin 107356668Sshin // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 107456668Sshin info_ptr->may_skip_backward = false; // not subject to resetting or drifting 107556668Sshin info_ptr->may_skip_forward = false; // not subject to resetting or drifting 107656668Sshin } else { 1077122679Sume // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1078122679Sume info_ptr->max_value = ALL_64_BITS; 107956668Sshin 108056668Sshin // gettimeofday is a real time clock so it skips 108156668Sshin info_ptr->may_skip_backward = true; 108295023Ssuz info_ptr->may_skip_forward = true; 108356668Sshin } 108456668Sshin 108556668Sshin info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1086} 1087 1088// Return the real, user, and system times in seconds from an 1089// arbitrary fixed point in the past. 1090bool os::getTimesSecs(double* process_real_time, 1091 double* process_user_time, 1092 double* process_system_time) { 1093 struct tms ticks; 1094 clock_t real_ticks = times(&ticks); 1095 1096 if (real_ticks == (clock_t) (-1)) { 1097 return false; 1098 } else { 1099 double ticks_per_second = (double) clock_tics_per_sec; 1100 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1101 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1102 *process_real_time = ((double) real_ticks) / ticks_per_second; 1103 1104 return true; 1105 } 1106} 1107 1108 1109char * os::local_time_string(char *buf, size_t buflen) { 1110 struct tm t; 1111 time_t long_time; 1112 time(&long_time); 1113 localtime_r(&long_time, &t); 1114 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1115 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1116 t.tm_hour, t.tm_min, t.tm_sec); 1117 return buf; 1118} 1119 1120struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1121 return localtime_r(clock, res); 1122} 1123 1124//////////////////////////////////////////////////////////////////////////////// 1125// runtime exit support 1126 1127// Note: os::shutdown() might be called very early during initialization, or 1128// called from signal handler. Before adding something to os::shutdown(), make 1129// sure it is async-safe and can handle partially initialized VM. 1130void os::shutdown() { 1131 1132 // allow PerfMemory to attempt cleanup of any persistent resources 1133 perfMemory_exit(); 1134 1135 // needs to remove object in file system 1136 AttachListener::abort(); 1137 1138 // flush buffered output, finish log files 1139 ostream_abort(); 1140 1141 // Check for abort hook 1142 abort_hook_t abort_hook = Arguments::abort_hook(); 1143 if (abort_hook != NULL) { 1144 abort_hook(); 1145 } 1146 1147} 1148 1149// Note: os::abort() might be called very early during initialization, or 1150// called from signal handler. Before adding something to os::abort(), make 1151// sure it is async-safe and can handle partially initialized VM. 1152void os::abort(bool dump_core) { 1153 os::shutdown(); 1154 if (dump_core) { 1155#ifndef PRODUCT 1156 fdStream out(defaultStream::output_fd()); 1157 out.print_raw("Current thread is "); 1158 char buf[16]; 1159 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1160 out.print_raw_cr(buf); 1161 out.print_raw_cr("Dumping core ..."); 1162#endif 1163 ::abort(); // dump core 1164 } 1165 1166 ::exit(1); 1167} 1168 1169// Die immediately, no exit hook, no abort hook, no cleanup. 1170void os::die() { 1171 // _exit() on BsdThreads only kills current thread 1172 ::abort(); 1173} 1174 1175// This method is a copy of JDK's sysGetLastErrorString 1176// from src/solaris/hpi/src/system_md.c 1177 1178size_t os::lasterror(char *buf, size_t len) { 1179 if (errno == 0) return 0; 1180 1181 const char *s = ::strerror(errno); 1182 size_t n = ::strlen(s); 1183 if (n >= len) { 1184 n = len - 1; 1185 } 1186 ::strncpy(buf, s, n); 1187 buf[n] = '\0'; 1188 return n; 1189} 1190 1191// Information of current thread in variety of formats 1192pid_t os::Bsd::gettid() { 1193 int retval = -1; 1194 1195#ifdef __APPLE__ //XNU kernel 1196 // despite the fact mach port is actually not a thread id use it 1197 // instead of syscall(SYS_thread_selfid) as it certainly fits to u4 1198 retval = ::pthread_mach_thread_np(::pthread_self()); 1199 guarantee(retval != 0, "just checking"); 1200 return retval; 1201 1202#elif __FreeBSD__ 1203 retval = syscall(SYS_thr_self); 1204#elif __OpenBSD__ 1205 retval = syscall(SYS_getthrid); 1206#elif __NetBSD__ 1207 retval = (pid_t) syscall(SYS__lwp_self); 1208#endif 1209 1210 if (retval == -1) { 1211 return getpid(); 1212 } 1213} 1214 1215intx os::current_thread_id() { 1216#ifdef __APPLE__ 1217 return (intx)::pthread_mach_thread_np(::pthread_self()); 1218#else 1219 return (intx)::pthread_self(); 1220#endif 1221} 1222 1223int os::current_process_id() { 1224 1225 // Under the old bsd thread library, bsd gives each thread 1226 // its own process id. Because of this each thread will return 1227 // a different pid if this method were to return the result 1228 // of getpid(2). Bsd provides no api that returns the pid 1229 // of the launcher thread for the vm. This implementation 1230 // returns a unique pid, the pid of the launcher thread 1231 // that starts the vm 'process'. 1232 1233 // Under the NPTL, getpid() returns the same pid as the 1234 // launcher thread rather than a unique pid per thread. 1235 // Use gettid() if you want the old pre NPTL behaviour. 1236 1237 // if you are looking for the result of a call to getpid() that 1238 // returns a unique pid for the calling thread, then look at the 1239 // OSThread::thread_id() method in osThread_bsd.hpp file 1240 1241 return (int)(_initial_pid ? _initial_pid : getpid()); 1242} 1243 1244// DLL functions 1245 1246#define JNI_LIB_PREFIX "lib" 1247#ifdef __APPLE__ 1248 #define JNI_LIB_SUFFIX ".dylib" 1249#else 1250 #define JNI_LIB_SUFFIX ".so" 1251#endif 1252 1253const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; } 1254 1255// This must be hard coded because it's the system's temporary 1256// directory not the java application's temp directory, ala java.io.tmpdir. 1257#ifdef __APPLE__ 1258// macosx has a secure per-user temporary directory 1259char temp_path_storage[PATH_MAX]; 1260const char* os::get_temp_directory() { 1261 static char *temp_path = NULL; 1262 if (temp_path == NULL) { 1263 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX); 1264 if (pathSize == 0 || pathSize > PATH_MAX) { 1265 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage)); 1266 } 1267 temp_path = temp_path_storage; 1268 } 1269 return temp_path; 1270} 1271#else // __APPLE__ 1272const char* os::get_temp_directory() { return "/tmp"; } 1273#endif // __APPLE__ 1274 1275static bool file_exists(const char* filename) { 1276 struct stat statbuf; 1277 if (filename == NULL || strlen(filename) == 0) { 1278 return false; 1279 } 1280 return os::stat(filename, &statbuf) == 0; 1281} 1282 1283bool os::dll_build_name(char* buffer, size_t buflen, 1284 const char* pname, const char* fname) { 1285 bool retval = false; 1286 // Copied from libhpi 1287 const size_t pnamelen = pname ? strlen(pname) : 0; 1288 1289 // Return error on buffer overflow. 1290 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) { 1291 return retval; 1292 } 1293 1294 if (pnamelen == 0) { 1295 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname); 1296 retval = true; 1297 } else if (strchr(pname, *os::path_separator()) != NULL) { 1298 int n; 1299 char** pelements = split_path(pname, &n); 1300 if (pelements == NULL) { 1301 return false; 1302 } 1303 for (int i = 0; i < n; i++) { 1304 // Really shouldn't be NULL, but check can't hurt 1305 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1306 continue; // skip the empty path values 1307 } 1308 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, 1309 pelements[i], fname); 1310 if (file_exists(buffer)) { 1311 retval = true; 1312 break; 1313 } 1314 } 1315 // release the storage 1316 for (int i = 0; i < n; i++) { 1317 if (pelements[i] != NULL) { 1318 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); 1319 } 1320 } 1321 if (pelements != NULL) { 1322 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal); 1323 } 1324 } else { 1325 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname); 1326 retval = true; 1327 } 1328 return retval; 1329} 1330 1331// check if addr is inside libjvm.so 1332bool os::address_is_in_vm(address addr) { 1333 static address libjvm_base_addr; 1334 Dl_info dlinfo; 1335 1336 if (libjvm_base_addr == NULL) { 1337 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1338 libjvm_base_addr = (address)dlinfo.dli_fbase; 1339 } 1340 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1341 } 1342 1343 if (dladdr((void *)addr, &dlinfo) != 0) { 1344 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1345 } 1346 1347 return false; 1348} 1349 1350 1351#define MACH_MAXSYMLEN 256 1352 1353bool os::dll_address_to_function_name(address addr, char *buf, 1354 int buflen, int *offset) { 1355 // buf is not optional, but offset is optional 1356 assert(buf != NULL, "sanity check"); 1357 1358 Dl_info dlinfo; 1359 char localbuf[MACH_MAXSYMLEN]; 1360 1361 if (dladdr((void*)addr, &dlinfo) != 0) { 1362 // see if we have a matching symbol 1363 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1364 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { 1365 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1366 } 1367 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1368 return true; 1369 } 1370 // no matching symbol so try for just file info 1371 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1372 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1373 buf, buflen, offset, dlinfo.dli_fname)) { 1374 return true; 1375 } 1376 } 1377 1378 // Handle non-dynamic manually: 1379 if (dlinfo.dli_fbase != NULL && 1380 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) { 1381 if (!Decoder::demangle(localbuf, buf, buflen)) { 1382 jio_snprintf(buf, buflen, "%s", localbuf); 1383 } 1384 return true; 1385 } 1386 } 1387 buf[0] = '\0'; 1388 if (offset != NULL) *offset = -1; 1389 return false; 1390} 1391 1392// ported from solaris version 1393bool os::dll_address_to_library_name(address addr, char* buf, 1394 int buflen, int* offset) { 1395 // buf is not optional, but offset is optional 1396 assert(buf != NULL, "sanity check"); 1397 1398 Dl_info dlinfo; 1399 1400 if (dladdr((void*)addr, &dlinfo) != 0) { 1401 if (dlinfo.dli_fname != NULL) { 1402 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1403 } 1404 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1405 *offset = addr - (address)dlinfo.dli_fbase; 1406 } 1407 return true; 1408 } 1409 1410 buf[0] = '\0'; 1411 if (offset) *offset = -1; 1412 return false; 1413} 1414 1415// Loads .dll/.so and 1416// in case of error it checks if .dll/.so was built for the 1417// same architecture as Hotspot is running on 1418 1419#ifdef __APPLE__ 1420void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1421 void * result= ::dlopen(filename, RTLD_LAZY); 1422 if (result != NULL) { 1423 // Successful loading 1424 return result; 1425 } 1426 1427 // Read system error message into ebuf 1428 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1429 ebuf[ebuflen-1]='\0'; 1430 1431 return NULL; 1432} 1433#else 1434void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1435 void * result= ::dlopen(filename, RTLD_LAZY); 1436 if (result != NULL) { 1437 // Successful loading 1438 return result; 1439 } 1440 1441 Elf32_Ehdr elf_head; 1442 1443 // Read system error message into ebuf 1444 // It may or may not be overwritten below 1445 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1446 ebuf[ebuflen-1]='\0'; 1447 int diag_msg_max_length=ebuflen-strlen(ebuf); 1448 char* diag_msg_buf=ebuf+strlen(ebuf); 1449 1450 if (diag_msg_max_length==0) { 1451 // No more space in ebuf for additional diagnostics message 1452 return NULL; 1453 } 1454 1455 1456 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1457 1458 if (file_descriptor < 0) { 1459 // Can't open library, report dlerror() message 1460 return NULL; 1461 } 1462 1463 bool failed_to_read_elf_head= 1464 (sizeof(elf_head)!= 1465 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1466 1467 ::close(file_descriptor); 1468 if (failed_to_read_elf_head) { 1469 // file i/o error - report dlerror() msg 1470 return NULL; 1471 } 1472 1473 typedef struct { 1474 Elf32_Half code; // Actual value as defined in elf.h 1475 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1476 char elf_class; // 32 or 64 bit 1477 char endianess; // MSB or LSB 1478 char* name; // String representation 1479 } arch_t; 1480 1481 #ifndef EM_486 1482 #define EM_486 6 /* Intel 80486 */ 1483 #endif 1484 1485 #ifndef EM_MIPS_RS3_LE 1486 #define EM_MIPS_RS3_LE 10 /* MIPS */ 1487 #endif 1488 1489 #ifndef EM_PPC64 1490 #define EM_PPC64 21 /* PowerPC64 */ 1491 #endif 1492 1493 #ifndef EM_S390 1494 #define EM_S390 22 /* IBM System/390 */ 1495 #endif 1496 1497 #ifndef EM_IA_64 1498 #define EM_IA_64 50 /* HP/Intel IA-64 */ 1499 #endif 1500 1501 #ifndef EM_X86_64 1502 #define EM_X86_64 62 /* AMD x86-64 */ 1503 #endif 1504 1505 static const arch_t arch_array[]={ 1506 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1507 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1508 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1509 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1510 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1511 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1512 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1513 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1514 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1515 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 1516 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, 1517 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, 1518 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, 1519 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, 1520 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, 1521 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} 1522 }; 1523 1524 #if (defined IA32) 1525 static Elf32_Half running_arch_code=EM_386; 1526 #elif (defined AMD64) 1527 static Elf32_Half running_arch_code=EM_X86_64; 1528 #elif (defined IA64) 1529 static Elf32_Half running_arch_code=EM_IA_64; 1530 #elif (defined __sparc) && (defined _LP64) 1531 static Elf32_Half running_arch_code=EM_SPARCV9; 1532 #elif (defined __sparc) && (!defined _LP64) 1533 static Elf32_Half running_arch_code=EM_SPARC; 1534 #elif (defined __powerpc64__) 1535 static Elf32_Half running_arch_code=EM_PPC64; 1536 #elif (defined __powerpc__) 1537 static Elf32_Half running_arch_code=EM_PPC; 1538 #elif (defined ARM) 1539 static Elf32_Half running_arch_code=EM_ARM; 1540 #elif (defined S390) 1541 static Elf32_Half running_arch_code=EM_S390; 1542 #elif (defined ALPHA) 1543 static Elf32_Half running_arch_code=EM_ALPHA; 1544 #elif (defined MIPSEL) 1545 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; 1546 #elif (defined PARISC) 1547 static Elf32_Half running_arch_code=EM_PARISC; 1548 #elif (defined MIPS) 1549 static Elf32_Half running_arch_code=EM_MIPS; 1550 #elif (defined M68K) 1551 static Elf32_Half running_arch_code=EM_68K; 1552 #else 1553 #error Method os::dll_load requires that one of following is defined:\ 1554 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K 1555 #endif 1556 1557 // Identify compatability class for VM's architecture and library's architecture 1558 // Obtain string descriptions for architectures 1559 1560 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1561 int running_arch_index=-1; 1562 1563 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1564 if (running_arch_code == arch_array[i].code) { 1565 running_arch_index = i; 1566 } 1567 if (lib_arch.code == arch_array[i].code) { 1568 lib_arch.compat_class = arch_array[i].compat_class; 1569 lib_arch.name = arch_array[i].name; 1570 } 1571 } 1572 1573 assert(running_arch_index != -1, 1574 "Didn't find running architecture code (running_arch_code) in arch_array"); 1575 if (running_arch_index == -1) { 1576 // Even though running architecture detection failed 1577 // we may still continue with reporting dlerror() message 1578 return NULL; 1579 } 1580 1581 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1582 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1583 return NULL; 1584 } 1585 1586#ifndef S390 1587 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1588 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1589 return NULL; 1590 } 1591#endif // !S390 1592 1593 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1594 if (lib_arch.name!=NULL) { 1595 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1596 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 1597 lib_arch.name, arch_array[running_arch_index].name); 1598 } else { 1599 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1600 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 1601 lib_arch.code, 1602 arch_array[running_arch_index].name); 1603 } 1604 } 1605 1606 return NULL; 1607} 1608#endif // !__APPLE__ 1609 1610void* os::get_default_process_handle() { 1611#ifdef __APPLE__ 1612 // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY 1613 // to avoid finding unexpected symbols on second (or later) 1614 // loads of a library. 1615 return (void*)::dlopen(NULL, RTLD_FIRST); 1616#else 1617 return (void*)::dlopen(NULL, RTLD_LAZY); 1618#endif 1619} 1620 1621// XXX: Do we need a lock around this as per Linux? 1622void* os::dll_lookup(void* handle, const char* name) { 1623 return dlsym(handle, name); 1624} 1625 1626 1627static bool _print_ascii_file(const char* filename, outputStream* st) { 1628 int fd = ::open(filename, O_RDONLY); 1629 if (fd == -1) { 1630 return false; 1631 } 1632 1633 char buf[32]; 1634 int bytes; 1635 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 1636 st->print_raw(buf, bytes); 1637 } 1638 1639 ::close(fd); 1640 1641 return true; 1642} 1643 1644void os::print_dll_info(outputStream *st) { 1645 st->print_cr("Dynamic libraries:"); 1646#ifdef RTLD_DI_LINKMAP 1647 Dl_info dli; 1648 void *handle; 1649 Link_map *map; 1650 Link_map *p; 1651 1652 if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 || 1653 dli.dli_fname == NULL) { 1654 st->print_cr("Error: Cannot print dynamic libraries."); 1655 return; 1656 } 1657 handle = dlopen(dli.dli_fname, RTLD_LAZY); 1658 if (handle == NULL) { 1659 st->print_cr("Error: Cannot print dynamic libraries."); 1660 return; 1661 } 1662 dlinfo(handle, RTLD_DI_LINKMAP, &map); 1663 if (map == NULL) { 1664 st->print_cr("Error: Cannot print dynamic libraries."); 1665 return; 1666 } 1667 1668 while (map->l_prev != NULL) 1669 map = map->l_prev; 1670 1671 while (map != NULL) { 1672 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); 1673 map = map->l_next; 1674 } 1675 1676 dlclose(handle); 1677#elif defined(__APPLE__) 1678 uint32_t count; 1679 uint32_t i; 1680 1681 count = _dyld_image_count(); 1682 for (i = 1; i < count; i++) { 1683 const char *name = _dyld_get_image_name(i); 1684 intptr_t slide = _dyld_get_image_vmaddr_slide(i); 1685 st->print_cr(PTR_FORMAT " \t%s", slide, name); 1686 } 1687#else 1688 st->print_cr("Error: Cannot print dynamic libraries."); 1689#endif 1690} 1691 1692void os::print_os_info_brief(outputStream* st) { 1693 st->print("Bsd"); 1694 1695 os::Posix::print_uname_info(st); 1696} 1697 1698void os::print_os_info(outputStream* st) { 1699 st->print("OS:"); 1700 st->print("Bsd"); 1701 1702 os::Posix::print_uname_info(st); 1703 1704 os::Posix::print_rlimit_info(st); 1705 1706 os::Posix::print_load_average(st); 1707} 1708 1709void os::pd_print_cpu_info(outputStream* st) { 1710 // Nothing to do for now. 1711} 1712 1713void os::print_memory_info(outputStream* st) { 1714 1715 st->print("Memory:"); 1716 st->print(" %dk page", os::vm_page_size()>>10); 1717 1718 st->print(", physical " UINT64_FORMAT "k", 1719 os::physical_memory() >> 10); 1720 st->print("(" UINT64_FORMAT "k free)", 1721 os::available_memory() >> 10); 1722 st->cr(); 1723 1724 // meminfo 1725 st->print("\n/proc/meminfo:\n"); 1726 _print_ascii_file("/proc/meminfo", st); 1727 st->cr(); 1728} 1729 1730void os::print_siginfo(outputStream* st, void* siginfo) { 1731 const siginfo_t* si = (const siginfo_t*)siginfo; 1732 1733 os::Posix::print_siginfo_brief(st, si); 1734 1735 if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 1736 UseSharedSpaces) { 1737 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1738 if (mapinfo->is_in_shared_space(si->si_addr)) { 1739 st->print("\n\nError accessing class data sharing archive." \ 1740 " Mapped file inaccessible during execution, " \ 1741 " possible disk/network problem."); 1742 } 1743 } 1744 st->cr(); 1745} 1746 1747 1748static void print_signal_handler(outputStream* st, int sig, 1749 char* buf, size_t buflen); 1750 1751void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 1752 st->print_cr("Signal Handlers:"); 1753 print_signal_handler(st, SIGSEGV, buf, buflen); 1754 print_signal_handler(st, SIGBUS , buf, buflen); 1755 print_signal_handler(st, SIGFPE , buf, buflen); 1756 print_signal_handler(st, SIGPIPE, buf, buflen); 1757 print_signal_handler(st, SIGXFSZ, buf, buflen); 1758 print_signal_handler(st, SIGILL , buf, buflen); 1759 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 1760 print_signal_handler(st, SR_signum, buf, buflen); 1761 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 1762 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 1763 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 1764 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 1765} 1766 1767static char saved_jvm_path[MAXPATHLEN] = {0}; 1768 1769// Find the full path to the current module, libjvm 1770void os::jvm_path(char *buf, jint buflen) { 1771 // Error checking. 1772 if (buflen < MAXPATHLEN) { 1773 assert(false, "must use a large-enough buffer"); 1774 buf[0] = '\0'; 1775 return; 1776 } 1777 // Lazy resolve the path to current module. 1778 if (saved_jvm_path[0] != 0) { 1779 strcpy(buf, saved_jvm_path); 1780 return; 1781 } 1782 1783 char dli_fname[MAXPATHLEN]; 1784 bool ret = dll_address_to_library_name( 1785 CAST_FROM_FN_PTR(address, os::jvm_path), 1786 dli_fname, sizeof(dli_fname), NULL); 1787 assert(ret, "cannot locate libjvm"); 1788 char *rp = NULL; 1789 if (ret && dli_fname[0] != '\0') { 1790 rp = realpath(dli_fname, buf); 1791 } 1792 if (rp == NULL) { 1793 return; 1794 } 1795 1796 if (Arguments::sun_java_launcher_is_altjvm()) { 1797 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 1798 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so" 1799 // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/" 1800 // appears at the right place in the string, then assume we are 1801 // installed in a JDK and we're done. Otherwise, check for a 1802 // JAVA_HOME environment variable and construct a path to the JVM 1803 // being overridden. 1804 1805 const char *p = buf + strlen(buf) - 1; 1806 for (int count = 0; p > buf && count < 5; ++count) { 1807 for (--p; p > buf && *p != '/'; --p) 1808 /* empty */ ; 1809 } 1810 1811 if (strncmp(p, "/jre/lib/", 9) != 0) { 1812 // Look for JAVA_HOME in the environment. 1813 char* java_home_var = ::getenv("JAVA_HOME"); 1814 if (java_home_var != NULL && java_home_var[0] != 0) { 1815 char* jrelib_p; 1816 int len; 1817 1818 // Check the current module name "libjvm" 1819 p = strrchr(buf, '/'); 1820 assert(strstr(p, "/libjvm") == p, "invalid library name"); 1821 1822 rp = realpath(java_home_var, buf); 1823 if (rp == NULL) { 1824 return; 1825 } 1826 1827 // determine if this is a legacy image or modules image 1828 // modules image doesn't have "jre" subdirectory 1829 len = strlen(buf); 1830 assert(len < buflen, "Ran out of buffer space"); 1831 jrelib_p = buf + len; 1832 1833 // Add the appropriate library subdir 1834 snprintf(jrelib_p, buflen-len, "/jre/lib"); 1835 if (0 != access(buf, F_OK)) { 1836 snprintf(jrelib_p, buflen-len, "/lib"); 1837 } 1838 1839 // Add the appropriate client or server subdir 1840 len = strlen(buf); 1841 jrelib_p = buf + len; 1842 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT); 1843 if (0 != access(buf, F_OK)) { 1844 snprintf(jrelib_p, buflen-len, "%s", ""); 1845 } 1846 1847 // If the path exists within JAVA_HOME, add the JVM library name 1848 // to complete the path to JVM being overridden. Otherwise fallback 1849 // to the path to the current library. 1850 if (0 == access(buf, F_OK)) { 1851 // Use current module name "libjvm" 1852 len = strlen(buf); 1853 snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX); 1854 } else { 1855 // Fall back to path of current library 1856 rp = realpath(dli_fname, buf); 1857 if (rp == NULL) { 1858 return; 1859 } 1860 } 1861 } 1862 } 1863 } 1864 1865 strncpy(saved_jvm_path, buf, MAXPATHLEN); 1866} 1867 1868void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 1869 // no prefix required, not even "_" 1870} 1871 1872void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 1873 // no suffix required 1874} 1875 1876//////////////////////////////////////////////////////////////////////////////// 1877// sun.misc.Signal support 1878 1879static volatile jint sigint_count = 0; 1880 1881static void UserHandler(int sig, void *siginfo, void *context) { 1882 // 4511530 - sem_post is serialized and handled by the manager thread. When 1883 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 1884 // don't want to flood the manager thread with sem_post requests. 1885 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) { 1886 return; 1887 } 1888 1889 // Ctrl-C is pressed during error reporting, likely because the error 1890 // handler fails to abort. Let VM die immediately. 1891 if (sig == SIGINT && is_error_reported()) { 1892 os::die(); 1893 } 1894 1895 os::signal_notify(sig); 1896} 1897 1898void* os::user_handler() { 1899 return CAST_FROM_FN_PTR(void*, UserHandler); 1900} 1901 1902extern "C" { 1903 typedef void (*sa_handler_t)(int); 1904 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 1905} 1906 1907void* os::signal(int signal_number, void* handler) { 1908 struct sigaction sigAct, oldSigAct; 1909 1910 sigfillset(&(sigAct.sa_mask)); 1911 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 1912 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 1913 1914 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 1915 // -1 means registration failed 1916 return (void *)-1; 1917 } 1918 1919 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 1920} 1921 1922void os::signal_raise(int signal_number) { 1923 ::raise(signal_number); 1924} 1925 1926// The following code is moved from os.cpp for making this 1927// code platform specific, which it is by its very nature. 1928 1929// Will be modified when max signal is changed to be dynamic 1930int os::sigexitnum_pd() { 1931 return NSIG; 1932} 1933 1934// a counter for each possible signal value 1935static volatile jint pending_signals[NSIG+1] = { 0 }; 1936 1937// Bsd(POSIX) specific hand shaking semaphore. 1938#ifdef __APPLE__ 1939typedef semaphore_t os_semaphore_t; 1940 1941 #define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value) 1942 #define SEM_WAIT(sem) semaphore_wait(sem) 1943 #define SEM_POST(sem) semaphore_signal(sem) 1944 #define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem) 1945#else 1946typedef sem_t os_semaphore_t; 1947 1948 #define SEM_INIT(sem, value) sem_init(&sem, 0, value) 1949 #define SEM_WAIT(sem) sem_wait(&sem) 1950 #define SEM_POST(sem) sem_post(&sem) 1951 #define SEM_DESTROY(sem) sem_destroy(&sem) 1952#endif 1953 1954class Semaphore : public StackObj { 1955 public: 1956 Semaphore(); 1957 ~Semaphore(); 1958 void signal(); 1959 void wait(); 1960 bool trywait(); 1961 bool timedwait(unsigned int sec, int nsec); 1962 private: 1963 jlong currenttime() const; 1964 os_semaphore_t _semaphore; 1965}; 1966 1967Semaphore::Semaphore() : _semaphore(0) { 1968 SEM_INIT(_semaphore, 0); 1969} 1970 1971Semaphore::~Semaphore() { 1972 SEM_DESTROY(_semaphore); 1973} 1974 1975void Semaphore::signal() { 1976 SEM_POST(_semaphore); 1977} 1978 1979void Semaphore::wait() { 1980 SEM_WAIT(_semaphore); 1981} 1982 1983jlong Semaphore::currenttime() const { 1984 struct timeval tv; 1985 gettimeofday(&tv, NULL); 1986 return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000); 1987} 1988 1989#ifdef __APPLE__ 1990bool Semaphore::trywait() { 1991 return timedwait(0, 0); 1992} 1993 1994bool Semaphore::timedwait(unsigned int sec, int nsec) { 1995 kern_return_t kr = KERN_ABORTED; 1996 mach_timespec_t waitspec; 1997 waitspec.tv_sec = sec; 1998 waitspec.tv_nsec = nsec; 1999 2000 jlong starttime = currenttime(); 2001 2002 kr = semaphore_timedwait(_semaphore, waitspec); 2003 while (kr == KERN_ABORTED) { 2004 jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec; 2005 2006 jlong current = currenttime(); 2007 jlong passedtime = current - starttime; 2008 2009 if (passedtime >= totalwait) { 2010 waitspec.tv_sec = 0; 2011 waitspec.tv_nsec = 0; 2012 } else { 2013 jlong waittime = totalwait - (current - starttime); 2014 waitspec.tv_sec = waittime / NANOSECS_PER_SEC; 2015 waitspec.tv_nsec = waittime % NANOSECS_PER_SEC; 2016 } 2017 2018 kr = semaphore_timedwait(_semaphore, waitspec); 2019 } 2020 2021 return kr == KERN_SUCCESS; 2022} 2023 2024#else 2025 2026bool Semaphore::trywait() { 2027 return sem_trywait(&_semaphore) == 0; 2028} 2029 2030bool Semaphore::timedwait(unsigned int sec, int nsec) { 2031 struct timespec ts; 2032 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec); 2033 2034 while (1) { 2035 int result = sem_timedwait(&_semaphore, &ts); 2036 if (result == 0) { 2037 return true; 2038 } else if (errno == EINTR) { 2039 continue; 2040 } else if (errno == ETIMEDOUT) { 2041 return false; 2042 } else { 2043 return false; 2044 } 2045 } 2046} 2047 2048#endif // __APPLE__ 2049 2050static os_semaphore_t sig_sem; 2051static Semaphore sr_semaphore; 2052 2053void os::signal_init_pd() { 2054 // Initialize signal structures 2055 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2056 2057 // Initialize signal semaphore 2058 ::SEM_INIT(sig_sem, 0); 2059} 2060 2061void os::signal_notify(int sig) { 2062 Atomic::inc(&pending_signals[sig]); 2063 ::SEM_POST(sig_sem); 2064} 2065 2066static int check_pending_signals(bool wait) { 2067 Atomic::store(0, &sigint_count); 2068 for (;;) { 2069 for (int i = 0; i < NSIG + 1; i++) { 2070 jint n = pending_signals[i]; 2071 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2072 return i; 2073 } 2074 } 2075 if (!wait) { 2076 return -1; 2077 } 2078 JavaThread *thread = JavaThread::current(); 2079 ThreadBlockInVM tbivm(thread); 2080 2081 bool threadIsSuspended; 2082 do { 2083 thread->set_suspend_equivalent(); 2084 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2085 ::SEM_WAIT(sig_sem); 2086 2087 // were we externally suspended while we were waiting? 2088 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2089 if (threadIsSuspended) { 2090 // The semaphore has been incremented, but while we were waiting 2091 // another thread suspended us. We don't want to continue running 2092 // while suspended because that would surprise the thread that 2093 // suspended us. 2094 ::SEM_POST(sig_sem); 2095 2096 thread->java_suspend_self(); 2097 } 2098 } while (threadIsSuspended); 2099 } 2100} 2101 2102int os::signal_lookup() { 2103 return check_pending_signals(false); 2104} 2105 2106int os::signal_wait() { 2107 return check_pending_signals(true); 2108} 2109 2110//////////////////////////////////////////////////////////////////////////////// 2111// Virtual Memory 2112 2113int os::vm_page_size() { 2114 // Seems redundant as all get out 2115 assert(os::Bsd::page_size() != -1, "must call os::init"); 2116 return os::Bsd::page_size(); 2117} 2118 2119// Solaris allocates memory by pages. 2120int os::vm_allocation_granularity() { 2121 assert(os::Bsd::page_size() != -1, "must call os::init"); 2122 return os::Bsd::page_size(); 2123} 2124 2125// Rationale behind this function: 2126// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2127// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2128// samples for JITted code. Here we create private executable mapping over the code cache 2129// and then we can use standard (well, almost, as mapping can change) way to provide 2130// info for the reporting script by storing timestamp and location of symbol 2131void bsd_wrap_code(char* base, size_t size) { 2132 static volatile jint cnt = 0; 2133 2134 if (!UseOprofile) { 2135 return; 2136 } 2137 2138 char buf[PATH_MAX + 1]; 2139 int num = Atomic::add(1, &cnt); 2140 2141 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d", 2142 os::get_temp_directory(), os::current_process_id(), num); 2143 unlink(buf); 2144 2145 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); 2146 2147 if (fd != -1) { 2148 off_t rv = ::lseek(fd, size-2, SEEK_SET); 2149 if (rv != (off_t)-1) { 2150 if (::write(fd, "", 1) == 1) { 2151 mmap(base, size, 2152 PROT_READ|PROT_WRITE|PROT_EXEC, 2153 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2154 } 2155 } 2156 ::close(fd); 2157 unlink(buf); 2158 } 2159} 2160 2161static void warn_fail_commit_memory(char* addr, size_t size, bool exec, 2162 int err) { 2163 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2164 ", %d) failed; error='%s' (errno=%d)", addr, size, exec, 2165 strerror(err), err); 2166} 2167 2168// NOTE: Bsd kernel does not really reserve the pages for us. 2169// All it does is to check if there are enough free pages 2170// left at the time of mmap(). This could be a potential 2171// problem. 2172bool os::pd_commit_memory(char* addr, size_t size, bool exec) { 2173 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2174#ifdef __OpenBSD__ 2175 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 2176 if (::mprotect(addr, size, prot) == 0) { 2177 return true; 2178 } 2179#else 2180 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, 2181 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2182 if (res != (uintptr_t) MAP_FAILED) { 2183 return true; 2184 } 2185#endif 2186 2187 // Warn about any commit errors we see in non-product builds just 2188 // in case mmap() doesn't work as described on the man page. 2189 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);) 2190 2191 return false; 2192} 2193 2194bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 2195 bool exec) { 2196 // alignment_hint is ignored on this OS 2197 return pd_commit_memory(addr, size, exec); 2198} 2199 2200void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, 2201 const char* mesg) { 2202 assert(mesg != NULL, "mesg must be specified"); 2203 if (!pd_commit_memory(addr, size, exec)) { 2204 // add extra info in product mode for vm_exit_out_of_memory(): 2205 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);) 2206 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2207 } 2208} 2209 2210void os::pd_commit_memory_or_exit(char* addr, size_t size, 2211 size_t alignment_hint, bool exec, 2212 const char* mesg) { 2213 // alignment_hint is ignored on this OS 2214 pd_commit_memory_or_exit(addr, size, exec, mesg); 2215} 2216 2217void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2218} 2219 2220void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { 2221 ::madvise(addr, bytes, MADV_DONTNEED); 2222} 2223 2224void os::numa_make_global(char *addr, size_t bytes) { 2225} 2226 2227void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2228} 2229 2230bool os::numa_topology_changed() { return false; } 2231 2232size_t os::numa_get_groups_num() { 2233 return 1; 2234} 2235 2236int os::numa_get_group_id() { 2237 return 0; 2238} 2239 2240size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2241 if (size > 0) { 2242 ids[0] = 0; 2243 return 1; 2244 } 2245 return 0; 2246} 2247 2248bool os::get_page_info(char *start, page_info* info) { 2249 return false; 2250} 2251 2252char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 2253 return end; 2254} 2255 2256 2257bool os::pd_uncommit_memory(char* addr, size_t size) { 2258#ifdef __OpenBSD__ 2259 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 2260 return ::mprotect(addr, size, PROT_NONE) == 0; 2261#else 2262 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, 2263 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); 2264 return res != (uintptr_t) MAP_FAILED; 2265#endif 2266} 2267 2268bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 2269 return os::commit_memory(addr, size, !ExecMem); 2270} 2271 2272// If this is a growable mapping, remove the guard pages entirely by 2273// munmap()ping them. If not, just call uncommit_memory(). 2274bool os::remove_stack_guard_pages(char* addr, size_t size) { 2275 return os::uncommit_memory(addr, size); 2276} 2277 2278static address _highest_vm_reserved_address = NULL; 2279 2280// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 2281// at 'requested_addr'. If there are existing memory mappings at the same 2282// location, however, they will be overwritten. If 'fixed' is false, 2283// 'requested_addr' is only treated as a hint, the return value may or 2284// may not start from the requested address. Unlike Bsd mmap(), this 2285// function returns NULL to indicate failure. 2286static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 2287 char * addr; 2288 int flags; 2289 2290 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 2291 if (fixed) { 2292 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address"); 2293 flags |= MAP_FIXED; 2294 } 2295 2296 // Map reserved/uncommitted pages PROT_NONE so we fail early if we 2297 // touch an uncommitted page. Otherwise, the read/write might 2298 // succeed if we have enough swap space to back the physical page. 2299 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, 2300 flags, -1, 0); 2301 2302 if (addr != MAP_FAILED) { 2303 // anon_mmap() should only get called during VM initialization, 2304 // don't need lock (actually we can skip locking even it can be called 2305 // from multiple threads, because _highest_vm_reserved_address is just a 2306 // hint about the upper limit of non-stack memory regions.) 2307 if ((address)addr + bytes > _highest_vm_reserved_address) { 2308 _highest_vm_reserved_address = (address)addr + bytes; 2309 } 2310 } 2311 2312 return addr == MAP_FAILED ? NULL : addr; 2313} 2314 2315// Don't update _highest_vm_reserved_address, because there might be memory 2316// regions above addr + size. If so, releasing a memory region only creates 2317// a hole in the address space, it doesn't help prevent heap-stack collision. 2318// 2319static int anon_munmap(char * addr, size_t size) { 2320 return ::munmap(addr, size) == 0; 2321} 2322 2323char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 2324 size_t alignment_hint) { 2325 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 2326} 2327 2328bool os::pd_release_memory(char* addr, size_t size) { 2329 return anon_munmap(addr, size); 2330} 2331 2332static bool bsd_mprotect(char* addr, size_t size, int prot) { 2333 // Bsd wants the mprotect address argument to be page aligned. 2334 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size()); 2335 2336 // According to SUSv3, mprotect() should only be used with mappings 2337 // established by mmap(), and mmap() always maps whole pages. Unaligned 2338 // 'addr' likely indicates problem in the VM (e.g. trying to change 2339 // protection of malloc'ed or statically allocated memory). Check the 2340 // caller if you hit this assert. 2341 assert(addr == bottom, "sanity check"); 2342 2343 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size()); 2344 return ::mprotect(bottom, size, prot) == 0; 2345} 2346 2347// Set protections specified 2348bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2349 bool is_committed) { 2350 unsigned int p = 0; 2351 switch (prot) { 2352 case MEM_PROT_NONE: p = PROT_NONE; break; 2353 case MEM_PROT_READ: p = PROT_READ; break; 2354 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 2355 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 2356 default: 2357 ShouldNotReachHere(); 2358 } 2359 // is_committed is unused. 2360 return bsd_mprotect(addr, bytes, p); 2361} 2362 2363bool os::guard_memory(char* addr, size_t size) { 2364 return bsd_mprotect(addr, size, PROT_NONE); 2365} 2366 2367bool os::unguard_memory(char* addr, size_t size) { 2368 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE); 2369} 2370 2371bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) { 2372 return false; 2373} 2374 2375// Large page support 2376 2377static size_t _large_page_size = 0; 2378 2379void os::large_page_init() { 2380} 2381 2382 2383char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) { 2384 fatal("This code is not used or maintained."); 2385 2386 // "exec" is passed in but not used. Creating the shared image for 2387 // the code cache doesn't have an SHM_X executable permission to check. 2388 assert(UseLargePages && UseSHM, "only for SHM large pages"); 2389 2390 key_t key = IPC_PRIVATE; 2391 char *addr; 2392 2393 bool warn_on_failure = UseLargePages && 2394 (!FLAG_IS_DEFAULT(UseLargePages) || 2395 !FLAG_IS_DEFAULT(LargePageSizeInBytes)); 2396 2397 // Create a large shared memory region to attach to based on size. 2398 // Currently, size is the total size of the heap 2399 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W); 2400 if (shmid == -1) { 2401 // Possible reasons for shmget failure: 2402 // 1. shmmax is too small for Java heap. 2403 // > check shmmax value: cat /proc/sys/kernel/shmmax 2404 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 2405 // 2. not enough large page memory. 2406 // > check available large pages: cat /proc/meminfo 2407 // > increase amount of large pages: 2408 // echo new_value > /proc/sys/vm/nr_hugepages 2409 // Note 1: different Bsd may use different name for this property, 2410 // e.g. on Redhat AS-3 it is "hugetlb_pool". 2411 // Note 2: it's possible there's enough physical memory available but 2412 // they are so fragmented after a long run that they can't 2413 // coalesce into large pages. Try to reserve large pages when 2414 // the system is still "fresh". 2415 if (warn_on_failure) { 2416 warning("Failed to reserve shared memory (errno = %d).", errno); 2417 } 2418 return NULL; 2419 } 2420 2421 // attach to the region 2422 addr = (char*)shmat(shmid, req_addr, 0); 2423 int err = errno; 2424 2425 // Remove shmid. If shmat() is successful, the actual shared memory segment 2426 // will be deleted when it's detached by shmdt() or when the process 2427 // terminates. If shmat() is not successful this will remove the shared 2428 // segment immediately. 2429 shmctl(shmid, IPC_RMID, NULL); 2430 2431 if ((intptr_t)addr == -1) { 2432 if (warn_on_failure) { 2433 warning("Failed to attach shared memory (errno = %d).", err); 2434 } 2435 return NULL; 2436 } 2437 2438 // The memory is committed 2439 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC); 2440 2441 return addr; 2442} 2443 2444bool os::release_memory_special(char* base, size_t bytes) { 2445 if (MemTracker::tracking_level() > NMT_minimal) { 2446 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 2447 // detaching the SHM segment will also delete it, see reserve_memory_special() 2448 int rslt = shmdt(base); 2449 if (rslt == 0) { 2450 tkr.record((address)base, bytes); 2451 return true; 2452 } else { 2453 return false; 2454 } 2455 } else { 2456 return shmdt(base) == 0; 2457 } 2458} 2459 2460size_t os::large_page_size() { 2461 return _large_page_size; 2462} 2463 2464// HugeTLBFS allows application to commit large page memory on demand; 2465// with SysV SHM the entire memory region must be allocated as shared 2466// memory. 2467bool os::can_commit_large_page_memory() { 2468 return UseHugeTLBFS; 2469} 2470 2471bool os::can_execute_large_page_memory() { 2472 return UseHugeTLBFS; 2473} 2474 2475// Reserve memory at an arbitrary address, only if that area is 2476// available (and not reserved for something else). 2477 2478char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2479 const int max_tries = 10; 2480 char* base[max_tries]; 2481 size_t size[max_tries]; 2482 const size_t gap = 0x000000; 2483 2484 // Assert only that the size is a multiple of the page size, since 2485 // that's all that mmap requires, and since that's all we really know 2486 // about at this low abstraction level. If we need higher alignment, 2487 // we can either pass an alignment to this method or verify alignment 2488 // in one of the methods further up the call chain. See bug 5044738. 2489 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 2490 2491 // Repeatedly allocate blocks until the block is allocated at the 2492 // right spot. Give up after max_tries. Note that reserve_memory() will 2493 // automatically update _highest_vm_reserved_address if the call is 2494 // successful. The variable tracks the highest memory address every reserved 2495 // by JVM. It is used to detect heap-stack collision if running with 2496 // fixed-stack BsdThreads. Because here we may attempt to reserve more 2497 // space than needed, it could confuse the collision detecting code. To 2498 // solve the problem, save current _highest_vm_reserved_address and 2499 // calculate the correct value before return. 2500 address old_highest = _highest_vm_reserved_address; 2501 2502 // Bsd mmap allows caller to pass an address as hint; give it a try first, 2503 // if kernel honors the hint then we can return immediately. 2504 char * addr = anon_mmap(requested_addr, bytes, false); 2505 if (addr == requested_addr) { 2506 return requested_addr; 2507 } 2508 2509 if (addr != NULL) { 2510 // mmap() is successful but it fails to reserve at the requested address 2511 anon_munmap(addr, bytes); 2512 } 2513 2514 int i; 2515 for (i = 0; i < max_tries; ++i) { 2516 base[i] = reserve_memory(bytes); 2517 2518 if (base[i] != NULL) { 2519 // Is this the block we wanted? 2520 if (base[i] == requested_addr) { 2521 size[i] = bytes; 2522 break; 2523 } 2524 2525 // Does this overlap the block we wanted? Give back the overlapped 2526 // parts and try again. 2527 2528 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 2529 if (top_overlap >= 0 && top_overlap < bytes) { 2530 unmap_memory(base[i], top_overlap); 2531 base[i] += top_overlap; 2532 size[i] = bytes - top_overlap; 2533 } else { 2534 size_t bottom_overlap = base[i] + bytes - requested_addr; 2535 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 2536 unmap_memory(requested_addr, bottom_overlap); 2537 size[i] = bytes - bottom_overlap; 2538 } else { 2539 size[i] = bytes; 2540 } 2541 } 2542 } 2543 } 2544 2545 // Give back the unused reserved pieces. 2546 2547 for (int j = 0; j < i; ++j) { 2548 if (base[j] != NULL) { 2549 unmap_memory(base[j], size[j]); 2550 } 2551 } 2552 2553 if (i < max_tries) { 2554 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 2555 return requested_addr; 2556 } else { 2557 _highest_vm_reserved_address = old_highest; 2558 return NULL; 2559 } 2560} 2561 2562size_t os::read(int fd, void *buf, unsigned int nBytes) { 2563 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes)); 2564} 2565 2566void os::naked_short_sleep(jlong ms) { 2567 struct timespec req; 2568 2569 assert(ms < 1000, "Un-interruptable sleep, short time use only"); 2570 req.tv_sec = 0; 2571 if (ms > 0) { 2572 req.tv_nsec = (ms % 1000) * 1000000; 2573 } else { 2574 req.tv_nsec = 1; 2575 } 2576 2577 nanosleep(&req, NULL); 2578 2579 return; 2580} 2581 2582// Sleep forever; naked call to OS-specific sleep; use with CAUTION 2583void os::infinite_sleep() { 2584 while (true) { // sleep forever ... 2585 ::sleep(100); // ... 100 seconds at a time 2586 } 2587} 2588 2589// Used to convert frequent JVM_Yield() to nops 2590bool os::dont_yield() { 2591 return DontYieldALot; 2592} 2593 2594void os::naked_yield() { 2595 sched_yield(); 2596} 2597 2598//////////////////////////////////////////////////////////////////////////////// 2599// thread priority support 2600 2601// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER 2602// only supports dynamic priority, static priority must be zero. For real-time 2603// applications, Bsd supports SCHED_RR which allows static priority (1-99). 2604// However, for large multi-threaded applications, SCHED_RR is not only slower 2605// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 2606// of 5 runs - Sep 2005). 2607// 2608// The following code actually changes the niceness of kernel-thread/LWP. It 2609// has an assumption that setpriority() only modifies one kernel-thread/LWP, 2610// not the entire user process, and user level threads are 1:1 mapped to kernel 2611// threads. It has always been the case, but could change in the future. For 2612// this reason, the code should not be used as default (ThreadPriorityPolicy=0). 2613// It is only used when ThreadPriorityPolicy=1 and requires root privilege. 2614 2615#if !defined(__APPLE__) 2616int os::java_to_os_priority[CriticalPriority + 1] = { 2617 19, // 0 Entry should never be used 2618 2619 0, // 1 MinPriority 2620 3, // 2 2621 6, // 3 2622 2623 10, // 4 2624 15, // 5 NormPriority 2625 18, // 6 2626 2627 21, // 7 2628 25, // 8 2629 28, // 9 NearMaxPriority 2630 2631 31, // 10 MaxPriority 2632 2633 31 // 11 CriticalPriority 2634}; 2635#else 2636// Using Mach high-level priority assignments 2637int os::java_to_os_priority[CriticalPriority + 1] = { 2638 0, // 0 Entry should never be used (MINPRI_USER) 2639 2640 27, // 1 MinPriority 2641 28, // 2 2642 29, // 3 2643 2644 30, // 4 2645 31, // 5 NormPriority (BASEPRI_DEFAULT) 2646 32, // 6 2647 2648 33, // 7 2649 34, // 8 2650 35, // 9 NearMaxPriority 2651 2652 36, // 10 MaxPriority 2653 2654 36 // 11 CriticalPriority 2655}; 2656#endif 2657 2658static int prio_init() { 2659 if (ThreadPriorityPolicy == 1) { 2660 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 2661 // if effective uid is not root. Perhaps, a more elegant way of doing 2662 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 2663 if (geteuid() != 0) { 2664 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 2665 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd"); 2666 } 2667 ThreadPriorityPolicy = 0; 2668 } 2669 } 2670 if (UseCriticalJavaThreadPriority) { 2671 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; 2672 } 2673 return 0; 2674} 2675 2676OSReturn os::set_native_priority(Thread* thread, int newpri) { 2677 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; 2678 2679#ifdef __OpenBSD__ 2680 // OpenBSD pthread_setprio starves low priority threads 2681 return OS_OK; 2682#elif defined(__FreeBSD__) 2683 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri); 2684#elif defined(__APPLE__) || defined(__NetBSD__) 2685 struct sched_param sp; 2686 int policy; 2687 pthread_t self = pthread_self(); 2688 2689 if (pthread_getschedparam(self, &policy, &sp) != 0) { 2690 return OS_ERR; 2691 } 2692 2693 sp.sched_priority = newpri; 2694 if (pthread_setschedparam(self, policy, &sp) != 0) { 2695 return OS_ERR; 2696 } 2697 2698 return OS_OK; 2699#else 2700 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 2701 return (ret == 0) ? OS_OK : OS_ERR; 2702#endif 2703} 2704 2705OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { 2706 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { 2707 *priority_ptr = java_to_os_priority[NormPriority]; 2708 return OS_OK; 2709 } 2710 2711 errno = 0; 2712#if defined(__OpenBSD__) || defined(__FreeBSD__) 2713 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id()); 2714#elif defined(__APPLE__) || defined(__NetBSD__) 2715 int policy; 2716 struct sched_param sp; 2717 2718 pthread_getschedparam(pthread_self(), &policy, &sp); 2719 *priority_ptr = sp.sched_priority; 2720#else 2721 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 2722#endif 2723 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 2724} 2725 2726// Hint to the underlying OS that a task switch would not be good. 2727// Void return because it's a hint and can fail. 2728void os::hint_no_preempt() {} 2729 2730//////////////////////////////////////////////////////////////////////////////// 2731// suspend/resume support 2732 2733// the low-level signal-based suspend/resume support is a remnant from the 2734// old VM-suspension that used to be for java-suspension, safepoints etc, 2735// within hotspot. Now there is a single use-case for this: 2736// - calling get_thread_pc() on the VMThread by the flat-profiler task 2737// that runs in the watcher thread. 2738// The remaining code is greatly simplified from the more general suspension 2739// code that used to be used. 2740// 2741// The protocol is quite simple: 2742// - suspend: 2743// - sends a signal to the target thread 2744// - polls the suspend state of the osthread using a yield loop 2745// - target thread signal handler (SR_handler) sets suspend state 2746// and blocks in sigsuspend until continued 2747// - resume: 2748// - sets target osthread state to continue 2749// - sends signal to end the sigsuspend loop in the SR_handler 2750// 2751// Note that the SR_lock plays no role in this suspend/resume protocol. 2752 2753static void resume_clear_context(OSThread *osthread) { 2754 osthread->set_ucontext(NULL); 2755 osthread->set_siginfo(NULL); 2756} 2757 2758static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { 2759 osthread->set_ucontext(context); 2760 osthread->set_siginfo(siginfo); 2761} 2762 2763// Handler function invoked when a thread's execution is suspended or 2764// resumed. We have to be careful that only async-safe functions are 2765// called here (Note: most pthread functions are not async safe and 2766// should be avoided.) 2767// 2768// Note: sigwait() is a more natural fit than sigsuspend() from an 2769// interface point of view, but sigwait() prevents the signal hander 2770// from being run. libpthread would get very confused by not having 2771// its signal handlers run and prevents sigwait()'s use with the 2772// mutex granting granting signal. 2773// 2774// Currently only ever called on the VMThread or JavaThread 2775// 2776static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 2777 // Save and restore errno to avoid confusing native code with EINTR 2778 // after sigsuspend. 2779 int old_errno = errno; 2780 2781 Thread* thread = Thread::current(); 2782 OSThread* osthread = thread->osthread(); 2783 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 2784 2785 os::SuspendResume::State current = osthread->sr.state(); 2786 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 2787 suspend_save_context(osthread, siginfo, context); 2788 2789 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 2790 os::SuspendResume::State state = osthread->sr.suspended(); 2791 if (state == os::SuspendResume::SR_SUSPENDED) { 2792 sigset_t suspend_set; // signals for sigsuspend() 2793 2794 // get current set of blocked signals and unblock resume signal 2795 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 2796 sigdelset(&suspend_set, SR_signum); 2797 2798 sr_semaphore.signal(); 2799 // wait here until we are resumed 2800 while (1) { 2801 sigsuspend(&suspend_set); 2802 2803 os::SuspendResume::State result = osthread->sr.running(); 2804 if (result == os::SuspendResume::SR_RUNNING) { 2805 sr_semaphore.signal(); 2806 break; 2807 } else if (result != os::SuspendResume::SR_SUSPENDED) { 2808 ShouldNotReachHere(); 2809 } 2810 } 2811 2812 } else if (state == os::SuspendResume::SR_RUNNING) { 2813 // request was cancelled, continue 2814 } else { 2815 ShouldNotReachHere(); 2816 } 2817 2818 resume_clear_context(osthread); 2819 } else if (current == os::SuspendResume::SR_RUNNING) { 2820 // request was cancelled, continue 2821 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 2822 // ignore 2823 } else { 2824 // ignore 2825 } 2826 2827 errno = old_errno; 2828} 2829 2830 2831static int SR_initialize() { 2832 struct sigaction act; 2833 char *s; 2834 // Get signal number to use for suspend/resume 2835 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 2836 int sig = ::strtol(s, 0, 10); 2837 if (sig > 0 || sig < NSIG) { 2838 SR_signum = sig; 2839 } 2840 } 2841 2842 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 2843 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 2844 2845 sigemptyset(&SR_sigset); 2846 sigaddset(&SR_sigset, SR_signum); 2847 2848 // Set up signal handler for suspend/resume 2849 act.sa_flags = SA_RESTART|SA_SIGINFO; 2850 act.sa_handler = (void (*)(int)) SR_handler; 2851 2852 // SR_signum is blocked by default. 2853 // 4528190 - We also need to block pthread restart signal (32 on all 2854 // supported Bsd platforms). Note that BsdThreads need to block 2855 // this signal for all threads to work properly. So we don't have 2856 // to use hard-coded signal number when setting up the mask. 2857 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 2858 2859 if (sigaction(SR_signum, &act, 0) == -1) { 2860 return -1; 2861 } 2862 2863 // Save signal flag 2864 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags); 2865 return 0; 2866} 2867 2868static int sr_notify(OSThread* osthread) { 2869 int status = pthread_kill(osthread->pthread_id(), SR_signum); 2870 assert_status(status == 0, status, "pthread_kill"); 2871 return status; 2872} 2873 2874// "Randomly" selected value for how long we want to spin 2875// before bailing out on suspending a thread, also how often 2876// we send a signal to a thread we want to resume 2877static const int RANDOMLY_LARGE_INTEGER = 1000000; 2878static const int RANDOMLY_LARGE_INTEGER2 = 100; 2879 2880// returns true on success and false on error - really an error is fatal 2881// but this seems the normal response to library errors 2882static bool do_suspend(OSThread* osthread) { 2883 assert(osthread->sr.is_running(), "thread should be running"); 2884 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 2885 2886 // mark as suspended and send signal 2887 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 2888 // failed to switch, state wasn't running? 2889 ShouldNotReachHere(); 2890 return false; 2891 } 2892 2893 if (sr_notify(osthread) != 0) { 2894 ShouldNotReachHere(); 2895 } 2896 2897 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 2898 while (true) { 2899 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 2900 break; 2901 } else { 2902 // timeout 2903 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 2904 if (cancelled == os::SuspendResume::SR_RUNNING) { 2905 return false; 2906 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 2907 // make sure that we consume the signal on the semaphore as well 2908 sr_semaphore.wait(); 2909 break; 2910 } else { 2911 ShouldNotReachHere(); 2912 return false; 2913 } 2914 } 2915 } 2916 2917 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 2918 return true; 2919} 2920 2921static void do_resume(OSThread* osthread) { 2922 assert(osthread->sr.is_suspended(), "thread should be suspended"); 2923 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 2924 2925 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 2926 // failed to switch to WAKEUP_REQUEST 2927 ShouldNotReachHere(); 2928 return; 2929 } 2930 2931 while (true) { 2932 if (sr_notify(osthread) == 0) { 2933 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 2934 if (osthread->sr.is_running()) { 2935 return; 2936 } 2937 } 2938 } else { 2939 ShouldNotReachHere(); 2940 } 2941 } 2942 2943 guarantee(osthread->sr.is_running(), "Must be running!"); 2944} 2945 2946/////////////////////////////////////////////////////////////////////////////////// 2947// signal handling (except suspend/resume) 2948 2949// This routine may be used by user applications as a "hook" to catch signals. 2950// The user-defined signal handler must pass unrecognized signals to this 2951// routine, and if it returns true (non-zero), then the signal handler must 2952// return immediately. If the flag "abort_if_unrecognized" is true, then this 2953// routine will never retun false (zero), but instead will execute a VM panic 2954// routine kill the process. 2955// 2956// If this routine returns false, it is OK to call it again. This allows 2957// the user-defined signal handler to perform checks either before or after 2958// the VM performs its own checks. Naturally, the user code would be making 2959// a serious error if it tried to handle an exception (such as a null check 2960// or breakpoint) that the VM was generating for its own correct operation. 2961// 2962// This routine may recognize any of the following kinds of signals: 2963// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 2964// It should be consulted by handlers for any of those signals. 2965// 2966// The caller of this routine must pass in the three arguments supplied 2967// to the function referred to in the "sa_sigaction" (not the "sa_handler") 2968// field of the structure passed to sigaction(). This routine assumes that 2969// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 2970// 2971// Note that the VM will print warnings if it detects conflicting signal 2972// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 2973// 2974extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo, 2975 void* ucontext, 2976 int abort_if_unrecognized); 2977 2978void signalHandler(int sig, siginfo_t* info, void* uc) { 2979 assert(info != NULL && uc != NULL, "it must be old kernel"); 2980 int orig_errno = errno; // Preserve errno value over signal handler. 2981 JVM_handle_bsd_signal(sig, info, uc, true); 2982 errno = orig_errno; 2983} 2984 2985 2986// This boolean allows users to forward their own non-matching signals 2987// to JVM_handle_bsd_signal, harmlessly. 2988bool os::Bsd::signal_handlers_are_installed = false; 2989 2990// For signal-chaining 2991struct sigaction os::Bsd::sigact[MAXSIGNUM]; 2992unsigned int os::Bsd::sigs = 0; 2993bool os::Bsd::libjsig_is_loaded = false; 2994typedef struct sigaction *(*get_signal_t)(int); 2995get_signal_t os::Bsd::get_signal_action = NULL; 2996 2997struct sigaction* os::Bsd::get_chained_signal_action(int sig) { 2998 struct sigaction *actp = NULL; 2999 3000 if (libjsig_is_loaded) { 3001 // Retrieve the old signal handler from libjsig 3002 actp = (*get_signal_action)(sig); 3003 } 3004 if (actp == NULL) { 3005 // Retrieve the preinstalled signal handler from jvm 3006 actp = get_preinstalled_handler(sig); 3007 } 3008 3009 return actp; 3010} 3011 3012static bool call_chained_handler(struct sigaction *actp, int sig, 3013 siginfo_t *siginfo, void *context) { 3014 // Call the old signal handler 3015 if (actp->sa_handler == SIG_DFL) { 3016 // It's more reasonable to let jvm treat it as an unexpected exception 3017 // instead of taking the default action. 3018 return false; 3019 } else if (actp->sa_handler != SIG_IGN) { 3020 if ((actp->sa_flags & SA_NODEFER) == 0) { 3021 // automaticlly block the signal 3022 sigaddset(&(actp->sa_mask), sig); 3023 } 3024 3025 sa_handler_t hand; 3026 sa_sigaction_t sa; 3027 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 3028 // retrieve the chained handler 3029 if (siginfo_flag_set) { 3030 sa = actp->sa_sigaction; 3031 } else { 3032 hand = actp->sa_handler; 3033 } 3034 3035 if ((actp->sa_flags & SA_RESETHAND) != 0) { 3036 actp->sa_handler = SIG_DFL; 3037 } 3038 3039 // try to honor the signal mask 3040 sigset_t oset; 3041 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 3042 3043 // call into the chained handler 3044 if (siginfo_flag_set) { 3045 (*sa)(sig, siginfo, context); 3046 } else { 3047 (*hand)(sig); 3048 } 3049 3050 // restore the signal mask 3051 pthread_sigmask(SIG_SETMASK, &oset, 0); 3052 } 3053 // Tell jvm's signal handler the signal is taken care of. 3054 return true; 3055} 3056 3057bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) { 3058 bool chained = false; 3059 // signal-chaining 3060 if (UseSignalChaining) { 3061 struct sigaction *actp = get_chained_signal_action(sig); 3062 if (actp != NULL) { 3063 chained = call_chained_handler(actp, sig, siginfo, context); 3064 } 3065 } 3066 return chained; 3067} 3068 3069struct sigaction* os::Bsd::get_preinstalled_handler(int sig) { 3070 if ((((unsigned int)1 << sig) & sigs) != 0) { 3071 return &sigact[sig]; 3072 } 3073 return NULL; 3074} 3075 3076void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 3077 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3078 sigact[sig] = oldAct; 3079 sigs |= (unsigned int)1 << sig; 3080} 3081 3082// for diagnostic 3083int os::Bsd::sigflags[MAXSIGNUM]; 3084 3085int os::Bsd::get_our_sigflags(int sig) { 3086 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3087 return sigflags[sig]; 3088} 3089 3090void os::Bsd::set_our_sigflags(int sig, int flags) { 3091 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3092 sigflags[sig] = flags; 3093} 3094 3095void os::Bsd::set_signal_handler(int sig, bool set_installed) { 3096 // Check for overwrite. 3097 struct sigaction oldAct; 3098 sigaction(sig, (struct sigaction*)NULL, &oldAct); 3099 3100 void* oldhand = oldAct.sa_sigaction 3101 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3102 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3103 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 3104 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 3105 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 3106 if (AllowUserSignalHandlers || !set_installed) { 3107 // Do not overwrite; user takes responsibility to forward to us. 3108 return; 3109 } else if (UseSignalChaining) { 3110 // save the old handler in jvm 3111 save_preinstalled_handler(sig, oldAct); 3112 // libjsig also interposes the sigaction() call below and saves the 3113 // old sigaction on it own. 3114 } else { 3115 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " 3116 "%#lx for signal %d.", (long)oldhand, sig)); 3117 } 3118 } 3119 3120 struct sigaction sigAct; 3121 sigfillset(&(sigAct.sa_mask)); 3122 sigAct.sa_handler = SIG_DFL; 3123 if (!set_installed) { 3124 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3125 } else { 3126 sigAct.sa_sigaction = signalHandler; 3127 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3128 } 3129#ifdef __APPLE__ 3130 // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV 3131 // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages" 3132 // if the signal handler declares it will handle it on alternate stack. 3133 // Notice we only declare we will handle it on alt stack, but we are not 3134 // actually going to use real alt stack - this is just a workaround. 3135 // Please see ux_exception.c, method catch_mach_exception_raise for details 3136 // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c 3137 if (sig == SIGSEGV) { 3138 sigAct.sa_flags |= SA_ONSTACK; 3139 } 3140#endif 3141 3142 // Save flags, which are set by ours 3143 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3144 sigflags[sig] = sigAct.sa_flags; 3145 3146 int ret = sigaction(sig, &sigAct, &oldAct); 3147 assert(ret == 0, "check"); 3148 3149 void* oldhand2 = oldAct.sa_sigaction 3150 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3151 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3152 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 3153} 3154 3155// install signal handlers for signals that HotSpot needs to 3156// handle in order to support Java-level exception handling. 3157 3158void os::Bsd::install_signal_handlers() { 3159 if (!signal_handlers_are_installed) { 3160 signal_handlers_are_installed = true; 3161 3162 // signal-chaining 3163 typedef void (*signal_setting_t)(); 3164 signal_setting_t begin_signal_setting = NULL; 3165 signal_setting_t end_signal_setting = NULL; 3166 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3167 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 3168 if (begin_signal_setting != NULL) { 3169 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3170 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 3171 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 3172 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 3173 libjsig_is_loaded = true; 3174 assert(UseSignalChaining, "should enable signal-chaining"); 3175 } 3176 if (libjsig_is_loaded) { 3177 // Tell libjsig jvm is setting signal handlers 3178 (*begin_signal_setting)(); 3179 } 3180 3181 set_signal_handler(SIGSEGV, true); 3182 set_signal_handler(SIGPIPE, true); 3183 set_signal_handler(SIGBUS, true); 3184 set_signal_handler(SIGILL, true); 3185 set_signal_handler(SIGFPE, true); 3186 set_signal_handler(SIGXFSZ, true); 3187 3188#if defined(__APPLE__) 3189 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including 3190 // signals caught and handled by the JVM. To work around this, we reset the mach task 3191 // signal handler that's placed on our process by CrashReporter. This disables 3192 // CrashReporter-based reporting. 3193 // 3194 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes 3195 // on caught fatal signals. 3196 // 3197 // Additionally, gdb installs both standard BSD signal handlers, and mach exception 3198 // handlers. By replacing the existing task exception handler, we disable gdb's mach 3199 // exception handling, while leaving the standard BSD signal handlers functional. 3200 kern_return_t kr; 3201 kr = task_set_exception_ports(mach_task_self(), 3202 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC, 3203 MACH_PORT_NULL, 3204 EXCEPTION_STATE_IDENTITY, 3205 MACHINE_THREAD_STATE); 3206 3207 assert(kr == KERN_SUCCESS, "could not set mach task signal handler"); 3208#endif 3209 3210 if (libjsig_is_loaded) { 3211 // Tell libjsig jvm finishes setting signal handlers 3212 (*end_signal_setting)(); 3213 } 3214 3215 // We don't activate signal checker if libjsig is in place, we trust ourselves 3216 // and if UserSignalHandler is installed all bets are off 3217 if (CheckJNICalls) { 3218 if (libjsig_is_loaded) { 3219 if (PrintJNIResolving) { 3220 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 3221 } 3222 check_signals = false; 3223 } 3224 if (AllowUserSignalHandlers) { 3225 if (PrintJNIResolving) { 3226 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 3227 } 3228 check_signals = false; 3229 } 3230 } 3231 } 3232} 3233 3234 3235///// 3236// glibc on Bsd platform uses non-documented flag 3237// to indicate, that some special sort of signal 3238// trampoline is used. 3239// We will never set this flag, and we should 3240// ignore this flag in our diagnostic 3241#ifdef SIGNIFICANT_SIGNAL_MASK 3242 #undef SIGNIFICANT_SIGNAL_MASK 3243#endif 3244#define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 3245 3246static const char* get_signal_handler_name(address handler, 3247 char* buf, int buflen) { 3248 int offset; 3249 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 3250 if (found) { 3251 // skip directory names 3252 const char *p1, *p2; 3253 p1 = buf; 3254 size_t len = strlen(os::file_separator()); 3255 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 3256 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 3257 } else { 3258 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 3259 } 3260 return buf; 3261} 3262 3263static void print_signal_handler(outputStream* st, int sig, 3264 char* buf, size_t buflen) { 3265 struct sigaction sa; 3266 3267 sigaction(sig, NULL, &sa); 3268 3269 // See comment for SIGNIFICANT_SIGNAL_MASK define 3270 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3271 3272 st->print("%s: ", os::exception_name(sig, buf, buflen)); 3273 3274 address handler = (sa.sa_flags & SA_SIGINFO) 3275 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 3276 : CAST_FROM_FN_PTR(address, sa.sa_handler); 3277 3278 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 3279 st->print("SIG_DFL"); 3280 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 3281 st->print("SIG_IGN"); 3282 } else { 3283 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 3284 } 3285 3286 st->print(", sa_mask[0]="); 3287 os::Posix::print_signal_set_short(st, &sa.sa_mask); 3288 3289 address rh = VMError::get_resetted_sighandler(sig); 3290 // May be, handler was resetted by VMError? 3291 if (rh != NULL) { 3292 handler = rh; 3293 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 3294 } 3295 3296 st->print(", sa_flags="); 3297 os::Posix::print_sa_flags(st, sa.sa_flags); 3298 3299 // Check: is it our handler? 3300 if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 3301 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 3302 // It is our signal handler 3303 // check for flags, reset system-used one! 3304 if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { 3305 st->print( 3306 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 3307 os::Bsd::get_our_sigflags(sig)); 3308 } 3309 } 3310 st->cr(); 3311} 3312 3313 3314#define DO_SIGNAL_CHECK(sig) \ 3315 do { \ 3316 if (!sigismember(&check_signal_done, sig)) { \ 3317 os::Bsd::check_signal_handler(sig); \ 3318 } \ 3319 } while (0) 3320 3321// This method is a periodic task to check for misbehaving JNI applications 3322// under CheckJNI, we can add any periodic checks here 3323 3324void os::run_periodic_checks() { 3325 3326 if (check_signals == false) return; 3327 3328 // SEGV and BUS if overridden could potentially prevent 3329 // generation of hs*.log in the event of a crash, debugging 3330 // such a case can be very challenging, so we absolutely 3331 // check the following for a good measure: 3332 DO_SIGNAL_CHECK(SIGSEGV); 3333 DO_SIGNAL_CHECK(SIGILL); 3334 DO_SIGNAL_CHECK(SIGFPE); 3335 DO_SIGNAL_CHECK(SIGBUS); 3336 DO_SIGNAL_CHECK(SIGPIPE); 3337 DO_SIGNAL_CHECK(SIGXFSZ); 3338 3339 3340 // ReduceSignalUsage allows the user to override these handlers 3341 // see comments at the very top and jvm_solaris.h 3342 if (!ReduceSignalUsage) { 3343 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 3344 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 3345 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 3346 DO_SIGNAL_CHECK(BREAK_SIGNAL); 3347 } 3348 3349 DO_SIGNAL_CHECK(SR_signum); 3350 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 3351} 3352 3353typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 3354 3355static os_sigaction_t os_sigaction = NULL; 3356 3357void os::Bsd::check_signal_handler(int sig) { 3358 char buf[O_BUFLEN]; 3359 address jvmHandler = NULL; 3360 3361 3362 struct sigaction act; 3363 if (os_sigaction == NULL) { 3364 // only trust the default sigaction, in case it has been interposed 3365 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 3366 if (os_sigaction == NULL) return; 3367 } 3368 3369 os_sigaction(sig, (struct sigaction*)NULL, &act); 3370 3371 3372 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3373 3374 address thisHandler = (act.sa_flags & SA_SIGINFO) 3375 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 3376 : CAST_FROM_FN_PTR(address, act.sa_handler); 3377 3378 3379 switch (sig) { 3380 case SIGSEGV: 3381 case SIGBUS: 3382 case SIGFPE: 3383 case SIGPIPE: 3384 case SIGILL: 3385 case SIGXFSZ: 3386 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 3387 break; 3388 3389 case SHUTDOWN1_SIGNAL: 3390 case SHUTDOWN2_SIGNAL: 3391 case SHUTDOWN3_SIGNAL: 3392 case BREAK_SIGNAL: 3393 jvmHandler = (address)user_handler(); 3394 break; 3395 3396 case INTERRUPT_SIGNAL: 3397 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 3398 break; 3399 3400 default: 3401 if (sig == SR_signum) { 3402 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 3403 } else { 3404 return; 3405 } 3406 break; 3407 } 3408 3409 if (thisHandler != jvmHandler) { 3410 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 3411 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 3412 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 3413 // No need to check this sig any longer 3414 sigaddset(&check_signal_done, sig); 3415 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 3416 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 3417 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 3418 exception_name(sig, buf, O_BUFLEN)); 3419 } 3420 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) { 3421 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 3422 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig)); 3423 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 3424 // No need to check this sig any longer 3425 sigaddset(&check_signal_done, sig); 3426 } 3427 3428 // Dump all the signal 3429 if (sigismember(&check_signal_done, sig)) { 3430 print_signal_handlers(tty, buf, O_BUFLEN); 3431 } 3432} 3433 3434extern void report_error(char* file_name, int line_no, char* title, 3435 char* format, ...); 3436 3437extern bool signal_name(int signo, char* buf, size_t len); 3438 3439const char* os::exception_name(int exception_code, char* buf, size_t size) { 3440 if (0 < exception_code && exception_code <= SIGRTMAX) { 3441 // signal 3442 if (!signal_name(exception_code, buf, size)) { 3443 jio_snprintf(buf, size, "SIG%d", exception_code); 3444 } 3445 return buf; 3446 } else { 3447 return NULL; 3448 } 3449} 3450 3451// this is called _before_ the most of global arguments have been parsed 3452void os::init(void) { 3453 char dummy; // used to get a guess on initial stack address 3454// first_hrtime = gethrtime(); 3455 3456 // With BsdThreads the JavaMain thread pid (primordial thread) 3457 // is different than the pid of the java launcher thread. 3458 // So, on Bsd, the launcher thread pid is passed to the VM 3459 // via the sun.java.launcher.pid property. 3460 // Use this property instead of getpid() if it was correctly passed. 3461 // See bug 6351349. 3462 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 3463 3464 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 3465 3466 clock_tics_per_sec = CLK_TCK; 3467 3468 init_random(1234567); 3469 3470 ThreadCritical::initialize(); 3471 3472 Bsd::set_page_size(getpagesize()); 3473 if (Bsd::page_size() == -1) { 3474 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)", 3475 strerror(errno))); 3476 } 3477 init_page_sizes((size_t) Bsd::page_size()); 3478 3479 Bsd::initialize_system_info(); 3480 3481 // main_thread points to the aboriginal thread 3482 Bsd::_main_thread = pthread_self(); 3483 3484 Bsd::clock_init(); 3485 initial_time_count = javaTimeNanos(); 3486 3487#ifdef __APPLE__ 3488 // XXXDARWIN 3489 // Work around the unaligned VM callbacks in hotspot's 3490 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on 3491 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces 3492 // alignment when doing symbol lookup. To work around this, we force early 3493 // binding of all symbols now, thus binding when alignment is known-good. 3494 _dyld_bind_fully_image_containing_address((const void *) &os::init); 3495#endif 3496} 3497 3498// To install functions for atexit system call 3499extern "C" { 3500 static void perfMemory_exit_helper() { 3501 perfMemory_exit(); 3502 } 3503} 3504 3505// this is called _after_ the global arguments have been parsed 3506jint os::init_2(void) { 3507 // Allocate a single page and mark it as readable for safepoint polling 3508 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3509 guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); 3510 3511 os::set_polling_page(polling_page); 3512 3513#ifndef PRODUCT 3514 if (Verbose && PrintMiscellaneous) { 3515 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", 3516 (intptr_t)polling_page); 3517 } 3518#endif 3519 3520 if (!UseMembar) { 3521 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3522 guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); 3523 os::set_memory_serialize_page(mem_serialize_page); 3524 3525#ifndef PRODUCT 3526 if (Verbose && PrintMiscellaneous) { 3527 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", 3528 (intptr_t)mem_serialize_page); 3529 } 3530#endif 3531 } 3532 3533 // initialize suspend/resume support - must do this before signal_sets_init() 3534 if (SR_initialize() != 0) { 3535 perror("SR_initialize failed"); 3536 return JNI_ERR; 3537 } 3538 3539 Bsd::signal_sets_init(); 3540 Bsd::install_signal_handlers(); 3541 3542 // Check minimum allowable stack size for thread creation and to initialize 3543 // the java system classes, including StackOverflowError - depends on page 3544 // size. Add a page for compiler2 recursion in main thread. 3545 // Add in 2*BytesPerWord times page size to account for VM stack during 3546 // class initialization depending on 32 or 64 bit VM. 3547 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed, 3548 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+ 3549 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size()); 3550 3551 size_t threadStackSizeInBytes = ThreadStackSize * K; 3552 if (threadStackSizeInBytes != 0 && 3553 threadStackSizeInBytes < os::Bsd::min_stack_allowed) { 3554 tty->print_cr("\nThe stack size specified is too small, " 3555 "Specify at least %dk", 3556 os::Bsd::min_stack_allowed/ K); 3557 return JNI_ERR; 3558 } 3559 3560 // Make the stack size a multiple of the page size so that 3561 // the yellow/red zones can be guarded. 3562 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 3563 vm_page_size())); 3564 3565 if (MaxFDLimit) { 3566 // set the number of file descriptors to max. print out error 3567 // if getrlimit/setrlimit fails but continue regardless. 3568 struct rlimit nbr_files; 3569 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 3570 if (status != 0) { 3571 if (PrintMiscellaneous && (Verbose || WizardMode)) { 3572 perror("os::init_2 getrlimit failed"); 3573 } 3574 } else { 3575 nbr_files.rlim_cur = nbr_files.rlim_max; 3576 3577#ifdef __APPLE__ 3578 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if 3579 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must 3580 // be used instead 3581 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur); 3582#endif 3583 3584 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 3585 if (status != 0) { 3586 if (PrintMiscellaneous && (Verbose || WizardMode)) { 3587 perror("os::init_2 setrlimit failed"); 3588 } 3589 } 3590 } 3591 } 3592 3593 // at-exit methods are called in the reverse order of their registration. 3594 // atexit functions are called on return from main or as a result of a 3595 // call to exit(3C). There can be only 32 of these functions registered 3596 // and atexit() does not set errno. 3597 3598 if (PerfAllowAtExitRegistration) { 3599 // only register atexit functions if PerfAllowAtExitRegistration is set. 3600 // atexit functions can be delayed until process exit time, which 3601 // can be problematic for embedded VM situations. Embedded VMs should 3602 // call DestroyJavaVM() to assure that VM resources are released. 3603 3604 // note: perfMemory_exit_helper atexit function may be removed in 3605 // the future if the appropriate cleanup code can be added to the 3606 // VM_Exit VMOperation's doit method. 3607 if (atexit(perfMemory_exit_helper) != 0) { 3608 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 3609 } 3610 } 3611 3612 // initialize thread priority policy 3613 prio_init(); 3614 3615#ifdef __APPLE__ 3616 // dynamically link to objective c gc registration 3617 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY); 3618 if (handleLibObjc != NULL) { 3619 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER); 3620 } 3621#endif 3622 3623 return JNI_OK; 3624} 3625 3626// this is called at the end of vm_initialization 3627void os::init_3(void) { } 3628 3629// Mark the polling page as unreadable 3630void os::make_polling_page_unreadable(void) { 3631 if (!guard_memory((char*)_polling_page, Bsd::page_size())) { 3632 fatal("Could not disable polling page"); 3633 } 3634} 3635 3636// Mark the polling page as readable 3637void os::make_polling_page_readable(void) { 3638 if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { 3639 fatal("Could not enable polling page"); 3640 } 3641} 3642 3643int os::active_processor_count() { 3644 return _processor_count; 3645} 3646 3647void os::set_native_thread_name(const char *name) { 3648#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 3649 // This is only supported in Snow Leopard and beyond 3650 if (name != NULL) { 3651 // Add a "Java: " prefix to the name 3652 char buf[MAXTHREADNAMESIZE]; 3653 snprintf(buf, sizeof(buf), "Java: %s", name); 3654 pthread_setname_np(buf); 3655 } 3656#endif 3657} 3658 3659bool os::distribute_processes(uint length, uint* distribution) { 3660 // Not yet implemented. 3661 return false; 3662} 3663 3664bool os::bind_to_processor(uint processor_id) { 3665 // Not yet implemented. 3666 return false; 3667} 3668 3669void os::SuspendedThreadTask::internal_do_task() { 3670 if (do_suspend(_thread->osthread())) { 3671 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 3672 do_task(context); 3673 do_resume(_thread->osthread()); 3674 } 3675} 3676 3677/// 3678class PcFetcher : public os::SuspendedThreadTask { 3679 public: 3680 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 3681 ExtendedPC result(); 3682 protected: 3683 void do_task(const os::SuspendedThreadTaskContext& context); 3684 private: 3685 ExtendedPC _epc; 3686}; 3687 3688ExtendedPC PcFetcher::result() { 3689 guarantee(is_done(), "task is not done yet."); 3690 return _epc; 3691} 3692 3693void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 3694 Thread* thread = context.thread(); 3695 OSThread* osthread = thread->osthread(); 3696 if (osthread->ucontext() != NULL) { 3697 _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext()); 3698 } else { 3699 // NULL context is unexpected, double-check this is the VMThread 3700 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 3701 } 3702} 3703 3704// Suspends the target using the signal mechanism and then grabs the PC before 3705// resuming the target. Used by the flat-profiler only 3706ExtendedPC os::get_thread_pc(Thread* thread) { 3707 // Make sure that it is called by the watcher for the VMThread 3708 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 3709 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 3710 3711 PcFetcher fetcher(thread); 3712 fetcher.run(); 3713 return fetcher.result(); 3714} 3715 3716int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, 3717 pthread_mutex_t *_mutex, 3718 const struct timespec *_abstime) { 3719 return pthread_cond_timedwait(_cond, _mutex, _abstime); 3720} 3721 3722//////////////////////////////////////////////////////////////////////////////// 3723// debug support 3724 3725bool os::find(address addr, outputStream* st) { 3726 Dl_info dlinfo; 3727 memset(&dlinfo, 0, sizeof(dlinfo)); 3728 if (dladdr(addr, &dlinfo) != 0) { 3729 st->print(PTR_FORMAT ": ", addr); 3730 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 3731 st->print("%s+%#x", dlinfo.dli_sname, 3732 addr - (intptr_t)dlinfo.dli_saddr); 3733 } else if (dlinfo.dli_fbase != NULL) { 3734 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 3735 } else { 3736 st->print("<absolute address>"); 3737 } 3738 if (dlinfo.dli_fname != NULL) { 3739 st->print(" in %s", dlinfo.dli_fname); 3740 } 3741 if (dlinfo.dli_fbase != NULL) { 3742 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 3743 } 3744 st->cr(); 3745 3746 if (Verbose) { 3747 // decode some bytes around the PC 3748 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 3749 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 3750 address lowest = (address) dlinfo.dli_sname; 3751 if (!lowest) lowest = (address) dlinfo.dli_fbase; 3752 if (begin < lowest) begin = lowest; 3753 Dl_info dlinfo2; 3754 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 3755 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) { 3756 end = (address) dlinfo2.dli_saddr; 3757 } 3758 Disassembler::decode(begin, end, st); 3759 } 3760 return true; 3761 } 3762 return false; 3763} 3764 3765//////////////////////////////////////////////////////////////////////////////// 3766// misc 3767 3768// This does not do anything on Bsd. This is basically a hook for being 3769// able to use structured exception handling (thread-local exception filters) 3770// on, e.g., Win32. 3771void os::os_exception_wrapper(java_call_t f, JavaValue* value, 3772 methodHandle* method, JavaCallArguments* args, 3773 Thread* thread) { 3774 f(value, method, args, thread); 3775} 3776 3777void os::print_statistics() { 3778} 3779 3780int os::message_box(const char* title, const char* message) { 3781 int i; 3782 fdStream err(defaultStream::error_fd()); 3783 for (i = 0; i < 78; i++) err.print_raw("="); 3784 err.cr(); 3785 err.print_raw_cr(title); 3786 for (i = 0; i < 78; i++) err.print_raw("-"); 3787 err.cr(); 3788 err.print_raw_cr(message); 3789 for (i = 0; i < 78; i++) err.print_raw("="); 3790 err.cr(); 3791 3792 char buf[16]; 3793 // Prevent process from exiting upon "read error" without consuming all CPU 3794 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 3795 3796 return buf[0] == 'y' || buf[0] == 'Y'; 3797} 3798 3799int os::stat(const char *path, struct stat *sbuf) { 3800 char pathbuf[MAX_PATH]; 3801 if (strlen(path) > MAX_PATH - 1) { 3802 errno = ENAMETOOLONG; 3803 return -1; 3804 } 3805 os::native_path(strcpy(pathbuf, path)); 3806 return ::stat(pathbuf, sbuf); 3807} 3808 3809bool os::check_heap(bool force) { 3810 return true; 3811} 3812 3813ATTRIBUTE_PRINTF(3, 0) 3814int local_vsnprintf(char* buf, size_t count, const char* format, 3815 va_list args) { 3816 return ::vsnprintf(buf, count, format, args); 3817} 3818 3819// Is a (classpath) directory empty? 3820bool os::dir_is_empty(const char* path) { 3821 DIR *dir = NULL; 3822 struct dirent *ptr; 3823 3824 dir = opendir(path); 3825 if (dir == NULL) return true; 3826 3827 // Scan the directory 3828 bool result = true; 3829 char buf[sizeof(struct dirent) + MAX_PATH]; 3830 while (result && (ptr = ::readdir(dir)) != NULL) { 3831 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 3832 result = false; 3833 } 3834 } 3835 closedir(dir); 3836 return result; 3837} 3838 3839// This code originates from JDK's sysOpen and open64_w 3840// from src/solaris/hpi/src/system_md.c 3841 3842#ifndef O_DELETE 3843 #define O_DELETE 0x10000 3844#endif 3845 3846// Open a file. Unlink the file immediately after open returns 3847// if the specified oflag has the O_DELETE flag set. 3848// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c 3849 3850int os::open(const char *path, int oflag, int mode) { 3851 if (strlen(path) > MAX_PATH - 1) { 3852 errno = ENAMETOOLONG; 3853 return -1; 3854 } 3855 int fd; 3856 int o_delete = (oflag & O_DELETE); 3857 oflag = oflag & ~O_DELETE; 3858 3859 fd = ::open(path, oflag, mode); 3860 if (fd == -1) return -1; 3861 3862 // If the open succeeded, the file might still be a directory 3863 { 3864 struct stat buf; 3865 int ret = ::fstat(fd, &buf); 3866 int st_mode = buf.st_mode; 3867 3868 if (ret != -1) { 3869 if ((st_mode & S_IFMT) == S_IFDIR) { 3870 errno = EISDIR; 3871 ::close(fd); 3872 return -1; 3873 } 3874 } else { 3875 ::close(fd); 3876 return -1; 3877 } 3878 } 3879 3880 // All file descriptors that are opened in the JVM and not 3881 // specifically destined for a subprocess should have the 3882 // close-on-exec flag set. If we don't set it, then careless 3rd 3883 // party native code might fork and exec without closing all 3884 // appropriate file descriptors (e.g. as we do in closeDescriptors in 3885 // UNIXProcess.c), and this in turn might: 3886 // 3887 // - cause end-of-file to fail to be detected on some file 3888 // descriptors, resulting in mysterious hangs, or 3889 // 3890 // - might cause an fopen in the subprocess to fail on a system 3891 // suffering from bug 1085341. 3892 // 3893 // (Yes, the default setting of the close-on-exec flag is a Unix 3894 // design flaw) 3895 // 3896 // See: 3897 // 1085341: 32-bit stdio routines should support file descriptors >255 3898 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed 3899 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 3900 // 3901#ifdef FD_CLOEXEC 3902 { 3903 int flags = ::fcntl(fd, F_GETFD); 3904 if (flags != -1) { 3905 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 3906 } 3907 } 3908#endif 3909 3910 if (o_delete != 0) { 3911 ::unlink(path); 3912 } 3913 return fd; 3914} 3915 3916 3917// create binary file, rewriting existing file if required 3918int os::create_binary_file(const char* path, bool rewrite_existing) { 3919 int oflags = O_WRONLY | O_CREAT; 3920 if (!rewrite_existing) { 3921 oflags |= O_EXCL; 3922 } 3923 return ::open(path, oflags, S_IREAD | S_IWRITE); 3924} 3925 3926// return current position of file pointer 3927jlong os::current_file_offset(int fd) { 3928 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR); 3929} 3930 3931// move file pointer to the specified offset 3932jlong os::seek_to_file_offset(int fd, jlong offset) { 3933 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET); 3934} 3935 3936// This code originates from JDK's sysAvailable 3937// from src/solaris/hpi/src/native_threads/src/sys_api_td.c 3938 3939int os::available(int fd, jlong *bytes) { 3940 jlong cur, end; 3941 int mode; 3942 struct stat buf; 3943 3944 if (::fstat(fd, &buf) >= 0) { 3945 mode = buf.st_mode; 3946 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 3947 // XXX: is the following call interruptible? If so, this might 3948 // need to go through the INTERRUPT_IO() wrapper as for other 3949 // blocking, interruptible calls in this file. 3950 int n; 3951 if (::ioctl(fd, FIONREAD, &n) >= 0) { 3952 *bytes = n; 3953 return 1; 3954 } 3955 } 3956 } 3957 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) { 3958 return 0; 3959 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) { 3960 return 0; 3961 } else if (::lseek(fd, cur, SEEK_SET) == -1) { 3962 return 0; 3963 } 3964 *bytes = end - cur; 3965 return 1; 3966} 3967 3968int os::socket_available(int fd, jint *pbytes) { 3969 if (fd < 0) { 3970 return OS_OK; 3971 } 3972 3973 int ret; 3974 3975 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret); 3976 3977 //%% note ioctl can return 0 when successful, JVM_SocketAvailable 3978 // is expected to return 0 on failure and 1 on success to the jdk. 3979 3980 return (ret == OS_ERR) ? 0 : 1; 3981} 3982 3983// Map a block of memory. 3984char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 3985 char *addr, size_t bytes, bool read_only, 3986 bool allow_exec) { 3987 int prot; 3988 int flags; 3989 3990 if (read_only) { 3991 prot = PROT_READ; 3992 flags = MAP_SHARED; 3993 } else { 3994 prot = PROT_READ | PROT_WRITE; 3995 flags = MAP_PRIVATE; 3996 } 3997 3998 if (allow_exec) { 3999 prot |= PROT_EXEC; 4000 } 4001 4002 if (addr != NULL) { 4003 flags |= MAP_FIXED; 4004 } 4005 4006 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 4007 fd, file_offset); 4008 if (mapped_address == MAP_FAILED) { 4009 return NULL; 4010 } 4011 return mapped_address; 4012} 4013 4014 4015// Remap a block of memory. 4016char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 4017 char *addr, size_t bytes, bool read_only, 4018 bool allow_exec) { 4019 // same as map_memory() on this OS 4020 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4021 allow_exec); 4022} 4023 4024 4025// Unmap a block of memory. 4026bool os::pd_unmap_memory(char* addr, size_t bytes) { 4027 return munmap(addr, bytes) == 0; 4028} 4029 4030// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 4031// are used by JVM M&M and JVMTI to get user+sys or user CPU time 4032// of a thread. 4033// 4034// current_thread_cpu_time() and thread_cpu_time(Thread*) returns 4035// the fast estimate available on the platform. 4036 4037jlong os::current_thread_cpu_time() { 4038#ifdef __APPLE__ 4039 return os::thread_cpu_time(Thread::current(), true /* user + sys */); 4040#else 4041 Unimplemented(); 4042 return 0; 4043#endif 4044} 4045 4046jlong os::thread_cpu_time(Thread* thread) { 4047#ifdef __APPLE__ 4048 return os::thread_cpu_time(thread, true /* user + sys */); 4049#else 4050 Unimplemented(); 4051 return 0; 4052#endif 4053} 4054 4055jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 4056#ifdef __APPLE__ 4057 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 4058#else 4059 Unimplemented(); 4060 return 0; 4061#endif 4062} 4063 4064jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 4065#ifdef __APPLE__ 4066 struct thread_basic_info tinfo; 4067 mach_msg_type_number_t tcount = THREAD_INFO_MAX; 4068 kern_return_t kr; 4069 thread_t mach_thread; 4070 4071 mach_thread = thread->osthread()->thread_id(); 4072 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount); 4073 if (kr != KERN_SUCCESS) { 4074 return -1; 4075 } 4076 4077 if (user_sys_cpu_time) { 4078 jlong nanos; 4079 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000; 4080 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000; 4081 return nanos; 4082 } else { 4083 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000); 4084 } 4085#else 4086 Unimplemented(); 4087 return 0; 4088#endif 4089} 4090 4091 4092void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4093 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4094 info_ptr->may_skip_backward = false; // elapsed time not wall time 4095 info_ptr->may_skip_forward = false; // elapsed time not wall time 4096 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4097} 4098 4099void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4100 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4101 info_ptr->may_skip_backward = false; // elapsed time not wall time 4102 info_ptr->may_skip_forward = false; // elapsed time not wall time 4103 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4104} 4105 4106bool os::is_thread_cpu_time_supported() { 4107#ifdef __APPLE__ 4108 return true; 4109#else 4110 return false; 4111#endif 4112} 4113 4114// System loadavg support. Returns -1 if load average cannot be obtained. 4115// Bsd doesn't yet have a (official) notion of processor sets, 4116// so just return the system wide load average. 4117int os::loadavg(double loadavg[], int nelem) { 4118 return ::getloadavg(loadavg, nelem); 4119} 4120 4121void os::pause() { 4122 char filename[MAX_PATH]; 4123 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4124 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4125 } else { 4126 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4127 } 4128 4129 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4130 if (fd != -1) { 4131 struct stat buf; 4132 ::close(fd); 4133 while (::stat(filename, &buf) == 0) { 4134 (void)::poll(NULL, 0, 100); 4135 } 4136 } else { 4137 jio_fprintf(stderr, 4138 "Could not open pause file '%s', continuing immediately.\n", filename); 4139 } 4140} 4141 4142 4143// Refer to the comments in os_solaris.cpp park-unpark. 4144// 4145// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 4146// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 4147// For specifics regarding the bug see GLIBC BUGID 261237 : 4148// http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 4149// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 4150// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 4151// is used. (The simple C test-case provided in the GLIBC bug report manifests the 4152// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 4153// and monitorenter when we're using 1-0 locking. All those operations may result in 4154// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 4155// of libpthread avoids the problem, but isn't practical. 4156// 4157// Possible remedies: 4158// 4159// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 4160// This is palliative and probabilistic, however. If the thread is preempted 4161// between the call to compute_abstime() and pthread_cond_timedwait(), more 4162// than the minimum period may have passed, and the abstime may be stale (in the 4163// past) resultin in a hang. Using this technique reduces the odds of a hang 4164// but the JVM is still vulnerable, particularly on heavily loaded systems. 4165// 4166// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 4167// of the usual flag-condvar-mutex idiom. The write side of the pipe is set 4168// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 4169// reduces to poll()+read(). This works well, but consumes 2 FDs per extant 4170// thread. 4171// 4172// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 4173// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 4174// a timeout request to the chron thread and then blocking via pthread_cond_wait(). 4175// This also works well. In fact it avoids kernel-level scalability impediments 4176// on certain platforms that don't handle lots of active pthread_cond_timedwait() 4177// timers in a graceful fashion. 4178// 4179// 4. When the abstime value is in the past it appears that control returns 4180// correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 4181// Subsequent timedwait/wait calls may hang indefinitely. Given that, we 4182// can avoid the problem by reinitializing the condvar -- by cond_destroy() 4183// followed by cond_init() -- after all calls to pthread_cond_timedwait(). 4184// It may be possible to avoid reinitialization by checking the return 4185// value from pthread_cond_timedwait(). In addition to reinitializing the 4186// condvar we must establish the invariant that cond_signal() is only called 4187// within critical sections protected by the adjunct mutex. This prevents 4188// cond_signal() from "seeing" a condvar that's in the midst of being 4189// reinitialized or that is corrupt. Sadly, this invariant obviates the 4190// desirable signal-after-unlock optimization that avoids futile context switching. 4191// 4192// I'm also concerned that some versions of NTPL might allocate an auxilliary 4193// structure when a condvar is used or initialized. cond_destroy() would 4194// release the helper structure. Our reinitialize-after-timedwait fix 4195// put excessive stress on malloc/free and locks protecting the c-heap. 4196// 4197// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 4198// It may be possible to refine (4) by checking the kernel and NTPL verisons 4199// and only enabling the work-around for vulnerable environments. 4200 4201// utility to compute the abstime argument to timedwait: 4202// millis is the relative timeout time 4203// abstime will be the absolute timeout time 4204// TODO: replace compute_abstime() with unpackTime() 4205 4206static struct timespec* compute_abstime(struct timespec* abstime, 4207 jlong millis) { 4208 if (millis < 0) millis = 0; 4209 struct timeval now; 4210 int status = gettimeofday(&now, NULL); 4211 assert(status == 0, "gettimeofday"); 4212 jlong seconds = millis / 1000; 4213 millis %= 1000; 4214 if (seconds > 50000000) { // see man cond_timedwait(3T) 4215 seconds = 50000000; 4216 } 4217 abstime->tv_sec = now.tv_sec + seconds; 4218 long usec = now.tv_usec + millis * 1000; 4219 if (usec >= 1000000) { 4220 abstime->tv_sec += 1; 4221 usec -= 1000000; 4222 } 4223 abstime->tv_nsec = usec * 1000; 4224 return abstime; 4225} 4226 4227void os::PlatformEvent::park() { // AKA "down()" 4228 // Invariant: Only the thread associated with the Event/PlatformEvent 4229 // may call park(). 4230 // TODO: assert that _Assoc != NULL or _Assoc == Self 4231 assert(_nParked == 0, "invariant"); 4232 4233 int v; 4234 for (;;) { 4235 v = _Event; 4236 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4237 } 4238 guarantee(v >= 0, "invariant"); 4239 if (v == 0) { 4240 // Do this the hard way by blocking ... 4241 int status = pthread_mutex_lock(_mutex); 4242 assert_status(status == 0, status, "mutex_lock"); 4243 guarantee(_nParked == 0, "invariant"); 4244 ++_nParked; 4245 while (_Event < 0) { 4246 status = pthread_cond_wait(_cond, _mutex); 4247 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 4248 // Treat this the same as if the wait was interrupted 4249 if (status == ETIMEDOUT) { status = EINTR; } 4250 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 4251 } 4252 --_nParked; 4253 4254 _Event = 0; 4255 status = pthread_mutex_unlock(_mutex); 4256 assert_status(status == 0, status, "mutex_unlock"); 4257 // Paranoia to ensure our locked and lock-free paths interact 4258 // correctly with each other. 4259 OrderAccess::fence(); 4260 } 4261 guarantee(_Event >= 0, "invariant"); 4262} 4263 4264int os::PlatformEvent::park(jlong millis) { 4265 guarantee(_nParked == 0, "invariant"); 4266 4267 int v; 4268 for (;;) { 4269 v = _Event; 4270 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4271 } 4272 guarantee(v >= 0, "invariant"); 4273 if (v != 0) return OS_OK; 4274 4275 // We do this the hard way, by blocking the thread. 4276 // Consider enforcing a minimum timeout value. 4277 struct timespec abst; 4278 compute_abstime(&abst, millis); 4279 4280 int ret = OS_TIMEOUT; 4281 int status = pthread_mutex_lock(_mutex); 4282 assert_status(status == 0, status, "mutex_lock"); 4283 guarantee(_nParked == 0, "invariant"); 4284 ++_nParked; 4285 4286 // Object.wait(timo) will return because of 4287 // (a) notification 4288 // (b) timeout 4289 // (c) thread.interrupt 4290 // 4291 // Thread.interrupt and object.notify{All} both call Event::set. 4292 // That is, we treat thread.interrupt as a special case of notification. 4293 // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false. 4294 // We assume all ETIME returns are valid. 4295 // 4296 // TODO: properly differentiate simultaneous notify+interrupt. 4297 // In that case, we should propagate the notify to another waiter. 4298 4299 while (_Event < 0) { 4300 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst); 4301 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4302 pthread_cond_destroy(_cond); 4303 pthread_cond_init(_cond, NULL); 4304 } 4305 assert_status(status == 0 || status == EINTR || 4306 status == ETIMEDOUT, 4307 status, "cond_timedwait"); 4308 if (!FilterSpuriousWakeups) break; // previous semantics 4309 if (status == ETIMEDOUT) break; 4310 // We consume and ignore EINTR and spurious wakeups. 4311 } 4312 --_nParked; 4313 if (_Event >= 0) { 4314 ret = OS_OK; 4315 } 4316 _Event = 0; 4317 status = pthread_mutex_unlock(_mutex); 4318 assert_status(status == 0, status, "mutex_unlock"); 4319 assert(_nParked == 0, "invariant"); 4320 // Paranoia to ensure our locked and lock-free paths interact 4321 // correctly with each other. 4322 OrderAccess::fence(); 4323 return ret; 4324} 4325 4326void os::PlatformEvent::unpark() { 4327 // Transitions for _Event: 4328 // 0 :=> 1 4329 // 1 :=> 1 4330 // -1 :=> either 0 or 1; must signal target thread 4331 // That is, we can safely transition _Event from -1 to either 4332 // 0 or 1. 4333 // See also: "Semaphores in Plan 9" by Mullender & Cox 4334 // 4335 // Note: Forcing a transition from "-1" to "1" on an unpark() means 4336 // that it will take two back-to-back park() calls for the owning 4337 // thread to block. This has the benefit of forcing a spurious return 4338 // from the first park() call after an unpark() call which will help 4339 // shake out uses of park() and unpark() without condition variables. 4340 4341 if (Atomic::xchg(1, &_Event) >= 0) return; 4342 4343 // Wait for the thread associated with the event to vacate 4344 int status = pthread_mutex_lock(_mutex); 4345 assert_status(status == 0, status, "mutex_lock"); 4346 int AnyWaiters = _nParked; 4347 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 4348 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 4349 AnyWaiters = 0; 4350 pthread_cond_signal(_cond); 4351 } 4352 status = pthread_mutex_unlock(_mutex); 4353 assert_status(status == 0, status, "mutex_unlock"); 4354 if (AnyWaiters != 0) { 4355 status = pthread_cond_signal(_cond); 4356 assert_status(status == 0, status, "cond_signal"); 4357 } 4358 4359 // Note that we signal() _after dropping the lock for "immortal" Events. 4360 // This is safe and avoids a common class of futile wakeups. In rare 4361 // circumstances this can cause a thread to return prematurely from 4362 // cond_{timed}wait() but the spurious wakeup is benign and the victim will 4363 // simply re-test the condition and re-park itself. 4364} 4365 4366 4367// JSR166 4368// ------------------------------------------------------- 4369 4370// The solaris and bsd implementations of park/unpark are fairly 4371// conservative for now, but can be improved. They currently use a 4372// mutex/condvar pair, plus a a count. 4373// Park decrements count if > 0, else does a condvar wait. Unpark 4374// sets count to 1 and signals condvar. Only one thread ever waits 4375// on the condvar. Contention seen when trying to park implies that someone 4376// is unparking you, so don't wait. And spurious returns are fine, so there 4377// is no need to track notifications. 4378 4379#define MAX_SECS 100000000 4380 4381// This code is common to bsd and solaris and will be moved to a 4382// common place in dolphin. 4383// 4384// The passed in time value is either a relative time in nanoseconds 4385// or an absolute time in milliseconds. Either way it has to be unpacked 4386// into suitable seconds and nanoseconds components and stored in the 4387// given timespec structure. 4388// Given time is a 64-bit value and the time_t used in the timespec is only 4389// a signed-32-bit value (except on 64-bit Bsd) we have to watch for 4390// overflow if times way in the future are given. Further on Solaris versions 4391// prior to 10 there is a restriction (see cond_timedwait) that the specified 4392// number of seconds, in abstime, is less than current_time + 100,000,000. 4393// As it will be 28 years before "now + 100000000" will overflow we can 4394// ignore overflow and just impose a hard-limit on seconds using the value 4395// of "now + 100,000,000". This places a limit on the timeout of about 3.17 4396// years from "now". 4397 4398static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) { 4399 assert(time > 0, "convertTime"); 4400 4401 struct timeval now; 4402 int status = gettimeofday(&now, NULL); 4403 assert(status == 0, "gettimeofday"); 4404 4405 time_t max_secs = now.tv_sec + MAX_SECS; 4406 4407 if (isAbsolute) { 4408 jlong secs = time / 1000; 4409 if (secs > max_secs) { 4410 absTime->tv_sec = max_secs; 4411 } else { 4412 absTime->tv_sec = secs; 4413 } 4414 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 4415 } else { 4416 jlong secs = time / NANOSECS_PER_SEC; 4417 if (secs >= MAX_SECS) { 4418 absTime->tv_sec = max_secs; 4419 absTime->tv_nsec = 0; 4420 } else { 4421 absTime->tv_sec = now.tv_sec + secs; 4422 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 4423 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 4424 absTime->tv_nsec -= NANOSECS_PER_SEC; 4425 ++absTime->tv_sec; // note: this must be <= max_secs 4426 } 4427 } 4428 } 4429 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 4430 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 4431 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 4432 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 4433} 4434 4435void Parker::park(bool isAbsolute, jlong time) { 4436 // Ideally we'd do something useful while spinning, such 4437 // as calling unpackTime(). 4438 4439 // Optional fast-path check: 4440 // Return immediately if a permit is available. 4441 // We depend on Atomic::xchg() having full barrier semantics 4442 // since we are doing a lock-free update to _counter. 4443 if (Atomic::xchg(0, &_counter) > 0) return; 4444 4445 Thread* thread = Thread::current(); 4446 assert(thread->is_Java_thread(), "Must be JavaThread"); 4447 JavaThread *jt = (JavaThread *)thread; 4448 4449 // Optional optimization -- avoid state transitions if there's an interrupt pending. 4450 // Check interrupt before trying to wait 4451 if (Thread::is_interrupted(thread, false)) { 4452 return; 4453 } 4454 4455 // Next, demultiplex/decode time arguments 4456 struct timespec absTime; 4457 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 4458 return; 4459 } 4460 if (time > 0) { 4461 unpackTime(&absTime, isAbsolute, time); 4462 } 4463 4464 4465 // Enter safepoint region 4466 // Beware of deadlocks such as 6317397. 4467 // The per-thread Parker:: mutex is a classic leaf-lock. 4468 // In particular a thread must never block on the Threads_lock while 4469 // holding the Parker:: mutex. If safepoints are pending both the 4470 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 4471 ThreadBlockInVM tbivm(jt); 4472 4473 // Don't wait if cannot get lock since interference arises from 4474 // unblocking. Also. check interrupt before trying wait 4475 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 4476 return; 4477 } 4478 4479 int status; 4480 if (_counter > 0) { // no wait needed 4481 _counter = 0; 4482 status = pthread_mutex_unlock(_mutex); 4483 assert(status == 0, "invariant"); 4484 // Paranoia to ensure our locked and lock-free paths interact 4485 // correctly with each other and Java-level accesses. 4486 OrderAccess::fence(); 4487 return; 4488 } 4489 4490#ifdef ASSERT 4491 // Don't catch signals while blocked; let the running threads have the signals. 4492 // (This allows a debugger to break into the running thread.) 4493 sigset_t oldsigs; 4494 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals(); 4495 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 4496#endif 4497 4498 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 4499 jt->set_suspend_equivalent(); 4500 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 4501 4502 if (time == 0) { 4503 status = pthread_cond_wait(_cond, _mutex); 4504 } else { 4505 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &absTime); 4506 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4507 pthread_cond_destroy(_cond); 4508 pthread_cond_init(_cond, NULL); 4509 } 4510 } 4511 assert_status(status == 0 || status == EINTR || 4512 status == ETIMEDOUT, 4513 status, "cond_timedwait"); 4514 4515#ifdef ASSERT 4516 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 4517#endif 4518 4519 _counter = 0; 4520 status = pthread_mutex_unlock(_mutex); 4521 assert_status(status == 0, status, "invariant"); 4522 // Paranoia to ensure our locked and lock-free paths interact 4523 // correctly with each other and Java-level accesses. 4524 OrderAccess::fence(); 4525 4526 // If externally suspended while waiting, re-suspend 4527 if (jt->handle_special_suspend_equivalent_condition()) { 4528 jt->java_suspend_self(); 4529 } 4530} 4531 4532void Parker::unpark() { 4533 int status = pthread_mutex_lock(_mutex); 4534 assert(status == 0, "invariant"); 4535 const int s = _counter; 4536 _counter = 1; 4537 if (s < 1) { 4538 if (WorkAroundNPTLTimedWaitHang) { 4539 status = pthread_cond_signal(_cond); 4540 assert(status == 0, "invariant"); 4541 status = pthread_mutex_unlock(_mutex); 4542 assert(status == 0, "invariant"); 4543 } else { 4544 status = pthread_mutex_unlock(_mutex); 4545 assert(status == 0, "invariant"); 4546 status = pthread_cond_signal(_cond); 4547 assert(status == 0, "invariant"); 4548 } 4549 } else { 4550 pthread_mutex_unlock(_mutex); 4551 assert(status == 0, "invariant"); 4552 } 4553} 4554 4555 4556// Darwin has no "environ" in a dynamic library. 4557#ifdef __APPLE__ 4558 #include <crt_externs.h> 4559 #define environ (*_NSGetEnviron()) 4560#else 4561extern char** environ; 4562#endif 4563 4564// Run the specified command in a separate process. Return its exit value, 4565// or -1 on failure (e.g. can't fork a new process). 4566// Unlike system(), this function can be called from signal handler. It 4567// doesn't block SIGINT et al. 4568int os::fork_and_exec(char* cmd) { 4569 const char * argv[4] = {"sh", "-c", cmd, NULL}; 4570 4571 // fork() in BsdThreads/NPTL is not async-safe. It needs to run 4572 // pthread_atfork handlers and reset pthread library. All we need is a 4573 // separate process to execve. Make a direct syscall to fork process. 4574 // On IA64 there's no fork syscall, we have to use fork() and hope for 4575 // the best... 4576 pid_t pid = fork(); 4577 4578 if (pid < 0) { 4579 // fork failed 4580 return -1; 4581 4582 } else if (pid == 0) { 4583 // child process 4584 4585 // execve() in BsdThreads will call pthread_kill_other_threads_np() 4586 // first to kill every thread on the thread list. Because this list is 4587 // not reset by fork() (see notes above), execve() will instead kill 4588 // every thread in the parent process. We know this is the only thread 4589 // in the new process, so make a system call directly. 4590 // IA64 should use normal execve() from glibc to match the glibc fork() 4591 // above. 4592 execve("/bin/sh", (char* const*)argv, environ); 4593 4594 // execve failed 4595 _exit(-1); 4596 4597 } else { 4598 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 4599 // care about the actual exit code, for now. 4600 4601 int status; 4602 4603 // Wait for the child process to exit. This returns immediately if 4604 // the child has already exited. */ 4605 while (waitpid(pid, &status, 0) < 0) { 4606 switch (errno) { 4607 case ECHILD: return 0; 4608 case EINTR: break; 4609 default: return -1; 4610 } 4611 } 4612 4613 if (WIFEXITED(status)) { 4614 // The child exited normally; get its exit code. 4615 return WEXITSTATUS(status); 4616 } else if (WIFSIGNALED(status)) { 4617 // The child exited because of a signal 4618 // The best value to return is 0x80 + signal number, 4619 // because that is what all Unix shells do, and because 4620 // it allows callers to distinguish between process exit and 4621 // process death by signal. 4622 return 0x80 + WTERMSIG(status); 4623 } else { 4624 // Unknown exit code; pass it through 4625 return status; 4626 } 4627 } 4628} 4629 4630// is_headless_jre() 4631// 4632// Test for the existence of xawt/libmawt.so or libawt_xawt.so 4633// in order to report if we are running in a headless jre 4634// 4635// Since JDK8 xawt/libmawt.so was moved into the same directory 4636// as libawt.so, and renamed libawt_xawt.so 4637// 4638bool os::is_headless_jre() { 4639#ifdef __APPLE__ 4640 // We no longer build headless-only on Mac OS X 4641 return false; 4642#else 4643 struct stat statbuf; 4644 char buf[MAXPATHLEN]; 4645 char libmawtpath[MAXPATHLEN]; 4646 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX; 4647 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX; 4648 char *p; 4649 4650 // Get path to libjvm.so 4651 os::jvm_path(buf, sizeof(buf)); 4652 4653 // Get rid of libjvm.so 4654 p = strrchr(buf, '/'); 4655 if (p == NULL) { 4656 return false; 4657 } else { 4658 *p = '\0'; 4659 } 4660 4661 // Get rid of client or server 4662 p = strrchr(buf, '/'); 4663 if (p == NULL) { 4664 return false; 4665 } else { 4666 *p = '\0'; 4667 } 4668 4669 // check xawt/libmawt.so 4670 strcpy(libmawtpath, buf); 4671 strcat(libmawtpath, xawtstr); 4672 if (::stat(libmawtpath, &statbuf) == 0) return false; 4673 4674 // check libawt_xawt.so 4675 strcpy(libmawtpath, buf); 4676 strcat(libmawtpath, new_xawtstr); 4677 if (::stat(libmawtpath, &statbuf) == 0) return false; 4678 4679 return true; 4680#endif 4681} 4682 4683// Get the default path to the core file 4684// Returns the length of the string 4685int os::get_core_path(char* buffer, size_t bufferSize) { 4686 int n = jio_snprintf(buffer, bufferSize, "/cores"); 4687 4688 // Truncate if theoretical string was longer than bufferSize 4689 n = MIN2(n, (int)bufferSize); 4690 4691 return n; 4692} 4693 4694#ifndef PRODUCT 4695void TestReserveMemorySpecial_test() { 4696 // No tests available for this platform 4697} 4698#endif 4699