1 /*
   2  * Copyright (c) 1999, 2013, 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_linux.h"
  34 #include "memory/allocation.inline.hpp"
  35 #include "memory/filemap.hpp"
  36 #include "mutex_linux.inline.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "os_share_linux.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/init.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/javaCalls.hpp"
  49 #include "runtime/mutexLocker.hpp"
  50 #include "runtime/objectMonitor.hpp"
  51 #include "runtime/osThread.hpp"
  52 #include "runtime/perfMemory.hpp"
  53 #include "runtime/sharedRuntime.hpp"
  54 #include "runtime/statSampler.hpp"
  55 #include "runtime/stubRoutines.hpp"
  56 #include "runtime/threadCritical.hpp"
  57 #include "runtime/timer.hpp"
  58 #include "services/attachListener.hpp"
  59 #include "services/memTracker.hpp"
  60 #include "services/runtimeService.hpp"
  61 #include "thread_linux.inline.hpp"
  62 #include "utilities/decoder.hpp"
  63 #include "utilities/defaultStream.hpp"
  64 #include "utilities/events.hpp"
  65 #include "utilities/elfFile.hpp"
  66 #include "utilities/growableArray.hpp"
  67 #include "utilities/vmError.hpp"
  68 #ifdef TARGET_ARCH_x86
  69 # include "assembler_x86.inline.hpp"
  70 # include "nativeInst_x86.hpp"
  71 #endif
  72 #ifdef TARGET_ARCH_sparc
  73 # include "assembler_sparc.inline.hpp"
  74 # include "nativeInst_sparc.hpp"
  75 #endif
  76 #ifdef TARGET_ARCH_zero
  77 # include "assembler_zero.inline.hpp"
  78 # include "nativeInst_zero.hpp"
  79 #endif
  80 #ifdef TARGET_ARCH_arm
  81 # include "assembler_arm.inline.hpp"
  82 # include "nativeInst_arm.hpp"
  83 #endif
  84 #ifdef TARGET_ARCH_ppc
  85 # include "assembler_ppc.inline.hpp"
  86 # include "nativeInst_ppc.hpp"
  87 #endif
  88 
  89 // put OS-includes here
  90 # include <sys/types.h>
  91 # include <sys/mman.h>
  92 # include <sys/stat.h>
  93 # include <sys/select.h>
  94 # include <pthread.h>
  95 # include <signal.h>
  96 # include <errno.h>
  97 # include <dlfcn.h>
  98 # include <stdio.h>
  99 # include <unistd.h>
 100 # include <sys/resource.h>
 101 # include <pthread.h>
 102 # include <sys/stat.h>
 103 # include <sys/time.h>
 104 # include <sys/times.h>
 105 # include <sys/utsname.h>
 106 # include <sys/socket.h>
 107 # include <sys/wait.h>
 108 # include <pwd.h>
 109 # include <poll.h>
 110 # include <semaphore.h>
 111 # include <fcntl.h>
 112 # include <string.h>
 113 # include <syscall.h>
 114 # include <sys/sysinfo.h>
 115 # include <gnu/libc-version.h>
 116 # include <sys/ipc.h>
 117 # include <sys/shm.h>
 118 # include <link.h>
 119 # include <stdint.h>
 120 # include <inttypes.h>
 121 # include <sys/ioctl.h>
 122 
 123 #define MAX_PATH    (2 * K)
 124 
 125 // for timer info max values which include all bits
 126 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 127 
 128 #define LARGEPAGES_BIT (1 << 6)
 129 ////////////////////////////////////////////////////////////////////////////////
 130 // global variables
 131 julong os::Linux::_physical_memory = 0;
 132 
 133 address   os::Linux::_initial_thread_stack_bottom = NULL;
 134 uintptr_t os::Linux::_initial_thread_stack_size   = 0;
 135 
 136 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL;
 137 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
 138 Mutex* os::Linux::_createThread_lock = NULL;
 139 pthread_t os::Linux::_main_thread;
 140 int os::Linux::_page_size = -1;
 141 const int os::Linux::_vm_default_page_size = (8 * K);
 142 bool os::Linux::_is_floating_stack = false;
 143 bool os::Linux::_is_NPTL = false;
 144 bool os::Linux::_supports_fast_thread_cpu_time = false;
 145 const char * os::Linux::_glibc_version = NULL;
 146 const char * os::Linux::_libpthread_version = NULL;
 147 
 148 static jlong initial_time_count=0;
 149 
 150 static int clock_tics_per_sec = 100;
 151 
 152 // For diagnostics to print a message once. see run_periodic_checks
 153 static sigset_t check_signal_done;
 154 static bool check_signals = true;;
 155 
 156 static pid_t _initial_pid = 0;
 157 
 158 /* Signal number used to suspend/resume a thread */
 159 
 160 /* do not use any signal number less than SIGSEGV, see 4355769 */
 161 static int SR_signum = SIGUSR2;
 162 sigset_t SR_sigset;
 163 
 164 /* Used to protect dlsym() calls */
 165 static pthread_mutex_t dl_mutex;
 166 
 167 // Declarations
 168 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 169 
 170 #ifdef JAVASE_EMBEDDED
 171 class MemNotifyThread: public Thread {
 172   friend class VMStructs;
 173  public:
 174   virtual void run();
 175 
 176  private:
 177   static MemNotifyThread* _memnotify_thread;
 178   int _fd;
 179 
 180  public:
 181 
 182   // Constructor
 183   MemNotifyThread(int fd);
 184 
 185   // Tester
 186   bool is_memnotify_thread() const { return true; }
 187 
 188   // Printing
 189   char* name() const { return (char*)"Linux MemNotify Thread"; }
 190 
 191   // Returns the single instance of the MemNotifyThread
 192   static MemNotifyThread* memnotify_thread() { return _memnotify_thread; }
 193 
 194   // Create and start the single instance of MemNotifyThread
 195   static void start();
 196 };
 197 #endif // JAVASE_EMBEDDED
 198 
 199 // utility functions
 200 
 201 static int SR_initialize();
 202 static int SR_finalize();
 203 
 204 julong os::available_memory() {
 205   return Linux::available_memory();
 206 }
 207 
 208 julong os::Linux::available_memory() {
 209   // values in struct sysinfo are "unsigned long"
 210   struct sysinfo si;
 211   sysinfo(&si);
 212 
 213   return (julong)si.freeram * si.mem_unit;
 214 }
 215 
 216 julong os::physical_memory() {
 217   return Linux::physical_memory();
 218 }
 219 
 220 julong os::allocatable_physical_memory(julong size) {
 221 #ifdef _LP64
 222   return size;
 223 #else
 224   julong result = MIN2(size, (julong)3800*M);
 225    if (!is_allocatable(result)) {
 226      // See comments under solaris for alignment considerations
 227      julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
 228      result =  MIN2(size, reasonable_size);
 229    }
 230    return result;
 231 #endif // _LP64
 232 }
 233 
 234 ////////////////////////////////////////////////////////////////////////////////
 235 // environment support
 236 
 237 bool os::getenv(const char* name, char* buf, int len) {
 238   const char* val = ::getenv(name);
 239   if (val != NULL && strlen(val) < (size_t)len) {
 240     strcpy(buf, val);
 241     return true;
 242   }
 243   if (len > 0) buf[0] = 0;  // return a null string
 244   return false;
 245 }
 246 
 247 
 248 // Return true if user is running as root.
 249 
 250 bool os::have_special_privileges() {
 251   static bool init = false;
 252   static bool privileges = false;
 253   if (!init) {
 254     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 255     init = true;
 256   }
 257   return privileges;
 258 }
 259 
 260 
 261 #ifndef SYS_gettid
 262 // i386: 224, ia64: 1105, amd64: 186, sparc 143
 263 #ifdef __ia64__
 264 #define SYS_gettid 1105
 265 #elif __i386__
 266 #define SYS_gettid 224
 267 #elif __amd64__
 268 #define SYS_gettid 186
 269 #elif __sparc__
 270 #define SYS_gettid 143
 271 #else
 272 #error define gettid for the arch
 273 #endif
 274 #endif
 275 
 276 // Cpu architecture string
 277 #if   defined(ZERO)
 278 static char cpu_arch[] = ZERO_LIBARCH;
 279 #elif defined(IA64)
 280 static char cpu_arch[] = "ia64";
 281 #elif defined(IA32)
 282 static char cpu_arch[] = "i386";
 283 #elif defined(AMD64)
 284 static char cpu_arch[] = "amd64";
 285 #elif defined(ARM)
 286 static char cpu_arch[] = "arm";
 287 #elif defined(PPC)
 288 static char cpu_arch[] = "ppc";
 289 #elif defined(SPARC)
 290 #  ifdef _LP64
 291 static char cpu_arch[] = "sparcv9";
 292 #  else
 293 static char cpu_arch[] = "sparc";
 294 #  endif
 295 #else
 296 #error Add appropriate cpu_arch setting
 297 #endif
 298 
 299 
 300 // pid_t gettid()
 301 //
 302 // Returns the kernel thread id of the currently running thread. Kernel
 303 // thread id is used to access /proc.
 304 //
 305 // (Note that getpid() on LinuxThreads returns kernel thread id too; but
 306 // on NPTL, it returns the same pid for all threads, as required by POSIX.)
 307 //
 308 pid_t os::Linux::gettid() {
 309   int rslt = syscall(SYS_gettid);
 310   if (rslt == -1) {
 311      // old kernel, no NPTL support
 312      return getpid();
 313   } else {
 314      return (pid_t)rslt;
 315   }
 316 }
 317 
 318 // Most versions of linux have a bug where the number of processors are
 319 // determined by looking at the /proc file system.  In a chroot environment,
 320 // the system call returns 1.  This causes the VM to act as if it is
 321 // a single processor and elide locking (see is_MP() call).
 322 static bool unsafe_chroot_detected = false;
 323 static const char *unstable_chroot_error = "/proc file system not found.\n"
 324                      "Java may be unstable running multithreaded in a chroot "
 325                      "environment on Linux when /proc filesystem is not mounted.";
 326 
 327 void os::Linux::initialize_system_info() {
 328   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 329   if (processor_count() == 1) {
 330     pid_t pid = os::Linux::gettid();
 331     char fname[32];
 332     jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
 333     FILE *fp = fopen(fname, "r");
 334     if (fp == NULL) {
 335       unsafe_chroot_detected = true;
 336     } else {
 337       fclose(fp);
 338     }
 339   }
 340   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
 341   assert(processor_count() > 0, "linux error");
 342 }
 343 
 344 void os::init_system_properties_values() {
 345 //  char arch[12];
 346 //  sysinfo(SI_ARCHITECTURE, arch, sizeof(arch));
 347 
 348   // The next steps are taken in the product version:
 349   //
 350   // Obtain the JAVA_HOME value from the location of libjvm[_g].so.
 351   // This library should be located at:
 352   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so.
 353   //
 354   // If "/jre/lib/" appears at the right place in the path, then we
 355   // assume libjvm[_g].so is installed in a JDK and we use this path.
 356   //
 357   // Otherwise exit with message: "Could not create the Java virtual machine."
 358   //
 359   // The following extra steps are taken in the debugging version:
 360   //
 361   // If "/jre/lib/" does NOT appear at the right place in the path
 362   // instead of exit check for $JAVA_HOME environment variable.
 363   //
 364   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 365   // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so
 366   // it looks like libjvm[_g].so is installed there
 367   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so.
 368   //
 369   // Otherwise exit.
 370   //
 371   // Important note: if the location of libjvm.so changes this
 372   // code needs to be changed accordingly.
 373 
 374   // The next few definitions allow the code to be verbatim:
 375 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n), mtInternal)
 376 #define getenv(n) ::getenv(n)
 377 
 378 /*
 379  * See ld(1):
 380  *      The linker uses the following search paths to locate required
 381  *      shared libraries:
 382  *        1: ...
 383  *        ...
 384  *        7: The default directories, normally /lib and /usr/lib.
 385  */
 386 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
 387 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
 388 #else
 389 #define DEFAULT_LIBPATH "/lib:/usr/lib"
 390 #endif
 391 
 392 #define EXTENSIONS_DIR  "/lib/ext"
 393 #define ENDORSED_DIR    "/lib/endorsed"
 394 #define REG_DIR         "/usr/java/packages"
 395 
 396   {
 397     /* sysclasspath, java_home, dll_dir */
 398     {
 399         char *home_path;
 400         char *dll_path;
 401         char *pslash;
 402         char buf[MAXPATHLEN];
 403         os::jvm_path(buf, sizeof(buf));
 404 
 405         // Found the full path to libjvm.so.
 406         // Now cut the path to <java_home>/jre if we can.
 407         *(strrchr(buf, '/')) = '\0';  /* get rid of /libjvm.so */
 408         pslash = strrchr(buf, '/');
 409         if (pslash != NULL)
 410             *pslash = '\0';           /* get rid of /{client|server|hotspot} */
 411         dll_path = malloc(strlen(buf) + 1);
 412         if (dll_path == NULL)
 413             return;
 414         strcpy(dll_path, buf);
 415         Arguments::set_dll_dir(dll_path);
 416 
 417         if (pslash != NULL) {
 418             pslash = strrchr(buf, '/');
 419             if (pslash != NULL) {
 420                 *pslash = '\0';       /* get rid of /<arch> */
 421                 pslash = strrchr(buf, '/');
 422                 if (pslash != NULL)
 423                     *pslash = '\0';   /* get rid of /lib */
 424             }
 425         }
 426 
 427         home_path = malloc(strlen(buf) + 1);
 428         if (home_path == NULL)
 429             return;
 430         strcpy(home_path, buf);
 431         Arguments::set_java_home(home_path);
 432 
 433         if (!set_boot_path('/', ':'))
 434             return;
 435     }
 436 
 437     /*
 438      * Where to look for native libraries
 439      *
 440      * Note: Due to a legacy implementation, most of the library path
 441      * is set in the launcher.  This was to accomodate linking restrictions
 442      * on legacy Linux implementations (which are no longer supported).
 443      * Eventually, all the library path setting will be done here.
 444      *
 445      * However, to prevent the proliferation of improperly built native
 446      * libraries, the new path component /usr/java/packages is added here.
 447      * Eventually, all the library path setting will be done here.
 448      */
 449     {
 450         char *ld_library_path;
 451 
 452         /*
 453          * Construct the invariant part of ld_library_path. Note that the
 454          * space for the colon and the trailing null are provided by the
 455          * nulls included by the sizeof operator (so actually we allocate
 456          * a byte more than necessary).
 457          */
 458         ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") +
 459             strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH));
 460         sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch);
 461 
 462         /*
 463          * Get the user setting of LD_LIBRARY_PATH, and prepended it.  It
 464          * should always exist (until the legacy problem cited above is
 465          * addressed).
 466          */
 467         char *v = getenv("LD_LIBRARY_PATH");
 468         if (v != NULL) {
 469             char *t = ld_library_path;
 470             /* That's +1 for the colon and +1 for the trailing '\0' */
 471             ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1);
 472             sprintf(ld_library_path, "%s:%s", v, t);
 473         }
 474         Arguments::set_library_path(ld_library_path);
 475     }
 476 
 477     /*
 478      * Extensions directories.
 479      *
 480      * Note that the space for the colon and the trailing null are provided
 481      * by the nulls included by the sizeof operator (so actually one byte more
 482      * than necessary is allocated).
 483      */
 484     {
 485         char *buf = malloc(strlen(Arguments::get_java_home()) +
 486             sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR));
 487         sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR,
 488             Arguments::get_java_home());
 489         Arguments::set_ext_dirs(buf);
 490     }
 491 
 492     /* Endorsed standards default directory. */
 493     {
 494         char * buf;
 495         buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR));
 496         sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
 497         Arguments::set_endorsed_dirs(buf);
 498     }
 499   }
 500 
 501 #undef malloc
 502 #undef getenv
 503 #undef EXTENSIONS_DIR
 504 #undef ENDORSED_DIR
 505 
 506   // Done
 507   return;
 508 }
 509 
 510 ////////////////////////////////////////////////////////////////////////////////
 511 // breakpoint support
 512 
 513 void os::breakpoint() {
 514   BREAKPOINT;
 515 }
 516 
 517 extern "C" void breakpoint() {
 518   // use debugger to set breakpoint here
 519 }
 520 
 521 ////////////////////////////////////////////////////////////////////////////////
 522 // signal support
 523 
 524 debug_only(static bool signal_sets_initialized = false);
 525 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
 526 
 527 bool os::Linux::is_sig_ignored(int sig) {
 528       struct sigaction oact;
 529       sigaction(sig, (struct sigaction*)NULL, &oact);
 530       void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
 531                                      : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
 532       if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
 533            return true;
 534       else
 535            return false;
 536 }
 537 
 538 void os::Linux::signal_sets_init() {
 539   // Should also have an assertion stating we are still single-threaded.
 540   assert(!signal_sets_initialized, "Already initialized");
 541   // Fill in signals that are necessarily unblocked for all threads in
 542   // the VM. Currently, we unblock the following signals:
 543   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
 544   //                         by -Xrs (=ReduceSignalUsage));
 545   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
 546   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
 547   // the dispositions or masks wrt these signals.
 548   // Programs embedding the VM that want to use the above signals for their
 549   // own purposes must, at this time, use the "-Xrs" option to prevent
 550   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
 551   // (See bug 4345157, and other related bugs).
 552   // In reality, though, unblocking these signals is really a nop, since
 553   // these signals are not blocked by default.
 554   sigemptyset(&unblocked_sigs);
 555   sigemptyset(&allowdebug_blocked_sigs);
 556   sigaddset(&unblocked_sigs, SIGILL);
 557   sigaddset(&unblocked_sigs, SIGSEGV);
 558   sigaddset(&unblocked_sigs, SIGBUS);
 559   sigaddset(&unblocked_sigs, SIGFPE);
 560   sigaddset(&unblocked_sigs, SR_signum);
 561 
 562   if (!ReduceSignalUsage) {
 563    if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
 564       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
 565       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
 566    }
 567    if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
 568       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
 569       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
 570    }
 571    if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
 572       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
 573       sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
 574    }
 575   }
 576   // Fill in signals that are blocked by all but the VM thread.
 577   sigemptyset(&vm_sigs);
 578   if (!ReduceSignalUsage)
 579     sigaddset(&vm_sigs, BREAK_SIGNAL);
 580   debug_only(signal_sets_initialized = true);
 581 
 582 }
 583 
 584 // These are signals that are unblocked while a thread is running Java.
 585 // (For some reason, they get blocked by default.)
 586 sigset_t* os::Linux::unblocked_signals() {
 587   assert(signal_sets_initialized, "Not initialized");
 588   return &unblocked_sigs;
 589 }
 590 
 591 // These are the signals that are blocked while a (non-VM) thread is
 592 // running Java. Only the VM thread handles these signals.
 593 sigset_t* os::Linux::vm_signals() {
 594   assert(signal_sets_initialized, "Not initialized");
 595   return &vm_sigs;
 596 }
 597 
 598 // These are signals that are blocked during cond_wait to allow debugger in
 599 sigset_t* os::Linux::allowdebug_blocked_signals() {
 600   assert(signal_sets_initialized, "Not initialized");
 601   return &allowdebug_blocked_sigs;
 602 }
 603 
 604 void os::Linux::hotspot_sigmask(Thread* thread) {
 605 
 606   //Save caller's signal mask before setting VM signal mask
 607   sigset_t caller_sigmask;
 608   pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
 609 
 610   OSThread* osthread = thread->osthread();
 611   osthread->set_caller_sigmask(caller_sigmask);
 612 
 613   pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL);
 614 
 615   if (!ReduceSignalUsage) {
 616     if (thread->is_VM_thread()) {
 617       // Only the VM thread handles BREAK_SIGNAL ...
 618       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 619     } else {
 620       // ... all other threads block BREAK_SIGNAL
 621       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 622     }
 623   }
 624 }
 625 
 626 //////////////////////////////////////////////////////////////////////////////
 627 // detecting pthread library
 628 
 629 void os::Linux::libpthread_init() {
 630   // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
 631   // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
 632   // generic name for earlier versions.
 633   // Define macros here so we can build HotSpot on old systems.
 634 # ifndef _CS_GNU_LIBC_VERSION
 635 # define _CS_GNU_LIBC_VERSION 2
 636 # endif
 637 # ifndef _CS_GNU_LIBPTHREAD_VERSION
 638 # define _CS_GNU_LIBPTHREAD_VERSION 3
 639 # endif
 640 
 641   size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
 642   if (n > 0) {
 643      char *str = (char *)malloc(n, mtInternal);
 644      confstr(_CS_GNU_LIBC_VERSION, str, n);
 645      os::Linux::set_glibc_version(str);
 646   } else {
 647      // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
 648      static char _gnu_libc_version[32];
 649      jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version),
 650               "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release());
 651      os::Linux::set_glibc_version(_gnu_libc_version);
 652   }
 653 
 654   n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
 655   if (n > 0) {
 656      char *str = (char *)malloc(n, mtInternal);
 657      confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
 658      // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
 659      // us "NPTL-0.29" even we are running with LinuxThreads. Check if this
 660      // is the case. LinuxThreads has a hard limit on max number of threads.
 661      // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
 662      // On the other hand, NPTL does not have such a limit, sysconf()
 663      // will return -1 and errno is not changed. Check if it is really NPTL.
 664      if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 &&
 665          strstr(str, "NPTL") &&
 666          sysconf(_SC_THREAD_THREADS_MAX) > 0) {
 667        free(str);
 668        os::Linux::set_libpthread_version("linuxthreads");
 669      } else {
 670        os::Linux::set_libpthread_version(str);
 671      }
 672   } else {
 673     // glibc before 2.3.2 only has LinuxThreads.
 674     os::Linux::set_libpthread_version("linuxthreads");
 675   }
 676 
 677   if (strstr(libpthread_version(), "NPTL")) {
 678      os::Linux::set_is_NPTL();
 679   } else {
 680      os::Linux::set_is_LinuxThreads();
 681   }
 682 
 683   // LinuxThreads have two flavors: floating-stack mode, which allows variable
 684   // stack size; and fixed-stack mode. NPTL is always floating-stack.
 685   if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) {
 686      os::Linux::set_is_floating_stack();
 687   }
 688 }
 689 
 690 /////////////////////////////////////////////////////////////////////////////
 691 // thread stack
 692 
 693 // Force Linux kernel to expand current thread stack. If "bottom" is close
 694 // to the stack guard, caller should block all signals.
 695 //
 696 // MAP_GROWSDOWN:
 697 //   A special mmap() flag that is used to implement thread stacks. It tells
 698 //   kernel that the memory region should extend downwards when needed. This
 699 //   allows early versions of LinuxThreads to only mmap the first few pages
 700 //   when creating a new thread. Linux kernel will automatically expand thread
 701 //   stack as needed (on page faults).
 702 //
 703 //   However, because the memory region of a MAP_GROWSDOWN stack can grow on
 704 //   demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
 705 //   region, it's hard to tell if the fault is due to a legitimate stack
 706 //   access or because of reading/writing non-exist memory (e.g. buffer
 707 //   overrun). As a rule, if the fault happens below current stack pointer,
 708 //   Linux kernel does not expand stack, instead a SIGSEGV is sent to the
 709 //   application (see Linux kernel fault.c).
 710 //
 711 //   This Linux feature can cause SIGSEGV when VM bangs thread stack for
 712 //   stack overflow detection.
 713 //
 714 //   Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
 715 //   not use this flag. However, the stack of initial thread is not created
 716 //   by pthread, it is still MAP_GROWSDOWN. Also it's possible (though
 717 //   unlikely) that user code can create a thread with MAP_GROWSDOWN stack
 718 //   and then attach the thread to JVM.
 719 //
 720 // To get around the problem and allow stack banging on Linux, we need to
 721 // manually expand thread stack after receiving the SIGSEGV.
 722 //
 723 // There are two ways to expand thread stack to address "bottom", we used
 724 // both of them in JVM before 1.5:
 725 //   1. adjust stack pointer first so that it is below "bottom", and then
 726 //      touch "bottom"
 727 //   2. mmap() the page in question
 728 //
 729 // Now alternate signal stack is gone, it's harder to use 2. For instance,
 730 // if current sp is already near the lower end of page 101, and we need to
 731 // call mmap() to map page 100, it is possible that part of the mmap() frame
 732 // will be placed in page 100. When page 100 is mapped, it is zero-filled.
 733 // That will destroy the mmap() frame and cause VM to crash.
 734 //
 735 // The following code works by adjusting sp first, then accessing the "bottom"
 736 // page to force a page fault. Linux kernel will then automatically expand the
 737 // stack mapping.
 738 //
 739 // _expand_stack_to() assumes its frame size is less than page size, which
 740 // should always be true if the function is not inlined.
 741 
 742 #if __GNUC__ < 3    // gcc 2.x does not support noinline attribute
 743 #define NOINLINE
 744 #else
 745 #define NOINLINE __attribute__ ((noinline))
 746 #endif
 747 
 748 static void _expand_stack_to(address bottom) NOINLINE;
 749 
 750 static void _expand_stack_to(address bottom) {
 751   address sp;
 752   size_t size;
 753   volatile char *p;
 754 
 755   // Adjust bottom to point to the largest address within the same page, it
 756   // gives us a one-page buffer if alloca() allocates slightly more memory.
 757   bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size());
 758   bottom += os::Linux::page_size() - 1;
 759 
 760   // sp might be slightly above current stack pointer; if that's the case, we
 761   // will alloca() a little more space than necessary, which is OK. Don't use
 762   // os::current_stack_pointer(), as its result can be slightly below current
 763   // stack pointer, causing us to not alloca enough to reach "bottom".
 764   sp = (address)&sp;
 765 
 766   if (sp > bottom) {
 767     size = sp - bottom;
 768     p = (volatile char *)alloca(size);
 769     assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
 770     p[0] = '\0';
 771   }
 772 }
 773 
 774 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
 775   assert(t!=NULL, "just checking");
 776   assert(t->osthread()->expanding_stack(), "expand should be set");
 777   assert(t->stack_base() != NULL, "stack_base was not initialized");
 778 
 779   if (addr <  t->stack_base() && addr >= t->stack_yellow_zone_base()) {
 780     sigset_t mask_all, old_sigset;
 781     sigfillset(&mask_all);
 782     pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
 783     _expand_stack_to(addr);
 784     pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
 785     return true;
 786   }
 787   return false;
 788 }
 789 
 790 //////////////////////////////////////////////////////////////////////////////
 791 // create new thread
 792 
 793 static address highest_vm_reserved_address();
 794 
 795 // check if it's safe to start a new thread
 796 static bool _thread_safety_check(Thread* thread) {
 797   if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) {
 798     // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat)
 799     //   Heap is mmap'ed at lower end of memory space. Thread stacks are
 800     //   allocated (MAP_FIXED) from high address space. Every thread stack
 801     //   occupies a fixed size slot (usually 2Mbytes, but user can change
 802     //   it to other values if they rebuild LinuxThreads).
 803     //
 804     // Problem with MAP_FIXED is that mmap() can still succeed even part of
 805     // the memory region has already been mmap'ed. That means if we have too
 806     // many threads and/or very large heap, eventually thread stack will
 807     // collide with heap.
 808     //
 809     // Here we try to prevent heap/stack collision by comparing current
 810     // stack bottom with the highest address that has been mmap'ed by JVM
 811     // plus a safety margin for memory maps created by native code.
 812     //
 813     // This feature can be disabled by setting ThreadSafetyMargin to 0
 814     //
 815     if (ThreadSafetyMargin > 0) {
 816       address stack_bottom = os::current_stack_base() - os::current_stack_size();
 817 
 818       // not safe if our stack extends below the safety margin
 819       return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address();
 820     } else {
 821       return true;
 822     }
 823   } else {
 824     // Floating stack LinuxThreads or NPTL:
 825     //   Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When
 826     //   there's not enough space left, pthread_create() will fail. If we come
 827     //   here, that means enough space has been reserved for stack.
 828     return true;
 829   }
 830 }
 831 
 832 // Thread start routine for all newly created threads
 833 static void *java_start(Thread *thread) {
 834   // Try to randomize the cache line index of hot stack frames.
 835   // This helps when threads of the same stack traces evict each other's
 836   // cache lines. The threads can be either from the same JVM instance, or
 837   // from different JVM instances. The benefit is especially true for
 838   // processors with hyperthreading technology.
 839   static int counter = 0;
 840   int pid = os::current_process_id();
 841   alloca(((pid ^ counter++) & 7) * 128);
 842 
 843   ThreadLocalStorage::set_thread(thread);
 844 
 845   OSThread* osthread = thread->osthread();
 846   Monitor* sync = osthread->startThread_lock();
 847 
 848   // non floating stack LinuxThreads needs extra check, see above
 849   if (!_thread_safety_check(thread)) {
 850     // notify parent thread
 851     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
 852     osthread->set_state(ZOMBIE);
 853     sync->notify_all();
 854     return NULL;
 855   }
 856 
 857   // thread_id is kernel thread id (similar to Solaris LWP id)
 858   osthread->set_thread_id(os::Linux::gettid());
 859 
 860   if (UseNUMA) {
 861     int lgrp_id = os::numa_get_group_id();
 862     if (lgrp_id != -1) {
 863       thread->set_lgrp_id(lgrp_id);
 864     }
 865   }
 866   // initialize signal mask for this thread
 867   os::Linux::hotspot_sigmask(thread);
 868 
 869   // initialize floating point control register
 870   os::Linux::init_thread_fpu_state();
 871 
 872   // handshaking with parent thread
 873   {
 874     MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
 875 
 876     // notify parent thread
 877     osthread->set_state(INITIALIZED);
 878     sync->notify_all();
 879 
 880     // wait until os::start_thread()
 881     while (osthread->get_state() == INITIALIZED) {
 882       sync->wait(Mutex::_no_safepoint_check_flag);
 883     }
 884   }
 885 
 886   // call one more level start routine
 887   thread->run();
 888 
 889   return 0;
 890 }
 891 
 892 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
 893   assert(thread->osthread() == NULL, "caller responsible");
 894 
 895   // Allocate the OSThread object
 896   OSThread* osthread = new OSThread(NULL, NULL);
 897   if (osthread == NULL) {
 898     return false;
 899   }
 900 
 901   // set the correct thread state
 902   osthread->set_thread_type(thr_type);
 903 
 904   // Initial state is ALLOCATED but not INITIALIZED
 905   osthread->set_state(ALLOCATED);
 906 
 907   thread->set_osthread(osthread);
 908 
 909   // init thread attributes
 910   pthread_attr_t attr;
 911   pthread_attr_init(&attr);
 912   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 913 
 914   // stack size
 915   if (os::Linux::supports_variable_stack_size()) {
 916     // calculate stack size if it's not specified by caller
 917     if (stack_size == 0) {
 918       stack_size = os::Linux::default_stack_size(thr_type);
 919 
 920       switch (thr_type) {
 921       case os::java_thread:
 922         // Java threads use ThreadStackSize which default value can be
 923         // changed with the flag -Xss
 924         assert (JavaThread::stack_size_at_create() > 0, "this should be set");
 925         stack_size = JavaThread::stack_size_at_create();
 926         break;
 927       case os::compiler_thread:
 928         if (CompilerThreadStackSize > 0) {
 929           stack_size = (size_t)(CompilerThreadStackSize * K);
 930           break;
 931         } // else fall through:
 932           // use VMThreadStackSize if CompilerThreadStackSize is not defined
 933       case os::vm_thread:
 934       case os::pgc_thread:
 935       case os::cgc_thread:
 936       case os::watcher_thread:
 937         if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
 938         break;
 939       }
 940     }
 941 
 942     stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
 943     pthread_attr_setstacksize(&attr, stack_size);
 944   } else {
 945     // let pthread_create() pick the default value.
 946   }
 947 
 948   // glibc guard page
 949   pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type));
 950 
 951   ThreadState state;
 952 
 953   {
 954     // Serialize thread creation if we are running with fixed stack LinuxThreads
 955     bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack();
 956     if (lock) {
 957       os::Linux::createThread_lock()->lock_without_safepoint_check();
 958     }
 959 
 960     pthread_t tid;
 961     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
 962 
 963     pthread_attr_destroy(&attr);
 964 
 965     if (ret != 0) {
 966       if (PrintMiscellaneous && (Verbose || WizardMode)) {
 967         perror("pthread_create()");
 968       }
 969       // Need to clean up stuff we've allocated so far
 970       thread->set_osthread(NULL);
 971       delete osthread;
 972       if (lock) os::Linux::createThread_lock()->unlock();
 973       return false;
 974     }
 975 
 976     // Store pthread info into the OSThread
 977     osthread->set_pthread_id(tid);
 978 
 979     // Wait until child thread is either initialized or aborted
 980     {
 981       Monitor* sync_with_child = osthread->startThread_lock();
 982       MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 983       while ((state = osthread->get_state()) == ALLOCATED) {
 984         sync_with_child->wait(Mutex::_no_safepoint_check_flag);
 985       }
 986     }
 987 
 988     if (lock) {
 989       os::Linux::createThread_lock()->unlock();
 990     }
 991   }
 992 
 993   // Aborted due to thread limit being reached
 994   if (state == ZOMBIE) {
 995       thread->set_osthread(NULL);
 996       delete osthread;
 997       return false;
 998   }
 999 
1000   // The thread is returned suspended (in state INITIALIZED),
1001   // and is started higher up in the call chain
1002   assert(state == INITIALIZED, "race condition");
1003   return true;
1004 }
1005 
1006 /////////////////////////////////////////////////////////////////////////////
1007 // attach existing thread
1008 
1009 // bootstrap the main thread
1010 bool os::create_main_thread(JavaThread* thread) {
1011   assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
1012   return create_attached_thread(thread);
1013 }
1014 
1015 bool os::create_attached_thread(JavaThread* thread) {
1016 #ifdef ASSERT
1017     thread->verify_not_published();
1018 #endif
1019 
1020   // Allocate the OSThread object
1021   OSThread* osthread = new OSThread(NULL, NULL);
1022 
1023   if (osthread == NULL) {
1024     return false;
1025   }
1026 
1027   // Store pthread info into the OSThread
1028   osthread->set_thread_id(os::Linux::gettid());
1029   osthread->set_pthread_id(::pthread_self());
1030 
1031   // initialize floating point control register
1032   os::Linux::init_thread_fpu_state();
1033 
1034   // Initial thread state is RUNNABLE
1035   osthread->set_state(RUNNABLE);
1036 
1037   thread->set_osthread(osthread);
1038 
1039   if (UseNUMA) {
1040     int lgrp_id = os::numa_get_group_id();
1041     if (lgrp_id != -1) {
1042       thread->set_lgrp_id(lgrp_id);
1043     }
1044   }
1045 
1046   if (os::Linux::is_initial_thread()) {
1047     // If current thread is initial thread, its stack is mapped on demand,
1048     // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
1049     // the entire stack region to avoid SEGV in stack banging.
1050     // It is also useful to get around the heap-stack-gap problem on SuSE
1051     // kernel (see 4821821 for details). We first expand stack to the top
1052     // of yellow zone, then enable stack yellow zone (order is significant,
1053     // enabling yellow zone first will crash JVM on SuSE Linux), so there
1054     // is no gap between the last two virtual memory regions.
1055 
1056     JavaThread *jt = (JavaThread *)thread;
1057     address addr = jt->stack_yellow_zone_base();
1058     assert(addr != NULL, "initialization problem?");
1059     assert(jt->stack_available(addr) > 0, "stack guard should not be enabled");
1060 
1061     osthread->set_expanding_stack();
1062     os::Linux::manually_expand_stack(jt, addr);
1063     osthread->clear_expanding_stack();
1064   }
1065 
1066   // initialize signal mask for this thread
1067   // and save the caller's signal mask
1068   os::Linux::hotspot_sigmask(thread);
1069 
1070   return true;
1071 }
1072 
1073 void os::pd_start_thread(Thread* thread) {
1074   OSThread * osthread = thread->osthread();
1075   assert(osthread->get_state() != INITIALIZED, "just checking");
1076   Monitor* sync_with_child = osthread->startThread_lock();
1077   MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
1078   sync_with_child->notify();
1079 }
1080 
1081 // Free Linux resources related to the OSThread
1082 void os::free_thread(OSThread* osthread) {
1083   assert(osthread != NULL, "osthread not set");
1084 
1085   if (Thread::current()->osthread() == osthread) {
1086     // Restore caller's signal mask
1087     sigset_t sigmask = osthread->caller_sigmask();
1088     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1089    }
1090 
1091   delete osthread;
1092 }
1093 
1094 //////////////////////////////////////////////////////////////////////////////
1095 // thread local storage
1096 
1097 int os::allocate_thread_local_storage() {
1098   pthread_key_t key;
1099   int rslt = pthread_key_create(&key, NULL);
1100   assert(rslt == 0, "cannot allocate thread local storage");
1101   return (int)key;
1102 }
1103 
1104 // Note: This is currently not used by VM, as we don't destroy TLS key
1105 // on VM exit.
1106 void os::free_thread_local_storage(int index) {
1107   int rslt = pthread_key_delete((pthread_key_t)index);
1108   assert(rslt == 0, "invalid index");
1109 }
1110 
1111 void os::thread_local_storage_at_put(int index, void* value) {
1112   int rslt = pthread_setspecific((pthread_key_t)index, value);
1113   assert(rslt == 0, "pthread_setspecific failed");
1114 }
1115 
1116 extern "C" Thread* get_thread() {
1117   return ThreadLocalStorage::thread();
1118 }
1119 
1120 //////////////////////////////////////////////////////////////////////////////
1121 // initial thread
1122 
1123 // Check if current thread is the initial thread, similar to Solaris thr_main.
1124 bool os::Linux::is_initial_thread(void) {
1125   char dummy;
1126   // If called before init complete, thread stack bottom will be null.
1127   // Can be called if fatal error occurs before initialization.
1128   if (initial_thread_stack_bottom() == NULL) return false;
1129   assert(initial_thread_stack_bottom() != NULL &&
1130          initial_thread_stack_size()   != 0,
1131          "os::init did not locate initial thread's stack region");
1132   if ((address)&dummy >= initial_thread_stack_bottom() &&
1133       (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size())
1134        return true;
1135   else return false;
1136 }
1137 
1138 // Find the virtual memory area that contains addr
1139 static bool find_vma(address addr, address* vma_low, address* vma_high) {
1140   FILE *fp = fopen("/proc/self/maps", "r");
1141   if (fp) {
1142     address low, high;
1143     while (!feof(fp)) {
1144       if (fscanf(fp, "%p-%p", &low, &high) == 2) {
1145         if (low <= addr && addr < high) {
1146            if (vma_low)  *vma_low  = low;
1147            if (vma_high) *vma_high = high;
1148            fclose (fp);
1149            return true;
1150         }
1151       }
1152       for (;;) {
1153         int ch = fgetc(fp);
1154         if (ch == EOF || ch == (int)'\n') break;
1155       }
1156     }
1157     fclose(fp);
1158   }
1159   return false;
1160 }
1161 
1162 // Locate initial thread stack. This special handling of initial thread stack
1163 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
1164 // bogus value for initial thread.
1165 void os::Linux::capture_initial_stack(size_t max_size) {
1166   // stack size is the easy part, get it from RLIMIT_STACK
1167   size_t stack_size;
1168   struct rlimit rlim;
1169   getrlimit(RLIMIT_STACK, &rlim);
1170   stack_size = rlim.rlim_cur;
1171 
1172   // 6308388: a bug in ld.so will relocate its own .data section to the
1173   //   lower end of primordial stack; reduce ulimit -s value a little bit
1174   //   so we won't install guard page on ld.so's data section.
1175   stack_size -= 2 * page_size();
1176 
1177   // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat
1178   //   7.1, in both cases we will get 2G in return value.
1179   // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0,
1180   //   SuSE 7.2, Debian) can not handle alternate signal stack correctly
1181   //   for initial thread if its stack size exceeds 6M. Cap it at 2M,
1182   //   in case other parts in glibc still assumes 2M max stack size.
1183   // FIXME: alt signal stack is gone, maybe we can relax this constraint?
1184 #ifndef IA64
1185   if (stack_size > 2 * K * K) stack_size = 2 * K * K;
1186 #else
1187   // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
1188   if (stack_size > 4 * K * K) stack_size = 4 * K * K;
1189 #endif
1190 
1191   // Try to figure out where the stack base (top) is. This is harder.
1192   //
1193   // When an application is started, glibc saves the initial stack pointer in
1194   // a global variable "__libc_stack_end", which is then used by system
1195   // libraries. __libc_stack_end should be pretty close to stack top. The
1196   // variable is available since the very early days. However, because it is
1197   // a private interface, it could disappear in the future.
1198   //
1199   // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
1200   // to __libc_stack_end, it is very close to stack top, but isn't the real
1201   // stack top. Note that /proc may not exist if VM is running as a chroot
1202   // program, so reading /proc/<pid>/stat could fail. Also the contents of
1203   // /proc/<pid>/stat could change in the future (though unlikely).
1204   //
1205   // We try __libc_stack_end first. If that doesn't work, look for
1206   // /proc/<pid>/stat. If neither of them works, we use current stack pointer
1207   // as a hint, which should work well in most cases.
1208 
1209   uintptr_t stack_start;
1210 
1211   // try __libc_stack_end first
1212   uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1213   if (p && *p) {
1214     stack_start = *p;
1215   } else {
1216     // see if we can get the start_stack field from /proc/self/stat
1217     FILE *fp;
1218     int pid;
1219     char state;
1220     int ppid;
1221     int pgrp;
1222     int session;
1223     int nr;
1224     int tpgrp;
1225     unsigned long flags;
1226     unsigned long minflt;
1227     unsigned long cminflt;
1228     unsigned long majflt;
1229     unsigned long cmajflt;
1230     unsigned long utime;
1231     unsigned long stime;
1232     long cutime;
1233     long cstime;
1234     long prio;
1235     long nice;
1236     long junk;
1237     long it_real;
1238     uintptr_t start;
1239     uintptr_t vsize;
1240     intptr_t rss;
1241     uintptr_t rsslim;
1242     uintptr_t scodes;
1243     uintptr_t ecode;
1244     int i;
1245 
1246     // Figure what the primordial thread stack base is. Code is inspired
1247     // by email from Hans Boehm. /proc/self/stat begins with current pid,
1248     // followed by command name surrounded by parentheses, state, etc.
1249     char stat[2048];
1250     int statlen;
1251 
1252     fp = fopen("/proc/self/stat", "r");
1253     if (fp) {
1254       statlen = fread(stat, 1, 2047, fp);
1255       stat[statlen] = '\0';
1256       fclose(fp);
1257 
1258       // Skip pid and the command string. Note that we could be dealing with
1259       // weird command names, e.g. user could decide to rename java launcher
1260       // to "java 1.4.2 :)", then the stat file would look like
1261       //                1234 (java 1.4.2 :)) R ... ...
1262       // We don't really need to know the command string, just find the last
1263       // occurrence of ")" and then start parsing from there. See bug 4726580.
1264       char * s = strrchr(stat, ')');
1265 
1266       i = 0;
1267       if (s) {
1268         // Skip blank chars
1269         do s++; while (isspace(*s));
1270 
1271 #define _UFM UINTX_FORMAT
1272 #define _DFM INTX_FORMAT
1273 
1274         /*                                     1   1   1   1   1   1   1   1   1   1   2   2    2    2    2    2    2    2    2 */
1275         /*              3  4  5  6  7  8   9   0   1   2   3   4   5   6   7   8   9   0   1    2    3    4    5    6    7    8 */
1276         i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,
1277              &state,          /* 3  %c  */
1278              &ppid,           /* 4  %d  */
1279              &pgrp,           /* 5  %d  */
1280              &session,        /* 6  %d  */
1281              &nr,             /* 7  %d  */
1282              &tpgrp,          /* 8  %d  */
1283              &flags,          /* 9  %lu  */
1284              &minflt,         /* 10 %lu  */
1285              &cminflt,        /* 11 %lu  */
1286              &majflt,         /* 12 %lu  */
1287              &cmajflt,        /* 13 %lu  */
1288              &utime,          /* 14 %lu  */
1289              &stime,          /* 15 %lu  */
1290              &cutime,         /* 16 %ld  */
1291              &cstime,         /* 17 %ld  */
1292              &prio,           /* 18 %ld  */
1293              &nice,           /* 19 %ld  */
1294              &junk,           /* 20 %ld  */
1295              &it_real,        /* 21 %ld  */
1296              &start,          /* 22 UINTX_FORMAT */
1297              &vsize,          /* 23 UINTX_FORMAT */
1298              &rss,            /* 24 INTX_FORMAT  */
1299              &rsslim,         /* 25 UINTX_FORMAT */
1300              &scodes,         /* 26 UINTX_FORMAT */
1301              &ecode,          /* 27 UINTX_FORMAT */
1302              &stack_start);   /* 28 UINTX_FORMAT */
1303       }
1304 
1305 #undef _UFM
1306 #undef _DFM
1307 
1308       if (i != 28 - 2) {
1309          assert(false, "Bad conversion from /proc/self/stat");
1310          // product mode - assume we are the initial thread, good luck in the
1311          // embedded case.
1312          warning("Can't detect initial thread stack location - bad conversion");
1313          stack_start = (uintptr_t) &rlim;
1314       }
1315     } else {
1316       // For some reason we can't open /proc/self/stat (for example, running on
1317       // FreeBSD with a Linux emulator, or inside chroot), this should work for
1318       // most cases, so don't abort:
1319       warning("Can't detect initial thread stack location - no /proc/self/stat");
1320       stack_start = (uintptr_t) &rlim;
1321     }
1322   }
1323 
1324   // Now we have a pointer (stack_start) very close to the stack top, the
1325   // next thing to do is to figure out the exact location of stack top. We
1326   // can find out the virtual memory area that contains stack_start by
1327   // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1328   // and its upper limit is the real stack top. (again, this would fail if
1329   // running inside chroot, because /proc may not exist.)
1330 
1331   uintptr_t stack_top;
1332   address low, high;
1333   if (find_vma((address)stack_start, &low, &high)) {
1334     // success, "high" is the true stack top. (ignore "low", because initial
1335     // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1336     stack_top = (uintptr_t)high;
1337   } else {
1338     // failed, likely because /proc/self/maps does not exist
1339     warning("Can't detect initial thread stack location - find_vma failed");
1340     // best effort: stack_start is normally within a few pages below the real
1341     // stack top, use it as stack top, and reduce stack size so we won't put
1342     // guard page outside stack.
1343     stack_top = stack_start;
1344     stack_size -= 16 * page_size();
1345   }
1346 
1347   // stack_top could be partially down the page so align it
1348   stack_top = align_size_up(stack_top, page_size());
1349 
1350   if (max_size && stack_size > max_size) {
1351      _initial_thread_stack_size = max_size;
1352   } else {
1353      _initial_thread_stack_size = stack_size;
1354   }
1355 
1356   _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
1357   _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1358 }
1359 
1360 ////////////////////////////////////////////////////////////////////////////////
1361 // time support
1362 
1363 // Time since start-up in seconds to a fine granularity.
1364 // Used by VMSelfDestructTimer and the MemProfiler.
1365 double os::elapsedTime() {
1366 
1367   return (double)(os::elapsed_counter()) * 0.000001;
1368 }
1369 
1370 jlong os::elapsed_counter() {
1371   timeval time;
1372   int status = gettimeofday(&time, NULL);
1373   return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count;
1374 }
1375 
1376 jlong os::elapsed_frequency() {
1377   return (1000 * 1000);
1378 }
1379 
1380 // For now, we say that linux does not support vtime.  I have no idea
1381 // whether it can actually be made to (DLD, 9/13/05).
1382 
1383 bool os::supports_vtime() { return false; }
1384 bool os::enable_vtime()   { return false; }
1385 bool os::vtime_enabled()  { return false; }
1386 double os::elapsedVTime() {
1387   // better than nothing, but not much
1388   return elapsedTime();
1389 }
1390 
1391 jlong os::javaTimeMillis() {
1392   timeval time;
1393   int status = gettimeofday(&time, NULL);
1394   assert(status != -1, "linux error");
1395   return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
1396 }
1397 
1398 #ifndef CLOCK_MONOTONIC
1399 #define CLOCK_MONOTONIC (1)
1400 #endif
1401 
1402 void os::Linux::clock_init() {
1403   // we do dlopen's in this particular order due to bug in linux
1404   // dynamical loader (see 6348968) leading to crash on exit
1405   void* handle = dlopen("librt.so.1", RTLD_LAZY);
1406   if (handle == NULL) {
1407     handle = dlopen("librt.so", RTLD_LAZY);
1408   }
1409 
1410   if (handle) {
1411     int (*clock_getres_func)(clockid_t, struct timespec*) =
1412            (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1413     int (*clock_gettime_func)(clockid_t, struct timespec*) =
1414            (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1415     if (clock_getres_func && clock_gettime_func) {
1416       // See if monotonic clock is supported by the kernel. Note that some
1417       // early implementations simply return kernel jiffies (updated every
1418       // 1/100 or 1/1000 second). It would be bad to use such a low res clock
1419       // for nano time (though the monotonic property is still nice to have).
1420       // It's fixed in newer kernels, however clock_getres() still returns
1421       // 1/HZ. We check if clock_getres() works, but will ignore its reported
1422       // resolution for now. Hopefully as people move to new kernels, this
1423       // won't be a problem.
1424       struct timespec res;
1425       struct timespec tp;
1426       if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 &&
1427           clock_gettime_func(CLOCK_MONOTONIC, &tp)  == 0) {
1428         // yes, monotonic clock is supported
1429         _clock_gettime = clock_gettime_func;
1430       } else {
1431         // close librt if there is no monotonic clock
1432         dlclose(handle);
1433       }
1434     }
1435   }
1436 }
1437 
1438 #ifndef SYS_clock_getres
1439 
1440 #if defined(IA32) || defined(AMD64)
1441 #define SYS_clock_getres IA32_ONLY(266)  AMD64_ONLY(229)
1442 #define sys_clock_getres(x,y)  ::syscall(SYS_clock_getres, x, y)
1443 #else
1444 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
1445 #define sys_clock_getres(x,y)  -1
1446 #endif
1447 
1448 #else
1449 #define sys_clock_getres(x,y)  ::syscall(SYS_clock_getres, x, y)
1450 #endif
1451 
1452 void os::Linux::fast_thread_clock_init() {
1453   if (!UseLinuxPosixThreadCPUClocks) {
1454     return;
1455   }
1456   clockid_t clockid;
1457   struct timespec tp;
1458   int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1459       (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1460 
1461   // Switch to using fast clocks for thread cpu time if
1462   // the sys_clock_getres() returns 0 error code.
1463   // Note, that some kernels may support the current thread
1464   // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1465   // returned by the pthread_getcpuclockid().
1466   // If the fast Posix clocks are supported then the sys_clock_getres()
1467   // must return at least tp.tv_sec == 0 which means a resolution
1468   // better than 1 sec. This is extra check for reliability.
1469 
1470   if(pthread_getcpuclockid_func &&
1471      pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1472      sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1473 
1474     _supports_fast_thread_cpu_time = true;
1475     _pthread_getcpuclockid = pthread_getcpuclockid_func;
1476   }
1477 }
1478 
1479 jlong os::javaTimeNanos() {
1480   if (Linux::supports_monotonic_clock()) {
1481     struct timespec tp;
1482     int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
1483     assert(status == 0, "gettime error");
1484     jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1485     return result;
1486   } else {
1487     timeval time;
1488     int status = gettimeofday(&time, NULL);
1489     assert(status != -1, "linux error");
1490     jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1491     return 1000 * usecs;
1492   }
1493 }
1494 
1495 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1496   if (Linux::supports_monotonic_clock()) {
1497     info_ptr->max_value = ALL_64_BITS;
1498 
1499     // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1500     info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
1501     info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
1502   } else {
1503     // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1504     info_ptr->max_value = ALL_64_BITS;
1505 
1506     // gettimeofday is a real time clock so it skips
1507     info_ptr->may_skip_backward = true;
1508     info_ptr->may_skip_forward = true;
1509   }
1510 
1511   info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
1512 }
1513 
1514 // Return the real, user, and system times in seconds from an
1515 // arbitrary fixed point in the past.
1516 bool os::getTimesSecs(double* process_real_time,
1517                       double* process_user_time,
1518                       double* process_system_time) {
1519   struct tms ticks;
1520   clock_t real_ticks = times(&ticks);
1521 
1522   if (real_ticks == (clock_t) (-1)) {
1523     return false;
1524   } else {
1525     double ticks_per_second = (double) clock_tics_per_sec;
1526     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1527     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1528     *process_real_time = ((double) real_ticks) / ticks_per_second;
1529 
1530     return true;
1531   }
1532 }
1533 
1534 
1535 char * os::local_time_string(char *buf, size_t buflen) {
1536   struct tm t;
1537   time_t long_time;
1538   time(&long_time);
1539   localtime_r(&long_time, &t);
1540   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1541                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1542                t.tm_hour, t.tm_min, t.tm_sec);
1543   return buf;
1544 }
1545 
1546 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
1547   return localtime_r(clock, res);
1548 }
1549 
1550 ////////////////////////////////////////////////////////////////////////////////
1551 // runtime exit support
1552 
1553 // Note: os::shutdown() might be called very early during initialization, or
1554 // called from signal handler. Before adding something to os::shutdown(), make
1555 // sure it is async-safe and can handle partially initialized VM.
1556 void os::shutdown() {
1557 
1558   // allow PerfMemory to attempt cleanup of any persistent resources
1559   perfMemory_exit();
1560 
1561   // needs to remove object in file system
1562   AttachListener::abort();
1563 
1564   // flush buffered output, finish log files
1565   ostream_abort();
1566 
1567   // Check for abort hook
1568   abort_hook_t abort_hook = Arguments::abort_hook();
1569   if (abort_hook != NULL) {
1570     abort_hook();
1571   }
1572 
1573 }
1574 
1575 // Note: os::abort() might be called very early during initialization, or
1576 // called from signal handler. Before adding something to os::abort(), make
1577 // sure it is async-safe and can handle partially initialized VM.
1578 void os::abort(bool dump_core) {
1579   os::shutdown();
1580   if (dump_core) {
1581 #ifndef PRODUCT
1582     fdStream out(defaultStream::output_fd());
1583     out.print_raw("Current thread is ");
1584     char buf[16];
1585     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1586     out.print_raw_cr(buf);
1587     out.print_raw_cr("Dumping core ...");
1588 #endif
1589     ::abort(); // dump core
1590   }
1591 
1592   ::exit(1);
1593 }
1594 
1595 // Die immediately, no exit hook, no abort hook, no cleanup.
1596 void os::die() {
1597   // _exit() on LinuxThreads only kills current thread
1598   ::abort();
1599 }
1600 
1601 // unused on linux for now.
1602 void os::set_error_file(const char *logfile) {}
1603 
1604 
1605 // This method is a copy of JDK's sysGetLastErrorString
1606 // from src/solaris/hpi/src/system_md.c
1607 
1608 size_t os::lasterror(char *buf, size_t len) {
1609 
1610   if (errno == 0)  return 0;
1611 
1612   const char *s = ::strerror(errno);
1613   size_t n = ::strlen(s);
1614   if (n >= len) {
1615     n = len - 1;
1616   }
1617   ::strncpy(buf, s, n);
1618   buf[n] = '\0';
1619   return n;
1620 }
1621 
1622 intx os::current_thread_id() { return (intx)pthread_self(); }
1623 int os::current_process_id() {
1624 
1625   // Under the old linux thread library, linux gives each thread
1626   // its own process id. Because of this each thread will return
1627   // a different pid if this method were to return the result
1628   // of getpid(2). Linux provides no api that returns the pid
1629   // of the launcher thread for the vm. This implementation
1630   // returns a unique pid, the pid of the launcher thread
1631   // that starts the vm 'process'.
1632 
1633   // Under the NPTL, getpid() returns the same pid as the
1634   // launcher thread rather than a unique pid per thread.
1635   // Use gettid() if you want the old pre NPTL behaviour.
1636 
1637   // if you are looking for the result of a call to getpid() that
1638   // returns a unique pid for the calling thread, then look at the
1639   // OSThread::thread_id() method in osThread_linux.hpp file
1640 
1641   return (int)(_initial_pid ? _initial_pid : getpid());
1642 }
1643 
1644 // DLL functions
1645 
1646 const char* os::dll_file_extension() { return ".so"; }
1647 
1648 // This must be hard coded because it's the system's temporary
1649 // directory not the java application's temp directory, ala java.io.tmpdir.
1650 const char* os::get_temp_directory() { return "/tmp"; }
1651 
1652 static bool file_exists(const char* filename) {
1653   struct stat statbuf;
1654   if (filename == NULL || strlen(filename) == 0) {
1655     return false;
1656   }
1657   return os::stat(filename, &statbuf) == 0;
1658 }
1659 
1660 void os::dll_build_name(char* buffer, size_t buflen,
1661                         const char* pname, const char* fname) {
1662   // Copied from libhpi
1663   const size_t pnamelen = pname ? strlen(pname) : 0;
1664 
1665   // Quietly truncate on buffer overflow.  Should be an error.
1666   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1667       *buffer = '\0';
1668       return;
1669   }
1670 
1671   if (pnamelen == 0) {
1672     snprintf(buffer, buflen, "lib%s.so", fname);
1673   } else if (strchr(pname, *os::path_separator()) != NULL) {
1674     int n;
1675     char** pelements = split_path(pname, &n);
1676     for (int i = 0 ; i < n ; i++) {
1677       // Really shouldn't be NULL, but check can't hurt
1678       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1679         continue; // skip the empty path values
1680       }
1681       snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1682       if (file_exists(buffer)) {
1683         break;
1684       }
1685     }
1686     // release the storage
1687     for (int i = 0 ; i < n ; i++) {
1688       if (pelements[i] != NULL) {
1689         FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1690       }
1691     }
1692     if (pelements != NULL) {
1693       FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1694     }
1695   } else {
1696     snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1697   }
1698 }
1699 
1700 const char* os::get_current_directory(char *buf, int buflen) {
1701   return getcwd(buf, buflen);
1702 }
1703 
1704 // check if addr is inside libjvm[_g].so
1705 bool os::address_is_in_vm(address addr) {
1706   static address libjvm_base_addr;
1707   Dl_info dlinfo;
1708 
1709   if (libjvm_base_addr == NULL) {
1710     dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo);
1711     libjvm_base_addr = (address)dlinfo.dli_fbase;
1712     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1713   }
1714 
1715   if (dladdr((void *)addr, &dlinfo)) {
1716     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1717   }
1718 
1719   return false;
1720 }
1721 
1722 bool os::dll_address_to_function_name(address addr, char *buf,
1723                                       int buflen, int *offset) {
1724   Dl_info dlinfo;
1725 
1726   if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) {
1727     if (buf != NULL) {
1728       if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1729         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1730       }
1731     }
1732     if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1733     return true;
1734   } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) {
1735     if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1736         buf, buflen, offset, dlinfo.dli_fname)) {
1737        return true;
1738     }
1739   }
1740 
1741   if (buf != NULL) buf[0] = '\0';
1742   if (offset != NULL) *offset = -1;
1743   return false;
1744 }
1745 
1746 struct _address_to_library_name {
1747   address addr;          // input : memory address
1748   size_t  buflen;        //         size of fname
1749   char*   fname;         // output: library name
1750   address base;          //         library base addr
1751 };
1752 
1753 static int address_to_library_name_callback(struct dl_phdr_info *info,
1754                                             size_t size, void *data) {
1755   int i;
1756   bool found = false;
1757   address libbase = NULL;
1758   struct _address_to_library_name * d = (struct _address_to_library_name *)data;
1759 
1760   // iterate through all loadable segments
1761   for (i = 0; i < info->dlpi_phnum; i++) {
1762     address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1763     if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1764       // base address of a library is the lowest address of its loaded
1765       // segments.
1766       if (libbase == NULL || libbase > segbase) {
1767         libbase = segbase;
1768       }
1769       // see if 'addr' is within current segment
1770       if (segbase <= d->addr &&
1771           d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
1772         found = true;
1773       }
1774     }
1775   }
1776 
1777   // dlpi_name is NULL or empty if the ELF file is executable, return 0
1778   // so dll_address_to_library_name() can fall through to use dladdr() which
1779   // can figure out executable name from argv[0].
1780   if (found && info->dlpi_name && info->dlpi_name[0]) {
1781     d->base = libbase;
1782     if (d->fname) {
1783       jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
1784     }
1785     return 1;
1786   }
1787   return 0;
1788 }
1789 
1790 bool os::dll_address_to_library_name(address addr, char* buf,
1791                                      int buflen, int* offset) {
1792   Dl_info dlinfo;
1793   struct _address_to_library_name data;
1794 
1795   // There is a bug in old glibc dladdr() implementation that it could resolve
1796   // to wrong library name if the .so file has a base address != NULL. Here
1797   // we iterate through the program headers of all loaded libraries to find
1798   // out which library 'addr' really belongs to. This workaround can be
1799   // removed once the minimum requirement for glibc is moved to 2.3.x.
1800   data.addr = addr;
1801   data.fname = buf;
1802   data.buflen = buflen;
1803   data.base = NULL;
1804   int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
1805 
1806   if (rslt) {
1807      // buf already contains library name
1808      if (offset) *offset = addr - data.base;
1809      return true;
1810   } else if (dladdr((void*)addr, &dlinfo)){
1811      if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1812      if (offset) *offset = addr - (address)dlinfo.dli_fbase;
1813      return true;
1814   } else {
1815      if (buf) buf[0] = '\0';
1816      if (offset) *offset = -1;
1817      return false;
1818   }
1819 }
1820 
1821   // Loads .dll/.so and
1822   // in case of error it checks if .dll/.so was built for the
1823   // same architecture as Hotspot is running on
1824 
1825 
1826 // Remember the stack's state. The Linux dynamic linker will change
1827 // the stack to 'executable' at most once, so we must safepoint only once.
1828 bool os::Linux::_stack_is_executable = false;
1829 
1830 // VM operation that loads a library.  This is necessary if stack protection
1831 // of the Java stacks can be lost during loading the library.  If we
1832 // do not stop the Java threads, they can stack overflow before the stacks
1833 // are protected again.
1834 class VM_LinuxDllLoad: public VM_Operation {
1835  private:
1836   const char *_filename;
1837   char *_ebuf;
1838   int _ebuflen;
1839   void *_lib;
1840  public:
1841   VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1842     _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
1843   VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1844   void doit() {
1845     _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1846     os::Linux::_stack_is_executable = true;
1847   }
1848   void* loaded_library() { return _lib; }
1849 };
1850 
1851 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1852 {
1853   void * result = NULL;
1854   bool load_attempted = false;
1855 
1856   // Check whether the library to load might change execution rights
1857   // of the stack. If they are changed, the protection of the stack
1858   // guard pages will be lost. We need a safepoint to fix this.
1859   //
1860   // See Linux man page execstack(8) for more info.
1861   if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1862     ElfFile ef(filename);
1863     if (!ef.specifies_noexecstack()) {
1864       if (!is_init_completed()) {
1865         os::Linux::_stack_is_executable = true;
1866         // This is OK - No Java threads have been created yet, and hence no
1867         // stack guard pages to fix.
1868         //
1869         // This should happen only when you are building JDK7 using a very
1870         // old version of JDK6 (e.g., with JPRT) and running test_gamma.
1871         //
1872         // Dynamic loader will make all stacks executable after
1873         // this function returns, and will not do that again.
1874         assert(Threads::first() == NULL, "no Java threads should exist yet.");
1875       } else {
1876         warning("You have loaded library %s which might have disabled stack guard. "
1877                 "The VM will try to fix the stack guard now.\n"
1878                 "It's highly recommended that you fix the library with "
1879                 "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1880                 filename);
1881 
1882         assert(Thread::current()->is_Java_thread(), "must be Java thread");
1883         JavaThread *jt = JavaThread::current();
1884         if (jt->thread_state() != _thread_in_native) {
1885           // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1886           // that requires ExecStack. Cannot enter safe point. Let's give up.
1887           warning("Unable to fix stack guard. Giving up.");
1888         } else {
1889           if (!LoadExecStackDllInVMThread) {
1890             // This is for the case where the DLL has an static
1891             // constructor function that executes JNI code. We cannot
1892             // load such DLLs in the VMThread.
1893             result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1894           }
1895 
1896           ThreadInVMfromNative tiv(jt);
1897           debug_only(VMNativeEntryWrapper vew;)
1898 
1899           VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1900           VMThread::execute(&op);
1901           if (LoadExecStackDllInVMThread) {
1902             result = op.loaded_library();
1903           }
1904           load_attempted = true;
1905         }
1906       }
1907     }
1908   }
1909 
1910   if (!load_attempted) {
1911     result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1912   }
1913 
1914   if (result != NULL) {
1915     // Successful loading
1916     return result;
1917   }
1918 
1919   Elf32_Ehdr elf_head;
1920   int diag_msg_max_length=ebuflen-strlen(ebuf);
1921   char* diag_msg_buf=ebuf+strlen(ebuf);
1922 
1923   if (diag_msg_max_length==0) {
1924     // No more space in ebuf for additional diagnostics message
1925     return NULL;
1926   }
1927 
1928 
1929   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1930 
1931   if (file_descriptor < 0) {
1932     // Can't open library, report dlerror() message
1933     return NULL;
1934   }
1935 
1936   bool failed_to_read_elf_head=
1937     (sizeof(elf_head)!=
1938         (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1939 
1940   ::close(file_descriptor);
1941   if (failed_to_read_elf_head) {
1942     // file i/o error - report dlerror() msg
1943     return NULL;
1944   }
1945 
1946   typedef struct {
1947     Elf32_Half  code;         // Actual value as defined in elf.h
1948     Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1949     char        elf_class;    // 32 or 64 bit
1950     char        endianess;    // MSB or LSB
1951     char*       name;         // String representation
1952   } arch_t;
1953 
1954   #ifndef EM_486
1955   #define EM_486          6               /* Intel 80486 */
1956   #endif
1957 
1958   static const arch_t arch_array[]={
1959     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1960     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1961     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1962     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1963     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1964     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1965     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1966     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1967     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1968     {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1969     {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1970     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1971     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1972     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1973     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1974     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1975   };
1976 
1977   #if  (defined IA32)
1978     static  Elf32_Half running_arch_code=EM_386;
1979   #elif   (defined AMD64)
1980     static  Elf32_Half running_arch_code=EM_X86_64;
1981   #elif  (defined IA64)
1982     static  Elf32_Half running_arch_code=EM_IA_64;
1983   #elif  (defined __sparc) && (defined _LP64)
1984     static  Elf32_Half running_arch_code=EM_SPARCV9;
1985   #elif  (defined __sparc) && (!defined _LP64)
1986     static  Elf32_Half running_arch_code=EM_SPARC;
1987   #elif  (defined __powerpc64__)
1988     static  Elf32_Half running_arch_code=EM_PPC64;
1989   #elif  (defined __powerpc__)
1990     static  Elf32_Half running_arch_code=EM_PPC;
1991   #elif  (defined ARM)
1992     static  Elf32_Half running_arch_code=EM_ARM;
1993   #elif  (defined S390)
1994     static  Elf32_Half running_arch_code=EM_S390;
1995   #elif  (defined ALPHA)
1996     static  Elf32_Half running_arch_code=EM_ALPHA;
1997   #elif  (defined MIPSEL)
1998     static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1999   #elif  (defined PARISC)
2000     static  Elf32_Half running_arch_code=EM_PARISC;
2001   #elif  (defined MIPS)
2002     static  Elf32_Half running_arch_code=EM_MIPS;
2003   #elif  (defined M68K)
2004     static  Elf32_Half running_arch_code=EM_68K;
2005   #else
2006     #error Method os::dll_load requires that one of following is defined:\
2007          IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
2008   #endif
2009 
2010   // Identify compatability class for VM's architecture and library's architecture
2011   // Obtain string descriptions for architectures
2012 
2013   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
2014   int running_arch_index=-1;
2015 
2016   for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
2017     if (running_arch_code == arch_array[i].code) {
2018       running_arch_index    = i;
2019     }
2020     if (lib_arch.code == arch_array[i].code) {
2021       lib_arch.compat_class = arch_array[i].compat_class;
2022       lib_arch.name         = arch_array[i].name;
2023     }
2024   }
2025 
2026   assert(running_arch_index != -1,
2027     "Didn't find running architecture code (running_arch_code) in arch_array");
2028   if (running_arch_index == -1) {
2029     // Even though running architecture detection failed
2030     // we may still continue with reporting dlerror() message
2031     return NULL;
2032   }
2033 
2034   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
2035     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
2036     return NULL;
2037   }
2038 
2039 #ifndef S390
2040   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
2041     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
2042     return NULL;
2043   }
2044 #endif // !S390
2045 
2046   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
2047     if ( lib_arch.name!=NULL ) {
2048       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2049         " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
2050         lib_arch.name, arch_array[running_arch_index].name);
2051     } else {
2052       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2053       " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
2054         lib_arch.code,
2055         arch_array[running_arch_index].name);
2056     }
2057   }
2058 
2059   return NULL;
2060 }
2061 
2062 void * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
2063   void * result = ::dlopen(filename, RTLD_LAZY);
2064   if (result == NULL) {
2065     ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
2066     ebuf[ebuflen-1] = '\0';
2067   }
2068   return result;
2069 }
2070 
2071 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
2072   void * result = NULL;
2073   if (LoadExecStackDllInVMThread) {
2074     result = dlopen_helper(filename, ebuf, ebuflen);
2075   }
2076 
2077   // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
2078   // library that requires an executable stack, or which does not have this
2079   // stack attribute set, dlopen changes the stack attribute to executable. The
2080   // read protection of the guard pages gets lost.
2081   //
2082   // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
2083   // may have been queued at the same time.
2084 
2085   if (!_stack_is_executable) {
2086     JavaThread *jt = Threads::first();
2087 
2088     while (jt) {
2089       if (!jt->stack_guard_zone_unused() &&        // Stack not yet fully initialized
2090           jt->stack_yellow_zone_enabled()) {       // No pending stack overflow exceptions
2091         if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
2092                               jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
2093           warning("Attempt to reguard stack yellow zone failed.");
2094         }
2095       }
2096       jt = jt->next();
2097     }
2098   }
2099 
2100   return result;
2101 }
2102 
2103 /*
2104  * glibc-2.0 libdl is not MT safe.  If you are building with any glibc,
2105  * chances are you might want to run the generated bits against glibc-2.0
2106  * libdl.so, so always use locking for any version of glibc.
2107  */
2108 void* os::dll_lookup(void* handle, const char* name) {
2109   pthread_mutex_lock(&dl_mutex);
2110   void* res = dlsym(handle, name);
2111   pthread_mutex_unlock(&dl_mutex);
2112   return res;
2113 }
2114 
2115 
2116 static bool _print_ascii_file(const char* filename, outputStream* st) {
2117   int fd = ::open(filename, O_RDONLY);
2118   if (fd == -1) {
2119      return false;
2120   }
2121 
2122   char buf[32];
2123   int bytes;
2124   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
2125     st->print_raw(buf, bytes);
2126   }
2127 
2128   ::close(fd);
2129 
2130   return true;
2131 }
2132 
2133 void os::print_dll_info(outputStream *st) {
2134    st->print_cr("Dynamic libraries:");
2135 
2136    char fname[32];
2137    pid_t pid = os::Linux::gettid();
2138 
2139    jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
2140 
2141    if (!_print_ascii_file(fname, st)) {
2142      st->print("Can not get library information for pid = %d\n", pid);
2143    }
2144 }
2145 
2146 void os::print_os_info_brief(outputStream* st) {
2147   os::Linux::print_distro_info(st);
2148 
2149   os::Posix::print_uname_info(st);
2150 
2151   os::Linux::print_libversion_info(st);
2152 
2153 }
2154 
2155 void os::print_os_info(outputStream* st) {
2156   st->print("OS:");
2157 
2158   os::Linux::print_distro_info(st);
2159 
2160   os::Posix::print_uname_info(st);
2161 
2162   // Print warning if unsafe chroot environment detected
2163   if (unsafe_chroot_detected) {
2164     st->print("WARNING!! ");
2165     st->print_cr(unstable_chroot_error);
2166   }
2167 
2168   os::Linux::print_libversion_info(st);
2169 
2170   os::Posix::print_rlimit_info(st);
2171 
2172   os::Posix::print_load_average(st);
2173 
2174   os::Linux::print_full_memory_info(st);
2175 }
2176 
2177 // Try to identify popular distros.
2178 // Most Linux distributions have /etc/XXX-release file, which contains
2179 // the OS version string. Some have more than one /etc/XXX-release file
2180 // (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.),
2181 // so the order is important.
2182 void os::Linux::print_distro_info(outputStream* st) {
2183   if (!_print_ascii_file("/etc/mandrake-release", st) &&
2184       !_print_ascii_file("/etc/sun-release", st) &&
2185       !_print_ascii_file("/etc/redhat-release", st) &&
2186       !_print_ascii_file("/etc/SuSE-release", st) &&
2187       !_print_ascii_file("/etc/turbolinux-release", st) &&
2188       !_print_ascii_file("/etc/gentoo-release", st) &&
2189       !_print_ascii_file("/etc/debian_version", st) &&
2190       !_print_ascii_file("/etc/ltib-release", st) &&
2191       !_print_ascii_file("/etc/angstrom-version", st)) {
2192       st->print("Linux");
2193   }
2194   st->cr();
2195 }
2196 
2197 void os::Linux::print_libversion_info(outputStream* st) {
2198   // libc, pthread
2199   st->print("libc:");
2200   st->print(os::Linux::glibc_version()); st->print(" ");
2201   st->print(os::Linux::libpthread_version()); st->print(" ");
2202   if (os::Linux::is_LinuxThreads()) {
2203      st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed");
2204   }
2205   st->cr();
2206 }
2207 
2208 void os::Linux::print_full_memory_info(outputStream* st) {
2209    st->print("\n/proc/meminfo:\n");
2210    _print_ascii_file("/proc/meminfo", st);
2211    st->cr();
2212 }
2213 
2214 void os::print_memory_info(outputStream* st) {
2215 
2216   st->print("Memory:");
2217   st->print(" %dk page", os::vm_page_size()>>10);
2218 
2219   // values in struct sysinfo are "unsigned long"
2220   struct sysinfo si;
2221   sysinfo(&si);
2222 
2223   st->print(", physical " UINT64_FORMAT "k",
2224             os::physical_memory() >> 10);
2225   st->print("(" UINT64_FORMAT "k free)",
2226             os::available_memory() >> 10);
2227   st->print(", swap " UINT64_FORMAT "k",
2228             ((jlong)si.totalswap * si.mem_unit) >> 10);
2229   st->print("(" UINT64_FORMAT "k free)",
2230             ((jlong)si.freeswap * si.mem_unit) >> 10);
2231   st->cr();
2232 }
2233 
2234 void os::pd_print_cpu_info(outputStream* st) {
2235   st->print("\n/proc/cpuinfo:\n");
2236   if (!_print_ascii_file("/proc/cpuinfo", st)) {
2237     st->print("  <Not Available>");
2238   }
2239   st->cr();
2240 }
2241 
2242 // Taken from /usr/include/bits/siginfo.h  Supposed to be architecture specific
2243 // but they're the same for all the linux arch that we support
2244 // and they're the same for solaris but there's no common place to put this.
2245 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR",
2246                           "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG",
2247                           "ILL_COPROC", "ILL_BADSTK" };
2248 
2249 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV",
2250                           "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES",
2251                           "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" };
2252 
2253 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" };
2254 
2255 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" };
2256 
2257 void os::print_siginfo(outputStream* st, void* siginfo) {
2258   st->print("siginfo:");
2259 
2260   const int buflen = 100;
2261   char buf[buflen];
2262   siginfo_t *si = (siginfo_t*)siginfo;
2263   st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen));
2264   if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) {
2265     st->print("si_errno=%s", buf);
2266   } else {
2267     st->print("si_errno=%d", si->si_errno);
2268   }
2269   const int c = si->si_code;
2270   assert(c > 0, "unexpected si_code");
2271   switch (si->si_signo) {
2272   case SIGILL:
2273     st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]);
2274     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2275     break;
2276   case SIGFPE:
2277     st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]);
2278     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2279     break;
2280   case SIGSEGV:
2281     st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]);
2282     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2283     break;
2284   case SIGBUS:
2285     st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]);
2286     st->print(", si_addr=" PTR_FORMAT, si->si_addr);
2287     break;
2288   default:
2289     st->print(", si_code=%d", si->si_code);
2290     // no si_addr
2291   }
2292 
2293   if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
2294       UseSharedSpaces) {
2295     FileMapInfo* mapinfo = FileMapInfo::current_info();
2296     if (mapinfo->is_in_shared_space(si->si_addr)) {
2297       st->print("\n\nError accessing class data sharing archive."   \
2298                 " Mapped file inaccessible during execution, "      \
2299                 " possible disk/network problem.");
2300     }
2301   }
2302   st->cr();
2303 }
2304 
2305 
2306 static void print_signal_handler(outputStream* st, int sig,
2307                                  char* buf, size_t buflen);
2308 
2309 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2310   st->print_cr("Signal Handlers:");
2311   print_signal_handler(st, SIGSEGV, buf, buflen);
2312   print_signal_handler(st, SIGBUS , buf, buflen);
2313   print_signal_handler(st, SIGFPE , buf, buflen);
2314   print_signal_handler(st, SIGPIPE, buf, buflen);
2315   print_signal_handler(st, SIGXFSZ, buf, buflen);
2316   print_signal_handler(st, SIGILL , buf, buflen);
2317   print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
2318   print_signal_handler(st, SR_signum, buf, buflen);
2319   print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
2320   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2321   print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
2322   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2323 }
2324 
2325 static char saved_jvm_path[MAXPATHLEN] = {0};
2326 
2327 // Find the full path to the current module, libjvm.so or libjvm_g.so
2328 void os::jvm_path(char *buf, jint buflen) {
2329   // Error checking.
2330   if (buflen < MAXPATHLEN) {
2331     assert(false, "must use a large-enough buffer");
2332     buf[0] = '\0';
2333     return;
2334   }
2335   // Lazy resolve the path to current module.
2336   if (saved_jvm_path[0] != 0) {
2337     strcpy(buf, saved_jvm_path);
2338     return;
2339   }
2340 
2341   char dli_fname[MAXPATHLEN];
2342   bool ret = dll_address_to_library_name(
2343                 CAST_FROM_FN_PTR(address, os::jvm_path),
2344                 dli_fname, sizeof(dli_fname), NULL);
2345   assert(ret != 0, "cannot locate libjvm");
2346   char *rp = realpath(dli_fname, buf);
2347   if (rp == NULL)
2348     return;
2349 
2350   if (Arguments::created_by_gamma_launcher()) {
2351     // Support for the gamma launcher.  Typical value for buf is
2352     // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".  If "/jre/lib/" appears at
2353     // the right place in the string, then assume we are installed in a JDK and
2354     // we're done.  Otherwise, check for a JAVA_HOME environment variable and fix
2355     // up the path so it looks like libjvm.so is installed there (append a
2356     // fake suffix hotspot/libjvm.so).
2357     const char *p = buf + strlen(buf) - 1;
2358     for (int count = 0; p > buf && count < 5; ++count) {
2359       for (--p; p > buf && *p != '/'; --p)
2360         /* empty */ ;
2361     }
2362 
2363     if (strncmp(p, "/jre/lib/", 9) != 0) {
2364       // Look for JAVA_HOME in the environment.
2365       char* java_home_var = ::getenv("JAVA_HOME");
2366       if (java_home_var != NULL && java_home_var[0] != 0) {
2367         char* jrelib_p;
2368         int len;
2369 
2370         // Check the current module name "libjvm.so" or "libjvm_g.so".
2371         p = strrchr(buf, '/');
2372         assert(strstr(p, "/libjvm") == p, "invalid library name");
2373         p = strstr(p, "_g") ? "_g" : "";
2374 
2375         rp = realpath(java_home_var, buf);
2376         if (rp == NULL)
2377           return;
2378 
2379         // determine if this is a legacy image or modules image
2380         // modules image doesn't have "jre" subdirectory
2381         len = strlen(buf);
2382         jrelib_p = buf + len;
2383         snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2384         if (0 != access(buf, F_OK)) {
2385           snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2386         }
2387 
2388         if (0 == access(buf, F_OK)) {
2389           // Use current module name "libjvm[_g].so" instead of
2390           // "libjvm"debug_only("_g")".so" since for fastdebug version
2391           // we should have "libjvm.so" but debug_only("_g") adds "_g"!
2392           len = strlen(buf);
2393           snprintf(buf + len, buflen-len, "/hotspot/libjvm%s.so", p);
2394         } else {
2395           // Go back to path of .so
2396           rp = realpath(dli_fname, buf);
2397           if (rp == NULL)
2398             return;
2399         }
2400       }
2401     }
2402   }
2403 
2404   strcpy(saved_jvm_path, buf);
2405 }
2406 
2407 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2408   // no prefix required, not even "_"
2409 }
2410 
2411 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2412   // no suffix required
2413 }
2414 
2415 ////////////////////////////////////////////////////////////////////////////////
2416 // sun.misc.Signal support
2417 
2418 static volatile jint sigint_count = 0;
2419 
2420 static void
2421 UserHandler(int sig, void *siginfo, void *context) {
2422   // 4511530 - sem_post is serialized and handled by the manager thread. When
2423   // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
2424   // don't want to flood the manager thread with sem_post requests.
2425   if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
2426       return;
2427 
2428   // Ctrl-C is pressed during error reporting, likely because the error
2429   // handler fails to abort. Let VM die immediately.
2430   if (sig == SIGINT && is_error_reported()) {
2431      os::die();
2432   }
2433 
2434   os::signal_notify(sig);
2435 }
2436 
2437 void* os::user_handler() {
2438   return CAST_FROM_FN_PTR(void*, UserHandler);
2439 }
2440 
2441 class Semaphore : public StackObj {
2442   public:
2443     Semaphore();
2444     ~Semaphore();
2445     void signal();
2446     void wait();
2447     bool trywait();
2448     bool timedwait(unsigned int sec, int nsec);
2449   private:
2450     sem_t _semaphore;
2451 };
2452 
2453 
2454 Semaphore::Semaphore() {
2455   sem_init(&_semaphore, 0, 0);
2456 }
2457 
2458 Semaphore::~Semaphore() {
2459   sem_destroy(&_semaphore);
2460 }
2461 
2462 void Semaphore::signal() {
2463   sem_post(&_semaphore);
2464 }
2465 
2466 void Semaphore::wait() {
2467   sem_wait(&_semaphore);
2468 }
2469 
2470 bool Semaphore::trywait() {
2471   return sem_trywait(&_semaphore) == 0;
2472 }
2473 
2474 bool Semaphore::timedwait(unsigned int sec, int nsec) {
2475   struct timespec ts;
2476   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2477 
2478   while (1) {
2479     int result = sem_timedwait(&_semaphore, &ts);
2480     if (result == 0) {
2481       return true;
2482     } else if (errno == EINTR) {
2483       continue;
2484     } else if (errno == ETIMEDOUT) {
2485       return false;
2486     } else {
2487       return false;
2488     }
2489   }
2490 }
2491 
2492 extern "C" {
2493   typedef void (*sa_handler_t)(int);
2494   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2495 }
2496 
2497 void* os::signal(int signal_number, void* handler) {
2498   struct sigaction sigAct, oldSigAct;
2499 
2500   sigfillset(&(sigAct.sa_mask));
2501   sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
2502   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2503 
2504   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2505     // -1 means registration failed
2506     return (void *)-1;
2507   }
2508 
2509   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2510 }
2511 
2512 void os::signal_raise(int signal_number) {
2513   ::raise(signal_number);
2514 }
2515 
2516 /*
2517  * The following code is moved from os.cpp for making this
2518  * code platform specific, which it is by its very nature.
2519  */
2520 
2521 // Will be modified when max signal is changed to be dynamic
2522 int os::sigexitnum_pd() {
2523   return NSIG;
2524 }
2525 
2526 // a counter for each possible signal value
2527 static volatile jint pending_signals[NSIG+1] = { 0 };
2528 
2529 // Linux(POSIX) specific hand shaking semaphore.
2530 static sem_t sig_sem;
2531 static Semaphore sr_semaphore;
2532 
2533 void os::signal_init_pd() {
2534   // Initialize signal structures
2535   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2536 
2537   // Initialize signal semaphore
2538   ::sem_init(&sig_sem, 0, 0);
2539 }
2540 
2541 void os::signal_notify(int sig) {
2542   Atomic::inc(&pending_signals[sig]);
2543   ::sem_post(&sig_sem);
2544 }
2545 
2546 static int check_pending_signals(bool wait) {
2547   Atomic::store(0, &sigint_count);
2548   for (;;) {
2549     for (int i = 0; i < NSIG + 1; i++) {
2550       jint n = pending_signals[i];
2551       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2552         return i;
2553       }
2554     }
2555     if (!wait) {
2556       return -1;
2557     }
2558     JavaThread *thread = JavaThread::current();
2559     ThreadBlockInVM tbivm(thread);
2560 
2561     bool threadIsSuspended;
2562     do {
2563       thread->set_suspend_equivalent();
2564       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2565       ::sem_wait(&sig_sem);
2566 
2567       // were we externally suspended while we were waiting?
2568       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2569       if (threadIsSuspended) {
2570         //
2571         // The semaphore has been incremented, but while we were waiting
2572         // another thread suspended us. We don't want to continue running
2573         // while suspended because that would surprise the thread that
2574         // suspended us.
2575         //
2576         ::sem_post(&sig_sem);
2577 
2578         thread->java_suspend_self();
2579       }
2580     } while (threadIsSuspended);
2581   }
2582 }
2583 
2584 int os::signal_lookup() {
2585   return check_pending_signals(false);
2586 }
2587 
2588 int os::signal_wait() {
2589   return check_pending_signals(true);
2590 }
2591 
2592 ////////////////////////////////////////////////////////////////////////////////
2593 // Virtual Memory
2594 
2595 int os::vm_page_size() {
2596   // Seems redundant as all get out
2597   assert(os::Linux::page_size() != -1, "must call os::init");
2598   return os::Linux::page_size();
2599 }
2600 
2601 // Solaris allocates memory by pages.
2602 int os::vm_allocation_granularity() {
2603   assert(os::Linux::page_size() != -1, "must call os::init");
2604   return os::Linux::page_size();
2605 }
2606 
2607 // Rationale behind this function:
2608 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2609 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2610 //  samples for JITted code. Here we create private executable mapping over the code cache
2611 //  and then we can use standard (well, almost, as mapping can change) way to provide
2612 //  info for the reporting script by storing timestamp and location of symbol
2613 void linux_wrap_code(char* base, size_t size) {
2614   static volatile jint cnt = 0;
2615 
2616   if (!UseOprofile) {
2617     return;
2618   }
2619 
2620   char buf[PATH_MAX+1];
2621   int num = Atomic::add(1, &cnt);
2622 
2623   snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2624            os::get_temp_directory(), os::current_process_id(), num);
2625   unlink(buf);
2626 
2627   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2628 
2629   if (fd != -1) {
2630     off_t rv = ::lseek(fd, size-2, SEEK_SET);
2631     if (rv != (off_t)-1) {
2632       if (::write(fd, "", 1) == 1) {
2633         mmap(base, size,
2634              PROT_READ|PROT_WRITE|PROT_EXEC,
2635              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2636       }
2637     }
2638     ::close(fd);
2639     unlink(buf);
2640   }
2641 }
2642 
2643 // NOTE: Linux kernel does not really reserve the pages for us.
2644 //       All it does is to check if there are enough free pages
2645 //       left at the time of mmap(). This could be a potential
2646 //       problem.
2647 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2648   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2649   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2650                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2651   if (res != (uintptr_t) MAP_FAILED) {
2652     if (UseNUMAInterleaving) {
2653       numa_make_global(addr, size);
2654     }
2655     return true;
2656   }
2657   return false;
2658 }
2659 
2660 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
2661 #ifndef MAP_HUGETLB
2662 #define MAP_HUGETLB 0x40000
2663 #endif
2664 
2665 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2666 #ifndef MADV_HUGEPAGE
2667 #define MADV_HUGEPAGE 14
2668 #endif
2669 
2670 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2671                        bool exec) {
2672   if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2673     int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2674     uintptr_t res =
2675       (uintptr_t) ::mmap(addr, size, prot,
2676                          MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS|MAP_HUGETLB,
2677                          -1, 0);
2678     if (res != (uintptr_t) MAP_FAILED) {
2679       if (UseNUMAInterleaving) {
2680         numa_make_global(addr, size);
2681       }
2682       return true;
2683     }
2684     // Fall through and try to use small pages
2685   }
2686 
2687   if (commit_memory(addr, size, exec)) {
2688     realign_memory(addr, size, alignment_hint);
2689     return true;
2690   }
2691   return false;
2692 }
2693 
2694 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2695   if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
2696     // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2697     // be supported or the memory may already be backed by huge pages.
2698     ::madvise(addr, bytes, MADV_HUGEPAGE);
2699   }
2700 }
2701 
2702 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2703   // This method works by doing an mmap over an existing mmaping and effectively discarding
2704   // the existing pages. However it won't work for SHM-based large pages that cannot be
2705   // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2706   // small pages on top of the SHM segment. This method always works for small pages, so we
2707   // allow that in any case.
2708   if (alignment_hint <= (size_t)os::vm_page_size() || !UseSHM) {
2709     commit_memory(addr, bytes, alignment_hint, false);
2710   }
2711 }
2712 
2713 void os::numa_make_global(char *addr, size_t bytes) {
2714   Linux::numa_interleave_memory(addr, bytes);
2715 }
2716 
2717 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2718   Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2719 }
2720 
2721 bool os::numa_topology_changed()   { return false; }
2722 
2723 size_t os::numa_get_groups_num() {
2724   int max_node = Linux::numa_max_node();
2725   return max_node > 0 ? max_node + 1 : 1;
2726 }
2727 
2728 int os::numa_get_group_id() {
2729   int cpu_id = Linux::sched_getcpu();
2730   if (cpu_id != -1) {
2731     int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2732     if (lgrp_id != -1) {
2733       return lgrp_id;
2734     }
2735   }
2736   return 0;
2737 }
2738 
2739 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2740   for (size_t i = 0; i < size; i++) {
2741     ids[i] = i;
2742   }
2743   return size;
2744 }
2745 
2746 bool os::get_page_info(char *start, page_info* info) {
2747   return false;
2748 }
2749 
2750 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2751   return end;
2752 }
2753 
2754 
2755 int os::Linux::sched_getcpu_syscall(void) {
2756   unsigned int cpu;
2757   int retval = -1;
2758 
2759 #if defined(IA32)
2760 # ifndef SYS_getcpu
2761 # define SYS_getcpu 318
2762 # endif
2763   retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2764 #elif defined(AMD64)
2765 // Unfortunately we have to bring all these macros here from vsyscall.h
2766 // to be able to compile on old linuxes.
2767 # define __NR_vgetcpu 2
2768 # define VSYSCALL_START (-10UL << 20)
2769 # define VSYSCALL_SIZE 1024
2770 # define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2771   typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2772   vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2773   retval = vgetcpu(&cpu, NULL, NULL);
2774 #endif
2775 
2776   return (retval == -1) ? retval : cpu;
2777 }
2778 
2779 // Something to do with the numa-aware allocator needs these symbols
2780 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2781 extern "C" JNIEXPORT void numa_error(char *where) { }
2782 extern "C" JNIEXPORT int fork1() { return fork(); }
2783 
2784 
2785 // If we are running with libnuma version > 2, then we should
2786 // be trying to use symbols with versions 1.1
2787 // If we are running with earlier version, which did not have symbol versions,
2788 // we should use the base version.
2789 void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2790   void *f = dlvsym(handle, name, "libnuma_1.1");
2791   if (f == NULL) {
2792     f = dlsym(handle, name);
2793   }
2794   return f;
2795 }
2796 
2797 bool os::Linux::libnuma_init() {
2798   // sched_getcpu() should be in libc.
2799   set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2800                                   dlsym(RTLD_DEFAULT, "sched_getcpu")));
2801 
2802   // If it's not, try a direct syscall.
2803   if (sched_getcpu() == -1)
2804     set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, (void*)&sched_getcpu_syscall));
2805 
2806   if (sched_getcpu() != -1) { // Does it work?
2807     void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2808     if (handle != NULL) {
2809       set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2810                                            libnuma_dlsym(handle, "numa_node_to_cpus")));
2811       set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2812                                        libnuma_dlsym(handle, "numa_max_node")));
2813       set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2814                                         libnuma_dlsym(handle, "numa_available")));
2815       set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2816                                             libnuma_dlsym(handle, "numa_tonode_memory")));
2817       set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2818                                             libnuma_dlsym(handle, "numa_interleave_memory")));
2819 
2820 
2821       if (numa_available() != -1) {
2822         set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2823         // Create a cpu -> node mapping
2824         _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2825         rebuild_cpu_to_node_map();
2826         return true;
2827       }
2828     }
2829   }
2830   return false;
2831 }
2832 
2833 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
2834 // The table is later used in get_node_by_cpu().
2835 void os::Linux::rebuild_cpu_to_node_map() {
2836   const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
2837                               // in libnuma (possible values are starting from 16,
2838                               // and continuing up with every other power of 2, but less
2839                               // than the maximum number of CPUs supported by kernel), and
2840                               // is a subject to change (in libnuma version 2 the requirements
2841                               // are more reasonable) we'll just hardcode the number they use
2842                               // in the library.
2843   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
2844 
2845   size_t cpu_num = os::active_processor_count();
2846   size_t cpu_map_size = NCPUS / BitsPerCLong;
2847   size_t cpu_map_valid_size =
2848     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
2849 
2850   cpu_to_node()->clear();
2851   cpu_to_node()->at_grow(cpu_num - 1);
2852   size_t node_num = numa_get_groups_num();
2853 
2854   unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
2855   for (size_t i = 0; i < node_num; i++) {
2856     if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
2857       for (size_t j = 0; j < cpu_map_valid_size; j++) {
2858         if (cpu_map[j] != 0) {
2859           for (size_t k = 0; k < BitsPerCLong; k++) {
2860             if (cpu_map[j] & (1UL << k)) {
2861               cpu_to_node()->at_put(j * BitsPerCLong + k, i);
2862             }
2863           }
2864         }
2865       }
2866     }
2867   }
2868   FREE_C_HEAP_ARRAY(unsigned long, cpu_map, mtInternal);
2869 }
2870 
2871 int os::Linux::get_node_by_cpu(int cpu_id) {
2872   if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
2873     return cpu_to_node()->at(cpu_id);
2874   }
2875   return -1;
2876 }
2877 
2878 GrowableArray<int>* os::Linux::_cpu_to_node;
2879 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
2880 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
2881 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
2882 os::Linux::numa_available_func_t os::Linux::_numa_available;
2883 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
2884 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
2885 unsigned long* os::Linux::_numa_all_nodes;
2886 
2887 bool os::pd_uncommit_memory(char* addr, size_t size) {
2888   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2889                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2890   return res  != (uintptr_t) MAP_FAILED;
2891 }
2892 
2893 // Linux uses a growable mapping for the stack, and if the mapping for
2894 // the stack guard pages is not removed when we detach a thread the
2895 // stack cannot grow beyond the pages where the stack guard was
2896 // mapped.  If at some point later in the process the stack expands to
2897 // that point, the Linux kernel cannot expand the stack any further
2898 // because the guard pages are in the way, and a segfault occurs.
2899 //
2900 // However, it's essential not to split the stack region by unmapping
2901 // a region (leaving a hole) that's already part of the stack mapping,
2902 // so if the stack mapping has already grown beyond the guard pages at
2903 // the time we create them, we have to truncate the stack mapping.
2904 // So, we need to know the extent of the stack mapping when
2905 // create_stack_guard_pages() is called.
2906 
2907 // Find the bounds of the stack mapping.  Return true for success.
2908 //
2909 // We only need this for stacks that are growable: at the time of
2910 // writing thread stacks don't use growable mappings (i.e. those
2911 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
2912 // only applies to the main thread.
2913 
2914 static
2915 bool get_stack_bounds(uintptr_t *bottom, uintptr_t *top) {
2916 
2917   char buf[128];
2918   int fd, sz;
2919 
2920   if ((fd = ::open("/proc/self/maps", O_RDONLY)) < 0) {
2921     return false;
2922   }
2923 
2924   const char kw[] = "[stack]";
2925   const int kwlen = sizeof(kw)-1;
2926 
2927   // Address part of /proc/self/maps couldn't be more than 128 bytes
2928   while ((sz = os::get_line_chars(fd, buf, sizeof(buf))) > 0) {
2929      if (sz > kwlen && ::memcmp(buf+sz-kwlen, kw, kwlen) == 0) {
2930         // Extract addresses
2931         if (sscanf(buf, "%" SCNxPTR "-%" SCNxPTR, bottom, top) == 2) {
2932            uintptr_t sp = (uintptr_t) __builtin_frame_address(0);
2933            if (sp >= *bottom && sp <= *top) {
2934               ::close(fd);
2935               return true;
2936            }
2937         }
2938      }
2939   }
2940 
2941  ::close(fd);
2942   return false;
2943 }
2944 
2945 
2946 // If the (growable) stack mapping already extends beyond the point
2947 // where we're going to put our guard pages, truncate the mapping at
2948 // that point by munmap()ping it.  This ensures that when we later
2949 // munmap() the guard pages we don't leave a hole in the stack
2950 // mapping. This only affects the main/initial thread, but guard
2951 // against future OS changes
2952 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2953   uintptr_t stack_extent, stack_base;
2954   bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
2955   if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
2956       assert(os::Linux::is_initial_thread(),
2957            "growable stack in non-initial thread");
2958     if (stack_extent < (uintptr_t)addr)
2959       ::munmap((void*)stack_extent, (uintptr_t)addr - stack_extent);
2960   }
2961 
2962   return os::commit_memory(addr, size);
2963 }
2964 
2965 // If this is a growable mapping, remove the guard pages entirely by
2966 // munmap()ping them.  If not, just call uncommit_memory(). This only
2967 // affects the main/initial thread, but guard against future OS changes
2968 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2969   uintptr_t stack_extent, stack_base;
2970   bool chk_bounds = NOT_DEBUG(os::Linux::is_initial_thread()) DEBUG_ONLY(true);
2971   if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
2972       assert(os::Linux::is_initial_thread(),
2973            "growable stack in non-initial thread");
2974 
2975     return ::munmap(addr, size) == 0;
2976   }
2977 
2978   return os::uncommit_memory(addr, size);
2979 }
2980 
2981 static address _highest_vm_reserved_address = NULL;
2982 
2983 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
2984 // at 'requested_addr'. If there are existing memory mappings at the same
2985 // location, however, they will be overwritten. If 'fixed' is false,
2986 // 'requested_addr' is only treated as a hint, the return value may or
2987 // may not start from the requested address. Unlike Linux mmap(), this
2988 // function returns NULL to indicate failure.
2989 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
2990   char * addr;
2991   int flags;
2992 
2993   flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
2994   if (fixed) {
2995     assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
2996     flags |= MAP_FIXED;
2997   }
2998 
2999   // Map uncommitted pages PROT_READ and PROT_WRITE, change access
3000   // to PROT_EXEC if executable when we commit the page.
3001   addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
3002                        flags, -1, 0);
3003 
3004   if (addr != MAP_FAILED) {
3005     // anon_mmap() should only get called during VM initialization,
3006     // don't need lock (actually we can skip locking even it can be called
3007     // from multiple threads, because _highest_vm_reserved_address is just a
3008     // hint about the upper limit of non-stack memory regions.)
3009     if ((address)addr + bytes > _highest_vm_reserved_address) {
3010       _highest_vm_reserved_address = (address)addr + bytes;
3011     }
3012   }
3013 
3014   return addr == MAP_FAILED ? NULL : addr;
3015 }
3016 
3017 // Don't update _highest_vm_reserved_address, because there might be memory
3018 // regions above addr + size. If so, releasing a memory region only creates
3019 // a hole in the address space, it doesn't help prevent heap-stack collision.
3020 //
3021 static int anon_munmap(char * addr, size_t size) {
3022   return ::munmap(addr, size) == 0;
3023 }
3024 
3025 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
3026                          size_t alignment_hint) {
3027   return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
3028 }
3029 
3030 bool os::pd_release_memory(char* addr, size_t size) {
3031   return anon_munmap(addr, size);
3032 }
3033 
3034 static address highest_vm_reserved_address() {
3035   return _highest_vm_reserved_address;
3036 }
3037 
3038 static bool linux_mprotect(char* addr, size_t size, int prot) {
3039   // Linux wants the mprotect address argument to be page aligned.
3040   char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
3041 
3042   // According to SUSv3, mprotect() should only be used with mappings
3043   // established by mmap(), and mmap() always maps whole pages. Unaligned
3044   // 'addr' likely indicates problem in the VM (e.g. trying to change
3045   // protection of malloc'ed or statically allocated memory). Check the
3046   // caller if you hit this assert.
3047   assert(addr == bottom, "sanity check");
3048 
3049   size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3050   return ::mprotect(bottom, size, prot) == 0;
3051 }
3052 
3053 // Set protections specified
3054 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3055                         bool is_committed) {
3056   unsigned int p = 0;
3057   switch (prot) {
3058   case MEM_PROT_NONE: p = PROT_NONE; break;
3059   case MEM_PROT_READ: p = PROT_READ; break;
3060   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
3061   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3062   default:
3063     ShouldNotReachHere();
3064   }
3065   // is_committed is unused.
3066   return linux_mprotect(addr, bytes, p);
3067 }
3068 
3069 bool os::guard_memory(char* addr, size_t size) {
3070   return linux_mprotect(addr, size, PROT_NONE);
3071 }
3072 
3073 bool os::unguard_memory(char* addr, size_t size) {
3074   return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3075 }
3076 
3077 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3078   bool result = false;
3079   void *p = mmap (NULL, page_size, PROT_READ|PROT_WRITE,
3080                   MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
3081                   -1, 0);
3082 
3083   if (p != (void *) -1) {
3084     // We don't know if this really is a huge page or not.
3085     FILE *fp = fopen("/proc/self/maps", "r");
3086     if (fp) {
3087       while (!feof(fp)) {
3088         char chars[257];
3089         long x = 0;
3090         if (fgets(chars, sizeof(chars), fp)) {
3091           if (sscanf(chars, "%lx-%*x", &x) == 1
3092               && x == (long)p) {
3093             if (strstr (chars, "hugepage")) {
3094               result = true;
3095               break;
3096             }
3097           }
3098         }
3099       }
3100       fclose(fp);
3101     }
3102     munmap (p, page_size);
3103     if (result)
3104       return true;
3105   }
3106 
3107   if (warn) {
3108     warning("HugeTLBFS is not supported by the operating system.");
3109   }
3110 
3111   return result;
3112 }
3113 
3114 /*
3115 * Set the coredump_filter bits to include largepages in core dump (bit 6)
3116 *
3117 * From the coredump_filter documentation:
3118 *
3119 * - (bit 0) anonymous private memory
3120 * - (bit 1) anonymous shared memory
3121 * - (bit 2) file-backed private memory
3122 * - (bit 3) file-backed shared memory
3123 * - (bit 4) ELF header pages in file-backed private memory areas (it is
3124 *           effective only if the bit 2 is cleared)
3125 * - (bit 5) hugetlb private memory
3126 * - (bit 6) hugetlb shared memory
3127 */
3128 static void set_coredump_filter(void) {
3129   FILE *f;
3130   long cdm;
3131 
3132   if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3133     return;
3134   }
3135 
3136   if (fscanf(f, "%lx", &cdm) != 1) {
3137     fclose(f);
3138     return;
3139   }
3140 
3141   rewind(f);
3142 
3143   if ((cdm & LARGEPAGES_BIT) == 0) {
3144     cdm |= LARGEPAGES_BIT;
3145     fprintf(f, "%#lx", cdm);
3146   }
3147 
3148   fclose(f);
3149 }
3150 
3151 // Large page support
3152 
3153 static size_t _large_page_size = 0;
3154 
3155 void os::large_page_init() {
3156   if (!UseLargePages) {
3157     UseHugeTLBFS = false;
3158     UseSHM = false;
3159     return;
3160   }
3161 
3162   if (FLAG_IS_DEFAULT(UseHugeTLBFS) && FLAG_IS_DEFAULT(UseSHM)) {
3163     // If UseLargePages is specified on the command line try both methods,
3164     // if it's default, then try only HugeTLBFS.
3165     if (FLAG_IS_DEFAULT(UseLargePages)) {
3166       UseHugeTLBFS = true;
3167     } else {
3168       UseHugeTLBFS = UseSHM = true;
3169     }
3170   }
3171 
3172   if (LargePageSizeInBytes) {
3173     _large_page_size = LargePageSizeInBytes;
3174   } else {
3175     // large_page_size on Linux is used to round up heap size. x86 uses either
3176     // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3177     // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3178     // page as large as 256M.
3179     //
3180     // Here we try to figure out page size by parsing /proc/meminfo and looking
3181     // for a line with the following format:
3182     //    Hugepagesize:     2048 kB
3183     //
3184     // If we can't determine the value (e.g. /proc is not mounted, or the text
3185     // format has been changed), we'll use the largest page size supported by
3186     // the processor.
3187 
3188 #ifndef ZERO
3189     _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
3190                        ARM_ONLY(2 * M) PPC_ONLY(4 * M);
3191 #endif // ZERO
3192 
3193     FILE *fp = fopen("/proc/meminfo", "r");
3194     if (fp) {
3195       while (!feof(fp)) {
3196         int x = 0;
3197         char buf[16];
3198         if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3199           if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3200             _large_page_size = x * K;
3201             break;
3202           }
3203         } else {
3204           // skip to next line
3205           for (;;) {
3206             int ch = fgetc(fp);
3207             if (ch == EOF || ch == (int)'\n') break;
3208           }
3209         }
3210       }
3211       fclose(fp);
3212     }
3213   }
3214 
3215   // print a warning if any large page related flag is specified on command line
3216   bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3217 
3218   const size_t default_page_size = (size_t)Linux::page_size();
3219   if (_large_page_size > default_page_size) {
3220     _page_sizes[0] = _large_page_size;
3221     _page_sizes[1] = default_page_size;
3222     _page_sizes[2] = 0;
3223   }
3224   UseHugeTLBFS = UseHugeTLBFS &&
3225                  Linux::hugetlbfs_sanity_check(warn_on_failure, _large_page_size);
3226 
3227   if (UseHugeTLBFS)
3228     UseSHM = false;
3229 
3230   UseLargePages = UseHugeTLBFS || UseSHM;
3231 
3232   set_coredump_filter();
3233 }
3234 
3235 #ifndef SHM_HUGETLB
3236 #define SHM_HUGETLB 04000
3237 #endif
3238 
3239 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
3240   // "exec" is passed in but not used.  Creating the shared image for
3241   // the code cache doesn't have an SHM_X executable permission to check.
3242   assert(UseLargePages && UseSHM, "only for SHM large pages");
3243 
3244   key_t key = IPC_PRIVATE;
3245   char *addr;
3246 
3247   bool warn_on_failure = UseLargePages &&
3248                         (!FLAG_IS_DEFAULT(UseLargePages) ||
3249                          !FLAG_IS_DEFAULT(LargePageSizeInBytes)
3250                         );
3251   char msg[128];
3252 
3253   // Create a large shared memory region to attach to based on size.
3254   // Currently, size is the total size of the heap
3255   int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3256   if (shmid == -1) {
3257      // Possible reasons for shmget failure:
3258      // 1. shmmax is too small for Java heap.
3259      //    > check shmmax value: cat /proc/sys/kernel/shmmax
3260      //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
3261      // 2. not enough large page memory.
3262      //    > check available large pages: cat /proc/meminfo
3263      //    > increase amount of large pages:
3264      //          echo new_value > /proc/sys/vm/nr_hugepages
3265      //      Note 1: different Linux may use different name for this property,
3266      //            e.g. on Redhat AS-3 it is "hugetlb_pool".
3267      //      Note 2: it's possible there's enough physical memory available but
3268      //            they are so fragmented after a long run that they can't
3269      //            coalesce into large pages. Try to reserve large pages when
3270      //            the system is still "fresh".
3271      if (warn_on_failure) {
3272        jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
3273        warning(msg);
3274      }
3275      return NULL;
3276   }
3277 
3278   // attach to the region
3279   addr = (char*)shmat(shmid, req_addr, 0);
3280   int err = errno;
3281 
3282   // Remove shmid. If shmat() is successful, the actual shared memory segment
3283   // will be deleted when it's detached by shmdt() or when the process
3284   // terminates. If shmat() is not successful this will remove the shared
3285   // segment immediately.
3286   shmctl(shmid, IPC_RMID, NULL);
3287 
3288   if ((intptr_t)addr == -1) {
3289      if (warn_on_failure) {
3290        jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
3291        warning(msg);
3292      }
3293      return NULL;
3294   }
3295 
3296   if ((addr != NULL) && UseNUMAInterleaving) {
3297     numa_make_global(addr, bytes);
3298   }
3299 
3300   // The memory is committed
3301   address pc = CALLER_PC;
3302   MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
3303   MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
3304 
3305   return addr;
3306 }
3307 
3308 bool os::release_memory_special(char* base, size_t bytes) {
3309   // detaching the SHM segment will also delete it, see reserve_memory_special()
3310   int rslt = shmdt(base);
3311   if (rslt == 0) {
3312     MemTracker::record_virtual_memory_uncommit((address)base, bytes);
3313     MemTracker::record_virtual_memory_release((address)base, bytes);
3314     return true;
3315   } else {
3316    return false;
3317   }
3318 }
3319 
3320 size_t os::large_page_size() {
3321   return _large_page_size;
3322 }
3323 
3324 // HugeTLBFS allows application to commit large page memory on demand;
3325 // with SysV SHM the entire memory region must be allocated as shared
3326 // memory.
3327 bool os::can_commit_large_page_memory() {
3328   return UseHugeTLBFS;
3329 }
3330 
3331 bool os::can_execute_large_page_memory() {
3332   return UseHugeTLBFS;
3333 }
3334 
3335 // Reserve memory at an arbitrary address, only if that area is
3336 // available (and not reserved for something else).
3337 
3338 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
3339   const int max_tries = 10;
3340   char* base[max_tries];
3341   size_t size[max_tries];
3342   const size_t gap = 0x000000;
3343 
3344   // Assert only that the size is a multiple of the page size, since
3345   // that's all that mmap requires, and since that's all we really know
3346   // about at this low abstraction level.  If we need higher alignment,
3347   // we can either pass an alignment to this method or verify alignment
3348   // in one of the methods further up the call chain.  See bug 5044738.
3349   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
3350 
3351   // Repeatedly allocate blocks until the block is allocated at the
3352   // right spot. Give up after max_tries. Note that reserve_memory() will
3353   // automatically update _highest_vm_reserved_address if the call is
3354   // successful. The variable tracks the highest memory address every reserved
3355   // by JVM. It is used to detect heap-stack collision if running with
3356   // fixed-stack LinuxThreads. Because here we may attempt to reserve more
3357   // space than needed, it could confuse the collision detecting code. To
3358   // solve the problem, save current _highest_vm_reserved_address and
3359   // calculate the correct value before return.
3360   address old_highest = _highest_vm_reserved_address;
3361 
3362   // Linux mmap allows caller to pass an address as hint; give it a try first,
3363   // if kernel honors the hint then we can return immediately.
3364   char * addr = anon_mmap(requested_addr, bytes, false);
3365   if (addr == requested_addr) {
3366      return requested_addr;
3367   }
3368 
3369   if (addr != NULL) {
3370      // mmap() is successful but it fails to reserve at the requested address
3371      anon_munmap(addr, bytes);
3372   }
3373 
3374   int i;
3375   for (i = 0; i < max_tries; ++i) {
3376     base[i] = reserve_memory(bytes);
3377 
3378     if (base[i] != NULL) {
3379       // Is this the block we wanted?
3380       if (base[i] == requested_addr) {
3381         size[i] = bytes;
3382         break;
3383       }
3384 
3385       // Does this overlap the block we wanted? Give back the overlapped
3386       // parts and try again.
3387 
3388       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
3389       if (top_overlap >= 0 && top_overlap < bytes) {
3390         unmap_memory(base[i], top_overlap);
3391         base[i] += top_overlap;
3392         size[i] = bytes - top_overlap;
3393       } else {
3394         size_t bottom_overlap = base[i] + bytes - requested_addr;
3395         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
3396           unmap_memory(requested_addr, bottom_overlap);
3397           size[i] = bytes - bottom_overlap;
3398         } else {
3399           size[i] = bytes;
3400         }
3401       }
3402     }
3403   }
3404 
3405   // Give back the unused reserved pieces.
3406 
3407   for (int j = 0; j < i; ++j) {
3408     if (base[j] != NULL) {
3409       unmap_memory(base[j], size[j]);
3410     }
3411   }
3412 
3413   if (i < max_tries) {
3414     _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
3415     return requested_addr;
3416   } else {
3417     _highest_vm_reserved_address = old_highest;
3418     return NULL;
3419   }
3420 }
3421 
3422 size_t os::read(int fd, void *buf, unsigned int nBytes) {
3423   return ::read(fd, buf, nBytes);
3424 }
3425 
3426 // TODO-FIXME: reconcile Solaris' os::sleep with the linux variation.
3427 // Solaris uses poll(), linux uses park().
3428 // Poll() is likely a better choice, assuming that Thread.interrupt()
3429 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
3430 // SIGSEGV, see 4355769.
3431 
3432 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
3433   assert(thread == Thread::current(),  "thread consistency check");
3434 
3435   ParkEvent * const slp = thread->_SleepEvent ;
3436   slp->reset() ;
3437   OrderAccess::fence() ;
3438 
3439   if (interruptible) {
3440     jlong prevtime = javaTimeNanos();
3441 
3442     for (;;) {
3443       if (os::is_interrupted(thread, true)) {
3444         return OS_INTRPT;
3445       }
3446 
3447       jlong newtime = javaTimeNanos();
3448 
3449       if (newtime - prevtime < 0) {
3450         // time moving backwards, should only happen if no monotonic clock
3451         // not a guarantee() because JVM should not abort on kernel/glibc bugs
3452         assert(!Linux::supports_monotonic_clock(), "time moving backwards");
3453       } else {
3454         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
3455       }
3456 
3457       if(millis <= 0) {
3458         return OS_OK;
3459       }
3460 
3461       prevtime = newtime;
3462 
3463       {
3464         assert(thread->is_Java_thread(), "sanity check");
3465         JavaThread *jt = (JavaThread *) thread;
3466         ThreadBlockInVM tbivm(jt);
3467         OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
3468 
3469         jt->set_suspend_equivalent();
3470         // cleared by handle_special_suspend_equivalent_condition() or
3471         // java_suspend_self() via check_and_wait_while_suspended()
3472 
3473         slp->park(millis);
3474 
3475         // were we externally suspended while we were waiting?
3476         jt->check_and_wait_while_suspended();
3477       }
3478     }
3479   } else {
3480     OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
3481     jlong prevtime = javaTimeNanos();
3482 
3483     for (;;) {
3484       // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
3485       // the 1st iteration ...
3486       jlong newtime = javaTimeNanos();
3487 
3488       if (newtime - prevtime < 0) {
3489         // time moving backwards, should only happen if no monotonic clock
3490         // not a guarantee() because JVM should not abort on kernel/glibc bugs
3491         assert(!Linux::supports_monotonic_clock(), "time moving backwards");
3492       } else {
3493         millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
3494       }
3495 
3496       if(millis <= 0) break ;
3497 
3498       prevtime = newtime;
3499       slp->park(millis);
3500     }
3501     return OS_OK ;
3502   }
3503 }
3504 
3505 int os::naked_sleep() {
3506   // %% make the sleep time an integer flag. for now use 1 millisec.
3507   return os::sleep(Thread::current(), 1, false);
3508 }
3509 
3510 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
3511 void os::infinite_sleep() {
3512   while (true) {    // sleep forever ...
3513     ::sleep(100);   // ... 100 seconds at a time
3514   }
3515 }
3516 
3517 // Used to convert frequent JVM_Yield() to nops
3518 bool os::dont_yield() {
3519   return DontYieldALot;
3520 }
3521 
3522 void os::yield() {
3523   sched_yield();
3524 }
3525 
3526 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
3527 
3528 void os::yield_all(int attempts) {
3529   // Yields to all threads, including threads with lower priorities
3530   // Threads on Linux are all with same priority. The Solaris style
3531   // os::yield_all() with nanosleep(1ms) is not necessary.
3532   sched_yield();
3533 }
3534 
3535 // Called from the tight loops to possibly influence time-sharing heuristics
3536 void os::loop_breaker(int attempts) {
3537   os::yield_all(attempts);
3538 }
3539 
3540 ////////////////////////////////////////////////////////////////////////////////
3541 // thread priority support
3542 
3543 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
3544 // only supports dynamic priority, static priority must be zero. For real-time
3545 // applications, Linux supports SCHED_RR which allows static priority (1-99).
3546 // However, for large multi-threaded applications, SCHED_RR is not only slower
3547 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
3548 // of 5 runs - Sep 2005).
3549 //
3550 // The following code actually changes the niceness of kernel-thread/LWP. It
3551 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
3552 // not the entire user process, and user level threads are 1:1 mapped to kernel
3553 // threads. It has always been the case, but could change in the future. For
3554 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
3555 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
3556 
3557 int os::java_to_os_priority[CriticalPriority + 1] = {
3558   19,              // 0 Entry should never be used
3559 
3560    4,              // 1 MinPriority
3561    3,              // 2
3562    2,              // 3
3563 
3564    1,              // 4
3565    0,              // 5 NormPriority
3566   -1,              // 6
3567 
3568   -2,              // 7
3569   -3,              // 8
3570   -4,              // 9 NearMaxPriority
3571 
3572   -5,              // 10 MaxPriority
3573 
3574   -5               // 11 CriticalPriority
3575 };
3576 
3577 static int prio_init() {
3578   if (ThreadPriorityPolicy == 1) {
3579     // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
3580     // if effective uid is not root. Perhaps, a more elegant way of doing
3581     // this is to test CAP_SYS_NICE capability, but that will require libcap.so
3582     if (geteuid() != 0) {
3583       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
3584         warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
3585       }
3586       ThreadPriorityPolicy = 0;
3587     }
3588   }
3589   if (UseCriticalJavaThreadPriority) {
3590     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
3591   }
3592   return 0;
3593 }
3594 
3595 OSReturn os::set_native_priority(Thread* thread, int newpri) {
3596   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
3597 
3598   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
3599   return (ret == 0) ? OS_OK : OS_ERR;
3600 }
3601 
3602 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
3603   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
3604     *priority_ptr = java_to_os_priority[NormPriority];
3605     return OS_OK;
3606   }
3607 
3608   errno = 0;
3609   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
3610   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
3611 }
3612 
3613 // Hint to the underlying OS that a task switch would not be good.
3614 // Void return because it's a hint and can fail.
3615 void os::hint_no_preempt() {}
3616 
3617 ////////////////////////////////////////////////////////////////////////////////
3618 // suspend/resume support
3619 
3620 //  the low-level signal-based suspend/resume support is a remnant from the
3621 //  old VM-suspension that used to be for java-suspension, safepoints etc,
3622 //  within hotspot. Now there is a single use-case for this:
3623 //    - calling get_thread_pc() on the VMThread by the flat-profiler task
3624 //      that runs in the watcher thread.
3625 //  The remaining code is greatly simplified from the more general suspension
3626 //  code that used to be used.
3627 //
3628 //  The protocol is quite simple:
3629 //  - suspend:
3630 //      - sends a signal to the target thread
3631 //      - polls the suspend state of the osthread using a yield loop
3632 //      - target thread signal handler (SR_handler) sets suspend state
3633 //        and blocks in sigsuspend until continued
3634 //  - resume:
3635 //      - sets target osthread state to continue
3636 //      - sends signal to end the sigsuspend loop in the SR_handler
3637 //
3638 //  Note that the SR_lock plays no role in this suspend/resume protocol.
3639 //
3640 
3641 static void resume_clear_context(OSThread *osthread) {
3642   osthread->set_ucontext(NULL);
3643   osthread->set_siginfo(NULL);
3644 }
3645 
3646 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
3647   osthread->set_ucontext(context);
3648   osthread->set_siginfo(siginfo);
3649 }
3650 
3651 //
3652 // Handler function invoked when a thread's execution is suspended or
3653 // resumed. We have to be careful that only async-safe functions are
3654 // called here (Note: most pthread functions are not async safe and
3655 // should be avoided.)
3656 //
3657 // Note: sigwait() is a more natural fit than sigsuspend() from an
3658 // interface point of view, but sigwait() prevents the signal hander
3659 // from being run. libpthread would get very confused by not having
3660 // its signal handlers run and prevents sigwait()'s use with the
3661 // mutex granting granting signal.
3662 //
3663 // Currently only ever called on the VMThread and JavaThreads (PC sampling)
3664 //
3665 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
3666   // Save and restore errno to avoid confusing native code with EINTR
3667   // after sigsuspend.
3668   int old_errno = errno;
3669 
3670   Thread* thread = Thread::current();
3671   OSThread* osthread = thread->osthread();
3672   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3673 
3674   os::SuspendResume::State current = osthread->sr.state();
3675   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3676     suspend_save_context(osthread, siginfo, context);
3677 
3678     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3679     os::SuspendResume::State state = osthread->sr.suspended();
3680     if (state == os::SuspendResume::SR_SUSPENDED) {
3681       sigset_t suspend_set;  // signals for sigsuspend()
3682 
3683       // get current set of blocked signals and unblock resume signal
3684       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3685       sigdelset(&suspend_set, SR_signum);
3686 
3687       sr_semaphore.signal();
3688       // wait here until we are resumed
3689       while (1) {
3690         sigsuspend(&suspend_set);
3691 
3692         os::SuspendResume::State result = osthread->sr.running();
3693         if (result == os::SuspendResume::SR_RUNNING) {
3694           sr_semaphore.signal();
3695           break;
3696         }
3697       }
3698 
3699     } else if (state == os::SuspendResume::SR_RUNNING) {
3700       // request was cancelled, continue
3701     } else {
3702       ShouldNotReachHere();
3703     }
3704 
3705     resume_clear_context(osthread);
3706   } else if (current == os::SuspendResume::SR_RUNNING) {
3707     // request was cancelled, continue
3708   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3709     // ignore
3710   } else {
3711     // ignore
3712   }
3713 
3714   errno = old_errno;
3715 }
3716 
3717 
3718 static int SR_initialize() {
3719   struct sigaction act;
3720   char *s;
3721   /* Get signal number to use for suspend/resume */
3722   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
3723     int sig = ::strtol(s, 0, 10);
3724     if (sig > 0 || sig < _NSIG) {
3725         SR_signum = sig;
3726     }
3727   }
3728 
3729   assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
3730         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
3731 
3732   sigemptyset(&SR_sigset);
3733   sigaddset(&SR_sigset, SR_signum);
3734 
3735   /* Set up signal handler for suspend/resume */
3736   act.sa_flags = SA_RESTART|SA_SIGINFO;
3737   act.sa_handler = (void (*)(int)) SR_handler;
3738 
3739   // SR_signum is blocked by default.
3740   // 4528190 - We also need to block pthread restart signal (32 on all
3741   // supported Linux platforms). Note that LinuxThreads need to block
3742   // this signal for all threads to work properly. So we don't have
3743   // to use hard-coded signal number when setting up the mask.
3744   pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
3745 
3746   if (sigaction(SR_signum, &act, 0) == -1) {
3747     return -1;
3748   }
3749 
3750   // Save signal flag
3751   os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
3752   return 0;
3753 }
3754 
3755 static int SR_finalize() {
3756   return 0;
3757 }
3758 
3759 static int sr_notify(OSThread* osthread) {
3760   int status = pthread_kill(osthread->pthread_id(), SR_signum);
3761   assert_status(status == 0, status, "pthread_kill");
3762   return status;
3763 }
3764 
3765 // "Randomly" selected value for how long we want to spin
3766 // before bailing out on suspending a thread, also how often
3767 // we send a signal to a thread we want to resume
3768 static const int RANDOMLY_LARGE_INTEGER = 1000000;
3769 static const int RANDOMLY_LARGE_INTEGER2 = 100;
3770 
3771 // returns true on success and false on error - really an error is fatal
3772 // but this seems the normal response to library errors
3773 static bool do_suspend(OSThread* osthread) {
3774   assert(osthread->sr.is_running(), "thread should be running");
3775   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3776 
3777   // mark as suspended and send signal
3778   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3779     // failed to switch, state wasn't running?
3780     ShouldNotReachHere();
3781     return false;
3782   }
3783 
3784   if (sr_notify(osthread) != 0) {
3785     ShouldNotReachHere();
3786   }
3787 
3788   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3789   while (true) {
3790     if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3791       break;
3792     } else {
3793       // timeout
3794       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3795       if (cancelled == os::SuspendResume::SR_RUNNING) {
3796         return false;
3797       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3798         // make sure that we consume the signal on the semaphore as well
3799         sr_semaphore.wait();
3800         break;
3801       } else {
3802         ShouldNotReachHere();
3803         return false;
3804       }
3805     }
3806   }
3807 
3808   guarantee(osthread->sr.is_suspended(), "Must be suspended");
3809   return true;
3810 }
3811 
3812 static void do_resume(OSThread* osthread) {
3813   assert(osthread->sr.is_suspended(), "thread should be suspended");
3814   assert(!sr_semaphore.trywait(), "invalid semaphore state");
3815 
3816   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3817     // failed to switch to WAKEUP_REQUEST
3818     ShouldNotReachHere();
3819     return;
3820   }
3821 
3822   while (true) {
3823     if (sr_notify(osthread) == 0) {
3824       if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3825         if (osthread->sr.is_running()) {
3826           return;
3827         }
3828       }
3829     } else {
3830       ShouldNotReachHere();
3831     }
3832   }
3833 
3834   guarantee(osthread->sr.is_running(), "Must be running!");
3835 }
3836 
3837 ////////////////////////////////////////////////////////////////////////////////
3838 // interrupt support
3839 
3840 void os::interrupt(Thread* thread) {
3841   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3842     "possibility of dangling Thread pointer");
3843 
3844   OSThread* osthread = thread->osthread();
3845 
3846   if (!osthread->interrupted()) {
3847     osthread->set_interrupted(true);
3848     // More than one thread can get here with the same value of osthread,
3849     // resulting in multiple notifications.  We do, however, want the store
3850     // to interrupted() to be visible to other threads before we execute unpark().
3851     OrderAccess::fence();
3852     ParkEvent * const slp = thread->_SleepEvent ;
3853     if (slp != NULL) slp->unpark() ;
3854   }
3855 
3856   // For JSR166. Unpark even if interrupt status already was set
3857   if (thread->is_Java_thread())
3858     ((JavaThread*)thread)->parker()->unpark();
3859 
3860   ParkEvent * ev = thread->_ParkEvent ;
3861   if (ev != NULL) ev->unpark() ;
3862 
3863 }
3864 
3865 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
3866   assert(Thread::current() == thread || Threads_lock->owned_by_self(),
3867     "possibility of dangling Thread pointer");
3868 
3869   OSThread* osthread = thread->osthread();
3870 
3871   bool interrupted = osthread->interrupted();
3872 
3873   if (interrupted && clear_interrupted) {
3874     osthread->set_interrupted(false);
3875     // consider thread->_SleepEvent->reset() ... optional optimization
3876   }
3877 
3878   return interrupted;
3879 }
3880 
3881 ///////////////////////////////////////////////////////////////////////////////////
3882 // signal handling (except suspend/resume)
3883 
3884 // This routine may be used by user applications as a "hook" to catch signals.
3885 // The user-defined signal handler must pass unrecognized signals to this
3886 // routine, and if it returns true (non-zero), then the signal handler must
3887 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
3888 // routine will never retun false (zero), but instead will execute a VM panic
3889 // routine kill the process.
3890 //
3891 // If this routine returns false, it is OK to call it again.  This allows
3892 // the user-defined signal handler to perform checks either before or after
3893 // the VM performs its own checks.  Naturally, the user code would be making
3894 // a serious error if it tried to handle an exception (such as a null check
3895 // or breakpoint) that the VM was generating for its own correct operation.
3896 //
3897 // This routine may recognize any of the following kinds of signals:
3898 //    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
3899 // It should be consulted by handlers for any of those signals.
3900 //
3901 // The caller of this routine must pass in the three arguments supplied
3902 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3903 // field of the structure passed to sigaction().  This routine assumes that
3904 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3905 //
3906 // Note that the VM will print warnings if it detects conflicting signal
3907 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3908 //
3909 extern "C" JNIEXPORT int
3910 JVM_handle_linux_signal(int signo, siginfo_t* siginfo,
3911                         void* ucontext, int abort_if_unrecognized);
3912 
3913 void signalHandler(int sig, siginfo_t* info, void* uc) {
3914   assert(info != NULL && uc != NULL, "it must be old kernel");
3915   JVM_handle_linux_signal(sig, info, uc, true);
3916 }
3917 
3918 
3919 // This boolean allows users to forward their own non-matching signals
3920 // to JVM_handle_linux_signal, harmlessly.
3921 bool os::Linux::signal_handlers_are_installed = false;
3922 
3923 // For signal-chaining
3924 struct sigaction os::Linux::sigact[MAXSIGNUM];
3925 unsigned int os::Linux::sigs = 0;
3926 bool os::Linux::libjsig_is_loaded = false;
3927 typedef struct sigaction *(*get_signal_t)(int);
3928 get_signal_t os::Linux::get_signal_action = NULL;
3929 
3930 struct sigaction* os::Linux::get_chained_signal_action(int sig) {
3931   struct sigaction *actp = NULL;
3932 
3933   if (libjsig_is_loaded) {
3934     // Retrieve the old signal handler from libjsig
3935     actp = (*get_signal_action)(sig);
3936   }
3937   if (actp == NULL) {
3938     // Retrieve the preinstalled signal handler from jvm
3939     actp = get_preinstalled_handler(sig);
3940   }
3941 
3942   return actp;
3943 }
3944 
3945 static bool call_chained_handler(struct sigaction *actp, int sig,
3946                                  siginfo_t *siginfo, void *context) {
3947   // Call the old signal handler
3948   if (actp->sa_handler == SIG_DFL) {
3949     // It's more reasonable to let jvm treat it as an unexpected exception
3950     // instead of taking the default action.
3951     return false;
3952   } else if (actp->sa_handler != SIG_IGN) {
3953     if ((actp->sa_flags & SA_NODEFER) == 0) {
3954       // automaticlly block the signal
3955       sigaddset(&(actp->sa_mask), sig);
3956     }
3957 
3958     sa_handler_t hand;
3959     sa_sigaction_t sa;
3960     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3961     // retrieve the chained handler
3962     if (siginfo_flag_set) {
3963       sa = actp->sa_sigaction;
3964     } else {
3965       hand = actp->sa_handler;
3966     }
3967 
3968     if ((actp->sa_flags & SA_RESETHAND) != 0) {
3969       actp->sa_handler = SIG_DFL;
3970     }
3971 
3972     // try to honor the signal mask
3973     sigset_t oset;
3974     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3975 
3976     // call into the chained handler
3977     if (siginfo_flag_set) {
3978       (*sa)(sig, siginfo, context);
3979     } else {
3980       (*hand)(sig);
3981     }
3982 
3983     // restore the signal mask
3984     pthread_sigmask(SIG_SETMASK, &oset, 0);
3985   }
3986   // Tell jvm's signal handler the signal is taken care of.
3987   return true;
3988 }
3989 
3990 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3991   bool chained = false;
3992   // signal-chaining
3993   if (UseSignalChaining) {
3994     struct sigaction *actp = get_chained_signal_action(sig);
3995     if (actp != NULL) {
3996       chained = call_chained_handler(actp, sig, siginfo, context);
3997     }
3998   }
3999   return chained;
4000 }
4001 
4002 struct sigaction* os::Linux::get_preinstalled_handler(int sig) {
4003   if ((( (unsigned int)1 << sig ) & sigs) != 0) {
4004     return &sigact[sig];
4005   }
4006   return NULL;
4007 }
4008 
4009 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4010   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4011   sigact[sig] = oldAct;
4012   sigs |= (unsigned int)1 << sig;
4013 }
4014 
4015 // for diagnostic
4016 int os::Linux::sigflags[MAXSIGNUM];
4017 
4018 int os::Linux::get_our_sigflags(int sig) {
4019   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4020   return sigflags[sig];
4021 }
4022 
4023 void os::Linux::set_our_sigflags(int sig, int flags) {
4024   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4025   sigflags[sig] = flags;
4026 }
4027 
4028 void os::Linux::set_signal_handler(int sig, bool set_installed) {
4029   // Check for overwrite.
4030   struct sigaction oldAct;
4031   sigaction(sig, (struct sigaction*)NULL, &oldAct);
4032 
4033   void* oldhand = oldAct.sa_sigaction
4034                 ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
4035                 : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
4036   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4037       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4038       oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
4039     if (AllowUserSignalHandlers || !set_installed) {
4040       // Do not overwrite; user takes responsibility to forward to us.
4041       return;
4042     } else if (UseSignalChaining) {
4043       // save the old handler in jvm
4044       save_preinstalled_handler(sig, oldAct);
4045       // libjsig also interposes the sigaction() call below and saves the
4046       // old sigaction on it own.
4047     } else {
4048       fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
4049                     "%#lx for signal %d.", (long)oldhand, sig));
4050     }
4051   }
4052 
4053   struct sigaction sigAct;
4054   sigfillset(&(sigAct.sa_mask));
4055   sigAct.sa_handler = SIG_DFL;
4056   if (!set_installed) {
4057     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4058   } else {
4059     sigAct.sa_sigaction = signalHandler;
4060     sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4061   }
4062   // Save flags, which are set by ours
4063   assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4064   sigflags[sig] = sigAct.sa_flags;
4065 
4066   int ret = sigaction(sig, &sigAct, &oldAct);
4067   assert(ret == 0, "check");
4068 
4069   void* oldhand2  = oldAct.sa_sigaction
4070                   ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4071                   : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4072   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4073 }
4074 
4075 // install signal handlers for signals that HotSpot needs to
4076 // handle in order to support Java-level exception handling.
4077 
4078 void os::Linux::install_signal_handlers() {
4079   if (!signal_handlers_are_installed) {
4080     signal_handlers_are_installed = true;
4081 
4082     // signal-chaining
4083     typedef void (*signal_setting_t)();
4084     signal_setting_t begin_signal_setting = NULL;
4085     signal_setting_t end_signal_setting = NULL;
4086     begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4087                              dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4088     if (begin_signal_setting != NULL) {
4089       end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4090                              dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4091       get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4092                             dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4093       libjsig_is_loaded = true;
4094       assert(UseSignalChaining, "should enable signal-chaining");
4095     }
4096     if (libjsig_is_loaded) {
4097       // Tell libjsig jvm is setting signal handlers
4098       (*begin_signal_setting)();
4099     }
4100 
4101     set_signal_handler(SIGSEGV, true);
4102     set_signal_handler(SIGPIPE, true);
4103     set_signal_handler(SIGBUS, true);
4104     set_signal_handler(SIGILL, true);
4105     set_signal_handler(SIGFPE, true);
4106     set_signal_handler(SIGXFSZ, true);
4107 
4108     if (libjsig_is_loaded) {
4109       // Tell libjsig jvm finishes setting signal handlers
4110       (*end_signal_setting)();
4111     }
4112 
4113     // We don't activate signal checker if libjsig is in place, we trust ourselves
4114     // and if UserSignalHandler is installed all bets are off.
4115     // Log that signal checking is off only if -verbose:jni is specified.
4116     if (CheckJNICalls) {
4117       if (libjsig_is_loaded) {
4118         if (PrintJNIResolving) {
4119           tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4120         }
4121         check_signals = false;
4122       }
4123       if (AllowUserSignalHandlers) {
4124         if (PrintJNIResolving) {
4125           tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4126         }
4127         check_signals = false;
4128       }
4129     }
4130   }
4131 }
4132 
4133 // This is the fastest way to get thread cpu time on Linux.
4134 // Returns cpu time (user+sys) for any thread, not only for current.
4135 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
4136 // It might work on 2.6.10+ with a special kernel/glibc patch.
4137 // For reference, please, see IEEE Std 1003.1-2004:
4138 //   http://www.unix.org/single_unix_specification
4139 
4140 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4141   struct timespec tp;
4142   int rc = os::Linux::clock_gettime(clockid, &tp);
4143   assert(rc == 0, "clock_gettime is expected to return 0 code");
4144 
4145   return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4146 }
4147 
4148 /////
4149 // glibc on Linux platform uses non-documented flag
4150 // to indicate, that some special sort of signal
4151 // trampoline is used.
4152 // We will never set this flag, and we should
4153 // ignore this flag in our diagnostic
4154 #ifdef SIGNIFICANT_SIGNAL_MASK
4155 #undef SIGNIFICANT_SIGNAL_MASK
4156 #endif
4157 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
4158 
4159 static const char* get_signal_handler_name(address handler,
4160                                            char* buf, int buflen) {
4161   int offset;
4162   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
4163   if (found) {
4164     // skip directory names
4165     const char *p1, *p2;
4166     p1 = buf;
4167     size_t len = strlen(os::file_separator());
4168     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
4169     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
4170   } else {
4171     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
4172   }
4173   return buf;
4174 }
4175 
4176 static void print_signal_handler(outputStream* st, int sig,
4177                                  char* buf, size_t buflen) {
4178   struct sigaction sa;
4179 
4180   sigaction(sig, NULL, &sa);
4181 
4182   // See comment for SIGNIFICANT_SIGNAL_MASK define
4183   sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4184 
4185   st->print("%s: ", os::exception_name(sig, buf, buflen));
4186 
4187   address handler = (sa.sa_flags & SA_SIGINFO)
4188     ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
4189     : CAST_FROM_FN_PTR(address, sa.sa_handler);
4190 
4191   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
4192     st->print("SIG_DFL");
4193   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
4194     st->print("SIG_IGN");
4195   } else {
4196     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
4197   }
4198 
4199   st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask);
4200 
4201   address rh = VMError::get_resetted_sighandler(sig);
4202   // May be, handler was resetted by VMError?
4203   if(rh != NULL) {
4204     handler = rh;
4205     sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
4206   }
4207 
4208   st->print(", sa_flags="   PTR32_FORMAT, sa.sa_flags);
4209 
4210   // Check: is it our handler?
4211   if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
4212      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
4213     // It is our signal handler
4214     // check for flags, reset system-used one!
4215     if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
4216       st->print(
4217                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
4218                 os::Linux::get_our_sigflags(sig));
4219     }
4220   }
4221   st->cr();
4222 }
4223 
4224 
4225 #define DO_SIGNAL_CHECK(sig) \
4226   if (!sigismember(&check_signal_done, sig)) \
4227     os::Linux::check_signal_handler(sig)
4228 
4229 // This method is a periodic task to check for misbehaving JNI applications
4230 // under CheckJNI, we can add any periodic checks here
4231 
4232 void os::run_periodic_checks() {
4233 
4234   if (check_signals == false) return;
4235 
4236   // SEGV and BUS if overridden could potentially prevent
4237   // generation of hs*.log in the event of a crash, debugging
4238   // such a case can be very challenging, so we absolutely
4239   // check the following for a good measure:
4240   DO_SIGNAL_CHECK(SIGSEGV);
4241   DO_SIGNAL_CHECK(SIGILL);
4242   DO_SIGNAL_CHECK(SIGFPE);
4243   DO_SIGNAL_CHECK(SIGBUS);
4244   DO_SIGNAL_CHECK(SIGPIPE);
4245   DO_SIGNAL_CHECK(SIGXFSZ);
4246 
4247 
4248   // ReduceSignalUsage allows the user to override these handlers
4249   // see comments at the very top and jvm_solaris.h
4250   if (!ReduceSignalUsage) {
4251     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4252     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4253     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4254     DO_SIGNAL_CHECK(BREAK_SIGNAL);
4255   }
4256 
4257   DO_SIGNAL_CHECK(SR_signum);
4258   DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
4259 }
4260 
4261 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4262 
4263 static os_sigaction_t os_sigaction = NULL;
4264 
4265 void os::Linux::check_signal_handler(int sig) {
4266   char buf[O_BUFLEN];
4267   address jvmHandler = NULL;
4268 
4269 
4270   struct sigaction act;
4271   if (os_sigaction == NULL) {
4272     // only trust the default sigaction, in case it has been interposed
4273     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4274     if (os_sigaction == NULL) return;
4275   }
4276 
4277   os_sigaction(sig, (struct sigaction*)NULL, &act);
4278 
4279 
4280   act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4281 
4282   address thisHandler = (act.sa_flags & SA_SIGINFO)
4283     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4284     : CAST_FROM_FN_PTR(address, act.sa_handler) ;
4285 
4286 
4287   switch(sig) {
4288   case SIGSEGV:
4289   case SIGBUS:
4290   case SIGFPE:
4291   case SIGPIPE:
4292   case SIGILL:
4293   case SIGXFSZ:
4294     jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
4295     break;
4296 
4297   case SHUTDOWN1_SIGNAL:
4298   case SHUTDOWN2_SIGNAL:
4299   case SHUTDOWN3_SIGNAL:
4300   case BREAK_SIGNAL:
4301     jvmHandler = (address)user_handler();
4302     break;
4303 
4304   case INTERRUPT_SIGNAL:
4305     jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
4306     break;
4307 
4308   default:
4309     if (sig == SR_signum) {
4310       jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
4311     } else {
4312       return;
4313     }
4314     break;
4315   }
4316 
4317   if (thisHandler != jvmHandler) {
4318     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4319     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4320     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4321     // No need to check this sig any longer
4322     sigaddset(&check_signal_done, sig);
4323   } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
4324     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4325     tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
4326     tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
4327     // No need to check this sig any longer
4328     sigaddset(&check_signal_done, sig);
4329   }
4330 
4331   // Dump all the signal
4332   if (sigismember(&check_signal_done, sig)) {
4333     print_signal_handlers(tty, buf, O_BUFLEN);
4334   }
4335 }
4336 
4337 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
4338 
4339 extern bool signal_name(int signo, char* buf, size_t len);
4340 
4341 const char* os::exception_name(int exception_code, char* buf, size_t size) {
4342   if (0 < exception_code && exception_code <= SIGRTMAX) {
4343     // signal
4344     if (!signal_name(exception_code, buf, size)) {
4345       jio_snprintf(buf, size, "SIG%d", exception_code);
4346     }
4347     return buf;
4348   } else {
4349     return NULL;
4350   }
4351 }
4352 
4353 // this is called _before_ the most of global arguments have been parsed
4354 void os::init(void) {
4355   char dummy;   /* used to get a guess on initial stack address */
4356 //  first_hrtime = gethrtime();
4357 
4358   // With LinuxThreads the JavaMain thread pid (primordial thread)
4359   // is different than the pid of the java launcher thread.
4360   // So, on Linux, the launcher thread pid is passed to the VM
4361   // via the sun.java.launcher.pid property.
4362   // Use this property instead of getpid() if it was correctly passed.
4363   // See bug 6351349.
4364   pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
4365 
4366   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
4367 
4368   clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4369 
4370   init_random(1234567);
4371 
4372   ThreadCritical::initialize();
4373 
4374   Linux::set_page_size(sysconf(_SC_PAGESIZE));
4375   if (Linux::page_size() == -1) {
4376     fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)",
4377                   strerror(errno)));
4378   }
4379   init_page_sizes((size_t) Linux::page_size());
4380 
4381   Linux::initialize_system_info();
4382 
4383   // main_thread points to the aboriginal thread
4384   Linux::_main_thread = pthread_self();
4385 
4386   Linux::clock_init();
4387   initial_time_count = os::elapsed_counter();
4388   pthread_mutex_init(&dl_mutex, NULL);
4389 
4390   // If the pagesize of the VM is greater than 8K determine the appropriate
4391   // number of initial guard pages.  The user can change this with the
4392   // command line arguments, if needed.
4393   if (vm_page_size() > (int)Linux::vm_default_page_size()) {
4394     StackYellowPages = 1;
4395     StackRedPages = 1;
4396     StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
4397   }
4398 }
4399 
4400 // To install functions for atexit system call
4401 extern "C" {
4402   static void perfMemory_exit_helper() {
4403     perfMemory_exit();
4404   }
4405 }
4406 
4407 // this is called _after_ the global arguments have been parsed
4408 jint os::init_2(void)
4409 {
4410   Linux::fast_thread_clock_init();
4411 
4412   // Allocate a single page and mark it as readable for safepoint polling
4413   address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4414   guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
4415 
4416   os::set_polling_page( polling_page );
4417 
4418 #ifndef PRODUCT
4419   if(Verbose && PrintMiscellaneous)
4420     tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
4421 #endif
4422 
4423   if (!UseMembar) {
4424     address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4425     guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
4426     os::set_memory_serialize_page( mem_serialize_page );
4427 
4428 #ifndef PRODUCT
4429     if(Verbose && PrintMiscellaneous)
4430       tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
4431 #endif
4432   }
4433 
4434   os::large_page_init();
4435 
4436   // initialize suspend/resume support - must do this before signal_sets_init()
4437   if (SR_initialize() != 0) {
4438     perror("SR_initialize failed");
4439     return JNI_ERR;
4440   }
4441 
4442   Linux::signal_sets_init();
4443   Linux::install_signal_handlers();
4444 
4445   // Check minimum allowable stack size for thread creation and to initialize
4446   // the java system classes, including StackOverflowError - depends on page
4447   // size.  Add a page for compiler2 recursion in main thread.
4448   // Add in 2*BytesPerWord times page size to account for VM stack during
4449   // class initialization depending on 32 or 64 bit VM.
4450   os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
4451             (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
4452                     (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
4453 
4454   size_t threadStackSizeInBytes = ThreadStackSize * K;
4455   if (threadStackSizeInBytes != 0 &&
4456       threadStackSizeInBytes < os::Linux::min_stack_allowed) {
4457         tty->print_cr("\nThe stack size specified is too small, "
4458                       "Specify at least %dk",
4459                       os::Linux::min_stack_allowed/ K);
4460         return JNI_ERR;
4461   }
4462 
4463   // Make the stack size a multiple of the page size so that
4464   // the yellow/red zones can be guarded.
4465   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4466         vm_page_size()));
4467 
4468   Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4469 
4470   Linux::libpthread_init();
4471   if (PrintMiscellaneous && (Verbose || WizardMode)) {
4472      tty->print_cr("[HotSpot is running with %s, %s(%s)]\n",
4473           Linux::glibc_version(), Linux::libpthread_version(),
4474           Linux::is_floating_stack() ? "floating stack" : "fixed stack");
4475   }
4476 
4477   if (UseNUMA) {
4478     if (!Linux::libnuma_init()) {
4479       UseNUMA = false;
4480     } else {
4481       if ((Linux::numa_max_node() < 1)) {
4482         // There's only one node(they start from 0), disable NUMA.
4483         UseNUMA = false;
4484       }
4485     }
4486     // With SHM large pages we cannot uncommit a page, so there's not way
4487     // we can make the adaptive lgrp chunk resizing work. If the user specified
4488     // both UseNUMA and UseLargePages (or UseSHM) on the command line - warn and
4489     // disable adaptive resizing.
4490     if (UseNUMA && UseLargePages && UseSHM) {
4491       if (!FLAG_IS_DEFAULT(UseNUMA)) {
4492         if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseSHM)) {
4493           UseLargePages = false;
4494         } else {
4495           warning("UseNUMA is not fully compatible with SHM large pages, disabling adaptive resizing");
4496           UseAdaptiveSizePolicy = false;
4497           UseAdaptiveNUMAChunkSizing = false;
4498         }
4499       } else {
4500         UseNUMA = false;
4501       }
4502     }
4503     if (!UseNUMA && ForceNUMA) {
4504       UseNUMA = true;
4505     }
4506   }
4507 
4508   if (MaxFDLimit) {
4509     // set the number of file descriptors to max. print out error
4510     // if getrlimit/setrlimit fails but continue regardless.
4511     struct rlimit nbr_files;
4512     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4513     if (status != 0) {
4514       if (PrintMiscellaneous && (Verbose || WizardMode))
4515         perror("os::init_2 getrlimit failed");
4516     } else {
4517       nbr_files.rlim_cur = nbr_files.rlim_max;
4518       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4519       if (status != 0) {
4520         if (PrintMiscellaneous && (Verbose || WizardMode))
4521           perror("os::init_2 setrlimit failed");
4522       }
4523     }
4524   }
4525 
4526   // Initialize lock used to serialize thread creation (see os::create_thread)
4527   Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
4528 
4529   // at-exit methods are called in the reverse order of their registration.
4530   // atexit functions are called on return from main or as a result of a
4531   // call to exit(3C). There can be only 32 of these functions registered
4532   // and atexit() does not set errno.
4533 
4534   if (PerfAllowAtExitRegistration) {
4535     // only register atexit functions if PerfAllowAtExitRegistration is set.
4536     // atexit functions can be delayed until process exit time, which
4537     // can be problematic for embedded VM situations. Embedded VMs should
4538     // call DestroyJavaVM() to assure that VM resources are released.
4539 
4540     // note: perfMemory_exit_helper atexit function may be removed in
4541     // the future if the appropriate cleanup code can be added to the
4542     // VM_Exit VMOperation's doit method.
4543     if (atexit(perfMemory_exit_helper) != 0) {
4544       warning("os::init2 atexit(perfMemory_exit_helper) failed");
4545     }
4546   }
4547 
4548   // initialize thread priority policy
4549   prio_init();
4550 
4551   return JNI_OK;
4552 }
4553 
4554 // this is called at the end of vm_initialization
4555 void os::init_3(void)
4556 {
4557 #ifdef JAVASE_EMBEDDED
4558   // Start the MemNotifyThread
4559   if (LowMemoryProtection) {
4560     MemNotifyThread::start();
4561   }
4562   return;
4563 #endif
4564 }
4565 
4566 // Mark the polling page as unreadable
4567 void os::make_polling_page_unreadable(void) {
4568   if( !guard_memory((char*)_polling_page, Linux::page_size()) )
4569     fatal("Could not disable polling page");
4570 };
4571 
4572 // Mark the polling page as readable
4573 void os::make_polling_page_readable(void) {
4574   if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
4575     fatal("Could not enable polling page");
4576   }
4577 };
4578 
4579 int os::active_processor_count() {
4580   // Linux doesn't yet have a (official) notion of processor sets,
4581   // so just return the number of online processors.
4582   int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4583   assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
4584   return online_cpus;
4585 }
4586 
4587 void os::set_native_thread_name(const char *name) {
4588   // Not yet implemented.
4589   return;
4590 }
4591 
4592 bool os::distribute_processes(uint length, uint* distribution) {
4593   // Not yet implemented.
4594   return false;
4595 }
4596 
4597 bool os::bind_to_processor(uint processor_id) {
4598   // Not yet implemented.
4599   return false;
4600 }
4601 
4602 ///
4603 
4604 void os::SuspendedThreadTask::internal_do_task() {
4605   if (do_suspend(_thread->osthread())) {
4606     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
4607     do_task(context);
4608     do_resume(_thread->osthread());
4609   }
4610 }
4611 
4612 class PcFetcher : public os::SuspendedThreadTask {
4613 public:
4614   PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
4615   ExtendedPC result();
4616 protected:
4617   void do_task(const os::SuspendedThreadTaskContext& context);
4618 private:
4619   ExtendedPC _epc;
4620 };
4621 
4622 ExtendedPC PcFetcher::result() {
4623   guarantee(is_done(), "task is not done yet.");
4624   return _epc;
4625 }
4626 
4627 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
4628   Thread* thread = context.thread();
4629   OSThread* osthread = thread->osthread();
4630   if (osthread->ucontext() != NULL) {
4631     _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
4632   } else {
4633     // NULL context is unexpected, double-check this is the VMThread
4634     guarantee(thread->is_VM_thread(), "can only be called for VMThread");
4635   }
4636 }
4637 
4638 // Suspends the target using the signal mechanism and then grabs the PC before
4639 // resuming the target. Used by the flat-profiler only
4640 ExtendedPC os::get_thread_pc(Thread* thread) {
4641   // Make sure that it is called by the watcher for the VMThread
4642   assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
4643   assert(thread->is_VM_thread(), "Can only be called for VMThread");
4644 
4645   PcFetcher fetcher(thread);
4646   fetcher.run();
4647   return fetcher.result();
4648 }
4649 
4650 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
4651 {
4652    if (is_NPTL()) {
4653       return pthread_cond_timedwait(_cond, _mutex, _abstime);
4654    } else {
4655 #ifndef IA64
4656       // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
4657       // word back to default 64bit precision if condvar is signaled. Java
4658       // wants 53bit precision.  Save and restore current value.
4659       int fpu = get_fpu_control_word();
4660 #endif // IA64
4661       int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
4662 #ifndef IA64
4663       set_fpu_control_word(fpu);
4664 #endif // IA64
4665       return status;
4666    }
4667 }
4668 
4669 ////////////////////////////////////////////////////////////////////////////////
4670 // debug support
4671 
4672 static address same_page(address x, address y) {
4673   int page_bits = -os::vm_page_size();
4674   if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
4675     return x;
4676   else if (x > y)
4677     return (address)(intptr_t(y) | ~page_bits) + 1;
4678   else
4679     return (address)(intptr_t(y) & page_bits);
4680 }
4681 
4682 bool os::find(address addr, outputStream* st) {
4683   Dl_info dlinfo;
4684   memset(&dlinfo, 0, sizeof(dlinfo));
4685   if (dladdr(addr, &dlinfo)) {
4686     st->print(PTR_FORMAT ": ", addr);
4687     if (dlinfo.dli_sname != NULL) {
4688       st->print("%s+%#x", dlinfo.dli_sname,
4689                  addr - (intptr_t)dlinfo.dli_saddr);
4690     } else if (dlinfo.dli_fname) {
4691       st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
4692     } else {
4693       st->print("<absolute address>");
4694     }
4695     if (dlinfo.dli_fname) {
4696       st->print(" in %s", dlinfo.dli_fname);
4697     }
4698     if (dlinfo.dli_fbase) {
4699       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
4700     }
4701     st->cr();
4702 
4703     if (Verbose) {
4704       // decode some bytes around the PC
4705       address begin = same_page(addr-40, addr);
4706       address end   = same_page(addr+40, addr);
4707       address       lowest = (address) dlinfo.dli_sname;
4708       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4709       if (begin < lowest)  begin = lowest;
4710       Dl_info dlinfo2;
4711       if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr
4712           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
4713         end = (address) dlinfo2.dli_saddr;
4714       Disassembler::decode(begin, end, st);
4715     }
4716     return true;
4717   }
4718   return false;
4719 }
4720 
4721 ////////////////////////////////////////////////////////////////////////////////
4722 // misc
4723 
4724 // This does not do anything on Linux. This is basically a hook for being
4725 // able to use structured exception handling (thread-local exception filters)
4726 // on, e.g., Win32.
4727 void
4728 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
4729                          JavaCallArguments* args, Thread* thread) {
4730   f(value, method, args, thread);
4731 }
4732 
4733 void os::print_statistics() {
4734 }
4735 
4736 int os::message_box(const char* title, const char* message) {
4737   int i;
4738   fdStream err(defaultStream::error_fd());
4739   for (i = 0; i < 78; i++) err.print_raw("=");
4740   err.cr();
4741   err.print_raw_cr(title);
4742   for (i = 0; i < 78; i++) err.print_raw("-");
4743   err.cr();
4744   err.print_raw_cr(message);
4745   for (i = 0; i < 78; i++) err.print_raw("=");
4746   err.cr();
4747 
4748   char buf[16];
4749   // Prevent process from exiting upon "read error" without consuming all CPU
4750   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
4751 
4752   return buf[0] == 'y' || buf[0] == 'Y';
4753 }
4754 
4755 int os::stat(const char *path, struct stat *sbuf) {
4756   char pathbuf[MAX_PATH];
4757   if (strlen(path) > MAX_PATH - 1) {
4758     errno = ENAMETOOLONG;
4759     return -1;
4760   }
4761   os::native_path(strcpy(pathbuf, path));
4762   return ::stat(pathbuf, sbuf);
4763 }
4764 
4765 bool os::check_heap(bool force) {
4766   return true;
4767 }
4768 
4769 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
4770   return ::vsnprintf(buf, count, format, args);
4771 }
4772 
4773 // Is a (classpath) directory empty?
4774 bool os::dir_is_empty(const char* path) {
4775   DIR *dir = NULL;
4776   struct dirent *ptr;
4777 
4778   dir = opendir(path);
4779   if (dir == NULL) return true;
4780 
4781   /* Scan the directory */
4782   bool result = true;
4783   char buf[sizeof(struct dirent) + MAX_PATH];
4784   while (result && (ptr = ::readdir(dir)) != NULL) {
4785     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4786       result = false;
4787     }
4788   }
4789   closedir(dir);
4790   return result;
4791 }
4792 
4793 // This code originates from JDK's sysOpen and open64_w
4794 // from src/solaris/hpi/src/system_md.c
4795 
4796 #ifndef O_DELETE
4797 #define O_DELETE 0x10000
4798 #endif
4799 
4800 // Open a file. Unlink the file immediately after open returns
4801 // if the specified oflag has the O_DELETE flag set.
4802 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
4803 
4804 int os::open(const char *path, int oflag, int mode) {
4805 
4806   if (strlen(path) > MAX_PATH - 1) {
4807     errno = ENAMETOOLONG;
4808     return -1;
4809   }
4810   int fd;
4811   int o_delete = (oflag & O_DELETE);
4812   oflag = oflag & ~O_DELETE;
4813 
4814   fd = ::open64(path, oflag, mode);
4815   if (fd == -1) return -1;
4816 
4817   //If the open succeeded, the file might still be a directory
4818   {
4819     struct stat64 buf64;
4820     int ret = ::fstat64(fd, &buf64);
4821     int st_mode = buf64.st_mode;
4822 
4823     if (ret != -1) {
4824       if ((st_mode & S_IFMT) == S_IFDIR) {
4825         errno = EISDIR;
4826         ::close(fd);
4827         return -1;
4828       }
4829     } else {
4830       ::close(fd);
4831       return -1;
4832     }
4833   }
4834 
4835     /*
4836      * All file descriptors that are opened in the JVM and not
4837      * specifically destined for a subprocess should have the
4838      * close-on-exec flag set.  If we don't set it, then careless 3rd
4839      * party native code might fork and exec without closing all
4840      * appropriate file descriptors (e.g. as we do in closeDescriptors in
4841      * UNIXProcess.c), and this in turn might:
4842      *
4843      * - cause end-of-file to fail to be detected on some file
4844      *   descriptors, resulting in mysterious hangs, or
4845      *
4846      * - might cause an fopen in the subprocess to fail on a system
4847      *   suffering from bug 1085341.
4848      *
4849      * (Yes, the default setting of the close-on-exec flag is a Unix
4850      * design flaw)
4851      *
4852      * See:
4853      * 1085341: 32-bit stdio routines should support file descriptors >255
4854      * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4855      * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4856      */
4857 #ifdef FD_CLOEXEC
4858     {
4859         int flags = ::fcntl(fd, F_GETFD);
4860         if (flags != -1)
4861             ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4862     }
4863 #endif
4864 
4865   if (o_delete != 0) {
4866     ::unlink(path);
4867   }
4868   return fd;
4869 }
4870 
4871 
4872 // create binary file, rewriting existing file if required
4873 int os::create_binary_file(const char* path, bool rewrite_existing) {
4874   int oflags = O_WRONLY | O_CREAT;
4875   if (!rewrite_existing) {
4876     oflags |= O_EXCL;
4877   }
4878   return ::open64(path, oflags, S_IREAD | S_IWRITE);
4879 }
4880 
4881 // return current position of file pointer
4882 jlong os::current_file_offset(int fd) {
4883   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4884 }
4885 
4886 // move file pointer to the specified offset
4887 jlong os::seek_to_file_offset(int fd, jlong offset) {
4888   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4889 }
4890 
4891 // This code originates from JDK's sysAvailable
4892 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
4893 
4894 int os::available(int fd, jlong *bytes) {
4895   jlong cur, end;
4896   int mode;
4897   struct stat64 buf64;
4898 
4899   if (::fstat64(fd, &buf64) >= 0) {
4900     mode = buf64.st_mode;
4901     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4902       /*
4903       * XXX: is the following call interruptible? If so, this might
4904       * need to go through the INTERRUPT_IO() wrapper as for other
4905       * blocking, interruptible calls in this file.
4906       */
4907       int n;
4908       if (::ioctl(fd, FIONREAD, &n) >= 0) {
4909         *bytes = n;
4910         return 1;
4911       }
4912     }
4913   }
4914   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4915     return 0;
4916   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4917     return 0;
4918   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4919     return 0;
4920   }
4921   *bytes = end - cur;
4922   return 1;
4923 }
4924 
4925 int os::socket_available(int fd, jint *pbytes) {
4926   // Linux doc says EINTR not returned, unlike Solaris
4927   int ret = ::ioctl(fd, FIONREAD, pbytes);
4928 
4929   //%% note ioctl can return 0 when successful, JVM_SocketAvailable
4930   // is expected to return 0 on failure and 1 on success to the jdk.
4931   return (ret < 0) ? 0 : 1;
4932 }
4933 
4934 // Map a block of memory.
4935 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4936                      char *addr, size_t bytes, bool read_only,
4937                      bool allow_exec) {
4938   int prot;
4939   int flags = MAP_PRIVATE;
4940 
4941   if (read_only) {
4942     prot = PROT_READ;
4943   } else {
4944     prot = PROT_READ | PROT_WRITE;
4945   }
4946 
4947   if (allow_exec) {
4948     prot |= PROT_EXEC;
4949   }
4950 
4951   if (addr != NULL) {
4952     flags |= MAP_FIXED;
4953   }
4954 
4955   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4956                                      fd, file_offset);
4957   if (mapped_address == MAP_FAILED) {
4958     return NULL;
4959   }
4960   return mapped_address;
4961 }
4962 
4963 
4964 // Remap a block of memory.
4965 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4966                        char *addr, size_t bytes, bool read_only,
4967                        bool allow_exec) {
4968   // same as map_memory() on this OS
4969   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4970                         allow_exec);
4971 }
4972 
4973 
4974 // Unmap a block of memory.
4975 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4976   return munmap(addr, bytes) == 0;
4977 }
4978 
4979 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
4980 
4981 static clockid_t thread_cpu_clockid(Thread* thread) {
4982   pthread_t tid = thread->osthread()->pthread_id();
4983   clockid_t clockid;
4984 
4985   // Get thread clockid
4986   int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
4987   assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
4988   return clockid;
4989 }
4990 
4991 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4992 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4993 // of a thread.
4994 //
4995 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
4996 // the fast estimate available on the platform.
4997 
4998 jlong os::current_thread_cpu_time() {
4999   if (os::Linux::supports_fast_thread_cpu_time()) {
5000     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5001   } else {
5002     // return user + sys since the cost is the same
5003     return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5004   }
5005 }
5006 
5007 jlong os::thread_cpu_time(Thread* thread) {
5008   // consistent with what current_thread_cpu_time() returns
5009   if (os::Linux::supports_fast_thread_cpu_time()) {
5010     return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5011   } else {
5012     return slow_thread_cpu_time(thread, true /* user + sys */);
5013   }
5014 }
5015 
5016 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5017   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5018     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5019   } else {
5020     return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5021   }
5022 }
5023 
5024 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5025   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5026     return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5027   } else {
5028     return slow_thread_cpu_time(thread, user_sys_cpu_time);
5029   }
5030 }
5031 
5032 //
5033 //  -1 on error.
5034 //
5035 
5036 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5037   static bool proc_pid_cpu_avail = true;
5038   static bool proc_task_unchecked = true;
5039   static const char *proc_stat_path = "/proc/%d/stat";
5040   pid_t  tid = thread->osthread()->thread_id();
5041   int i;
5042   char *s;
5043   char stat[2048];
5044   int statlen;
5045   char proc_name[64];
5046   int count;
5047   long sys_time, user_time;
5048   char string[64];
5049   char cdummy;
5050   int idummy;
5051   long ldummy;
5052   FILE *fp;
5053 
5054   // We first try accessing /proc/<pid>/cpu since this is faster to
5055   // process.  If this file is not present (linux kernels 2.5 and above)
5056   // then we open /proc/<pid>/stat.
5057   if ( proc_pid_cpu_avail ) {
5058     sprintf(proc_name, "/proc/%d/cpu", tid);
5059     fp =  fopen(proc_name, "r");
5060     if ( fp != NULL ) {
5061       count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time);
5062       fclose(fp);
5063       if ( count != 3 ) return -1;
5064 
5065       if (user_sys_cpu_time) {
5066         return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5067       } else {
5068         return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5069       }
5070     }
5071     else proc_pid_cpu_avail = false;
5072   }
5073 
5074   // The /proc/<tid>/stat aggregates per-process usage on
5075   // new Linux kernels 2.6+ where NPTL is supported.
5076   // The /proc/self/task/<tid>/stat still has the per-thread usage.
5077   // See bug 6328462.
5078   // There can be no directory /proc/self/task on kernels 2.4 with NPTL
5079   // and possibly in some other cases, so we check its availability.
5080   if (proc_task_unchecked && os::Linux::is_NPTL()) {
5081     // This is executed only once
5082     proc_task_unchecked = false;
5083     fp = fopen("/proc/self/task", "r");
5084     if (fp != NULL) {
5085       proc_stat_path = "/proc/self/task/%d/stat";
5086       fclose(fp);
5087     }
5088   }
5089 
5090   sprintf(proc_name, proc_stat_path, tid);
5091   fp = fopen(proc_name, "r");
5092   if ( fp == NULL ) return -1;
5093   statlen = fread(stat, 1, 2047, fp);
5094   stat[statlen] = '\0';
5095   fclose(fp);
5096 
5097   // Skip pid and the command string. Note that we could be dealing with
5098   // weird command names, e.g. user could decide to rename java launcher
5099   // to "java 1.4.2 :)", then the stat file would look like
5100   //                1234 (java 1.4.2 :)) R ... ...
5101   // We don't really need to know the command string, just find the last
5102   // occurrence of ")" and then start parsing from there. See bug 4726580.
5103   s = strrchr(stat, ')');
5104   i = 0;
5105   if (s == NULL ) return -1;
5106 
5107   // Skip blank chars
5108   do s++; while (isspace(*s));
5109 
5110   count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5111                  &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5112                  &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5113                  &user_time, &sys_time);
5114   if ( count != 13 ) return -1;
5115   if (user_sys_cpu_time) {
5116     return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5117   } else {
5118     return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5119   }
5120 }
5121 
5122 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5123   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5124   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5125   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5126   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5127 }
5128 
5129 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5130   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5131   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5132   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5133   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5134 }
5135 
5136 bool os::is_thread_cpu_time_supported() {
5137   return true;
5138 }
5139 
5140 // System loadavg support.  Returns -1 if load average cannot be obtained.
5141 // Linux doesn't yet have a (official) notion of processor sets,
5142 // so just return the system wide load average.
5143 int os::loadavg(double loadavg[], int nelem) {
5144   return ::getloadavg(loadavg, nelem);
5145 }
5146 
5147 void os::pause() {
5148   char filename[MAX_PATH];
5149   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5150     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
5151   } else {
5152     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5153   }
5154 
5155   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5156   if (fd != -1) {
5157     struct stat buf;
5158     ::close(fd);
5159     while (::stat(filename, &buf) == 0) {
5160       (void)::poll(NULL, 0, 100);
5161     }
5162   } else {
5163     jio_fprintf(stderr,
5164       "Could not open pause file '%s', continuing immediately.\n", filename);
5165   }
5166 }
5167 
5168 
5169 // Refer to the comments in os_solaris.cpp park-unpark.
5170 //
5171 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
5172 // hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
5173 // For specifics regarding the bug see GLIBC BUGID 261237 :
5174 //    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
5175 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
5176 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
5177 // is used.  (The simple C test-case provided in the GLIBC bug report manifests the
5178 // hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
5179 // and monitorenter when we're using 1-0 locking.  All those operations may result in
5180 // calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
5181 // of libpthread avoids the problem, but isn't practical.
5182 //
5183 // Possible remedies:
5184 //
5185 // 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
5186 //      This is palliative and probabilistic, however.  If the thread is preempted
5187 //      between the call to compute_abstime() and pthread_cond_timedwait(), more
5188 //      than the minimum period may have passed, and the abstime may be stale (in the
5189 //      past) resultin in a hang.   Using this technique reduces the odds of a hang
5190 //      but the JVM is still vulnerable, particularly on heavily loaded systems.
5191 //
5192 // 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
5193 //      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
5194 //      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
5195 //      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
5196 //      thread.
5197 //
5198 // 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
5199 //      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
5200 //      a timeout request to the chron thread and then blocking via pthread_cond_wait().
5201 //      This also works well.  In fact it avoids kernel-level scalability impediments
5202 //      on certain platforms that don't handle lots of active pthread_cond_timedwait()
5203 //      timers in a graceful fashion.
5204 //
5205 // 4.   When the abstime value is in the past it appears that control returns
5206 //      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
5207 //      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
5208 //      can avoid the problem by reinitializing the condvar -- by cond_destroy()
5209 //      followed by cond_init() -- after all calls to pthread_cond_timedwait().
5210 //      It may be possible to avoid reinitialization by checking the return
5211 //      value from pthread_cond_timedwait().  In addition to reinitializing the
5212 //      condvar we must establish the invariant that cond_signal() is only called
5213 //      within critical sections protected by the adjunct mutex.  This prevents
5214 //      cond_signal() from "seeing" a condvar that's in the midst of being
5215 //      reinitialized or that is corrupt.  Sadly, this invariant obviates the
5216 //      desirable signal-after-unlock optimization that avoids futile context switching.
5217 //
5218 //      I'm also concerned that some versions of NTPL might allocate an auxilliary
5219 //      structure when a condvar is used or initialized.  cond_destroy()  would
5220 //      release the helper structure.  Our reinitialize-after-timedwait fix
5221 //      put excessive stress on malloc/free and locks protecting the c-heap.
5222 //
5223 // We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
5224 // It may be possible to refine (4) by checking the kernel and NTPL verisons
5225 // and only enabling the work-around for vulnerable environments.
5226 
5227 // utility to compute the abstime argument to timedwait:
5228 // millis is the relative timeout time
5229 // abstime will be the absolute timeout time
5230 // TODO: replace compute_abstime() with unpackTime()
5231 
5232 static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
5233   if (millis < 0)  millis = 0;
5234   struct timeval now;
5235   int status = gettimeofday(&now, NULL);
5236   assert(status == 0, "gettimeofday");
5237   jlong seconds = millis / 1000;
5238   millis %= 1000;
5239   if (seconds > 50000000) { // see man cond_timedwait(3T)
5240     seconds = 50000000;
5241   }
5242   abstime->tv_sec = now.tv_sec  + seconds;
5243   long       usec = now.tv_usec + millis * 1000;
5244   if (usec >= 1000000) {
5245     abstime->tv_sec += 1;
5246     usec -= 1000000;
5247   }
5248   abstime->tv_nsec = usec * 1000;
5249   return abstime;
5250 }
5251 
5252 
5253 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
5254 // Conceptually TryPark() should be equivalent to park(0).
5255 
5256 int os::PlatformEvent::TryPark() {
5257   for (;;) {
5258     const int v = _Event ;
5259     guarantee ((v == 0) || (v == 1), "invariant") ;
5260     if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
5261   }
5262 }
5263 
5264 void os::PlatformEvent::park() {       // AKA "down()"
5265   // Invariant: Only the thread associated with the Event/PlatformEvent
5266   // may call park().
5267   // TODO: assert that _Assoc != NULL or _Assoc == Self
5268   int v ;
5269   for (;;) {
5270       v = _Event ;
5271       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5272   }
5273   guarantee (v >= 0, "invariant") ;
5274   if (v == 0) {
5275      // Do this the hard way by blocking ...
5276      int status = pthread_mutex_lock(_mutex);
5277      assert_status(status == 0, status, "mutex_lock");
5278      guarantee (_nParked == 0, "invariant") ;
5279      ++ _nParked ;
5280      while (_Event < 0) {
5281         status = pthread_cond_wait(_cond, _mutex);
5282         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5283         // Treat this the same as if the wait was interrupted
5284         if (status == ETIME) { status = EINTR; }
5285         assert_status(status == 0 || status == EINTR, status, "cond_wait");
5286      }
5287      -- _nParked ;
5288 
5289     _Event = 0 ;
5290      status = pthread_mutex_unlock(_mutex);
5291      assert_status(status == 0, status, "mutex_unlock");
5292     // Paranoia to ensure our locked and lock-free paths interact
5293     // correctly with each other.
5294     OrderAccess::fence();
5295   }
5296   guarantee (_Event >= 0, "invariant") ;
5297 }
5298 
5299 int os::PlatformEvent::park(jlong millis) {
5300   guarantee (_nParked == 0, "invariant") ;
5301 
5302   int v ;
5303   for (;;) {
5304       v = _Event ;
5305       if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5306   }
5307   guarantee (v >= 0, "invariant") ;
5308   if (v != 0) return OS_OK ;
5309 
5310   // We do this the hard way, by blocking the thread.
5311   // Consider enforcing a minimum timeout value.
5312   struct timespec abst;
5313   compute_abstime(&abst, millis);
5314 
5315   int ret = OS_TIMEOUT;
5316   int status = pthread_mutex_lock(_mutex);
5317   assert_status(status == 0, status, "mutex_lock");
5318   guarantee (_nParked == 0, "invariant") ;
5319   ++_nParked ;
5320 
5321   // Object.wait(timo) will return because of
5322   // (a) notification
5323   // (b) timeout
5324   // (c) thread.interrupt
5325   //
5326   // Thread.interrupt and object.notify{All} both call Event::set.
5327   // That is, we treat thread.interrupt as a special case of notification.
5328   // The underlying Solaris implementation, cond_timedwait, admits
5329   // spurious/premature wakeups, but the JLS/JVM spec prevents the
5330   // JVM from making those visible to Java code.  As such, we must
5331   // filter out spurious wakeups.  We assume all ETIME returns are valid.
5332   //
5333   // TODO: properly differentiate simultaneous notify+interrupt.
5334   // In that case, we should propagate the notify to another waiter.
5335 
5336   while (_Event < 0) {
5337     status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
5338     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5339       pthread_cond_destroy (_cond);
5340       pthread_cond_init (_cond, NULL) ;
5341     }
5342     assert_status(status == 0 || status == EINTR ||
5343                   status == ETIME || status == ETIMEDOUT,
5344                   status, "cond_timedwait");
5345     if (!FilterSpuriousWakeups) break ;                 // previous semantics
5346     if (status == ETIME || status == ETIMEDOUT) break ;
5347     // We consume and ignore EINTR and spurious wakeups.
5348   }
5349   --_nParked ;
5350   if (_Event >= 0) {
5351      ret = OS_OK;
5352   }
5353   _Event = 0 ;
5354   status = pthread_mutex_unlock(_mutex);
5355   assert_status(status == 0, status, "mutex_unlock");
5356   assert (_nParked == 0, "invariant") ;
5357   // Paranoia to ensure our locked and lock-free paths interact
5358   // correctly with each other.
5359   OrderAccess::fence();
5360   return ret;
5361 }
5362 
5363 void os::PlatformEvent::unpark() {
5364   // Transitions for _Event:
5365   //    0 :=> 1
5366   //    1 :=> 1
5367   //   -1 :=> either 0 or 1; must signal target thread
5368   //          That is, we can safely transition _Event from -1 to either
5369   //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
5370   //          unpark() calls.
5371   // See also: "Semaphores in Plan 9" by Mullender & Cox
5372   //
5373   // Note: Forcing a transition from "-1" to "1" on an unpark() means
5374   // that it will take two back-to-back park() calls for the owning
5375   // thread to block. This has the benefit of forcing a spurious return
5376   // from the first park() call after an unpark() call which will help
5377   // shake out uses of park() and unpark() without condition variables.
5378 
5379   if (Atomic::xchg(1, &_Event) >= 0) return;
5380 
5381   // Wait for the thread associated with the event to vacate
5382   int status = pthread_mutex_lock(_mutex);
5383   assert_status(status == 0, status, "mutex_lock");
5384   int AnyWaiters = _nParked;
5385   assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5386   if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
5387     AnyWaiters = 0;
5388     pthread_cond_signal(_cond);
5389   }
5390   status = pthread_mutex_unlock(_mutex);
5391   assert_status(status == 0, status, "mutex_unlock");
5392   if (AnyWaiters != 0) {
5393     status = pthread_cond_signal(_cond);
5394     assert_status(status == 0, status, "cond_signal");
5395   }
5396 
5397   // Note that we signal() _after dropping the lock for "immortal" Events.
5398   // This is safe and avoids a common class of  futile wakeups.  In rare
5399   // circumstances this can cause a thread to return prematurely from
5400   // cond_{timed}wait() but the spurious wakeup is benign and the victim will
5401   // simply re-test the condition and re-park itself.
5402 }
5403 
5404 
5405 // JSR166
5406 // -------------------------------------------------------
5407 
5408 /*
5409  * The solaris and linux implementations of park/unpark are fairly
5410  * conservative for now, but can be improved. They currently use a
5411  * mutex/condvar pair, plus a a count.
5412  * Park decrements count if > 0, else does a condvar wait.  Unpark
5413  * sets count to 1 and signals condvar.  Only one thread ever waits
5414  * on the condvar. Contention seen when trying to park implies that someone
5415  * is unparking you, so don't wait. And spurious returns are fine, so there
5416  * is no need to track notifications.
5417  */
5418 
5419 #define MAX_SECS 100000000
5420 /*
5421  * This code is common to linux and solaris and will be moved to a
5422  * common place in dolphin.
5423  *
5424  * The passed in time value is either a relative time in nanoseconds
5425  * or an absolute time in milliseconds. Either way it has to be unpacked
5426  * into suitable seconds and nanoseconds components and stored in the
5427  * given timespec structure.
5428  * Given time is a 64-bit value and the time_t used in the timespec is only
5429  * a signed-32-bit value (except on 64-bit Linux) we have to watch for
5430  * overflow if times way in the future are given. Further on Solaris versions
5431  * prior to 10 there is a restriction (see cond_timedwait) that the specified
5432  * number of seconds, in abstime, is less than current_time  + 100,000,000.
5433  * As it will be 28 years before "now + 100000000" will overflow we can
5434  * ignore overflow and just impose a hard-limit on seconds using the value
5435  * of "now + 100,000,000". This places a limit on the timeout of about 3.17
5436  * years from "now".
5437  */
5438 
5439 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5440   assert (time > 0, "convertTime");
5441 
5442   struct timeval now;
5443   int status = gettimeofday(&now, NULL);
5444   assert(status == 0, "gettimeofday");
5445 
5446   time_t max_secs = now.tv_sec + MAX_SECS;
5447 
5448   if (isAbsolute) {
5449     jlong secs = time / 1000;
5450     if (secs > max_secs) {
5451       absTime->tv_sec = max_secs;
5452     }
5453     else {
5454       absTime->tv_sec = secs;
5455     }
5456     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5457   }
5458   else {
5459     jlong secs = time / NANOSECS_PER_SEC;
5460     if (secs >= MAX_SECS) {
5461       absTime->tv_sec = max_secs;
5462       absTime->tv_nsec = 0;
5463     }
5464     else {
5465       absTime->tv_sec = now.tv_sec + secs;
5466       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5467       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5468         absTime->tv_nsec -= NANOSECS_PER_SEC;
5469         ++absTime->tv_sec; // note: this must be <= max_secs
5470       }
5471     }
5472   }
5473   assert(absTime->tv_sec >= 0, "tv_sec < 0");
5474   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5475   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5476   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5477 }
5478 
5479 void Parker::park(bool isAbsolute, jlong time) {
5480   // Ideally we'd do something useful while spinning, such
5481   // as calling unpackTime().
5482 
5483   // Optional fast-path check:
5484   // Return immediately if a permit is available.
5485   // We depend on Atomic::xchg() having full barrier semantics
5486   // since we are doing a lock-free update to _counter.
5487   if (Atomic::xchg(0, &_counter) > 0) return;
5488 
5489   Thread* thread = Thread::current();
5490   assert(thread->is_Java_thread(), "Must be JavaThread");
5491   JavaThread *jt = (JavaThread *)thread;
5492 
5493   // Optional optimization -- avoid state transitions if there's an interrupt pending.
5494   // Check interrupt before trying to wait
5495   if (Thread::is_interrupted(thread, false)) {
5496     return;
5497   }
5498 
5499   // Next, demultiplex/decode time arguments
5500   timespec absTime;
5501   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
5502     return;
5503   }
5504   if (time > 0) {
5505     unpackTime(&absTime, isAbsolute, time);
5506   }
5507 
5508 
5509   // Enter safepoint region
5510   // Beware of deadlocks such as 6317397.
5511   // The per-thread Parker:: mutex is a classic leaf-lock.
5512   // In particular a thread must never block on the Threads_lock while
5513   // holding the Parker:: mutex.  If safepoints are pending both the
5514   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5515   ThreadBlockInVM tbivm(jt);
5516 
5517   // Don't wait if cannot get lock since interference arises from
5518   // unblocking.  Also. check interrupt before trying wait
5519   if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
5520     return;
5521   }
5522 
5523   int status ;
5524   if (_counter > 0)  { // no wait needed
5525     _counter = 0;
5526     status = pthread_mutex_unlock(_mutex);
5527     assert (status == 0, "invariant") ;
5528     // Paranoia to ensure our locked and lock-free paths interact
5529     // correctly with each other and Java-level accesses.
5530     OrderAccess::fence();
5531     return;
5532   }
5533 
5534 #ifdef ASSERT
5535   // Don't catch signals while blocked; let the running threads have the signals.
5536   // (This allows a debugger to break into the running thread.)
5537   sigset_t oldsigs;
5538   sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
5539   pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5540 #endif
5541 
5542   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5543   jt->set_suspend_equivalent();
5544   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5545 
5546   if (time == 0) {
5547     status = pthread_cond_wait (_cond, _mutex) ;
5548   } else {
5549     status = os::Linux::safe_cond_timedwait (_cond, _mutex, &absTime) ;
5550     if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5551       pthread_cond_destroy (_cond) ;
5552       pthread_cond_init    (_cond, NULL);
5553     }
5554   }
5555   assert_status(status == 0 || status == EINTR ||
5556                 status == ETIME || status == ETIMEDOUT,
5557                 status, "cond_timedwait");
5558 
5559 #ifdef ASSERT
5560   pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
5561 #endif
5562 
5563   _counter = 0 ;
5564   status = pthread_mutex_unlock(_mutex) ;
5565   assert_status(status == 0, status, "invariant") ;
5566   // Paranoia to ensure our locked and lock-free paths interact
5567   // correctly with each other and Java-level accesses.
5568   OrderAccess::fence();
5569 
5570   // If externally suspended while waiting, re-suspend
5571   if (jt->handle_special_suspend_equivalent_condition()) {
5572     jt->java_suspend_self();
5573   }
5574 }
5575 
5576 void Parker::unpark() {
5577   int s, status ;
5578   status = pthread_mutex_lock(_mutex);
5579   assert (status == 0, "invariant") ;
5580   s = _counter;
5581   _counter = 1;
5582   if (s < 1) {
5583      if (WorkAroundNPTLTimedWaitHang) {
5584         status = pthread_cond_signal (_cond) ;
5585         assert (status == 0, "invariant") ;
5586         status = pthread_mutex_unlock(_mutex);
5587         assert (status == 0, "invariant") ;
5588      } else {
5589         status = pthread_mutex_unlock(_mutex);
5590         assert (status == 0, "invariant") ;
5591         status = pthread_cond_signal (_cond) ;
5592         assert (status == 0, "invariant") ;
5593      }
5594   } else {
5595     pthread_mutex_unlock(_mutex);
5596     assert (status == 0, "invariant") ;
5597   }
5598 }
5599 
5600 
5601 extern char** environ;
5602 
5603 #ifndef __NR_fork
5604 #define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57)
5605 #endif
5606 
5607 #ifndef __NR_execve
5608 #define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59)
5609 #endif
5610 
5611 // Run the specified command in a separate process. Return its exit value,
5612 // or -1 on failure (e.g. can't fork a new process).
5613 // Unlike system(), this function can be called from signal handler. It
5614 // doesn't block SIGINT et al.
5615 int os::fork_and_exec(char* cmd) {
5616   const char * argv[4] = {"sh", "-c", cmd, NULL};
5617 
5618   // fork() in LinuxThreads/NPTL is not async-safe. It needs to run
5619   // pthread_atfork handlers and reset pthread library. All we need is a
5620   // separate process to execve. Make a direct syscall to fork process.
5621   // On IA64 there's no fork syscall, we have to use fork() and hope for
5622   // the best...
5623   pid_t pid = NOT_IA64(syscall(__NR_fork);)
5624               IA64_ONLY(fork();)
5625 
5626   if (pid < 0) {
5627     // fork failed
5628     return -1;
5629 
5630   } else if (pid == 0) {
5631     // child process
5632 
5633     // execve() in LinuxThreads will call pthread_kill_other_threads_np()
5634     // first to kill every thread on the thread list. Because this list is
5635     // not reset by fork() (see notes above), execve() will instead kill
5636     // every thread in the parent process. We know this is the only thread
5637     // in the new process, so make a system call directly.
5638     // IA64 should use normal execve() from glibc to match the glibc fork()
5639     // above.
5640     NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);)
5641     IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);)
5642 
5643     // execve failed
5644     _exit(-1);
5645 
5646   } else  {
5647     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5648     // care about the actual exit code, for now.
5649 
5650     int status;
5651 
5652     // Wait for the child process to exit.  This returns immediately if
5653     // the child has already exited. */
5654     while (waitpid(pid, &status, 0) < 0) {
5655         switch (errno) {
5656         case ECHILD: return 0;
5657         case EINTR: break;
5658         default: return -1;
5659         }
5660     }
5661 
5662     if (WIFEXITED(status)) {
5663        // The child exited normally; get its exit code.
5664        return WEXITSTATUS(status);
5665     } else if (WIFSIGNALED(status)) {
5666        // The child exited because of a signal
5667        // The best value to return is 0x80 + signal number,
5668        // because that is what all Unix shells do, and because
5669        // it allows callers to distinguish between process exit and
5670        // process death by signal.
5671        return 0x80 + WTERMSIG(status);
5672     } else {
5673        // Unknown exit code; pass it through
5674        return status;
5675     }
5676   }
5677 }
5678 
5679 // is_headless_jre()
5680 //
5681 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
5682 // in order to report if we are running in a headless jre
5683 //
5684 // Since JDK8 xawt/libmawt.so was moved into the same directory
5685 // as libawt.so, and renamed libawt_xawt.so
5686 //
5687 bool os::is_headless_jre() {
5688     struct stat statbuf;
5689     char buf[MAXPATHLEN];
5690     char libmawtpath[MAXPATHLEN];
5691     const char *xawtstr  = "/xawt/libmawt.so";
5692     const char *new_xawtstr = "/libawt_xawt.so";
5693     char *p;
5694 
5695     // Get path to libjvm.so
5696     os::jvm_path(buf, sizeof(buf));
5697 
5698     // Get rid of libjvm.so
5699     p = strrchr(buf, '/');
5700     if (p == NULL) return false;
5701     else *p = '\0';
5702 
5703     // Get rid of client or server
5704     p = strrchr(buf, '/');
5705     if (p == NULL) return false;
5706     else *p = '\0';
5707 
5708     // check xawt/libmawt.so
5709     strcpy(libmawtpath, buf);
5710     strcat(libmawtpath, xawtstr);
5711     if (::stat(libmawtpath, &statbuf) == 0) return false;
5712 
5713     // check libawt_xawt.so
5714     strcpy(libmawtpath, buf);
5715     strcat(libmawtpath, new_xawtstr);
5716     if (::stat(libmawtpath, &statbuf) == 0) return false;
5717 
5718     return true;
5719 }
5720 
5721 // Get the default path to the core file
5722 // Returns the length of the string
5723 int os::get_core_path(char* buffer, size_t bufferSize) {
5724   const char* p = get_current_directory(buffer, bufferSize);
5725 
5726   if (p == NULL) {
5727     assert(p != NULL, "failed to get current directory");
5728     return 0;
5729   }
5730 
5731   return strlen(buffer);
5732 }
5733 
5734 #ifdef JAVASE_EMBEDDED
5735 //
5736 // A thread to watch the '/dev/mem_notify' device, which will tell us when the OS is running low on memory.
5737 //
5738 MemNotifyThread* MemNotifyThread::_memnotify_thread = NULL;
5739 
5740 // ctor
5741 //
5742 MemNotifyThread::MemNotifyThread(int fd): Thread() {
5743   assert(memnotify_thread() == NULL, "we can only allocate one MemNotifyThread");
5744   _fd = fd;
5745 
5746   if (os::create_thread(this, os::os_thread)) {
5747     _memnotify_thread = this;
5748     os::set_priority(this, NearMaxPriority);
5749     os::start_thread(this);
5750   }
5751 }
5752 
5753 // Where all the work gets done
5754 //
5755 void MemNotifyThread::run() {
5756   assert(this == memnotify_thread(), "expected the singleton MemNotifyThread");
5757 
5758   // Set up the select arguments
5759   fd_set rfds;
5760   if (_fd != -1) {
5761     FD_ZERO(&rfds);
5762     FD_SET(_fd, &rfds);
5763   }
5764 
5765   // Now wait for the mem_notify device to wake up
5766   while (1) {
5767     // Wait for the mem_notify device to signal us..
5768     int rc = select(_fd+1, _fd != -1 ? &rfds : NULL, NULL, NULL, NULL);
5769     if (rc == -1) {
5770       perror("select!\n");
5771       break;
5772     } else if (rc) {
5773       //ssize_t free_before = os::available_memory();
5774       //tty->print ("Notified: Free: %dK \n",os::available_memory()/1024);
5775 
5776       // The kernel is telling us there is not much memory left...
5777       // try to do something about that
5778 
5779       // If we are not already in a GC, try one.
5780       if (!Universe::heap()->is_gc_active()) {
5781         Universe::heap()->collect(GCCause::_allocation_failure);
5782 
5783         //ssize_t free_after = os::available_memory();
5784         //tty->print ("Post-Notify: Free: %dK\n",free_after/1024);
5785         //tty->print ("GC freed: %dK\n", (free_after - free_before)/1024);
5786       }
5787       // We might want to do something like the following if we find the GC's are not helping...
5788       // Universe::heap()->size_policy()->set_gc_time_limit_exceeded(true);
5789     }
5790   }
5791 }
5792 
5793 //
5794 // See if the /dev/mem_notify device exists, and if so, start a thread to monitor it.
5795 //
5796 void MemNotifyThread::start() {
5797   int    fd;
5798   fd = open ("/dev/mem_notify", O_RDONLY, 0);
5799   if (fd < 0) {
5800       return;
5801   }
5802 
5803   if (memnotify_thread() == NULL) {
5804     new MemNotifyThread(fd);
5805   }
5806 }
5807 
5808 #endif // JAVASE_EMBEDDED