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