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