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