1 /*
   2  * Copyright (c) 1999, 2020, 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 "jvm.h"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "code/vtableStubs.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/disassembler.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logStream.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "memory/filemap.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "os_bsd.inline.hpp"
  41 #include "os_posix.inline.hpp"
  42 #include "os_share_bsd.hpp"
  43 #include "prims/jniFastGetField.hpp"
  44 #include "prims/jvm_misc.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/atomic.hpp"
  47 #include "runtime/extendedPC.hpp"
  48 #include "runtime/globals.hpp"
  49 #include "runtime/interfaceSupport.inline.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/javaCalls.hpp"
  52 #include "runtime/mutexLocker.hpp"
  53 #include "runtime/objectMonitor.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/perfMemory.hpp"
  56 #include "runtime/semaphore.hpp"
  57 #include "runtime/sharedRuntime.hpp"
  58 #include "runtime/statSampler.hpp"
  59 #include "runtime/stubRoutines.hpp"
  60 #include "runtime/thread.inline.hpp"
  61 #include "runtime/threadCritical.hpp"
  62 #include "runtime/timer.hpp"
  63 #include "services/attachListener.hpp"
  64 #include "services/memTracker.hpp"
  65 #include "services/runtimeService.hpp"
  66 #include "utilities/align.hpp"
  67 #include "utilities/decoder.hpp"
  68 #include "utilities/defaultStream.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/growableArray.hpp"
  71 #include "utilities/vmError.hpp"
  72 
  73 // put OS-includes here
  74 # include <dlfcn.h>
  75 # include <errno.h>
  76 # include <fcntl.h>
  77 # include <inttypes.h>
  78 # include <poll.h>
  79 # include <pthread.h>
  80 # include <pwd.h>
  81 # include <signal.h>
  82 # include <stdint.h>
  83 # include <stdio.h>
  84 # include <string.h>
  85 # include <sys/ioctl.h>
  86 # include <sys/mman.h>
  87 # include <sys/param.h>
  88 # include <sys/resource.h>
  89 # include <sys/socket.h>
  90 # include <sys/stat.h>
  91 # include <sys/syscall.h>
  92 # include <sys/sysctl.h>
  93 # include <sys/time.h>
  94 # include <sys/times.h>
  95 # include <sys/types.h>
  96 # include <sys/wait.h>
  97 # include <time.h>
  98 # include <unistd.h>
  99 
 100 #if defined(__FreeBSD__) || defined(__NetBSD__)
 101   #include <elf.h>
 102 #endif
 103 
 104 #ifdef __APPLE__
 105   #include <mach-o/dyld.h>
 106 #endif
 107 
 108 #ifndef MAP_ANONYMOUS
 109   #define MAP_ANONYMOUS MAP_ANON
 110 #endif
 111 
 112 #define MAX_PATH    (2 * K)
 113 
 114 // for timer info max values which include all bits
 115 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 116 
 117 ////////////////////////////////////////////////////////////////////////////////
 118 // global variables
 119 julong os::Bsd::_physical_memory = 0;
 120 
 121 #ifdef __APPLE__
 122 mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0};
 123 volatile uint64_t         os::Bsd::_max_abstime   = 0;
 124 #else
 125 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
 126 #endif
 127 pthread_t os::Bsd::_main_thread;
 128 int os::Bsd::_page_size = -1;
 129 
 130 static jlong initial_time_count=0;
 131 
 132 static int clock_tics_per_sec = 100;
 133 
 134 // For diagnostics to print a message once. see run_periodic_checks
 135 static sigset_t check_signal_done;
 136 static bool check_signals = true;
 137 
 138 // Signal number used to suspend/resume a thread
 139 
 140 // do not use any signal number less than SIGSEGV, see 4355769
 141 static int SR_signum = SIGUSR2;
 142 sigset_t SR_sigset;
 143 
 144 #ifdef __APPLE__
 145 static const int processor_id_unassigned = -1;
 146 static const int processor_id_assigning = -2;
 147 static const int processor_id_map_size = 256;
 148 static volatile int processor_id_map[processor_id_map_size];
 149 static volatile int processor_id_next = 0;
 150 #endif
 151 
 152 ////////////////////////////////////////////////////////////////////////////////
 153 // utility functions
 154 
 155 static int SR_initialize();
 156 
 157 julong os::available_memory() {
 158   return Bsd::available_memory();
 159 }
 160 
 161 // available here means free
 162 julong os::Bsd::available_memory() {
 163   uint64_t available = physical_memory() >> 2;
 164 #ifdef __APPLE__
 165   mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
 166   vm_statistics64_data_t vmstat;
 167   kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
 168                                          (host_info64_t)&vmstat, &count);
 169   assert(kerr == KERN_SUCCESS,
 170          "host_statistics64 failed - check mach_host_self() and count");
 171   if (kerr == KERN_SUCCESS) {
 172     available = vmstat.free_count * os::vm_page_size();
 173   }
 174 #endif
 175   return available;
 176 }
 177 
 178 // for more info see :
 179 // https://man.openbsd.org/sysctl.2
 180 void os::Bsd::print_uptime_info(outputStream* st) {
 181   struct timeval boottime;
 182   size_t len = sizeof(boottime);
 183   int mib[2];
 184   mib[0] = CTL_KERN;
 185   mib[1] = KERN_BOOTTIME;
 186 
 187   if (sysctl(mib, 2, &boottime, &len, NULL, 0) >= 0) {
 188     time_t bootsec = boottime.tv_sec;
 189     time_t currsec = time(NULL);
 190     os::print_dhm(st, "OS uptime:", (long) difftime(currsec, bootsec));
 191   }
 192 }
 193 
 194 julong os::physical_memory() {
 195   return Bsd::physical_memory();
 196 }
 197 
 198 // Return true if user is running as root.
 199 
 200 bool os::have_special_privileges() {
 201   static bool init = false;
 202   static bool privileges = false;
 203   if (!init) {
 204     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 205     init = true;
 206   }
 207   return privileges;
 208 }
 209 
 210 
 211 
 212 // Cpu architecture string
 213 #if   defined(ZERO)
 214 static char cpu_arch[] = ZERO_LIBARCH;
 215 #elif defined(IA64)
 216 static char cpu_arch[] = "ia64";
 217 #elif defined(IA32)
 218 static char cpu_arch[] = "i386";
 219 #elif defined(AMD64)
 220 static char cpu_arch[] = "amd64";
 221 #elif defined(ARM)
 222 static char cpu_arch[] = "arm";
 223 #elif defined(PPC32)
 224 static char cpu_arch[] = "ppc";
 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   } else {
 251     set_processor_count(1);   // fallback
 252   }
 253 
 254 #ifdef __APPLE__
 255   // initialize processor id map
 256   for (int i = 0; i < processor_id_map_size; i++) {
 257     processor_id_map[i] = processor_id_unassigned;
 258   }
 259 #endif
 260 
 261   // get physical memory via hw.memsize sysctl (hw.memsize is used
 262   // since it returns a 64 bit value)
 263   mib[0] = CTL_HW;
 264 
 265 #if defined (HW_MEMSIZE) // Apple
 266   mib[1] = HW_MEMSIZE;
 267 #elif defined(HW_PHYSMEM) // Most of BSD
 268   mib[1] = HW_PHYSMEM;
 269 #elif defined(HW_REALMEM) // Old FreeBSD
 270   mib[1] = HW_REALMEM;
 271 #else
 272   #error No ways to get physmem
 273 #endif
 274 
 275   len = sizeof(mem_val);
 276   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
 277     assert(len == sizeof(mem_val), "unexpected data size");
 278     _physical_memory = mem_val;
 279   } else {
 280     _physical_memory = 256 * 1024 * 1024;       // fallback (XXXBSD?)
 281   }
 282 
 283 #ifdef __OpenBSD__
 284   {
 285     // limit _physical_memory memory view on OpenBSD since
 286     // datasize rlimit restricts us anyway.
 287     struct rlimit limits;
 288     getrlimit(RLIMIT_DATA, &limits);
 289     _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
 290   }
 291 #endif
 292 }
 293 
 294 #ifdef __APPLE__
 295 static const char *get_home() {
 296   const char *home_dir = ::getenv("HOME");
 297   if ((home_dir == NULL) || (*home_dir == '\0')) {
 298     struct passwd *passwd_info = getpwuid(geteuid());
 299     if (passwd_info != NULL) {
 300       home_dir = passwd_info->pw_dir;
 301     }
 302   }
 303 
 304   return home_dir;
 305 }
 306 #endif
 307 
 308 void os::init_system_properties_values() {
 309   // The next steps are taken in the product version:
 310   //
 311   // Obtain the JAVA_HOME value from the location of libjvm.so.
 312   // This library should be located at:
 313   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 314   //
 315   // If "/jre/lib/" appears at the right place in the path, then we
 316   // assume libjvm.so is installed in a JDK and we use this path.
 317   //
 318   // Otherwise exit with message: "Could not create the Java virtual machine."
 319   //
 320   // The following extra steps are taken in the debugging version:
 321   //
 322   // If "/jre/lib/" does NOT appear at the right place in the path
 323   // instead of exit check for $JAVA_HOME environment variable.
 324   //
 325   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 326   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 327   // it looks like libjvm.so is installed there
 328   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 329   //
 330   // Otherwise exit.
 331   //
 332   // Important note: if the location of libjvm.so changes this
 333   // code needs to be changed accordingly.
 334 
 335   // See ld(1):
 336   //      The linker uses the following search paths to locate required
 337   //      shared libraries:
 338   //        1: ...
 339   //        ...
 340   //        7: The default directories, normally /lib and /usr/lib.
 341 #ifndef DEFAULT_LIBPATH
 342   #ifndef OVERRIDE_LIBPATH
 343     #define DEFAULT_LIBPATH "/lib:/usr/lib"
 344   #else
 345     #define DEFAULT_LIBPATH OVERRIDE_LIBPATH
 346   #endif
 347 #endif
 348 
 349 // Base path of extensions installed on the system.
 350 #define SYS_EXT_DIR     "/usr/java/packages"
 351 #define EXTENSIONS_DIR  "/lib/ext"
 352 
 353 #ifndef __APPLE__
 354 
 355   // Buffer that fits several sprintfs.
 356   // Note that the space for the colon and the trailing null are provided
 357   // by the nulls included by the sizeof operator.
 358   const size_t bufsize =
 359     MAX2((size_t)MAXPATHLEN,  // For dll_dir & friends.
 360          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 361   char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 362 
 363   // sysclasspath, java_home, dll_dir
 364   {
 365     char *pslash;
 366     os::jvm_path(buf, bufsize);
 367 
 368     // Found the full path to libjvm.so.
 369     // Now cut the path to <java_home>/jre if we can.
 370     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 371     pslash = strrchr(buf, '/');
 372     if (pslash != NULL) {
 373       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 374     }
 375     Arguments::set_dll_dir(buf);
 376 
 377     if (pslash != NULL) {
 378       pslash = strrchr(buf, '/');
 379       if (pslash != NULL) {
 380         *pslash = '\0';          // Get rid of /<arch>.
 381         pslash = strrchr(buf, '/');
 382         if (pslash != NULL) {
 383           *pslash = '\0';        // Get rid of /lib.
 384         }
 385       }
 386     }
 387     Arguments::set_java_home(buf);
 388     if (!set_boot_path('/', ':')) {
 389       vm_exit_during_initialization("Failed setting boot class path.", NULL);
 390     }
 391   }
 392 
 393   // Where to look for native libraries.
 394   //
 395   // Note: Due to a legacy implementation, most of the library path
 396   // is set in the launcher. This was to accomodate linking restrictions
 397   // on legacy Bsd implementations (which are no longer supported).
 398   // Eventually, all the library path setting will be done here.
 399   //
 400   // However, to prevent the proliferation of improperly built native
 401   // libraries, the new path component /usr/java/packages is added here.
 402   // Eventually, all the library path setting will be done here.
 403   {
 404     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 405     // should always exist (until the legacy problem cited above is
 406     // addressed).
 407     const char *v = ::getenv("LD_LIBRARY_PATH");
 408     const char *v_colon = ":";
 409     if (v == NULL) { v = ""; v_colon = ""; }
 410     // That's +1 for the colon and +1 for the trailing '\0'.
 411     char *ld_library_path = NEW_C_HEAP_ARRAY(char,
 412                                              strlen(v) + 1 +
 413                                              sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
 414                                              mtInternal);
 415     sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
 416     Arguments::set_library_path(ld_library_path);
 417     FREE_C_HEAP_ARRAY(char, ld_library_path);
 418   }
 419 
 420   // Extensions directories.
 421   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 422   Arguments::set_ext_dirs(buf);
 423 
 424   FREE_C_HEAP_ARRAY(char, buf);
 425 
 426 #else // __APPLE__
 427 
 428   #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
 429   #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
 430 
 431   const char *user_home_dir = get_home();
 432   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
 433   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
 434     sizeof(SYS_EXTENSIONS_DIRS);
 435 
 436   // Buffer that fits several sprintfs.
 437   // Note that the space for the colon and the trailing null are provided
 438   // by the nulls included by the sizeof operator.
 439   const size_t bufsize =
 440     MAX2((size_t)MAXPATHLEN,  // for dll_dir & friends.
 441          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size); // extensions dir
 442   char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 443 
 444   // sysclasspath, java_home, dll_dir
 445   {
 446     char *pslash;
 447     os::jvm_path(buf, bufsize);
 448 
 449     // Found the full path to libjvm.so.
 450     // Now cut the path to <java_home>/jre if we can.
 451     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 452     pslash = strrchr(buf, '/');
 453     if (pslash != NULL) {
 454       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 455     }
 456 #ifdef STATIC_BUILD
 457     strcat(buf, "/lib");
 458 #endif
 459 
 460     Arguments::set_dll_dir(buf);
 461 
 462     if (pslash != NULL) {
 463       pslash = strrchr(buf, '/');
 464       if (pslash != NULL) {
 465         *pslash = '\0';          // Get rid of /lib.
 466       }
 467     }
 468     Arguments::set_java_home(buf);
 469     set_boot_path('/', ':');
 470   }
 471 
 472   // Where to look for native libraries.
 473   //
 474   // Note: Due to a legacy implementation, most of the library path
 475   // is set in the launcher. This was to accomodate linking restrictions
 476   // on legacy Bsd implementations (which are no longer supported).
 477   // Eventually, all the library path setting will be done here.
 478   //
 479   // However, to prevent the proliferation of improperly built native
 480   // libraries, the new path component /usr/java/packages is added here.
 481   // Eventually, all the library path setting will be done here.
 482   {
 483     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 484     // should always exist (until the legacy problem cited above is
 485     // addressed).
 486     // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code
 487     // can specify a directory inside an app wrapper
 488     const char *l = ::getenv("JAVA_LIBRARY_PATH");
 489     const char *l_colon = ":";
 490     if (l == NULL) { l = ""; l_colon = ""; }
 491 
 492     const char *v = ::getenv("DYLD_LIBRARY_PATH");
 493     const char *v_colon = ":";
 494     if (v == NULL) { v = ""; v_colon = ""; }
 495 
 496     // Apple's Java6 has "." at the beginning of java.library.path.
 497     // OpenJDK on Windows has "." at the end of java.library.path.
 498     // OpenJDK on Linux and Solaris don't have "." in java.library.path
 499     // at all. To ease the transition from Apple's Java6 to OpenJDK7,
 500     // "." is appended to the end of java.library.path. Yes, this
 501     // could cause a change in behavior, but Apple's Java6 behavior
 502     // can be achieved by putting "." at the beginning of the
 503     // JAVA_LIBRARY_PATH environment variable.
 504     char *ld_library_path = NEW_C_HEAP_ARRAY(char,
 505                                              strlen(v) + 1 + strlen(l) + 1 +
 506                                              system_ext_size + 3,
 507                                              mtInternal);
 508     sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",
 509             v, v_colon, l, l_colon, user_home_dir);
 510     Arguments::set_library_path(ld_library_path);
 511     FREE_C_HEAP_ARRAY(char, ld_library_path);
 512   }
 513 
 514   // Extensions directories.
 515   //
 516   // Note that the space for the colon and the trailing null are provided
 517   // by the nulls included by the sizeof operator (so actually one byte more
 518   // than necessary is allocated).
 519   sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,
 520           user_home_dir, Arguments::get_java_home());
 521   Arguments::set_ext_dirs(buf);
 522 
 523   FREE_C_HEAP_ARRAY(char, buf);
 524 
 525 #undef SYS_EXTENSIONS_DIR
 526 #undef SYS_EXTENSIONS_DIRS
 527 
 528 #endif // __APPLE__
 529 
 530 #undef SYS_EXT_DIR
 531 #undef EXTENSIONS_DIR
 532 }
 533 
 534 ////////////////////////////////////////////////////////////////////////////////
 535 // breakpoint support
 536 
 537 void os::breakpoint() {
 538   BREAKPOINT;
 539 }
 540 
 541 extern "C" void breakpoint() {
 542   // use debugger to set breakpoint here
 543 }
 544 
 545 ////////////////////////////////////////////////////////////////////////////////
 546 // signal support
 547 
 548 debug_only(static bool signal_sets_initialized = false);
 549 static sigset_t unblocked_sigs, vm_sigs;
 550 
 551 void os::Bsd::signal_sets_init() {
 552   // Should also have an assertion stating we are still single-threaded.
 553   assert(!signal_sets_initialized, "Already initialized");
 554   // Fill in signals that are necessarily unblocked for all threads in
 555   // the VM. Currently, we unblock the following signals:
 556   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
 557   //                         by -Xrs (=ReduceSignalUsage));
 558   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
 559   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
 560   // the dispositions or masks wrt these signals.
 561   // Programs embedding the VM that want to use the above signals for their
 562   // own purposes must, at this time, use the "-Xrs" option to prevent
 563   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
 564   // (See bug 4345157, and other related bugs).
 565   // In reality, though, unblocking these signals is really a nop, since
 566   // these signals are not blocked by default.
 567   sigemptyset(&unblocked_sigs);
 568   sigaddset(&unblocked_sigs, SIGILL);
 569   sigaddset(&unblocked_sigs, SIGSEGV);
 570   sigaddset(&unblocked_sigs, SIGBUS);
 571   sigaddset(&unblocked_sigs, SIGFPE);
 572   sigaddset(&unblocked_sigs, SR_signum);
 573 
 574   if (!ReduceSignalUsage) {
 575     if (!os::Posix::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
 576       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
 577 
 578     }
 579     if (!os::Posix::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
 580       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
 581     }
 582     if (!os::Posix::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
 583       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
 584     }
 585   }
 586   // Fill in signals that are blocked by all but the VM thread.
 587   sigemptyset(&vm_sigs);
 588   if (!ReduceSignalUsage) {
 589     sigaddset(&vm_sigs, BREAK_SIGNAL);
 590   }
 591   debug_only(signal_sets_initialized = true);
 592 
 593 }
 594 
 595 // These are signals that are unblocked while a thread is running Java.
 596 // (For some reason, they get blocked by default.)
 597 sigset_t* os::Bsd::unblocked_signals() {
 598   assert(signal_sets_initialized, "Not initialized");
 599   return &unblocked_sigs;
 600 }
 601 
 602 // These are the signals that are blocked while a (non-VM) thread is
 603 // running Java. Only the VM thread handles these signals.
 604 sigset_t* os::Bsd::vm_signals() {
 605   assert(signal_sets_initialized, "Not initialized");
 606   return &vm_sigs;
 607 }
 608 
 609 void os::Bsd::hotspot_sigmask(Thread* thread) {
 610 
 611   //Save caller's signal mask before setting VM signal mask
 612   sigset_t caller_sigmask;
 613   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
 614 
 615   OSThread* osthread = thread->osthread();
 616   osthread->set_caller_sigmask(caller_sigmask);
 617 
 618   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
 619 
 620   if (!ReduceSignalUsage) {
 621     if (thread->is_VM_thread()) {
 622       // Only the VM thread handles BREAK_SIGNAL ...
 623       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 624     } else {
 625       // ... all other threads block BREAK_SIGNAL
 626       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 627     }
 628   }
 629 }
 630 
 631 
 632 //////////////////////////////////////////////////////////////////////////////
 633 // create new thread
 634 
 635 #ifdef __APPLE__
 636 // library handle for calling objc_registerThreadWithCollector()
 637 // without static linking to the libobjc library
 638   #define OBJC_LIB "/usr/lib/libobjc.dylib"
 639   #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
 640 typedef void (*objc_registerThreadWithCollector_t)();
 641 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
 642 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
 643 #endif
 644 
 645 // Thread start routine for all newly created threads
 646 static void *thread_native_entry(Thread *thread) {
 647 
 648   thread->record_stack_base_and_size();
 649 
 650   // Try to randomize the cache line index of hot stack frames.
 651   // This helps when threads of the same stack traces evict each other's
 652   // cache lines. The threads can be either from the same JVM instance, or
 653   // from different JVM instances. The benefit is especially true for
 654   // processors with hyperthreading technology.
 655   static int counter = 0;
 656   int pid = os::current_process_id();
 657   alloca(((pid ^ counter++) & 7) * 128);
 658 
 659   thread->initialize_thread_current();
 660 
 661   OSThread* osthread = thread->osthread();
 662   Monitor* sync = osthread->startThread_lock();
 663 
 664   osthread->set_thread_id(os::Bsd::gettid());
 665 
 666   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 667     os::current_thread_id(), (uintx) pthread_self());
 668 
 669 #ifdef __APPLE__
 670   // Store unique OS X thread id used by SA
 671   osthread->set_unique_thread_id();
 672 #endif
 673 
 674   // initialize signal mask for this thread
 675   os::Bsd::hotspot_sigmask(thread);
 676 
 677   // initialize floating point control register
 678   os::Bsd::init_thread_fpu_state();
 679 
 680 #ifdef __APPLE__
 681   // register thread with objc gc
 682   if (objc_registerThreadWithCollectorFunction != NULL) {
 683     objc_registerThreadWithCollectorFunction();
 684   }
 685 #endif
 686 
 687   // handshaking with parent thread
 688   {
 689     MutexLocker ml(sync, Mutex::_no_safepoint_check_flag);
 690 
 691     // notify parent thread
 692     osthread->set_state(INITIALIZED);
 693     sync->notify_all();
 694 
 695     // wait until os::start_thread()
 696     while (osthread->get_state() == INITIALIZED) {
 697       sync->wait_without_safepoint_check();
 698     }
 699   }
 700 
 701   // call one more level start routine
 702   thread->call_run();
 703 
 704   // Note: at this point the thread object may already have deleted itself.
 705   // Prevent dereferencing it from here on out.
 706   thread = NULL;
 707 
 708   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 709     os::current_thread_id(), (uintx) pthread_self());
 710 
 711   return 0;
 712 }
 713 
 714 bool os::create_thread(Thread* thread, ThreadType thr_type,
 715                        size_t req_stack_size) {
 716   assert(thread->osthread() == NULL, "caller responsible");
 717 
 718   // Allocate the OSThread object
 719   OSThread* osthread = new OSThread(NULL, NULL);
 720   if (osthread == NULL) {
 721     return false;
 722   }
 723 
 724   // set the correct thread state
 725   osthread->set_thread_type(thr_type);
 726 
 727   // Initial state is ALLOCATED but not INITIALIZED
 728   osthread->set_state(ALLOCATED);
 729 
 730   thread->set_osthread(osthread);
 731 
 732   // init thread attributes
 733   pthread_attr_t attr;
 734   pthread_attr_init(&attr);
 735   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 736 
 737   // calculate stack size if it's not specified by caller
 738   size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 739   int status = pthread_attr_setstacksize(&attr, stack_size);
 740   assert_status(status == 0, status, "pthread_attr_setstacksize");
 741 
 742   ThreadState state;
 743 
 744   {
 745     pthread_t tid;
 746     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);
 747 
 748     char buf[64];
 749     if (ret == 0) {
 750       log_info(os, thread)("Thread started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
 751         (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 752     } else {
 753       log_warning(os, thread)("Failed to start thread - pthread_create failed (%s) for attributes: %s.",
 754         os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 755       // Log some OS information which might explain why creating the thread failed.
 756       log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());
 757       LogStream st(Log(os, thread)::info());
 758       os::Posix::print_rlimit_info(&st);
 759       os::print_memory_info(&st);
 760     }
 761 
 762     pthread_attr_destroy(&attr);
 763 
 764     if (ret != 0) {
 765       // Need to clean up stuff we've allocated so far
 766       thread->set_osthread(NULL);
 767       delete osthread;
 768       return false;
 769     }
 770 
 771     // Store pthread info into the OSThread
 772     osthread->set_pthread_id(tid);
 773 
 774     // Wait until child thread is either initialized or aborted
 775     {
 776       Monitor* sync_with_child = osthread->startThread_lock();
 777       MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 778       while ((state = osthread->get_state()) == ALLOCATED) {
 779         sync_with_child->wait_without_safepoint_check();
 780       }
 781     }
 782 
 783   }
 784 
 785   // Aborted due to thread limit being reached
 786   if (state == ZOMBIE) {
 787     thread->set_osthread(NULL);
 788     delete osthread;
 789     return false;
 790   }
 791 
 792   // The thread is returned suspended (in state INITIALIZED),
 793   // and is started higher up in the call chain
 794   assert(state == INITIALIZED, "race condition");
 795   return true;
 796 }
 797 
 798 /////////////////////////////////////////////////////////////////////////////
 799 // attach existing thread
 800 
 801 // bootstrap the main thread
 802 bool os::create_main_thread(JavaThread* thread) {
 803   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
 804   return create_attached_thread(thread);
 805 }
 806 
 807 bool os::create_attached_thread(JavaThread* thread) {
 808 #ifdef ASSERT
 809   thread->verify_not_published();
 810 #endif
 811 
 812   // Allocate the OSThread object
 813   OSThread* osthread = new OSThread(NULL, NULL);
 814 
 815   if (osthread == NULL) {
 816     return false;
 817   }
 818 
 819   osthread->set_thread_id(os::Bsd::gettid());
 820 
 821 #ifdef __APPLE__
 822   // Store unique OS X thread id used by SA
 823   osthread->set_unique_thread_id();
 824 #endif
 825 
 826   // Store pthread info into the OSThread
 827   osthread->set_pthread_id(::pthread_self());
 828 
 829   // initialize floating point control register
 830   os::Bsd::init_thread_fpu_state();
 831 
 832   // Initial thread state is RUNNABLE
 833   osthread->set_state(RUNNABLE);
 834 
 835   thread->set_osthread(osthread);
 836 
 837   // initialize signal mask for this thread
 838   // and save the caller's signal mask
 839   os::Bsd::hotspot_sigmask(thread);
 840 
 841   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 842     os::current_thread_id(), (uintx) pthread_self());
 843 
 844   return true;
 845 }
 846 
 847 void os::pd_start_thread(Thread* thread) {
 848   OSThread * osthread = thread->osthread();
 849   assert(osthread->get_state() != INITIALIZED, "just checking");
 850   Monitor* sync_with_child = osthread->startThread_lock();
 851   MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 852   sync_with_child->notify();
 853 }
 854 
 855 // Free Bsd resources related to the OSThread
 856 void os::free_thread(OSThread* osthread) {
 857   assert(osthread != NULL, "osthread not set");
 858 
 859   // We are told to free resources of the argument thread,
 860   // but we can only really operate on the current thread.
 861   assert(Thread::current()->osthread() == osthread,
 862          "os::free_thread but not current thread");
 863 
 864   // Restore caller's signal mask
 865   sigset_t sigmask = osthread->caller_sigmask();
 866   pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
 867 
 868   delete osthread;
 869 }
 870 
 871 ////////////////////////////////////////////////////////////////////////////////
 872 // time support
 873 
 874 // Time since start-up in seconds to a fine granularity.
 875 // Used by VMSelfDestructTimer and the MemProfiler.
 876 double os::elapsedTime() {
 877 
 878   return ((double)os::elapsed_counter()) / os::elapsed_frequency();
 879 }
 880 
 881 jlong os::elapsed_counter() {
 882   return javaTimeNanos() - initial_time_count;
 883 }
 884 
 885 jlong os::elapsed_frequency() {
 886   return NANOSECS_PER_SEC; // nanosecond resolution
 887 }
 888 
 889 bool os::supports_vtime() { return true; }
 890 
 891 double os::elapsedVTime() {
 892   // better than nothing, but not much
 893   return elapsedTime();
 894 }
 895 
 896 jlong os::javaTimeMillis() {
 897   timeval time;
 898   int status = gettimeofday(&time, NULL);
 899   assert(status != -1, "bsd error");
 900   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
 901 }
 902 
 903 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
 904   timeval time;
 905   int status = gettimeofday(&time, NULL);
 906   assert(status != -1, "bsd error");
 907   seconds = jlong(time.tv_sec);
 908   nanos = jlong(time.tv_usec) * 1000;
 909 }
 910 
 911 #ifndef __APPLE__
 912   #ifndef CLOCK_MONOTONIC
 913     #define CLOCK_MONOTONIC (1)
 914   #endif
 915 #endif
 916 
 917 #ifdef __APPLE__
 918 void os::Bsd::clock_init() {
 919   mach_timebase_info(&_timebase_info);
 920 }
 921 #else
 922 void os::Bsd::clock_init() {
 923   struct timespec res;
 924   struct timespec tp;
 925   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
 926       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
 927     // yes, monotonic clock is supported
 928     _clock_gettime = ::clock_gettime;
 929   }
 930 }
 931 #endif
 932 
 933 
 934 
 935 #ifdef __APPLE__
 936 
 937 jlong os::javaTimeNanos() {
 938   const uint64_t tm = mach_absolute_time();
 939   const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
 940   const uint64_t prev = Bsd::_max_abstime;
 941   if (now <= prev) {
 942     return prev;   // same or retrograde time;
 943   }
 944   const uint64_t obsv = Atomic::cmpxchg(&Bsd::_max_abstime, prev, now);
 945   assert(obsv >= prev, "invariant");   // Monotonicity
 946   // If the CAS succeeded then we're done and return "now".
 947   // If the CAS failed and the observed value "obsv" is >= now then
 948   // we should return "obsv".  If the CAS failed and now > obsv > prv then
 949   // some other thread raced this thread and installed a new value, in which case
 950   // we could either (a) retry the entire operation, (b) retry trying to install now
 951   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
 952   // we might discard a higher "now" value in deference to a slightly lower but freshly
 953   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
 954   // to (a) or (b) -- and greatly reduces coherence traffic.
 955   // We might also condition (c) on the magnitude of the delta between obsv and now.
 956   // Avoiding excessive CAS operations to hot RW locations is critical.
 957   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
 958   return (prev == obsv) ? now : obsv;
 959 }
 960 
 961 #else // __APPLE__
 962 
 963 jlong os::javaTimeNanos() {
 964   if (os::supports_monotonic_clock()) {
 965     struct timespec tp;
 966     int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);
 967     assert(status == 0, "gettime error");
 968     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
 969     return result;
 970   } else {
 971     timeval time;
 972     int status = gettimeofday(&time, NULL);
 973     assert(status != -1, "bsd error");
 974     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
 975     return 1000 * usecs;
 976   }
 977 }
 978 
 979 #endif // __APPLE__
 980 
 981 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
 982   if (os::supports_monotonic_clock()) {
 983     info_ptr->max_value = ALL_64_BITS;
 984 
 985     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
 986     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
 987     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
 988   } else {
 989     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
 990     info_ptr->max_value = ALL_64_BITS;
 991 
 992     // gettimeofday is a real time clock so it skips
 993     info_ptr->may_skip_backward = true;
 994     info_ptr->may_skip_forward = true;
 995   }
 996 
 997   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
 998 }
 999 
1000 // Return the real, user, and system times in seconds from an
1001 // arbitrary fixed point in the past.
1002 bool os::getTimesSecs(double* process_real_time,
1003                       double* process_user_time,
1004                       double* process_system_time) {
1005   struct tms ticks;
1006   clock_t real_ticks = times(&ticks);
1007 
1008   if (real_ticks == (clock_t) (-1)) {
1009     return false;
1010   } else {
1011     double ticks_per_second = (double) clock_tics_per_sec;
1012     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1013     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1014     *process_real_time = ((double) real_ticks) / ticks_per_second;
1015 
1016     return true;
1017   }
1018 }
1019 
1020 
1021 char * os::local_time_string(char *buf, size_t buflen) {
1022   struct tm t;
1023   time_t long_time;
1024   time(&long_time);
1025   localtime_r(&long_time, &t);
1026   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1027                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1028                t.tm_hour, t.tm_min, t.tm_sec);
1029   return buf;
1030 }
1031 
1032 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
1033   return localtime_r(clock, res);
1034 }
1035 
1036 ////////////////////////////////////////////////////////////////////////////////
1037 // runtime exit support
1038 
1039 // Note: os::shutdown() might be called very early during initialization, or
1040 // called from signal handler. Before adding something to os::shutdown(), make
1041 // sure it is async-safe and can handle partially initialized VM.
1042 void os::shutdown() {
1043 
1044   // allow PerfMemory to attempt cleanup of any persistent resources
1045   perfMemory_exit();
1046 
1047   // needs to remove object in file system
1048   AttachListener::abort();
1049 
1050   // flush buffered output, finish log files
1051   ostream_abort();
1052 
1053   // Check for abort hook
1054   abort_hook_t abort_hook = Arguments::abort_hook();
1055   if (abort_hook != NULL) {
1056     abort_hook();
1057   }
1058 
1059 }
1060 
1061 // Note: os::abort() might be called very early during initialization, or
1062 // called from signal handler. Before adding something to os::abort(), make
1063 // sure it is async-safe and can handle partially initialized VM.
1064 void os::abort(bool dump_core, void* siginfo, const void* context) {
1065   os::shutdown();
1066   if (dump_core) {
1067 #ifndef PRODUCT
1068     fdStream out(defaultStream::output_fd());
1069     out.print_raw("Current thread is ");
1070     char buf[16];
1071     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1072     out.print_raw_cr(buf);
1073     out.print_raw_cr("Dumping core ...");
1074 #endif
1075     ::abort(); // dump core
1076   }
1077 
1078   ::exit(1);
1079 }
1080 
1081 // Die immediately, no exit hook, no abort hook, no cleanup.
1082 // Dump a core file, if possible, for debugging.
1083 void os::die() {
1084   if (TestUnresponsiveErrorHandler && !CreateCoredumpOnCrash) {
1085     // For TimeoutInErrorHandlingTest.java, we just kill the VM
1086     // and don't take the time to generate a core file.
1087     os::signal_raise(SIGKILL);
1088   } else {
1089     // _exit() on BsdThreads only kills current thread
1090     ::abort();
1091   }
1092 }
1093 
1094 // Information of current thread in variety of formats
1095 pid_t os::Bsd::gettid() {
1096   int retval = -1;
1097 
1098 #ifdef __APPLE__ // XNU kernel
1099   mach_port_t port = mach_thread_self();
1100   guarantee(MACH_PORT_VALID(port), "just checking");
1101   mach_port_deallocate(mach_task_self(), port);
1102   return (pid_t)port;
1103 
1104 #else
1105   #ifdef __FreeBSD__
1106   retval = syscall(SYS_thr_self);
1107   #else
1108     #ifdef __OpenBSD__
1109   retval = syscall(SYS_getthrid);
1110     #else
1111       #ifdef __NetBSD__
1112   retval = (pid_t) syscall(SYS__lwp_self);
1113       #endif
1114     #endif
1115   #endif
1116 #endif
1117 
1118   if (retval == -1) {
1119     return getpid();
1120   }
1121 }
1122 
1123 intx os::current_thread_id() {
1124 #ifdef __APPLE__
1125   return (intx)os::Bsd::gettid();
1126 #else
1127   return (intx)::pthread_self();
1128 #endif
1129 }
1130 
1131 int os::current_process_id() {
1132   return (int)(getpid());
1133 }
1134 
1135 // DLL functions
1136 
1137 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1138 
1139 // This must be hard coded because it's the system's temporary
1140 // directory not the java application's temp directory, ala java.io.tmpdir.
1141 #ifdef __APPLE__
1142 // macosx has a secure per-user temporary directory
1143 char temp_path_storage[PATH_MAX];
1144 const char* os::get_temp_directory() {
1145   static char *temp_path = NULL;
1146   if (temp_path == NULL) {
1147     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1148     if (pathSize == 0 || pathSize > PATH_MAX) {
1149       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1150     }
1151     temp_path = temp_path_storage;
1152   }
1153   return temp_path;
1154 }
1155 #else // __APPLE__
1156 const char* os::get_temp_directory() { return "/tmp"; }
1157 #endif // __APPLE__
1158 
1159 // check if addr is inside libjvm.so
1160 bool os::address_is_in_vm(address addr) {
1161   static address libjvm_base_addr;
1162   Dl_info dlinfo;
1163 
1164   if (libjvm_base_addr == NULL) {
1165     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1166       libjvm_base_addr = (address)dlinfo.dli_fbase;
1167     }
1168     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1169   }
1170 
1171   if (dladdr((void *)addr, &dlinfo) != 0) {
1172     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1173   }
1174 
1175   return false;
1176 }
1177 
1178 
1179 #define MACH_MAXSYMLEN 256
1180 
1181 bool os::dll_address_to_function_name(address addr, char *buf,
1182                                       int buflen, int *offset,
1183                                       bool demangle) {
1184   // buf is not optional, but offset is optional
1185   assert(buf != NULL, "sanity check");
1186 
1187   Dl_info dlinfo;
1188   char localbuf[MACH_MAXSYMLEN];
1189 
1190   if (dladdr((void*)addr, &dlinfo) != 0) {
1191     // see if we have a matching symbol
1192     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1193       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1194         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1195       }
1196       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1197       return true;
1198     }
1199     // no matching symbol so try for just file info
1200     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1201       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1202                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1203         return true;
1204       }
1205     }
1206 
1207     // Handle non-dynamic manually:
1208     if (dlinfo.dli_fbase != NULL &&
1209         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1210                         dlinfo.dli_fbase)) {
1211       if (!(demangle && Decoder::demangle(localbuf, buf, buflen))) {
1212         jio_snprintf(buf, buflen, "%s", localbuf);
1213       }
1214       return true;
1215     }
1216   }
1217   buf[0] = '\0';
1218   if (offset != NULL) *offset = -1;
1219   return false;
1220 }
1221 
1222 // ported from solaris version
1223 bool os::dll_address_to_library_name(address addr, char* buf,
1224                                      int buflen, int* offset) {
1225   // buf is not optional, but offset is optional
1226   assert(buf != NULL, "sanity check");
1227 
1228   Dl_info dlinfo;
1229 
1230   if (dladdr((void*)addr, &dlinfo) != 0) {
1231     if (dlinfo.dli_fname != NULL) {
1232       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1233     }
1234     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1235       *offset = addr - (address)dlinfo.dli_fbase;
1236     }
1237     return true;
1238   }
1239 
1240   buf[0] = '\0';
1241   if (offset) *offset = -1;
1242   return false;
1243 }
1244 
1245 // Loads .dll/.so and
1246 // in case of error it checks if .dll/.so was built for the
1247 // same architecture as Hotspot is running on
1248 
1249 #ifdef __APPLE__
1250 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1251 #ifdef STATIC_BUILD
1252   return os::get_default_process_handle();
1253 #else
1254   log_info(os)("attempting shared library load of %s", filename);
1255 
1256   void * result= ::dlopen(filename, RTLD_LAZY);
1257   if (result != NULL) {
1258     Events::log(NULL, "Loaded shared library %s", filename);
1259     // Successful loading
1260     log_info(os)("shared library load of %s was successful", filename);
1261     return result;
1262   }
1263 
1264   const char* error_report = ::dlerror();
1265   if (error_report == NULL) {
1266     error_report = "dlerror returned no error description";
1267   }
1268   if (ebuf != NULL && ebuflen > 0) {
1269     // Read system error message into ebuf
1270     ::strncpy(ebuf, error_report, ebuflen-1);
1271     ebuf[ebuflen-1]='\0';
1272   }
1273   Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1274   log_info(os)("shared library load of %s failed, %s", filename, error_report);
1275 
1276   return NULL;
1277 #endif // STATIC_BUILD
1278 }
1279 #else
1280 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1281 #ifdef STATIC_BUILD
1282   return os::get_default_process_handle();
1283 #else
1284   log_info(os)("attempting shared library load of %s", filename);
1285   void * result= ::dlopen(filename, RTLD_LAZY);
1286   if (result != NULL) {
1287     Events::log(NULL, "Loaded shared library %s", filename);
1288     // Successful loading
1289     log_info(os)("shared library load of %s was successful", filename);
1290     return result;
1291   }
1292 
1293   Elf32_Ehdr elf_head;
1294 
1295   const char* const error_report = ::dlerror();
1296   if (error_report == NULL) {
1297     error_report = "dlerror returned no error description";
1298   }
1299   if (ebuf != NULL && ebuflen > 0) {
1300     // Read system error message into ebuf
1301     ::strncpy(ebuf, error_report, ebuflen-1);
1302     ebuf[ebuflen-1]='\0';
1303   }
1304   Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1305   log_info(os)("shared library load of %s failed, %s", filename, error_report);
1306 
1307   int diag_msg_max_length=ebuflen-strlen(ebuf);
1308   char* diag_msg_buf=ebuf+strlen(ebuf);
1309 
1310   if (diag_msg_max_length==0) {
1311     // No more space in ebuf for additional diagnostics message
1312     return NULL;
1313   }
1314 
1315 
1316   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1317 
1318   if (file_descriptor < 0) {
1319     // Can't open library, report dlerror() message
1320     return NULL;
1321   }
1322 
1323   bool failed_to_read_elf_head=
1324     (sizeof(elf_head)!=
1325      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1326 
1327   ::close(file_descriptor);
1328   if (failed_to_read_elf_head) {
1329     // file i/o error - report dlerror() msg
1330     return NULL;
1331   }
1332 
1333   typedef struct {
1334     Elf32_Half  code;         // Actual value as defined in elf.h
1335     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1336     char        elf_class;    // 32 or 64 bit
1337     char        endianess;    // MSB or LSB
1338     char*       name;         // String representation
1339   } arch_t;
1340 
1341   #ifndef EM_486
1342     #define EM_486          6               /* Intel 80486 */
1343   #endif
1344 
1345   #ifndef EM_MIPS_RS3_LE
1346     #define EM_MIPS_RS3_LE  10              /* MIPS */
1347   #endif
1348 
1349   #ifndef EM_PPC64
1350     #define EM_PPC64        21              /* PowerPC64 */
1351   #endif
1352 
1353   #ifndef EM_S390
1354     #define EM_S390         22              /* IBM System/390 */
1355   #endif
1356 
1357   #ifndef EM_IA_64
1358     #define EM_IA_64        50              /* HP/Intel IA-64 */
1359   #endif
1360 
1361   #ifndef EM_X86_64
1362     #define EM_X86_64       62              /* AMD x86-64 */
1363   #endif
1364 
1365   static const arch_t arch_array[]={
1366     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1367     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1368     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1369     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1370     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1371     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1372     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1373     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1374     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1375     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1376     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1377     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1378     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1379   };
1380 
1381   #if  (defined IA32)
1382   static  Elf32_Half running_arch_code=EM_386;
1383   #elif   (defined AMD64)
1384   static  Elf32_Half running_arch_code=EM_X86_64;
1385   #elif  (defined IA64)
1386   static  Elf32_Half running_arch_code=EM_IA_64;
1387   #elif  (defined __powerpc64__)
1388   static  Elf32_Half running_arch_code=EM_PPC64;
1389   #elif  (defined __powerpc__)
1390   static  Elf32_Half running_arch_code=EM_PPC;
1391   #elif  (defined ARM)
1392   static  Elf32_Half running_arch_code=EM_ARM;
1393   #elif  (defined S390)
1394   static  Elf32_Half running_arch_code=EM_S390;
1395   #elif  (defined ALPHA)
1396   static  Elf32_Half running_arch_code=EM_ALPHA;
1397   #elif  (defined MIPSEL)
1398   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1399   #elif  (defined PARISC)
1400   static  Elf32_Half running_arch_code=EM_PARISC;
1401   #elif  (defined MIPS)
1402   static  Elf32_Half running_arch_code=EM_MIPS;
1403   #elif  (defined M68K)
1404   static  Elf32_Half running_arch_code=EM_68K;
1405   #else
1406     #error Method os::dll_load requires that one of following is defined:\
1407          IA32, AMD64, IA64, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1408   #endif
1409 
1410   // Identify compatability class for VM's architecture and library's architecture
1411   // Obtain string descriptions for architectures
1412 
1413   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1414   int running_arch_index=-1;
1415 
1416   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1417     if (running_arch_code == arch_array[i].code) {
1418       running_arch_index    = i;
1419     }
1420     if (lib_arch.code == arch_array[i].code) {
1421       lib_arch.compat_class = arch_array[i].compat_class;
1422       lib_arch.name         = arch_array[i].name;
1423     }
1424   }
1425 
1426   assert(running_arch_index != -1,
1427          "Didn't find running architecture code (running_arch_code) in arch_array");
1428   if (running_arch_index == -1) {
1429     // Even though running architecture detection failed
1430     // we may still continue with reporting dlerror() message
1431     return NULL;
1432   }
1433 
1434   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1435     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1436     return NULL;
1437   }
1438 
1439 #ifndef S390
1440   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1441     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1442     return NULL;
1443   }
1444 #endif // !S390
1445 
1446   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1447     if (lib_arch.name!=NULL) {
1448       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1449                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1450                  lib_arch.name, arch_array[running_arch_index].name);
1451     } else {
1452       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1453                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1454                  lib_arch.code,
1455                  arch_array[running_arch_index].name);
1456     }
1457   }
1458 
1459   return NULL;
1460 #endif // STATIC_BUILD
1461 }
1462 #endif // !__APPLE__
1463 
1464 void* os::get_default_process_handle() {
1465 #ifdef __APPLE__
1466   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
1467   // to avoid finding unexpected symbols on second (or later)
1468   // loads of a library.
1469   return (void*)::dlopen(NULL, RTLD_FIRST);
1470 #else
1471   return (void*)::dlopen(NULL, RTLD_LAZY);
1472 #endif
1473 }
1474 
1475 // XXX: Do we need a lock around this as per Linux?
1476 void* os::dll_lookup(void* handle, const char* name) {
1477   return dlsym(handle, name);
1478 }
1479 
1480 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1481   outputStream * out = (outputStream *) param;
1482   out->print_cr(INTPTR_FORMAT " \t%s", (intptr_t)base_address, name);
1483   return 0;
1484 }
1485 
1486 void os::print_dll_info(outputStream *st) {
1487   st->print_cr("Dynamic libraries:");
1488   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1489     st->print_cr("Error: Cannot print dynamic libraries.");
1490   }
1491 }
1492 
1493 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1494 #ifdef RTLD_DI_LINKMAP
1495   Dl_info dli;
1496   void *handle;
1497   Link_map *map;
1498   Link_map *p;
1499 
1500   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1501       dli.dli_fname == NULL) {
1502     return 1;
1503   }
1504   handle = dlopen(dli.dli_fname, RTLD_LAZY);
1505   if (handle == NULL) {
1506     return 1;
1507   }
1508   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1509   if (map == NULL) {
1510     dlclose(handle);
1511     return 1;
1512   }
1513 
1514   while (map->l_prev != NULL)
1515     map = map->l_prev;
1516 
1517   while (map != NULL) {
1518     // Value for top_address is returned as 0 since we don't have any information about module size
1519     if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1520       dlclose(handle);
1521       return 1;
1522     }
1523     map = map->l_next;
1524   }
1525 
1526   dlclose(handle);
1527 #elif defined(__APPLE__)
1528   for (uint32_t i = 1; i < _dyld_image_count(); i++) {
1529     // Value for top_address is returned as 0 since we don't have any information about module size
1530     if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {
1531       return 1;
1532     }
1533   }
1534   return 0;
1535 #else
1536   return 1;
1537 #endif
1538 }
1539 
1540 void os::get_summary_os_info(char* buf, size_t buflen) {
1541   // These buffers are small because we want this to be brief
1542   // and not use a lot of stack while generating the hs_err file.
1543   char os[100];
1544   size_t size = sizeof(os);
1545   int mib_kern[] = { CTL_KERN, KERN_OSTYPE };
1546   if (sysctl(mib_kern, 2, os, &size, NULL, 0) < 0) {
1547 #ifdef __APPLE__
1548       strncpy(os, "Darwin", sizeof(os));
1549 #elif __OpenBSD__
1550       strncpy(os, "OpenBSD", sizeof(os));
1551 #else
1552       strncpy(os, "BSD", sizeof(os));
1553 #endif
1554   }
1555 
1556   char release[100];
1557   size = sizeof(release);
1558   int mib_release[] = { CTL_KERN, KERN_OSRELEASE };
1559   if (sysctl(mib_release, 2, release, &size, NULL, 0) < 0) {
1560       // if error, leave blank
1561       strncpy(release, "", sizeof(release));
1562   }
1563   snprintf(buf, buflen, "%s %s", os, release);
1564 }
1565 
1566 void os::print_os_info_brief(outputStream* st) {
1567   os::Posix::print_uname_info(st);
1568 }
1569 
1570 void os::print_os_info(outputStream* st) {
1571   st->print("OS:");
1572 
1573   os::Posix::print_uname_info(st);
1574 
1575   os::Bsd::print_uptime_info(st);
1576 
1577   os::Posix::print_rlimit_info(st);
1578 
1579   os::Posix::print_load_average(st);
1580 
1581   VM_Version::print_platform_virtualization_info(st);
1582 }
1583 
1584 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1585   // Nothing to do for now.
1586 }
1587 
1588 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1589   unsigned int mhz;
1590   size_t size = sizeof(mhz);
1591   int mib[] = { CTL_HW, HW_CPU_FREQ };
1592   if (sysctl(mib, 2, &mhz, &size, NULL, 0) < 0) {
1593     mhz = 1;  // looks like an error but can be divided by
1594   } else {
1595     mhz /= 1000000;  // reported in millions
1596   }
1597 
1598   char model[100];
1599   size = sizeof(model);
1600   int mib_model[] = { CTL_HW, HW_MODEL };
1601   if (sysctl(mib_model, 2, model, &size, NULL, 0) < 0) {
1602     strncpy(model, cpu_arch, sizeof(model));
1603   }
1604 
1605   char machine[100];
1606   size = sizeof(machine);
1607   int mib_machine[] = { CTL_HW, HW_MACHINE };
1608   if (sysctl(mib_machine, 2, machine, &size, NULL, 0) < 0) {
1609       strncpy(machine, "", sizeof(machine));
1610   }
1611 
1612   snprintf(buf, buflen, "%s %s %d MHz", model, machine, mhz);
1613 }
1614 
1615 void os::print_memory_info(outputStream* st) {
1616   xsw_usage swap_usage;
1617   size_t size = sizeof(swap_usage);
1618 
1619   st->print("Memory:");
1620   st->print(" %dk page", os::vm_page_size()>>10);
1621 
1622   st->print(", physical " UINT64_FORMAT "k",
1623             os::physical_memory() >> 10);
1624   st->print("(" UINT64_FORMAT "k free)",
1625             os::available_memory() >> 10);
1626 
1627   if((sysctlbyname("vm.swapusage", &swap_usage, &size, NULL, 0) == 0) || (errno == ENOMEM)) {
1628     if (size >= offset_of(xsw_usage, xsu_used)) {
1629       st->print(", swap " UINT64_FORMAT "k",
1630                 ((julong) swap_usage.xsu_total) >> 10);
1631       st->print("(" UINT64_FORMAT "k free)",
1632                 ((julong) swap_usage.xsu_avail) >> 10);
1633     }
1634   }
1635 
1636   st->cr();
1637 }
1638 
1639 static void print_signal_handler(outputStream* st, int sig,
1640                                  char* buf, size_t buflen);
1641 
1642 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1643   st->print_cr("Signal Handlers:");
1644   print_signal_handler(st, SIGSEGV, buf, buflen);
1645   print_signal_handler(st, SIGBUS , buf, buflen);
1646   print_signal_handler(st, SIGFPE , buf, buflen);
1647   print_signal_handler(st, SIGPIPE, buf, buflen);
1648   print_signal_handler(st, SIGXFSZ, buf, buflen);
1649   print_signal_handler(st, SIGILL , buf, buflen);
1650   print_signal_handler(st, SR_signum, buf, buflen);
1651   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1652   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1653   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1654   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1655 }
1656 
1657 static char saved_jvm_path[MAXPATHLEN] = {0};
1658 
1659 // Find the full path to the current module, libjvm
1660 void os::jvm_path(char *buf, jint buflen) {
1661   // Error checking.
1662   if (buflen < MAXPATHLEN) {
1663     assert(false, "must use a large-enough buffer");
1664     buf[0] = '\0';
1665     return;
1666   }
1667   // Lazy resolve the path to current module.
1668   if (saved_jvm_path[0] != 0) {
1669     strcpy(buf, saved_jvm_path);
1670     return;
1671   }
1672 
1673   char dli_fname[MAXPATHLEN];
1674   bool ret = dll_address_to_library_name(
1675                                          CAST_FROM_FN_PTR(address, os::jvm_path),
1676                                          dli_fname, sizeof(dli_fname), NULL);
1677   assert(ret, "cannot locate libjvm");
1678   char *rp = NULL;
1679   if (ret && dli_fname[0] != '\0') {
1680     rp = os::Posix::realpath(dli_fname, buf, buflen);
1681   }
1682   if (rp == NULL) {
1683     return;
1684   }
1685 
1686   if (Arguments::sun_java_launcher_is_altjvm()) {
1687     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
1688     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
1689     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
1690     // appears at the right place in the string, then assume we are
1691     // installed in a JDK and we're done. Otherwise, check for a
1692     // JAVA_HOME environment variable and construct a path to the JVM
1693     // being overridden.
1694 
1695     const char *p = buf + strlen(buf) - 1;
1696     for (int count = 0; p > buf && count < 5; ++count) {
1697       for (--p; p > buf && *p != '/'; --p)
1698         /* empty */ ;
1699     }
1700 
1701     if (strncmp(p, "/jre/lib/", 9) != 0) {
1702       // Look for JAVA_HOME in the environment.
1703       char* java_home_var = ::getenv("JAVA_HOME");
1704       if (java_home_var != NULL && java_home_var[0] != 0) {
1705         char* jrelib_p;
1706         int len;
1707 
1708         // Check the current module name "libjvm"
1709         p = strrchr(buf, '/');
1710         assert(strstr(p, "/libjvm") == p, "invalid library name");
1711 
1712         rp = os::Posix::realpath(java_home_var, buf, buflen);
1713         if (rp == NULL) {
1714           return;
1715         }
1716 
1717         // determine if this is a legacy image or modules image
1718         // modules image doesn't have "jre" subdirectory
1719         len = strlen(buf);
1720         assert(len < buflen, "Ran out of buffer space");
1721         jrelib_p = buf + len;
1722 
1723         // Add the appropriate library subdir
1724         snprintf(jrelib_p, buflen-len, "/jre/lib");
1725         if (0 != access(buf, F_OK)) {
1726           snprintf(jrelib_p, buflen-len, "/lib");
1727         }
1728 
1729         // Add the appropriate client or server subdir
1730         len = strlen(buf);
1731         jrelib_p = buf + len;
1732         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1733         if (0 != access(buf, F_OK)) {
1734           snprintf(jrelib_p, buflen-len, "%s", "");
1735         }
1736 
1737         // If the path exists within JAVA_HOME, add the JVM library name
1738         // to complete the path to JVM being overridden.  Otherwise fallback
1739         // to the path to the current library.
1740         if (0 == access(buf, F_OK)) {
1741           // Use current module name "libjvm"
1742           len = strlen(buf);
1743           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1744         } else {
1745           // Fall back to path of current library
1746           rp = os::Posix::realpath(dli_fname, buf, buflen);
1747           if (rp == NULL) {
1748             return;
1749           }
1750         }
1751       }
1752     }
1753   }
1754 
1755   strncpy(saved_jvm_path, buf, MAXPATHLEN);
1756   saved_jvm_path[MAXPATHLEN - 1] = '\0';
1757 }
1758 
1759 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1760   // no prefix required, not even "_"
1761 }
1762 
1763 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1764   // no suffix required
1765 }
1766 
1767 ////////////////////////////////////////////////////////////////////////////////
1768 // sun.misc.Signal support
1769 
1770 static void UserHandler(int sig, void *siginfo, void *context) {
1771   // Ctrl-C is pressed during error reporting, likely because the error
1772   // handler fails to abort. Let VM die immediately.
1773   if (sig == SIGINT && VMError::is_error_reported()) {
1774     os::die();
1775   }
1776 
1777   os::signal_notify(sig);
1778 }
1779 
1780 void* os::user_handler() {
1781   return CAST_FROM_FN_PTR(void*, UserHandler);
1782 }
1783 
1784 extern "C" {
1785   typedef void (*sa_handler_t)(int);
1786   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1787 }
1788 
1789 void* os::signal(int signal_number, void* handler) {
1790   struct sigaction sigAct, oldSigAct;
1791 
1792   sigfillset(&(sigAct.sa_mask));
1793   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
1794   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1795 
1796   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1797     // -1 means registration failed
1798     return (void *)-1;
1799   }
1800 
1801   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1802 }
1803 
1804 void os::signal_raise(int signal_number) {
1805   ::raise(signal_number);
1806 }
1807 
1808 // The following code is moved from os.cpp for making this
1809 // code platform specific, which it is by its very nature.
1810 
1811 // Will be modified when max signal is changed to be dynamic
1812 int os::sigexitnum_pd() {
1813   return NSIG;
1814 }
1815 
1816 // a counter for each possible signal value
1817 static volatile jint pending_signals[NSIG+1] = { 0 };
1818 static Semaphore* sig_sem = NULL;
1819 
1820 static void jdk_misc_signal_init() {
1821   // Initialize signal structures
1822   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
1823 
1824   // Initialize signal semaphore
1825   sig_sem = new Semaphore();
1826 }
1827 
1828 void os::signal_notify(int sig) {
1829   if (sig_sem != NULL) {
1830     Atomic::inc(&pending_signals[sig]);
1831     sig_sem->signal();
1832   } else {
1833     // Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init
1834     // initialization isn't called.
1835     assert(ReduceSignalUsage, "signal semaphore should be created");
1836   }
1837 }
1838 
1839 static int check_pending_signals() {
1840   for (;;) {
1841     for (int i = 0; i < NSIG + 1; i++) {
1842       jint n = pending_signals[i];
1843       if (n > 0 && n == Atomic::cmpxchg(&pending_signals[i], n, n - 1)) {
1844         return i;
1845       }
1846     }
1847     JavaThread *thread = JavaThread::current();
1848     ThreadBlockInVM tbivm(thread);
1849 
1850     bool threadIsSuspended;
1851     do {
1852       thread->set_suspend_equivalent();
1853       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1854       sig_sem->wait();
1855 
1856       // were we externally suspended while we were waiting?
1857       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
1858       if (threadIsSuspended) {
1859         // The semaphore has been incremented, but while we were waiting
1860         // another thread suspended us. We don't want to continue running
1861         // while suspended because that would surprise the thread that
1862         // suspended us.
1863         sig_sem->signal();
1864 
1865         thread->java_suspend_self();
1866       }
1867     } while (threadIsSuspended);
1868   }
1869 }
1870 
1871 int os::signal_wait() {
1872   return check_pending_signals();
1873 }
1874 
1875 ////////////////////////////////////////////////////////////////////////////////
1876 // Virtual Memory
1877 
1878 int os::vm_page_size() {
1879   // Seems redundant as all get out
1880   assert(os::Bsd::page_size() != -1, "must call os::init");
1881   return os::Bsd::page_size();
1882 }
1883 
1884 // Solaris allocates memory by pages.
1885 int os::vm_allocation_granularity() {
1886   assert(os::Bsd::page_size() != -1, "must call os::init");
1887   return os::Bsd::page_size();
1888 }
1889 
1890 // Rationale behind this function:
1891 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
1892 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
1893 //  samples for JITted code. Here we create private executable mapping over the code cache
1894 //  and then we can use standard (well, almost, as mapping can change) way to provide
1895 //  info for the reporting script by storing timestamp and location of symbol
1896 void bsd_wrap_code(char* base, size_t size) {
1897   static volatile jint cnt = 0;
1898 
1899   if (!UseOprofile) {
1900     return;
1901   }
1902 
1903   char buf[PATH_MAX + 1];
1904   int num = Atomic::add(&cnt, 1);
1905 
1906   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
1907            os::get_temp_directory(), os::current_process_id(), num);
1908   unlink(buf);
1909 
1910   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
1911 
1912   if (fd != -1) {
1913     off_t rv = ::lseek(fd, size-2, SEEK_SET);
1914     if (rv != (off_t)-1) {
1915       if (::write(fd, "", 1) == 1) {
1916         mmap(base, size,
1917              PROT_READ|PROT_WRITE|PROT_EXEC,
1918              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
1919       }
1920     }
1921     ::close(fd);
1922     unlink(buf);
1923   }
1924 }
1925 
1926 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
1927                                     int err) {
1928   warning("INFO: os::commit_memory(" INTPTR_FORMAT ", " SIZE_FORMAT
1929           ", %d) failed; error='%s' (errno=%d)", (intptr_t)addr, size, exec,
1930            os::errno_name(err), err);
1931 }
1932 
1933 // NOTE: Bsd kernel does not really reserve the pages for us.
1934 //       All it does is to check if there are enough free pages
1935 //       left at the time of mmap(). This could be a potential
1936 //       problem.
1937 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
1938   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
1939 #ifdef __OpenBSD__
1940   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
1941   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(addr), p2i(addr+size), prot);
1942   if (::mprotect(addr, size, prot) == 0) {
1943     return true;
1944   }
1945 #else
1946   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
1947                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
1948   if (res != (uintptr_t) MAP_FAILED) {
1949     return true;
1950   }
1951 #endif
1952 
1953   // Warn about any commit errors we see in non-product builds just
1954   // in case mmap() doesn't work as described on the man page.
1955   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
1956 
1957   return false;
1958 }
1959 
1960 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
1961                           bool exec) {
1962   // alignment_hint is ignored on this OS
1963   return pd_commit_memory(addr, size, exec);
1964 }
1965 
1966 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
1967                                   const char* mesg) {
1968   assert(mesg != NULL, "mesg must be specified");
1969   if (!pd_commit_memory(addr, size, exec)) {
1970     // add extra info in product mode for vm_exit_out_of_memory():
1971     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
1972     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
1973   }
1974 }
1975 
1976 void os::pd_commit_memory_or_exit(char* addr, size_t size,
1977                                   size_t alignment_hint, bool exec,
1978                                   const char* mesg) {
1979   // alignment_hint is ignored on this OS
1980   pd_commit_memory_or_exit(addr, size, exec, mesg);
1981 }
1982 
1983 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1984 }
1985 
1986 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1987   ::madvise(addr, bytes, MADV_DONTNEED);
1988 }
1989 
1990 void os::numa_make_global(char *addr, size_t bytes) {
1991 }
1992 
1993 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
1994 }
1995 
1996 bool os::numa_topology_changed()   { return false; }
1997 
1998 size_t os::numa_get_groups_num() {
1999   return 1;
2000 }
2001 
2002 int os::numa_get_group_id() {
2003   return 0;
2004 }
2005 
2006 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2007   if (size > 0) {
2008     ids[0] = 0;
2009     return 1;
2010   }
2011   return 0;
2012 }
2013 
2014 int os::numa_get_group_id_for_address(const void* address) {
2015   return 0;
2016 }
2017 
2018 bool os::get_page_info(char *start, page_info* info) {
2019   return false;
2020 }
2021 
2022 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2023   return end;
2024 }
2025 
2026 
2027 bool os::pd_uncommit_memory(char* addr, size_t size) {
2028 #ifdef __OpenBSD__
2029   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2030   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with PROT_NONE", p2i(addr), p2i(addr+size));
2031   return ::mprotect(addr, size, PROT_NONE) == 0;
2032 #else
2033   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2034                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2035   return res  != (uintptr_t) MAP_FAILED;
2036 #endif
2037 }
2038 
2039 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2040   return os::commit_memory(addr, size, !ExecMem);
2041 }
2042 
2043 // If this is a growable mapping, remove the guard pages entirely by
2044 // munmap()ping them.  If not, just call uncommit_memory().
2045 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2046   return os::uncommit_memory(addr, size);
2047 }
2048 
2049 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2050 // at 'requested_addr'. If there are existing memory mappings at the same
2051 // location, however, they will be overwritten. If 'fixed' is false,
2052 // 'requested_addr' is only treated as a hint, the return value may or
2053 // may not start from the requested address. Unlike Bsd mmap(), this
2054 // function returns NULL to indicate failure.
2055 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2056   char * addr;
2057   int flags;
2058 
2059   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2060   if (fixed) {
2061     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2062     flags |= MAP_FIXED;
2063   }
2064 
2065   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2066   // touch an uncommitted page. Otherwise, the read/write might
2067   // succeed if we have enough swap space to back the physical page.
2068   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2069                        flags, -1, 0);
2070 
2071   return addr == MAP_FAILED ? NULL : addr;
2072 }
2073 
2074 static int anon_munmap(char * addr, size_t size) {
2075   return ::munmap(addr, size) == 0;
2076 }
2077 
2078 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2079                             size_t alignment_hint) {
2080   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2081 }
2082 
2083 bool os::pd_release_memory(char* addr, size_t size) {
2084   return anon_munmap(addr, size);
2085 }
2086 
2087 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2088   // Bsd wants the mprotect address argument to be page aligned.
2089   char* bottom = (char*)align_down((intptr_t)addr, os::Bsd::page_size());
2090 
2091   // According to SUSv3, mprotect() should only be used with mappings
2092   // established by mmap(), and mmap() always maps whole pages. Unaligned
2093   // 'addr' likely indicates problem in the VM (e.g. trying to change
2094   // protection of malloc'ed or statically allocated memory). Check the
2095   // caller if you hit this assert.
2096   assert(addr == bottom, "sanity check");
2097 
2098   size = align_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2099   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);
2100   return ::mprotect(bottom, size, prot) == 0;
2101 }
2102 
2103 // Set protections specified
2104 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2105                         bool is_committed) {
2106   unsigned int p = 0;
2107   switch (prot) {
2108   case MEM_PROT_NONE: p = PROT_NONE; break;
2109   case MEM_PROT_READ: p = PROT_READ; break;
2110   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2111   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2112   default:
2113     ShouldNotReachHere();
2114   }
2115   // is_committed is unused.
2116   return bsd_mprotect(addr, bytes, p);
2117 }
2118 
2119 bool os::guard_memory(char* addr, size_t size) {
2120   return bsd_mprotect(addr, size, PROT_NONE);
2121 }
2122 
2123 bool os::unguard_memory(char* addr, size_t size) {
2124   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2125 }
2126 
2127 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2128   return false;
2129 }
2130 
2131 // Large page support
2132 
2133 static size_t _large_page_size = 0;
2134 
2135 void os::large_page_init() {
2136 }
2137 
2138 
2139 char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2140   fatal("os::reserve_memory_special should not be called on BSD.");
2141   return NULL;
2142 }
2143 
2144 bool os::pd_release_memory_special(char* base, size_t bytes) {
2145   fatal("os::release_memory_special should not be called on BSD.");
2146   return false;
2147 }
2148 
2149 size_t os::large_page_size() {
2150   return _large_page_size;
2151 }
2152 
2153 bool os::can_commit_large_page_memory() {
2154   // Does not matter, we do not support huge pages.
2155   return false;
2156 }
2157 
2158 bool os::can_execute_large_page_memory() {
2159   // Does not matter, we do not support huge pages.
2160   return false;
2161 }
2162 
2163 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr, int file_desc) {
2164   assert(file_desc >= 0, "file_desc is not valid");
2165   char* result = pd_attempt_reserve_memory_at(bytes, requested_addr);
2166   if (result != NULL) {
2167     if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {
2168       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
2169     }
2170   }
2171   return result;
2172 }
2173 
2174 // Reserve memory at an arbitrary address, only if that area is
2175 // available (and not reserved for something else).
2176 
2177 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2178   // Assert only that the size is a multiple of the page size, since
2179   // that's all that mmap requires, and since that's all we really know
2180   // about at this low abstraction level.  If we need higher alignment,
2181   // we can either pass an alignment to this method or verify alignment
2182   // in one of the methods further up the call chain.  See bug 5044738.
2183   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2184 
2185   // Repeatedly allocate blocks until the block is allocated at the
2186   // right spot.
2187 
2188   // Bsd mmap allows caller to pass an address as hint; give it a try first,
2189   // if kernel honors the hint then we can return immediately.
2190   char * addr = anon_mmap(requested_addr, bytes, false);
2191   if (addr == requested_addr) {
2192     return requested_addr;
2193   }
2194 
2195   if (addr != NULL) {
2196     // mmap() is successful but it fails to reserve at the requested address
2197     anon_munmap(addr, bytes);
2198   }
2199 
2200   return NULL;
2201 }
2202 
2203 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2204 void os::infinite_sleep() {
2205   while (true) {    // sleep forever ...
2206     ::sleep(100);   // ... 100 seconds at a time
2207   }
2208 }
2209 
2210 // Used to convert frequent JVM_Yield() to nops
2211 bool os::dont_yield() {
2212   return DontYieldALot;
2213 }
2214 
2215 void os::naked_yield() {
2216   sched_yield();
2217 }
2218 
2219 ////////////////////////////////////////////////////////////////////////////////
2220 // thread priority support
2221 
2222 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2223 // only supports dynamic priority, static priority must be zero. For real-time
2224 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2225 // However, for large multi-threaded applications, SCHED_RR is not only slower
2226 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2227 // of 5 runs - Sep 2005).
2228 //
2229 // The following code actually changes the niceness of kernel-thread/LWP. It
2230 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2231 // not the entire user process, and user level threads are 1:1 mapped to kernel
2232 // threads. It has always been the case, but could change in the future. For
2233 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2234 // It is only used when ThreadPriorityPolicy=1 and may require system level permission
2235 // (e.g., root privilege or CAP_SYS_NICE capability).
2236 
2237 #if !defined(__APPLE__)
2238 int os::java_to_os_priority[CriticalPriority + 1] = {
2239   19,              // 0 Entry should never be used
2240 
2241    0,              // 1 MinPriority
2242    3,              // 2
2243    6,              // 3
2244 
2245   10,              // 4
2246   15,              // 5 NormPriority
2247   18,              // 6
2248 
2249   21,              // 7
2250   25,              // 8
2251   28,              // 9 NearMaxPriority
2252 
2253   31,              // 10 MaxPriority
2254 
2255   31               // 11 CriticalPriority
2256 };
2257 #else
2258 // Using Mach high-level priority assignments
2259 int os::java_to_os_priority[CriticalPriority + 1] = {
2260    0,              // 0 Entry should never be used (MINPRI_USER)
2261 
2262   27,              // 1 MinPriority
2263   28,              // 2
2264   29,              // 3
2265 
2266   30,              // 4
2267   31,              // 5 NormPriority (BASEPRI_DEFAULT)
2268   32,              // 6
2269 
2270   33,              // 7
2271   34,              // 8
2272   35,              // 9 NearMaxPriority
2273 
2274   36,              // 10 MaxPriority
2275 
2276   36               // 11 CriticalPriority
2277 };
2278 #endif
2279 
2280 static int prio_init() {
2281   if (ThreadPriorityPolicy == 1) {
2282     if (geteuid() != 0) {
2283       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {
2284         warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \
2285                 "e.g., being the root user. If the necessary permission is not " \
2286                 "possessed, changes to priority will be silently ignored.");
2287       }
2288     }
2289   }
2290   if (UseCriticalJavaThreadPriority) {
2291     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2292   }
2293   return 0;
2294 }
2295 
2296 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2297   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
2298 
2299 #ifdef __OpenBSD__
2300   // OpenBSD pthread_setprio starves low priority threads
2301   return OS_OK;
2302 #elif defined(__FreeBSD__)
2303   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2304   return (ret == 0) ? OS_OK : OS_ERR;
2305 #elif defined(__APPLE__) || defined(__NetBSD__)
2306   struct sched_param sp;
2307   int policy;
2308 
2309   if (pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp) != 0) {
2310     return OS_ERR;
2311   }
2312 
2313   sp.sched_priority = newpri;
2314   if (pthread_setschedparam(thread->osthread()->pthread_id(), policy, &sp) != 0) {
2315     return OS_ERR;
2316   }
2317 
2318   return OS_OK;
2319 #else
2320   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2321   return (ret == 0) ? OS_OK : OS_ERR;
2322 #endif
2323 }
2324 
2325 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2326   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
2327     *priority_ptr = java_to_os_priority[NormPriority];
2328     return OS_OK;
2329   }
2330 
2331   errno = 0;
2332 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2333   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2334 #elif defined(__APPLE__) || defined(__NetBSD__)
2335   int policy;
2336   struct sched_param sp;
2337 
2338   int res = pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp);
2339   if (res != 0) {
2340     *priority_ptr = -1;
2341     return OS_ERR;
2342   } else {
2343     *priority_ptr = sp.sched_priority;
2344     return OS_OK;
2345   }
2346 #else
2347   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2348 #endif
2349   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2350 }
2351 
2352 ////////////////////////////////////////////////////////////////////////////////
2353 // suspend/resume support
2354 
2355 //  The low-level signal-based suspend/resume support is a remnant from the
2356 //  old VM-suspension that used to be for java-suspension, safepoints etc,
2357 //  within hotspot. Currently used by JFR's OSThreadSampler
2358 //
2359 //  The remaining code is greatly simplified from the more general suspension
2360 //  code that used to be used.
2361 //
2362 //  The protocol is quite simple:
2363 //  - suspend:
2364 //      - sends a signal to the target thread
2365 //      - polls the suspend state of the osthread using a yield loop
2366 //      - target thread signal handler (SR_handler) sets suspend state
2367 //        and blocks in sigsuspend until continued
2368 //  - resume:
2369 //      - sets target osthread state to continue
2370 //      - sends signal to end the sigsuspend loop in the SR_handler
2371 //
2372 //  Note that the SR_lock plays no role in this suspend/resume protocol,
2373 //  but is checked for NULL in SR_handler as a thread termination indicator.
2374 //  The SR_lock is, however, used by JavaThread::java_suspend()/java_resume() APIs.
2375 //
2376 //  Note that resume_clear_context() and suspend_save_context() are needed
2377 //  by SR_handler(), so that fetch_frame_from_ucontext() works,
2378 //  which in part is used by:
2379 //    - Forte Analyzer: AsyncGetCallTrace()
2380 //    - StackBanging: get_frame_at_stack_banging_point()
2381 
2382 static void resume_clear_context(OSThread *osthread) {
2383   osthread->set_ucontext(NULL);
2384   osthread->set_siginfo(NULL);
2385 }
2386 
2387 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2388   osthread->set_ucontext(context);
2389   osthread->set_siginfo(siginfo);
2390 }
2391 
2392 // Handler function invoked when a thread's execution is suspended or
2393 // resumed. We have to be careful that only async-safe functions are
2394 // called here (Note: most pthread functions are not async safe and
2395 // should be avoided.)
2396 //
2397 // Note: sigwait() is a more natural fit than sigsuspend() from an
2398 // interface point of view, but sigwait() prevents the signal hander
2399 // from being run. libpthread would get very confused by not having
2400 // its signal handlers run and prevents sigwait()'s use with the
2401 // mutex granting granting signal.
2402 //
2403 // Currently only ever called on the VMThread or JavaThread
2404 //
2405 #ifdef __APPLE__
2406 static OSXSemaphore sr_semaphore;
2407 #else
2408 static PosixSemaphore sr_semaphore;
2409 #endif
2410 
2411 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2412   // Save and restore errno to avoid confusing native code with EINTR
2413   // after sigsuspend.
2414   int old_errno = errno;
2415 
2416   Thread* thread = Thread::current_or_null_safe();
2417   assert(thread != NULL, "Missing current thread in SR_handler");
2418 
2419   // On some systems we have seen signal delivery get "stuck" until the signal
2420   // mask is changed as part of thread termination. Check that the current thread
2421   // has not already terminated (via SR_lock()) - else the following assertion
2422   // will fail because the thread is no longer a JavaThread as the ~JavaThread
2423   // destructor has completed.
2424 
2425   if (thread->SR_lock() == NULL) {
2426     return;
2427   }
2428 
2429   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2430 
2431   OSThread* osthread = thread->osthread();
2432 
2433   os::SuspendResume::State current = osthread->sr.state();
2434   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2435     suspend_save_context(osthread, siginfo, context);
2436 
2437     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2438     os::SuspendResume::State state = osthread->sr.suspended();
2439     if (state == os::SuspendResume::SR_SUSPENDED) {
2440       sigset_t suspend_set;  // signals for sigsuspend()
2441 
2442       // get current set of blocked signals and unblock resume signal
2443       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2444       sigdelset(&suspend_set, SR_signum);
2445 
2446       sr_semaphore.signal();
2447       // wait here until we are resumed
2448       while (1) {
2449         sigsuspend(&suspend_set);
2450 
2451         os::SuspendResume::State result = osthread->sr.running();
2452         if (result == os::SuspendResume::SR_RUNNING) {
2453           sr_semaphore.signal();
2454           break;
2455         } else if (result != os::SuspendResume::SR_SUSPENDED) {
2456           ShouldNotReachHere();
2457         }
2458       }
2459 
2460     } else if (state == os::SuspendResume::SR_RUNNING) {
2461       // request was cancelled, continue
2462     } else {
2463       ShouldNotReachHere();
2464     }
2465 
2466     resume_clear_context(osthread);
2467   } else if (current == os::SuspendResume::SR_RUNNING) {
2468     // request was cancelled, continue
2469   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2470     // ignore
2471   } else {
2472     // ignore
2473   }
2474 
2475   errno = old_errno;
2476 }
2477 
2478 
2479 static int SR_initialize() {
2480   struct sigaction act;
2481   char *s;
2482   // Get signal number to use for suspend/resume
2483   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2484     int sig = ::strtol(s, 0, 10);
2485     if (sig > MAX2(SIGSEGV, SIGBUS) &&  // See 4355769.
2486         sig < NSIG) {                   // Must be legal signal and fit into sigflags[].
2487       SR_signum = sig;
2488     } else {
2489       warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
2490               sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, SR_signum);
2491     }
2492   }
2493 
2494   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2495          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2496 
2497   sigemptyset(&SR_sigset);
2498   sigaddset(&SR_sigset, SR_signum);
2499 
2500   // Set up signal handler for suspend/resume
2501   act.sa_flags = SA_RESTART|SA_SIGINFO;
2502   act.sa_handler = (void (*)(int)) SR_handler;
2503 
2504   // SR_signum is blocked by default.
2505   // 4528190 - We also need to block pthread restart signal (32 on all
2506   // supported Bsd platforms). Note that BsdThreads need to block
2507   // this signal for all threads to work properly. So we don't have
2508   // to use hard-coded signal number when setting up the mask.
2509   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2510 
2511   if (sigaction(SR_signum, &act, 0) == -1) {
2512     return -1;
2513   }
2514 
2515   // Save signal flag
2516   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2517   return 0;
2518 }
2519 
2520 static int sr_notify(OSThread* osthread) {
2521   int status = pthread_kill(osthread->pthread_id(), SR_signum);
2522   assert_status(status == 0, status, "pthread_kill");
2523   return status;
2524 }
2525 
2526 // "Randomly" selected value for how long we want to spin
2527 // before bailing out on suspending a thread, also how often
2528 // we send a signal to a thread we want to resume
2529 static const int RANDOMLY_LARGE_INTEGER = 1000000;
2530 static const int RANDOMLY_LARGE_INTEGER2 = 100;
2531 
2532 // returns true on success and false on error - really an error is fatal
2533 // but this seems the normal response to library errors
2534 static bool do_suspend(OSThread* osthread) {
2535   assert(osthread->sr.is_running(), "thread should be running");
2536   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2537 
2538   // mark as suspended and send signal
2539   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2540     // failed to switch, state wasn't running?
2541     ShouldNotReachHere();
2542     return false;
2543   }
2544 
2545   if (sr_notify(osthread) != 0) {
2546     ShouldNotReachHere();
2547   }
2548 
2549   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2550   while (true) {
2551     if (sr_semaphore.timedwait(2)) {
2552       break;
2553     } else {
2554       // timeout
2555       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2556       if (cancelled == os::SuspendResume::SR_RUNNING) {
2557         return false;
2558       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2559         // make sure that we consume the signal on the semaphore as well
2560         sr_semaphore.wait();
2561         break;
2562       } else {
2563         ShouldNotReachHere();
2564         return false;
2565       }
2566     }
2567   }
2568 
2569   guarantee(osthread->sr.is_suspended(), "Must be suspended");
2570   return true;
2571 }
2572 
2573 static void do_resume(OSThread* osthread) {
2574   assert(osthread->sr.is_suspended(), "thread should be suspended");
2575   assert(!sr_semaphore.trywait(), "invalid semaphore state");
2576 
2577   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2578     // failed to switch to WAKEUP_REQUEST
2579     ShouldNotReachHere();
2580     return;
2581   }
2582 
2583   while (true) {
2584     if (sr_notify(osthread) == 0) {
2585       if (sr_semaphore.timedwait(2)) {
2586         if (osthread->sr.is_running()) {
2587           return;
2588         }
2589       }
2590     } else {
2591       ShouldNotReachHere();
2592     }
2593   }
2594 
2595   guarantee(osthread->sr.is_running(), "Must be running!");
2596 }
2597 
2598 ///////////////////////////////////////////////////////////////////////////////////
2599 // signal handling (except suspend/resume)
2600 
2601 // This routine may be used by user applications as a "hook" to catch signals.
2602 // The user-defined signal handler must pass unrecognized signals to this
2603 // routine, and if it returns true (non-zero), then the signal handler must
2604 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
2605 // routine will never retun false (zero), but instead will execute a VM panic
2606 // routine kill the process.
2607 //
2608 // If this routine returns false, it is OK to call it again.  This allows
2609 // the user-defined signal handler to perform checks either before or after
2610 // the VM performs its own checks.  Naturally, the user code would be making
2611 // a serious error if it tried to handle an exception (such as a null check
2612 // or breakpoint) that the VM was generating for its own correct operation.
2613 //
2614 // This routine may recognize any of the following kinds of signals:
2615 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
2616 // It should be consulted by handlers for any of those signals.
2617 //
2618 // The caller of this routine must pass in the three arguments supplied
2619 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
2620 // field of the structure passed to sigaction().  This routine assumes that
2621 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
2622 //
2623 // Note that the VM will print warnings if it detects conflicting signal
2624 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
2625 //
2626 extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
2627                                                void* ucontext,
2628                                                int abort_if_unrecognized);
2629 
2630 static void signalHandler(int sig, siginfo_t* info, void* uc) {
2631   assert(info != NULL && uc != NULL, "it must be old kernel");
2632   int orig_errno = errno;  // Preserve errno value over signal handler.
2633   JVM_handle_bsd_signal(sig, info, uc, true);
2634   errno = orig_errno;
2635 }
2636 
2637 
2638 // This boolean allows users to forward their own non-matching signals
2639 // to JVM_handle_bsd_signal, harmlessly.
2640 bool os::Bsd::signal_handlers_are_installed = false;
2641 
2642 // For signal-chaining
2643 bool os::Bsd::libjsig_is_loaded = false;
2644 typedef struct sigaction *(*get_signal_t)(int);
2645 get_signal_t os::Bsd::get_signal_action = NULL;
2646 
2647 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
2648   struct sigaction *actp = NULL;
2649 
2650   if (libjsig_is_loaded) {
2651     // Retrieve the old signal handler from libjsig
2652     actp = (*get_signal_action)(sig);
2653   }
2654   if (actp == NULL) {
2655     // Retrieve the preinstalled signal handler from jvm
2656     actp = os::Posix::get_preinstalled_handler(sig);
2657   }
2658 
2659   return actp;
2660 }
2661 
2662 static bool call_chained_handler(struct sigaction *actp, int sig,
2663                                  siginfo_t *siginfo, void *context) {
2664   // Call the old signal handler
2665   if (actp->sa_handler == SIG_DFL) {
2666     // It's more reasonable to let jvm treat it as an unexpected exception
2667     // instead of taking the default action.
2668     return false;
2669   } else if (actp->sa_handler != SIG_IGN) {
2670     if ((actp->sa_flags & SA_NODEFER) == 0) {
2671       // automaticlly block the signal
2672       sigaddset(&(actp->sa_mask), sig);
2673     }
2674 
2675     sa_handler_t hand;
2676     sa_sigaction_t sa;
2677     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
2678     // retrieve the chained handler
2679     if (siginfo_flag_set) {
2680       sa = actp->sa_sigaction;
2681     } else {
2682       hand = actp->sa_handler;
2683     }
2684 
2685     if ((actp->sa_flags & SA_RESETHAND) != 0) {
2686       actp->sa_handler = SIG_DFL;
2687     }
2688 
2689     // try to honor the signal mask
2690     sigset_t oset;
2691     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
2692 
2693     // call into the chained handler
2694     if (siginfo_flag_set) {
2695       (*sa)(sig, siginfo, context);
2696     } else {
2697       (*hand)(sig);
2698     }
2699 
2700     // restore the signal mask
2701     pthread_sigmask(SIG_SETMASK, &oset, 0);
2702   }
2703   // Tell jvm's signal handler the signal is taken care of.
2704   return true;
2705 }
2706 
2707 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
2708   bool chained = false;
2709   // signal-chaining
2710   if (UseSignalChaining) {
2711     struct sigaction *actp = get_chained_signal_action(sig);
2712     if (actp != NULL) {
2713       chained = call_chained_handler(actp, sig, siginfo, context);
2714     }
2715   }
2716   return chained;
2717 }
2718 
2719 // for diagnostic
2720 int sigflags[NSIG];
2721 
2722 int os::Bsd::get_our_sigflags(int sig) {
2723   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2724   return sigflags[sig];
2725 }
2726 
2727 void os::Bsd::set_our_sigflags(int sig, int flags) {
2728   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2729   if (sig > 0 && sig < NSIG) {
2730     sigflags[sig] = flags;
2731   }
2732 }
2733 
2734 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
2735   // Check for overwrite.
2736   struct sigaction oldAct;
2737   sigaction(sig, (struct sigaction*)NULL, &oldAct);
2738 
2739   void* oldhand = oldAct.sa_sigaction
2740                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
2741                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
2742   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
2743       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
2744       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
2745     if (AllowUserSignalHandlers || !set_installed) {
2746       // Do not overwrite; user takes responsibility to forward to us.
2747       return;
2748     } else if (UseSignalChaining) {
2749       // save the old handler in jvm
2750       os::Posix::save_preinstalled_handler(sig, oldAct);
2751       // libjsig also interposes the sigaction() call below and saves the
2752       // old sigaction on it own.
2753     } else {
2754       fatal("Encountered unexpected pre-existing sigaction handler "
2755             "%#lx for signal %d.", (long)oldhand, sig);
2756     }
2757   }
2758 
2759   struct sigaction sigAct;
2760   sigfillset(&(sigAct.sa_mask));
2761   sigAct.sa_handler = SIG_DFL;
2762   if (!set_installed) {
2763     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
2764   } else {
2765     sigAct.sa_sigaction = signalHandler;
2766     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
2767   }
2768 #ifdef __APPLE__
2769   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
2770   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
2771   // if the signal handler declares it will handle it on alternate stack.
2772   // Notice we only declare we will handle it on alt stack, but we are not
2773   // actually going to use real alt stack - this is just a workaround.
2774   // Please see ux_exception.c, method catch_mach_exception_raise for details
2775   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
2776   if (sig == SIGSEGV) {
2777     sigAct.sa_flags |= SA_ONSTACK;
2778   }
2779 #endif
2780 
2781   // Save flags, which are set by ours
2782   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2783   sigflags[sig] = sigAct.sa_flags;
2784 
2785   int ret = sigaction(sig, &sigAct, &oldAct);
2786   assert(ret == 0, "check");
2787 
2788   void* oldhand2  = oldAct.sa_sigaction
2789                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
2790                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
2791   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
2792 }
2793 
2794 // install signal handlers for signals that HotSpot needs to
2795 // handle in order to support Java-level exception handling.
2796 
2797 void os::Bsd::install_signal_handlers() {
2798   if (!signal_handlers_are_installed) {
2799     signal_handlers_are_installed = true;
2800 
2801     // signal-chaining
2802     typedef void (*signal_setting_t)();
2803     signal_setting_t begin_signal_setting = NULL;
2804     signal_setting_t end_signal_setting = NULL;
2805     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
2806                                           dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
2807     if (begin_signal_setting != NULL) {
2808       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
2809                                           dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
2810       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
2811                                          dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
2812       libjsig_is_loaded = true;
2813       assert(UseSignalChaining, "should enable signal-chaining");
2814     }
2815     if (libjsig_is_loaded) {
2816       // Tell libjsig jvm is setting signal handlers
2817       (*begin_signal_setting)();
2818     }
2819 
2820     set_signal_handler(SIGSEGV, true);
2821     set_signal_handler(SIGPIPE, true);
2822     set_signal_handler(SIGBUS, true);
2823     set_signal_handler(SIGILL, true);
2824     set_signal_handler(SIGFPE, true);
2825     set_signal_handler(SIGXFSZ, true);
2826 
2827 #if defined(__APPLE__)
2828     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
2829     // signals caught and handled by the JVM. To work around this, we reset the mach task
2830     // signal handler that's placed on our process by CrashReporter. This disables
2831     // CrashReporter-based reporting.
2832     //
2833     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
2834     // on caught fatal signals.
2835     //
2836     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
2837     // handlers. By replacing the existing task exception handler, we disable gdb's mach
2838     // exception handling, while leaving the standard BSD signal handlers functional.
2839     kern_return_t kr;
2840     kr = task_set_exception_ports(mach_task_self(),
2841                                   EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
2842                                   MACH_PORT_NULL,
2843                                   EXCEPTION_STATE_IDENTITY,
2844                                   MACHINE_THREAD_STATE);
2845 
2846     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
2847 #endif
2848 
2849     if (libjsig_is_loaded) {
2850       // Tell libjsig jvm finishes setting signal handlers
2851       (*end_signal_setting)();
2852     }
2853 
2854     // We don't activate signal checker if libjsig is in place, we trust ourselves
2855     // and if UserSignalHandler is installed all bets are off
2856     if (CheckJNICalls) {
2857       if (libjsig_is_loaded) {
2858         log_debug(jni, resolve)("Info: libjsig is activated, all active signal checking is disabled");
2859         check_signals = false;
2860       }
2861       if (AllowUserSignalHandlers) {
2862         log_debug(jni, resolve)("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
2863         check_signals = false;
2864       }
2865     }
2866   }
2867 }
2868 
2869 
2870 /////
2871 // glibc on Bsd platform uses non-documented flag
2872 // to indicate, that some special sort of signal
2873 // trampoline is used.
2874 // We will never set this flag, and we should
2875 // ignore this flag in our diagnostic
2876 #ifdef SIGNIFICANT_SIGNAL_MASK
2877   #undef SIGNIFICANT_SIGNAL_MASK
2878 #endif
2879 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
2880 
2881 static const char* get_signal_handler_name(address handler,
2882                                            char* buf, int buflen) {
2883   int offset;
2884   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
2885   if (found) {
2886     // skip directory names
2887     const char *p1, *p2;
2888     p1 = buf;
2889     size_t len = strlen(os::file_separator());
2890     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
2891     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
2892   } else {
2893     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
2894   }
2895   return buf;
2896 }
2897 
2898 static void print_signal_handler(outputStream* st, int sig,
2899                                  char* buf, size_t buflen) {
2900   struct sigaction sa;
2901 
2902   sigaction(sig, NULL, &sa);
2903 
2904   // See comment for SIGNIFICANT_SIGNAL_MASK define
2905   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
2906 
2907   st->print("%s: ", os::exception_name(sig, buf, buflen));
2908 
2909   address handler = (sa.sa_flags & SA_SIGINFO)
2910     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
2911     : CAST_FROM_FN_PTR(address, sa.sa_handler);
2912 
2913   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
2914     st->print("SIG_DFL");
2915   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
2916     st->print("SIG_IGN");
2917   } else {
2918     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
2919   }
2920 
2921   st->print(", sa_mask[0]=");
2922   os::Posix::print_signal_set_short(st, &sa.sa_mask);
2923 
2924   address rh = VMError::get_resetted_sighandler(sig);
2925   // May be, handler was resetted by VMError?
2926   if (rh != NULL) {
2927     handler = rh;
2928     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
2929   }
2930 
2931   st->print(", sa_flags=");
2932   os::Posix::print_sa_flags(st, sa.sa_flags);
2933 
2934   // Check: is it our handler?
2935   if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
2936       handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
2937     // It is our signal handler
2938     // check for flags, reset system-used one!
2939     if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
2940       st->print(
2941                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
2942                 os::Bsd::get_our_sigflags(sig));
2943     }
2944   }
2945   st->cr();
2946 }
2947 
2948 
2949 #define DO_SIGNAL_CHECK(sig)                      \
2950   do {                                            \
2951     if (!sigismember(&check_signal_done, sig)) {  \
2952       os::Bsd::check_signal_handler(sig);         \
2953     }                                             \
2954   } while (0)
2955 
2956 // This method is a periodic task to check for misbehaving JNI applications
2957 // under CheckJNI, we can add any periodic checks here
2958 
2959 void os::run_periodic_checks() {
2960 
2961   if (check_signals == false) return;
2962 
2963   // SEGV and BUS if overridden could potentially prevent
2964   // generation of hs*.log in the event of a crash, debugging
2965   // such a case can be very challenging, so we absolutely
2966   // check the following for a good measure:
2967   DO_SIGNAL_CHECK(SIGSEGV);
2968   DO_SIGNAL_CHECK(SIGILL);
2969   DO_SIGNAL_CHECK(SIGFPE);
2970   DO_SIGNAL_CHECK(SIGBUS);
2971   DO_SIGNAL_CHECK(SIGPIPE);
2972   DO_SIGNAL_CHECK(SIGXFSZ);
2973 
2974 
2975   // ReduceSignalUsage allows the user to override these handlers
2976   // see comments at the very top and jvm_md.h
2977   if (!ReduceSignalUsage) {
2978     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
2979     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
2980     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
2981     DO_SIGNAL_CHECK(BREAK_SIGNAL);
2982   }
2983 
2984   DO_SIGNAL_CHECK(SR_signum);
2985 }
2986 
2987 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
2988 
2989 static os_sigaction_t os_sigaction = NULL;
2990 
2991 void os::Bsd::check_signal_handler(int sig) {
2992   char buf[O_BUFLEN];
2993   address jvmHandler = NULL;
2994 
2995 
2996   struct sigaction act;
2997   if (os_sigaction == NULL) {
2998     // only trust the default sigaction, in case it has been interposed
2999     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3000     if (os_sigaction == NULL) return;
3001   }
3002 
3003   os_sigaction(sig, (struct sigaction*)NULL, &act);
3004 
3005 
3006   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
3007 
3008   address thisHandler = (act.sa_flags & SA_SIGINFO)
3009     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3010     : CAST_FROM_FN_PTR(address, act.sa_handler);
3011 
3012 
3013   switch (sig) {
3014   case SIGSEGV:
3015   case SIGBUS:
3016   case SIGFPE:
3017   case SIGPIPE:
3018   case SIGILL:
3019   case SIGXFSZ:
3020     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3021     break;
3022 
3023   case SHUTDOWN1_SIGNAL:
3024   case SHUTDOWN2_SIGNAL:
3025   case SHUTDOWN3_SIGNAL:
3026   case BREAK_SIGNAL:
3027     jvmHandler = (address)user_handler();
3028     break;
3029 
3030   default:
3031     if (sig == SR_signum) {
3032       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3033     } else {
3034       return;
3035     }
3036     break;
3037   }
3038 
3039   if (thisHandler != jvmHandler) {
3040     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3041     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3042     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3043     // No need to check this sig any longer
3044     sigaddset(&check_signal_done, sig);
3045     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
3046     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
3047       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
3048                     exception_name(sig, buf, O_BUFLEN));
3049     }
3050   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3051     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3052     tty->print("expected:");
3053     os::Posix::print_sa_flags(tty, os::Bsd::get_our_sigflags(sig));
3054     tty->cr();
3055     tty->print("  found:");
3056     os::Posix::print_sa_flags(tty, act.sa_flags);
3057     tty->cr();
3058     // No need to check this sig any longer
3059     sigaddset(&check_signal_done, sig);
3060   }
3061 
3062   // Dump all the signal
3063   if (sigismember(&check_signal_done, sig)) {
3064     print_signal_handlers(tty, buf, O_BUFLEN);
3065   }
3066 }
3067 
3068 extern void report_error(char* file_name, int line_no, char* title,
3069                          char* format, ...);
3070 
3071 // this is called _before_ the most of global arguments have been parsed
3072 void os::init(void) {
3073   char dummy;   // used to get a guess on initial stack address
3074 
3075   clock_tics_per_sec = CLK_TCK;
3076 
3077   init_random(1234567);
3078 
3079   Bsd::set_page_size(getpagesize());
3080   if (Bsd::page_size() == -1) {
3081     fatal("os_bsd.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
3082   }
3083   init_page_sizes((size_t) Bsd::page_size());
3084 
3085   Bsd::initialize_system_info();
3086 
3087   // _main_thread points to the thread that created/loaded the JVM.
3088   Bsd::_main_thread = pthread_self();
3089 
3090   Bsd::clock_init();
3091   initial_time_count = javaTimeNanos();
3092 
3093   os::Posix::init();
3094 }
3095 
3096 // To install functions for atexit system call
3097 extern "C" {
3098   static void perfMemory_exit_helper() {
3099     perfMemory_exit();
3100   }
3101 }
3102 
3103 // this is called _after_ the global arguments have been parsed
3104 jint os::init_2(void) {
3105 
3106   // This could be set after os::Posix::init() but all platforms
3107   // have to set it the same so we have to mirror Solaris.
3108   DEBUG_ONLY(os::set_mutex_init_done();)
3109 
3110   os::Posix::init_2();
3111 
3112   // initialize suspend/resume support - must do this before signal_sets_init()
3113   if (SR_initialize() != 0) {
3114     perror("SR_initialize failed");
3115     return JNI_ERR;
3116   }
3117 
3118   Bsd::signal_sets_init();
3119   Bsd::install_signal_handlers();
3120   // Initialize data for jdk.internal.misc.Signal
3121   if (!ReduceSignalUsage) {
3122     jdk_misc_signal_init();
3123   }
3124 
3125   // Check and sets minimum stack sizes against command line options
3126   if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
3127     return JNI_ERR;
3128   }
3129 
3130   if (MaxFDLimit) {
3131     // set the number of file descriptors to max. print out error
3132     // if getrlimit/setrlimit fails but continue regardless.
3133     struct rlimit nbr_files;
3134     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3135     if (status != 0) {
3136       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
3137     } else {
3138       nbr_files.rlim_cur = nbr_files.rlim_max;
3139 
3140 #ifdef __APPLE__
3141       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3142       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3143       // be used instead
3144       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3145 #endif
3146 
3147       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3148       if (status != 0) {
3149         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
3150       }
3151     }
3152   }
3153 
3154   // at-exit methods are called in the reverse order of their registration.
3155   // atexit functions are called on return from main or as a result of a
3156   // call to exit(3C). There can be only 32 of these functions registered
3157   // and atexit() does not set errno.
3158 
3159   if (PerfAllowAtExitRegistration) {
3160     // only register atexit functions if PerfAllowAtExitRegistration is set.
3161     // atexit functions can be delayed until process exit time, which
3162     // can be problematic for embedded VM situations. Embedded VMs should
3163     // call DestroyJavaVM() to assure that VM resources are released.
3164 
3165     // note: perfMemory_exit_helper atexit function may be removed in
3166     // the future if the appropriate cleanup code can be added to the
3167     // VM_Exit VMOperation's doit method.
3168     if (atexit(perfMemory_exit_helper) != 0) {
3169       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
3170     }
3171   }
3172 
3173   // initialize thread priority policy
3174   prio_init();
3175 
3176 #ifdef __APPLE__
3177   // dynamically link to objective c gc registration
3178   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3179   if (handleLibObjc != NULL) {
3180     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3181   }
3182 #endif
3183 
3184   return JNI_OK;
3185 }
3186 
3187 int os::active_processor_count() {
3188   // User has overridden the number of active processors
3189   if (ActiveProcessorCount > 0) {
3190     log_trace(os)("active_processor_count: "
3191                   "active processor count set by user : %d",
3192                   ActiveProcessorCount);
3193     return ActiveProcessorCount;
3194   }
3195 
3196   return _processor_count;
3197 }
3198 
3199 #ifdef __APPLE__
3200 uint os::processor_id() {
3201   // Get the initial APIC id and return the associated processor id. The initial APIC
3202   // id is limited to 8-bits, which means we can have at most 256 unique APIC ids. If
3203   // the system has more processors (or the initial APIC ids are discontiguous) the
3204   // APIC id will be truncated and more than one processor will potentially share the
3205   // same processor id. This is not optimal, but unlikely to happen in practice. Should
3206   // this become a real problem we could switch to using x2APIC ids, which are 32-bit
3207   // wide. However, note that x2APIC is Intel-specific, and the wider number space
3208   // would require a more complicated mapping approach.
3209   uint eax = 0x1;
3210   uint ebx;
3211   uint ecx = 0;
3212   uint edx;
3213 
3214   __asm__ ("cpuid\n\t" : "+a" (eax), "+b" (ebx), "+c" (ecx), "+d" (edx) : );
3215 
3216   uint apic_id = (ebx >> 24) & (processor_id_map_size - 1);
3217   int processor_id = Atomic::load(&processor_id_map[apic_id]);
3218 
3219   while (processor_id < 0) {
3220     // Assign processor id to APIC id
3221     processor_id = Atomic::cmpxchg(&processor_id_map[apic_id], processor_id_unassigned, processor_id_assigning);
3222     if (processor_id == processor_id_unassigned) {
3223       processor_id = Atomic::fetch_and_add(&processor_id_next, 1) % os::processor_count();
3224       Atomic::store(&processor_id_map[apic_id], processor_id);
3225     }
3226   }
3227 
3228   assert(processor_id >= 0 && processor_id < os::processor_count(), "invalid processor id");
3229 
3230   return (uint)processor_id;
3231 }
3232 #endif
3233 
3234 void os::set_native_thread_name(const char *name) {
3235 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3236   // This is only supported in Snow Leopard and beyond
3237   if (name != NULL) {
3238     // Add a "Java: " prefix to the name
3239     char buf[MAXTHREADNAMESIZE];
3240     snprintf(buf, sizeof(buf), "Java: %s", name);
3241     pthread_setname_np(buf);
3242   }
3243 #endif
3244 }
3245 
3246 bool os::bind_to_processor(uint processor_id) {
3247   // Not yet implemented.
3248   return false;
3249 }
3250 
3251 void os::SuspendedThreadTask::internal_do_task() {
3252   if (do_suspend(_thread->osthread())) {
3253     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3254     do_task(context);
3255     do_resume(_thread->osthread());
3256   }
3257 }
3258 
3259 ////////////////////////////////////////////////////////////////////////////////
3260 // debug support
3261 
3262 bool os::find(address addr, outputStream* st) {
3263   Dl_info dlinfo;
3264   memset(&dlinfo, 0, sizeof(dlinfo));
3265   if (dladdr(addr, &dlinfo) != 0) {
3266     st->print(INTPTR_FORMAT ": ", (intptr_t)addr);
3267     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
3268       st->print("%s+%#x", dlinfo.dli_sname,
3269                 (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_saddr));
3270     } else if (dlinfo.dli_fbase != NULL) {
3271       st->print("<offset %#x>", (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_fbase));
3272     } else {
3273       st->print("<absolute address>");
3274     }
3275     if (dlinfo.dli_fname != NULL) {
3276       st->print(" in %s", dlinfo.dli_fname);
3277     }
3278     if (dlinfo.dli_fbase != NULL) {
3279       st->print(" at " INTPTR_FORMAT, (intptr_t)dlinfo.dli_fbase);
3280     }
3281     st->cr();
3282 
3283     if (Verbose) {
3284       // decode some bytes around the PC
3285       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3286       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3287       address       lowest = (address) dlinfo.dli_sname;
3288       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
3289       if (begin < lowest)  begin = lowest;
3290       Dl_info dlinfo2;
3291       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
3292           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
3293         end = (address) dlinfo2.dli_saddr;
3294       }
3295       Disassembler::decode(begin, end, st);
3296     }
3297     return true;
3298   }
3299   return false;
3300 }
3301 
3302 ////////////////////////////////////////////////////////////////////////////////
3303 // misc
3304 
3305 // This does not do anything on Bsd. This is basically a hook for being
3306 // able to use structured exception handling (thread-local exception filters)
3307 // on, e.g., Win32.
3308 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3309                               const methodHandle& method, JavaCallArguments* args,
3310                               Thread* thread) {
3311   f(value, method, args, thread);
3312 }
3313 
3314 void os::print_statistics() {
3315 }
3316 
3317 bool os::message_box(const char* title, const char* message) {
3318   int i;
3319   fdStream err(defaultStream::error_fd());
3320   for (i = 0; i < 78; i++) err.print_raw("=");
3321   err.cr();
3322   err.print_raw_cr(title);
3323   for (i = 0; i < 78; i++) err.print_raw("-");
3324   err.cr();
3325   err.print_raw_cr(message);
3326   for (i = 0; i < 78; i++) err.print_raw("=");
3327   err.cr();
3328 
3329   char buf[16];
3330   // Prevent process from exiting upon "read error" without consuming all CPU
3331   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3332 
3333   return buf[0] == 'y' || buf[0] == 'Y';
3334 }
3335 
3336 static inline struct timespec get_mtime(const char* filename) {
3337   struct stat st;
3338   int ret = os::stat(filename, &st);
3339   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
3340 #ifdef __APPLE__
3341   return st.st_mtimespec;
3342 #else
3343   return st.st_mtim;
3344 #endif
3345 }
3346 
3347 int os::compare_file_modified_times(const char* file1, const char* file2) {
3348   struct timespec filetime1 = get_mtime(file1);
3349   struct timespec filetime2 = get_mtime(file2);
3350   int diff = filetime1.tv_sec - filetime2.tv_sec;
3351   if (diff == 0) {
3352     return filetime1.tv_nsec - filetime2.tv_nsec;
3353   }
3354   return diff;
3355 }
3356 
3357 // Is a (classpath) directory empty?
3358 bool os::dir_is_empty(const char* path) {
3359   DIR *dir = NULL;
3360   struct dirent *ptr;
3361 
3362   dir = opendir(path);
3363   if (dir == NULL) return true;
3364 
3365   // Scan the directory
3366   bool result = true;
3367   while (result && (ptr = readdir(dir)) != NULL) {
3368     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3369       result = false;
3370     }
3371   }
3372   closedir(dir);
3373   return result;
3374 }
3375 
3376 // This code originates from JDK's sysOpen and open64_w
3377 // from src/solaris/hpi/src/system_md.c
3378 
3379 int os::open(const char *path, int oflag, int mode) {
3380   if (strlen(path) > MAX_PATH - 1) {
3381     errno = ENAMETOOLONG;
3382     return -1;
3383   }
3384   int fd;
3385 
3386   fd = ::open(path, oflag, mode);
3387   if (fd == -1) return -1;
3388 
3389   // If the open succeeded, the file might still be a directory
3390   {
3391     struct stat buf;
3392     int ret = ::fstat(fd, &buf);
3393     int st_mode = buf.st_mode;
3394 
3395     if (ret != -1) {
3396       if ((st_mode & S_IFMT) == S_IFDIR) {
3397         errno = EISDIR;
3398         ::close(fd);
3399         return -1;
3400       }
3401     } else {
3402       ::close(fd);
3403       return -1;
3404     }
3405   }
3406 
3407   // All file descriptors that are opened in the JVM and not
3408   // specifically destined for a subprocess should have the
3409   // close-on-exec flag set.  If we don't set it, then careless 3rd
3410   // party native code might fork and exec without closing all
3411   // appropriate file descriptors (e.g. as we do in closeDescriptors in
3412   // UNIXProcess.c), and this in turn might:
3413   //
3414   // - cause end-of-file to fail to be detected on some file
3415   //   descriptors, resulting in mysterious hangs, or
3416   //
3417   // - might cause an fopen in the subprocess to fail on a system
3418   //   suffering from bug 1085341.
3419   //
3420   // (Yes, the default setting of the close-on-exec flag is a Unix
3421   // design flaw)
3422   //
3423   // See:
3424   // 1085341: 32-bit stdio routines should support file descriptors >255
3425   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3426   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3427   //
3428 #ifdef FD_CLOEXEC
3429   {
3430     int flags = ::fcntl(fd, F_GETFD);
3431     if (flags != -1) {
3432       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3433     }
3434   }
3435 #endif
3436 
3437   return fd;
3438 }
3439 
3440 
3441 // create binary file, rewriting existing file if required
3442 int os::create_binary_file(const char* path, bool rewrite_existing) {
3443   int oflags = O_WRONLY | O_CREAT;
3444   if (!rewrite_existing) {
3445     oflags |= O_EXCL;
3446   }
3447   return ::open(path, oflags, S_IREAD | S_IWRITE);
3448 }
3449 
3450 // return current position of file pointer
3451 jlong os::current_file_offset(int fd) {
3452   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3453 }
3454 
3455 // move file pointer to the specified offset
3456 jlong os::seek_to_file_offset(int fd, jlong offset) {
3457   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3458 }
3459 
3460 // This code originates from JDK's sysAvailable
3461 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
3462 
3463 int os::available(int fd, jlong *bytes) {
3464   jlong cur, end;
3465   int mode;
3466   struct stat buf;
3467 
3468   if (::fstat(fd, &buf) >= 0) {
3469     mode = buf.st_mode;
3470     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
3471       int n;
3472       if (::ioctl(fd, FIONREAD, &n) >= 0) {
3473         *bytes = n;
3474         return 1;
3475       }
3476     }
3477   }
3478   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
3479     return 0;
3480   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
3481     return 0;
3482   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
3483     return 0;
3484   }
3485   *bytes = end - cur;
3486   return 1;
3487 }
3488 
3489 // Map a block of memory.
3490 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
3491                         char *addr, size_t bytes, bool read_only,
3492                         bool allow_exec) {
3493   int prot;
3494   int flags;
3495 
3496   if (read_only) {
3497     prot = PROT_READ;
3498     flags = MAP_SHARED;
3499   } else {
3500     prot = PROT_READ | PROT_WRITE;
3501     flags = MAP_PRIVATE;
3502   }
3503 
3504   if (allow_exec) {
3505     prot |= PROT_EXEC;
3506   }
3507 
3508   if (addr != NULL) {
3509     flags |= MAP_FIXED;
3510   }
3511 
3512   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
3513                                      fd, file_offset);
3514   if (mapped_address == MAP_FAILED) {
3515     return NULL;
3516   }
3517   return mapped_address;
3518 }
3519 
3520 
3521 // Remap a block of memory.
3522 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
3523                           char *addr, size_t bytes, bool read_only,
3524                           bool allow_exec) {
3525   // same as map_memory() on this OS
3526   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
3527                         allow_exec);
3528 }
3529 
3530 
3531 // Unmap a block of memory.
3532 bool os::pd_unmap_memory(char* addr, size_t bytes) {
3533   return munmap(addr, bytes) == 0;
3534 }
3535 
3536 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
3537 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
3538 // of a thread.
3539 //
3540 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
3541 // the fast estimate available on the platform.
3542 
3543 jlong os::current_thread_cpu_time() {
3544 #ifdef __APPLE__
3545   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
3546 #else
3547   Unimplemented();
3548   return 0;
3549 #endif
3550 }
3551 
3552 jlong os::thread_cpu_time(Thread* thread) {
3553 #ifdef __APPLE__
3554   return os::thread_cpu_time(thread, true /* user + sys */);
3555 #else
3556   Unimplemented();
3557   return 0;
3558 #endif
3559 }
3560 
3561 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
3562 #ifdef __APPLE__
3563   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
3564 #else
3565   Unimplemented();
3566   return 0;
3567 #endif
3568 }
3569 
3570 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
3571 #ifdef __APPLE__
3572   struct thread_basic_info tinfo;
3573   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
3574   kern_return_t kr;
3575   thread_t mach_thread;
3576 
3577   mach_thread = thread->osthread()->thread_id();
3578   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
3579   if (kr != KERN_SUCCESS) {
3580     return -1;
3581   }
3582 
3583   if (user_sys_cpu_time) {
3584     jlong nanos;
3585     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
3586     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
3587     return nanos;
3588   } else {
3589     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
3590   }
3591 #else
3592   Unimplemented();
3593   return 0;
3594 #endif
3595 }
3596 
3597 
3598 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3599   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
3600   info_ptr->may_skip_backward = false;     // elapsed time not wall time
3601   info_ptr->may_skip_forward = false;      // elapsed time not wall time
3602   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
3603 }
3604 
3605 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3606   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
3607   info_ptr->may_skip_backward = false;     // elapsed time not wall time
3608   info_ptr->may_skip_forward = false;      // elapsed time not wall time
3609   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
3610 }
3611 
3612 bool os::is_thread_cpu_time_supported() {
3613 #ifdef __APPLE__
3614   return true;
3615 #else
3616   return false;
3617 #endif
3618 }
3619 
3620 // System loadavg support.  Returns -1 if load average cannot be obtained.
3621 // Bsd doesn't yet have a (official) notion of processor sets,
3622 // so just return the system wide load average.
3623 int os::loadavg(double loadavg[], int nelem) {
3624   return ::getloadavg(loadavg, nelem);
3625 }
3626 
3627 void os::pause() {
3628   char filename[MAX_PATH];
3629   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
3630     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
3631   } else {
3632     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
3633   }
3634 
3635   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3636   if (fd != -1) {
3637     struct stat buf;
3638     ::close(fd);
3639     while (::stat(filename, &buf) == 0) {
3640       (void)::poll(NULL, 0, 100);
3641     }
3642   } else {
3643     jio_fprintf(stderr,
3644                 "Could not open pause file '%s', continuing immediately.\n", filename);
3645   }
3646 }
3647 
3648 // Darwin has no "environ" in a dynamic library.
3649 #ifdef __APPLE__
3650   #include <crt_externs.h>
3651   #define environ (*_NSGetEnviron())
3652 #else
3653 extern char** environ;
3654 #endif
3655 
3656 // Run the specified command in a separate process. Return its exit value,
3657 // or -1 on failure (e.g. can't fork a new process).
3658 // Unlike system(), this function can be called from signal handler. It
3659 // doesn't block SIGINT et al.
3660 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {
3661   const char * argv[4] = {"sh", "-c", cmd, NULL};
3662 
3663   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
3664   // pthread_atfork handlers and reset pthread library. All we need is a
3665   // separate process to execve. Make a direct syscall to fork process.
3666   // On IA64 there's no fork syscall, we have to use fork() and hope for
3667   // the best...
3668   pid_t pid = fork();
3669 
3670   if (pid < 0) {
3671     // fork failed
3672     return -1;
3673 
3674   } else if (pid == 0) {
3675     // child process
3676 
3677     // execve() in BsdThreads will call pthread_kill_other_threads_np()
3678     // first to kill every thread on the thread list. Because this list is
3679     // not reset by fork() (see notes above), execve() will instead kill
3680     // every thread in the parent process. We know this is the only thread
3681     // in the new process, so make a system call directly.
3682     // IA64 should use normal execve() from glibc to match the glibc fork()
3683     // above.
3684     execve("/bin/sh", (char* const*)argv, environ);
3685 
3686     // execve failed
3687     _exit(-1);
3688 
3689   } else  {
3690     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
3691     // care about the actual exit code, for now.
3692 
3693     int status;
3694 
3695     // Wait for the child process to exit.  This returns immediately if
3696     // the child has already exited. */
3697     while (waitpid(pid, &status, 0) < 0) {
3698       switch (errno) {
3699       case ECHILD: return 0;
3700       case EINTR: break;
3701       default: return -1;
3702       }
3703     }
3704 
3705     if (WIFEXITED(status)) {
3706       // The child exited normally; get its exit code.
3707       return WEXITSTATUS(status);
3708     } else if (WIFSIGNALED(status)) {
3709       // The child exited because of a signal
3710       // The best value to return is 0x80 + signal number,
3711       // because that is what all Unix shells do, and because
3712       // it allows callers to distinguish between process exit and
3713       // process death by signal.
3714       return 0x80 + WTERMSIG(status);
3715     } else {
3716       // Unknown exit code; pass it through
3717       return status;
3718     }
3719   }
3720 }
3721 
3722 // Get the kern.corefile setting, or otherwise the default path to the core file
3723 // Returns the length of the string
3724 int os::get_core_path(char* buffer, size_t bufferSize) {
3725   int n = 0;
3726 #ifdef __APPLE__
3727   char coreinfo[MAX_PATH];
3728   size_t sz = sizeof(coreinfo);
3729   int ret = sysctlbyname("kern.corefile", coreinfo, &sz, NULL, 0);
3730   if (ret == 0) {
3731     char *pid_pos = strstr(coreinfo, "%P");
3732     // skip over the "%P" to preserve any optional custom user pattern
3733     const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : "";
3734 
3735     if (pid_pos != NULL) {
3736       *pid_pos = '\0';
3737       n = jio_snprintf(buffer, bufferSize, "%s%d%s", coreinfo, os::current_process_id(), tail);
3738     } else {
3739       n = jio_snprintf(buffer, bufferSize, "%s", coreinfo);
3740     }
3741   } else
3742 #endif
3743   {
3744     n = jio_snprintf(buffer, bufferSize, "/cores/core.%d", os::current_process_id());
3745   }
3746   // Truncate if theoretical string was longer than bufferSize
3747   n = MIN2(n, (int)bufferSize);
3748 
3749   return n;
3750 }
3751 
3752 bool os::supports_map_sync() {
3753   return false;
3754 }
3755 
3756 #ifndef PRODUCT
3757 void TestReserveMemorySpecial_test() {
3758   // No tests available for this platform
3759 }
3760 #endif
3761 
3762 bool os::start_debugging(char *buf, int buflen) {
3763   int len = (int)strlen(buf);
3764   char *p = &buf[len];
3765 
3766   jio_snprintf(p, buflen-len,
3767              "\n\n"
3768              "Do you want to debug the problem?\n\n"
3769              "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " INTX_FORMAT " (" INTPTR_FORMAT ")\n"
3770              "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
3771              "Otherwise, press RETURN to abort...",
3772              os::current_process_id(), os::current_process_id(),
3773              os::current_thread_id(), os::current_thread_id());
3774 
3775   bool yes = os::message_box("Unexpected Error", buf);
3776 
3777   if (yes) {
3778     // yes, user asked VM to launch debugger
3779     jio_snprintf(buf, sizeof(buf), "gdb /proc/%d/exe %d",
3780                      os::current_process_id(), os::current_process_id());
3781 
3782     os::fork_and_exec(buf);
3783     yes = false;
3784   }
3785   return yes;
3786 }