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