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