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