rev 6280 : [mq]: osx-clock

   1 /*
   2  * Copyright (c) 1999, 2014, 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_share_bsd.hpp"
  40 #include "prims/jniFastGetField.hpp"
  41 #include "prims/jvm.h"
  42 #include "prims/jvm_misc.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/extendedPC.hpp"
  45 #include "runtime/globals.hpp"
  46 #include "runtime/interfaceSupport.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/javaCalls.hpp"
  49 #include "runtime/mutexLocker.hpp"
  50 #include "runtime/objectMonitor.hpp"
  51 #include "runtime/osThread.hpp"
  52 #include "runtime/perfMemory.hpp"
  53 #include "runtime/sharedRuntime.hpp"
  54 #include "runtime/statSampler.hpp"
  55 #include "runtime/stubRoutines.hpp"
  56 #include "runtime/thread.inline.hpp"
  57 #include "runtime/threadCritical.hpp"
  58 #include "runtime/timer.hpp"
  59 #include "services/attachListener.hpp"
  60 #include "services/memTracker.hpp"
  61 #include "services/runtimeService.hpp"
  62 #include "utilities/decoder.hpp"
  63 #include "utilities/defaultStream.hpp"
  64 #include "utilities/events.hpp"
  65 #include "utilities/growableArray.hpp"
  66 #include "utilities/vmError.hpp"
  67 
  68 // put OS-includes here
  69 # include <sys/types.h>
  70 # include <sys/mman.h>
  71 # include <sys/stat.h>
  72 # include <sys/select.h>
  73 # include <pthread.h>
  74 # include <signal.h>
  75 # include <errno.h>
  76 # include <dlfcn.h>
  77 # include <stdio.h>
  78 # include <unistd.h>
  79 # include <sys/resource.h>
  80 # include <pthread.h>
  81 # include <sys/stat.h>
  82 # include <sys/time.h>
  83 # include <sys/times.h>
  84 # include <sys/utsname.h>
  85 # include <sys/socket.h>
  86 # include <sys/wait.h>
  87 # include <time.h>
  88 # include <pwd.h>
  89 # include <poll.h>
  90 # include <semaphore.h>
  91 # include <fcntl.h>
  92 # include <string.h>
  93 # include <sys/param.h>
  94 # include <sys/sysctl.h>
  95 # include <sys/ipc.h>
  96 # include <sys/shm.h>
  97 #ifndef __APPLE__
  98 # include <link.h>
  99 #endif
 100 # include <stdint.h>
 101 # include <inttypes.h>
 102 # include <sys/ioctl.h>
 103 # include <sys/syscall.h>
 104 
 105 #if defined(__FreeBSD__) || defined(__NetBSD__)
 106 # include <elf.h>
 107 #endif
 108 
 109 #ifdef __APPLE__
 110 # include <mach/mach.h> // semaphore_* API
 111 # include <mach-o/dyld.h>
 112 # include <sys/proc_info.h>
 113 # include <objc/objc-auto.h>
 114 #endif
 115 
 116 #ifndef MAP_ANONYMOUS
 117 #define MAP_ANONYMOUS MAP_ANON
 118 #endif
 119 
 120 #define MAX_PATH    (2 * K)
 121 
 122 // for timer info max values which include all bits
 123 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 124 
 125 #define LARGEPAGES_BIT (1 << 6)
 126 ////////////////////////////////////////////////////////////////////////////////
 127 // global variables
 128 julong os::Bsd::_physical_memory = 0;
 129 
 130 



 131 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;

 132 pthread_t os::Bsd::_main_thread;
 133 int os::Bsd::_page_size = -1;
 134 
 135 static jlong initial_time_count=0;
 136 
 137 static int clock_tics_per_sec = 100;
 138 
 139 // For diagnostics to print a message once. see run_periodic_checks
 140 static sigset_t check_signal_done;
 141 static bool check_signals = true;
 142 
 143 static pid_t _initial_pid = 0;
 144 
 145 /* Signal number used to suspend/resume a thread */
 146 
 147 /* do not use any signal number less than SIGSEGV, see 4355769 */
 148 static int SR_signum = SIGUSR2;
 149 sigset_t SR_sigset;
 150 
 151 
 152 ////////////////////////////////////////////////////////////////////////////////
 153 // utility functions
 154 
 155 static int SR_initialize();
 156 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 157 
 158 julong os::available_memory() {
 159   return Bsd::available_memory();
 160 }
 161 
 162 // available here means free
 163 julong os::Bsd::available_memory() {
 164   uint64_t available = physical_memory() >> 2;
 165 #ifdef __APPLE__
 166   mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
 167   vm_statistics64_data_t vmstat;
 168   kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
 169                                          (host_info64_t)&vmstat, &count);
 170   assert(kerr == KERN_SUCCESS,
 171          "host_statistics64 failed - check mach_host_self() and count");
 172   if (kerr == KERN_SUCCESS) {
 173     available = vmstat.free_count * os::vm_page_size();
 174   }
 175 #endif
 176   return available;
 177 }
 178 
 179 julong os::physical_memory() {
 180   return Bsd::physical_memory();
 181 }
 182 
 183 ////////////////////////////////////////////////////////////////////////////////
 184 // environment support
 185 
 186 bool os::getenv(const char* name, char* buf, int len) {
 187   const char* val = ::getenv(name);
 188   if (val != NULL && strlen(val) < (size_t)len) {
 189     strcpy(buf, val);
 190     return true;
 191   }
 192   if (len > 0) buf[0] = 0;  // return a null string
 193   return false;
 194 }
 195 
 196 
 197 // Return true if user is running as root.
 198 
 199 bool os::have_special_privileges() {
 200   static bool init = false;
 201   static bool privileges = false;
 202   if (!init) {
 203     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 204     init = true;
 205   }
 206   return privileges;
 207 }
 208 
 209 
 210 
 211 // Cpu architecture string
 212 #if   defined(ZERO)
 213 static char cpu_arch[] = ZERO_LIBARCH;
 214 #elif defined(IA64)
 215 static char cpu_arch[] = "ia64";
 216 #elif defined(IA32)
 217 static char cpu_arch[] = "i386";
 218 #elif defined(AMD64)
 219 static char cpu_arch[] = "amd64";
 220 #elif defined(ARM)
 221 static char cpu_arch[] = "arm";
 222 #elif defined(PPC32)
 223 static char cpu_arch[] = "ppc";
 224 #elif defined(SPARC)
 225 #  ifdef _LP64
 226 static char cpu_arch[] = "sparcv9";
 227 #  else
 228 static char cpu_arch[] = "sparc";
 229 #  endif
 230 #else
 231 #error Add appropriate cpu_arch setting
 232 #endif
 233 
 234 // Compiler variant
 235 #ifdef COMPILER2
 236 #define COMPILER_VARIANT "server"
 237 #else
 238 #define COMPILER_VARIANT "client"
 239 #endif
 240 
 241 
 242 void os::Bsd::initialize_system_info() {
 243   int mib[2];
 244   size_t len;
 245   int cpu_val;
 246   julong mem_val;
 247 
 248   /* get processors count via hw.ncpus sysctl */
 249   mib[0] = CTL_HW;
 250   mib[1] = HW_NCPU;
 251   len = sizeof(cpu_val);
 252   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
 253        assert(len == sizeof(cpu_val), "unexpected data size");
 254        set_processor_count(cpu_val);
 255   }
 256   else {
 257        set_processor_count(1);   // fallback
 258   }
 259 
 260   /* get physical memory via hw.memsize sysctl (hw.memsize is used
 261    * since it returns a 64 bit value)
 262    */
 263   mib[0] = CTL_HW;
 264 
 265 #if defined (HW_MEMSIZE) // Apple
 266   mib[1] = HW_MEMSIZE;
 267 #elif defined(HW_PHYSMEM) // Most of BSD
 268   mib[1] = HW_PHYSMEM;
 269 #elif defined(HW_REALMEM) // Old FreeBSD
 270   mib[1] = HW_REALMEM;
 271 #else
 272   #error No ways to get physmem
 273 #endif
 274 
 275   len = sizeof(mem_val);
 276   if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
 277        assert(len == sizeof(mem_val), "unexpected data size");
 278        _physical_memory = mem_val;
 279   } else {
 280        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
 281   }
 282 
 283 #ifdef __OpenBSD__
 284   {
 285        // limit _physical_memory memory view on OpenBSD since
 286        // datasize rlimit restricts us anyway.
 287        struct rlimit limits;
 288        getrlimit(RLIMIT_DATA, &limits);
 289        _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
 290   }
 291 #endif
 292 }
 293 
 294 #ifdef __APPLE__
 295 static const char *get_home() {
 296   const char *home_dir = ::getenv("HOME");
 297   if ((home_dir == NULL) || (*home_dir == '\0')) {
 298     struct passwd *passwd_info = getpwuid(geteuid());
 299     if (passwd_info != NULL) {
 300       home_dir = passwd_info->pw_dir;
 301     }
 302   }
 303 
 304   return home_dir;
 305 }
 306 #endif
 307 
 308 void os::init_system_properties_values() {
 309   // The next steps are taken in the product version:
 310   //
 311   // Obtain the JAVA_HOME value from the location of libjvm.so.
 312   // This library should be located at:
 313   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 314   //
 315   // If "/jre/lib/" appears at the right place in the path, then we
 316   // assume libjvm.so is installed in a JDK and we use this path.
 317   //
 318   // Otherwise exit with message: "Could not create the Java virtual machine."
 319   //
 320   // The following extra steps are taken in the debugging version:
 321   //
 322   // If "/jre/lib/" does NOT appear at the right place in the path
 323   // instead of exit check for $JAVA_HOME environment variable.
 324   //
 325   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 326   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 327   // it looks like libjvm.so is installed there
 328   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 329   //
 330   // Otherwise exit.
 331   //
 332   // Important note: if the location of libjvm.so changes this
 333   // code needs to be changed accordingly.
 334 
 335 // See ld(1):
 336 //      The linker uses the following search paths to locate required
 337 //      shared libraries:
 338 //        1: ...
 339 //        ...
 340 //        7: The default directories, normally /lib and /usr/lib.
 341 #ifndef DEFAULT_LIBPATH
 342 #define DEFAULT_LIBPATH "/lib:/usr/lib"
 343 #endif
 344 
 345 // Base path of extensions installed on the system.
 346 #define SYS_EXT_DIR     "/usr/java/packages"
 347 #define EXTENSIONS_DIR  "/lib/ext"
 348 #define ENDORSED_DIR    "/lib/endorsed"
 349 
 350 #ifndef __APPLE__
 351 
 352   // Buffer that fits several sprintfs.
 353   // Note that the space for the colon and the trailing null are provided
 354   // by the nulls included by the sizeof operator.
 355   const size_t bufsize =
 356     MAX3((size_t)MAXPATHLEN,  // For dll_dir & friends.
 357          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir
 358          (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
 359   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 360 
 361   // sysclasspath, java_home, dll_dir
 362   {
 363     char *pslash;
 364     os::jvm_path(buf, bufsize);
 365 
 366     // Found the full path to libjvm.so.
 367     // Now cut the path to <java_home>/jre if we can.
 368     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 369     pslash = strrchr(buf, '/');
 370     if (pslash != NULL) {
 371       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 372     }
 373     Arguments::set_dll_dir(buf);
 374 
 375     if (pslash != NULL) {
 376       pslash = strrchr(buf, '/');
 377       if (pslash != NULL) {
 378         *pslash = '\0';          // Get rid of /<arch>.
 379         pslash = strrchr(buf, '/');
 380         if (pslash != NULL) {
 381           *pslash = '\0';        // Get rid of /lib.
 382         }
 383       }
 384     }
 385     Arguments::set_java_home(buf);
 386     set_boot_path('/', ':');
 387   }
 388 
 389   // Where to look for native libraries.
 390   //
 391   // Note: Due to a legacy implementation, most of the library path
 392   // is set in the launcher. This was to accomodate linking restrictions
 393   // on legacy Bsd implementations (which are no longer supported).
 394   // Eventually, all the library path setting will be done here.
 395   //
 396   // However, to prevent the proliferation of improperly built native
 397   // libraries, the new path component /usr/java/packages is added here.
 398   // Eventually, all the library path setting will be done here.
 399   {
 400     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 401     // should always exist (until the legacy problem cited above is
 402     // addressed).
 403     const char *v = ::getenv("LD_LIBRARY_PATH");
 404     const char *v_colon = ":";
 405     if (v == NULL) { v = ""; v_colon = ""; }
 406     // That's +1 for the colon and +1 for the trailing '\0'.
 407     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
 408                                                      strlen(v) + 1 +
 409                                                      sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
 410                                                      mtInternal);
 411     sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
 412     Arguments::set_library_path(ld_library_path);
 413     FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);
 414   }
 415 
 416   // Extensions directories.
 417   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 418   Arguments::set_ext_dirs(buf);
 419 
 420   // Endorsed standards default directory.
 421   sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
 422   Arguments::set_endorsed_dirs(buf);
 423 
 424   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
 425 
 426 #else // __APPLE__
 427 
 428 #define SYS_EXTENSIONS_DIR   "/Library/Java/Extensions"
 429 #define SYS_EXTENSIONS_DIRS  SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
 430 
 431   const char *user_home_dir = get_home();
 432   // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
 433   size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
 434     sizeof(SYS_EXTENSIONS_DIRS);
 435 
 436   // Buffer that fits several sprintfs.
 437   // Note that the space for the colon and the trailing null are provided
 438   // by the nulls included by the sizeof operator.
 439   const size_t bufsize =
 440     MAX3((size_t)MAXPATHLEN,  // for dll_dir & friends.
 441          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size, // extensions dir
 442          (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
 443   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 444 
 445   // sysclasspath, java_home, dll_dir
 446   {
 447     char *pslash;
 448     os::jvm_path(buf, bufsize);
 449 
 450     // Found the full path to libjvm.so.
 451     // Now cut the path to <java_home>/jre if we can.
 452     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 453     pslash = strrchr(buf, '/');
 454     if (pslash != NULL) {
 455       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 456     }
 457     Arguments::set_dll_dir(buf);
 458 
 459     if (pslash != NULL) {
 460       pslash = strrchr(buf, '/');
 461       if (pslash != NULL) {
 462         *pslash = '\0';          // Get rid of /lib.
 463       }
 464     }
 465     Arguments::set_java_home(buf);
 466     set_boot_path('/', ':');
 467   }
 468 
 469   // Where to look for native libraries.
 470   //
 471   // Note: Due to a legacy implementation, most of the library path
 472   // is set in the launcher. This was to accomodate linking restrictions
 473   // on legacy Bsd implementations (which are no longer supported).
 474   // Eventually, all the library path setting will be done here.
 475   //
 476   // However, to prevent the proliferation of improperly built native
 477   // libraries, the new path component /usr/java/packages is added here.
 478   // Eventually, all the library path setting will be done here.
 479   {
 480     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 481     // should always exist (until the legacy problem cited above is
 482     // addressed).
 483     // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code
 484     // can specify a directory inside an app wrapper
 485     const char *l = ::getenv("JAVA_LIBRARY_PATH");
 486     const char *l_colon = ":";
 487     if (l == NULL) { l = ""; l_colon = ""; }
 488 
 489     const char *v = ::getenv("DYLD_LIBRARY_PATH");
 490     const char *v_colon = ":";
 491     if (v == NULL) { v = ""; v_colon = ""; }
 492 
 493     // Apple's Java6 has "." at the beginning of java.library.path.
 494     // OpenJDK on Windows has "." at the end of java.library.path.
 495     // OpenJDK on Linux and Solaris don't have "." in java.library.path
 496     // at all. To ease the transition from Apple's Java6 to OpenJDK7,
 497     // "." is appended to the end of java.library.path. Yes, this
 498     // could cause a change in behavior, but Apple's Java6 behavior
 499     // can be achieved by putting "." at the beginning of the
 500     // JAVA_LIBRARY_PATH environment variable.
 501     char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
 502                                                      strlen(v) + 1 + strlen(l) + 1 +
 503                                                      system_ext_size + 3,
 504                                                      mtInternal);
 505     sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",
 506             v, v_colon, l, l_colon, user_home_dir);
 507     Arguments::set_library_path(ld_library_path);
 508     FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);
 509   }
 510 
 511   // Extensions directories.
 512   //
 513   // Note that the space for the colon and the trailing null are provided
 514   // by the nulls included by the sizeof operator (so actually one byte more
 515   // than necessary is allocated).
 516   sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,
 517           user_home_dir, Arguments::get_java_home());
 518   Arguments::set_ext_dirs(buf);
 519 
 520   // Endorsed standards default directory.
 521   sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
 522   Arguments::set_endorsed_dirs(buf);
 523 
 524   FREE_C_HEAP_ARRAY(char, buf, mtInternal);
 525 
 526 #undef SYS_EXTENSIONS_DIR
 527 #undef SYS_EXTENSIONS_DIRS
 528 
 529 #endif // __APPLE__
 530 
 531 #undef SYS_EXT_DIR
 532 #undef EXTENSIONS_DIR
 533 #undef ENDORSED_DIR
 534 }
 535 
 536 ////////////////////////////////////////////////////////////////////////////////
 537 // breakpoint support
 538 
 539 void os::breakpoint() {
 540   BREAKPOINT;
 541 }
 542 
 543 extern "C" void breakpoint() {
 544   // use debugger to set breakpoint here
 545 }
 546 
 547 ////////////////////////////////////////////////////////////////////////////////
 548 // signal support
 549 
 550 debug_only(static bool signal_sets_initialized = false);
 551 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
 552 
 553 bool os::Bsd::is_sig_ignored(int sig) {
 554       struct sigaction oact;
 555       sigaction(sig, (struct sigaction*)NULL, &oact);
 556       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
 557                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
 558       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
 559            return true;
 560       else
 561            return false;
 562 }
 563 
 564 void os::Bsd::signal_sets_init() {
 565   // Should also have an assertion stating we are still single-threaded.
 566   assert(!signal_sets_initialized, "Already initialized");
 567   // Fill in signals that are necessarily unblocked for all threads in
 568   // the VM. Currently, we unblock the following signals:
 569   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
 570   //                         by -Xrs (=ReduceSignalUsage));
 571   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
 572   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
 573   // the dispositions or masks wrt these signals.
 574   // Programs embedding the VM that want to use the above signals for their
 575   // own purposes must, at this time, use the "-Xrs" option to prevent
 576   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
 577   // (See bug 4345157, and other related bugs).
 578   // In reality, though, unblocking these signals is really a nop, since
 579   // these signals are not blocked by default.
 580   sigemptyset(&unblocked_sigs);
 581   sigemptyset(&allowdebug_blocked_sigs);
 582   sigaddset(&unblocked_sigs, SIGILL);
 583   sigaddset(&unblocked_sigs, SIGSEGV);
 584   sigaddset(&unblocked_sigs, SIGBUS);
 585   sigaddset(&unblocked_sigs, SIGFPE);
 586   sigaddset(&unblocked_sigs, SR_signum);
 587 
 588   if (!ReduceSignalUsage) {
 589    if (!os::Bsd::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
 590       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
 591       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
 592    }
 593    if (!os::Bsd::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
 594       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
 595       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
 596    }
 597    if (!os::Bsd::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
 598       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
 599       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
 600    }
 601   }
 602   // Fill in signals that are blocked by all but the VM thread.
 603   sigemptyset(&vm_sigs);
 604   if (!ReduceSignalUsage)
 605     sigaddset(&vm_sigs, BREAK_SIGNAL);
 606   debug_only(signal_sets_initialized = true);
 607 
 608 }
 609 
 610 // These are signals that are unblocked while a thread is running Java.
 611 // (For some reason, they get blocked by default.)
 612 sigset_t* os::Bsd::unblocked_signals() {
 613   assert(signal_sets_initialized, "Not initialized");
 614   return &unblocked_sigs;
 615 }
 616 
 617 // These are the signals that are blocked while a (non-VM) thread is
 618 // running Java. Only the VM thread handles these signals.
 619 sigset_t* os::Bsd::vm_signals() {
 620   assert(signal_sets_initialized, "Not initialized");
 621   return &vm_sigs;
 622 }
 623 
 624 // These are signals that are blocked during cond_wait to allow debugger in
 625 sigset_t* os::Bsd::allowdebug_blocked_signals() {
 626   assert(signal_sets_initialized, "Not initialized");
 627   return &allowdebug_blocked_sigs;
 628 }
 629 
 630 void os::Bsd::hotspot_sigmask(Thread* thread) {
 631 
 632   //Save caller's signal mask before setting VM signal mask
 633   sigset_t caller_sigmask;
 634   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
 635 
 636   OSThread* osthread = thread->osthread();
 637   osthread->set_caller_sigmask(caller_sigmask);
 638 
 639   pthread_sigmask(SIG_UNBLOCK, os::Bsd::unblocked_signals(), NULL);
 640 
 641   if (!ReduceSignalUsage) {
 642     if (thread->is_VM_thread()) {
 643       // Only the VM thread handles BREAK_SIGNAL ...
 644       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 645     } else {
 646       // ... all other threads block BREAK_SIGNAL
 647       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 648     }
 649   }
 650 }
 651 
 652 
 653 //////////////////////////////////////////////////////////////////////////////
 654 // create new thread
 655 
 656 // check if it's safe to start a new thread
 657 static bool _thread_safety_check(Thread* thread) {
 658   return true;
 659 }
 660 
 661 #ifdef __APPLE__
 662 // library handle for calling objc_registerThreadWithCollector()
 663 // without static linking to the libobjc library
 664 #define OBJC_LIB "/usr/lib/libobjc.dylib"
 665 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
 666 typedef void (*objc_registerThreadWithCollector_t)();
 667 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
 668 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
 669 #endif
 670 
 671 #ifdef __APPLE__
 672 static uint64_t locate_unique_thread_id(mach_port_t mach_thread_port) {
 673   // Additional thread_id used to correlate threads in SA
 674   thread_identifier_info_data_t     m_ident_info;
 675   mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
 676 
 677   thread_info(mach_thread_port, THREAD_IDENTIFIER_INFO,
 678               (thread_info_t) &m_ident_info, &count);
 679 
 680   return m_ident_info.thread_id;
 681 }
 682 #endif
 683 
 684 // Thread start routine for all newly created threads
 685 static void *java_start(Thread *thread) {
 686   // Try to randomize the cache line index of hot stack frames.
 687   // This helps when threads of the same stack traces evict each other's
 688   // cache lines. The threads can be either from the same JVM instance, or
 689   // from different JVM instances. The benefit is especially true for
 690   // processors with hyperthreading technology.
 691   static int counter = 0;
 692   int pid = os::current_process_id();
 693   alloca(((pid ^ counter++) & 7) * 128);
 694 
 695   ThreadLocalStorage::set_thread(thread);
 696 
 697   OSThread* osthread = thread->osthread();
 698   Monitor* sync = osthread->startThread_lock();
 699 
 700   // non floating stack BsdThreads needs extra check, see above
 701   if (!_thread_safety_check(thread)) {
 702     // notify parent thread
 703     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
 704     osthread->set_state(ZOMBIE);
 705     sync->notify_all();
 706     return NULL;
 707   }
 708 
 709   osthread->set_thread_id(os::Bsd::gettid());
 710 
 711 #ifdef __APPLE__
 712   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
 713   guarantee(unique_thread_id != 0, "unique thread id was not found");
 714   osthread->set_unique_thread_id(unique_thread_id);
 715 #endif
 716   // initialize signal mask for this thread
 717   os::Bsd::hotspot_sigmask(thread);
 718 
 719   // initialize floating point control register
 720   os::Bsd::init_thread_fpu_state();
 721 
 722 #ifdef __APPLE__
 723   // register thread with objc gc
 724   if (objc_registerThreadWithCollectorFunction != NULL) {
 725     objc_registerThreadWithCollectorFunction();
 726   }
 727 #endif
 728 
 729   // handshaking with parent thread
 730   {
 731     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
 732 
 733     // notify parent thread
 734     osthread->set_state(INITIALIZED);
 735     sync->notify_all();
 736 
 737     // wait until os::start_thread()
 738     while (osthread->get_state() == INITIALIZED) {
 739       sync->wait(Mutex::_no_safepoint_check_flag);
 740     }
 741   }
 742 
 743   // call one more level start routine
 744   thread->run();
 745 
 746   return 0;
 747 }
 748 
 749 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
 750   assert(thread->osthread() == NULL, "caller responsible");
 751 
 752   // Allocate the OSThread object
 753   OSThread* osthread = new OSThread(NULL, NULL);
 754   if (osthread == NULL) {
 755     return false;
 756   }
 757 
 758   // set the correct thread state
 759   osthread->set_thread_type(thr_type);
 760 
 761   // Initial state is ALLOCATED but not INITIALIZED
 762   osthread->set_state(ALLOCATED);
 763 
 764   thread->set_osthread(osthread);
 765 
 766   // init thread attributes
 767   pthread_attr_t attr;
 768   pthread_attr_init(&attr);
 769   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 770 
 771   // stack size
 772   if (os::Bsd::supports_variable_stack_size()) {
 773     // calculate stack size if it's not specified by caller
 774     if (stack_size == 0) {
 775       stack_size = os::Bsd::default_stack_size(thr_type);
 776 
 777       switch (thr_type) {
 778       case os::java_thread:
 779         // Java threads use ThreadStackSize which default value can be
 780         // changed with the flag -Xss
 781         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
 782         stack_size = JavaThread::stack_size_at_create();
 783         break;
 784       case os::compiler_thread:
 785         if (CompilerThreadStackSize > 0) {
 786           stack_size = (size_t)(CompilerThreadStackSize * K);
 787           break;
 788         } // else fall through:
 789           // use VMThreadStackSize if CompilerThreadStackSize is not defined
 790       case os::vm_thread:
 791       case os::pgc_thread:
 792       case os::cgc_thread:
 793       case os::watcher_thread:
 794         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
 795         break;
 796       }
 797     }
 798 
 799     stack_size = MAX2(stack_size, os::Bsd::min_stack_allowed);
 800     pthread_attr_setstacksize(&attr, stack_size);
 801   } else {
 802     // let pthread_create() pick the default value.
 803   }
 804 
 805   ThreadState state;
 806 
 807   {
 808     pthread_t tid;
 809     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
 810 
 811     pthread_attr_destroy(&attr);
 812 
 813     if (ret != 0) {
 814       if (PrintMiscellaneous && (Verbose || WizardMode)) {
 815         perror("pthread_create()");
 816       }
 817       // Need to clean up stuff we've allocated so far
 818       thread->set_osthread(NULL);
 819       delete osthread;
 820       return false;
 821     }
 822 
 823     // Store pthread info into the OSThread
 824     osthread->set_pthread_id(tid);
 825 
 826     // Wait until child thread is either initialized or aborted
 827     {
 828       Monitor* sync_with_child = osthread->startThread_lock();
 829       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 830       while ((state = osthread->get_state()) == ALLOCATED) {
 831         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
 832       }
 833     }
 834 
 835   }
 836 
 837   // Aborted due to thread limit being reached
 838   if (state == ZOMBIE) {
 839       thread->set_osthread(NULL);
 840       delete osthread;
 841       return false;
 842   }
 843 
 844   // The thread is returned suspended (in state INITIALIZED),
 845   // and is started higher up in the call chain
 846   assert(state == INITIALIZED, "race condition");
 847   return true;
 848 }
 849 
 850 /////////////////////////////////////////////////////////////////////////////
 851 // attach existing thread
 852 
 853 // bootstrap the main thread
 854 bool os::create_main_thread(JavaThread* thread) {
 855   assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
 856   return create_attached_thread(thread);
 857 }
 858 
 859 bool os::create_attached_thread(JavaThread* thread) {
 860 #ifdef ASSERT
 861     thread->verify_not_published();
 862 #endif
 863 
 864   // Allocate the OSThread object
 865   OSThread* osthread = new OSThread(NULL, NULL);
 866 
 867   if (osthread == NULL) {
 868     return false;
 869   }
 870 
 871   osthread->set_thread_id(os::Bsd::gettid());
 872 
 873   // Store pthread info into the OSThread
 874 #ifdef __APPLE__
 875   uint64_t unique_thread_id = locate_unique_thread_id(osthread->thread_id());
 876   guarantee(unique_thread_id != 0, "just checking");
 877   osthread->set_unique_thread_id(unique_thread_id);
 878 #endif
 879   osthread->set_pthread_id(::pthread_self());
 880 
 881   // initialize floating point control register
 882   os::Bsd::init_thread_fpu_state();
 883 
 884   // Initial thread state is RUNNABLE
 885   osthread->set_state(RUNNABLE);
 886 
 887   thread->set_osthread(osthread);
 888 
 889   // initialize signal mask for this thread
 890   // and save the caller's signal mask
 891   os::Bsd::hotspot_sigmask(thread);
 892 
 893   return true;
 894 }
 895 
 896 void os::pd_start_thread(Thread* thread) {
 897   OSThread * osthread = thread->osthread();
 898   assert(osthread->get_state() != INITIALIZED, "just checking");
 899   Monitor* sync_with_child = osthread->startThread_lock();
 900   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 901   sync_with_child->notify();
 902 }
 903 
 904 // Free Bsd resources related to the OSThread
 905 void os::free_thread(OSThread* osthread) {
 906   assert(osthread != NULL, "osthread not set");
 907 
 908   if (Thread::current()->osthread() == osthread) {
 909     // Restore caller's signal mask
 910     sigset_t sigmask = osthread->caller_sigmask();
 911     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
 912    }
 913 
 914   delete osthread;
 915 }
 916 
 917 //////////////////////////////////////////////////////////////////////////////
 918 // thread local storage
 919 
 920 // Restore the thread pointer if the destructor is called. This is in case
 921 // someone from JNI code sets up a destructor with pthread_key_create to run
 922 // detachCurrentThread on thread death. Unless we restore the thread pointer we
 923 // will hang or crash. When detachCurrentThread is called the key will be set
 924 // to null and we will not be called again. If detachCurrentThread is never
 925 // called we could loop forever depending on the pthread implementation.
 926 static void restore_thread_pointer(void* p) {
 927   Thread* thread = (Thread*) p;
 928   os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);
 929 }
 930 
 931 int os::allocate_thread_local_storage() {
 932   pthread_key_t key;
 933   int rslt = pthread_key_create(&key, restore_thread_pointer);
 934   assert(rslt == 0, "cannot allocate thread local storage");
 935   return (int)key;
 936 }
 937 
 938 // Note: This is currently not used by VM, as we don't destroy TLS key
 939 // on VM exit.
 940 void os::free_thread_local_storage(int index) {
 941   int rslt = pthread_key_delete((pthread_key_t)index);
 942   assert(rslt == 0, "invalid index");
 943 }
 944 
 945 void os::thread_local_storage_at_put(int index, void* value) {
 946   int rslt = pthread_setspecific((pthread_key_t)index, value);
 947   assert(rslt == 0, "pthread_setspecific failed");
 948 }
 949 
 950 extern "C" Thread* get_thread() {
 951   return ThreadLocalStorage::thread();
 952 }
 953 
 954 
 955 ////////////////////////////////////////////////////////////////////////////////
 956 // time support
 957 
 958 // Time since start-up in seconds to a fine granularity.
 959 // Used by VMSelfDestructTimer and the MemProfiler.
 960 double os::elapsedTime() {
 961 
 962   return ((double)os::elapsed_counter()) / os::elapsed_frequency();
 963 }
 964 
 965 jlong os::elapsed_counter() {
 966   return javaTimeNanos() - initial_time_count;
 967 }
 968 
 969 jlong os::elapsed_frequency() {
 970   return NANOSECS_PER_SEC; // nanosecond resolution
 971 }
 972 
 973 bool os::supports_vtime() { return true; }
 974 bool os::enable_vtime()   { return false; }
 975 bool os::vtime_enabled()  { return false; }
 976 
 977 double os::elapsedVTime() {
 978   // better than nothing, but not much
 979   return elapsedTime();
 980 }
 981 
 982 jlong os::javaTimeMillis() {
 983   timeval time;
 984   int status = gettimeofday(&time, NULL);
 985   assert(status != -1, "bsd error");
 986   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
 987 }
 988 

 989 #ifndef CLOCK_MONOTONIC
 990 #define CLOCK_MONOTONIC (1)
 991 #endif

 992 
 993 #ifdef __APPLE__
 994 void os::Bsd::clock_init() {
 995         // XXXDARWIN: Investigate replacement monotonic clock
 996 }
 997 #else
 998 void os::Bsd::clock_init() {
 999   struct timespec res;
1000   struct timespec tp;
1001   if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
1002       ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
1003     // yes, monotonic clock is supported
1004     _clock_gettime = ::clock_gettime;
1005   }
1006 }
1007 #endif
1008 
1009 

































1010 jlong os::javaTimeNanos() {
1011   if (os::supports_monotonic_clock()) {
1012     struct timespec tp;
1013     int status = Bsd::clock_gettime(CLOCK_MONOTONIC, &tp);
1014     assert(status == 0, "gettime error");
1015     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1016     return result;
1017   } else {
1018     timeval time;
1019     int status = gettimeofday(&time, NULL);
1020     assert(status != -1, "bsd error");
1021     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1022     return 1000 * usecs;
1023   }
1024 }
1025 


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