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     ::abort(); // dump core
1068   }
1069 
1070   ::exit(1);
1071 }
1072 
1073 // Die immediately, no exit hook, no abort hook, no cleanup.
1074 // Dump a core file, if possible, for debugging.
1075 void os::die() {
1076   if (TestUnresponsiveErrorHandler && !CreateCoredumpOnCrash) {
1077     // For TimeoutInErrorHandlingTest.java, we just kill the VM
1078     // and don't take the time to generate a core file.
1079     os::signal_raise(SIGKILL);
1080   } else {
1081     // _exit() on BsdThreads only kills current thread
1082     ::abort();
1083   }
1084 }
1085 
1086 // Information of current thread in variety of formats
1087 pid_t os::Bsd::gettid() {
1088   int retval = -1;
1089 
1090 #ifdef __APPLE__ // XNU kernel
1091   mach_port_t port = mach_thread_self();
1092   guarantee(MACH_PORT_VALID(port), "just checking");
1093   mach_port_deallocate(mach_task_self(), port);
1094   return (pid_t)port;
1095 
1096 #else
1097   #ifdef __FreeBSD__
1098   retval = syscall(SYS_thr_self);
1099   #else
1100     #ifdef __OpenBSD__
1101   retval = syscall(SYS_getthrid);
1102     #else
1103       #ifdef __NetBSD__
1104   retval = (pid_t) syscall(SYS__lwp_self);
1105       #endif
1106     #endif
1107   #endif
1108 #endif
1109 
1110   if (retval == -1) {
1111     return getpid();
1112   }
1113 }
1114 
1115 intx os::current_thread_id() {
1116 #ifdef __APPLE__
1117   return (intx)os::Bsd::gettid();
1118 #else
1119   return (intx)::pthread_self();
1120 #endif
1121 }
1122 
1123 int os::current_process_id() {
1124   return (int)(getpid());
1125 }
1126 
1127 // DLL functions
1128 
1129 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1130 
1131 // This must be hard coded because it's the system's temporary
1132 // directory not the java application's temp directory, ala java.io.tmpdir.
1133 #ifdef __APPLE__
1134 // macosx has a secure per-user temporary directory
1135 char temp_path_storage[PATH_MAX];
1136 const char* os::get_temp_directory() {
1137   static char *temp_path = NULL;
1138   if (temp_path == NULL) {
1139     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1140     if (pathSize == 0 || pathSize > PATH_MAX) {
1141       strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1142     }
1143     temp_path = temp_path_storage;
1144   }
1145   return temp_path;
1146 }
1147 #else // __APPLE__
1148 const char* os::get_temp_directory() { return "/tmp"; }
1149 #endif // __APPLE__
1150 
1151 // check if addr is inside libjvm.so
1152 bool os::address_is_in_vm(address addr) {
1153   static address libjvm_base_addr;
1154   Dl_info dlinfo;
1155 
1156   if (libjvm_base_addr == NULL) {
1157     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1158       libjvm_base_addr = (address)dlinfo.dli_fbase;
1159     }
1160     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1161   }
1162 
1163   if (dladdr((void *)addr, &dlinfo) != 0) {
1164     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1165   }
1166 
1167   return false;
1168 }
1169 
1170 
1171 #define MACH_MAXSYMLEN 256
1172 
1173 bool os::dll_address_to_function_name(address addr, char *buf,
1174                                       int buflen, int *offset,
1175                                       bool demangle) {
1176   // buf is not optional, but offset is optional
1177   assert(buf != NULL, "sanity check");
1178 
1179   Dl_info dlinfo;
1180   char localbuf[MACH_MAXSYMLEN];
1181 
1182   if (dladdr((void*)addr, &dlinfo) != 0) {
1183     // see if we have a matching symbol
1184     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1185       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1186         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1187       }
1188       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1189       return true;
1190     }
1191     // no matching symbol so try for just file info
1192     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1193       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1194                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1195         return true;
1196       }
1197     }
1198 
1199     // Handle non-dynamic manually:
1200     if (dlinfo.dli_fbase != NULL &&
1201         Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1202                         dlinfo.dli_fbase)) {
1203       if (!(demangle && Decoder::demangle(localbuf, buf, buflen))) {
1204         jio_snprintf(buf, buflen, "%s", localbuf);
1205       }
1206       return true;
1207     }
1208   }
1209   buf[0] = '\0';
1210   if (offset != NULL) *offset = -1;
1211   return false;
1212 }
1213 
1214 // ported from solaris version
1215 bool os::dll_address_to_library_name(address addr, char* buf,
1216                                      int buflen, int* offset) {
1217   // buf is not optional, but offset is optional
1218   assert(buf != NULL, "sanity check");
1219 
1220   Dl_info dlinfo;
1221 
1222   if (dladdr((void*)addr, &dlinfo) != 0) {
1223     if (dlinfo.dli_fname != NULL) {
1224       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1225     }
1226     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1227       *offset = addr - (address)dlinfo.dli_fbase;
1228     }
1229     return true;
1230   }
1231 
1232   buf[0] = '\0';
1233   if (offset) *offset = -1;
1234   return false;
1235 }
1236 
1237 // Loads .dll/.so and
1238 // in case of error it checks if .dll/.so was built for the
1239 // same architecture as Hotspot is running on
1240 
1241 #ifdef __APPLE__
1242 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1243 #ifdef STATIC_BUILD
1244   return os::get_default_process_handle();
1245 #else
1246   log_info(os)("attempting shared library load of %s", filename);
1247 
1248   void * result= ::dlopen(filename, RTLD_LAZY);
1249   if (result != NULL) {
1250     Events::log(NULL, "Loaded shared library %s", filename);
1251     // Successful loading
1252     log_info(os)("shared library load of %s was successful", filename);
1253     return result;
1254   }
1255 
1256   const char* error_report = ::dlerror();
1257   if (error_report == NULL) {
1258     error_report = "dlerror returned no error description";
1259   }
1260   if (ebuf != NULL && ebuflen > 0) {
1261     // Read system error message into ebuf
1262     ::strncpy(ebuf, error_report, ebuflen-1);
1263     ebuf[ebuflen-1]='\0';
1264   }
1265   Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1266   log_info(os)("shared library load of %s failed, %s", filename, error_report);
1267 
1268   return NULL;
1269 #endif // STATIC_BUILD
1270 }
1271 #else
1272 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1273 #ifdef STATIC_BUILD
1274   return os::get_default_process_handle();
1275 #else
1276   log_info(os)("attempting shared library load of %s", filename);
1277   void * result= ::dlopen(filename, RTLD_LAZY);
1278   if (result != NULL) {
1279     Events::log(NULL, "Loaded shared library %s", filename);
1280     // Successful loading
1281     log_info(os)("shared library load of %s was successful", filename);
1282     return result;
1283   }
1284 
1285   Elf32_Ehdr elf_head;
1286 
1287   const char* const error_report = ::dlerror();
1288   if (error_report == NULL) {
1289     error_report = "dlerror returned no error description";
1290   }
1291   if (ebuf != NULL && ebuflen > 0) {
1292     // Read system error message into ebuf
1293     ::strncpy(ebuf, error_report, ebuflen-1);
1294     ebuf[ebuflen-1]='\0';
1295   }
1296   Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1297   log_info(os)("shared library load of %s failed, %s", filename, error_report);
1298 
1299   int diag_msg_max_length=ebuflen-strlen(ebuf);
1300   char* diag_msg_buf=ebuf+strlen(ebuf);
1301 
1302   if (diag_msg_max_length==0) {
1303     // No more space in ebuf for additional diagnostics message
1304     return NULL;
1305   }
1306 
1307 
1308   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1309 
1310   if (file_descriptor < 0) {
1311     // Can't open library, report dlerror() message
1312     return NULL;
1313   }
1314 
1315   bool failed_to_read_elf_head=
1316     (sizeof(elf_head)!=
1317      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1318 
1319   ::close(file_descriptor);
1320   if (failed_to_read_elf_head) {
1321     // file i/o error - report dlerror() msg
1322     return NULL;
1323   }
1324 
1325   typedef struct {
1326     Elf32_Half  code;         // Actual value as defined in elf.h
1327     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1328     char        elf_class;    // 32 or 64 bit
1329     char        endianess;    // MSB or LSB
1330     char*       name;         // String representation
1331   } arch_t;
1332 
1333   #ifndef EM_486
1334     #define EM_486          6               /* Intel 80486 */
1335   #endif
1336 
1337   #ifndef EM_MIPS_RS3_LE
1338     #define EM_MIPS_RS3_LE  10              /* MIPS */
1339   #endif
1340 
1341   #ifndef EM_PPC64
1342     #define EM_PPC64        21              /* PowerPC64 */
1343   #endif
1344 
1345   #ifndef EM_S390
1346     #define EM_S390         22              /* IBM System/390 */
1347   #endif
1348 
1349   #ifndef EM_IA_64
1350     #define EM_IA_64        50              /* HP/Intel IA-64 */
1351   #endif
1352 
1353   #ifndef EM_X86_64
1354     #define EM_X86_64       62              /* AMD x86-64 */
1355   #endif
1356 
1357   static const arch_t arch_array[]={
1358     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1359     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1360     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1361     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1362     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1363     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1364     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1365     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1366     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1367     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1368     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1369     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1370     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1371   };
1372 
1373   #if  (defined IA32)
1374   static  Elf32_Half running_arch_code=EM_386;
1375   #elif   (defined AMD64)
1376   static  Elf32_Half running_arch_code=EM_X86_64;
1377   #elif  (defined IA64)
1378   static  Elf32_Half running_arch_code=EM_IA_64;
1379   #elif  (defined __powerpc64__)
1380   static  Elf32_Half running_arch_code=EM_PPC64;
1381   #elif  (defined __powerpc__)
1382   static  Elf32_Half running_arch_code=EM_PPC;
1383   #elif  (defined ARM)
1384   static  Elf32_Half running_arch_code=EM_ARM;
1385   #elif  (defined S390)
1386   static  Elf32_Half running_arch_code=EM_S390;
1387   #elif  (defined ALPHA)
1388   static  Elf32_Half running_arch_code=EM_ALPHA;
1389   #elif  (defined MIPSEL)
1390   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1391   #elif  (defined PARISC)
1392   static  Elf32_Half running_arch_code=EM_PARISC;
1393   #elif  (defined MIPS)
1394   static  Elf32_Half running_arch_code=EM_MIPS;
1395   #elif  (defined M68K)
1396   static  Elf32_Half running_arch_code=EM_68K;
1397   #else
1398     #error Method os::dll_load requires that one of following is defined:\
1399          IA32, AMD64, IA64, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1400   #endif
1401 
1402   // Identify compatability class for VM's architecture and library's architecture
1403   // Obtain string descriptions for architectures
1404 
1405   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1406   int running_arch_index=-1;
1407 
1408   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1409     if (running_arch_code == arch_array[i].code) {
1410       running_arch_index    = i;
1411     }
1412     if (lib_arch.code == arch_array[i].code) {
1413       lib_arch.compat_class = arch_array[i].compat_class;
1414       lib_arch.name         = arch_array[i].name;
1415     }
1416   }
1417 
1418   assert(running_arch_index != -1,
1419          "Didn't find running architecture code (running_arch_code) in arch_array");
1420   if (running_arch_index == -1) {
1421     // Even though running architecture detection failed
1422     // we may still continue with reporting dlerror() message
1423     return NULL;
1424   }
1425 
1426   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1427     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1428     return NULL;
1429   }
1430 
1431 #ifndef S390
1432   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1433     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1434     return NULL;
1435   }
1436 #endif // !S390
1437 
1438   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1439     if (lib_arch.name!=NULL) {
1440       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1441                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1442                  lib_arch.name, arch_array[running_arch_index].name);
1443     } else {
1444       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1445                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1446                  lib_arch.code,
1447                  arch_array[running_arch_index].name);
1448     }
1449   }
1450 
1451   return NULL;
1452 #endif // STATIC_BUILD
1453 }
1454 #endif // !__APPLE__
1455 
1456 void* os::get_default_process_handle() {
1457 #ifdef __APPLE__
1458   // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
1459   // to avoid finding unexpected symbols on second (or later)
1460   // loads of a library.
1461   return (void*)::dlopen(NULL, RTLD_FIRST);
1462 #else
1463   return (void*)::dlopen(NULL, RTLD_LAZY);
1464 #endif
1465 }
1466 
1467 // XXX: Do we need a lock around this as per Linux?
1468 void* os::dll_lookup(void* handle, const char* name) {
1469   return dlsym(handle, name);
1470 }
1471 
1472 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1473   outputStream * out = (outputStream *) param;
1474   out->print_cr(INTPTR_FORMAT " \t%s", (intptr_t)base_address, name);
1475   return 0;
1476 }
1477 
1478 void os::print_dll_info(outputStream *st) {
1479   st->print_cr("Dynamic libraries:");
1480   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1481     st->print_cr("Error: Cannot print dynamic libraries.");
1482   }
1483 }
1484 
1485 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1486 #ifdef RTLD_DI_LINKMAP
1487   Dl_info dli;
1488   void *handle;
1489   Link_map *map;
1490   Link_map *p;
1491 
1492   if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1493       dli.dli_fname == NULL) {
1494     return 1;
1495   }
1496   handle = dlopen(dli.dli_fname, RTLD_LAZY);
1497   if (handle == NULL) {
1498     return 1;
1499   }
1500   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1501   if (map == NULL) {
1502     dlclose(handle);
1503     return 1;
1504   }
1505 
1506   while (map->l_prev != NULL)
1507     map = map->l_prev;
1508 
1509   while (map != NULL) {
1510     // Value for top_address is returned as 0 since we don't have any information about module size
1511     if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1512       dlclose(handle);
1513       return 1;
1514     }
1515     map = map->l_next;
1516   }
1517 
1518   dlclose(handle);
1519 #elif defined(__APPLE__)
1520   for (uint32_t i = 1; i < _dyld_image_count(); i++) {
1521     // Value for top_address is returned as 0 since we don't have any information about module size
1522     if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {
1523       return 1;
1524     }
1525   }
1526   return 0;
1527 #else
1528   return 1;
1529 #endif
1530 }
1531 
1532 void os::get_summary_os_info(char* buf, size_t buflen) {
1533   // These buffers are small because we want this to be brief
1534   // and not use a lot of stack while generating the hs_err file.
1535   char os[100];
1536   size_t size = sizeof(os);
1537   int mib_kern[] = { CTL_KERN, KERN_OSTYPE };
1538   if (sysctl(mib_kern, 2, os, &size, NULL, 0) < 0) {
1539 #ifdef __APPLE__
1540       strncpy(os, "Darwin", sizeof(os));
1541 #elif __OpenBSD__
1542       strncpy(os, "OpenBSD", sizeof(os));
1543 #else
1544       strncpy(os, "BSD", sizeof(os));
1545 #endif
1546   }
1547 
1548   char release[100];
1549   size = sizeof(release);
1550   int mib_release[] = { CTL_KERN, KERN_OSRELEASE };
1551   if (sysctl(mib_release, 2, release, &size, NULL, 0) < 0) {
1552       // if error, leave blank
1553       strncpy(release, "", sizeof(release));
1554   }
1555   snprintf(buf, buflen, "%s %s", os, release);
1556 }
1557 
1558 void os::print_os_info_brief(outputStream* st) {
1559   os::Posix::print_uname_info(st);
1560 }
1561 
1562 void os::print_os_info(outputStream* st) {
1563   st->print("OS:");
1564 
1565   os::Posix::print_uname_info(st);
1566 
1567   os::Bsd::print_uptime_info(st);
1568 
1569   os::Posix::print_rlimit_info(st);
1570 
1571   os::Posix::print_load_average(st);
1572 
1573   VM_Version::print_platform_virtualization_info(st);
1574 }
1575 
1576 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1577   // Nothing to do for now.
1578 }
1579 
1580 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1581   unsigned int mhz;
1582   size_t size = sizeof(mhz);
1583   int mib[] = { CTL_HW, HW_CPU_FREQ };
1584   if (sysctl(mib, 2, &mhz, &size, NULL, 0) < 0) {
1585     mhz = 1;  // looks like an error but can be divided by
1586   } else {
1587     mhz /= 1000000;  // reported in millions
1588   }
1589 
1590   char model[100];
1591   size = sizeof(model);
1592   int mib_model[] = { CTL_HW, HW_MODEL };
1593   if (sysctl(mib_model, 2, model, &size, NULL, 0) < 0) {
1594     strncpy(model, cpu_arch, sizeof(model));
1595   }
1596 
1597   char machine[100];
1598   size = sizeof(machine);
1599   int mib_machine[] = { CTL_HW, HW_MACHINE };
1600   if (sysctl(mib_machine, 2, machine, &size, NULL, 0) < 0) {
1601       strncpy(machine, "", sizeof(machine));
1602   }
1603 
1604   snprintf(buf, buflen, "%s %s %d MHz", model, machine, mhz);
1605 }
1606 
1607 void os::print_memory_info(outputStream* st) {
1608   xsw_usage swap_usage;
1609   size_t size = sizeof(swap_usage);
1610 
1611   st->print("Memory:");
1612   st->print(" %dk page", os::vm_page_size()>>10);
1613 
1614   st->print(", physical " UINT64_FORMAT "k",
1615             os::physical_memory() >> 10);
1616   st->print("(" UINT64_FORMAT "k free)",
1617             os::available_memory() >> 10);
1618 
1619   if((sysctlbyname("vm.swapusage", &swap_usage, &size, NULL, 0) == 0) || (errno == ENOMEM)) {
1620     if (size >= offset_of(xsw_usage, xsu_used)) {
1621       st->print(", swap " UINT64_FORMAT "k",
1622                 ((julong) swap_usage.xsu_total) >> 10);
1623       st->print("(" UINT64_FORMAT "k free)",
1624                 ((julong) swap_usage.xsu_avail) >> 10);
1625     }
1626   }
1627 
1628   st->cr();
1629 }
1630 
1631 static void print_signal_handler(outputStream* st, int sig,
1632                                  char* buf, size_t buflen);
1633 
1634 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1635   st->print_cr("Signal Handlers:");
1636   print_signal_handler(st, SIGSEGV, buf, buflen);
1637   print_signal_handler(st, SIGBUS , buf, buflen);
1638   print_signal_handler(st, SIGFPE , buf, buflen);
1639   print_signal_handler(st, SIGPIPE, buf, buflen);
1640   print_signal_handler(st, SIGXFSZ, buf, buflen);
1641   print_signal_handler(st, SIGILL , buf, buflen);
1642   print_signal_handler(st, SR_signum, buf, buflen);
1643   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
1644   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1645   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
1646   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1647 }
1648 
1649 static char saved_jvm_path[MAXPATHLEN] = {0};
1650 
1651 // Find the full path to the current module, libjvm
1652 void os::jvm_path(char *buf, jint buflen) {
1653   // Error checking.
1654   if (buflen < MAXPATHLEN) {
1655     assert(false, "must use a large-enough buffer");
1656     buf[0] = '\0';
1657     return;
1658   }
1659   // Lazy resolve the path to current module.
1660   if (saved_jvm_path[0] != 0) {
1661     strcpy(buf, saved_jvm_path);
1662     return;
1663   }
1664 
1665   char dli_fname[MAXPATHLEN];
1666   bool ret = dll_address_to_library_name(
1667                                          CAST_FROM_FN_PTR(address, os::jvm_path),
1668                                          dli_fname, sizeof(dli_fname), NULL);
1669   assert(ret, "cannot locate libjvm");
1670   char *rp = NULL;
1671   if (ret && dli_fname[0] != '\0') {
1672     rp = os::Posix::realpath(dli_fname, buf, buflen);
1673   }
1674   if (rp == NULL) {
1675     return;
1676   }
1677 
1678   if (Arguments::sun_java_launcher_is_altjvm()) {
1679     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
1680     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
1681     // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
1682     // appears at the right place in the string, then assume we are
1683     // installed in a JDK and we're done. Otherwise, check for a
1684     // JAVA_HOME environment variable and construct a path to the JVM
1685     // being overridden.
1686 
1687     const char *p = buf + strlen(buf) - 1;
1688     for (int count = 0; p > buf && count < 5; ++count) {
1689       for (--p; p > buf && *p != '/'; --p)
1690         /* empty */ ;
1691     }
1692 
1693     if (strncmp(p, "/jre/lib/", 9) != 0) {
1694       // Look for JAVA_HOME in the environment.
1695       char* java_home_var = ::getenv("JAVA_HOME");
1696       if (java_home_var != NULL && java_home_var[0] != 0) {
1697         char* jrelib_p;
1698         int len;
1699 
1700         // Check the current module name "libjvm"
1701         p = strrchr(buf, '/');
1702         assert(strstr(p, "/libjvm") == p, "invalid library name");
1703 
1704         rp = os::Posix::realpath(java_home_var, buf, buflen);
1705         if (rp == NULL) {
1706           return;
1707         }
1708 
1709         // determine if this is a legacy image or modules image
1710         // modules image doesn't have "jre" subdirectory
1711         len = strlen(buf);
1712         assert(len < buflen, "Ran out of buffer space");
1713         jrelib_p = buf + len;
1714 
1715         // Add the appropriate library subdir
1716         snprintf(jrelib_p, buflen-len, "/jre/lib");
1717         if (0 != access(buf, F_OK)) {
1718           snprintf(jrelib_p, buflen-len, "/lib");
1719         }
1720 
1721         // Add the appropriate client or server subdir
1722         len = strlen(buf);
1723         jrelib_p = buf + len;
1724         snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1725         if (0 != access(buf, F_OK)) {
1726           snprintf(jrelib_p, buflen-len, "%s", "");
1727         }
1728 
1729         // If the path exists within JAVA_HOME, add the JVM library name
1730         // to complete the path to JVM being overridden.  Otherwise fallback
1731         // to the path to the current library.
1732         if (0 == access(buf, F_OK)) {
1733           // Use current module name "libjvm"
1734           len = strlen(buf);
1735           snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1736         } else {
1737           // Fall back to path of current library
1738           rp = os::Posix::realpath(dli_fname, buf, buflen);
1739           if (rp == NULL) {
1740             return;
1741           }
1742         }
1743       }
1744     }
1745   }
1746 
1747   strncpy(saved_jvm_path, buf, MAXPATHLEN);
1748   saved_jvm_path[MAXPATHLEN - 1] = '\0';
1749 }
1750 
1751 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1752   // no prefix required, not even "_"
1753 }
1754 
1755 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1756   // no suffix required
1757 }
1758 
1759 ////////////////////////////////////////////////////////////////////////////////
1760 // sun.misc.Signal support
1761 
1762 static void UserHandler(int sig, void *siginfo, void *context) {
1763   // Ctrl-C is pressed during error reporting, likely because the error
1764   // handler fails to abort. Let VM die immediately.
1765   if (sig == SIGINT && VMError::is_error_reported()) {
1766     os::die();
1767   }
1768 
1769   os::signal_notify(sig);
1770 }
1771 
1772 void* os::user_handler() {
1773   return CAST_FROM_FN_PTR(void*, UserHandler);
1774 }
1775 
1776 extern "C" {
1777   typedef void (*sa_handler_t)(int);
1778   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
1779 }
1780 
1781 void* os::signal(int signal_number, void* handler) {
1782   struct sigaction sigAct, oldSigAct;
1783 
1784   sigfillset(&(sigAct.sa_mask));
1785   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
1786   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
1787 
1788   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
1789     // -1 means registration failed
1790     return (void *)-1;
1791   }
1792 
1793   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
1794 }
1795 
1796 void os::signal_raise(int signal_number) {
1797   ::raise(signal_number);
1798 }
1799 
1800 // The following code is moved from os.cpp for making this
1801 // code platform specific, which it is by its very nature.
1802 
1803 // Will be modified when max signal is changed to be dynamic
1804 int os::sigexitnum_pd() {
1805   return NSIG;
1806 }
1807 
1808 // a counter for each possible signal value
1809 static volatile jint pending_signals[NSIG+1] = { 0 };
1810 static Semaphore* sig_sem = NULL;
1811 
1812 static void jdk_misc_signal_init() {
1813   // Initialize signal structures
1814   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
1815 
1816   // Initialize signal semaphore
1817   sig_sem = new Semaphore();
1818 }
1819 
1820 void os::signal_notify(int sig) {
1821   if (sig_sem != NULL) {
1822     Atomic::inc(&pending_signals[sig]);
1823     sig_sem->signal();
1824   } else {
1825     // Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init
1826     // initialization isn't called.
1827     assert(ReduceSignalUsage, "signal semaphore should be created");
1828   }
1829 }
1830 
1831 static int check_pending_signals() {
1832   for (;;) {
1833     for (int i = 0; i < NSIG + 1; i++) {
1834       jint n = pending_signals[i];
1835       if (n > 0 && n == Atomic::cmpxchg(&pending_signals[i], n, n - 1)) {
1836         return i;
1837       }
1838     }
1839     JavaThread *thread = JavaThread::current();
1840     ThreadBlockInVM tbivm(thread);
1841 
1842     bool threadIsSuspended;
1843     do {
1844       thread->set_suspend_equivalent();
1845       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1846       sig_sem->wait();
1847 
1848       // were we externally suspended while we were waiting?
1849       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
1850       if (threadIsSuspended) {
1851         // The semaphore has been incremented, but while we were waiting
1852         // another thread suspended us. We don't want to continue running
1853         // while suspended because that would surprise the thread that
1854         // suspended us.
1855         sig_sem->signal();
1856 
1857         thread->java_suspend_self();
1858       }
1859     } while (threadIsSuspended);
1860   }
1861 }
1862 
1863 int os::signal_wait() {
1864   return check_pending_signals();
1865 }
1866 
1867 ////////////////////////////////////////////////////////////////////////////////
1868 // Virtual Memory
1869 
1870 int os::vm_page_size() {
1871   // Seems redundant as all get out
1872   assert(os::Bsd::page_size() != -1, "must call os::init");
1873   return os::Bsd::page_size();
1874 }
1875 
1876 // Solaris allocates memory by pages.
1877 int os::vm_allocation_granularity() {
1878   assert(os::Bsd::page_size() != -1, "must call os::init");
1879   return os::Bsd::page_size();
1880 }
1881 
1882 // Rationale behind this function:
1883 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
1884 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
1885 //  samples for JITted code. Here we create private executable mapping over the code cache
1886 //  and then we can use standard (well, almost, as mapping can change) way to provide
1887 //  info for the reporting script by storing timestamp and location of symbol
1888 void bsd_wrap_code(char* base, size_t size) {
1889   static volatile jint cnt = 0;
1890 
1891   if (!UseOprofile) {
1892     return;
1893   }
1894 
1895   char buf[PATH_MAX + 1];
1896   int num = Atomic::add(&cnt, 1);
1897 
1898   snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
1899            os::get_temp_directory(), os::current_process_id(), num);
1900   unlink(buf);
1901 
1902   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
1903 
1904   if (fd != -1) {
1905     off_t rv = ::lseek(fd, size-2, SEEK_SET);
1906     if (rv != (off_t)-1) {
1907       if (::write(fd, "", 1) == 1) {
1908         mmap(base, size,
1909              PROT_READ|PROT_WRITE|PROT_EXEC,
1910              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
1911       }
1912     }
1913     ::close(fd);
1914     unlink(buf);
1915   }
1916 }
1917 
1918 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
1919                                     int err) {
1920   warning("INFO: os::commit_memory(" INTPTR_FORMAT ", " SIZE_FORMAT
1921           ", %d) failed; error='%s' (errno=%d)", (intptr_t)addr, size, exec,
1922            os::errno_name(err), err);
1923 }
1924 
1925 // NOTE: Bsd kernel does not really reserve the pages for us.
1926 //       All it does is to check if there are enough free pages
1927 //       left at the time of mmap(). This could be a potential
1928 //       problem.
1929 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
1930   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
1931 #ifdef __OpenBSD__
1932   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
1933   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(addr), p2i(addr+size), prot);
1934   if (::mprotect(addr, size, prot) == 0) {
1935     return true;
1936   }
1937 #else
1938   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
1939                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
1940   if (res != (uintptr_t) MAP_FAILED) {
1941     return true;
1942   }
1943 #endif
1944 
1945   // Warn about any commit errors we see in non-product builds just
1946   // in case mmap() doesn't work as described on the man page.
1947   NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
1948 
1949   return false;
1950 }
1951 
1952 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
1953                           bool exec) {
1954   // alignment_hint is ignored on this OS
1955   return pd_commit_memory(addr, size, exec);
1956 }
1957 
1958 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
1959                                   const char* mesg) {
1960   assert(mesg != NULL, "mesg must be specified");
1961   if (!pd_commit_memory(addr, size, exec)) {
1962     // add extra info in product mode for vm_exit_out_of_memory():
1963     PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
1964     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
1965   }
1966 }
1967 
1968 void os::pd_commit_memory_or_exit(char* addr, size_t size,
1969                                   size_t alignment_hint, bool exec,
1970                                   const char* mesg) {
1971   // alignment_hint is ignored on this OS
1972   pd_commit_memory_or_exit(addr, size, exec, mesg);
1973 }
1974 
1975 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1976 }
1977 
1978 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1979   ::madvise(addr, bytes, MADV_DONTNEED);
1980 }
1981 
1982 void os::numa_make_global(char *addr, size_t bytes) {
1983 }
1984 
1985 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
1986 }
1987 
1988 bool os::numa_topology_changed()   { return false; }
1989 
1990 size_t os::numa_get_groups_num() {
1991   return 1;
1992 }
1993 
1994 int os::numa_get_group_id() {
1995   return 0;
1996 }
1997 
1998 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
1999   if (size > 0) {
2000     ids[0] = 0;
2001     return 1;
2002   }
2003   return 0;
2004 }
2005 
2006 int os::numa_get_group_id_for_address(const void* address) {
2007   return 0;
2008 }
2009 
2010 bool os::get_page_info(char *start, page_info* info) {
2011   return false;
2012 }
2013 
2014 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2015   return end;
2016 }
2017 
2018 
2019 bool os::pd_uncommit_memory(char* addr, size_t size) {
2020 #ifdef __OpenBSD__
2021   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
2022   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with PROT_NONE", p2i(addr), p2i(addr+size));
2023   return ::mprotect(addr, size, PROT_NONE) == 0;
2024 #else
2025   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2026                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2027   return res  != (uintptr_t) MAP_FAILED;
2028 #endif
2029 }
2030 
2031 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2032   return os::commit_memory(addr, size, !ExecMem);
2033 }
2034 
2035 // If this is a growable mapping, remove the guard pages entirely by
2036 // munmap()ping them.  If not, just call uncommit_memory().
2037 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2038   return os::uncommit_memory(addr, size);
2039 }
2040 
2041 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2042 // at 'requested_addr'. If there are existing memory mappings at the same
2043 // location, however, they will be overwritten. If 'fixed' is false,
2044 // 'requested_addr' is only treated as a hint, the return value may or
2045 // may not start from the requested address. Unlike Bsd mmap(), this
2046 // function returns NULL to indicate failure.
2047 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2048   char * addr;
2049   int flags;
2050 
2051   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2052   if (fixed) {
2053     assert((uintptr_t)requested_addr % os::Bsd::page_size() == 0, "unaligned address");
2054     flags |= MAP_FIXED;
2055   }
2056 
2057   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
2058   // touch an uncommitted page. Otherwise, the read/write might
2059   // succeed if we have enough swap space to back the physical page.
2060   addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
2061                        flags, -1, 0);
2062 
2063   return addr == MAP_FAILED ? NULL : addr;
2064 }
2065 
2066 static int anon_munmap(char * addr, size_t size) {
2067   return ::munmap(addr, size) == 0;
2068 }
2069 
2070 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2071                             size_t alignment_hint) {
2072   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
2073 }
2074 
2075 bool os::pd_release_memory(char* addr, size_t size) {
2076   return anon_munmap(addr, size);
2077 }
2078 
2079 static bool bsd_mprotect(char* addr, size_t size, int prot) {
2080   // Bsd wants the mprotect address argument to be page aligned.
2081   char* bottom = (char*)align_down((intptr_t)addr, os::Bsd::page_size());
2082 
2083   // According to SUSv3, mprotect() should only be used with mappings
2084   // established by mmap(), and mmap() always maps whole pages. Unaligned
2085   // 'addr' likely indicates problem in the VM (e.g. trying to change
2086   // protection of malloc'ed or statically allocated memory). Check the
2087   // caller if you hit this assert.
2088   assert(addr == bottom, "sanity check");
2089 
2090   size = align_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
2091   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);
2092   return ::mprotect(bottom, size, prot) == 0;
2093 }
2094 
2095 // Set protections specified
2096 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2097                         bool is_committed) {
2098   unsigned int p = 0;
2099   switch (prot) {
2100   case MEM_PROT_NONE: p = PROT_NONE; break;
2101   case MEM_PROT_READ: p = PROT_READ; break;
2102   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2103   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2104   default:
2105     ShouldNotReachHere();
2106   }
2107   // is_committed is unused.
2108   return bsd_mprotect(addr, bytes, p);
2109 }
2110 
2111 bool os::guard_memory(char* addr, size_t size) {
2112   return bsd_mprotect(addr, size, PROT_NONE);
2113 }
2114 
2115 bool os::unguard_memory(char* addr, size_t size) {
2116   return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2117 }
2118 
2119 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2120   return false;
2121 }
2122 
2123 // Large page support
2124 
2125 static size_t _large_page_size = 0;
2126 
2127 void os::large_page_init() {
2128 }
2129 
2130 
2131 char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2132   fatal("os::reserve_memory_special should not be called on BSD.");
2133   return NULL;
2134 }
2135 
2136 bool os::pd_release_memory_special(char* base, size_t bytes) {
2137   fatal("os::release_memory_special should not be called on BSD.");
2138   return false;
2139 }
2140 
2141 size_t os::large_page_size() {
2142   return _large_page_size;
2143 }
2144 
2145 bool os::can_commit_large_page_memory() {
2146   // Does not matter, we do not support huge pages.
2147   return false;
2148 }
2149 
2150 bool os::can_execute_large_page_memory() {
2151   // Does not matter, we do not support huge pages.
2152   return false;
2153 }
2154 
2155 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr, int file_desc) {
2156   assert(file_desc >= 0, "file_desc is not valid");
2157   char* result = pd_attempt_reserve_memory_at(bytes, requested_addr);
2158   if (result != NULL) {
2159     if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {
2160       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
2161     }
2162   }
2163   return result;
2164 }
2165 
2166 // Reserve memory at an arbitrary address, only if that area is
2167 // available (and not reserved for something else).
2168 
2169 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2170   // Assert only that the size is a multiple of the page size, since
2171   // that's all that mmap requires, and since that's all we really know
2172   // about at this low abstraction level.  If we need higher alignment,
2173   // we can either pass an alignment to this method or verify alignment
2174   // in one of the methods further up the call chain.  See bug 5044738.
2175   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2176 
2177   // Repeatedly allocate blocks until the block is allocated at the
2178   // right spot.
2179 
2180   // Bsd mmap allows caller to pass an address as hint; give it a try first,
2181   // if kernel honors the hint then we can return immediately.
2182   char * addr = anon_mmap(requested_addr, bytes, false);
2183   if (addr == requested_addr) {
2184     return requested_addr;
2185   }
2186 
2187   if (addr != NULL) {
2188     // mmap() is successful but it fails to reserve at the requested address
2189     anon_munmap(addr, bytes);
2190   }
2191 
2192   return NULL;
2193 }
2194 
2195 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2196 void os::infinite_sleep() {
2197   while (true) {    // sleep forever ...
2198     ::sleep(100);   // ... 100 seconds at a time
2199   }
2200 }
2201 
2202 // Used to convert frequent JVM_Yield() to nops
2203 bool os::dont_yield() {
2204   return DontYieldALot;
2205 }
2206 
2207 void os::naked_yield() {
2208   sched_yield();
2209 }
2210 
2211 ////////////////////////////////////////////////////////////////////////////////
2212 // thread priority support
2213 
2214 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2215 // only supports dynamic priority, static priority must be zero. For real-time
2216 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2217 // However, for large multi-threaded applications, SCHED_RR is not only slower
2218 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2219 // of 5 runs - Sep 2005).
2220 //
2221 // The following code actually changes the niceness of kernel-thread/LWP. It
2222 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2223 // not the entire user process, and user level threads are 1:1 mapped to kernel
2224 // threads. It has always been the case, but could change in the future. For
2225 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2226 // It is only used when ThreadPriorityPolicy=1 and may require system level permission
2227 // (e.g., root privilege or CAP_SYS_NICE capability).
2228 
2229 #if !defined(__APPLE__)
2230 int os::java_to_os_priority[CriticalPriority + 1] = {
2231   19,              // 0 Entry should never be used
2232 
2233    0,              // 1 MinPriority
2234    3,              // 2
2235    6,              // 3
2236 
2237   10,              // 4
2238   15,              // 5 NormPriority
2239   18,              // 6
2240 
2241   21,              // 7
2242   25,              // 8
2243   28,              // 9 NearMaxPriority
2244 
2245   31,              // 10 MaxPriority
2246 
2247   31               // 11 CriticalPriority
2248 };
2249 #else
2250 // Using Mach high-level priority assignments
2251 int os::java_to_os_priority[CriticalPriority + 1] = {
2252    0,              // 0 Entry should never be used (MINPRI_USER)
2253 
2254   27,              // 1 MinPriority
2255   28,              // 2
2256   29,              // 3
2257 
2258   30,              // 4
2259   31,              // 5 NormPriority (BASEPRI_DEFAULT)
2260   32,              // 6
2261 
2262   33,              // 7
2263   34,              // 8
2264   35,              // 9 NearMaxPriority
2265 
2266   36,              // 10 MaxPriority
2267 
2268   36               // 11 CriticalPriority
2269 };
2270 #endif
2271 
2272 static int prio_init() {
2273   if (ThreadPriorityPolicy == 1) {
2274     if (geteuid() != 0) {
2275       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {
2276         warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \
2277                 "e.g., being the root user. If the necessary permission is not " \
2278                 "possessed, changes to priority will be silently ignored.");
2279       }
2280     }
2281   }
2282   if (UseCriticalJavaThreadPriority) {
2283     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2284   }
2285   return 0;
2286 }
2287 
2288 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2289   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
2290 
2291 #ifdef __OpenBSD__
2292   // OpenBSD pthread_setprio starves low priority threads
2293   return OS_OK;
2294 #elif defined(__FreeBSD__)
2295   int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
2296   return (ret == 0) ? OS_OK : OS_ERR;
2297 #elif defined(__APPLE__) || defined(__NetBSD__)
2298   struct sched_param sp;
2299   int policy;
2300 
2301   if (pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp) != 0) {
2302     return OS_ERR;
2303   }
2304 
2305   sp.sched_priority = newpri;
2306   if (pthread_setschedparam(thread->osthread()->pthread_id(), policy, &sp) != 0) {
2307     return OS_ERR;
2308   }
2309 
2310   return OS_OK;
2311 #else
2312   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
2313   return (ret == 0) ? OS_OK : OS_ERR;
2314 #endif
2315 }
2316 
2317 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2318   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
2319     *priority_ptr = java_to_os_priority[NormPriority];
2320     return OS_OK;
2321   }
2322 
2323   errno = 0;
2324 #if defined(__OpenBSD__) || defined(__FreeBSD__)
2325   *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
2326 #elif defined(__APPLE__) || defined(__NetBSD__)
2327   int policy;
2328   struct sched_param sp;
2329 
2330   int res = pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp);
2331   if (res != 0) {
2332     *priority_ptr = -1;
2333     return OS_ERR;
2334   } else {
2335     *priority_ptr = sp.sched_priority;
2336     return OS_OK;
2337   }
2338 #else
2339   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
2340 #endif
2341   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2342 }
2343 
2344 ////////////////////////////////////////////////////////////////////////////////
2345 // suspend/resume support
2346 
2347 //  The low-level signal-based suspend/resume support is a remnant from the
2348 //  old VM-suspension that used to be for java-suspension, safepoints etc,
2349 //  within hotspot. Currently used by JFR's OSThreadSampler
2350 //
2351 //  The remaining code is greatly simplified from the more general suspension
2352 //  code that used to be used.
2353 //
2354 //  The protocol is quite simple:
2355 //  - suspend:
2356 //      - sends a signal to the target thread
2357 //      - polls the suspend state of the osthread using a yield loop
2358 //      - target thread signal handler (SR_handler) sets suspend state
2359 //        and blocks in sigsuspend until continued
2360 //  - resume:
2361 //      - sets target osthread state to continue
2362 //      - sends signal to end the sigsuspend loop in the SR_handler
2363 //
2364 //  Note that the SR_lock plays no role in this suspend/resume protocol,
2365 //  but is checked for NULL in SR_handler as a thread termination indicator.
2366 //  The SR_lock is, however, used by JavaThread::java_suspend()/java_resume() APIs.
2367 //
2368 //  Note that resume_clear_context() and suspend_save_context() are needed
2369 //  by SR_handler(), so that fetch_frame_from_ucontext() works,
2370 //  which in part is used by:
2371 //    - Forte Analyzer: AsyncGetCallTrace()
2372 //    - StackBanging: get_frame_at_stack_banging_point()
2373 
2374 static void resume_clear_context(OSThread *osthread) {
2375   osthread->set_ucontext(NULL);
2376   osthread->set_siginfo(NULL);
2377 }
2378 
2379 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
2380   osthread->set_ucontext(context);
2381   osthread->set_siginfo(siginfo);
2382 }
2383 
2384 // Handler function invoked when a thread's execution is suspended or
2385 // resumed. We have to be careful that only async-safe functions are
2386 // called here (Note: most pthread functions are not async safe and
2387 // should be avoided.)
2388 //
2389 // Note: sigwait() is a more natural fit than sigsuspend() from an
2390 // interface point of view, but sigwait() prevents the signal hander
2391 // from being run. libpthread would get very confused by not having
2392 // its signal handlers run and prevents sigwait()'s use with the
2393 // mutex granting granting signal.
2394 //
2395 // Currently only ever called on the VMThread or JavaThread
2396 //
2397 #ifdef __APPLE__
2398 static OSXSemaphore sr_semaphore;
2399 #else
2400 static PosixSemaphore sr_semaphore;
2401 #endif
2402 
2403 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
2404   // Save and restore errno to avoid confusing native code with EINTR
2405   // after sigsuspend.
2406   int old_errno = errno;
2407 
2408   Thread* thread = Thread::current_or_null_safe();
2409   assert(thread != NULL, "Missing current thread in SR_handler");
2410 
2411   // On some systems we have seen signal delivery get "stuck" until the signal
2412   // mask is changed as part of thread termination. Check that the current thread
2413   // has not already terminated (via SR_lock()) - else the following assertion
2414   // will fail because the thread is no longer a JavaThread as the ~JavaThread
2415   // destructor has completed.
2416 
2417   if (thread->SR_lock() == NULL) {
2418     return;
2419   }
2420 
2421   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
2422 
2423   OSThread* osthread = thread->osthread();
2424 
2425   os::SuspendResume::State current = osthread->sr.state();
2426   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
2427     suspend_save_context(osthread, siginfo, context);
2428 
2429     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
2430     os::SuspendResume::State state = osthread->sr.suspended();
2431     if (state == os::SuspendResume::SR_SUSPENDED) {
2432       sigset_t suspend_set;  // signals for sigsuspend()
2433 
2434       // get current set of blocked signals and unblock resume signal
2435       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
2436       sigdelset(&suspend_set, SR_signum);
2437 
2438       sr_semaphore.signal();
2439       // wait here until we are resumed
2440       while (1) {
2441         sigsuspend(&suspend_set);
2442 
2443         os::SuspendResume::State result = osthread->sr.running();
2444         if (result == os::SuspendResume::SR_RUNNING) {
2445           sr_semaphore.signal();
2446           break;
2447         } else if (result != os::SuspendResume::SR_SUSPENDED) {
2448           ShouldNotReachHere();
2449         }
2450       }
2451 
2452     } else if (state == os::SuspendResume::SR_RUNNING) {
2453       // request was cancelled, continue
2454     } else {
2455       ShouldNotReachHere();
2456     }
2457 
2458     resume_clear_context(osthread);
2459   } else if (current == os::SuspendResume::SR_RUNNING) {
2460     // request was cancelled, continue
2461   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
2462     // ignore
2463   } else {
2464     // ignore
2465   }
2466 
2467   errno = old_errno;
2468 }
2469 
2470 
2471 static int SR_initialize() {
2472   struct sigaction act;
2473   char *s;
2474   // Get signal number to use for suspend/resume
2475   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
2476     int sig = ::strtol(s, 0, 10);
2477     if (sig > MAX2(SIGSEGV, SIGBUS) &&  // See 4355769.
2478         sig < NSIG) {                   // Must be legal signal and fit into sigflags[].
2479       SR_signum = sig;
2480     } else {
2481       warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
2482               sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, SR_signum);
2483     }
2484   }
2485 
2486   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
2487          "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
2488 
2489   sigemptyset(&SR_sigset);
2490   sigaddset(&SR_sigset, SR_signum);
2491 
2492   // Set up signal handler for suspend/resume
2493   act.sa_flags = SA_RESTART|SA_SIGINFO;
2494   act.sa_handler = (void (*)(int)) SR_handler;
2495 
2496   // SR_signum is blocked by default.
2497   // 4528190 - We also need to block pthread restart signal (32 on all
2498   // supported Bsd platforms). Note that BsdThreads need to block
2499   // this signal for all threads to work properly. So we don't have
2500   // to use hard-coded signal number when setting up the mask.
2501   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
2502 
2503   if (sigaction(SR_signum, &act, 0) == -1) {
2504     return -1;
2505   }
2506 
2507   // Save signal flag
2508   os::Bsd::set_our_sigflags(SR_signum, act.sa_flags);
2509   return 0;
2510 }
2511 
2512 static int sr_notify(OSThread* osthread) {
2513   int status = pthread_kill(osthread->pthread_id(), SR_signum);
2514   assert_status(status == 0, status, "pthread_kill");
2515   return status;
2516 }
2517 
2518 // "Randomly" selected value for how long we want to spin
2519 // before bailing out on suspending a thread, also how often
2520 // we send a signal to a thread we want to resume
2521 static const int RANDOMLY_LARGE_INTEGER = 1000000;
2522 static const int RANDOMLY_LARGE_INTEGER2 = 100;
2523 
2524 // returns true on success and false on error - really an error is fatal
2525 // but this seems the normal response to library errors
2526 static bool do_suspend(OSThread* osthread) {
2527   assert(osthread->sr.is_running(), "thread should be running");
2528   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
2529 
2530   // mark as suspended and send signal
2531   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
2532     // failed to switch, state wasn't running?
2533     ShouldNotReachHere();
2534     return false;
2535   }
2536 
2537   if (sr_notify(osthread) != 0) {
2538     ShouldNotReachHere();
2539   }
2540 
2541   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
2542   while (true) {
2543     if (sr_semaphore.timedwait(2)) {
2544       break;
2545     } else {
2546       // timeout
2547       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
2548       if (cancelled == os::SuspendResume::SR_RUNNING) {
2549         return false;
2550       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
2551         // make sure that we consume the signal on the semaphore as well
2552         sr_semaphore.wait();
2553         break;
2554       } else {
2555         ShouldNotReachHere();
2556         return false;
2557       }
2558     }
2559   }
2560 
2561   guarantee(osthread->sr.is_suspended(), "Must be suspended");
2562   return true;
2563 }
2564 
2565 static void do_resume(OSThread* osthread) {
2566   assert(osthread->sr.is_suspended(), "thread should be suspended");
2567   assert(!sr_semaphore.trywait(), "invalid semaphore state");
2568 
2569   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
2570     // failed to switch to WAKEUP_REQUEST
2571     ShouldNotReachHere();
2572     return;
2573   }
2574 
2575   while (true) {
2576     if (sr_notify(osthread) == 0) {
2577       if (sr_semaphore.timedwait(2)) {
2578         if (osthread->sr.is_running()) {
2579           return;
2580         }
2581       }
2582     } else {
2583       ShouldNotReachHere();
2584     }
2585   }
2586 
2587   guarantee(osthread->sr.is_running(), "Must be running!");
2588 }
2589 
2590 ///////////////////////////////////////////////////////////////////////////////////
2591 // signal handling (except suspend/resume)
2592 
2593 // This routine may be used by user applications as a "hook" to catch signals.
2594 // The user-defined signal handler must pass unrecognized signals to this
2595 // routine, and if it returns true (non-zero), then the signal handler must
2596 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
2597 // routine will never retun false (zero), but instead will execute a VM panic
2598 // routine kill the process.
2599 //
2600 // If this routine returns false, it is OK to call it again.  This allows
2601 // the user-defined signal handler to perform checks either before or after
2602 // the VM performs its own checks.  Naturally, the user code would be making
2603 // a serious error if it tried to handle an exception (such as a null check
2604 // or breakpoint) that the VM was generating for its own correct operation.
2605 //
2606 // This routine may recognize any of the following kinds of signals:
2607 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
2608 // It should be consulted by handlers for any of those signals.
2609 //
2610 // The caller of this routine must pass in the three arguments supplied
2611 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
2612 // field of the structure passed to sigaction().  This routine assumes that
2613 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
2614 //
2615 // Note that the VM will print warnings if it detects conflicting signal
2616 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
2617 //
2618 extern "C" JNIEXPORT int JVM_handle_bsd_signal(int signo, siginfo_t* siginfo,
2619                                                void* ucontext,
2620                                                int abort_if_unrecognized);
2621 
2622 static void signalHandler(int sig, siginfo_t* info, void* uc) {
2623   assert(info != NULL && uc != NULL, "it must be old kernel");
2624   int orig_errno = errno;  // Preserve errno value over signal handler.
2625   JVM_handle_bsd_signal(sig, info, uc, true);
2626   errno = orig_errno;
2627 }
2628 
2629 
2630 // This boolean allows users to forward their own non-matching signals
2631 // to JVM_handle_bsd_signal, harmlessly.
2632 bool os::Bsd::signal_handlers_are_installed = false;
2633 
2634 // For signal-chaining
2635 bool os::Bsd::libjsig_is_loaded = false;
2636 typedef struct sigaction *(*get_signal_t)(int);
2637 get_signal_t os::Bsd::get_signal_action = NULL;
2638 
2639 struct sigaction* os::Bsd::get_chained_signal_action(int sig) {
2640   struct sigaction *actp = NULL;
2641 
2642   if (libjsig_is_loaded) {
2643     // Retrieve the old signal handler from libjsig
2644     actp = (*get_signal_action)(sig);
2645   }
2646   if (actp == NULL) {
2647     // Retrieve the preinstalled signal handler from jvm
2648     actp = os::Posix::get_preinstalled_handler(sig);
2649   }
2650 
2651   return actp;
2652 }
2653 
2654 static bool call_chained_handler(struct sigaction *actp, int sig,
2655                                  siginfo_t *siginfo, void *context) {
2656   // Call the old signal handler
2657   if (actp->sa_handler == SIG_DFL) {
2658     // It's more reasonable to let jvm treat it as an unexpected exception
2659     // instead of taking the default action.
2660     return false;
2661   } else if (actp->sa_handler != SIG_IGN) {
2662     if ((actp->sa_flags & SA_NODEFER) == 0) {
2663       // automaticlly block the signal
2664       sigaddset(&(actp->sa_mask), sig);
2665     }
2666 
2667     sa_handler_t hand;
2668     sa_sigaction_t sa;
2669     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
2670     // retrieve the chained handler
2671     if (siginfo_flag_set) {
2672       sa = actp->sa_sigaction;
2673     } else {
2674       hand = actp->sa_handler;
2675     }
2676 
2677     if ((actp->sa_flags & SA_RESETHAND) != 0) {
2678       actp->sa_handler = SIG_DFL;
2679     }
2680 
2681     // try to honor the signal mask
2682     sigset_t oset;
2683     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
2684 
2685     // call into the chained handler
2686     if (siginfo_flag_set) {
2687       (*sa)(sig, siginfo, context);
2688     } else {
2689       (*hand)(sig);
2690     }
2691 
2692     // restore the signal mask
2693     pthread_sigmask(SIG_SETMASK, &oset, 0);
2694   }
2695   // Tell jvm's signal handler the signal is taken care of.
2696   return true;
2697 }
2698 
2699 bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) {
2700   bool chained = false;
2701   // signal-chaining
2702   if (UseSignalChaining) {
2703     struct sigaction *actp = get_chained_signal_action(sig);
2704     if (actp != NULL) {
2705       chained = call_chained_handler(actp, sig, siginfo, context);
2706     }
2707   }
2708   return chained;
2709 }
2710 
2711 // for diagnostic
2712 int sigflags[NSIG];
2713 
2714 int os::Bsd::get_our_sigflags(int sig) {
2715   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2716   return sigflags[sig];
2717 }
2718 
2719 void os::Bsd::set_our_sigflags(int sig, int flags) {
2720   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2721   if (sig > 0 && sig < NSIG) {
2722     sigflags[sig] = flags;
2723   }
2724 }
2725 
2726 void os::Bsd::set_signal_handler(int sig, bool set_installed) {
2727   // Check for overwrite.
2728   struct sigaction oldAct;
2729   sigaction(sig, (struct sigaction*)NULL, &oldAct);
2730 
2731   void* oldhand = oldAct.sa_sigaction
2732                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
2733                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
2734   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
2735       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
2736       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
2737     if (AllowUserSignalHandlers || !set_installed) {
2738       // Do not overwrite; user takes responsibility to forward to us.
2739       return;
2740     } else if (UseSignalChaining) {
2741       // save the old handler in jvm
2742       os::Posix::save_preinstalled_handler(sig, oldAct);
2743       // libjsig also interposes the sigaction() call below and saves the
2744       // old sigaction on it own.
2745     } else {
2746       fatal("Encountered unexpected pre-existing sigaction handler "
2747             "%#lx for signal %d.", (long)oldhand, sig);
2748     }
2749   }
2750 
2751   struct sigaction sigAct;
2752   sigfillset(&(sigAct.sa_mask));
2753   sigAct.sa_handler = SIG_DFL;
2754   if (!set_installed) {
2755     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
2756   } else {
2757     sigAct.sa_sigaction = signalHandler;
2758     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
2759   }
2760 #ifdef __APPLE__
2761   // Needed for main thread as XNU (Mac OS X kernel) will only deliver SIGSEGV
2762   // (which starts as SIGBUS) on main thread with faulting address inside "stack+guard pages"
2763   // if the signal handler declares it will handle it on alternate stack.
2764   // Notice we only declare we will handle it on alt stack, but we are not
2765   // actually going to use real alt stack - this is just a workaround.
2766   // Please see ux_exception.c, method catch_mach_exception_raise for details
2767   // link http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/bsd/uxkern/ux_exception.c
2768   if (sig == SIGSEGV) {
2769     sigAct.sa_flags |= SA_ONSTACK;
2770   }
2771 #endif
2772 
2773   // Save flags, which are set by ours
2774   assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
2775   sigflags[sig] = sigAct.sa_flags;
2776 
2777   int ret = sigaction(sig, &sigAct, &oldAct);
2778   assert(ret == 0, "check");
2779 
2780   void* oldhand2  = oldAct.sa_sigaction
2781                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
2782                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
2783   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
2784 }
2785 
2786 // install signal handlers for signals that HotSpot needs to
2787 // handle in order to support Java-level exception handling.
2788 
2789 void os::Bsd::install_signal_handlers() {
2790   if (!signal_handlers_are_installed) {
2791     signal_handlers_are_installed = true;
2792 
2793     // signal-chaining
2794     typedef void (*signal_setting_t)();
2795     signal_setting_t begin_signal_setting = NULL;
2796     signal_setting_t end_signal_setting = NULL;
2797     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
2798                                           dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
2799     if (begin_signal_setting != NULL) {
2800       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
2801                                           dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
2802       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
2803                                          dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
2804       libjsig_is_loaded = true;
2805       assert(UseSignalChaining, "should enable signal-chaining");
2806     }
2807     if (libjsig_is_loaded) {
2808       // Tell libjsig jvm is setting signal handlers
2809       (*begin_signal_setting)();
2810     }
2811 
2812     set_signal_handler(SIGSEGV, true);
2813     set_signal_handler(SIGPIPE, true);
2814     set_signal_handler(SIGBUS, true);
2815     set_signal_handler(SIGILL, true);
2816     set_signal_handler(SIGFPE, true);
2817     set_signal_handler(SIGXFSZ, true);
2818 
2819 #if defined(__APPLE__)
2820     // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
2821     // signals caught and handled by the JVM. To work around this, we reset the mach task
2822     // signal handler that's placed on our process by CrashReporter. This disables
2823     // CrashReporter-based reporting.
2824     //
2825     // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
2826     // on caught fatal signals.
2827     //
2828     // Additionally, gdb installs both standard BSD signal handlers, and mach exception
2829     // handlers. By replacing the existing task exception handler, we disable gdb's mach
2830     // exception handling, while leaving the standard BSD signal handlers functional.
2831     kern_return_t kr;
2832     kr = task_set_exception_ports(mach_task_self(),
2833                                   EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
2834                                   MACH_PORT_NULL,
2835                                   EXCEPTION_STATE_IDENTITY,
2836                                   MACHINE_THREAD_STATE);
2837 
2838     assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
2839 #endif
2840 
2841     if (libjsig_is_loaded) {
2842       // Tell libjsig jvm finishes setting signal handlers
2843       (*end_signal_setting)();
2844     }
2845 
2846     // We don't activate signal checker if libjsig is in place, we trust ourselves
2847     // and if UserSignalHandler is installed all bets are off
2848     if (CheckJNICalls) {
2849       if (libjsig_is_loaded) {
2850         log_debug(jni, resolve)("Info: libjsig is activated, all active signal checking is disabled");
2851         check_signals = false;
2852       }
2853       if (AllowUserSignalHandlers) {
2854         log_debug(jni, resolve)("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
2855         check_signals = false;
2856       }
2857     }
2858   }
2859 }
2860 
2861 
2862 /////
2863 // glibc on Bsd platform uses non-documented flag
2864 // to indicate, that some special sort of signal
2865 // trampoline is used.
2866 // We will never set this flag, and we should
2867 // ignore this flag in our diagnostic
2868 #ifdef SIGNIFICANT_SIGNAL_MASK
2869   #undef SIGNIFICANT_SIGNAL_MASK
2870 #endif
2871 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
2872 
2873 static const char* get_signal_handler_name(address handler,
2874                                            char* buf, int buflen) {
2875   int offset;
2876   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
2877   if (found) {
2878     // skip directory names
2879     const char *p1, *p2;
2880     p1 = buf;
2881     size_t len = strlen(os::file_separator());
2882     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
2883     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
2884   } else {
2885     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
2886   }
2887   return buf;
2888 }
2889 
2890 static void print_signal_handler(outputStream* st, int sig,
2891                                  char* buf, size_t buflen) {
2892   struct sigaction sa;
2893 
2894   sigaction(sig, NULL, &sa);
2895 
2896   // See comment for SIGNIFICANT_SIGNAL_MASK define
2897   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
2898 
2899   st->print("%s: ", os::exception_name(sig, buf, buflen));
2900 
2901   address handler = (sa.sa_flags & SA_SIGINFO)
2902     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
2903     : CAST_FROM_FN_PTR(address, sa.sa_handler);
2904 
2905   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
2906     st->print("SIG_DFL");
2907   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
2908     st->print("SIG_IGN");
2909   } else {
2910     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
2911   }
2912 
2913   st->print(", sa_mask[0]=");
2914   os::Posix::print_signal_set_short(st, &sa.sa_mask);
2915 
2916   address rh = VMError::get_resetted_sighandler(sig);
2917   // May be, handler was resetted by VMError?
2918   if (rh != NULL) {
2919     handler = rh;
2920     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
2921   }
2922 
2923   st->print(", sa_flags=");
2924   os::Posix::print_sa_flags(st, sa.sa_flags);
2925 
2926   // Check: is it our handler?
2927   if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
2928       handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
2929     // It is our signal handler
2930     // check for flags, reset system-used one!
2931     if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) {
2932       st->print(
2933                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
2934                 os::Bsd::get_our_sigflags(sig));
2935     }
2936   }
2937   st->cr();
2938 }
2939 
2940 
2941 #define DO_SIGNAL_CHECK(sig)                      \
2942   do {                                            \
2943     if (!sigismember(&check_signal_done, sig)) {  \
2944       os::Bsd::check_signal_handler(sig);         \
2945     }                                             \
2946   } while (0)
2947 
2948 // This method is a periodic task to check for misbehaving JNI applications
2949 // under CheckJNI, we can add any periodic checks here
2950 
2951 void os::run_periodic_checks() {
2952 
2953   if (check_signals == false) return;
2954 
2955   // SEGV and BUS if overridden could potentially prevent
2956   // generation of hs*.log in the event of a crash, debugging
2957   // such a case can be very challenging, so we absolutely
2958   // check the following for a good measure:
2959   DO_SIGNAL_CHECK(SIGSEGV);
2960   DO_SIGNAL_CHECK(SIGILL);
2961   DO_SIGNAL_CHECK(SIGFPE);
2962   DO_SIGNAL_CHECK(SIGBUS);
2963   DO_SIGNAL_CHECK(SIGPIPE);
2964   DO_SIGNAL_CHECK(SIGXFSZ);
2965 
2966 
2967   // ReduceSignalUsage allows the user to override these handlers
2968   // see comments at the very top and jvm_md.h
2969   if (!ReduceSignalUsage) {
2970     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
2971     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
2972     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
2973     DO_SIGNAL_CHECK(BREAK_SIGNAL);
2974   }
2975 
2976   DO_SIGNAL_CHECK(SR_signum);
2977 }
2978 
2979 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
2980 
2981 static os_sigaction_t os_sigaction = NULL;
2982 
2983 void os::Bsd::check_signal_handler(int sig) {
2984   char buf[O_BUFLEN];
2985   address jvmHandler = NULL;
2986 
2987 
2988   struct sigaction act;
2989   if (os_sigaction == NULL) {
2990     // only trust the default sigaction, in case it has been interposed
2991     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
2992     if (os_sigaction == NULL) return;
2993   }
2994 
2995   os_sigaction(sig, (struct sigaction*)NULL, &act);
2996 
2997 
2998   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
2999 
3000   address thisHandler = (act.sa_flags & SA_SIGINFO)
3001     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3002     : CAST_FROM_FN_PTR(address, act.sa_handler);
3003 
3004 
3005   switch (sig) {
3006   case SIGSEGV:
3007   case SIGBUS:
3008   case SIGFPE:
3009   case SIGPIPE:
3010   case SIGILL:
3011   case SIGXFSZ:
3012     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
3013     break;
3014 
3015   case SHUTDOWN1_SIGNAL:
3016   case SHUTDOWN2_SIGNAL:
3017   case SHUTDOWN3_SIGNAL:
3018   case BREAK_SIGNAL:
3019     jvmHandler = (address)user_handler();
3020     break;
3021 
3022   default:
3023     if (sig == SR_signum) {
3024       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
3025     } else {
3026       return;
3027     }
3028     break;
3029   }
3030 
3031   if (thisHandler != jvmHandler) {
3032     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3033     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3034     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3035     // No need to check this sig any longer
3036     sigaddset(&check_signal_done, sig);
3037     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
3038     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
3039       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
3040                     exception_name(sig, buf, O_BUFLEN));
3041     }
3042   } else if(os::Bsd::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Bsd::get_our_sigflags(sig)) {
3043     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3044     tty->print("expected:");
3045     os::Posix::print_sa_flags(tty, os::Bsd::get_our_sigflags(sig));
3046     tty->cr();
3047     tty->print("  found:");
3048     os::Posix::print_sa_flags(tty, act.sa_flags);
3049     tty->cr();
3050     // No need to check this sig any longer
3051     sigaddset(&check_signal_done, sig);
3052   }
3053 
3054   // Dump all the signal
3055   if (sigismember(&check_signal_done, sig)) {
3056     print_signal_handlers(tty, buf, O_BUFLEN);
3057   }
3058 }
3059 
3060 extern void report_error(char* file_name, int line_no, char* title,
3061                          char* format, ...);
3062 
3063 // this is called _before_ the most of global arguments have been parsed
3064 void os::init(void) {
3065   char dummy;   // used to get a guess on initial stack address
3066 
3067   clock_tics_per_sec = CLK_TCK;
3068 
3069   init_random(1234567);
3070 
3071   Bsd::set_page_size(getpagesize());
3072   if (Bsd::page_size() == -1) {
3073     fatal("os_bsd.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
3074   }
3075   init_page_sizes((size_t) Bsd::page_size());
3076 
3077   Bsd::initialize_system_info();
3078 
3079   // _main_thread points to the thread that created/loaded the JVM.
3080   Bsd::_main_thread = pthread_self();
3081 
3082   Bsd::clock_init();
3083   initial_time_count = javaTimeNanos();
3084 
3085   os::Posix::init();
3086 }
3087 
3088 // To install functions for atexit system call
3089 extern "C" {
3090   static void perfMemory_exit_helper() {
3091     perfMemory_exit();
3092   }
3093 }
3094 
3095 // this is called _after_ the global arguments have been parsed
3096 jint os::init_2(void) {
3097 
3098   // This could be set after os::Posix::init() but all platforms
3099   // have to set it the same so we have to mirror Solaris.
3100   DEBUG_ONLY(os::set_mutex_init_done();)
3101 
3102   os::Posix::init_2();
3103 
3104   // initialize suspend/resume support - must do this before signal_sets_init()
3105   if (SR_initialize() != 0) {
3106     perror("SR_initialize failed");
3107     return JNI_ERR;
3108   }
3109 
3110   Bsd::signal_sets_init();
3111   Bsd::install_signal_handlers();
3112   // Initialize data for jdk.internal.misc.Signal
3113   if (!ReduceSignalUsage) {
3114     jdk_misc_signal_init();
3115   }
3116 
3117   // Check and sets minimum stack sizes against command line options
3118   if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
3119     return JNI_ERR;
3120   }
3121 
3122   // Not supported.
3123   FLAG_SET_ERGO(UseNUMA, false);
3124   FLAG_SET_ERGO(UseNUMAInterleaving, false);
3125 
3126   if (MaxFDLimit) {
3127     // set the number of file descriptors to max. print out error
3128     // if getrlimit/setrlimit fails but continue regardless.
3129     struct rlimit nbr_files;
3130     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
3131     if (status != 0) {
3132       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
3133     } else {
3134       nbr_files.rlim_cur = nbr_files.rlim_max;
3135 
3136 #ifdef __APPLE__
3137       // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
3138       // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
3139       // be used instead
3140       nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
3141 #endif
3142 
3143       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
3144       if (status != 0) {
3145         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
3146       }
3147     }
3148   }
3149 
3150   // at-exit methods are called in the reverse order of their registration.
3151   // atexit functions are called on return from main or as a result of a
3152   // call to exit(3C). There can be only 32 of these functions registered
3153   // and atexit() does not set errno.
3154 
3155   if (PerfAllowAtExitRegistration) {
3156     // only register atexit functions if PerfAllowAtExitRegistration is set.
3157     // atexit functions can be delayed until process exit time, which
3158     // can be problematic for embedded VM situations. Embedded VMs should
3159     // call DestroyJavaVM() to assure that VM resources are released.
3160 
3161     // note: perfMemory_exit_helper atexit function may be removed in
3162     // the future if the appropriate cleanup code can be added to the
3163     // VM_Exit VMOperation's doit method.
3164     if (atexit(perfMemory_exit_helper) != 0) {
3165       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
3166     }
3167   }
3168 
3169   // initialize thread priority policy
3170   prio_init();
3171 
3172 #ifdef __APPLE__
3173   // dynamically link to objective c gc registration
3174   void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
3175   if (handleLibObjc != NULL) {
3176     objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
3177   }
3178 #endif
3179 
3180   return JNI_OK;
3181 }
3182 
3183 int os::active_processor_count() {
3184   // User has overridden the number of active processors
3185   if (ActiveProcessorCount > 0) {
3186     log_trace(os)("active_processor_count: "
3187                   "active processor count set by user : %d",
3188                   ActiveProcessorCount);
3189     return ActiveProcessorCount;
3190   }
3191 
3192   return _processor_count;
3193 }
3194 
3195 #ifdef __APPLE__
3196 uint os::processor_id() {
3197   // Get the initial APIC id and return the associated processor id. The initial APIC
3198   // id is limited to 8-bits, which means we can have at most 256 unique APIC ids. If
3199   // the system has more processors (or the initial APIC ids are discontiguous) the
3200   // APIC id will be truncated and more than one processor will potentially share the
3201   // same processor id. This is not optimal, but unlikely to happen in practice. Should
3202   // this become a real problem we could switch to using x2APIC ids, which are 32-bit
3203   // wide. However, note that x2APIC is Intel-specific, and the wider number space
3204   // would require a more complicated mapping approach.
3205   uint eax = 0x1;
3206   uint ebx;
3207   uint ecx = 0;
3208   uint edx;
3209 
3210   __asm__ ("cpuid\n\t" : "+a" (eax), "+b" (ebx), "+c" (ecx), "+d" (edx) : );
3211 
3212   uint apic_id = (ebx >> 24) & (processor_id_map_size - 1);
3213   int processor_id = Atomic::load(&processor_id_map[apic_id]);
3214 
3215   while (processor_id < 0) {
3216     // Assign processor id to APIC id
3217     processor_id = Atomic::cmpxchg(&processor_id_map[apic_id], processor_id_unassigned, processor_id_assigning);
3218     if (processor_id == processor_id_unassigned) {
3219       processor_id = Atomic::fetch_and_add(&processor_id_next, 1) % os::processor_count();
3220       Atomic::store(&processor_id_map[apic_id], processor_id);
3221     }
3222   }
3223 
3224   assert(processor_id >= 0 && processor_id < os::processor_count(), "invalid processor id");
3225 
3226   return (uint)processor_id;
3227 }
3228 #endif
3229 
3230 void os::set_native_thread_name(const char *name) {
3231 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
3232   // This is only supported in Snow Leopard and beyond
3233   if (name != NULL) {
3234     // Add a "Java: " prefix to the name
3235     char buf[MAXTHREADNAMESIZE];
3236     snprintf(buf, sizeof(buf), "Java: %s", name);
3237     pthread_setname_np(buf);
3238   }
3239 #endif
3240 }
3241 
3242 bool os::bind_to_processor(uint processor_id) {
3243   // Not yet implemented.
3244   return false;
3245 }
3246 
3247 void os::SuspendedThreadTask::internal_do_task() {
3248   if (do_suspend(_thread->osthread())) {
3249     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3250     do_task(context);
3251     do_resume(_thread->osthread());
3252   }
3253 }
3254 
3255 ////////////////////////////////////////////////////////////////////////////////
3256 // debug support
3257 
3258 bool os::find(address addr, outputStream* st) {
3259   Dl_info dlinfo;
3260   memset(&dlinfo, 0, sizeof(dlinfo));
3261   if (dladdr(addr, &dlinfo) != 0) {
3262     st->print(INTPTR_FORMAT ": ", (intptr_t)addr);
3263     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
3264       st->print("%s+%#x", dlinfo.dli_sname,
3265                 (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_saddr));
3266     } else if (dlinfo.dli_fbase != NULL) {
3267       st->print("<offset %#x>", (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_fbase));
3268     } else {
3269       st->print("<absolute address>");
3270     }
3271     if (dlinfo.dli_fname != NULL) {
3272       st->print(" in %s", dlinfo.dli_fname);
3273     }
3274     if (dlinfo.dli_fbase != NULL) {
3275       st->print(" at " INTPTR_FORMAT, (intptr_t)dlinfo.dli_fbase);
3276     }
3277     st->cr();
3278 
3279     if (Verbose) {
3280       // decode some bytes around the PC
3281       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
3282       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
3283       address       lowest = (address) dlinfo.dli_sname;
3284       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
3285       if (begin < lowest)  begin = lowest;
3286       Dl_info dlinfo2;
3287       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
3288           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
3289         end = (address) dlinfo2.dli_saddr;
3290       }
3291       Disassembler::decode(begin, end, st);
3292     }
3293     return true;
3294   }
3295   return false;
3296 }
3297 
3298 ////////////////////////////////////////////////////////////////////////////////
3299 // misc
3300 
3301 // This does not do anything on Bsd. This is basically a hook for being
3302 // able to use structured exception handling (thread-local exception filters)
3303 // on, e.g., Win32.
3304 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3305                               const methodHandle& method, JavaCallArguments* args,
3306                               Thread* thread) {
3307   f(value, method, args, thread);
3308 }
3309 
3310 void os::print_statistics() {
3311 }
3312 
3313 bool os::message_box(const char* title, const char* message) {
3314   int i;
3315   fdStream err(defaultStream::error_fd());
3316   for (i = 0; i < 78; i++) err.print_raw("=");
3317   err.cr();
3318   err.print_raw_cr(title);
3319   for (i = 0; i < 78; i++) err.print_raw("-");
3320   err.cr();
3321   err.print_raw_cr(message);
3322   for (i = 0; i < 78; i++) err.print_raw("=");
3323   err.cr();
3324 
3325   char buf[16];
3326   // Prevent process from exiting upon "read error" without consuming all CPU
3327   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3328 
3329   return buf[0] == 'y' || buf[0] == 'Y';
3330 }
3331 
3332 static inline struct timespec get_mtime(const char* filename) {
3333   struct stat st;
3334   int ret = os::stat(filename, &st);
3335   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
3336 #ifdef __APPLE__
3337   return st.st_mtimespec;
3338 #else
3339   return st.st_mtim;
3340 #endif
3341 }
3342 
3343 int os::compare_file_modified_times(const char* file1, const char* file2) {
3344   struct timespec filetime1 = get_mtime(file1);
3345   struct timespec filetime2 = get_mtime(file2);
3346   int diff = filetime1.tv_sec - filetime2.tv_sec;
3347   if (diff == 0) {
3348     return filetime1.tv_nsec - filetime2.tv_nsec;
3349   }
3350   return diff;
3351 }
3352 
3353 // Is a (classpath) directory empty?
3354 bool os::dir_is_empty(const char* path) {
3355   DIR *dir = NULL;
3356   struct dirent *ptr;
3357 
3358   dir = opendir(path);
3359   if (dir == NULL) return true;
3360 
3361   // Scan the directory
3362   bool result = true;
3363   while (result && (ptr = readdir(dir)) != NULL) {
3364     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
3365       result = false;
3366     }
3367   }
3368   closedir(dir);
3369   return result;
3370 }
3371 
3372 // This code originates from JDK's sysOpen and open64_w
3373 // from src/solaris/hpi/src/system_md.c
3374 
3375 int os::open(const char *path, int oflag, int mode) {
3376   if (strlen(path) > MAX_PATH - 1) {
3377     errno = ENAMETOOLONG;
3378     return -1;
3379   }
3380   int fd;
3381 
3382   fd = ::open(path, oflag, mode);
3383   if (fd == -1) return -1;
3384 
3385   // If the open succeeded, the file might still be a directory
3386   {
3387     struct stat buf;
3388     int ret = ::fstat(fd, &buf);
3389     int st_mode = buf.st_mode;
3390 
3391     if (ret != -1) {
3392       if ((st_mode & S_IFMT) == S_IFDIR) {
3393         errno = EISDIR;
3394         ::close(fd);
3395         return -1;
3396       }
3397     } else {
3398       ::close(fd);
3399       return -1;
3400     }
3401   }
3402 
3403   // All file descriptors that are opened in the JVM and not
3404   // specifically destined for a subprocess should have the
3405   // close-on-exec flag set.  If we don't set it, then careless 3rd
3406   // party native code might fork and exec without closing all
3407   // appropriate file descriptors (e.g. as we do in closeDescriptors in
3408   // UNIXProcess.c), and this in turn might:
3409   //
3410   // - cause end-of-file to fail to be detected on some file
3411   //   descriptors, resulting in mysterious hangs, or
3412   //
3413   // - might cause an fopen in the subprocess to fail on a system
3414   //   suffering from bug 1085341.
3415   //
3416   // (Yes, the default setting of the close-on-exec flag is a Unix
3417   // design flaw)
3418   //
3419   // See:
3420   // 1085341: 32-bit stdio routines should support file descriptors >255
3421   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
3422   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
3423   //
3424 #ifdef FD_CLOEXEC
3425   {
3426     int flags = ::fcntl(fd, F_GETFD);
3427     if (flags != -1) {
3428       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3429     }
3430   }
3431 #endif
3432 
3433   return fd;
3434 }
3435 
3436 
3437 // create binary file, rewriting existing file if required
3438 int os::create_binary_file(const char* path, bool rewrite_existing) {
3439   int oflags = O_WRONLY | O_CREAT;
3440   if (!rewrite_existing) {
3441     oflags |= O_EXCL;
3442   }
3443   return ::open(path, oflags, S_IREAD | S_IWRITE);
3444 }
3445 
3446 // return current position of file pointer
3447 jlong os::current_file_offset(int fd) {
3448   return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
3449 }
3450 
3451 // move file pointer to the specified offset
3452 jlong os::seek_to_file_offset(int fd, jlong offset) {
3453   return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
3454 }
3455 
3456 // This code originates from JDK's sysAvailable
3457 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
3458 
3459 int os::available(int fd, jlong *bytes) {
3460   jlong cur, end;
3461   int mode;
3462   struct stat buf;
3463 
3464   if (::fstat(fd, &buf) >= 0) {
3465     mode = buf.st_mode;
3466     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
3467       int n;
3468       if (::ioctl(fd, FIONREAD, &n) >= 0) {
3469         *bytes = n;
3470         return 1;
3471       }
3472     }
3473   }
3474   if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
3475     return 0;
3476   } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
3477     return 0;
3478   } else if (::lseek(fd, cur, SEEK_SET) == -1) {
3479     return 0;
3480   }
3481   *bytes = end - cur;
3482   return 1;
3483 }
3484 
3485 // Map a block of memory.
3486 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
3487                         char *addr, size_t bytes, bool read_only,
3488                         bool allow_exec) {
3489   int prot;
3490   int flags;
3491 
3492   if (read_only) {
3493     prot = PROT_READ;
3494     flags = MAP_SHARED;
3495   } else {
3496     prot = PROT_READ | PROT_WRITE;
3497     flags = MAP_PRIVATE;
3498   }
3499 
3500   if (allow_exec) {
3501     prot |= PROT_EXEC;
3502   }
3503 
3504   if (addr != NULL) {
3505     flags |= MAP_FIXED;
3506   }
3507 
3508   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
3509                                      fd, file_offset);
3510   if (mapped_address == MAP_FAILED) {
3511     return NULL;
3512   }
3513   return mapped_address;
3514 }
3515 
3516 
3517 // Remap a block of memory.
3518 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
3519                           char *addr, size_t bytes, bool read_only,
3520                           bool allow_exec) {
3521   // same as map_memory() on this OS
3522   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
3523                         allow_exec);
3524 }
3525 
3526 
3527 // Unmap a block of memory.
3528 bool os::pd_unmap_memory(char* addr, size_t bytes) {
3529   return munmap(addr, bytes) == 0;
3530 }
3531 
3532 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
3533 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
3534 // of a thread.
3535 //
3536 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
3537 // the fast estimate available on the platform.
3538 
3539 jlong os::current_thread_cpu_time() {
3540 #ifdef __APPLE__
3541   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
3542 #else
3543   Unimplemented();
3544   return 0;
3545 #endif
3546 }
3547 
3548 jlong os::thread_cpu_time(Thread* thread) {
3549 #ifdef __APPLE__
3550   return os::thread_cpu_time(thread, true /* user + sys */);
3551 #else
3552   Unimplemented();
3553   return 0;
3554 #endif
3555 }
3556 
3557 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
3558 #ifdef __APPLE__
3559   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
3560 #else
3561   Unimplemented();
3562   return 0;
3563 #endif
3564 }
3565 
3566 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
3567 #ifdef __APPLE__
3568   struct thread_basic_info tinfo;
3569   mach_msg_type_number_t tcount = THREAD_INFO_MAX;
3570   kern_return_t kr;
3571   thread_t mach_thread;
3572 
3573   mach_thread = thread->osthread()->thread_id();
3574   kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
3575   if (kr != KERN_SUCCESS) {
3576     return -1;
3577   }
3578 
3579   if (user_sys_cpu_time) {
3580     jlong nanos;
3581     nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
3582     nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
3583     return nanos;
3584   } else {
3585     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
3586   }
3587 #else
3588   Unimplemented();
3589   return 0;
3590 #endif
3591 }
3592 
3593 
3594 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3595   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
3596   info_ptr->may_skip_backward = false;     // elapsed time not wall time
3597   info_ptr->may_skip_forward = false;      // elapsed time not wall time
3598   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
3599 }
3600 
3601 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
3602   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
3603   info_ptr->may_skip_backward = false;     // elapsed time not wall time
3604   info_ptr->may_skip_forward = false;      // elapsed time not wall time
3605   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
3606 }
3607 
3608 bool os::is_thread_cpu_time_supported() {
3609 #ifdef __APPLE__
3610   return true;
3611 #else
3612   return false;
3613 #endif
3614 }
3615 
3616 // System loadavg support.  Returns -1 if load average cannot be obtained.
3617 // Bsd doesn't yet have a (official) notion of processor sets,
3618 // so just return the system wide load average.
3619 int os::loadavg(double loadavg[], int nelem) {
3620   return ::getloadavg(loadavg, nelem);
3621 }
3622 
3623 void os::pause() {
3624   char filename[MAX_PATH];
3625   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
3626     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
3627   } else {
3628     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
3629   }
3630 
3631   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
3632   if (fd != -1) {
3633     struct stat buf;
3634     ::close(fd);
3635     while (::stat(filename, &buf) == 0) {
3636       (void)::poll(NULL, 0, 100);
3637     }
3638   } else {
3639     jio_fprintf(stderr,
3640                 "Could not open pause file '%s', continuing immediately.\n", filename);
3641   }
3642 }
3643 
3644 // Darwin has no "environ" in a dynamic library.
3645 #ifdef __APPLE__
3646   #include <crt_externs.h>
3647   #define environ (*_NSGetEnviron())
3648 #else
3649 extern char** environ;
3650 #endif
3651 
3652 // Run the specified command in a separate process. Return its exit value,
3653 // or -1 on failure (e.g. can't fork a new process).
3654 // Unlike system(), this function can be called from signal handler. It
3655 // doesn't block SIGINT et al.
3656 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {
3657   const char * argv[4] = {"sh", "-c", cmd, NULL};
3658 
3659   // fork() in BsdThreads/NPTL is not async-safe. It needs to run
3660   // pthread_atfork handlers and reset pthread library. All we need is a
3661   // separate process to execve. Make a direct syscall to fork process.
3662   // On IA64 there's no fork syscall, we have to use fork() and hope for
3663   // the best...
3664   pid_t pid = fork();
3665 
3666   if (pid < 0) {
3667     // fork failed
3668     return -1;
3669 
3670   } else if (pid == 0) {
3671     // child process
3672 
3673     // execve() in BsdThreads will call pthread_kill_other_threads_np()
3674     // first to kill every thread on the thread list. Because this list is
3675     // not reset by fork() (see notes above), execve() will instead kill
3676     // every thread in the parent process. We know this is the only thread
3677     // in the new process, so make a system call directly.
3678     // IA64 should use normal execve() from glibc to match the glibc fork()
3679     // above.
3680     execve("/bin/sh", (char* const*)argv, environ);
3681 
3682     // execve failed
3683     _exit(-1);
3684 
3685   } else  {
3686     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
3687     // care about the actual exit code, for now.
3688 
3689     int status;
3690 
3691     // Wait for the child process to exit.  This returns immediately if
3692     // the child has already exited. */
3693     while (waitpid(pid, &status, 0) < 0) {
3694       switch (errno) {
3695       case ECHILD: return 0;
3696       case EINTR: break;
3697       default: return -1;
3698       }
3699     }
3700 
3701     if (WIFEXITED(status)) {
3702       // The child exited normally; get its exit code.
3703       return WEXITSTATUS(status);
3704     } else if (WIFSIGNALED(status)) {
3705       // The child exited because of a signal
3706       // The best value to return is 0x80 + signal number,
3707       // because that is what all Unix shells do, and because
3708       // it allows callers to distinguish between process exit and
3709       // process death by signal.
3710       return 0x80 + WTERMSIG(status);
3711     } else {
3712       // Unknown exit code; pass it through
3713       return status;
3714     }
3715   }
3716 }
3717 
3718 // Get the kern.corefile setting, or otherwise the default path to the core file
3719 // Returns the length of the string
3720 int os::get_core_path(char* buffer, size_t bufferSize) {
3721   int n = 0;
3722 #ifdef __APPLE__
3723   char coreinfo[MAX_PATH];
3724   size_t sz = sizeof(coreinfo);
3725   int ret = sysctlbyname("kern.corefile", coreinfo, &sz, NULL, 0);
3726   if (ret == 0) {
3727     char *pid_pos = strstr(coreinfo, "%P");
3728     // skip over the "%P" to preserve any optional custom user pattern
3729     const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : "";
3730 
3731     if (pid_pos != NULL) {
3732       *pid_pos = '\0';
3733       n = jio_snprintf(buffer, bufferSize, "%s%d%s", coreinfo, os::current_process_id(), tail);
3734     } else {
3735       n = jio_snprintf(buffer, bufferSize, "%s", coreinfo);
3736     }
3737   } else
3738 #endif
3739   {
3740     n = jio_snprintf(buffer, bufferSize, "/cores/core.%d", os::current_process_id());
3741   }
3742   // Truncate if theoretical string was longer than bufferSize
3743   n = MIN2(n, (int)bufferSize);
3744 
3745   return n;
3746 }
3747 
3748 bool os::supports_map_sync() {
3749   return false;
3750 }
3751 
3752 #ifndef PRODUCT
3753 void TestReserveMemorySpecial_test() {
3754   // No tests available for this platform
3755 }
3756 #endif
3757 
3758 bool os::start_debugging(char *buf, int buflen) {
3759   int len = (int)strlen(buf);
3760   char *p = &buf[len];
3761 
3762   jio_snprintf(p, buflen-len,
3763              "\n\n"
3764              "Do you want to debug the problem?\n\n"
3765              "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " INTX_FORMAT " (" INTPTR_FORMAT ")\n"
3766              "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
3767              "Otherwise, press RETURN to abort...",
3768              os::current_process_id(), os::current_process_id(),
3769              os::current_thread_id(), os::current_thread_id());
3770 
3771   bool yes = os::message_box("Unexpected Error", buf);
3772 
3773   if (yes) {
3774     // yes, user asked VM to launch debugger
3775     jio_snprintf(buf, sizeof(buf), "gdb /proc/%d/exe %d",
3776                      os::current_process_id(), os::current_process_id());
3777 
3778     os::fork_and_exec(buf);
3779     yes = false;
3780   }
3781   return yes;
3782 }