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