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