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