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