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