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