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