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