src/os/bsd/vm/os_bsd.cpp

Tue, 17 Oct 2017 12:58:25 +0800

author
aoqi
date
Tue, 17 Oct 2017 12:58:25 +0800
changeset 7994
04ff2f6cd0eb
parent 7824
bbceafdc7a5f
parent 7535
7ae4e26cb1e0
child 9122
024be04bb151
permissions
-rw-r--r--

merge

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

mercurial