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