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