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