os_bsd.cpp revision 6649:01ab9db4584f
1185029Spjd/* 2185029Spjd * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. 3185029Spjd * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4185029Spjd * 5185029Spjd * This code is free software; you can redistribute it and/or modify it 6185029Spjd * under the terms of the GNU General Public License version 2 only, as 7185029Spjd * published by the Free Software Foundation. 8185029Spjd * 9185029Spjd * This code is distributed in the hope that it will be useful, but WITHOUT 10185029Spjd * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11185029Spjd * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12185029Spjd * version 2 for more details (a copy is included in the LICENSE file that 13185029Spjd * accompanied this code). 14185029Spjd * 15185029Spjd * You should have received a copy of the GNU General Public License version 16185029Spjd * 2 along with this work; if not, write to the Free Software Foundation, 17185029Spjd * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18185029Spjd * 19185029Spjd * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20185029Spjd * or visit www.oracle.com if you need additional information or have any 21185029Spjd * questions. 22219089Spjd * 23247265Smm */ 24185029Spjd 25185029Spjd// no precompiled headers 26185029Spjd#include "classfile/classLoader.hpp" 27185029Spjd#include "classfile/systemDictionary.hpp" 28185029Spjd#include "classfile/vmSymbols.hpp" 29185029Spjd#include "code/icBuffer.hpp" 30185029Spjd#include "code/vtableStubs.hpp" 31185029Spjd#include "compiler/compileBroker.hpp" 32185029Spjd#include "compiler/disassembler.hpp" 33185029Spjd#include "interpreter/interpreter.hpp" 34185029Spjd#include "jvm_bsd.h" 35185029Spjd#include "memory/allocation.inline.hpp" 36185029Spjd#include "memory/filemap.hpp" 37185029Spjd#include "mutex_bsd.inline.hpp" 38185029Spjd#include "oops/oop.inline.hpp" 39185029Spjd#include "os_share_bsd.hpp" 40185029Spjd#include "prims/jniFastGetField.hpp" 41185029Spjd#include "prims/jvm.h" 42185029Spjd#include "prims/jvm_misc.hpp" 43185029Spjd#include "runtime/arguments.hpp" 44185029Spjd#include "runtime/atomic.inline.hpp" 45219089Spjd#include "runtime/extendedPC.hpp" 46219089Spjd#include "runtime/globals.hpp" 47185029Spjd#include "runtime/interfaceSupport.hpp" 48185029Spjd#include "runtime/java.hpp" 49185029Spjd#include "runtime/javaCalls.hpp" 50219089Spjd#include "runtime/mutexLocker.hpp" 51185029Spjd#include "runtime/objectMonitor.hpp" 52185029Spjd#include "runtime/orderAccess.inline.hpp" 53185029Spjd#include "runtime/osThread.hpp" 54185029Spjd#include "runtime/perfMemory.hpp" 55185029Spjd#include "runtime/sharedRuntime.hpp" 56185029Spjd#include "runtime/statSampler.hpp" 57185029Spjd#include "runtime/stubRoutines.hpp" 58185029Spjd#include "runtime/thread.inline.hpp" 59185029Spjd#include "runtime/threadCritical.hpp" 60185029Spjd#include "runtime/timer.hpp" 61185029Spjd#include "services/attachListener.hpp" 62185029Spjd#include "services/memTracker.hpp" 63185029Spjd#include "services/runtimeService.hpp" 64185029Spjd#include "utilities/decoder.hpp" 65185029Spjd#include "utilities/defaultStream.hpp" 66185029Spjd#include "utilities/events.hpp" 67185029Spjd#include "utilities/growableArray.hpp" 68185029Spjd#include "utilities/vmError.hpp" 69185029Spjd 70185029Spjd// put OS-includes here 71185029Spjd# include <sys/types.h> 72185029Spjd# include <sys/mman.h> 73219089Spjd# include <sys/stat.h> 74185029Spjd# include <sys/select.h> 75185029Spjd# include <pthread.h> 76185029Spjd# include <signal.h> 77185029Spjd# include <errno.h> 78185029Spjd# include <dlfcn.h> 79185029Spjd# include <stdio.h> 80185029Spjd# include <unistd.h> 81185029Spjd# include <sys/resource.h> 82185029Spjd# include <pthread.h> 83185029Spjd# include <sys/stat.h> 84185029Spjd# include <sys/time.h> 85185029Spjd# include <sys/times.h> 86185029Spjd# include <sys/utsname.h> 87185029Spjd# include <sys/socket.h> 88185029Spjd# include <sys/wait.h> 89185029Spjd# include <time.h> 90185029Spjd# include <pwd.h> 91185029Spjd# include <poll.h> 92185029Spjd# include <semaphore.h> 93185029Spjd# include <fcntl.h> 94185029Spjd# include <string.h> 95185029Spjd# include <sys/param.h> 96185029Spjd# include <sys/sysctl.h> 97185029Spjd# include <sys/ipc.h> 98185029Spjd# include <sys/shm.h> 99185029Spjd#ifndef __APPLE__ 100185029Spjd# include <link.h> 101185029Spjd#endif 102185029Spjd# include <stdint.h> 103185029Spjd# include <inttypes.h> 104185029Spjd# include <sys/ioctl.h> 105185029Spjd# include <sys/syscall.h> 106185029Spjd 107185029Spjd#if defined(__FreeBSD__) || defined(__NetBSD__) 108185029Spjd# include <elf.h> 109185029Spjd#endif 110185029Spjd 111185029Spjd#ifdef __APPLE__ 112185029Spjd# include <mach/mach.h> // semaphore_* API 113185029Spjd# include <mach-o/dyld.h> 114185029Spjd# include <sys/proc_info.h> 115185029Spjd# include <objc/objc-auto.h> 116185029Spjd#endif 117185029Spjd 118185029Spjd#ifndef MAP_ANONYMOUS 119185029Spjd#define MAP_ANONYMOUS MAP_ANON 120185029Spjd#endif 121185029Spjd 122185029Spjd#define MAX_PATH (2 * K) 123185029Spjd 124185029Spjd// for timer info max values which include all bits 125185029Spjd#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 126185029Spjd 127185029Spjd#define LARGEPAGES_BIT (1 << 6) 128185029Spjd 129185029SpjdPRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 130185029Spjd 131185029Spjd//////////////////////////////////////////////////////////////////////////////// 132185029Spjd// global variables 133185029Spjdjulong os::Bsd::_physical_memory = 0; 134185029Spjd 135185029Spjd#ifdef __APPLE__ 136185029Spjdmach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0}; 137185029Spjdvolatile uint64_t os::Bsd::_max_abstime = 0; 138185029Spjd#else 139185029Spjdint (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL; 140185029Spjd#endif 141185029Spjdpthread_t os::Bsd::_main_thread; 142185029Spjdint os::Bsd::_page_size = -1; 143185029Spjd 144185029Spjdstatic jlong initial_time_count=0; 145185029Spjd 146185029Spjdstatic int clock_tics_per_sec = 100; 147186568Srwatson 148185029Spjd// For diagnostics to print a message once. see run_periodic_checks 149185029Spjdstatic sigset_t check_signal_done; 150185029Spjdstatic bool check_signals = true; 151185029Spjd 152185029Spjdstatic pid_t _initial_pid = 0; 153185029Spjd 154185029Spjd/* Signal number used to suspend/resume a thread */ 155185029Spjd 156185029Spjd/* do not use any signal number less than SIGSEGV, see 4355769 */ 157185029Spjdstatic int SR_signum = SIGUSR2; 158185029Spjdsigset_t SR_sigset; 159185029Spjd 160185029Spjd 161185029Spjd//////////////////////////////////////////////////////////////////////////////// 162185029Spjd// utility functions 163185029Spjd 164185029Spjdstatic int SR_initialize(); 165185029Spjdstatic void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 166185029Spjd 167185029Spjdjulong os::available_memory() { 168185029Spjd return Bsd::available_memory(); 169185029Spjd} 170219089Spjd 171185029Spjd// available here means free 172185029Spjdjulong os::Bsd::available_memory() { 173185029Spjd uint64_t available = physical_memory() >> 2; 174219089Spjd#ifdef __APPLE__ 175219089Spjd mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; 176219089Spjd vm_statistics64_data_t vmstat; 177185029Spjd kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64, 178185029Spjd (host_info64_t)&vmstat, &count); 179185029Spjd assert(kerr == KERN_SUCCESS, 180185029Spjd "host_statistics64 failed - check mach_host_self() and count"); 181185029Spjd if (kerr == KERN_SUCCESS) { 182185029Spjd available = vmstat.free_count * os::vm_page_size(); 183185029Spjd } 184185029Spjd#endif 185185029Spjd return available; 186185029Spjd} 187185029Spjd 188185029Spjdjulong os::physical_memory() { 189185029Spjd return Bsd::physical_memory(); 190185029Spjd} 191185029Spjd 192185029Spjd//////////////////////////////////////////////////////////////////////////////// 193185029Spjd// environment support 194185029Spjd 195185029Spjdbool os::getenv(const char* name, char* buf, int len) { 196185029Spjd const char* val = ::getenv(name); 197185029Spjd if (val != NULL && strlen(val) < (size_t)len) { 198185029Spjd strcpy(buf, val); 199185029Spjd return true; 200219089Spjd } 201219089Spjd if (len > 0) buf[0] = 0; // return a null string 202185029Spjd return false; 203185029Spjd} 204185029Spjd 205185029Spjd 206185029Spjd// Return true if user is running as root. 207185029Spjd 208185029Spjdbool os::have_special_privileges() { 209185029Spjd static bool init = false; 210185029Spjd static bool privileges = false; 211185029Spjd if (!init) { 212185029Spjd privileges = (getuid() != geteuid()) || (getgid() != getegid()); 213185029Spjd init = true; 214185029Spjd } 215185029Spjd return privileges; 216185029Spjd} 217185029Spjd 218185029Spjd 219185029Spjd 220185029Spjd// Cpu architecture string 221185029Spjd#if defined(ZERO) 222185029Spjdstatic char cpu_arch[] = ZERO_LIBARCH; 223185029Spjd#elif defined(IA64) 224185029Spjdstatic char cpu_arch[] = "ia64"; 225185029Spjd#elif defined(IA32) 226185029Spjdstatic char cpu_arch[] = "i386"; 227185029Spjd#elif defined(AMD64) 228185029Spjdstatic char cpu_arch[] = "amd64"; 229185029Spjd#elif defined(ARM) 230219089Spjdstatic char cpu_arch[] = "arm"; 231219089Spjd#elif defined(PPC32) 232219089Spjdstatic char cpu_arch[] = "ppc"; 233219089Spjd#elif defined(SPARC) 234219089Spjd# ifdef _LP64 235219089Spjdstatic char cpu_arch[] = "sparcv9"; 236219089Spjd# else 237185029Spjdstatic char cpu_arch[] = "sparc"; 238219089Spjd# endif 239219089Spjd#else 240219089Spjd#error Add appropriate cpu_arch setting 241185029Spjd#endif 242219089Spjd 243219089Spjd// Compiler variant 244219089Spjd#ifdef COMPILER2 245219089Spjd#define COMPILER_VARIANT "server" 246219089Spjd#else 247219089Spjd#define COMPILER_VARIANT "client" 248219089Spjd#endif 249219089Spjd 250219089Spjd 251219089Spjdvoid os::Bsd::initialize_system_info() { 252185029Spjd int mib[2]; 253185029Spjd size_t len; 254185029Spjd int cpu_val; 255185029Spjd julong mem_val; 256185029Spjd 257185029Spjd /* get processors count via hw.ncpus sysctl */ 258185029Spjd mib[0] = CTL_HW; 259185029Spjd mib[1] = HW_NCPU; 260185029Spjd len = sizeof(cpu_val); 261185029Spjd if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) { 262185029Spjd assert(len == sizeof(cpu_val), "unexpected data size"); 263185029Spjd set_processor_count(cpu_val); 264185029Spjd } 265185029Spjd else { 266185029Spjd set_processor_count(1); // fallback 267185029Spjd } 268185029Spjd 269185029Spjd /* get physical memory via hw.memsize sysctl (hw.memsize is used 270185029Spjd * since it returns a 64 bit value) 271185029Spjd */ 272185029Spjd mib[0] = CTL_HW; 273185029Spjd 274185029Spjd#if defined (HW_MEMSIZE) // Apple 275185029Spjd mib[1] = HW_MEMSIZE; 276185029Spjd#elif defined(HW_PHYSMEM) // Most of BSD 277185029Spjd mib[1] = HW_PHYSMEM; 278185029Spjd#elif defined(HW_REALMEM) // Old FreeBSD 279185029Spjd mib[1] = HW_REALMEM; 280185029Spjd#else 281185029Spjd #error No ways to get physmem 282185029Spjd#endif 283185029Spjd 284185029Spjd len = sizeof(mem_val); 285185029Spjd if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) { 286185029Spjd assert(len == sizeof(mem_val), "unexpected data size"); 287185029Spjd _physical_memory = mem_val; 288185029Spjd } else { 289185029Spjd _physical_memory = 256*1024*1024; // fallback (XXXBSD?) 290185029Spjd } 291185029Spjd 292219089Spjd#ifdef __OpenBSD__ 293185029Spjd { 294185029Spjd // limit _physical_memory memory view on OpenBSD since 295185029Spjd // datasize rlimit restricts us anyway. 296185029Spjd struct rlimit limits; 297185029Spjd getrlimit(RLIMIT_DATA, &limits); 298185029Spjd _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur); 299185029Spjd } 300185029Spjd#endif 301239774Smm} 302185029Spjd 303185029Spjd#ifdef __APPLE__ 304185029Spjdstatic const char *get_home() { 305185029Spjd const char *home_dir = ::getenv("HOME"); 306185029Spjd if ((home_dir == NULL) || (*home_dir == '\0')) { 307185029Spjd struct passwd *passwd_info = getpwuid(geteuid()); 308185029Spjd if (passwd_info != NULL) { 309219089Spjd home_dir = passwd_info->pw_dir; 310219089Spjd } 311219089Spjd } 312219089Spjd 313219089Spjd return home_dir; 314219089Spjd} 315185029Spjd#endif 316185029Spjd 317185029Spjdvoid os::init_system_properties_values() { 318185029Spjd // The next steps are taken in the product version: 319185029Spjd // 320185029Spjd // Obtain the JAVA_HOME value from the location of libjvm.so. 321185029Spjd // This library should be located at: 322185029Spjd // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 323185029Spjd // 324219089Spjd // If "/jre/lib/" appears at the right place in the path, then we 325185029Spjd // assume libjvm.so is installed in a JDK and we use this path. 326185029Spjd // 327185029Spjd // Otherwise exit with message: "Could not create the Java virtual machine." 328185029Spjd // 329185029Spjd // The following extra steps are taken in the debugging version: 330185029Spjd // 331185029Spjd // If "/jre/lib/" does NOT appear at the right place in the path 332185029Spjd // instead of exit check for $JAVA_HOME environment variable. 333185029Spjd // 334185029Spjd // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 335185029Spjd // then we append a fake suffix "hotspot/libjvm.so" to this path so 336185029Spjd // it looks like libjvm.so is installed there 337185029Spjd // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 338185029Spjd // 339185029Spjd // Otherwise exit. 340185029Spjd // 341185029Spjd // Important note: if the location of libjvm.so changes this 342185029Spjd // code needs to be changed accordingly. 343185029Spjd 344185029Spjd// See ld(1): 345185029Spjd// The linker uses the following search paths to locate required 346185029Spjd// shared libraries: 347185029Spjd// 1: ... 348185029Spjd// ... 349185029Spjd// 7: The default directories, normally /lib and /usr/lib. 350185029Spjd#ifndef DEFAULT_LIBPATH 351185029Spjd#define DEFAULT_LIBPATH "/lib:/usr/lib" 352185029Spjd#endif 353185029Spjd 354185029Spjd// Base path of extensions installed on the system. 355185029Spjd#define SYS_EXT_DIR "/usr/java/packages" 356219089Spjd#define EXTENSIONS_DIR "/lib/ext" 357185029Spjd#define ENDORSED_DIR "/lib/endorsed" 358185029Spjd 359185029Spjd#ifndef __APPLE__ 360185029Spjd 361185029Spjd // Buffer that fits several sprintfs. 362185029Spjd // Note that the space for the colon and the trailing null are provided 363185029Spjd // by the nulls included by the sizeof operator. 364185029Spjd const size_t bufsize = 365185029Spjd MAX3((size_t)MAXPATHLEN, // For dll_dir & friends. 366185029Spjd (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir 367185029Spjd (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir 368185029Spjd char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 369185029Spjd 370185029Spjd // sysclasspath, java_home, dll_dir 371185029Spjd { 372219089Spjd char *pslash; 373219089Spjd os::jvm_path(buf, bufsize); 374219089Spjd 375219089Spjd // Found the full path to libjvm.so. 376219089Spjd // Now cut the path to <java_home>/jre if we can. 377219089Spjd *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 378219089Spjd pslash = strrchr(buf, '/'); 379219089Spjd if (pslash != NULL) { 380219089Spjd *pslash = '\0'; // Get rid of /{client|server|hotspot}. 381219089Spjd } 382219089Spjd Arguments::set_dll_dir(buf); 383219089Spjd 384219089Spjd if (pslash != NULL) { 385219089Spjd pslash = strrchr(buf, '/'); 386219089Spjd if (pslash != NULL) { 387219089Spjd *pslash = '\0'; // Get rid of /<arch>. 388219089Spjd pslash = strrchr(buf, '/'); 389219089Spjd if (pslash != NULL) { 390219089Spjd *pslash = '\0'; // Get rid of /lib. 391219089Spjd } 392219089Spjd } 393185029Spjd } 394185029Spjd Arguments::set_java_home(buf); 395185029Spjd set_boot_path('/', ':'); 396185029Spjd } 397185029Spjd 398185029Spjd // Where to look for native libraries. 399185029Spjd // 400219089Spjd // Note: Due to a legacy implementation, most of the library path 401185029Spjd // is set in the launcher. This was to accomodate linking restrictions 402185029Spjd // on legacy Bsd implementations (which are no longer supported). 403219089Spjd // Eventually, all the library path setting will be done here. 404219089Spjd // 405219089Spjd // However, to prevent the proliferation of improperly built native 406219089Spjd // libraries, the new path component /usr/java/packages is added here. 407219089Spjd // Eventually, all the library path setting will be done here. 408219089Spjd { 409185029Spjd // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 410219089Spjd // should always exist (until the legacy problem cited above is 411219089Spjd // addressed). 412219089Spjd const char *v = ::getenv("LD_LIBRARY_PATH"); 413219089Spjd const char *v_colon = ":"; 414219089Spjd if (v == NULL) { v = ""; v_colon = ""; } 415185029Spjd // That's +1 for the colon and +1 for the trailing '\0'. 416219089Spjd char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 417219089Spjd strlen(v) + 1 + 418219089Spjd sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1, 419185029Spjd mtInternal); 420185029Spjd sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch); 421185029Spjd Arguments::set_library_path(ld_library_path); 422185029Spjd FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal); 423185029Spjd } 424185029Spjd 425185029Spjd // Extensions directories. 426239774Smm sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 427185029Spjd Arguments::set_ext_dirs(buf); 428185029Spjd 429185029Spjd // Endorsed standards default directory. 430185029Spjd sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 431185029Spjd Arguments::set_endorsed_dirs(buf); 432185029Spjd 433185029Spjd FREE_C_HEAP_ARRAY(char, buf, mtInternal); 434185029Spjd 435185029Spjd#else // __APPLE__ 436185029Spjd 437185029Spjd#define SYS_EXTENSIONS_DIR "/Library/Java/Extensions" 438185029Spjd#define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java" 439185029Spjd 440185029Spjd const char *user_home_dir = get_home(); 441185029Spjd // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir. 442185029Spjd size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) + 443185029Spjd sizeof(SYS_EXTENSIONS_DIRS); 444185029Spjd 445185029Spjd // Buffer that fits several sprintfs. 446185029Spjd // Note that the space for the colon and the trailing null are provided 447219089Spjd // by the nulls included by the sizeof operator. 448219089Spjd const size_t bufsize = 449185029Spjd MAX3((size_t)MAXPATHLEN, // for dll_dir & friends. 450185029Spjd (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir 451185029Spjd (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir 452185029Spjd char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 453185029Spjd 454185029Spjd // sysclasspath, java_home, dll_dir 455185029Spjd { 456185029Spjd char *pslash; 457185029Spjd os::jvm_path(buf, bufsize); 458185029Spjd 459239774Smm // Found the full path to libjvm.so. 460185029Spjd // Now cut the path to <java_home>/jre if we can. 461185029Spjd *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 462185029Spjd pslash = strrchr(buf, '/'); 463185029Spjd if (pslash != NULL) { 464185029Spjd *pslash = '\0'; // Get rid of /{client|server|hotspot}. 465185029Spjd } 466185029Spjd Arguments::set_dll_dir(buf); 467185029Spjd 468185029Spjd if (pslash != NULL) { 469185029Spjd pslash = strrchr(buf, '/'); 470185029Spjd if (pslash != NULL) { 471185029Spjd *pslash = '\0'; // Get rid of /lib. 472185029Spjd } 473185029Spjd } 474185029Spjd Arguments::set_java_home(buf); 475185029Spjd set_boot_path('/', ':'); 476185029Spjd } 477185029Spjd 478185029Spjd // Where to look for native libraries. 479185029Spjd // 480185029Spjd // Note: Due to a legacy implementation, most of the library path 481239774Smm // is set in the launcher. This was to accomodate linking restrictions 482185029Spjd // on legacy Bsd implementations (which are no longer supported). 483185029Spjd // Eventually, all the library path setting will be done here. 484185029Spjd // 485185029Spjd // However, to prevent the proliferation of improperly built native 486185029Spjd // libraries, the new path component /usr/java/packages is added here. 487185029Spjd // Eventually, all the library path setting will be done here. 488185029Spjd { 489185029Spjd // Get the user setting of LD_LIBRARY_PATH, and prepended it. It 490185029Spjd // should always exist (until the legacy problem cited above is 491185029Spjd // addressed). 492185029Spjd // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code 493185029Spjd // can specify a directory inside an app wrapper 494185029Spjd const char *l = ::getenv("JAVA_LIBRARY_PATH"); 495185029Spjd const char *l_colon = ":"; 496185029Spjd if (l == NULL) { l = ""; l_colon = ""; } 497185029Spjd 498185029Spjd const char *v = ::getenv("DYLD_LIBRARY_PATH"); 499185029Spjd const char *v_colon = ":"; 500185029Spjd if (v == NULL) { v = ""; v_colon = ""; } 501185029Spjd 502185029Spjd // Apple's Java6 has "." at the beginning of java.library.path. 503185029Spjd // OpenJDK on Windows has "." at the end of java.library.path. 504185029Spjd // OpenJDK on Linux and Solaris don't have "." in java.library.path 505219089Spjd // at all. To ease the transition from Apple's Java6 to OpenJDK7, 506219089Spjd // "." is appended to the end of java.library.path. Yes, this 507219089Spjd // could cause a change in behavior, but Apple's Java6 behavior 508219089Spjd // can be achieved by putting "." at the beginning of the 509219089Spjd // JAVA_LIBRARY_PATH environment variable. 510219089Spjd char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char, 511219089Spjd strlen(v) + 1 + strlen(l) + 1 + 512219089Spjd system_ext_size + 3, 513219089Spjd mtInternal); 514185029Spjd sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.", 515185029Spjd v, v_colon, l, l_colon, user_home_dir); 516185029Spjd Arguments::set_library_path(ld_library_path); 517185029Spjd FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal); 518185029Spjd } 519185029Spjd 520185029Spjd // Extensions directories. 521185029Spjd // 522185029Spjd // Note that the space for the colon and the trailing null are provided 523185029Spjd // by the nulls included by the sizeof operator (so actually one byte more 524185029Spjd // than necessary is allocated). 525185029Spjd sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS, 526185029Spjd user_home_dir, Arguments::get_java_home()); 527185029Spjd Arguments::set_ext_dirs(buf); 528185029Spjd 529185029Spjd // Endorsed standards default directory. 530185029Spjd sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 531185029Spjd Arguments::set_endorsed_dirs(buf); 532185029Spjd 533185029Spjd FREE_C_HEAP_ARRAY(char, buf, mtInternal); 534185029Spjd 535185029Spjd#undef SYS_EXTENSIONS_DIR 536219089Spjd#undef SYS_EXTENSIONS_DIRS 537219089Spjd 538239774Smm#endif // __APPLE__ 539219089Spjd 540219089Spjd#undef SYS_EXT_DIR 541219089Spjd#undef EXTENSIONS_DIR 542219089Spjd#undef ENDORSED_DIR 543219089Spjd} 544219089Spjd 545219089Spjd//////////////////////////////////////////////////////////////////////////////// 546219089Spjd// breakpoint support 547219089Spjd 548219089Spjdvoid os::breakpoint() { 549219089Spjd BREAKPOINT; 550219089Spjd} 551219089Spjd 552185029Spjdextern "C" void breakpoint() { 553185029Spjd // use debugger to set breakpoint here 554185029Spjd} 555185029Spjd 556185029Spjd//////////////////////////////////////////////////////////////////////////////// 557185029Spjd// signal support 558185029Spjd 559185029Spjddebug_only(static bool signal_sets_initialized = false); 560185029Spjdstatic sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 561185029Spjd 562185029Spjdbool os::Bsd::is_sig_ignored(int sig) { 563185029Spjd struct sigaction oact; 564219089Spjd sigaction(sig, (struct sigaction*)NULL, &oact); 565219089Spjd void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 566185029Spjd : CAST_FROM_FN_PTR(void*, oact.sa_handler); 567185029Spjd if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) 568185029Spjd return true; 569185029Spjd else 570185029Spjd return false; 571185029Spjd} 572219089Spjd 573219089Spjdvoid os::Bsd::signal_sets_init() { 574219089Spjd // Should also have an assertion stating we are still single-threaded. 575185029Spjd assert(!signal_sets_initialized, "Already initialized"); 576185029Spjd // Fill in signals that are necessarily unblocked for all threads in 577185029Spjd // the VM. Currently, we unblock the following signals: 578185029Spjd // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 579185029Spjd // by -Xrs (=ReduceSignalUsage)); 580185029Spjd // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 581185029Spjd // other threads. The "ReduceSignalUsage" boolean tells us not to alter 582185029Spjd // the dispositions or masks wrt these signals. 583185029Spjd // Programs embedding the VM that want to use the above signals for their 584185029Spjd // own purposes must, at this time, use the "-Xrs" option to prevent 585185029Spjd // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 586185029Spjd // (See bug 4345157, and other related bugs). 587185029Spjd // In reality, though, unblocking these signals is really a nop, since 588185029Spjd // these signals are not blocked by default. 589185029Spjd sigemptyset(&unblocked_sigs); 590185029Spjd sigemptyset(&allowdebug_blocked_sigs); 591185029Spjd sigaddset(&unblocked_sigs, SIGILL); 592185029Spjd sigaddset(&unblocked_sigs, SIGSEGV); 593185029Spjd sigaddset(&unblocked_sigs, SIGBUS); 594185029Spjd sigaddset(&unblocked_sigs, SIGFPE); 595185029Spjd sigaddset(&unblocked_sigs, SR_signum); 596185029Spjd 597185029Spjd if (!ReduceSignalUsage) { 598185029Spjd if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 599185029Spjd sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 600185029Spjd sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 601185029Spjd } 602185029Spjd if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 603185029Spjd sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 604185029Spjd sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 605185029Spjd } 606219089Spjd if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 607247265Smm sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 608185029Spjd sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 609185029Spjd } 610185029Spjd } 611185029Spjd // Fill in signals that are blocked by all but the VM thread. 612219089Spjd sigemptyset(&vm_sigs); 613219089Spjd if (!ReduceSignalUsage) 614219089Spjd sigaddset(&vm_sigs, BREAK_SIGNAL); 615219089Spjd debug_only(signal_sets_initialized = true); 616219089Spjd 617219089Spjd} 618219089Spjd 619219089Spjd// These are signals that are unblocked while a thread is running Java. 620219089Spjd// (For some reason, they get blocked by default.) 621219089Spjdsigset_t* os::Bsd::unblocked_signals() { 622219089Spjd assert(signal_sets_initialized, "Not initialized"); 623219089Spjd return &unblocked_sigs; 624185029Spjd} 625185029Spjd 626185029Spjd// These are the signals that are blocked while a (non-VM) thread is 627185029Spjd// running Java. Only the VM thread handles these signals. 628185029Spjdsigset_t* os::Bsd::vm_signals() { 629185029Spjd assert(signal_sets_initialized, "Not initialized"); 630185029Spjd return &vm_sigs; 631185029Spjd} 632185029Spjd 633247265Smm// These are signals that are blocked during cond_wait to allow debugger in 634247265Smmsigset_t* os::Bsd::allowdebug_blocked_signals() { 635247265Smm assert(signal_sets_initialized, "Not initialized"); 636247265Smm return &allowdebug_blocked_sigs; 637247265Smm} 638247265Smm 639247265Smmvoid os::Bsd::hotspot_sigmask(Thread* thread) { 640247265Smm 641247265Smm //Save caller's signal mask before setting VM signal mask 642185029Spjd sigset_t caller_sigmask; 643185029Spjd pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 644185029Spjd 645185029Spjd OSThread* osthread = thread->osthread(); 646185029Spjd osthread->set_caller_sigmask(caller_sigmask); 647185029Spjd 648185029Spjd pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL); 649219089Spjd 650219089Spjd if (!ReduceSignalUsage) { 651185029Spjd if (thread->is_VM_thread()) { 652185029Spjd // Only the VM thread handles BREAK_SIGNAL ... 653185029Spjd pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 654185029Spjd } else { 655185029Spjd // ... all other threads block BREAK_SIGNAL 656185029Spjd pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 657185029Spjd } 658185029Spjd } 659185029Spjd} 660185029Spjd 661185029Spjd 662185029Spjd////////////////////////////////////////////////////////////////////////////// 663185029Spjd// create new thread 664185029Spjd 665185029Spjd// check if it's safe to start a new thread 666185029Spjdstatic bool _thread_safety_check(Thread* thread) { 667213198Smm return true; 668213198Smm} 669213198Smm 670219089Spjd#ifdef __APPLE__ 671219089Spjd// library handle for calling objc_registerThreadWithCollector() 672219089Spjd// without static linking to the libobjc library 673219089Spjd#define OBJC_LIB "/usr/lib/libobjc.dylib" 674219089Spjd#define OBJC_GCREGISTER "objc_registerThreadWithCollector" 675219089Spjdtypedef void (*objc_registerThreadWithCollector_t)(); 676219089Spjdextern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction; 677219089Spjdobjc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL; 678219089Spjd#endif 679219089Spjd 680219089Spjd#ifdef __APPLE__ 681219089Spjdstatic uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) { 682185029Spjd // Additional thread_id used to correlate threads in SA 683185029Spjd thread_identifier_info_data_t m_ident_info; 684185029Spjd mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT; 685219089Spjd 686219089Spjd thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO, 687219089Spjd (thread_info_t) &m_ident_info, &count); 688219089Spjd 689219089Spjd return m_ident_info.thread_id; 690219089Spjd} 691185029Spjd#endif 692185029Spjd 693185029Spjd// Thread start routine for all newly created threads 694185029Spjdstatic void *java_start(Thread *thread) { 695185029Spjd // Try to randomize the cache line index of hot stack frames. 696185029Spjd // This helps when threads of the same stack traces evict each other's 697185029Spjd // cache lines. The threads can be either from the same JVM instance, or 698185029Spjd // from different JVM instances. The benefit is especially true for 699185029Spjd // processors with hyperthreading technology. 700185029Spjd static int counter = 0; 701185029Spjd int pid = os::current_process_id(); 702185029Spjd alloca(((pid ^ counter++) & 7) * 128); 703219089Spjd 704219089Spjd ThreadLocalStorage::set_thread(thread); 705219089Spjd 706247265Smm OSThread* osthread = thread->osthread(); 707219089Spjd Monitor* sync = osthread->startThread_lock(); 708185029Spjd 709185029Spjd // non floating stack BsdThreads needs extra check, see above 710185029Spjd if (!_thread_safety_check(thread)) { 711185029Spjd // notify parent thread 712185029Spjd MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 713185029Spjd osthread->set_state(ZOMBIE); 714219089Spjd sync->notify_all(); 715219089Spjd return NULL; 716219089Spjd } 717219089Spjd 718219089Spjd osthread->set_thread_id(os::Bsd::gettid()); 719219089Spjd 720219089Spjd#ifdef __APPLE__ 721219089Spjd uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id()); 722219089Spjd guarantee(unique_thread_id != 0, "unique thread id was not found"); 723219089Spjd osthread->set_unique_thread_id(unique_thread_id); 724219089Spjd#endif 725219089Spjd // initialize signal mask for this thread 726219089Spjd os::Bsd::hotspot_sigmask(thread); 727219089Spjd 728219089Spjd // initialize floating point control register 729219089Spjd os::Bsd::init_thread_fpu_state(); 730219089Spjd 731219089Spjd#ifdef __APPLE__ 732219089Spjd // register thread with objc gc 733219089Spjd if (objc_registerThreadWithCollectorFunction != NULL) { 734219089Spjd objc_registerThreadWithCollectorFunction(); 735219089Spjd } 736219089Spjd#endif 737219089Spjd 738219089Spjd // handshaking with parent thread 739219089Spjd { 740219089Spjd MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 741219089Spjd 742219089Spjd // notify parent thread 743185029Spjd osthread->set_state(INITIALIZED); 744185029Spjd sync->notify_all(); 745185029Spjd 746185029Spjd // wait until os::start_thread() 747185029Spjd while (osthread->get_state() == INITIALIZED) { 748185029Spjd sync->wait(Mutex::_no_safepoint_check_flag); 749185029Spjd } 750185029Spjd } 751185029Spjd 752185029Spjd // call one more level start routine 753185029Spjd thread->run(); 754185029Spjd 755185029Spjd return 0; 756185029Spjd} 757185029Spjd 758185029Spjdbool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 759185029Spjd assert(thread->osthread() == NULL, "caller responsible"); 760185029Spjd 761185029Spjd // Allocate the OSThread object 762185029Spjd OSThread* osthread = new OSThread(NULL, NULL); 763185029Spjd if (osthread == NULL) { 764185029Spjd return false; 765185029Spjd } 766185029Spjd 767185029Spjd // set the correct thread state 768185029Spjd osthread->set_thread_type(thr_type); 769185029Spjd 770185029Spjd // Initial state is ALLOCATED but not INITIALIZED 771185029Spjd osthread->set_state(ALLOCATED); 772185029Spjd 773185029Spjd thread->set_osthread(osthread); 774185029Spjd 775185029Spjd // init thread attributes 776185029Spjd pthread_attr_t attr; 777185029Spjd pthread_attr_init(&attr); 778185029Spjd pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 779185029Spjd 780247265Smm // stack size 781247265Smm if (os::Bsd::supports_variable_stack_size()) { 782247265Smm // calculate stack size if it's not specified by caller 783185029Spjd if (stack_size == 0) { 784185029Spjd stack_size = os::Bsd::default_stack_size(thr_type); 785185029Spjd 786185029Spjd switch (thr_type) { 787185029Spjd case os::java_thread: 788247265Smm // Java threads use ThreadStackSize which default value can be 789185029Spjd // changed with the flag -Xss 790185029Spjd assert(JavaThread::stack_size_at_create() > 0, "this should be set"); 791185029Spjd stack_size = JavaThread::stack_size_at_create(); 792185029Spjd break; 793185029Spjd case os::compiler_thread: 794185029Spjd if (CompilerThreadStackSize > 0) { 795185029Spjd stack_size = (size_t)(CompilerThreadStackSize * K); 796185029Spjd break; 797185029Spjd } // else fall through: 798185029Spjd // use VMThreadStackSize if CompilerThreadStackSize is not defined 799185029Spjd case os::vm_thread: 800185029Spjd case os::pgc_thread: 801185029Spjd case os::cgc_thread: 802185029Spjd case os::watcher_thread: 803185029Spjd if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 804185029Spjd break; 805185029Spjd } 806185029Spjd } 807185029Spjd 808185029Spjd stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed); 809185029Spjd pthread_attr_setstacksize(&attr, stack_size); 810185029Spjd } else { 811185029Spjd // let pthread_create() pick the default value. 812185029Spjd } 813185029Spjd 814185029Spjd ThreadState state; 815185029Spjd 816185029Spjd { 817185029Spjd pthread_t tid; 818185029Spjd int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 819185029Spjd 820247265Smm pthread_attr_destroy(&attr); 821185029Spjd 822185029Spjd if (ret != 0) { 823185029Spjd if (PrintMiscellaneous && (Verbose || WizardMode)) { 824185029Spjd perror("pthread_create()"); 825185029Spjd } 826185029Spjd // Need to clean up stuff we've allocated so far 827185029Spjd thread->set_osthread(NULL); 828185029Spjd delete osthread; 829185029Spjd return false; 830185029Spjd } 831185029Spjd 832185029Spjd // Store pthread info into the OSThread 833185029Spjd osthread->set_pthread_id(tid); 834185029Spjd 835185029Spjd // Wait until child thread is either initialized or aborted 836185029Spjd { 837185029Spjd Monitor* sync_with_child = osthread->startThread_lock(); 838185029Spjd MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 839185029Spjd while ((state = osthread->get_state()) == ALLOCATED) { 840185029Spjd sync_with_child->wait(Mutex::_no_safepoint_check_flag); 841185029Spjd } 842185029Spjd } 843219089Spjd 844185029Spjd } 845185029Spjd 846185029Spjd // Aborted due to thread limit being reached 847185029Spjd if (state == ZOMBIE) { 848219089Spjd thread->set_osthread(NULL); 849219089Spjd delete osthread; 850219089Spjd return false; 851219089Spjd } 852185029Spjd 853219089Spjd // The thread is returned suspended (in state INITIALIZED), 854247265Smm // and is started higher up in the call chain 855185029Spjd assert(state == INITIALIZED, "race condition"); 856185029Spjd return true; 857185029Spjd} 858185029Spjd 859185029Spjd///////////////////////////////////////////////////////////////////////////// 860185029Spjd// attach existing thread 861185029Spjd 862185029Spjd// bootstrap the main thread 863185029Spjdbool os::create_main_thread(JavaThread* thread) { 864185029Spjd assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread"); 865185029Spjd return create_attached_thread(thread); 866185029Spjd} 867185029Spjd 868185029Spjdbool os::create_attached_thread(JavaThread* thread) { 869185029Spjd#ifdef ASSERT 870185029Spjd thread->verify_not_published(); 871185029Spjd#endif 872185029Spjd 873185029Spjd // Allocate the OSThread object 874185029Spjd OSThread* osthread = new OSThread(NULL, NULL); 875185029Spjd 876185029Spjd if (osthread == NULL) { 877247265Smm return false; 878185029Spjd } 879185029Spjd 880185029Spjd osthread->set_thread_id(os::Bsd::gettid()); 881185029Spjd 882247265Smm // Store pthread info into the OSThread 883219089Spjd#ifdef __APPLE__ 884247265Smm uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id()); 885219089Spjd guarantee(unique_thread_id != 0, "just checking"); 886219089Spjd osthread->set_unique_thread_id(unique_thread_id); 887219089Spjd#endif 888219089Spjd osthread->set_pthread_id(::pthread_self()); 889219089Spjd 890219089Spjd // initialize floating point control register 891219089Spjd os::Bsd::init_thread_fpu_state(); 892219089Spjd 893219089Spjd // Initial thread state is RUNNABLE 894219089Spjd osthread->set_state(RUNNABLE); 895219089Spjd 896219089Spjd thread->set_osthread(osthread); 897219089Spjd 898219089Spjd // initialize signal mask for this thread 899219089Spjd // and save the caller's signal mask 900219089Spjd os::Bsd::hotspot_sigmask(thread); 901219089Spjd 902247265Smm return true; 903219089Spjd} 904219089Spjd 905219089Spjdvoid os::pd_start_thread(Thread* thread) { 906219089Spjd OSThread * osthread = thread->osthread(); 907219089Spjd assert(osthread->get_state() != INITIALIZED, "just checking"); 908219089Spjd Monitor* sync_with_child = osthread->startThread_lock(); 909219089Spjd MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 910219089Spjd sync_with_child->notify(); 911219089Spjd} 912219089Spjd 913219089Spjd// Free Bsd resources related to the OSThread 914219089Spjdvoid os::free_thread(OSThread* osthread) { 915219089Spjd assert(osthread != NULL, "osthread not set"); 916219089Spjd 917219089Spjd if (Thread::current()->osthread() == osthread) { 918219089Spjd // Restore caller's signal mask 919219089Spjd sigset_t sigmask = osthread->caller_sigmask(); 920219089Spjd pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 921219089Spjd } 922219089Spjd 923185029Spjd delete osthread; 924185029Spjd} 925185029Spjd 926219089Spjd////////////////////////////////////////////////////////////////////////////// 927219089Spjd// thread local storage 928185029Spjd 929185029Spjd// Restore the thread pointer if the destructor is called. This is in case 930185029Spjd// someone from JNI code sets up a destructor with pthread_key_create to run 931185029Spjd// detachCurrentThread on thread death. Unless we restore the thread pointer we 932185029Spjd// will hang or crash. When detachCurrentThread is called the key will be set 933185029Spjd// to null and we will not be called again. If detachCurrentThread is never 934185029Spjd// called we could loop forever depending on the pthread implementation. 935185029Spjdstatic void restore_thread_pointer(void* p) { 936185029Spjd Thread* thread = (Thread*) p; 937185029Spjd os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread); 938185029Spjd} 939185029Spjd 940185029Spjdint os::allocate_thread_local_storage() { 941185029Spjd pthread_key_t key; 942185029Spjd int rslt = pthread_key_create(&key, restore_thread_pointer); 943185029Spjd assert(rslt == 0, "cannot allocate thread local storage"); 944185029Spjd return (int)key; 945185029Spjd} 946185029Spjd 947185029Spjd// Note: This is currently not used by VM, as we don't destroy TLS key 948185029Spjd// on VM exit. 949185029Spjdvoid os::free_thread_local_storage(int index) { 950185029Spjd int rslt = pthread_key_delete((pthread_key_t)index); 951185029Spjd assert(rslt == 0, "invalid index"); 952185029Spjd} 953185029Spjd 954185029Spjdvoid os::thread_local_storage_at_put(int index, void* value) { 955185029Spjd int rslt = pthread_setspecific((pthread_key_t)index, value); 956247265Smm assert(rslt == 0, "pthread_setspecific failed"); 957185029Spjd} 958185029Spjd 959185029Spjdextern "C" Thread* get_thread() { 960185029Spjd return ThreadLocalStorage::thread(); 961185029Spjd} 962185029Spjd 963185029Spjd 964185029Spjd//////////////////////////////////////////////////////////////////////////////// 965185029Spjd// time support 966185029Spjd 967185029Spjd// Time since start-up in seconds to a fine granularity. 968185029Spjd// Used by VMSelfDestructTimer and the MemProfiler. 969185029Spjddouble os::elapsedTime() { 970185029Spjd 971185029Spjd return ((double)os::elapsed_counter()) / os::elapsed_frequency(); 972185029Spjd} 973185029Spjd 974185029Spjdjlong os::elapsed_counter() { 975185029Spjd return javaTimeNanos() - initial_time_count; 976185029Spjd} 977185029Spjd 978185029Spjdjlong os::elapsed_frequency() { 979185029Spjd return NANOSECS_PER_SEC; // nanosecond resolution 980185029Spjd} 981185029Spjd 982185029Spjdbool os::supports_vtime() { return true; } 983185029Spjdbool os::enable_vtime() { return false; } 984185029Spjdbool os::vtime_enabled() { return false; } 985185029Spjd 986185029Spjddouble os::elapsedVTime() { 987185029Spjd // better than nothing, but not much 988 return elapsedTime(); 989} 990 991jlong os::javaTimeMillis() { 992 timeval time; 993 int status = gettimeofday(&time, NULL); 994 assert(status != -1, "bsd error"); 995 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 996} 997 998#ifndef __APPLE__ 999#ifndef CLOCK_MONOTONIC 1000#define CLOCK_MONOTONIC (1) 1001#endif 1002#endif 1003 1004#ifdef __APPLE__ 1005void os::Bsd::clock_init() { 1006 mach_timebase_info(&_timebase_info); 1007} 1008#else 1009void os::Bsd::clock_init() { 1010 struct timespec res; 1011 struct timespec tp; 1012 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 && 1013 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { 1014 // yes, monotonic clock is supported 1015 _clock_gettime = ::clock_gettime; 1016 } 1017} 1018#endif 1019 1020 1021 1022#ifdef __APPLE__ 1023 1024jlong os::javaTimeNanos() { 1025 const uint64_t tm = mach_absolute_time(); 1026 const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom; 1027 const uint64_t prev = Bsd::_max_abstime; 1028 if (now <= prev) { 1029 return prev; // same or retrograde time; 1030 } 1031 const uint64_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&Bsd::_max_abstime, prev); 1032 assert(obsv >= prev, "invariant"); // Monotonicity 1033 // If the CAS succeeded then we're done and return "now". 1034 // If the CAS failed and the observed value "obsv" is >= now then 1035 // we should return "obsv". If the CAS failed and now > obsv > prv then 1036 // some other thread raced this thread and installed a new value, in which case 1037 // we could either (a) retry the entire operation, (b) retry trying to install now 1038 // or (c) just return obsv. We use (c). No loop is required although in some cases 1039 // we might discard a higher "now" value in deference to a slightly lower but freshly 1040 // installed obsv value. That's entirely benign -- it admits no new orderings compared 1041 // to (a) or (b) -- and greatly reduces coherence traffic. 1042 // We might also condition (c) on the magnitude of the delta between obsv and now. 1043 // Avoiding excessive CAS operations to hot RW locations is critical. 1044 // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate 1045 return (prev == obsv) ? now : obsv; 1046} 1047 1048#else // __APPLE__ 1049 1050jlong os::javaTimeNanos() { 1051 if (os::supports_monotonic_clock()) { 1052 struct timespec tp; 1053 int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp); 1054 assert(status == 0, "gettime error"); 1055 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 1056 return result; 1057 } else { 1058 timeval time; 1059 int status = gettimeofday(&time, NULL); 1060 assert(status != -1, "bsd error"); 1061 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1062 return 1000 * usecs; 1063 } 1064} 1065 1066#endif // __APPLE__ 1067 1068void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1069 if (os::supports_monotonic_clock()) { 1070 info_ptr->max_value = ALL_64_BITS; 1071 1072 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 1073 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1074 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1075 } else { 1076 // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1077 info_ptr->max_value = ALL_64_BITS; 1078 1079 // gettimeofday is a real time clock so it skips 1080 info_ptr->may_skip_backward = true; 1081 info_ptr->may_skip_forward = true; 1082 } 1083 1084 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1085} 1086 1087// Return the real, user, and system times in seconds from an 1088// arbitrary fixed point in the past. 1089bool os::getTimesSecs(double* process_real_time, 1090 double* process_user_time, 1091 double* process_system_time) { 1092 struct tms ticks; 1093 clock_t real_ticks = times(&ticks); 1094 1095 if (real_ticks == (clock_t) (-1)) { 1096 return false; 1097 } else { 1098 double ticks_per_second = (double) clock_tics_per_sec; 1099 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1100 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1101 *process_real_time = ((double) real_ticks) / ticks_per_second; 1102 1103 return true; 1104 } 1105} 1106 1107 1108char * os::local_time_string(char *buf, size_t buflen) { 1109 struct tm t; 1110 time_t long_time; 1111 time(&long_time); 1112 localtime_r(&long_time, &t); 1113 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1114 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1115 t.tm_hour, t.tm_min, t.tm_sec); 1116 return buf; 1117} 1118 1119struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1120 return localtime_r(clock, res); 1121} 1122 1123//////////////////////////////////////////////////////////////////////////////// 1124// runtime exit support 1125 1126// Note: os::shutdown() might be called very early during initialization, or 1127// called from signal handler. Before adding something to os::shutdown(), make 1128// sure it is async-safe and can handle partially initialized VM. 1129void os::shutdown() { 1130 1131 // allow PerfMemory to attempt cleanup of any persistent resources 1132 perfMemory_exit(); 1133 1134 // needs to remove object in file system 1135 AttachListener::abort(); 1136 1137 // flush buffered output, finish log files 1138 ostream_abort(); 1139 1140 // Check for abort hook 1141 abort_hook_t abort_hook = Arguments::abort_hook(); 1142 if (abort_hook != NULL) { 1143 abort_hook(); 1144 } 1145 1146} 1147 1148// Note: os::abort() might be called very early during initialization, or 1149// called from signal handler. Before adding something to os::abort(), make 1150// sure it is async-safe and can handle partially initialized VM. 1151void os::abort(bool dump_core) { 1152 os::shutdown(); 1153 if (dump_core) { 1154#ifndef PRODUCT 1155 fdStream out(defaultStream::output_fd()); 1156 out.print_raw("Current thread is "); 1157 char buf[16]; 1158 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1159 out.print_raw_cr(buf); 1160 out.print_raw_cr("Dumping core ..."); 1161#endif 1162 ::abort(); // dump core 1163 } 1164 1165 ::exit(1); 1166} 1167 1168// Die immediately, no exit hook, no abort hook, no cleanup. 1169void os::die() { 1170 // _exit() on BsdThreads only kills current thread 1171 ::abort(); 1172} 1173 1174// unused on bsd for now. 1175void os::set_error_file(const char *logfile) {} 1176 1177 1178// This method is a copy of JDK's sysGetLastErrorString 1179// from src/solaris/hpi/src/system_md.c 1180 1181size_t os::lasterror(char *buf, size_t len) { 1182 1183 if (errno == 0) return 0; 1184 1185 const char *s = ::strerror(errno); 1186 size_t n = ::strlen(s); 1187 if (n >= len) { 1188 n = len - 1; 1189 } 1190 ::strncpy(buf, s, n); 1191 buf[n] = '\0'; 1192 return n; 1193} 1194 1195// Information of current thread in variety of formats 1196pid_t os::Bsd::gettid() { 1197 int retval = -1; 1198 1199#ifdef __APPLE__ //XNU kernel 1200 // despite the fact mach port is actually not a thread id use it 1201 // instead of syscall(SYS_thread_selfid) as it certainly fits to u4 1202 retval = ::pthread_mach_thread_np(::pthread_self()); 1203 guarantee(retval != 0, "just checking"); 1204 return retval; 1205 1206#elif __FreeBSD__ 1207 retval = syscall(SYS_thr_self); 1208#elif __OpenBSD__ 1209 retval = syscall(SYS_getthrid); 1210#elif __NetBSD__ 1211 retval = (pid_t) syscall(SYS__lwp_self); 1212#endif 1213 1214 if (retval == -1) { 1215 return getpid(); 1216 } 1217} 1218 1219intx os::current_thread_id() { 1220#ifdef __APPLE__ 1221 return (intx)::pthread_mach_thread_np(::pthread_self()); 1222#else 1223 return (intx)::pthread_self(); 1224#endif 1225} 1226 1227int os::current_process_id() { 1228 1229 // Under the old bsd thread library, bsd gives each thread 1230 // its own process id. Because of this each thread will return 1231 // a different pid if this method were to return the result 1232 // of getpid(2). Bsd provides no api that returns the pid 1233 // of the launcher thread for the vm. This implementation 1234 // returns a unique pid, the pid of the launcher thread 1235 // that starts the vm 'process'. 1236 1237 // Under the NPTL, getpid() returns the same pid as the 1238 // launcher thread rather than a unique pid per thread. 1239 // Use gettid() if you want the old pre NPTL behaviour. 1240 1241 // if you are looking for the result of a call to getpid() that 1242 // returns a unique pid for the calling thread, then look at the 1243 // OSThread::thread_id() method in osThread_bsd.hpp file 1244 1245 return (int)(_initial_pid ? _initial_pid : getpid()); 1246} 1247 1248// DLL functions 1249 1250#define JNI_LIB_PREFIX "lib" 1251#ifdef __APPLE__ 1252#define JNI_LIB_SUFFIX ".dylib" 1253#else 1254#define JNI_LIB_SUFFIX ".so" 1255#endif 1256 1257const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; } 1258 1259// This must be hard coded because it's the system's temporary 1260// directory not the java application's temp directory, ala java.io.tmpdir. 1261#ifdef __APPLE__ 1262// macosx has a secure per-user temporary directory 1263char temp_path_storage[PATH_MAX]; 1264const char* os::get_temp_directory() { 1265 static char *temp_path = NULL; 1266 if (temp_path == NULL) { 1267 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX); 1268 if (pathSize == 0 || pathSize > PATH_MAX) { 1269 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage)); 1270 } 1271 temp_path = temp_path_storage; 1272 } 1273 return temp_path; 1274} 1275#else /* __APPLE__ */ 1276const char* os::get_temp_directory() { return "/tmp"; } 1277#endif /* __APPLE__ */ 1278 1279static bool file_exists(const char* filename) { 1280 struct stat statbuf; 1281 if (filename == NULL || strlen(filename) == 0) { 1282 return false; 1283 } 1284 return os::stat(filename, &statbuf) == 0; 1285} 1286 1287bool os::dll_build_name(char* buffer, size_t buflen, 1288 const char* pname, const char* fname) { 1289 bool retval = false; 1290 // Copied from libhpi 1291 const size_t pnamelen = pname ? strlen(pname) : 0; 1292 1293 // Return error on buffer overflow. 1294 if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) { 1295 return retval; 1296 } 1297 1298 if (pnamelen == 0) { 1299 snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname); 1300 retval = true; 1301 } else if (strchr(pname, *os::path_separator()) != NULL) { 1302 int n; 1303 char** pelements = split_path(pname, &n); 1304 if (pelements == NULL) { 1305 return false; 1306 } 1307 for (int i = 0; i < n; i++) { 1308 // Really shouldn't be NULL, but check can't hurt 1309 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1310 continue; // skip the empty path values 1311 } 1312 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, 1313 pelements[i], fname); 1314 if (file_exists(buffer)) { 1315 retval = true; 1316 break; 1317 } 1318 } 1319 // release the storage 1320 for (int i = 0; i < n; i++) { 1321 if (pelements[i] != NULL) { 1322 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); 1323 } 1324 } 1325 if (pelements != NULL) { 1326 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal); 1327 } 1328 } else { 1329 snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname); 1330 retval = true; 1331 } 1332 return retval; 1333} 1334 1335// check if addr is inside libjvm.so 1336bool os::address_is_in_vm(address addr) { 1337 static address libjvm_base_addr; 1338 Dl_info dlinfo; 1339 1340 if (libjvm_base_addr == NULL) { 1341 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1342 libjvm_base_addr = (address)dlinfo.dli_fbase; 1343 } 1344 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1345 } 1346 1347 if (dladdr((void *)addr, &dlinfo) != 0) { 1348 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1349 } 1350 1351 return false; 1352} 1353 1354 1355#define MACH_MAXSYMLEN 256 1356 1357bool os::dll_address_to_function_name(address addr, char *buf, 1358 int buflen, int *offset) { 1359 // buf is not optional, but offset is optional 1360 assert(buf != NULL, "sanity check"); 1361 1362 Dl_info dlinfo; 1363 char localbuf[MACH_MAXSYMLEN]; 1364 1365 if (dladdr((void*)addr, &dlinfo) != 0) { 1366 // see if we have a matching symbol 1367 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1368 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { 1369 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1370 } 1371 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1372 return true; 1373 } 1374 // no matching symbol so try for just file info 1375 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1376 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1377 buf, buflen, offset, dlinfo.dli_fname)) { 1378 return true; 1379 } 1380 } 1381 1382 // Handle non-dynamic manually: 1383 if (dlinfo.dli_fbase != NULL && 1384 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, 1385 dlinfo.dli_fbase)) { 1386 if (!Decoder::demangle(localbuf, buf, buflen)) { 1387 jio_snprintf(buf, buflen, "%s", localbuf); 1388 } 1389 return true; 1390 } 1391 } 1392 buf[0] = '\0'; 1393 if (offset != NULL) *offset = -1; 1394 return false; 1395} 1396 1397// ported from solaris version 1398bool os::dll_address_to_library_name(address addr, char* buf, 1399 int buflen, int* offset) { 1400 // buf is not optional, but offset is optional 1401 assert(buf != NULL, "sanity check"); 1402 1403 Dl_info dlinfo; 1404 1405 if (dladdr((void*)addr, &dlinfo) != 0) { 1406 if (dlinfo.dli_fname != NULL) { 1407 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1408 } 1409 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1410 *offset = addr - (address)dlinfo.dli_fbase; 1411 } 1412 return true; 1413 } 1414 1415 buf[0] = '\0'; 1416 if (offset) *offset = -1; 1417 return false; 1418} 1419 1420// Loads .dll/.so and 1421// in case of error it checks if .dll/.so was built for the 1422// same architecture as Hotspot is running on 1423 1424#ifdef __APPLE__ 1425void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1426 void * result= ::dlopen(filename, RTLD_LAZY); 1427 if (result != NULL) { 1428 // Successful loading 1429 return result; 1430 } 1431 1432 // Read system error message into ebuf 1433 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1434 ebuf[ebuflen-1]='\0'; 1435 1436 return NULL; 1437} 1438#else 1439void * os::dll_load(const char *filename, char *ebuf, int ebuflen) 1440{ 1441 void * result= ::dlopen(filename, RTLD_LAZY); 1442 if (result != NULL) { 1443 // Successful loading 1444 return result; 1445 } 1446 1447 Elf32_Ehdr elf_head; 1448 1449 // Read system error message into ebuf 1450 // It may or may not be overwritten below 1451 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1452 ebuf[ebuflen-1]='\0'; 1453 int diag_msg_max_length=ebuflen-strlen(ebuf); 1454 char* diag_msg_buf=ebuf+strlen(ebuf); 1455 1456 if (diag_msg_max_length==0) { 1457 // No more space in ebuf for additional diagnostics message 1458 return NULL; 1459 } 1460 1461 1462 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1463 1464 if (file_descriptor < 0) { 1465 // Can't open library, report dlerror() message 1466 return NULL; 1467 } 1468 1469 bool failed_to_read_elf_head= 1470 (sizeof(elf_head)!= 1471 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1472 1473 ::close(file_descriptor); 1474 if (failed_to_read_elf_head) { 1475 // file i/o error - report dlerror() msg 1476 return NULL; 1477 } 1478 1479 typedef struct { 1480 Elf32_Half code; // Actual value as defined in elf.h 1481 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1482 char elf_class; // 32 or 64 bit 1483 char endianess; // MSB or LSB 1484 char* name; // String representation 1485 } arch_t; 1486 1487 #ifndef EM_486 1488 #define EM_486 6 /* Intel 80486 */ 1489 #endif 1490 1491 #ifndef EM_MIPS_RS3_LE 1492 #define EM_MIPS_RS3_LE 10 /* MIPS */ 1493 #endif 1494 1495 #ifndef EM_PPC64 1496 #define EM_PPC64 21 /* PowerPC64 */ 1497 #endif 1498 1499 #ifndef EM_S390 1500 #define EM_S390 22 /* IBM System/390 */ 1501 #endif 1502 1503 #ifndef EM_IA_64 1504 #define EM_IA_64 50 /* HP/Intel IA-64 */ 1505 #endif 1506 1507 #ifndef EM_X86_64 1508 #define EM_X86_64 62 /* AMD x86-64 */ 1509 #endif 1510 1511 static const arch_t arch_array[]={ 1512 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1513 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1514 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1515 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1516 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1517 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1518 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1519 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1520 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1521 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, 1522 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, 1523 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, 1524 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, 1525 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, 1526 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, 1527 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} 1528 }; 1529 1530 #if (defined IA32) 1531 static Elf32_Half running_arch_code=EM_386; 1532 #elif (defined AMD64) 1533 static Elf32_Half running_arch_code=EM_X86_64; 1534 #elif (defined IA64) 1535 static Elf32_Half running_arch_code=EM_IA_64; 1536 #elif (defined __sparc) && (defined _LP64) 1537 static Elf32_Half running_arch_code=EM_SPARCV9; 1538 #elif (defined __sparc) && (!defined _LP64) 1539 static Elf32_Half running_arch_code=EM_SPARC; 1540 #elif (defined __powerpc64__) 1541 static Elf32_Half running_arch_code=EM_PPC64; 1542 #elif (defined __powerpc__) 1543 static Elf32_Half running_arch_code=EM_PPC; 1544 #elif (defined ARM) 1545 static Elf32_Half running_arch_code=EM_ARM; 1546 #elif (defined S390) 1547 static Elf32_Half running_arch_code=EM_S390; 1548 #elif (defined ALPHA) 1549 static Elf32_Half running_arch_code=EM_ALPHA; 1550 #elif (defined MIPSEL) 1551 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; 1552 #elif (defined PARISC) 1553 static Elf32_Half running_arch_code=EM_PARISC; 1554 #elif (defined MIPS) 1555 static Elf32_Half running_arch_code=EM_MIPS; 1556 #elif (defined M68K) 1557 static Elf32_Half running_arch_code=EM_68K; 1558 #else 1559 #error Method os::dll_load requires that one of following is defined:\ 1560 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K 1561 #endif 1562 1563 // Identify compatability class for VM's architecture and library's architecture 1564 // Obtain string descriptions for architectures 1565 1566 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1567 int running_arch_index=-1; 1568 1569 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1570 if (running_arch_code == arch_array[i].code) { 1571 running_arch_index = i; 1572 } 1573 if (lib_arch.code == arch_array[i].code) { 1574 lib_arch.compat_class = arch_array[i].compat_class; 1575 lib_arch.name = arch_array[i].name; 1576 } 1577 } 1578 1579 assert(running_arch_index != -1, 1580 "Didn't find running architecture code (running_arch_code) in arch_array"); 1581 if (running_arch_index == -1) { 1582 // Even though running architecture detection failed 1583 // we may still continue with reporting dlerror() message 1584 return NULL; 1585 } 1586 1587 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1588 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1589 return NULL; 1590 } 1591 1592#ifndef S390 1593 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1594 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1595 return NULL; 1596 } 1597#endif // !S390 1598 1599 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1600 if (lib_arch.name!=NULL) { 1601 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1602 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 1603 lib_arch.name, arch_array[running_arch_index].name); 1604 } else { 1605 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1606 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 1607 lib_arch.code, 1608 arch_array[running_arch_index].name); 1609 } 1610 } 1611 1612 return NULL; 1613} 1614#endif /* !__APPLE__ */ 1615 1616void* os::get_default_process_handle() { 1617#ifdef __APPLE__ 1618 // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY 1619 // to avoid finding unexpected symbols on second (or later) 1620 // loads of a library. 1621 return (void*)::dlopen(NULL, RTLD_FIRST); 1622#else 1623 return (void*)::dlopen(NULL, RTLD_LAZY); 1624#endif 1625} 1626 1627// XXX: Do we need a lock around this as per Linux? 1628void* os::dll_lookup(void* handle, const char* name) { 1629 return dlsym(handle, name); 1630} 1631 1632 1633static bool _print_ascii_file(const char* filename, outputStream* st) { 1634 int fd = ::open(filename, O_RDONLY); 1635 if (fd == -1) { 1636 return false; 1637 } 1638 1639 char buf[32]; 1640 int bytes; 1641 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 1642 st->print_raw(buf, bytes); 1643 } 1644 1645 ::close(fd); 1646 1647 return true; 1648} 1649 1650void os::print_dll_info(outputStream *st) { 1651 st->print_cr("Dynamic libraries:"); 1652#ifdef RTLD_DI_LINKMAP 1653 Dl_info dli; 1654 void *handle; 1655 Link_map *map; 1656 Link_map *p; 1657 1658 if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 || 1659 dli.dli_fname == NULL) { 1660 st->print_cr("Error: Cannot print dynamic libraries."); 1661 return; 1662 } 1663 handle = dlopen(dli.dli_fname, RTLD_LAZY); 1664 if (handle == NULL) { 1665 st->print_cr("Error: Cannot print dynamic libraries."); 1666 return; 1667 } 1668 dlinfo(handle, RTLD_DI_LINKMAP, &map); 1669 if (map == NULL) { 1670 st->print_cr("Error: Cannot print dynamic libraries."); 1671 return; 1672 } 1673 1674 while (map->l_prev != NULL) 1675 map = map->l_prev; 1676 1677 while (map != NULL) { 1678 st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); 1679 map = map->l_next; 1680 } 1681 1682 dlclose(handle); 1683#elif defined(__APPLE__) 1684 uint32_t count; 1685 uint32_t i; 1686 1687 count = _dyld_image_count(); 1688 for (i = 1; i < count; i++) { 1689 const char *name = _dyld_get_image_name(i); 1690 intptr_t slide = _dyld_get_image_vmaddr_slide(i); 1691 st->print_cr(PTR_FORMAT " \t%s", slide, name); 1692 } 1693#else 1694 st->print_cr("Error: Cannot print dynamic libraries."); 1695#endif 1696} 1697 1698void os::print_os_info_brief(outputStream* st) { 1699 st->print("Bsd"); 1700 1701 os::Posix::print_uname_info(st); 1702} 1703 1704void os::print_os_info(outputStream* st) { 1705 st->print("OS:"); 1706 st->print("Bsd"); 1707 1708 os::Posix::print_uname_info(st); 1709 1710 os::Posix::print_rlimit_info(st); 1711 1712 os::Posix::print_load_average(st); 1713} 1714 1715void os::pd_print_cpu_info(outputStream* st) { 1716 // Nothing to do for now. 1717} 1718 1719void os::print_memory_info(outputStream* st) { 1720 1721 st->print("Memory:"); 1722 st->print(" %dk page", os::vm_page_size()>>10); 1723 1724 st->print(", physical " UINT64_FORMAT "k", 1725 os::physical_memory() >> 10); 1726 st->print("(" UINT64_FORMAT "k free)", 1727 os::available_memory() >> 10); 1728 st->cr(); 1729 1730 // meminfo 1731 st->print("\n/proc/meminfo:\n"); 1732 _print_ascii_file("/proc/meminfo", st); 1733 st->cr(); 1734} 1735 1736void os::print_siginfo(outputStream* st, void* siginfo) { 1737 const siginfo_t* si = (const siginfo_t*)siginfo; 1738 1739 os::Posix::print_siginfo_brief(st, si); 1740 1741 if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 1742 UseSharedSpaces) { 1743 FileMapInfo* mapinfo = FileMapInfo::current_info(); 1744 if (mapinfo->is_in_shared_space(si->si_addr)) { 1745 st->print("\n\nError accessing class data sharing archive." \ 1746 " Mapped file inaccessible during execution, " \ 1747 " possible disk/network problem."); 1748 } 1749 } 1750 st->cr(); 1751} 1752 1753 1754static void print_signal_handler(outputStream* st, int sig, 1755 char* buf, size_t buflen); 1756 1757void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 1758 st->print_cr("Signal Handlers:"); 1759 print_signal_handler(st, SIGSEGV, buf, buflen); 1760 print_signal_handler(st, SIGBUS , buf, buflen); 1761 print_signal_handler(st, SIGFPE , buf, buflen); 1762 print_signal_handler(st, SIGPIPE, buf, buflen); 1763 print_signal_handler(st, SIGXFSZ, buf, buflen); 1764 print_signal_handler(st, SIGILL , buf, buflen); 1765 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 1766 print_signal_handler(st, SR_signum, buf, buflen); 1767 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 1768 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 1769 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 1770 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 1771} 1772 1773static char saved_jvm_path[MAXPATHLEN] = {0}; 1774 1775// Find the full path to the current module, libjvm 1776void os::jvm_path(char *buf, jint buflen) { 1777 // Error checking. 1778 if (buflen < MAXPATHLEN) { 1779 assert(false, "must use a large-enough buffer"); 1780 buf[0] = '\0'; 1781 return; 1782 } 1783 // Lazy resolve the path to current module. 1784 if (saved_jvm_path[0] != 0) { 1785 strcpy(buf, saved_jvm_path); 1786 return; 1787 } 1788 1789 char dli_fname[MAXPATHLEN]; 1790 bool ret = dll_address_to_library_name( 1791 CAST_FROM_FN_PTR(address, os::jvm_path), 1792 dli_fname, sizeof(dli_fname), NULL); 1793 assert(ret, "cannot locate libjvm"); 1794 char *rp = NULL; 1795 if (ret && dli_fname[0] != '\0') { 1796 rp = realpath(dli_fname, buf); 1797 } 1798 if (rp == NULL) 1799 return; 1800 1801 if (Arguments::sun_java_launcher_is_altjvm()) { 1802 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 1803 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so" 1804 // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/" 1805 // appears at the right place in the string, then assume we are 1806 // installed in a JDK and we're done. Otherwise, check for a 1807 // JAVA_HOME environment variable and construct a path to the JVM 1808 // being overridden. 1809 1810 const char *p = buf + strlen(buf) - 1; 1811 for (int count = 0; p > buf && count < 5; ++count) { 1812 for (--p; p > buf && *p != '/'; --p) 1813 /* empty */ ; 1814 } 1815 1816 if (strncmp(p, "/jre/lib/", 9) != 0) { 1817 // Look for JAVA_HOME in the environment. 1818 char* java_home_var = ::getenv("JAVA_HOME"); 1819 if (java_home_var != NULL && java_home_var[0] != 0) { 1820 char* jrelib_p; 1821 int len; 1822 1823 // Check the current module name "libjvm" 1824 p = strrchr(buf, '/'); 1825 assert(strstr(p, "/libjvm") == p, "invalid library name"); 1826 1827 rp = realpath(java_home_var, buf); 1828 if (rp == NULL) 1829 return; 1830 1831 // determine if this is a legacy image or modules image 1832 // modules image doesn't have "jre" subdirectory 1833 len = strlen(buf); 1834 jrelib_p = buf + len; 1835 1836 // Add the appropriate library subdir 1837 snprintf(jrelib_p, buflen-len, "/jre/lib"); 1838 if (0 != access(buf, F_OK)) { 1839 snprintf(jrelib_p, buflen-len, "/lib"); 1840 } 1841 1842 // Add the appropriate client or server subdir 1843 len = strlen(buf); 1844 jrelib_p = buf + len; 1845 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT); 1846 if (0 != access(buf, F_OK)) { 1847 snprintf(jrelib_p, buflen-len, "%s", ""); 1848 } 1849 1850 // If the path exists within JAVA_HOME, add the JVM library name 1851 // to complete the path to JVM being overridden. Otherwise fallback 1852 // to the path to the current library. 1853 if (0 == access(buf, F_OK)) { 1854 // Use current module name "libjvm" 1855 len = strlen(buf); 1856 snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX); 1857 } else { 1858 // Fall back to path of current library 1859 rp = realpath(dli_fname, buf); 1860 if (rp == NULL) 1861 return; 1862 } 1863 } 1864 } 1865 } 1866 1867 strcpy(saved_jvm_path, buf); 1868} 1869 1870void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 1871 // no prefix required, not even "_" 1872} 1873 1874void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 1875 // no suffix required 1876} 1877 1878//////////////////////////////////////////////////////////////////////////////// 1879// sun.misc.Signal support 1880 1881static volatile jint sigint_count = 0; 1882 1883static void 1884UserHandler(int sig, void *siginfo, void *context) { 1885 // 4511530 - sem_post is serialized and handled by the manager thread. When 1886 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 1887 // don't want to flood the manager thread with sem_post requests. 1888 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) 1889 return; 1890 1891 // Ctrl-C is pressed during error reporting, likely because the error 1892 // handler fails to abort. Let VM die immediately. 1893 if (sig == SIGINT && is_error_reported()) { 1894 os::die(); 1895 } 1896 1897 os::signal_notify(sig); 1898} 1899 1900void* os::user_handler() { 1901 return CAST_FROM_FN_PTR(void*, UserHandler); 1902} 1903 1904extern "C" { 1905 typedef void (*sa_handler_t)(int); 1906 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 1907} 1908 1909void* os::signal(int signal_number, void* handler) { 1910 struct sigaction sigAct, oldSigAct; 1911 1912 sigfillset(&(sigAct.sa_mask)); 1913 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 1914 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 1915 1916 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 1917 // -1 means registration failed 1918 return (void *)-1; 1919 } 1920 1921 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 1922} 1923 1924void os::signal_raise(int signal_number) { 1925 ::raise(signal_number); 1926} 1927 1928/* 1929 * The following code is moved from os.cpp for making this 1930 * code platform specific, which it is by its very nature. 1931 */ 1932 1933// Will be modified when max signal is changed to be dynamic 1934int os::sigexitnum_pd() { 1935 return NSIG; 1936} 1937 1938// a counter for each possible signal value 1939static volatile jint pending_signals[NSIG+1] = { 0 }; 1940 1941// Bsd(POSIX) specific hand shaking semaphore. 1942#ifdef __APPLE__ 1943typedef semaphore_t os_semaphore_t; 1944#define SEM_INIT(sem, value) semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value) 1945#define SEM_WAIT(sem) semaphore_wait(sem) 1946#define SEM_POST(sem) semaphore_signal(sem) 1947#define SEM_DESTROY(sem) semaphore_destroy(mach_task_self(), sem) 1948#else 1949typedef sem_t os_semaphore_t; 1950#define SEM_INIT(sem, value) sem_init(&sem, 0, value) 1951#define SEM_WAIT(sem) sem_wait(&sem) 1952#define SEM_POST(sem) sem_post(&sem) 1953#define SEM_DESTROY(sem) sem_destroy(&sem) 1954#endif 1955 1956class Semaphore : public StackObj { 1957 public: 1958 Semaphore(); 1959 ~Semaphore(); 1960 void signal(); 1961 void wait(); 1962 bool trywait(); 1963 bool timedwait(unsigned int sec, int nsec); 1964 private: 1965 jlong currenttime() const; 1966 os_semaphore_t _semaphore; 1967}; 1968 1969Semaphore::Semaphore() : _semaphore(0) { 1970 SEM_INIT(_semaphore, 0); 1971} 1972 1973Semaphore::~Semaphore() { 1974 SEM_DESTROY(_semaphore); 1975} 1976 1977void Semaphore::signal() { 1978 SEM_POST(_semaphore); 1979} 1980 1981void Semaphore::wait() { 1982 SEM_WAIT(_semaphore); 1983} 1984 1985jlong Semaphore::currenttime() const { 1986 struct timeval tv; 1987 gettimeofday(&tv, NULL); 1988 return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000); 1989} 1990 1991#ifdef __APPLE__ 1992bool Semaphore::trywait() { 1993 return timedwait(0, 0); 1994} 1995 1996bool Semaphore::timedwait(unsigned int sec, int nsec) { 1997 kern_return_t kr = KERN_ABORTED; 1998 mach_timespec_t waitspec; 1999 waitspec.tv_sec = sec; 2000 waitspec.tv_nsec = nsec; 2001 2002 jlong starttime = currenttime(); 2003 2004 kr = semaphore_timedwait(_semaphore, waitspec); 2005 while (kr == KERN_ABORTED) { 2006 jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec; 2007 2008 jlong current = currenttime(); 2009 jlong passedtime = current - starttime; 2010 2011 if (passedtime >= totalwait) { 2012 waitspec.tv_sec = 0; 2013 waitspec.tv_nsec = 0; 2014 } else { 2015 jlong waittime = totalwait - (current - starttime); 2016 waitspec.tv_sec = waittime / NANOSECS_PER_SEC; 2017 waitspec.tv_nsec = waittime % NANOSECS_PER_SEC; 2018 } 2019 2020 kr = semaphore_timedwait(_semaphore, waitspec); 2021 } 2022 2023 return kr == KERN_SUCCESS; 2024} 2025 2026#else 2027 2028bool Semaphore::trywait() { 2029 return sem_trywait(&_semaphore) == 0; 2030} 2031 2032bool Semaphore::timedwait(unsigned int sec, int nsec) { 2033 struct timespec ts; 2034 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec); 2035 2036 while (1) { 2037 int result = sem_timedwait(&_semaphore, &ts); 2038 if (result == 0) { 2039 return true; 2040 } else if (errno == EINTR) { 2041 continue; 2042 } else if (errno == ETIMEDOUT) { 2043 return false; 2044 } else { 2045 return false; 2046 } 2047 } 2048} 2049 2050#endif // __APPLE__ 2051 2052static os_semaphore_t sig_sem; 2053static Semaphore sr_semaphore; 2054 2055void os::signal_init_pd() { 2056 // Initialize signal structures 2057 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2058 2059 // Initialize signal semaphore 2060 ::SEM_INIT(sig_sem, 0); 2061} 2062 2063void os::signal_notify(int sig) { 2064 Atomic::inc(&pending_signals[sig]); 2065 ::SEM_POST(sig_sem); 2066} 2067 2068static int check_pending_signals(bool wait) { 2069 Atomic::store(0, &sigint_count); 2070 for (;;) { 2071 for (int i = 0; i < NSIG + 1; i++) { 2072 jint n = pending_signals[i]; 2073 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2074 return i; 2075 } 2076 } 2077 if (!wait) { 2078 return -1; 2079 } 2080 JavaThread *thread = JavaThread::current(); 2081 ThreadBlockInVM tbivm(thread); 2082 2083 bool threadIsSuspended; 2084 do { 2085 thread->set_suspend_equivalent(); 2086 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2087 ::SEM_WAIT(sig_sem); 2088 2089 // were we externally suspended while we were waiting? 2090 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2091 if (threadIsSuspended) { 2092 // 2093 // The semaphore has been incremented, but while we were waiting 2094 // another thread suspended us. We don't want to continue running 2095 // while suspended because that would surprise the thread that 2096 // suspended us. 2097 // 2098 ::SEM_POST(sig_sem); 2099 2100 thread->java_suspend_self(); 2101 } 2102 } while (threadIsSuspended); 2103 } 2104} 2105 2106int os::signal_lookup() { 2107 return check_pending_signals(false); 2108} 2109 2110int os::signal_wait() { 2111 return check_pending_signals(true); 2112} 2113 2114//////////////////////////////////////////////////////////////////////////////// 2115// Virtual Memory 2116 2117int os::vm_page_size() { 2118 // Seems redundant as all get out 2119 assert(os::Bsd::page_size() != -1, "must call os::init"); 2120 return os::Bsd::page_size(); 2121} 2122 2123// Solaris allocates memory by pages. 2124int os::vm_allocation_granularity() { 2125 assert(os::Bsd::page_size() != -1, "must call os::init"); 2126 return os::Bsd::page_size(); 2127} 2128 2129// Rationale behind this function: 2130// current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2131// mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2132// samples for JITted code. Here we create private executable mapping over the code cache 2133// and then we can use standard (well, almost, as mapping can change) way to provide 2134// info for the reporting script by storing timestamp and location of symbol 2135void bsd_wrap_code(char* base, size_t size) { 2136 static volatile jint cnt = 0; 2137 2138 if (!UseOprofile) { 2139 return; 2140 } 2141 2142 char buf[PATH_MAX + 1]; 2143 int num = Atomic::add(1, &cnt); 2144 2145 snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d", 2146 os::get_temp_directory(), os::current_process_id(), num); 2147 unlink(buf); 2148 2149 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU); 2150 2151 if (fd != -1) { 2152 off_t rv = ::lseek(fd, size-2, SEEK_SET); 2153 if (rv != (off_t)-1) { 2154 if (::write(fd, "", 1) == 1) { 2155 mmap(base, size, 2156 PROT_READ|PROT_WRITE|PROT_EXEC, 2157 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2158 } 2159 } 2160 ::close(fd); 2161 unlink(buf); 2162 } 2163} 2164 2165static void warn_fail_commit_memory(char* addr, size_t size, bool exec, 2166 int err) { 2167 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2168 ", %d) failed; error='%s' (errno=%d)", addr, size, exec, 2169 strerror(err), err); 2170} 2171 2172// NOTE: Bsd kernel does not really reserve the pages for us. 2173// All it does is to check if there are enough free pages 2174// left at the time of mmap(). This could be a potential 2175// problem. 2176bool os::pd_commit_memory(char* addr, size_t size, bool exec) { 2177 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2178#ifdef __OpenBSD__ 2179 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 2180 if (::mprotect(addr, size, prot) == 0) { 2181 return true; 2182 } 2183#else 2184 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, 2185 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2186 if (res != (uintptr_t) MAP_FAILED) { 2187 return true; 2188 } 2189#endif 2190 2191 // Warn about any commit errors we see in non-product builds just 2192 // in case mmap() doesn't work as described on the man page. 2193 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);) 2194 2195 return false; 2196} 2197 2198bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 2199 bool exec) { 2200 // alignment_hint is ignored on this OS 2201 return pd_commit_memory(addr, size, exec); 2202} 2203 2204void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec, 2205 const char* mesg) { 2206 assert(mesg != NULL, "mesg must be specified"); 2207 if (!pd_commit_memory(addr, size, exec)) { 2208 // add extra info in product mode for vm_exit_out_of_memory(): 2209 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);) 2210 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg); 2211 } 2212} 2213 2214void os::pd_commit_memory_or_exit(char* addr, size_t size, 2215 size_t alignment_hint, bool exec, 2216 const char* mesg) { 2217 // alignment_hint is ignored on this OS 2218 pd_commit_memory_or_exit(addr, size, exec, mesg); 2219} 2220 2221void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2222} 2223 2224void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) { 2225 ::madvise(addr, bytes, MADV_DONTNEED); 2226} 2227 2228void os::numa_make_global(char *addr, size_t bytes) { 2229} 2230 2231void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2232} 2233 2234bool os::numa_topology_changed() { return false; } 2235 2236size_t os::numa_get_groups_num() { 2237 return 1; 2238} 2239 2240int os::numa_get_group_id() { 2241 return 0; 2242} 2243 2244size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2245 if (size > 0) { 2246 ids[0] = 0; 2247 return 1; 2248 } 2249 return 0; 2250} 2251 2252bool os::get_page_info(char *start, page_info* info) { 2253 return false; 2254} 2255 2256char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 2257 return end; 2258} 2259 2260 2261bool os::pd_uncommit_memory(char* addr, size_t size) { 2262#ifdef __OpenBSD__ 2263 // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD 2264 return ::mprotect(addr, size, PROT_NONE) == 0; 2265#else 2266 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, 2267 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); 2268 return res != (uintptr_t) MAP_FAILED; 2269#endif 2270} 2271 2272bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 2273 return os::commit_memory(addr, size, !ExecMem); 2274} 2275 2276// If this is a growable mapping, remove the guard pages entirely by 2277// munmap()ping them. If not, just call uncommit_memory(). 2278bool os::remove_stack_guard_pages(char* addr, size_t size) { 2279 return os::uncommit_memory(addr, size); 2280} 2281 2282static address _highest_vm_reserved_address = NULL; 2283 2284// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 2285// at 'requested_addr'. If there are existing memory mappings at the same 2286// location, however, they will be overwritten. If 'fixed' is false, 2287// 'requested_addr' is only treated as a hint, the return value may or 2288// may not start from the requested address. Unlike Bsd mmap(), this 2289// function returns NULL to indicate failure. 2290static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 2291 char * addr; 2292 int flags; 2293 2294 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 2295 if (fixed) { 2296 assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address"); 2297 flags |= MAP_FIXED; 2298 } 2299 2300 // Map reserved/uncommitted pages PROT_NONE so we fail early if we 2301 // touch an uncommitted page. Otherwise, the read/write might 2302 // succeed if we have enough swap space to back the physical page. 2303 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, 2304 flags, -1, 0); 2305 2306 if (addr != MAP_FAILED) { 2307 // anon_mmap() should only get called during VM initialization, 2308 // don't need lock (actually we can skip locking even it can be called 2309 // from multiple threads, because _highest_vm_reserved_address is just a 2310 // hint about the upper limit of non-stack memory regions.) 2311 if ((address)addr + bytes > _highest_vm_reserved_address) { 2312 _highest_vm_reserved_address = (address)addr + bytes; 2313 } 2314 } 2315 2316 return addr == MAP_FAILED ? NULL : addr; 2317} 2318 2319// Don't update _highest_vm_reserved_address, because there might be memory 2320// regions above addr + size. If so, releasing a memory region only creates 2321// a hole in the address space, it doesn't help prevent heap-stack collision. 2322// 2323static int anon_munmap(char * addr, size_t size) { 2324 return ::munmap(addr, size) == 0; 2325} 2326 2327char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 2328 size_t alignment_hint) { 2329 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 2330} 2331 2332bool os::pd_release_memory(char* addr, size_t size) { 2333 return anon_munmap(addr, size); 2334} 2335 2336static bool bsd_mprotect(char* addr, size_t size, int prot) { 2337 // Bsd wants the mprotect address argument to be page aligned. 2338 char* bottom = (char*)align_size_down((intptr_t)addr, os::Bsd::page_size()); 2339 2340 // According to SUSv3, mprotect() should only be used with mappings 2341 // established by mmap(), and mmap() always maps whole pages. Unaligned 2342 // 'addr' likely indicates problem in the VM (e.g. trying to change 2343 // protection of malloc'ed or statically allocated memory). Check the 2344 // caller if you hit this assert. 2345 assert(addr == bottom, "sanity check"); 2346 2347 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size()); 2348 return ::mprotect(bottom, size, prot) == 0; 2349} 2350 2351// Set protections specified 2352bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2353 bool is_committed) { 2354 unsigned int p = 0; 2355 switch (prot) { 2356 case MEM_PROT_NONE: p = PROT_NONE; break; 2357 case MEM_PROT_READ: p = PROT_READ; break; 2358 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 2359 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 2360 default: 2361 ShouldNotReachHere(); 2362 } 2363 // is_committed is unused. 2364 return bsd_mprotect(addr, bytes, p); 2365} 2366 2367bool os::guard_memory(char* addr, size_t size) { 2368 return bsd_mprotect(addr, size, PROT_NONE); 2369} 2370 2371bool os::unguard_memory(char* addr, size_t size) { 2372 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE); 2373} 2374 2375bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) { 2376 return false; 2377} 2378 2379// Large page support 2380 2381static size_t _large_page_size = 0; 2382 2383void os::large_page_init() { 2384} 2385 2386 2387char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) { 2388 fatal("This code is not used or maintained."); 2389 2390 // "exec" is passed in but not used. Creating the shared image for 2391 // the code cache doesn't have an SHM_X executable permission to check. 2392 assert(UseLargePages && UseSHM, "only for SHM large pages"); 2393 2394 key_t key = IPC_PRIVATE; 2395 char *addr; 2396 2397 bool warn_on_failure = UseLargePages && 2398 (!FLAG_IS_DEFAULT(UseLargePages) || 2399 !FLAG_IS_DEFAULT(LargePageSizeInBytes) 2400 ); 2401 2402 // Create a large shared memory region to attach to based on size. 2403 // Currently, size is the total size of the heap 2404 int shmid = shmget(key, bytes, IPC_CREAT|SHM_R|SHM_W); 2405 if (shmid == -1) { 2406 // Possible reasons for shmget failure: 2407 // 1. shmmax is too small for Java heap. 2408 // > check shmmax value: cat /proc/sys/kernel/shmmax 2409 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 2410 // 2. not enough large page memory. 2411 // > check available large pages: cat /proc/meminfo 2412 // > increase amount of large pages: 2413 // echo new_value > /proc/sys/vm/nr_hugepages 2414 // Note 1: different Bsd may use different name for this property, 2415 // e.g. on Redhat AS-3 it is "hugetlb_pool". 2416 // Note 2: it's possible there's enough physical memory available but 2417 // they are so fragmented after a long run that they can't 2418 // coalesce into large pages. Try to reserve large pages when 2419 // the system is still "fresh". 2420 if (warn_on_failure) { 2421 warning("Failed to reserve shared memory (errno = %d).", errno); 2422 } 2423 return NULL; 2424 } 2425 2426 // attach to the region 2427 addr = (char*)shmat(shmid, req_addr, 0); 2428 int err = errno; 2429 2430 // Remove shmid. If shmat() is successful, the actual shared memory segment 2431 // will be deleted when it's detached by shmdt() or when the process 2432 // terminates. If shmat() is not successful this will remove the shared 2433 // segment immediately. 2434 shmctl(shmid, IPC_RMID, NULL); 2435 2436 if ((intptr_t)addr == -1) { 2437 if (warn_on_failure) { 2438 warning("Failed to attach shared memory (errno = %d).", err); 2439 } 2440 return NULL; 2441 } 2442 2443 // The memory is committed 2444 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC); 2445 2446 return addr; 2447} 2448 2449bool os::release_memory_special(char* base, size_t bytes) { 2450 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 2451 // detaching the SHM segment will also delete it, see reserve_memory_special() 2452 int rslt = shmdt(base); 2453 if (rslt == 0) { 2454 tkr.record((address)base, bytes); 2455 return true; 2456 } else { 2457 tkr.discard(); 2458 return false; 2459 } 2460 2461} 2462 2463size_t os::large_page_size() { 2464 return _large_page_size; 2465} 2466 2467// HugeTLBFS allows application to commit large page memory on demand; 2468// with SysV SHM the entire memory region must be allocated as shared 2469// memory. 2470bool os::can_commit_large_page_memory() { 2471 return UseHugeTLBFS; 2472} 2473 2474bool os::can_execute_large_page_memory() { 2475 return UseHugeTLBFS; 2476} 2477 2478// Reserve memory at an arbitrary address, only if that area is 2479// available (and not reserved for something else). 2480 2481char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2482 const int max_tries = 10; 2483 char* base[max_tries]; 2484 size_t size[max_tries]; 2485 const size_t gap = 0x000000; 2486 2487 // Assert only that the size is a multiple of the page size, since 2488 // that's all that mmap requires, and since that's all we really know 2489 // about at this low abstraction level. If we need higher alignment, 2490 // we can either pass an alignment to this method or verify alignment 2491 // in one of the methods further up the call chain. See bug 5044738. 2492 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 2493 2494 // Repeatedly allocate blocks until the block is allocated at the 2495 // right spot. Give up after max_tries. Note that reserve_memory() will 2496 // automatically update _highest_vm_reserved_address if the call is 2497 // successful. The variable tracks the highest memory address every reserved 2498 // by JVM. It is used to detect heap-stack collision if running with 2499 // fixed-stack BsdThreads. Because here we may attempt to reserve more 2500 // space than needed, it could confuse the collision detecting code. To 2501 // solve the problem, save current _highest_vm_reserved_address and 2502 // calculate the correct value before return. 2503 address old_highest = _highest_vm_reserved_address; 2504 2505 // Bsd mmap allows caller to pass an address as hint; give it a try first, 2506 // if kernel honors the hint then we can return immediately. 2507 char * addr = anon_mmap(requested_addr, bytes, false); 2508 if (addr == requested_addr) { 2509 return requested_addr; 2510 } 2511 2512 if (addr != NULL) { 2513 // mmap() is successful but it fails to reserve at the requested address 2514 anon_munmap(addr, bytes); 2515 } 2516 2517 int i; 2518 for (i = 0; i < max_tries; ++i) { 2519 base[i] = reserve_memory(bytes); 2520 2521 if (base[i] != NULL) { 2522 // Is this the block we wanted? 2523 if (base[i] == requested_addr) { 2524 size[i] = bytes; 2525 break; 2526 } 2527 2528 // Does this overlap the block we wanted? Give back the overlapped 2529 // parts and try again. 2530 2531 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 2532 if (top_overlap >= 0 && top_overlap < bytes) { 2533 unmap_memory(base[i], top_overlap); 2534 base[i] += top_overlap; 2535 size[i] = bytes - top_overlap; 2536 } else { 2537 size_t bottom_overlap = base[i] + bytes - requested_addr; 2538 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 2539 unmap_memory(requested_addr, bottom_overlap); 2540 size[i] = bytes - bottom_overlap; 2541 } else { 2542 size[i] = bytes; 2543 } 2544 } 2545 } 2546 } 2547 2548 // Give back the unused reserved pieces. 2549 2550 for (int j = 0; j < i; ++j) { 2551 if (base[j] != NULL) { 2552 unmap_memory(base[j], size[j]); 2553 } 2554 } 2555 2556 if (i < max_tries) { 2557 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 2558 return requested_addr; 2559 } else { 2560 _highest_vm_reserved_address = old_highest; 2561 return NULL; 2562 } 2563} 2564 2565size_t os::read(int fd, void *buf, unsigned int nBytes) { 2566 RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes)); 2567} 2568 2569void os::naked_short_sleep(jlong ms) { 2570 struct timespec req; 2571 2572 assert(ms < 1000, "Un-interruptable sleep, short time use only"); 2573 req.tv_sec = 0; 2574 if (ms > 0) { 2575 req.tv_nsec = (ms % 1000) * 1000000; 2576 } 2577 else { 2578 req.tv_nsec = 1; 2579 } 2580 2581 nanosleep(&req, NULL); 2582 2583 return; 2584} 2585 2586// Sleep forever; naked call to OS-specific sleep; use with CAUTION 2587void os::infinite_sleep() { 2588 while (true) { // sleep forever ... 2589 ::sleep(100); // ... 100 seconds at a time 2590 } 2591} 2592 2593// Used to convert frequent JVM_Yield() to nops 2594bool os::dont_yield() { 2595 return DontYieldALot; 2596} 2597 2598void os::yield() { 2599 sched_yield(); 2600} 2601 2602os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; } 2603 2604//////////////////////////////////////////////////////////////////////////////// 2605// thread priority support 2606 2607// Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER 2608// only supports dynamic priority, static priority must be zero. For real-time 2609// applications, Bsd supports SCHED_RR which allows static priority (1-99). 2610// However, for large multi-threaded applications, SCHED_RR is not only slower 2611// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 2612// of 5 runs - Sep 2005). 2613// 2614// The following code actually changes the niceness of kernel-thread/LWP. It 2615// has an assumption that setpriority() only modifies one kernel-thread/LWP, 2616// not the entire user process, and user level threads are 1:1 mapped to kernel 2617// threads. It has always been the case, but could change in the future. For 2618// this reason, the code should not be used as default (ThreadPriorityPolicy=0). 2619// It is only used when ThreadPriorityPolicy=1 and requires root privilege. 2620 2621#if !defined(__APPLE__) 2622int os::java_to_os_priority[CriticalPriority + 1] = { 2623 19, // 0 Entry should never be used 2624 2625 0, // 1 MinPriority 2626 3, // 2 2627 6, // 3 2628 2629 10, // 4 2630 15, // 5 NormPriority 2631 18, // 6 2632 2633 21, // 7 2634 25, // 8 2635 28, // 9 NearMaxPriority 2636 2637 31, // 10 MaxPriority 2638 2639 31 // 11 CriticalPriority 2640}; 2641#else 2642/* Using Mach high-level priority assignments */ 2643int os::java_to_os_priority[CriticalPriority + 1] = { 2644 0, // 0 Entry should never be used (MINPRI_USER) 2645 2646 27, // 1 MinPriority 2647 28, // 2 2648 29, // 3 2649 2650 30, // 4 2651 31, // 5 NormPriority (BASEPRI_DEFAULT) 2652 32, // 6 2653 2654 33, // 7 2655 34, // 8 2656 35, // 9 NearMaxPriority 2657 2658 36, // 10 MaxPriority 2659 2660 36 // 11 CriticalPriority 2661}; 2662#endif 2663 2664static int prio_init() { 2665 if (ThreadPriorityPolicy == 1) { 2666 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 2667 // if effective uid is not root. Perhaps, a more elegant way of doing 2668 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 2669 if (geteuid() != 0) { 2670 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 2671 warning("-XX:ThreadPriorityPolicy requires root privilege on Bsd"); 2672 } 2673 ThreadPriorityPolicy = 0; 2674 } 2675 } 2676 if (UseCriticalJavaThreadPriority) { 2677 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; 2678 } 2679 return 0; 2680} 2681 2682OSReturn os::set_native_priority(Thread* thread, int newpri) { 2683 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; 2684 2685#ifdef __OpenBSD__ 2686 // OpenBSD pthread_setprio starves low priority threads 2687 return OS_OK; 2688#elif defined(__FreeBSD__) 2689 int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri); 2690#elif defined(__APPLE__) || defined(__NetBSD__) 2691 struct sched_param sp; 2692 int policy; 2693 pthread_t self = pthread_self(); 2694 2695 if (pthread_getschedparam(self, &policy, &sp) != 0) 2696 return OS_ERR; 2697 2698 sp.sched_priority = newpri; 2699 if (pthread_setschedparam(self, policy, &sp) != 0) 2700 return OS_ERR; 2701 2702 return OS_OK; 2703#else 2704 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 2705 return (ret == 0) ? OS_OK : OS_ERR; 2706#endif 2707} 2708 2709OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { 2710 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { 2711 *priority_ptr = java_to_os_priority[NormPriority]; 2712 return OS_OK; 2713 } 2714 2715 errno = 0; 2716#if defined(__OpenBSD__) || defined(__FreeBSD__) 2717 *priority_ptr = pthread_getprio(thread->osthread()->pthread_id()); 2718#elif defined(__APPLE__) || defined(__NetBSD__) 2719 int policy; 2720 struct sched_param sp; 2721 2722 pthread_getschedparam(pthread_self(), &policy, &sp); 2723 *priority_ptr = sp.sched_priority; 2724#else 2725 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 2726#endif 2727 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 2728} 2729 2730// Hint to the underlying OS that a task switch would not be good. 2731// Void return because it's a hint and can fail. 2732void os::hint_no_preempt() {} 2733 2734//////////////////////////////////////////////////////////////////////////////// 2735// suspend/resume support 2736 2737// the low-level signal-based suspend/resume support is a remnant from the 2738// old VM-suspension that used to be for java-suspension, safepoints etc, 2739// within hotspot. Now there is a single use-case for this: 2740// - calling get_thread_pc() on the VMThread by the flat-profiler task 2741// that runs in the watcher thread. 2742// The remaining code is greatly simplified from the more general suspension 2743// code that used to be used. 2744// 2745// The protocol is quite simple: 2746// - suspend: 2747// - sends a signal to the target thread 2748// - polls the suspend state of the osthread using a yield loop 2749// - target thread signal handler (SR_handler) sets suspend state 2750// and blocks in sigsuspend until continued 2751// - resume: 2752// - sets target osthread state to continue 2753// - sends signal to end the sigsuspend loop in the SR_handler 2754// 2755// Note that the SR_lock plays no role in this suspend/resume protocol. 2756// 2757 2758static void resume_clear_context(OSThread *osthread) { 2759 osthread->set_ucontext(NULL); 2760 osthread->set_siginfo(NULL); 2761} 2762 2763static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { 2764 osthread->set_ucontext(context); 2765 osthread->set_siginfo(siginfo); 2766} 2767 2768// 2769// Handler function invoked when a thread's execution is suspended or 2770// resumed. We have to be careful that only async-safe functions are 2771// called here (Note: most pthread functions are not async safe and 2772// should be avoided.) 2773// 2774// Note: sigwait() is a more natural fit than sigsuspend() from an 2775// interface point of view, but sigwait() prevents the signal hander 2776// from being run. libpthread would get very confused by not having 2777// its signal handlers run and prevents sigwait()'s use with the 2778// mutex granting granting signal. 2779// 2780// Currently only ever called on the VMThread or JavaThread 2781// 2782static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 2783 // Save and restore errno to avoid confusing native code with EINTR 2784 // after sigsuspend. 2785 int old_errno = errno; 2786 2787 Thread* thread = Thread::current(); 2788 OSThread* osthread = thread->osthread(); 2789 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 2790 2791 os::SuspendResume::State current = osthread->sr.state(); 2792 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 2793 suspend_save_context(osthread, siginfo, context); 2794 2795 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 2796 os::SuspendResume::State state = osthread->sr.suspended(); 2797 if (state == os::SuspendResume::SR_SUSPENDED) { 2798 sigset_t suspend_set; // signals for sigsuspend() 2799 2800 // get current set of blocked signals and unblock resume signal 2801 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 2802 sigdelset(&suspend_set, SR_signum); 2803 2804 sr_semaphore.signal(); 2805 // wait here until we are resumed 2806 while (1) { 2807 sigsuspend(&suspend_set); 2808 2809 os::SuspendResume::State result = osthread->sr.running(); 2810 if (result == os::SuspendResume::SR_RUNNING) { 2811 sr_semaphore.signal(); 2812 break; 2813 } else if (result != os::SuspendResume::SR_SUSPENDED) { 2814 ShouldNotReachHere(); 2815 } 2816 } 2817 2818 } else if (state == os::SuspendResume::SR_RUNNING) { 2819 // request was cancelled, continue 2820 } else { 2821 ShouldNotReachHere(); 2822 } 2823 2824 resume_clear_context(osthread); 2825 } else if (current == os::SuspendResume::SR_RUNNING) { 2826 // request was cancelled, continue 2827 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 2828 // ignore 2829 } else { 2830 // ignore 2831 } 2832 2833 errno = old_errno; 2834} 2835 2836 2837static int SR_initialize() { 2838 struct sigaction act; 2839 char *s; 2840 /* Get signal number to use for suspend/resume */ 2841 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 2842 int sig = ::strtol(s, 0, 10); 2843 if (sig > 0 || sig < NSIG) { 2844 SR_signum = sig; 2845 } 2846 } 2847 2848 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 2849 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 2850 2851 sigemptyset(&SR_sigset); 2852 sigaddset(&SR_sigset, SR_signum); 2853 2854 /* Set up signal handler for suspend/resume */ 2855 act.sa_flags = SA_RESTART|SA_SIGINFO; 2856 act.sa_handler = (void (*)(int)) SR_handler; 2857 2858 // SR_signum is blocked by default. 2859 // 4528190 - We also need to block pthread restart signal (32 on all 2860 // supported Bsd platforms). Note that BsdThreads need to block 2861 // this signal for all threads to work properly. So we don't have 2862 // to use hard-coded signal number when setting up the mask. 2863 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 2864 2865 if (sigaction(SR_signum, &act, 0) == -1) { 2866 return -1; 2867 } 2868 2869 // Save signal flag 2870 os::Bsd::set_our_sigflags(SR_signum, act.sa_flags); 2871 return 0; 2872} 2873 2874static int sr_notify(OSThread* osthread) { 2875 int status = pthread_kill(osthread->pthread_id(), SR_signum); 2876 assert_status(status == 0, status, "pthread_kill"); 2877 return status; 2878} 2879 2880// "Randomly" selected value for how long we want to spin 2881// before bailing out on suspending a thread, also how often 2882// we send a signal to a thread we want to resume 2883static const int RANDOMLY_LARGE_INTEGER = 1000000; 2884static const int RANDOMLY_LARGE_INTEGER2 = 100; 2885 2886// returns true on success and false on error - really an error is fatal 2887// but this seems the normal response to library errors 2888static bool do_suspend(OSThread* osthread) { 2889 assert(osthread->sr.is_running(), "thread should be running"); 2890 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 2891 2892 // mark as suspended and send signal 2893 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 2894 // failed to switch, state wasn't running? 2895 ShouldNotReachHere(); 2896 return false; 2897 } 2898 2899 if (sr_notify(osthread) != 0) { 2900 ShouldNotReachHere(); 2901 } 2902 2903 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 2904 while (true) { 2905 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 2906 break; 2907 } else { 2908 // timeout 2909 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 2910 if (cancelled == os::SuspendResume::SR_RUNNING) { 2911 return false; 2912 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 2913 // make sure that we consume the signal on the semaphore as well 2914 sr_semaphore.wait(); 2915 break; 2916 } else { 2917 ShouldNotReachHere(); 2918 return false; 2919 } 2920 } 2921 } 2922 2923 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 2924 return true; 2925} 2926 2927static void do_resume(OSThread* osthread) { 2928 assert(osthread->sr.is_suspended(), "thread should be suspended"); 2929 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 2930 2931 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 2932 // failed to switch to WAKEUP_REQUEST 2933 ShouldNotReachHere(); 2934 return; 2935 } 2936 2937 while (true) { 2938 if (sr_notify(osthread) == 0) { 2939 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 2940 if (osthread->sr.is_running()) { 2941 return; 2942 } 2943 } 2944 } else { 2945 ShouldNotReachHere(); 2946 } 2947 } 2948 2949 guarantee(osthread->sr.is_running(), "Must be running!"); 2950} 2951 2952/////////////////////////////////////////////////////////////////////////////////// 2953// signal handling (except suspend/resume) 2954 2955// This routine may be used by user applications as a "hook" to catch signals. 2956// The user-defined signal handler must pass unrecognized signals to this 2957// routine, and if it returns true (non-zero), then the signal handler must 2958// return immediately. If the flag "abort_if_unrecognized" is true, then this 2959// routine will never retun false (zero), but instead will execute a VM panic 2960// routine kill the process. 2961// 2962// If this routine returns false, it is OK to call it again. This allows 2963// the user-defined signal handler to perform checks either before or after 2964// the VM performs its own checks. Naturally, the user code would be making 2965// a serious error if it tried to handle an exception (such as a null check 2966// or breakpoint) that the VM was generating for its own correct operation. 2967// 2968// This routine may recognize any of the following kinds of signals: 2969// SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 2970// It should be consulted by handlers for any of those signals. 2971// 2972// The caller of this routine must pass in the three arguments supplied 2973// to the function referred to in the "sa_sigaction" (not the "sa_handler") 2974// field of the structure passed to sigaction(). This routine assumes that 2975// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 2976// 2977// Note that the VM will print warnings if it detects conflicting signal 2978// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 2979// 2980extern "C" JNIEXPORT int 2981JVM_handle_bsd_signal(int signo, siginfo_t* siginfo, 2982 void* ucontext, int abort_if_unrecognized); 2983 2984void signalHandler(int sig, siginfo_t* info, void* uc) { 2985 assert(info != NULL && uc != NULL, "it must be old kernel"); 2986 int orig_errno = errno; // Preserve errno value over signal handler. 2987 JVM_handle_bsd_signal(sig, info, uc, true); 2988 errno = orig_errno; 2989} 2990 2991 2992// This boolean allows users to forward their own non-matching signals 2993// to JVM_handle_bsd_signal, harmlessly. 2994bool os::Bsd::signal_handlers_are_installed = false; 2995 2996// For signal-chaining 2997struct sigaction os::Bsd::sigact[MAXSIGNUM]; 2998unsigned int os::Bsd::sigs = 0; 2999bool os::Bsd::libjsig_is_loaded = false; 3000typedef struct sigaction *(*get_signal_t)(int); 3001get_signal_t os::Bsd::get_signal_action = NULL; 3002 3003struct sigaction* os::Bsd::get_chained_signal_action(int sig) { 3004 struct sigaction *actp = NULL; 3005 3006 if (libjsig_is_loaded) { 3007 // Retrieve the old signal handler from libjsig 3008 actp = (*get_signal_action)(sig); 3009 } 3010 if (actp == NULL) { 3011 // Retrieve the preinstalled signal handler from jvm 3012 actp = get_preinstalled_handler(sig); 3013 } 3014 3015 return actp; 3016} 3017 3018static bool call_chained_handler(struct sigaction *actp, int sig, 3019 siginfo_t *siginfo, void *context) { 3020 // Call the old signal handler 3021 if (actp->sa_handler == SIG_DFL) { 3022 // It's more reasonable to let jvm treat it as an unexpected exception 3023 // instead of taking the default action. 3024 return false; 3025 } else if (actp->sa_handler != SIG_IGN) { 3026 if ((actp->sa_flags & SA_NODEFER) == 0) { 3027 // automaticlly block the signal 3028 sigaddset(&(actp->sa_mask), sig); 3029 } 3030 3031 sa_handler_t hand; 3032 sa_sigaction_t sa; 3033 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 3034 // retrieve the chained handler 3035 if (siginfo_flag_set) { 3036 sa = actp->sa_sigaction; 3037 } else { 3038 hand = actp->sa_handler; 3039 } 3040 3041 if ((actp->sa_flags & SA_RESETHAND) != 0) { 3042 actp->sa_handler = SIG_DFL; 3043 } 3044 3045 // try to honor the signal mask 3046 sigset_t oset; 3047 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 3048 3049 // call into the chained handler 3050 if (siginfo_flag_set) { 3051 (*sa)(sig, siginfo, context); 3052 } else { 3053 (*hand)(sig); 3054 } 3055 3056 // restore the signal mask 3057 pthread_sigmask(SIG_SETMASK, &oset, 0); 3058 } 3059 // Tell jvm's signal handler the signal is taken care of. 3060 return true; 3061} 3062 3063bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) { 3064 bool chained = false; 3065 // signal-chaining 3066 if (UseSignalChaining) { 3067 struct sigaction *actp = get_chained_signal_action(sig); 3068 if (actp != NULL) { 3069 chained = call_chained_handler(actp, sig, siginfo, context); 3070 } 3071 } 3072 return chained; 3073} 3074 3075struct sigaction* os::Bsd::get_preinstalled_handler(int sig) { 3076 if ((((unsigned int)1 << sig) & sigs) != 0) { 3077 return &sigact[sig]; 3078 } 3079 return NULL; 3080} 3081 3082void os::Bsd::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 3083 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3084 sigact[sig] = oldAct; 3085 sigs |= (unsigned int)1 << sig; 3086} 3087 3088// for diagnostic 3089int os::Bsd::sigflags[MAXSIGNUM]; 3090 3091int os::Bsd::get_our_sigflags(int sig) { 3092 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3093 return sigflags[sig]; 3094} 3095 3096void os::Bsd::set_our_sigflags(int sig, int flags) { 3097 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3098 sigflags[sig] = flags; 3099} 3100 3101void os::Bsd::set_signal_handler(int sig, bool set_installed) { 3102 // Check for overwrite. 3103 struct sigaction oldAct; 3104 sigaction(sig, (struct sigaction*)NULL, &oldAct); 3105 3106 void* oldhand = oldAct.sa_sigaction 3107 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3108 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3109 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 3110 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 3111 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 3112 if (AllowUserSignalHandlers || !set_installed) { 3113 // Do not overwrite; user takes responsibility to forward to us. 3114 return; 3115 } else if (UseSignalChaining) { 3116 // save the old handler in jvm 3117 save_preinstalled_handler(sig, oldAct); 3118 // libjsig also interposes the sigaction() call below and saves the 3119 // old sigaction on it own. 3120 } else { 3121 fatal(err_msg("Encountered unexpected pre-existing sigaction handler " 3122 "%#lx for signal %d.", (long)oldhand, sig)); 3123 } 3124 } 3125 3126 struct sigaction sigAct; 3127 sigfillset(&(sigAct.sa_mask)); 3128 sigAct.sa_handler = SIG_DFL; 3129 if (!set_installed) { 3130 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3131 } else { 3132 sigAct.sa_sigaction = signalHandler; 3133 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3134 } 3135#ifdef __APPLE__ 3136 // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV 3137 // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages" 3138 // if the signal handler declares it will handle it on alternate stack. 3139 // Notice we only declare we will handle it on alt stack, but we are not 3140 // actually going to use real alt stack - this is just a workaround. 3141 // Please see ux_exception.c, method catch_mach_exception_raise for details 3142 // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c 3143 if (sig == SIGSEGV) { 3144 sigAct.sa_flags |= SA_ONSTACK; 3145 } 3146#endif 3147 3148 // Save flags, which are set by ours 3149 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3150 sigflags[sig] = sigAct.sa_flags; 3151 3152 int ret = sigaction(sig, &sigAct, &oldAct); 3153 assert(ret == 0, "check"); 3154 3155 void* oldhand2 = oldAct.sa_sigaction 3156 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3157 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3158 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 3159} 3160 3161// install signal handlers for signals that HotSpot needs to 3162// handle in order to support Java-level exception handling. 3163 3164void os::Bsd::install_signal_handlers() { 3165 if (!signal_handlers_are_installed) { 3166 signal_handlers_are_installed = true; 3167 3168 // signal-chaining 3169 typedef void (*signal_setting_t)(); 3170 signal_setting_t begin_signal_setting = NULL; 3171 signal_setting_t end_signal_setting = NULL; 3172 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3173 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 3174 if (begin_signal_setting != NULL) { 3175 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3176 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 3177 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 3178 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 3179 libjsig_is_loaded = true; 3180 assert(UseSignalChaining, "should enable signal-chaining"); 3181 } 3182 if (libjsig_is_loaded) { 3183 // Tell libjsig jvm is setting signal handlers 3184 (*begin_signal_setting)(); 3185 } 3186 3187 set_signal_handler(SIGSEGV, true); 3188 set_signal_handler(SIGPIPE, true); 3189 set_signal_handler(SIGBUS, true); 3190 set_signal_handler(SIGILL, true); 3191 set_signal_handler(SIGFPE, true); 3192 set_signal_handler(SIGXFSZ, true); 3193 3194#if defined(__APPLE__) 3195 // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including 3196 // signals caught and handled by the JVM. To work around this, we reset the mach task 3197 // signal handler that's placed on our process by CrashReporter. This disables 3198 // CrashReporter-based reporting. 3199 // 3200 // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes 3201 // on caught fatal signals. 3202 // 3203 // Additionally, gdb installs both standard BSD signal handlers, and mach exception 3204 // handlers. By replacing the existing task exception handler, we disable gdb's mach 3205 // exception handling, while leaving the standard BSD signal handlers functional. 3206 kern_return_t kr; 3207 kr = task_set_exception_ports(mach_task_self(), 3208 EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC, 3209 MACH_PORT_NULL, 3210 EXCEPTION_STATE_IDENTITY, 3211 MACHINE_THREAD_STATE); 3212 3213 assert(kr == KERN_SUCCESS, "could not set mach task signal handler"); 3214#endif 3215 3216 if (libjsig_is_loaded) { 3217 // Tell libjsig jvm finishes setting signal handlers 3218 (*end_signal_setting)(); 3219 } 3220 3221 // We don't activate signal checker if libjsig is in place, we trust ourselves 3222 // and if UserSignalHandler is installed all bets are off 3223 if (CheckJNICalls) { 3224 if (libjsig_is_loaded) { 3225 if (PrintJNIResolving) { 3226 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 3227 } 3228 check_signals = false; 3229 } 3230 if (AllowUserSignalHandlers) { 3231 if (PrintJNIResolving) { 3232 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 3233 } 3234 check_signals = false; 3235 } 3236 } 3237 } 3238} 3239 3240 3241///// 3242// glibc on Bsd platform uses non-documented flag 3243// to indicate, that some special sort of signal 3244// trampoline is used. 3245// We will never set this flag, and we should 3246// ignore this flag in our diagnostic 3247#ifdef SIGNIFICANT_SIGNAL_MASK 3248#undef SIGNIFICANT_SIGNAL_MASK 3249#endif 3250#define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 3251 3252static const char* get_signal_handler_name(address handler, 3253 char* buf, int buflen) { 3254 int offset; 3255 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 3256 if (found) { 3257 // skip directory names 3258 const char *p1, *p2; 3259 p1 = buf; 3260 size_t len = strlen(os::file_separator()); 3261 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 3262 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 3263 } else { 3264 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 3265 } 3266 return buf; 3267} 3268 3269static void print_signal_handler(outputStream* st, int sig, 3270 char* buf, size_t buflen) { 3271 struct sigaction sa; 3272 3273 sigaction(sig, NULL, &sa); 3274 3275 // See comment for SIGNIFICANT_SIGNAL_MASK define 3276 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3277 3278 st->print("%s: ", os::exception_name(sig, buf, buflen)); 3279 3280 address handler = (sa.sa_flags & SA_SIGINFO) 3281 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 3282 : CAST_FROM_FN_PTR(address, sa.sa_handler); 3283 3284 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 3285 st->print("SIG_DFL"); 3286 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 3287 st->print("SIG_IGN"); 3288 } else { 3289 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 3290 } 3291 3292 st->print(", sa_mask[0]="); 3293 os::Posix::print_signal_set_short(st, &sa.sa_mask); 3294 3295 address rh = VMError::get_resetted_sighandler(sig); 3296 // May be, handler was resetted by VMError? 3297 if (rh != NULL) { 3298 handler = rh; 3299 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 3300 } 3301 3302 st->print(", sa_flags="); 3303 os::Posix::print_sa_flags(st, sa.sa_flags); 3304 3305 // Check: is it our handler? 3306 if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 3307 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 3308 // It is our signal handler 3309 // check for flags, reset system-used one! 3310 if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { 3311 st->print( 3312 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 3313 os::Bsd::get_our_sigflags(sig)); 3314 } 3315 } 3316 st->cr(); 3317} 3318 3319 3320#define DO_SIGNAL_CHECK(sig) \ 3321 if (!sigismember(&check_signal_done, sig)) \ 3322 os::Bsd::check_signal_handler(sig) 3323 3324// This method is a periodic task to check for misbehaving JNI applications 3325// under CheckJNI, we can add any periodic checks here 3326 3327void os::run_periodic_checks() { 3328 3329 if (check_signals == false) return; 3330 3331 // SEGV and BUS if overridden could potentially prevent 3332 // generation of hs*.log in the event of a crash, debugging 3333 // such a case can be very challenging, so we absolutely 3334 // check the following for a good measure: 3335 DO_SIGNAL_CHECK(SIGSEGV); 3336 DO_SIGNAL_CHECK(SIGILL); 3337 DO_SIGNAL_CHECK(SIGFPE); 3338 DO_SIGNAL_CHECK(SIGBUS); 3339 DO_SIGNAL_CHECK(SIGPIPE); 3340 DO_SIGNAL_CHECK(SIGXFSZ); 3341 3342 3343 // ReduceSignalUsage allows the user to override these handlers 3344 // see comments at the very top and jvm_solaris.h 3345 if (!ReduceSignalUsage) { 3346 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 3347 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 3348 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 3349 DO_SIGNAL_CHECK(BREAK_SIGNAL); 3350 } 3351 3352 DO_SIGNAL_CHECK(SR_signum); 3353 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 3354} 3355 3356typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 3357 3358static os_sigaction_t os_sigaction = NULL; 3359 3360void os::Bsd::check_signal_handler(int sig) { 3361 char buf[O_BUFLEN]; 3362 address jvmHandler = NULL; 3363 3364 3365 struct sigaction act; 3366 if (os_sigaction == NULL) { 3367 // only trust the default sigaction, in case it has been interposed 3368 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 3369 if (os_sigaction == NULL) return; 3370 } 3371 3372 os_sigaction(sig, (struct sigaction*)NULL, &act); 3373 3374 3375 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3376 3377 address thisHandler = (act.sa_flags & SA_SIGINFO) 3378 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 3379 : CAST_FROM_FN_PTR(address, act.sa_handler); 3380 3381 3382 switch (sig) { 3383 case SIGSEGV: 3384 case SIGBUS: 3385 case SIGFPE: 3386 case SIGPIPE: 3387 case SIGILL: 3388 case SIGXFSZ: 3389 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 3390 break; 3391 3392 case SHUTDOWN1_SIGNAL: 3393 case SHUTDOWN2_SIGNAL: 3394 case SHUTDOWN3_SIGNAL: 3395 case BREAK_SIGNAL: 3396 jvmHandler = (address)user_handler(); 3397 break; 3398 3399 case INTERRUPT_SIGNAL: 3400 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 3401 break; 3402 3403 default: 3404 if (sig == SR_signum) { 3405 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 3406 } else { 3407 return; 3408 } 3409 break; 3410 } 3411 3412 if (thisHandler != jvmHandler) { 3413 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 3414 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 3415 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 3416 // No need to check this sig any longer 3417 sigaddset(&check_signal_done, sig); 3418 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 3419 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 3420 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 3421 exception_name(sig, buf, O_BUFLEN)); 3422 } 3423 } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) { 3424 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 3425 tty->print("expected:" PTR32_FORMAT, os::Bsd::get_our_sigflags(sig)); 3426 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 3427 // No need to check this sig any longer 3428 sigaddset(&check_signal_done, sig); 3429 } 3430 3431 // Dump all the signal 3432 if (sigismember(&check_signal_done, sig)) { 3433 print_signal_handlers(tty, buf, O_BUFLEN); 3434 } 3435} 3436 3437extern void report_error(char* file_name, int line_no, char* title, char* format, ...); 3438 3439extern bool signal_name(int signo, char* buf, size_t len); 3440 3441const char* os::exception_name(int exception_code, char* buf, size_t size) { 3442 if (0 < exception_code && exception_code <= SIGRTMAX) { 3443 // signal 3444 if (!signal_name(exception_code, buf, size)) { 3445 jio_snprintf(buf, size, "SIG%d", exception_code); 3446 } 3447 return buf; 3448 } else { 3449 return NULL; 3450 } 3451} 3452 3453// this is called _before_ the most of global arguments have been parsed 3454void os::init(void) { 3455 char dummy; /* used to get a guess on initial stack address */ 3456// first_hrtime = gethrtime(); 3457 3458 // With BsdThreads the JavaMain thread pid (primordial thread) 3459 // is different than the pid of the java launcher thread. 3460 // So, on Bsd, the launcher thread pid is passed to the VM 3461 // via the sun.java.launcher.pid property. 3462 // Use this property instead of getpid() if it was correctly passed. 3463 // See bug 6351349. 3464 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 3465 3466 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 3467 3468 clock_tics_per_sec = CLK_TCK; 3469 3470 init_random(1234567); 3471 3472 ThreadCritical::initialize(); 3473 3474 Bsd::set_page_size(getpagesize()); 3475 if (Bsd::page_size() == -1) { 3476 fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)", 3477 strerror(errno))); 3478 } 3479 init_page_sizes((size_t) Bsd::page_size()); 3480 3481 Bsd::initialize_system_info(); 3482 3483 // main_thread points to the aboriginal thread 3484 Bsd::_main_thread = pthread_self(); 3485 3486 Bsd::clock_init(); 3487 initial_time_count = javaTimeNanos(); 3488 3489#ifdef __APPLE__ 3490 // XXXDARWIN 3491 // Work around the unaligned VM callbacks in hotspot's 3492 // sharedRuntime. The callbacks don't use SSE2 instructions, and work on 3493 // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces 3494 // alignment when doing symbol lookup. To work around this, we force early 3495 // binding of all symbols now, thus binding when alignment is known-good. 3496 _dyld_bind_fully_image_containing_address((const void *) &os::init); 3497#endif 3498} 3499 3500// To install functions for atexit system call 3501extern "C" { 3502 static void perfMemory_exit_helper() { 3503 perfMemory_exit(); 3504 } 3505} 3506 3507// this is called _after_ the global arguments have been parsed 3508jint os::init_2(void) 3509{ 3510 // Allocate a single page and mark it as readable for safepoint polling 3511 address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3512 guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); 3513 3514 os::set_polling_page(polling_page); 3515 3516#ifndef PRODUCT 3517 if (Verbose && PrintMiscellaneous) 3518 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); 3519#endif 3520 3521 if (!UseMembar) { 3522 address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3523 guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); 3524 os::set_memory_serialize_page(mem_serialize_page); 3525 3526#ifndef PRODUCT 3527 if (Verbose && PrintMiscellaneous) 3528 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); 3529#endif 3530 } 3531 3532 // initialize suspend/resume support - must do this before signal_sets_init() 3533 if (SR_initialize() != 0) { 3534 perror("SR_initialize failed"); 3535 return JNI_ERR; 3536 } 3537 3538 Bsd::signal_sets_init(); 3539 Bsd::install_signal_handlers(); 3540 3541 // Check minimum allowable stack size for thread creation and to initialize 3542 // the java system classes, including StackOverflowError - depends on page 3543 // size. Add a page for compiler2 recursion in main thread. 3544 // Add in 2*BytesPerWord times page size to account for VM stack during 3545 // class initialization depending on 32 or 64 bit VM. 3546 os::Bsd::min_stack_allowed = MAX2(os::Bsd::min_stack_allowed, 3547 (size_t)(StackYellowPages+StackRedPages+StackShadowPages+ 3548 2*BytesPerWord COMPILER2_PRESENT(+1)) * Bsd::page_size()); 3549 3550 size_t threadStackSizeInBytes = ThreadStackSize * K; 3551 if (threadStackSizeInBytes != 0 && 3552 threadStackSizeInBytes < os::Bsd::min_stack_allowed) { 3553 tty->print_cr("\nThe stack size specified is too small, " 3554 "Specify at least %dk", 3555 os::Bsd::min_stack_allowed/ K); 3556 return JNI_ERR; 3557 } 3558 3559 // Make the stack size a multiple of the page size so that 3560 // the yellow/red zones can be guarded. 3561 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 3562 vm_page_size())); 3563 3564 if (MaxFDLimit) { 3565 // set the number of file descriptors to max. print out error 3566 // if getrlimit/setrlimit fails but continue regardless. 3567 struct rlimit nbr_files; 3568 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 3569 if (status != 0) { 3570 if (PrintMiscellaneous && (Verbose || WizardMode)) 3571 perror("os::init_2 getrlimit failed"); 3572 } else { 3573 nbr_files.rlim_cur = nbr_files.rlim_max; 3574 3575#ifdef __APPLE__ 3576 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if 3577 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must 3578 // be used instead 3579 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur); 3580#endif 3581 3582 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 3583 if (status != 0) { 3584 if (PrintMiscellaneous && (Verbose || WizardMode)) 3585 perror("os::init_2 setrlimit failed"); 3586 } 3587 } 3588 } 3589 3590 // at-exit methods are called in the reverse order of their registration. 3591 // atexit functions are called on return from main or as a result of a 3592 // call to exit(3C). There can be only 32 of these functions registered 3593 // and atexit() does not set errno. 3594 3595 if (PerfAllowAtExitRegistration) { 3596 // only register atexit functions if PerfAllowAtExitRegistration is set. 3597 // atexit functions can be delayed until process exit time, which 3598 // can be problematic for embedded VM situations. Embedded VMs should 3599 // call DestroyJavaVM() to assure that VM resources are released. 3600 3601 // note: perfMemory_exit_helper atexit function may be removed in 3602 // the future if the appropriate cleanup code can be added to the 3603 // VM_Exit VMOperation's doit method. 3604 if (atexit(perfMemory_exit_helper) != 0) { 3605 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 3606 } 3607 } 3608 3609 // initialize thread priority policy 3610 prio_init(); 3611 3612#ifdef __APPLE__ 3613 // dynamically link to objective c gc registration 3614 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY); 3615 if (handleLibObjc != NULL) { 3616 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER); 3617 } 3618#endif 3619 3620 return JNI_OK; 3621} 3622 3623// this is called at the end of vm_initialization 3624void os::init_3(void) { } 3625 3626// Mark the polling page as unreadable 3627void os::make_polling_page_unreadable(void) { 3628 if (!guard_memory((char*)_polling_page, Bsd::page_size())) 3629 fatal("Could not disable polling page"); 3630}; 3631 3632// Mark the polling page as readable 3633void os::make_polling_page_readable(void) { 3634 if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { 3635 fatal("Could not enable polling page"); 3636 } 3637}; 3638 3639int os::active_processor_count() { 3640 return _processor_count; 3641} 3642 3643void os::set_native_thread_name(const char *name) { 3644#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 3645 // This is only supported in Snow Leopard and beyond 3646 if (name != NULL) { 3647 // Add a "Java: " prefix to the name 3648 char buf[MAXTHREADNAMESIZE]; 3649 snprintf(buf, sizeof(buf), "Java: %s", name); 3650 pthread_setname_np(buf); 3651 } 3652#endif 3653} 3654 3655bool os::distribute_processes(uint length, uint* distribution) { 3656 // Not yet implemented. 3657 return false; 3658} 3659 3660bool os::bind_to_processor(uint processor_id) { 3661 // Not yet implemented. 3662 return false; 3663} 3664 3665void os::SuspendedThreadTask::internal_do_task() { 3666 if (do_suspend(_thread->osthread())) { 3667 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 3668 do_task(context); 3669 do_resume(_thread->osthread()); 3670 } 3671} 3672 3673/// 3674class PcFetcher : public os::SuspendedThreadTask { 3675public: 3676 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 3677 ExtendedPC result(); 3678protected: 3679 void do_task(const os::SuspendedThreadTaskContext& context); 3680private: 3681 ExtendedPC _epc; 3682}; 3683 3684ExtendedPC PcFetcher::result() { 3685 guarantee(is_done(), "task is not done yet."); 3686 return _epc; 3687} 3688 3689void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 3690 Thread* thread = context.thread(); 3691 OSThread* osthread = thread->osthread(); 3692 if (osthread->ucontext() != NULL) { 3693 _epc = os::Bsd::ucontext_get_pc((ucontext_t *) context.ucontext()); 3694 } else { 3695 // NULL context is unexpected, double-check this is the VMThread 3696 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 3697 } 3698} 3699 3700// Suspends the target using the signal mechanism and then grabs the PC before 3701// resuming the target. Used by the flat-profiler only 3702ExtendedPC os::get_thread_pc(Thread* thread) { 3703 // Make sure that it is called by the watcher for the VMThread 3704 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 3705 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 3706 3707 PcFetcher fetcher(thread); 3708 fetcher.run(); 3709 return fetcher.result(); 3710} 3711 3712int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) 3713{ 3714 return pthread_cond_timedwait(_cond, _mutex, _abstime); 3715} 3716 3717//////////////////////////////////////////////////////////////////////////////// 3718// debug support 3719 3720bool os::find(address addr, outputStream* st) { 3721 Dl_info dlinfo; 3722 memset(&dlinfo, 0, sizeof(dlinfo)); 3723 if (dladdr(addr, &dlinfo) != 0) { 3724 st->print(PTR_FORMAT ": ", addr); 3725 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 3726 st->print("%s+%#x", dlinfo.dli_sname, 3727 addr - (intptr_t)dlinfo.dli_saddr); 3728 } else if (dlinfo.dli_fbase != NULL) { 3729 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 3730 } else { 3731 st->print("<absolute address>"); 3732 } 3733 if (dlinfo.dli_fname != NULL) { 3734 st->print(" in %s", dlinfo.dli_fname); 3735 } 3736 if (dlinfo.dli_fbase != NULL) { 3737 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 3738 } 3739 st->cr(); 3740 3741 if (Verbose) { 3742 // decode some bytes around the PC 3743 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 3744 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 3745 address lowest = (address) dlinfo.dli_sname; 3746 if (!lowest) lowest = (address) dlinfo.dli_fbase; 3747 if (begin < lowest) begin = lowest; 3748 Dl_info dlinfo2; 3749 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 3750 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) 3751 end = (address) dlinfo2.dli_saddr; 3752 Disassembler::decode(begin, end, st); 3753 } 3754 return true; 3755 } 3756 return false; 3757} 3758 3759//////////////////////////////////////////////////////////////////////////////// 3760// misc 3761 3762// This does not do anything on Bsd. This is basically a hook for being 3763// able to use structured exception handling (thread-local exception filters) 3764// on, e.g., Win32. 3765void 3766os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, 3767 JavaCallArguments* args, Thread* thread) { 3768 f(value, method, args, thread); 3769} 3770 3771void os::print_statistics() { 3772} 3773 3774int os::message_box(const char* title, const char* message) { 3775 int i; 3776 fdStream err(defaultStream::error_fd()); 3777 for (i = 0; i < 78; i++) err.print_raw("="); 3778 err.cr(); 3779 err.print_raw_cr(title); 3780 for (i = 0; i < 78; i++) err.print_raw("-"); 3781 err.cr(); 3782 err.print_raw_cr(message); 3783 for (i = 0; i < 78; i++) err.print_raw("="); 3784 err.cr(); 3785 3786 char buf[16]; 3787 // Prevent process from exiting upon "read error" without consuming all CPU 3788 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 3789 3790 return buf[0] == 'y' || buf[0] == 'Y'; 3791} 3792 3793int os::stat(const char *path, struct stat *sbuf) { 3794 char pathbuf[MAX_PATH]; 3795 if (strlen(path) > MAX_PATH - 1) { 3796 errno = ENAMETOOLONG; 3797 return -1; 3798 } 3799 os::native_path(strcpy(pathbuf, path)); 3800 return ::stat(pathbuf, sbuf); 3801} 3802 3803bool os::check_heap(bool force) { 3804 return true; 3805} 3806 3807ATTRIBUTE_PRINTF(3, 0) 3808int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { 3809 return ::vsnprintf(buf, count, format, args); 3810} 3811 3812// Is a (classpath) directory empty? 3813bool os::dir_is_empty(const char* path) { 3814 DIR *dir = NULL; 3815 struct dirent *ptr; 3816 3817 dir = opendir(path); 3818 if (dir == NULL) return true; 3819 3820 /* Scan the directory */ 3821 bool result = true; 3822 char buf[sizeof(struct dirent) + MAX_PATH]; 3823 while (result && (ptr = ::readdir(dir)) != NULL) { 3824 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 3825 result = false; 3826 } 3827 } 3828 closedir(dir); 3829 return result; 3830} 3831 3832// This code originates from JDK's sysOpen and open64_w 3833// from src/solaris/hpi/src/system_md.c 3834 3835#ifndef O_DELETE 3836#define O_DELETE 0x10000 3837#endif 3838 3839// Open a file. Unlink the file immediately after open returns 3840// if the specified oflag has the O_DELETE flag set. 3841// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c 3842 3843int os::open(const char *path, int oflag, int mode) { 3844 3845 if (strlen(path) > MAX_PATH - 1) { 3846 errno = ENAMETOOLONG; 3847 return -1; 3848 } 3849 int fd; 3850 int o_delete = (oflag & O_DELETE); 3851 oflag = oflag & ~O_DELETE; 3852 3853 fd = ::open(path, oflag, mode); 3854 if (fd == -1) return -1; 3855 3856 //If the open succeeded, the file might still be a directory 3857 { 3858 struct stat buf; 3859 int ret = ::fstat(fd, &buf); 3860 int st_mode = buf.st_mode; 3861 3862 if (ret != -1) { 3863 if ((st_mode & S_IFMT) == S_IFDIR) { 3864 errno = EISDIR; 3865 ::close(fd); 3866 return -1; 3867 } 3868 } else { 3869 ::close(fd); 3870 return -1; 3871 } 3872 } 3873 3874 /* 3875 * All file descriptors that are opened in the JVM and not 3876 * specifically destined for a subprocess should have the 3877 * close-on-exec flag set. If we don't set it, then careless 3rd 3878 * party native code might fork and exec without closing all 3879 * appropriate file descriptors (e.g. as we do in closeDescriptors in 3880 * UNIXProcess.c), and this in turn might: 3881 * 3882 * - cause end-of-file to fail to be detected on some file 3883 * descriptors, resulting in mysterious hangs, or 3884 * 3885 * - might cause an fopen in the subprocess to fail on a system 3886 * suffering from bug 1085341. 3887 * 3888 * (Yes, the default setting of the close-on-exec flag is a Unix 3889 * design flaw) 3890 * 3891 * See: 3892 * 1085341: 32-bit stdio routines should support file descriptors >255 3893 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed 3894 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 3895 */ 3896#ifdef FD_CLOEXEC 3897 { 3898 int flags = ::fcntl(fd, F_GETFD); 3899 if (flags != -1) 3900 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 3901 } 3902#endif 3903 3904 if (o_delete != 0) { 3905 ::unlink(path); 3906 } 3907 return fd; 3908} 3909 3910 3911// create binary file, rewriting existing file if required 3912int os::create_binary_file(const char* path, bool rewrite_existing) { 3913 int oflags = O_WRONLY | O_CREAT; 3914 if (!rewrite_existing) { 3915 oflags |= O_EXCL; 3916 } 3917 return ::open(path, oflags, S_IREAD | S_IWRITE); 3918} 3919 3920// return current position of file pointer 3921jlong os::current_file_offset(int fd) { 3922 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR); 3923} 3924 3925// move file pointer to the specified offset 3926jlong os::seek_to_file_offset(int fd, jlong offset) { 3927 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET); 3928} 3929 3930// This code originates from JDK's sysAvailable 3931// from src/solaris/hpi/src/native_threads/src/sys_api_td.c 3932 3933int os::available(int fd, jlong *bytes) { 3934 jlong cur, end; 3935 int mode; 3936 struct stat buf; 3937 3938 if (::fstat(fd, &buf) >= 0) { 3939 mode = buf.st_mode; 3940 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 3941 /* 3942 * XXX: is the following call interruptible? If so, this might 3943 * need to go through the INTERRUPT_IO() wrapper as for other 3944 * blocking, interruptible calls in this file. 3945 */ 3946 int n; 3947 if (::ioctl(fd, FIONREAD, &n) >= 0) { 3948 *bytes = n; 3949 return 1; 3950 } 3951 } 3952 } 3953 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) { 3954 return 0; 3955 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) { 3956 return 0; 3957 } else if (::lseek(fd, cur, SEEK_SET) == -1) { 3958 return 0; 3959 } 3960 *bytes = end - cur; 3961 return 1; 3962} 3963 3964int os::socket_available(int fd, jint *pbytes) { 3965 if (fd < 0) 3966 return OS_OK; 3967 3968 int ret; 3969 3970 RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret); 3971 3972 //%% note ioctl can return 0 when successful, JVM_SocketAvailable 3973 // is expected to return 0 on failure and 1 on success to the jdk. 3974 3975 return (ret == OS_ERR) ? 0 : 1; 3976} 3977 3978// Map a block of memory. 3979char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 3980 char *addr, size_t bytes, bool read_only, 3981 bool allow_exec) { 3982 int prot; 3983 int flags; 3984 3985 if (read_only) { 3986 prot = PROT_READ; 3987 flags = MAP_SHARED; 3988 } else { 3989 prot = PROT_READ | PROT_WRITE; 3990 flags = MAP_PRIVATE; 3991 } 3992 3993 if (allow_exec) { 3994 prot |= PROT_EXEC; 3995 } 3996 3997 if (addr != NULL) { 3998 flags |= MAP_FIXED; 3999 } 4000 4001 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 4002 fd, file_offset); 4003 if (mapped_address == MAP_FAILED) { 4004 return NULL; 4005 } 4006 return mapped_address; 4007} 4008 4009 4010// Remap a block of memory. 4011char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 4012 char *addr, size_t bytes, bool read_only, 4013 bool allow_exec) { 4014 // same as map_memory() on this OS 4015 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4016 allow_exec); 4017} 4018 4019 4020// Unmap a block of memory. 4021bool os::pd_unmap_memory(char* addr, size_t bytes) { 4022 return munmap(addr, bytes) == 0; 4023} 4024 4025// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 4026// are used by JVM M&M and JVMTI to get user+sys or user CPU time 4027// of a thread. 4028// 4029// current_thread_cpu_time() and thread_cpu_time(Thread*) returns 4030// the fast estimate available on the platform. 4031 4032jlong os::current_thread_cpu_time() { 4033#ifdef __APPLE__ 4034 return os::thread_cpu_time(Thread::current(), true /* user + sys */); 4035#else 4036 Unimplemented(); 4037 return 0; 4038#endif 4039} 4040 4041jlong os::thread_cpu_time(Thread* thread) { 4042#ifdef __APPLE__ 4043 return os::thread_cpu_time(thread, true /* user + sys */); 4044#else 4045 Unimplemented(); 4046 return 0; 4047#endif 4048} 4049 4050jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 4051#ifdef __APPLE__ 4052 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 4053#else 4054 Unimplemented(); 4055 return 0; 4056#endif 4057} 4058 4059jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 4060#ifdef __APPLE__ 4061 struct thread_basic_info tinfo; 4062 mach_msg_type_number_t tcount = THREAD_INFO_MAX; 4063 kern_return_t kr; 4064 thread_t mach_thread; 4065 4066 mach_thread = thread->osthread()->thread_id(); 4067 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount); 4068 if (kr != KERN_SUCCESS) 4069 return -1; 4070 4071 if (user_sys_cpu_time) { 4072 jlong nanos; 4073 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000; 4074 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000; 4075 return nanos; 4076 } else { 4077 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000); 4078 } 4079#else 4080 Unimplemented(); 4081 return 0; 4082#endif 4083} 4084 4085 4086void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4087 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4088 info_ptr->may_skip_backward = false; // elapsed time not wall time 4089 info_ptr->may_skip_forward = false; // elapsed time not wall time 4090 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4091} 4092 4093void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4094 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4095 info_ptr->may_skip_backward = false; // elapsed time not wall time 4096 info_ptr->may_skip_forward = false; // elapsed time not wall time 4097 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4098} 4099 4100bool os::is_thread_cpu_time_supported() { 4101#ifdef __APPLE__ 4102 return true; 4103#else 4104 return false; 4105#endif 4106} 4107 4108// System loadavg support. Returns -1 if load average cannot be obtained. 4109// Bsd doesn't yet have a (official) notion of processor sets, 4110// so just return the system wide load average. 4111int os::loadavg(double loadavg[], int nelem) { 4112 return ::getloadavg(loadavg, nelem); 4113} 4114 4115void os::pause() { 4116 char filename[MAX_PATH]; 4117 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4118 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4119 } else { 4120 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4121 } 4122 4123 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4124 if (fd != -1) { 4125 struct stat buf; 4126 ::close(fd); 4127 while (::stat(filename, &buf) == 0) { 4128 (void)::poll(NULL, 0, 100); 4129 } 4130 } else { 4131 jio_fprintf(stderr, 4132 "Could not open pause file '%s', continuing immediately.\n", filename); 4133 } 4134} 4135 4136 4137// Refer to the comments in os_solaris.cpp park-unpark. 4138// 4139// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 4140// hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 4141// For specifics regarding the bug see GLIBC BUGID 261237 : 4142// http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 4143// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 4144// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 4145// is used. (The simple C test-case provided in the GLIBC bug report manifests the 4146// hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 4147// and monitorenter when we're using 1-0 locking. All those operations may result in 4148// calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 4149// of libpthread avoids the problem, but isn't practical. 4150// 4151// Possible remedies: 4152// 4153// 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 4154// This is palliative and probabilistic, however. If the thread is preempted 4155// between the call to compute_abstime() and pthread_cond_timedwait(), more 4156// than the minimum period may have passed, and the abstime may be stale (in the 4157// past) resultin in a hang. Using this technique reduces the odds of a hang 4158// but the JVM is still vulnerable, particularly on heavily loaded systems. 4159// 4160// 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 4161// of the usual flag-condvar-mutex idiom. The write side of the pipe is set 4162// NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 4163// reduces to poll()+read(). This works well, but consumes 2 FDs per extant 4164// thread. 4165// 4166// 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 4167// that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 4168// a timeout request to the chron thread and then blocking via pthread_cond_wait(). 4169// This also works well. In fact it avoids kernel-level scalability impediments 4170// on certain platforms that don't handle lots of active pthread_cond_timedwait() 4171// timers in a graceful fashion. 4172// 4173// 4. When the abstime value is in the past it appears that control returns 4174// correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 4175// Subsequent timedwait/wait calls may hang indefinitely. Given that, we 4176// can avoid the problem by reinitializing the condvar -- by cond_destroy() 4177// followed by cond_init() -- after all calls to pthread_cond_timedwait(). 4178// It may be possible to avoid reinitialization by checking the return 4179// value from pthread_cond_timedwait(). In addition to reinitializing the 4180// condvar we must establish the invariant that cond_signal() is only called 4181// within critical sections protected by the adjunct mutex. This prevents 4182// cond_signal() from "seeing" a condvar that's in the midst of being 4183// reinitialized or that is corrupt. Sadly, this invariant obviates the 4184// desirable signal-after-unlock optimization that avoids futile context switching. 4185// 4186// I'm also concerned that some versions of NTPL might allocate an auxilliary 4187// structure when a condvar is used or initialized. cond_destroy() would 4188// release the helper structure. Our reinitialize-after-timedwait fix 4189// put excessive stress on malloc/free and locks protecting the c-heap. 4190// 4191// We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 4192// It may be possible to refine (4) by checking the kernel and NTPL verisons 4193// and only enabling the work-around for vulnerable environments. 4194 4195// utility to compute the abstime argument to timedwait: 4196// millis is the relative timeout time 4197// abstime will be the absolute timeout time 4198// TODO: replace compute_abstime() with unpackTime() 4199 4200static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) { 4201 if (millis < 0) millis = 0; 4202 struct timeval now; 4203 int status = gettimeofday(&now, NULL); 4204 assert(status == 0, "gettimeofday"); 4205 jlong seconds = millis / 1000; 4206 millis %= 1000; 4207 if (seconds > 50000000) { // see man cond_timedwait(3T) 4208 seconds = 50000000; 4209 } 4210 abstime->tv_sec = now.tv_sec + seconds; 4211 long usec = now.tv_usec + millis * 1000; 4212 if (usec >= 1000000) { 4213 abstime->tv_sec += 1; 4214 usec -= 1000000; 4215 } 4216 abstime->tv_nsec = usec * 1000; 4217 return abstime; 4218} 4219 4220 4221// Test-and-clear _Event, always leaves _Event set to 0, returns immediately. 4222// Conceptually TryPark() should be equivalent to park(0). 4223 4224int os::PlatformEvent::TryPark() { 4225 for (;;) { 4226 const int v = _Event; 4227 guarantee((v == 0) || (v == 1), "invariant"); 4228 if (Atomic::cmpxchg(0, &_Event, v) == v) return v; 4229 } 4230} 4231 4232void os::PlatformEvent::park() { // AKA "down()" 4233 // Invariant: Only the thread associated with the Event/PlatformEvent 4234 // may call park(). 4235 // TODO: assert that _Assoc != NULL or _Assoc == Self 4236 int v; 4237 for (;;) { 4238 v = _Event; 4239 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4240 } 4241 guarantee(v >= 0, "invariant"); 4242 if (v == 0) { 4243 // Do this the hard way by blocking ... 4244 int status = pthread_mutex_lock(_mutex); 4245 assert_status(status == 0, status, "mutex_lock"); 4246 guarantee(_nParked == 0, "invariant"); 4247 ++_nParked; 4248 while (_Event < 0) { 4249 status = pthread_cond_wait(_cond, _mutex); 4250 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 4251 // Treat this the same as if the wait was interrupted 4252 if (status == ETIMEDOUT) { status = EINTR; } 4253 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 4254 } 4255 --_nParked; 4256 4257 _Event = 0; 4258 status = pthread_mutex_unlock(_mutex); 4259 assert_status(status == 0, status, "mutex_unlock"); 4260 // Paranoia to ensure our locked and lock-free paths interact 4261 // correctly with each other. 4262 OrderAccess::fence(); 4263 } 4264 guarantee(_Event >= 0, "invariant"); 4265} 4266 4267int os::PlatformEvent::park(jlong millis) { 4268 guarantee(_nParked == 0, "invariant"); 4269 4270 int v; 4271 for (;;) { 4272 v = _Event; 4273 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 4274 } 4275 guarantee(v >= 0, "invariant"); 4276 if (v != 0) return OS_OK; 4277 4278 // We do this the hard way, by blocking the thread. 4279 // Consider enforcing a minimum timeout value. 4280 struct timespec abst; 4281 compute_abstime(&abst, millis); 4282 4283 int ret = OS_TIMEOUT; 4284 int status = pthread_mutex_lock(_mutex); 4285 assert_status(status == 0, status, "mutex_lock"); 4286 guarantee(_nParked == 0, "invariant"); 4287 ++_nParked; 4288 4289 // Object.wait(timo) will return because of 4290 // (a) notification 4291 // (b) timeout 4292 // (c) thread.interrupt 4293 // 4294 // Thread.interrupt and object.notify{All} both call Event::set. 4295 // That is, we treat thread.interrupt as a special case of notification. 4296 // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false. 4297 // We assume all ETIME returns are valid. 4298 // 4299 // TODO: properly differentiate simultaneous notify+interrupt. 4300 // In that case, we should propagate the notify to another waiter. 4301 4302 while (_Event < 0) { 4303 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst); 4304 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4305 pthread_cond_destroy(_cond); 4306 pthread_cond_init(_cond, NULL); 4307 } 4308 assert_status(status == 0 || status == EINTR || 4309 status == ETIMEDOUT, 4310 status, "cond_timedwait"); 4311 if (!FilterSpuriousWakeups) break; // previous semantics 4312 if (status == ETIMEDOUT) break; 4313 // We consume and ignore EINTR and spurious wakeups. 4314 } 4315 --_nParked; 4316 if (_Event >= 0) { 4317 ret = OS_OK; 4318 } 4319 _Event = 0; 4320 status = pthread_mutex_unlock(_mutex); 4321 assert_status(status == 0, status, "mutex_unlock"); 4322 assert(_nParked == 0, "invariant"); 4323 // Paranoia to ensure our locked and lock-free paths interact 4324 // correctly with each other. 4325 OrderAccess::fence(); 4326 return ret; 4327} 4328 4329void os::PlatformEvent::unpark() { 4330 // Transitions for _Event: 4331 // 0 :=> 1 4332 // 1 :=> 1 4333 // -1 :=> either 0 or 1; must signal target thread 4334 // That is, we can safely transition _Event from -1 to either 4335 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back 4336 // unpark() calls. 4337 // See also: "Semaphores in Plan 9" by Mullender & Cox 4338 // 4339 // Note: Forcing a transition from "-1" to "1" on an unpark() means 4340 // that it will take two back-to-back park() calls for the owning 4341 // thread to block. This has the benefit of forcing a spurious return 4342 // from the first park() call after an unpark() call which will help 4343 // shake out uses of park() and unpark() without condition variables. 4344 4345 if (Atomic::xchg(1, &_Event) >= 0) return; 4346 4347 // Wait for the thread associated with the event to vacate 4348 int status = pthread_mutex_lock(_mutex); 4349 assert_status(status == 0, status, "mutex_lock"); 4350 int AnyWaiters = _nParked; 4351 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 4352 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 4353 AnyWaiters = 0; 4354 pthread_cond_signal(_cond); 4355 } 4356 status = pthread_mutex_unlock(_mutex); 4357 assert_status(status == 0, status, "mutex_unlock"); 4358 if (AnyWaiters != 0) { 4359 status = pthread_cond_signal(_cond); 4360 assert_status(status == 0, status, "cond_signal"); 4361 } 4362 4363 // Note that we signal() _after dropping the lock for "immortal" Events. 4364 // This is safe and avoids a common class of futile wakeups. In rare 4365 // circumstances this can cause a thread to return prematurely from 4366 // cond_{timed}wait() but the spurious wakeup is benign and the victim will 4367 // simply re-test the condition and re-park itself. 4368} 4369 4370 4371// JSR166 4372// ------------------------------------------------------- 4373 4374/* 4375 * The solaris and bsd implementations of park/unpark are fairly 4376 * conservative for now, but can be improved. They currently use a 4377 * mutex/condvar pair, plus a a count. 4378 * Park decrements count if > 0, else does a condvar wait. Unpark 4379 * sets count to 1 and signals condvar. Only one thread ever waits 4380 * on the condvar. Contention seen when trying to park implies that someone 4381 * is unparking you, so don't wait. And spurious returns are fine, so there 4382 * is no need to track notifications. 4383 */ 4384 4385#define MAX_SECS 100000000 4386/* 4387 * This code is common to bsd and solaris and will be moved to a 4388 * common place in dolphin. 4389 * 4390 * The passed in time value is either a relative time in nanoseconds 4391 * or an absolute time in milliseconds. Either way it has to be unpacked 4392 * into suitable seconds and nanoseconds components and stored in the 4393 * given timespec structure. 4394 * Given time is a 64-bit value and the time_t used in the timespec is only 4395 * a signed-32-bit value (except on 64-bit Bsd) we have to watch for 4396 * overflow if times way in the future are given. Further on Solaris versions 4397 * prior to 10 there is a restriction (see cond_timedwait) that the specified 4398 * number of seconds, in abstime, is less than current_time + 100,000,000. 4399 * As it will be 28 years before "now + 100000000" will overflow we can 4400 * ignore overflow and just impose a hard-limit on seconds using the value 4401 * of "now + 100,000,000". This places a limit on the timeout of about 3.17 4402 * years from "now". 4403 */ 4404 4405static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) { 4406 assert(time > 0, "convertTime"); 4407 4408 struct timeval now; 4409 int status = gettimeofday(&now, NULL); 4410 assert(status == 0, "gettimeofday"); 4411 4412 time_t max_secs = now.tv_sec + MAX_SECS; 4413 4414 if (isAbsolute) { 4415 jlong secs = time / 1000; 4416 if (secs > max_secs) { 4417 absTime->tv_sec = max_secs; 4418 } 4419 else { 4420 absTime->tv_sec = secs; 4421 } 4422 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 4423 } 4424 else { 4425 jlong secs = time / NANOSECS_PER_SEC; 4426 if (secs >= MAX_SECS) { 4427 absTime->tv_sec = max_secs; 4428 absTime->tv_nsec = 0; 4429 } 4430 else { 4431 absTime->tv_sec = now.tv_sec + secs; 4432 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 4433 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 4434 absTime->tv_nsec -= NANOSECS_PER_SEC; 4435 ++absTime->tv_sec; // note: this must be <= max_secs 4436 } 4437 } 4438 } 4439 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 4440 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 4441 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 4442 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 4443} 4444 4445void Parker::park(bool isAbsolute, jlong time) { 4446 // Ideally we'd do something useful while spinning, such 4447 // as calling unpackTime(). 4448 4449 // Optional fast-path check: 4450 // Return immediately if a permit is available. 4451 // We depend on Atomic::xchg() having full barrier semantics 4452 // since we are doing a lock-free update to _counter. 4453 if (Atomic::xchg(0, &_counter) > 0) return; 4454 4455 Thread* thread = Thread::current(); 4456 assert(thread->is_Java_thread(), "Must be JavaThread"); 4457 JavaThread *jt = (JavaThread *)thread; 4458 4459 // Optional optimization -- avoid state transitions if there's an interrupt pending. 4460 // Check interrupt before trying to wait 4461 if (Thread::is_interrupted(thread, false)) { 4462 return; 4463 } 4464 4465 // Next, demultiplex/decode time arguments 4466 struct timespec absTime; 4467 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 4468 return; 4469 } 4470 if (time > 0) { 4471 unpackTime(&absTime, isAbsolute, time); 4472 } 4473 4474 4475 // Enter safepoint region 4476 // Beware of deadlocks such as 6317397. 4477 // The per-thread Parker:: mutex is a classic leaf-lock. 4478 // In particular a thread must never block on the Threads_lock while 4479 // holding the Parker:: mutex. If safepoints are pending both the 4480 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 4481 ThreadBlockInVM tbivm(jt); 4482 4483 // Don't wait if cannot get lock since interference arises from 4484 // unblocking. Also. check interrupt before trying wait 4485 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 4486 return; 4487 } 4488 4489 int status; 4490 if (_counter > 0) { // no wait needed 4491 _counter = 0; 4492 status = pthread_mutex_unlock(_mutex); 4493 assert(status == 0, "invariant"); 4494 // Paranoia to ensure our locked and lock-free paths interact 4495 // correctly with each other and Java-level accesses. 4496 OrderAccess::fence(); 4497 return; 4498 } 4499 4500#ifdef ASSERT 4501 // Don't catch signals while blocked; let the running threads have the signals. 4502 // (This allows a debugger to break into the running thread.) 4503 sigset_t oldsigs; 4504 sigset_t* allowdebug_blocked = os::Bsd::allowdebug_blocked_signals(); 4505 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 4506#endif 4507 4508 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 4509 jt->set_suspend_equivalent(); 4510 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 4511 4512 if (time == 0) { 4513 status = pthread_cond_wait(_cond, _mutex); 4514 } else { 4515 status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &absTime); 4516 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4517 pthread_cond_destroy(_cond); 4518 pthread_cond_init(_cond, NULL); 4519 } 4520 } 4521 assert_status(status == 0 || status == EINTR || 4522 status == ETIMEDOUT, 4523 status, "cond_timedwait"); 4524 4525#ifdef ASSERT 4526 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 4527#endif 4528 4529 _counter = 0; 4530 status = pthread_mutex_unlock(_mutex); 4531 assert_status(status == 0, status, "invariant"); 4532 // Paranoia to ensure our locked and lock-free paths interact 4533 // correctly with each other and Java-level accesses. 4534 OrderAccess::fence(); 4535 4536 // If externally suspended while waiting, re-suspend 4537 if (jt->handle_special_suspend_equivalent_condition()) { 4538 jt->java_suspend_self(); 4539 } 4540} 4541 4542void Parker::unpark() { 4543 int s, status; 4544 status = pthread_mutex_lock(_mutex); 4545 assert(status == 0, "invariant"); 4546 s = _counter; 4547 _counter = 1; 4548 if (s < 1) { 4549 if (WorkAroundNPTLTimedWaitHang) { 4550 status = pthread_cond_signal(_cond); 4551 assert(status == 0, "invariant"); 4552 status = pthread_mutex_unlock(_mutex); 4553 assert(status == 0, "invariant"); 4554 } else { 4555 status = pthread_mutex_unlock(_mutex); 4556 assert(status == 0, "invariant"); 4557 status = pthread_cond_signal(_cond); 4558 assert(status == 0, "invariant"); 4559 } 4560 } else { 4561 pthread_mutex_unlock(_mutex); 4562 assert(status == 0, "invariant"); 4563 } 4564} 4565 4566 4567/* Darwin has no "environ" in a dynamic library. */ 4568#ifdef __APPLE__ 4569#include <crt_externs.h> 4570#define environ (*_NSGetEnviron()) 4571#else 4572extern char** environ; 4573#endif 4574 4575// Run the specified command in a separate process. Return its exit value, 4576// or -1 on failure (e.g. can't fork a new process). 4577// Unlike system(), this function can be called from signal handler. It 4578// doesn't block SIGINT et al. 4579int os::fork_and_exec(char* cmd) { 4580 const char * argv[4] = {"sh", "-c", cmd, NULL}; 4581 4582 // fork() in BsdThreads/NPTL is not async-safe. It needs to run 4583 // pthread_atfork handlers and reset pthread library. All we need is a 4584 // separate process to execve. Make a direct syscall to fork process. 4585 // On IA64 there's no fork syscall, we have to use fork() and hope for 4586 // the best... 4587 pid_t pid = fork(); 4588 4589 if (pid < 0) { 4590 // fork failed 4591 return -1; 4592 4593 } else if (pid == 0) { 4594 // child process 4595 4596 // execve() in BsdThreads will call pthread_kill_other_threads_np() 4597 // first to kill every thread on the thread list. Because this list is 4598 // not reset by fork() (see notes above), execve() will instead kill 4599 // every thread in the parent process. We know this is the only thread 4600 // in the new process, so make a system call directly. 4601 // IA64 should use normal execve() from glibc to match the glibc fork() 4602 // above. 4603 execve("/bin/sh", (char* const*)argv, environ); 4604 4605 // execve failed 4606 _exit(-1); 4607 4608 } else { 4609 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 4610 // care about the actual exit code, for now. 4611 4612 int status; 4613 4614 // Wait for the child process to exit. This returns immediately if 4615 // the child has already exited. */ 4616 while (waitpid(pid, &status, 0) < 0) { 4617 switch (errno) { 4618 case ECHILD: return 0; 4619 case EINTR: break; 4620 default: return -1; 4621 } 4622 } 4623 4624 if (WIFEXITED(status)) { 4625 // The child exited normally; get its exit code. 4626 return WEXITSTATUS(status); 4627 } else if (WIFSIGNALED(status)) { 4628 // The child exited because of a signal 4629 // The best value to return is 0x80 + signal number, 4630 // because that is what all Unix shells do, and because 4631 // it allows callers to distinguish between process exit and 4632 // process death by signal. 4633 return 0x80 + WTERMSIG(status); 4634 } else { 4635 // Unknown exit code; pass it through 4636 return status; 4637 } 4638 } 4639} 4640 4641// is_headless_jre() 4642// 4643// Test for the existence of xawt/libmawt.so or libawt_xawt.so 4644// in order to report if we are running in a headless jre 4645// 4646// Since JDK8 xawt/libmawt.so was moved into the same directory 4647// as libawt.so, and renamed libawt_xawt.so 4648// 4649bool os::is_headless_jre() { 4650#ifdef __APPLE__ 4651 // We no longer build headless-only on Mac OS X 4652 return false; 4653#else 4654 struct stat statbuf; 4655 char buf[MAXPATHLEN]; 4656 char libmawtpath[MAXPATHLEN]; 4657 const char *xawtstr = "/xawt/libmawt" JNI_LIB_SUFFIX; 4658 const char *new_xawtstr = "/libawt_xawt" JNI_LIB_SUFFIX; 4659 char *p; 4660 4661 // Get path to libjvm.so 4662 os::jvm_path(buf, sizeof(buf)); 4663 4664 // Get rid of libjvm.so 4665 p = strrchr(buf, '/'); 4666 if (p == NULL) return false; 4667 else *p = '\0'; 4668 4669 // Get rid of client or server 4670 p = strrchr(buf, '/'); 4671 if (p == NULL) return false; 4672 else *p = '\0'; 4673 4674 // check xawt/libmawt.so 4675 strcpy(libmawtpath, buf); 4676 strcat(libmawtpath, xawtstr); 4677 if (::stat(libmawtpath, &statbuf) == 0) return false; 4678 4679 // check libawt_xawt.so 4680 strcpy(libmawtpath, buf); 4681 strcat(libmawtpath, new_xawtstr); 4682 if (::stat(libmawtpath, &statbuf) == 0) return false; 4683 4684 return true; 4685#endif 4686} 4687 4688// Get the default path to the core file 4689// Returns the length of the string 4690int os::get_core_path(char* buffer, size_t bufferSize) { 4691 int n = jio_snprintf(buffer, bufferSize, "/cores"); 4692 4693 // Truncate if theoretical string was longer than bufferSize 4694 n = MIN2(n, (int)bufferSize); 4695 4696 return n; 4697} 4698 4699#ifndef PRODUCT 4700void TestReserveMemorySpecial_test() { 4701 // No tests available for this platform 4702} 4703#endif 4704