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