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