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