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