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