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