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