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