1 /*
2 * Copyright (c) 1999, 2020, 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 "jvmtifiles/jvmti.h"
36 #include "logging/log.hpp"
37 #include "logging/logStream.hpp"
38 #include "memory/allocation.inline.hpp"
39 #include "memory/filemap.hpp"
40 #include "oops/oop.inline.hpp"
41 #include "os_bsd.inline.hpp"
42 #include "os_posix.inline.hpp"
43 #include "os_share_bsd.hpp"
44 #include "prims/jniFastGetField.hpp"
45 #include "prims/jvm_misc.hpp"
46 #include "runtime/arguments.hpp"
47 #include "runtime/atomic.hpp"
48 #include "runtime/globals.hpp"
49 #include "runtime/globals_extension.hpp"
50 #include "runtime/interfaceSupport.inline.hpp"
51 #include "runtime/java.hpp"
52 #include "runtime/javaCalls.hpp"
53 #include "runtime/mutexLocker.hpp"
54 #include "runtime/objectMonitor.hpp"
55 #include "runtime/osThread.hpp"
56 #include "runtime/perfMemory.hpp"
57 #include "runtime/semaphore.hpp"
58 #include "runtime/sharedRuntime.hpp"
59 #include "runtime/statSampler.hpp"
60 #include "runtime/stubRoutines.hpp"
61 #include "runtime/thread.inline.hpp"
62 #include "runtime/threadCritical.hpp"
63 #include "runtime/timer.hpp"
64 #include "services/attachListener.hpp"
65 #include "services/memTracker.hpp"
66 #include "services/runtimeService.hpp"
67 #include "signals_posix.hpp"
68 #include "utilities/align.hpp"
69 #include "utilities/decoder.hpp"
70 #include "utilities/defaultStream.hpp"
71 #include "utilities/events.hpp"
72 #include "utilities/growableArray.hpp"
73 #include "utilities/vmError.hpp"
74
75 // put OS-includes here
76 # include <dlfcn.h>
77 # include <errno.h>
78 # include <fcntl.h>
79 # include <inttypes.h>
80 # include <poll.h>
81 # include <pthread.h>
82 # include <pwd.h>
83 # include <signal.h>
84 # include <stdint.h>
85 # include <stdio.h>
86 # include <string.h>
87 # include <sys/ioctl.h>
88 # include <sys/mman.h>
89 # include <sys/param.h>
90 # include <sys/resource.h>
91 # include <sys/socket.h>
92 # include <sys/stat.h>
93 # include <sys/syscall.h>
94 # include <sys/sysctl.h>
95 # include <sys/time.h>
96 # include <sys/times.h>
97 # include <sys/types.h>
98 # include <sys/wait.h>
99 # include <time.h>
100 # include <unistd.h>
101
102 #if !defined(__APPLE__)
103 #include <elf.h>
104 #endif
105
106 #if defined(__FreeBSD__) || defined(__DragonFly__)
107 #include <pthread_np.h>
108 #include <sys/link_elf.h>
109 #include <vm/vm_param.h>
110 #endif
111
112 #ifdef __OpenBSD__
113 #include <pthread_np.h>
114 #include <link_elf.h>
115 #endif
116
117 #ifdef __APPLE__
118 #include <mach-o/dyld.h>
119 // needed by current_stack_region() workaround for Mavericks
120 #include <errno.h>
121 #include <sys/types.h>
122 #include <sys/sysctl.h>
123 #define DEFAULT_MAIN_THREAD_STACK_PAGES 2048
124 #define OS_X_10_9_0_KERNEL_MAJOR_VERSION 13
125 #endif
126
127 #ifndef MAP_ANONYMOUS
128 #define MAP_ANONYMOUS MAP_ANON
129 #endif
130
131 #ifndef MAP_NORESERVE
132 #define MAP_NORESERVE 0
133 #endif
134
135 #define MAX_PATH (2 * K)
136
137 // for timer info max values which include all bits
138 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
139
140 ////////////////////////////////////////////////////////////////////////////////
141 // global variables
142 julong os::Bsd::_physical_memory = 0;
143
144 #ifdef __APPLE__
145 mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0};
146 volatile uint64_t os::Bsd::_max_abstime = 0;
147 #else
148 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
149 int (*os::Bsd::_getcpuclockid)(pthread_t, clockid_t *) = NULL;
150 #endif
151 pthread_t os::Bsd::_main_thread;
152 int os::Bsd::_page_size = -1;
153
154 static jlong initial_time_count=0;
155
156 static int clock_tics_per_sec = 100;
157
158 #ifdef __APPLE__
159 static const int processor_id_unassigned = -1;
160 static const int processor_id_assigning = -2;
161 static const int processor_id_map_size = 256;
162 static volatile int processor_id_map[processor_id_map_size];
163 static volatile int processor_id_next = 0;
164 #endif
165
166 ////////////////////////////////////////////////////////////////////////////////
167 // utility functions
168
available_memory()169 julong os::available_memory() {
170 return Bsd::available_memory();
171 }
172
173 // available here means free
available_memory()174 julong os::Bsd::available_memory() {
175 uint64_t available = physical_memory() >> 2;
176 #ifdef __APPLE__
177 mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
178 vm_statistics64_data_t vmstat;
179 kern_return_t kerr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
180 (host_info64_t)&vmstat, &count);
181 assert(kerr == KERN_SUCCESS,
182 "host_statistics64 failed - check mach_host_self() and count");
183 if (kerr == KERN_SUCCESS) {
184 available = vmstat.free_count * os::vm_page_size();
185 }
186 #elif defined(__FreeBSD__) || defined(__DragonFly__)
187 static const char *vm_stats[] = {
188 "vm.stats.vm.v_free_count",
189 "vm.stats.vm.v_cache_count",
190 "vm.stats.vm.v_inactive_count"
191 };
192 size_t size;
193 julong free_pages;
194 #ifdef __DragonFly__
195 u_long i, npages;
196 #else
197 u_int i, npages;
198 #endif
199
200 for (i = 0, free_pages = 0; i < sizeof(vm_stats) / sizeof(vm_stats[0]); i++) {
201 size = sizeof(npages);
202 if (sysctlbyname(vm_stats[i], &npages, &size, NULL, 0) == -1) {
203 free_pages = 0;
204 break;
205 }
206 free_pages += npages;
207 }
208 if (free_pages > 0)
209 available = free_pages * os::vm_page_size();
210 #endif
211 return available;
212 }
213
214 // for more info see :
215 // https://man.openbsd.org/sysctl.2
print_uptime_info(outputStream * st)216 void os::Bsd::print_uptime_info(outputStream* st) {
217 struct timeval boottime;
218 size_t len = sizeof(boottime);
219 int mib[2];
220 mib[0] = CTL_KERN;
221 mib[1] = KERN_BOOTTIME;
222
223 if (sysctl(mib, 2, &boottime, &len, NULL, 0) >= 0) {
224 time_t bootsec = boottime.tv_sec;
225 time_t currsec = time(NULL);
226 os::print_dhm(st, "OS uptime:", (long) difftime(currsec, bootsec));
227 }
228 }
229
physical_memory()230 julong os::physical_memory() {
231 return Bsd::physical_memory();
232 }
233
234 // Return true if user is running as root.
235
have_special_privileges()236 bool os::have_special_privileges() {
237 static bool init = false;
238 static bool privileges = false;
239 if (!init) {
240 #ifdef __APPLE__
241 privileges = (getuid() != geteuid()) || (getgid() != getegid());
242 #else
243 privileges = issetugid();
244 #endif
245 init = true;
246 }
247 return privileges;
248 }
249
250
251
252 // Cpu architecture string
253 #if defined(ZERO)
254 static char cpu_arch[] = ZERO_LIBARCH;
255 #elif defined(IA64)
256 static char cpu_arch[] = "ia64";
257 #elif defined(IA32)
258 static char cpu_arch[] = "i386";
259 #elif defined(AMD64)
260 static char cpu_arch[] = "amd64";
261 #elif defined(ARM)
262 static char cpu_arch[] = "arm";
263 #elif defined(PPC32)
264 static char cpu_arch[] = "ppc";
265 #elif defined(PPC64)
266 static char cpu_arch[] = "ppc64";
267 #elif defined(AARCH64)
268 static char cpu_arch[] = "aarch64";
269 #else
270 #error Add appropriate cpu_arch setting
271 #endif
272
273 // Compiler variant
274 #ifdef COMPILER2
275 #define COMPILER_VARIANT "server"
276 #else
277 #define COMPILER_VARIANT "client"
278 #endif
279
280
initialize_system_info()281 void os::Bsd::initialize_system_info() {
282 int mib[2];
283 size_t len;
284 int cpu_val;
285 #if defined (HW_MEMSIZE) // Apple
286 uint64_t mem_val;
287 #define MEMMIB HW_MEMSIZE;
288 #elif defined(HW_PHYSMEM64) // OpenBSD & NetBSD
289 int64_t mem_val;
290 #define MEMMIB HW_PHYSMEM64;
291 #elif defined(HW_PHYSMEM) // FreeBSD
292 unsigned long mem_val;
293 #define MEMMIB HW_PHYSMEM;
294 #else
295 #error No ways to get physmem
296 #endif
297
298 // get processors count via hw.ncpus sysctl
299 mib[0] = CTL_HW;
300 mib[1] = HW_NCPU;
301 len = sizeof(cpu_val);
302 if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
303 assert(len == sizeof(cpu_val), "unexpected data size");
304 set_processor_count(cpu_val);
305 } else {
306 set_processor_count(1); // fallback
307 }
308
309 #ifdef __APPLE__
310 // initialize processor id map
311 for (int i = 0; i < processor_id_map_size; i++) {
312 processor_id_map[i] = processor_id_unassigned;
313 }
314 #endif
315
316 // get physical memory via hw.memsize sysctl (hw.memsize is used
317 // since it returns a 64 bit value)
318 mib[0] = CTL_HW;
319 mib[1] = MEMMIB;
320
321 len = sizeof(mem_val);
322 if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
323 assert(len == sizeof(mem_val), "unexpected data size");
324 _physical_memory = mem_val;
325 } else {
326 _physical_memory = 256 * 1024 * 1024; // fallback (XXXBSD?)
327 }
328
329 #ifdef __OpenBSD__
330 {
331 // limit _physical_memory memory view on OpenBSD since
332 // datasize rlimit restricts us anyway.
333 struct rlimit limits;
334 getrlimit(RLIMIT_DATA, &limits);
335 _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
336 }
337 #endif
338 }
339
340 #ifdef __APPLE__
get_home()341 static const char *get_home() {
342 const char *home_dir = ::getenv("HOME");
343 if ((home_dir == NULL) || (*home_dir == '\0')) {
344 struct passwd *passwd_info = getpwuid(geteuid());
345 if (passwd_info != NULL) {
346 home_dir = passwd_info->pw_dir;
347 }
348 }
349
350 return home_dir;
351 }
352 #endif
353
init_system_properties_values()354 void os::init_system_properties_values() {
355 // The next steps are taken in the product version:
356 //
357 // Obtain the JAVA_HOME value from the location of libjvm.so.
358 // This library should be located at:
359 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
360 //
361 // If "/jre/lib/" appears at the right place in the path, then we
362 // assume libjvm.so is installed in a JDK and we use this path.
363 //
364 // Otherwise exit with message: "Could not create the Java virtual machine."
365 //
366 // The following extra steps are taken in the debugging version:
367 //
368 // If "/jre/lib/" does NOT appear at the right place in the path
369 // instead of exit check for $JAVA_HOME environment variable.
370 //
371 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
372 // then we append a fake suffix "hotspot/libjvm.so" to this path so
373 // it looks like libjvm.so is installed there
374 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
375 //
376 // Otherwise exit.
377 //
378 // Important note: if the location of libjvm.so changes this
379 // code needs to be changed accordingly.
380
381 // See ld(1):
382 // The linker uses the following search paths to locate required
383 // shared libraries:
384 // 1: ...
385 // ...
386 // 7: The default directories, normally /lib and /usr/lib.
387 #ifndef DEFAULT_LIBPATH
388 #ifndef OVERRIDE_LIBPATH
389 #ifdef __APPLE__
390 #define DEFAULT_LIBPATH "/lib:/usr/lib"
391 #elif defined(__NetBSD__)
392 #define DEFAULT_LIBPATH "/usr/lib:/usr/pkg/lib"
393 #else
394 #define DEFAULT_LIBPATH "/usr/lib:/usr/local/lib"
395 #endif
396 #else
397 #define DEFAULT_LIBPATH OVERRIDE_LIBPATH
398 #endif
399 #endif
400
401 // Base path of extensions installed on the system.
402 #define SYS_EXT_DIR "/usr/java/packages"
403 #define EXTENSIONS_DIR "/lib/ext"
404
405 #ifndef __APPLE__
406
407 // Buffer that fits several sprintfs.
408 // Note that the space for the colon and the trailing null are provided
409 // by the nulls included by the sizeof operator.
410 const size_t bufsize =
411 MAX2((size_t)MAXPATHLEN, // For dll_dir & friends.
412 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
413 char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
414
415 // sysclasspath, java_home, dll_dir
416 {
417 char *pslash;
418 os::jvm_path(buf, bufsize);
419
420 // Found the full path to libjvm.so.
421 // Now cut the path to <java_home>/jre if we can.
422 pslash = strrchr(buf, '/');
423 if (pslash != NULL) {
424 *pslash = '\0'; // Get rid of /libjvm.so.
425 }
426 pslash = strrchr(buf, '/');
427 if (pslash != NULL) {
428 *pslash = '\0'; // Get rid of /{client|server|hotspot}.
429 }
430 Arguments::set_dll_dir(buf);
431
432 if (pslash != NULL) {
433 pslash = strrchr(buf, '/');
434 if (pslash != NULL) {
435 *pslash = '\0'; // Get rid of /lib.
436 }
437 }
438 Arguments::set_java_home(buf);
439 if (!set_boot_path('/', ':')) {
440 vm_exit_during_initialization("Failed setting boot class path.", NULL);
441 }
442 }
443
444 // Where to look for native libraries.
445 //
446 // Note: Due to a legacy implementation, most of the library path
447 // is set in the launcher. This was to accomodate linking restrictions
448 // on legacy Bsd implementations (which are no longer supported).
449 // Eventually, all the library path setting will be done here.
450 //
451 // However, to prevent the proliferation of improperly built native
452 // libraries, the new path component /usr/java/packages is added here.
453 // Eventually, all the library path setting will be done here.
454 {
455 // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
456 // should always exist (until the legacy problem cited above is
457 // addressed).
458 const char *v = ::getenv("LD_LIBRARY_PATH");
459 const char *v_colon = ":";
460 if (v == NULL) { v = ""; v_colon = ""; }
461 // That's +1 for the colon and +1 for the trailing '\0'.
462 char *ld_library_path = NEW_C_HEAP_ARRAY(char,
463 strlen(v) + 1 +
464 sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
465 mtInternal);
466 sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
467 Arguments::set_library_path(ld_library_path);
468 FREE_C_HEAP_ARRAY(char, ld_library_path);
469 }
470
471 // Extensions directories.
472 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
473 Arguments::set_ext_dirs(buf);
474
475 FREE_C_HEAP_ARRAY(char, buf);
476
477 #else // __APPLE__
478
479 #define SYS_EXTENSIONS_DIR "/Library/Java/Extensions"
480 #define SYS_EXTENSIONS_DIRS SYS_EXTENSIONS_DIR ":/Network" SYS_EXTENSIONS_DIR ":/System" SYS_EXTENSIONS_DIR ":/usr/lib/java"
481
482 const char *user_home_dir = get_home();
483 // The null in SYS_EXTENSIONS_DIRS counts for the size of the colon after user_home_dir.
484 size_t system_ext_size = strlen(user_home_dir) + sizeof(SYS_EXTENSIONS_DIR) +
485 sizeof(SYS_EXTENSIONS_DIRS);
486
487 // Buffer that fits several sprintfs.
488 // Note that the space for the colon and the trailing null are provided
489 // by the nulls included by the sizeof operator.
490 const size_t bufsize =
491 MAX2((size_t)MAXPATHLEN, // for dll_dir & friends.
492 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + system_ext_size); // extensions dir
493 char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
494
495 // sysclasspath, java_home, dll_dir
496 {
497 char *pslash;
498 os::jvm_path(buf, bufsize);
499
500 // Found the full path to libjvm.so.
501 // Now cut the path to <java_home>/jre if we can.
502 *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
503 pslash = strrchr(buf, '/');
504 if (pslash != NULL) {
505 *pslash = '\0'; // Get rid of /{client|server|hotspot}.
506 }
507 #ifdef STATIC_BUILD
508 strcat(buf, "/lib");
509 #endif
510
511 Arguments::set_dll_dir(buf);
512
513 if (pslash != NULL) {
514 pslash = strrchr(buf, '/');
515 if (pslash != NULL) {
516 *pslash = '\0'; // Get rid of /lib.
517 }
518 }
519 Arguments::set_java_home(buf);
520 set_boot_path('/', ':');
521 }
522
523 // Where to look for native libraries.
524 //
525 // Note: Due to a legacy implementation, most of the library path
526 // is set in the launcher. This was to accomodate linking restrictions
527 // on legacy Bsd implementations (which are no longer supported).
528 // Eventually, all the library path setting will be done here.
529 //
530 // However, to prevent the proliferation of improperly built native
531 // libraries, the new path component /usr/java/packages is added here.
532 // Eventually, all the library path setting will be done here.
533 {
534 // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
535 // should always exist (until the legacy problem cited above is
536 // addressed).
537 // Prepend the default path with the JAVA_LIBRARY_PATH so that the app launcher code
538 // can specify a directory inside an app wrapper
539 const char *l = ::getenv("JAVA_LIBRARY_PATH");
540 const char *l_colon = ":";
541 if (l == NULL) { l = ""; l_colon = ""; }
542
543 const char *v = ::getenv("DYLD_LIBRARY_PATH");
544 const char *v_colon = ":";
545 if (v == NULL) { v = ""; v_colon = ""; }
546
547 // Apple's Java6 has "." at the beginning of java.library.path.
548 // OpenJDK on Windows has "." at the end of java.library.path.
549 // OpenJDK on Linux and Solaris don't have "." in java.library.path
550 // at all. To ease the transition from Apple's Java6 to OpenJDK7,
551 // "." is appended to the end of java.library.path. Yes, this
552 // could cause a change in behavior, but Apple's Java6 behavior
553 // can be achieved by putting "." at the beginning of the
554 // JAVA_LIBRARY_PATH environment variable.
555 char *ld_library_path = NEW_C_HEAP_ARRAY(char,
556 strlen(v) + 1 + strlen(l) + 1 +
557 system_ext_size + 3,
558 mtInternal);
559 sprintf(ld_library_path, "%s%s%s%s%s" SYS_EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS ":.",
560 v, v_colon, l, l_colon, user_home_dir);
561 Arguments::set_library_path(ld_library_path);
562 FREE_C_HEAP_ARRAY(char, ld_library_path);
563 }
564
565 // Extensions directories.
566 //
567 // Note that the space for the colon and the trailing null are provided
568 // by the nulls included by the sizeof operator (so actually one byte more
569 // than necessary is allocated).
570 sprintf(buf, "%s" SYS_EXTENSIONS_DIR ":%s" EXTENSIONS_DIR ":" SYS_EXTENSIONS_DIRS,
571 user_home_dir, Arguments::get_java_home());
572 Arguments::set_ext_dirs(buf);
573
574 FREE_C_HEAP_ARRAY(char, buf);
575
576 #undef SYS_EXTENSIONS_DIR
577 #undef SYS_EXTENSIONS_DIRS
578
579 #endif // __APPLE__
580
581 #undef SYS_EXT_DIR
582 #undef EXTENSIONS_DIR
583 }
584
585 ////////////////////////////////////////////////////////////////////////////////
586 // breakpoint support
587
breakpoint()588 void os::breakpoint() {
589 BREAKPOINT;
590 }
591
breakpoint()592 extern "C" void breakpoint() {
593 // use debugger to set breakpoint here
594 }
595
596 //////////////////////////////////////////////////////////////////////////////
597 // create new thread
598
599 #ifdef __APPLE__
600 // library handle for calling objc_registerThreadWithCollector()
601 // without static linking to the libobjc library
602 #define OBJC_LIB "/usr/lib/libobjc.dylib"
603 #define OBJC_GCREGISTER "objc_registerThreadWithCollector"
604 typedef void (*objc_registerThreadWithCollector_t)();
605 extern "C" objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction;
606 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
607 #endif
608
609 // Thread start routine for all newly created threads
thread_native_entry(Thread * thread)610 static void *thread_native_entry(Thread *thread) {
611
612 thread->record_stack_base_and_size();
613
614 // Try to randomize the cache line index of hot stack frames.
615 // This helps when threads of the same stack traces evict each other's
616 // cache lines. The threads can be either from the same JVM instance, or
617 // from different JVM instances. The benefit is especially true for
618 // processors with hyperthreading technology.
619 static int counter = 0;
620 int pid = os::current_process_id();
621 alloca(((pid ^ counter++) & 7) * 128);
622
623 thread->initialize_thread_current();
624
625 OSThread* osthread = thread->osthread();
626 Monitor* sync = osthread->startThread_lock();
627
628 osthread->set_thread_id(os::Bsd::gettid());
629
630 log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
631 os::current_thread_id(), (uintx) pthread_self());
632
633 #ifdef __APPLE__
634 // Store unique OS X thread id used by SA
635 osthread->set_unique_thread_id();
636 #endif
637
638 // initialize signal mask for this thread
639 PosixSignals::hotspot_sigmask(thread);
640
641 // initialize floating point control register
642 os::Bsd::init_thread_fpu_state();
643
644 #ifdef __APPLE__
645 // register thread with objc gc
646 if (objc_registerThreadWithCollectorFunction != NULL) {
647 objc_registerThreadWithCollectorFunction();
648 }
649 #endif
650
651 // handshaking with parent thread
652 {
653 MutexLocker ml(sync, Mutex::_no_safepoint_check_flag);
654
655 // notify parent thread
656 osthread->set_state(INITIALIZED);
657 sync->notify_all();
658
659 // wait until os::start_thread()
660 while (osthread->get_state() == INITIALIZED) {
661 sync->wait_without_safepoint_check();
662 }
663 }
664
665 // call one more level start routine
666 thread->call_run();
667
668 // Note: at this point the thread object may already have deleted itself.
669 // Prevent dereferencing it from here on out.
670 thread = NULL;
671
672 log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
673 os::current_thread_id(), (uintx) pthread_self());
674
675 return 0;
676 }
677
create_thread(Thread * thread,ThreadType thr_type,size_t req_stack_size)678 bool os::create_thread(Thread* thread, ThreadType thr_type,
679 size_t req_stack_size) {
680 assert(thread->osthread() == NULL, "caller responsible");
681
682 // Allocate the OSThread object
683 OSThread* osthread = new OSThread(NULL, NULL);
684 if (osthread == NULL) {
685 return false;
686 }
687
688 // set the correct thread state
689 osthread->set_thread_type(thr_type);
690
691 // Initial state is ALLOCATED but not INITIALIZED
692 osthread->set_state(ALLOCATED);
693
694 thread->set_osthread(osthread);
695
696 // init thread attributes
697 pthread_attr_t attr;
698 pthread_attr_init(&attr);
699 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
700
701 // calculate stack size if it's not specified by caller
702 size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
703 int status = pthread_attr_setstacksize(&attr, stack_size);
704 if (status != 0) {
705 // pthread_attr_setstacksize() function can fail
706 // if the stack size exceeds a system-imposed limit.
707 assert_status(status == EINVAL, status, "pthread_attr_setstacksize");
708 log_warning(os, thread)("The %sthread stack size specified is invalid: " SIZE_FORMAT "k",
709 (thr_type == compiler_thread) ? "compiler " : ((thr_type == java_thread) ? "" : "VM "),
710 stack_size / K);
711 thread->set_osthread(NULL);
712 delete osthread;
713 return false;
714 }
715
716 ThreadState state;
717
718 {
719 pthread_t tid;
720 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);
721
722 char buf[64];
723 if (ret == 0) {
724 log_info(os, thread)("Thread started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
725 (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
726 } else {
727 log_warning(os, thread)("Failed to start thread - pthread_create failed (%s) for attributes: %s.",
728 os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
729 // Log some OS information which might explain why creating the thread failed.
730 log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());
731 LogStream st(Log(os, thread)::info());
732 os::Posix::print_rlimit_info(&st);
733 os::print_memory_info(&st);
734 }
735
736 pthread_attr_destroy(&attr);
737
738 if (ret != 0) {
739 // Need to clean up stuff we've allocated so far
740 thread->set_osthread(NULL);
741 delete osthread;
742 return false;
743 }
744
745 // Store pthread info into the OSThread
746 osthread->set_pthread_id(tid);
747
748 // Wait until child thread is either initialized or aborted
749 {
750 Monitor* sync_with_child = osthread->startThread_lock();
751 MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
752 while ((state = osthread->get_state()) == ALLOCATED) {
753 sync_with_child->wait_without_safepoint_check();
754 }
755 }
756
757 }
758
759 // The thread is returned suspended (in state INITIALIZED),
760 // and is started higher up in the call chain
761 assert(state == INITIALIZED, "race condition");
762 return true;
763 }
764
765 /////////////////////////////////////////////////////////////////////////////
766 // attach existing thread
767
768 // bootstrap the main thread
create_main_thread(JavaThread * thread)769 bool os::create_main_thread(JavaThread* thread) {
770 assert(os::Bsd::_main_thread == pthread_self(), "should be called inside main thread");
771 return create_attached_thread(thread);
772 }
773
create_attached_thread(JavaThread * thread)774 bool os::create_attached_thread(JavaThread* thread) {
775 #ifdef ASSERT
776 thread->verify_not_published();
777 #endif
778
779 // Allocate the OSThread object
780 OSThread* osthread = new OSThread(NULL, NULL);
781
782 if (osthread == NULL) {
783 return false;
784 }
785
786 osthread->set_thread_id(os::Bsd::gettid());
787
788 #ifdef __APPLE__
789 // Store unique OS X thread id used by SA
790 osthread->set_unique_thread_id();
791 #endif
792
793 // Store pthread info into the OSThread
794 osthread->set_pthread_id(::pthread_self());
795
796 // initialize floating point control register
797 os::Bsd::init_thread_fpu_state();
798
799 // Initial thread state is RUNNABLE
800 osthread->set_state(RUNNABLE);
801
802 thread->set_osthread(osthread);
803
804 // initialize signal mask for this thread
805 // and save the caller's signal mask
806 PosixSignals::hotspot_sigmask(thread);
807
808 log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
809 os::current_thread_id(), (uintx) pthread_self());
810
811 return true;
812 }
813
pd_start_thread(Thread * thread)814 void os::pd_start_thread(Thread* thread) {
815 OSThread * osthread = thread->osthread();
816 assert(osthread->get_state() != INITIALIZED, "just checking");
817 Monitor* sync_with_child = osthread->startThread_lock();
818 MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
819 sync_with_child->notify();
820 }
821
822 // Free Bsd resources related to the OSThread
free_thread(OSThread * osthread)823 void os::free_thread(OSThread* osthread) {
824 assert(osthread != NULL, "osthread not set");
825
826 // We are told to free resources of the argument thread,
827 // but we can only really operate on the current thread.
828 assert(Thread::current()->osthread() == osthread,
829 "os::free_thread but not current thread");
830
831 // Restore caller's signal mask
832 sigset_t sigmask = osthread->caller_sigmask();
833 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
834
835 delete osthread;
836 }
837
838 ////////////////////////////////////////////////////////////////////////////////
839 // time support
840
841 // Time since start-up in seconds to a fine granularity.
842 // Used by VMSelfDestructTimer and the MemProfiler.
elapsedTime()843 double os::elapsedTime() {
844
845 return ((double)os::elapsed_counter()) / os::elapsed_frequency();
846 }
847
elapsed_counter()848 jlong os::elapsed_counter() {
849 return javaTimeNanos() - initial_time_count;
850 }
851
elapsed_frequency()852 jlong os::elapsed_frequency() {
853 return NANOSECS_PER_SEC; // nanosecond resolution
854 }
855
supports_vtime()856 bool os::supports_vtime() { return true; }
857
elapsedVTime()858 double os::elapsedVTime() {
859 #ifdef RUSAGE_THREAD
860 struct rusage usage;
861 int retval = getrusage(RUSAGE_THREAD, &usage);
862 if (retval == 0) {
863 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);
864 }
865 #endif
866 // better than nothing, but not much
867 return elapsedTime();
868 }
869
javaTimeMillis()870 jlong os::javaTimeMillis() {
871 if (os::Posix::supports_clock_gettime()) {
872 struct timespec ts;
873 int status = os::Posix::clock_gettime(CLOCK_REALTIME, &ts);
874 assert_status(status == 0, status, "gettime error");
875 return jlong(ts.tv_sec) * MILLIUNITS +
876 jlong(ts.tv_nsec) / NANOUNITS_PER_MILLIUNIT;
877 } else {
878 timeval time;
879 int status = gettimeofday(&time, NULL);
880 assert(status != -1, "bsd error");
881 return jlong(time.tv_sec) * MILLIUNITS +
882 jlong(time.tv_usec) / (MICROUNITS / MILLIUNITS);
883 }
884 }
885
javaTimeSystemUTC(jlong & seconds,jlong & nanos)886 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
887 if (os::Posix::supports_clock_gettime()) {
888 struct timespec ts;
889 int status = os::Posix::clock_gettime(CLOCK_REALTIME, &ts);
890 assert_status(status == 0, status, "gettime error");
891 seconds = jlong(ts.tv_sec);
892 nanos = jlong(ts.tv_nsec);
893 } else {
894 timeval time;
895 int status = gettimeofday(&time, NULL);
896 assert(status != -1, "bsd error");
897 seconds = jlong(time.tv_sec);
898 nanos = jlong(time.tv_usec) * (NANOUNITS / MICROUNITS);
899 }
900 }
901
902 #ifndef __APPLE__
903 #ifndef CLOCK_MONOTONIC
904 #define CLOCK_MONOTONIC (1)
905 #endif
906 #endif
907
908 #ifdef __APPLE__
clock_init()909 void os::Bsd::clock_init() {
910 mach_timebase_info(&_timebase_info);
911 }
912 #else
clock_init()913 void os::Bsd::clock_init() {
914 struct timespec res;
915 struct timespec tp;
916 _getcpuclockid = (int (*)(pthread_t, clockid_t *))dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
917 if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
918 ::clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
919 // yes, monotonic clock is supported
920 _clock_gettime = ::clock_gettime;
921 return;
922 }
923 warning("No monotonic clock was available - timed services may " \
924 "be adversely affected if the time-of-day clock changes");
925 }
926 #endif
927
928
929
930 #ifdef __APPLE__
931
javaTimeNanos()932 jlong os::javaTimeNanos() {
933 const uint64_t tm = mach_absolute_time();
934 const uint64_t now = (tm * Bsd::_timebase_info.numer) / Bsd::_timebase_info.denom;
935 const uint64_t prev = Bsd::_max_abstime;
936 if (now <= prev) {
937 return prev; // same or retrograde time;
938 }
939 const uint64_t obsv = Atomic::cmpxchg(&Bsd::_max_abstime, prev, now);
940 assert(obsv >= prev, "invariant"); // Monotonicity
941 // If the CAS succeeded then we're done and return "now".
942 // If the CAS failed and the observed value "obsv" is >= now then
943 // we should return "obsv". If the CAS failed and now > obsv > prv then
944 // some other thread raced this thread and installed a new value, in which case
945 // we could either (a) retry the entire operation, (b) retry trying to install now
946 // or (c) just return obsv. We use (c). No loop is required although in some cases
947 // we might discard a higher "now" value in deference to a slightly lower but freshly
948 // installed obsv value. That's entirely benign -- it admits no new orderings compared
949 // to (a) or (b) -- and greatly reduces coherence traffic.
950 // We might also condition (c) on the magnitude of the delta between obsv and now.
951 // Avoiding excessive CAS operations to hot RW locations is critical.
952 // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
953 return (prev == obsv) ? now : obsv;
954 }
955
956 #else // __APPLE__
957
javaTimeNanos()958 jlong os::javaTimeNanos() {
959 if (os::supports_monotonic_clock()) {
960 struct timespec tp;
961 int status = Bsd::_clock_gettime(CLOCK_MONOTONIC, &tp);
962 assert(status == 0, "gettime error");
963 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
964 return result;
965 } else {
966 timeval time;
967 int status = gettimeofday(&time, NULL);
968 assert(status != -1, "bsd error");
969 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
970 return 1000 * usecs;
971 }
972 }
973
974 #endif // __APPLE__
975
javaTimeNanos_info(jvmtiTimerInfo * info_ptr)976 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
977 if (os::supports_monotonic_clock()) {
978 info_ptr->max_value = ALL_64_BITS;
979
980 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
981 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
982 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
983 } else {
984 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
985 info_ptr->max_value = ALL_64_BITS;
986
987 // gettimeofday is a real time clock so it skips
988 info_ptr->may_skip_backward = true;
989 info_ptr->may_skip_forward = true;
990 }
991
992 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
993 }
994
995 // Return the real, user, and system times in seconds from an
996 // arbitrary fixed point in the past.
getTimesSecs(double * process_real_time,double * process_user_time,double * process_system_time)997 bool os::getTimesSecs(double* process_real_time,
998 double* process_user_time,
999 double* process_system_time) {
1000 struct tms ticks;
1001 clock_t real_ticks = times(&ticks);
1002
1003 if (real_ticks == (clock_t) (-1)) {
1004 return false;
1005 } else {
1006 double ticks_per_second = (double) clock_tics_per_sec;
1007 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1008 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1009 *process_real_time = ((double) real_ticks) / ticks_per_second;
1010
1011 return true;
1012 }
1013 }
1014
1015
local_time_string(char * buf,size_t buflen)1016 char * os::local_time_string(char *buf, size_t buflen) {
1017 struct tm t;
1018 time_t long_time;
1019 time(&long_time);
1020 localtime_r(&long_time, &t);
1021 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1022 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1023 t.tm_hour, t.tm_min, t.tm_sec);
1024 return buf;
1025 }
1026
localtime_pd(const time_t * clock,struct tm * res)1027 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1028 return localtime_r(clock, res);
1029 }
1030
1031 // Information of current thread in variety of formats
gettid()1032 pid_t os::Bsd::gettid() {
1033 int retval = -1;
1034
1035 #ifdef __APPLE__ // XNU kernel
1036 mach_port_t port = mach_thread_self();
1037 guarantee(MACH_PORT_VALID(port), "just checking");
1038 mach_port_deallocate(mach_task_self(), port);
1039 return (pid_t)port;
1040
1041 #elif defined(__FreeBSD__) || defined(__DragonFly__)
1042 return ::pthread_getthreadid_np();
1043 #elif defined(__OpenBSD__)
1044 retval = getthrid();
1045 #elif defined(__NetBSD__)
1046 retval = (pid_t) _lwp_self();
1047 #endif
1048
1049 if (retval == -1) {
1050 return getpid();
1051 }
1052 return retval;
1053 }
1054
current_thread_id()1055 intx os::current_thread_id() {
1056 #ifdef __APPLE__
1057 return (intx)os::Bsd::gettid();
1058 #elif defined(__FreeBSD__)
1059 return (intx)os::Bsd::gettid();
1060 #else
1061 return (intx)::pthread_self();
1062 #endif
1063 }
1064
current_process_id()1065 int os::current_process_id() {
1066 return (int)(getpid());
1067 }
1068
1069 // DLL functions
1070
dll_file_extension()1071 const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
1072
1073 // This must be hard coded because it's the system's temporary
1074 // directory not the java application's temp directory, ala java.io.tmpdir.
1075 #ifdef __APPLE__
1076 // macosx has a secure per-user temporary directory
1077 char temp_path_storage[PATH_MAX];
get_temp_directory()1078 const char* os::get_temp_directory() {
1079 static char *temp_path = NULL;
1080 if (temp_path == NULL) {
1081 int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, PATH_MAX);
1082 if (pathSize == 0 || pathSize > PATH_MAX) {
1083 strlcpy(temp_path_storage, "/tmp/", sizeof(temp_path_storage));
1084 }
1085 temp_path = temp_path_storage;
1086 }
1087 return temp_path;
1088 }
1089 #else // __APPLE__
get_temp_directory()1090 const char* os::get_temp_directory() { return "/tmp"; }
1091 #endif // __APPLE__
1092
1093 // check if addr is inside libjvm.so
address_is_in_vm(address addr)1094 bool os::address_is_in_vm(address addr) {
1095 static address libjvm_base_addr;
1096 Dl_info dlinfo;
1097
1098 if (libjvm_base_addr == NULL) {
1099 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1100 libjvm_base_addr = (address)dlinfo.dli_fbase;
1101 }
1102 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1103 }
1104
1105 if (dladdr((void *)addr, &dlinfo) != 0) {
1106 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1107 }
1108
1109 return false;
1110 }
1111
1112
1113 #define MACH_MAXSYMLEN 256
1114
dll_address_to_function_name(address addr,char * buf,int buflen,int * offset,bool demangle)1115 bool os::dll_address_to_function_name(address addr, char *buf,
1116 int buflen, int *offset,
1117 bool demangle) {
1118 // buf is not optional, but offset is optional
1119 assert(buf != NULL, "sanity check");
1120
1121 Dl_info dlinfo;
1122 char localbuf[MACH_MAXSYMLEN];
1123
1124 if (dladdr((void*)addr, &dlinfo) != 0) {
1125 // see if we have a matching symbol
1126 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1127 if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1128 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1129 }
1130 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1131 return true;
1132 }
1133 // no matching symbol so try for just file info
1134 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1135 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1136 buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1137 return true;
1138 }
1139 }
1140
1141 // Handle non-dynamic manually:
1142 if (dlinfo.dli_fbase != NULL &&
1143 Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset,
1144 dlinfo.dli_fbase)) {
1145 if (!(demangle && Decoder::demangle(localbuf, buf, buflen))) {
1146 jio_snprintf(buf, buflen, "%s", localbuf);
1147 }
1148 return true;
1149 }
1150 }
1151 buf[0] = '\0';
1152 if (offset != NULL) *offset = -1;
1153 return false;
1154 }
1155
1156 // ported from solaris version
dll_address_to_library_name(address addr,char * buf,int buflen,int * offset)1157 bool os::dll_address_to_library_name(address addr, char* buf,
1158 int buflen, int* offset) {
1159 // buf is not optional, but offset is optional
1160 assert(buf != NULL, "sanity check");
1161
1162 Dl_info dlinfo;
1163
1164 if (dladdr((void*)addr, &dlinfo) != 0) {
1165 if (dlinfo.dli_fname != NULL) {
1166 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1167 }
1168 if (dlinfo.dli_fbase != NULL && offset != NULL) {
1169 *offset = addr - (address)dlinfo.dli_fbase;
1170 }
1171 return true;
1172 }
1173
1174 buf[0] = '\0';
1175 if (offset) *offset = -1;
1176 return false;
1177 }
1178
1179 // Loads .dll/.so and
1180 // in case of error it checks if .dll/.so was built for the
1181 // same architecture as Hotspot is running on
1182
1183 #ifdef __APPLE__
dll_load(const char * filename,char * ebuf,int ebuflen)1184 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1185 #ifdef STATIC_BUILD
1186 return os::get_default_process_handle();
1187 #else
1188 log_info(os)("attempting shared library load of %s", filename);
1189
1190 void * result= ::dlopen(filename, RTLD_LAZY);
1191 if (result != NULL) {
1192 Events::log(NULL, "Loaded shared library %s", filename);
1193 // Successful loading
1194 log_info(os)("shared library load of %s was successful", filename);
1195 return result;
1196 }
1197
1198 const char* error_report = ::dlerror();
1199 if (error_report == NULL) {
1200 error_report = "dlerror returned no error description";
1201 }
1202 if (ebuf != NULL && ebuflen > 0) {
1203 // Read system error message into ebuf
1204 ::strncpy(ebuf, error_report, ebuflen-1);
1205 ebuf[ebuflen-1]='\0';
1206 }
1207 Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1208 log_info(os)("shared library load of %s failed, %s", filename, error_report);
1209
1210 return NULL;
1211 #endif // STATIC_BUILD
1212 }
1213 #else
dll_load(const char * filename,char * ebuf,int ebuflen)1214 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1215 #ifdef STATIC_BUILD
1216 return os::get_default_process_handle();
1217 #else
1218 log_info(os)("attempting shared library load of %s", filename);
1219 void * result= ::dlopen(filename, RTLD_LAZY);
1220 if (result != NULL) {
1221 Events::log(NULL, "Loaded shared library %s", filename);
1222 // Successful loading
1223 log_info(os)("shared library load of %s was successful", filename);
1224 return result;
1225 }
1226
1227 Elf32_Ehdr elf_head;
1228
1229 const char* const error_report = ::dlerror();
1230 if (ebuf != NULL && ebuflen > 0) {
1231 // Read system error message into ebuf
1232 ::strncpy(ebuf, error_report, ebuflen-1);
1233 ebuf[ebuflen-1]='\0';
1234 }
1235 Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report == NULL ? "dlerror returned no error description" : error_report);
1236 log_info(os)("shared library load of %s failed, %s", filename, error_report == NULL ? "dlerror returned no error description" : error_report);
1237
1238 int diag_msg_max_length=ebuflen-strlen(ebuf);
1239 char* diag_msg_buf=ebuf+strlen(ebuf);
1240
1241 if (diag_msg_max_length==0) {
1242 // No more space in ebuf for additional diagnostics message
1243 return NULL;
1244 }
1245
1246
1247 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1248
1249 if (file_descriptor < 0) {
1250 // Can't open library, report dlerror() message
1251 return NULL;
1252 }
1253
1254 bool failed_to_read_elf_head=
1255 (sizeof(elf_head)!=
1256 (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1257
1258 ::close(file_descriptor);
1259 if (failed_to_read_elf_head) {
1260 // file i/o error - report dlerror() msg
1261 return NULL;
1262 }
1263
1264 typedef struct {
1265 Elf32_Half code; // Actual value as defined in elf.h
1266 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1267 char elf_class; // 32 or 64 bit
1268 char endianess; // MSB or LSB
1269 char* name; // String representation
1270 } arch_t;
1271
1272 #ifndef EM_486
1273 #define EM_486 6 /* Intel 80486 */
1274 #endif
1275
1276 #ifndef EM_MIPS_RS3_LE
1277 #define EM_MIPS_RS3_LE 10 /* MIPS */
1278 #endif
1279
1280 #ifndef EM_PPC64
1281 #define EM_PPC64 21 /* PowerPC64 */
1282 #endif
1283
1284 #ifndef EM_S390
1285 #define EM_S390 22 /* IBM System/390 */
1286 #endif
1287
1288 #ifndef EM_IA_64
1289 #define EM_IA_64 50 /* HP/Intel IA-64 */
1290 #endif
1291
1292 #ifndef EM_X86_64
1293 #define EM_X86_64 62 /* AMD x86-64 */
1294 #endif
1295
1296 #ifndef EM_AARCH64
1297 #define EM_AARCH64 183 /* ARM AARCH64 */
1298 #endif
1299
1300 static const arch_t arch_array[]={
1301 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1302 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1303 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1304 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1305 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1306 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1307 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1308 {EM_AARCH64, EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"},
1309 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1310 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1311 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1312 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1313 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1314 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1315 };
1316
1317 #if (defined IA32)
1318 static Elf32_Half running_arch_code=EM_386;
1319 #elif (defined AMD64)
1320 static Elf32_Half running_arch_code=EM_X86_64;
1321 #elif (defined IA64)
1322 static Elf32_Half running_arch_code=EM_IA_64;
1323 #elif (defined __powerpc64__)
1324 static Elf32_Half running_arch_code=EM_PPC64;
1325 #elif (defined __powerpc__)
1326 static Elf32_Half running_arch_code=EM_PPC;
1327 #elif (defined AARCH64)
1328 static Elf32_Half running_arch_code=EM_AARCH64;
1329 #elif (defined ARM)
1330 static Elf32_Half running_arch_code=EM_ARM;
1331 #elif (defined S390)
1332 static Elf32_Half running_arch_code=EM_S390;
1333 #elif (defined ALPHA)
1334 static Elf32_Half running_arch_code=EM_ALPHA;
1335 #elif (defined MIPSEL)
1336 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1337 #elif (defined PARISC)
1338 static Elf32_Half running_arch_code=EM_PARISC;
1339 #elif (defined MIPS)
1340 static Elf32_Half running_arch_code=EM_MIPS;
1341 #elif (defined M68K)
1342 static Elf32_Half running_arch_code=EM_68K;
1343 #else
1344 #error Method os::dll_load requires that one of following is defined:\
1345 IA32, AMD64, IA64, __powerpc__, ARM, AARCH64, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
1346 #endif
1347
1348 // Identify compatability class for VM's architecture and library's architecture
1349 // Obtain string descriptions for architectures
1350
1351 arch_t lib_arch={elf_head.e_machine,0, (char)elf_head.e_ident[EI_CLASS], (char)elf_head.e_ident[EI_DATA], NULL};
1352 int running_arch_index=-1;
1353
1354 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1355 if (running_arch_code == arch_array[i].code) {
1356 running_arch_index = i;
1357 }
1358 if (lib_arch.code == arch_array[i].code) {
1359 lib_arch.compat_class = arch_array[i].compat_class;
1360 lib_arch.name = arch_array[i].name;
1361 }
1362 }
1363
1364 assert(running_arch_index != -1,
1365 "Didn't find running architecture code (running_arch_code) in arch_array");
1366 if (running_arch_index == -1) {
1367 // Even though running architecture detection failed
1368 // we may still continue with reporting dlerror() message
1369 return NULL;
1370 }
1371
1372 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1373 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1374 return NULL;
1375 }
1376
1377 #ifndef S390
1378 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1379 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1380 return NULL;
1381 }
1382 #endif // !S390
1383
1384 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1385 if (lib_arch.name!=NULL) {
1386 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1387 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1388 lib_arch.name, arch_array[running_arch_index].name);
1389 } else {
1390 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1391 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1392 lib_arch.code,
1393 arch_array[running_arch_index].name);
1394 }
1395 }
1396
1397 return NULL;
1398 #endif // STATIC_BUILD
1399 }
1400 #endif // !__APPLE__
1401
get_default_process_handle()1402 void* os::get_default_process_handle() {
1403 #ifdef __APPLE__
1404 // MacOS X needs to use RTLD_FIRST instead of RTLD_LAZY
1405 // to avoid finding unexpected symbols on second (or later)
1406 // loads of a library.
1407 return (void*)::dlopen(NULL, RTLD_FIRST);
1408 #else
1409 return (void*)::dlopen(NULL, RTLD_LAZY);
1410 #endif
1411 }
1412
1413 // XXX: Do we need a lock around this as per Linux?
dll_lookup(void * handle,const char * name)1414 void* os::dll_lookup(void* handle, const char* name) {
1415 return dlsym(handle, name);
1416 }
1417
_print_dll_info_cb(const char * name,address base_address,address top_address,void * param)1418 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1419 outputStream * out = (outputStream *) param;
1420 out->print_cr(INTPTR_FORMAT " \t%s", (intptr_t)base_address, name);
1421 return 0;
1422 }
1423
print_dll_info(outputStream * st)1424 void os::print_dll_info(outputStream *st) {
1425 st->print_cr("Dynamic libraries:");
1426 if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1427 st->print_cr("Error: Cannot print dynamic libraries.");
1428 }
1429 }
1430
1431 #if defined(__OpenBSD__)
1432 struct iterate_data {
1433 os::LoadedModulesCallbackFunc callback;
1434 void *param;
1435 };
1436
iter_callback(struct dl_phdr_info * info,size_t size,void * d)1437 static int iter_callback(struct dl_phdr_info *info, size_t size, void* d) {
1438 struct iterate_data *data = (struct iterate_data *)d;
1439
1440 if(data->callback(info->dlpi_name, (address)info->dlpi_addr, (address)0, data->param))
1441 return 1;
1442
1443 return 0;
1444 }
1445 #endif
1446
1447 #if defined(__FreeBSD__) || defined(__DragonFly__)
1448 struct loaded_modules_info_param {
1449 os::LoadedModulesCallbackFunc callback;
1450 void *param;
1451 };
1452
1453 #ifdef _LP64
1454 typedef Elf64_Phdr Elf_Phdr;
1455 #else
1456 typedef Elf32_Phdr Elf_Phdr;
1457 #endif
1458
dl_iterate_callback(struct dl_phdr_info * info,size_t size,void * data)1459 static int dl_iterate_callback(struct dl_phdr_info *info, size_t size, void *data) {
1460 if ((info->dlpi_name == NULL) || (*info->dlpi_name == '\0')) {
1461 return 0;
1462 }
1463
1464 struct loaded_modules_info_param *callback_param = reinterpret_cast<struct loaded_modules_info_param *>(data);
1465 address base = NULL;
1466 address top = NULL;
1467 for (int idx = 0; idx < info->dlpi_phnum; idx++) {
1468 const Elf_Phdr *phdr = info->dlpi_phdr + idx;
1469 if (phdr->p_type == PT_LOAD) {
1470 address raw_phdr_base = reinterpret_cast<address>(info->dlpi_addr + phdr->p_vaddr);
1471
1472 address phdr_base = align_down(raw_phdr_base, phdr->p_align);
1473 if ((base == NULL) || (base > phdr_base)) {
1474 base = phdr_base;
1475 }
1476
1477 address phdr_top = align_up(raw_phdr_base + phdr->p_memsz, phdr->p_align);
1478 if ((top == NULL) || (top < phdr_top)) {
1479 top = phdr_top;
1480 }
1481 }
1482 }
1483
1484 return callback_param->callback(info->dlpi_name, base, top, callback_param->param);
1485 }
1486 #endif
1487
get_loaded_modules_info(os::LoadedModulesCallbackFunc callback,void * param)1488 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1489 #if defined(__FreeBSD__) || defined(__DragonFly__)
1490 struct loaded_modules_info_param callback_param = {callback, param};
1491 return dl_iterate_phdr(&dl_iterate_callback, &callback_param);
1492 #elif defined(RTLD_DI_LINKMAP)
1493 Dl_info dli;
1494 void *handle;
1495 Link_map *map;
1496 Link_map *p;
1497
1498 if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||
1499 dli.dli_fname == NULL) {
1500 return 1;
1501 }
1502 handle = dlopen(dli.dli_fname, RTLD_LAZY);
1503 if (handle == NULL) {
1504 return 1;
1505 }
1506 dlinfo(handle, RTLD_DI_LINKMAP, &map);
1507 if (map == NULL) {
1508 dlclose(handle);
1509 return 1;
1510 }
1511
1512 while (map->l_prev != NULL)
1513 map = map->l_prev;
1514
1515 while (map != NULL) {
1516 // Value for top_address is returned as 0 since we don't have any information about module size
1517 if (callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1518 dlclose(handle);
1519 return 1;
1520 }
1521 map = map->l_next;
1522 }
1523
1524 dlclose(handle);
1525 return 0;
1526 #elif defined(__APPLE__)
1527 for (uint32_t i = 1; i < _dyld_image_count(); i++) {
1528 // Value for top_address is returned as 0 since we don't have any information about module size
1529 if (callback(_dyld_get_image_name(i), (address)_dyld_get_image_header(i), (address)0, param)) {
1530 return 1;
1531 }
1532 }
1533 return 0;
1534 #elif defined(__OpenBSD__)
1535 struct iterate_data data = { callback, param };
1536
1537 return dl_iterate_phdr(iter_callback, &data);
1538 #else
1539 return 1;
1540 #endif
1541 }
1542
get_summary_os_info(char * buf,size_t buflen)1543 void os::get_summary_os_info(char* buf, size_t buflen) {
1544 // These buffers are small because we want this to be brief
1545 // and not use a lot of stack while generating the hs_err file.
1546 char os[100];
1547 size_t size = sizeof(os);
1548 int mib_kern[] = { CTL_KERN, KERN_OSTYPE };
1549 if (sysctl(mib_kern, 2, os, &size, NULL, 0) < 0) {
1550 #ifdef __APPLE__
1551 strncpy(os, "Darwin", sizeof(os));
1552 #elif defined(__OpenBSD__)
1553 strncpy(os, "OpenBSD", sizeof(os));
1554 #else
1555 strncpy(os, "BSD", sizeof(os));
1556 #endif
1557 }
1558
1559 char release[100];
1560 size = sizeof(release);
1561 int mib_release[] = { CTL_KERN, KERN_OSRELEASE };
1562 if (sysctl(mib_release, 2, release, &size, NULL, 0) < 0) {
1563 // if error, leave blank
1564 strncpy(release, "", sizeof(release));
1565 }
1566
1567 #ifdef __APPLE__
1568 char osproductversion[100];
1569 size_t sz = sizeof(osproductversion);
1570 int ret = sysctlbyname("kern.osproductversion", osproductversion, &sz, NULL, 0);
1571 if (ret == 0) {
1572 char build[100];
1573 size = sizeof(build);
1574 int mib_build[] = { CTL_KERN, KERN_OSVERSION };
1575 if (sysctl(mib_build, 2, build, &size, NULL, 0) < 0) {
1576 snprintf(buf, buflen, "%s %s, macOS %s", os, release, osproductversion);
1577 } else {
1578 snprintf(buf, buflen, "%s %s, macOS %s (%s)", os, release, osproductversion, build);
1579 }
1580 } else
1581 #endif
1582 snprintf(buf, buflen, "%s %s", os, release);
1583 }
1584
print_os_info_brief(outputStream * st)1585 void os::print_os_info_brief(outputStream* st) {
1586 os::Posix::print_uname_info(st);
1587 }
1588
print_os_info(outputStream * st)1589 void os::print_os_info(outputStream* st) {
1590 st->print_cr("OS:");
1591
1592 os::Posix::print_uname_info(st);
1593
1594 os::Bsd::print_uptime_info(st);
1595
1596 os::Posix::print_rlimit_info(st);
1597
1598 os::Posix::print_load_average(st);
1599 st->cr();
1600
1601 VM_Version::print_platform_virtualization_info(st);
1602 }
1603
pd_print_cpu_info(outputStream * st,char * buf,size_t buflen)1604 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1605 size_t size = buflen;
1606 int mib[] = { CTL_HW, HW_MODEL };
1607 if (sysctl(mib, 2, buf, &size, NULL, 0) == 0) {
1608 st->print_cr("CPU Model: %s", buf);
1609 }
1610 }
1611
get_summary_cpu_info(char * buf,size_t buflen)1612 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1613 size_t size;
1614 #ifdef __APPLE__
1615 unsigned int mhz;
1616 size = sizeof(mhz);
1617 int mib[] = { CTL_HW, HW_CPU_FREQ };
1618 if (sysctl(mib, 2, &mhz, &size, NULL, 0) < 0) {
1619 mhz = 1; // looks like an error but can be divided by
1620 } else {
1621 mhz /= 1000000; // reported in millions
1622 }
1623 #endif
1624
1625 char model[100];
1626 size = sizeof(model);
1627 int mib_model[] = { CTL_HW, HW_MODEL };
1628 if (sysctl(mib_model, 2, model, &size, NULL, 0) < 0) {
1629 strncpy(model, cpu_arch, sizeof(model));
1630 }
1631
1632 char machine[100];
1633 size = sizeof(machine);
1634 int mib_machine[] = { CTL_HW, HW_MACHINE };
1635 if (sysctl(mib_machine, 2, machine, &size, NULL, 0) < 0) {
1636 strncpy(machine, "", sizeof(machine));
1637 }
1638
1639 #ifdef __APPLE__
1640 snprintf(buf, buflen, "%s %s %d MHz", model, machine, mhz);
1641 #else
1642 snprintf(buf, buflen, "%s %s", model, machine);
1643 #endif
1644 }
1645
1646 #ifdef __FreeBSD__
get_swap_info(int * total_pages,int * used_pages)1647 static void get_swap_info(int *total_pages, int *used_pages) {
1648 struct xswdev xsw;
1649 size_t mibsize, size;
1650 int mib[16];
1651 int n, total = 0, used = 0;
1652
1653 mibsize = sizeof(mib) / sizeof(mib[0]);
1654 if (sysctlnametomib("vm.swap_info", mib, &mibsize) != -1) {
1655 for (n = 0; ; n++) {
1656 mib[mibsize] = n;
1657 size = sizeof(xsw);
1658 if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
1659 break;
1660 total += xsw.xsw_nblks;
1661 used += xsw.xsw_used;
1662 }
1663 }
1664 *total_pages = total;
1665 *used_pages = used;
1666 }
1667 #endif
1668
print_memory_info(outputStream * st)1669 void os::print_memory_info(outputStream* st) {
1670 st->print("Memory:");
1671 st->print(" %dk page", os::vm_page_size()>>10);
1672
1673 st->print(", physical " UINT64_FORMAT "k",
1674 os::physical_memory() >> 10);
1675 st->print("(" UINT64_FORMAT "k free)",
1676 os::available_memory() >> 10);
1677
1678 #ifdef __APPLE__
1679 xsw_usage swap_usage;
1680 size_t size = sizeof(swap_usage);
1681 if((sysctlbyname("vm.swapusage", &swap_usage, &size, NULL, 0) == 0) || (errno == ENOMEM)) {
1682 if (size >= offset_of(xsw_usage, xsu_used)) {
1683 st->print(", swap " UINT64_FORMAT "k",
1684 ((julong) swap_usage.xsu_total) >> 10);
1685 st->print("(" UINT64_FORMAT "k free)",
1686 ((julong) swap_usage.xsu_avail) >> 10);
1687 }
1688 }
1689
1690 #elif defined(__FreeBSD__)
1691 int total, used;
1692 get_swap_info(&total, &used);
1693 st->print(", swap " UINT64_FORMAT "k",
1694 (((uint64_t) total) * ((uint64_t) os::vm_page_size())) >> 10);
1695 st->print("(" UINT64_FORMAT "k free)",
1696 (((uint64_t) (total - used)) * ((uint64_t) os::vm_page_size())) >> 10);
1697 #endif
1698 st->cr();
1699 }
1700
1701 static char saved_jvm_path[MAXPATHLEN] = {0};
1702
1703 // Find the full path to the current module, libjvm
jvm_path(char * buf,jint buflen)1704 void os::jvm_path(char *buf, jint buflen) {
1705 // Error checking.
1706 if (buflen < MAXPATHLEN) {
1707 assert(false, "must use a large-enough buffer");
1708 buf[0] = '\0';
1709 return;
1710 }
1711 // Lazy resolve the path to current module.
1712 if (saved_jvm_path[0] != 0) {
1713 strcpy(buf, saved_jvm_path);
1714 return;
1715 }
1716
1717 char dli_fname[MAXPATHLEN];
1718 bool ret = dll_address_to_library_name(
1719 CAST_FROM_FN_PTR(address, os::jvm_path),
1720 dli_fname, sizeof(dli_fname), NULL);
1721 assert(ret, "cannot locate libjvm");
1722 char *rp = NULL;
1723 if (ret && dli_fname[0] != '\0') {
1724 rp = os::Posix::realpath(dli_fname, buf, buflen);
1725 }
1726 if (rp == NULL) {
1727 return;
1728 }
1729
1730 if (Arguments::sun_java_launcher_is_altjvm()) {
1731 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
1732 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so"
1733 // or "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.dylib". If "/jre/lib/"
1734 // appears at the right place in the string, then assume we are
1735 // installed in a JDK and we're done. Otherwise, check for a
1736 // JAVA_HOME environment variable and construct a path to the JVM
1737 // being overridden.
1738
1739 const char *p = buf + strlen(buf) - 1;
1740 for (int count = 0; p > buf && count < 5; ++count) {
1741 for (--p; p > buf && *p != '/'; --p)
1742 /* empty */ ;
1743 }
1744
1745 if (strncmp(p, "/jre/lib/", 9) != 0) {
1746 // Look for JAVA_HOME in the environment.
1747 char* java_home_var = ::getenv("JAVA_HOME");
1748 if (java_home_var != NULL && java_home_var[0] != 0) {
1749 char* jrelib_p;
1750 int len;
1751
1752 // Check the current module name "libjvm"
1753 p = strrchr(buf, '/');
1754 assert(strstr(p, "/libjvm") == p, "invalid library name");
1755
1756 rp = os::Posix::realpath(java_home_var, buf, buflen);
1757 if (rp == NULL) {
1758 return;
1759 }
1760
1761 // determine if this is a legacy image or modules image
1762 // modules image doesn't have "jre" subdirectory
1763 len = strlen(buf);
1764 assert(len < buflen, "Ran out of buffer space");
1765 jrelib_p = buf + len;
1766
1767 // Add the appropriate library subdir
1768 snprintf(jrelib_p, buflen-len, "/jre/lib");
1769 if (0 != access(buf, F_OK)) {
1770 snprintf(jrelib_p, buflen-len, "/lib");
1771 }
1772
1773 // Add the appropriate client or server subdir
1774 len = strlen(buf);
1775 jrelib_p = buf + len;
1776 snprintf(jrelib_p, buflen-len, "/%s", COMPILER_VARIANT);
1777 if (0 != access(buf, F_OK)) {
1778 snprintf(jrelib_p, buflen-len, "%s", "");
1779 }
1780
1781 // If the path exists within JAVA_HOME, add the JVM library name
1782 // to complete the path to JVM being overridden. Otherwise fallback
1783 // to the path to the current library.
1784 if (0 == access(buf, F_OK)) {
1785 // Use current module name "libjvm"
1786 len = strlen(buf);
1787 snprintf(buf + len, buflen-len, "/libjvm%s", JNI_LIB_SUFFIX);
1788 } else {
1789 // Fall back to path of current library
1790 rp = os::Posix::realpath(dli_fname, buf, buflen);
1791 if (rp == NULL) {
1792 return;
1793 }
1794 }
1795 }
1796 }
1797 }
1798
1799 strncpy(saved_jvm_path, buf, MAXPATHLEN);
1800 saved_jvm_path[MAXPATHLEN - 1] = '\0';
1801 }
1802
print_jni_name_prefix_on(outputStream * st,int args_size)1803 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1804 // no prefix required, not even "_"
1805 }
1806
print_jni_name_suffix_on(outputStream * st,int args_size)1807 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1808 // no suffix required
1809 }
1810
1811 ////////////////////////////////////////////////////////////////////////////////
1812 // Virtual Memory
1813
vm_page_size()1814 int os::vm_page_size() {
1815 // Seems redundant as all get out
1816 assert(os::Bsd::page_size() != -1, "must call os::init");
1817 return os::Bsd::page_size();
1818 }
1819
1820 // Solaris allocates memory by pages.
vm_allocation_granularity()1821 int os::vm_allocation_granularity() {
1822 assert(os::Bsd::page_size() != -1, "must call os::init");
1823 return os::Bsd::page_size();
1824 }
1825
warn_fail_commit_memory(char * addr,size_t size,bool exec,int err)1826 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
1827 int err) {
1828 warning("INFO: os::commit_memory(" INTPTR_FORMAT ", " SIZE_FORMAT
1829 ", %d) failed; error='%s' (errno=%d)", (intptr_t)addr, size, exec,
1830 os::errno_name(err), err);
1831 }
1832
1833 // NOTE: Bsd kernel does not really reserve the pages for us.
1834 // All it does is to check if there are enough free pages
1835 // left at the time of mmap(). This could be a potential
1836 // problem.
pd_commit_memory(char * addr,size_t size,bool exec)1837 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
1838 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
1839 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
1840 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
1841 if (res != (uintptr_t) MAP_FAILED) {
1842 return true;
1843 }
1844
1845 // Warn about any commit errors we see in non-product builds just
1846 // in case mmap() doesn't work as described on the man page.
1847 NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
1848
1849 return false;
1850 }
1851
pd_commit_memory(char * addr,size_t size,size_t alignment_hint,bool exec)1852 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
1853 bool exec) {
1854 // alignment_hint is ignored on this OS
1855 return pd_commit_memory(addr, size, exec);
1856 }
1857
pd_commit_memory_or_exit(char * addr,size_t size,bool exec,const char * mesg)1858 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
1859 const char* mesg) {
1860 assert(mesg != NULL, "mesg must be specified");
1861 if (!pd_commit_memory(addr, size, exec)) {
1862 // add extra info in product mode for vm_exit_out_of_memory():
1863 PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
1864 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
1865 }
1866 }
1867
pd_commit_memory_or_exit(char * addr,size_t size,size_t alignment_hint,bool exec,const char * mesg)1868 void os::pd_commit_memory_or_exit(char* addr, size_t size,
1869 size_t alignment_hint, bool exec,
1870 const char* mesg) {
1871 // alignment_hint is ignored on this OS
1872 pd_commit_memory_or_exit(addr, size, exec, mesg);
1873 }
1874
pd_realign_memory(char * addr,size_t bytes,size_t alignment_hint)1875 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1876 }
1877
pd_free_memory(char * addr,size_t bytes,size_t alignment_hint)1878 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1879 ::madvise(addr, bytes, MADV_DONTNEED);
1880 }
1881
numa_make_global(char * addr,size_t bytes)1882 void os::numa_make_global(char *addr, size_t bytes) {
1883 }
1884
numa_make_local(char * addr,size_t bytes,int lgrp_hint)1885 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
1886 }
1887
numa_topology_changed()1888 bool os::numa_topology_changed() { return false; }
1889
numa_get_groups_num()1890 size_t os::numa_get_groups_num() {
1891 return 1;
1892 }
1893
numa_get_group_id()1894 int os::numa_get_group_id() {
1895 return 0;
1896 }
1897
numa_get_leaf_groups(int * ids,size_t size)1898 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
1899 if (size > 0) {
1900 ids[0] = 0;
1901 return 1;
1902 }
1903 return 0;
1904 }
1905
numa_get_group_id_for_address(const void * address)1906 int os::numa_get_group_id_for_address(const void* address) {
1907 return 0;
1908 }
1909
get_page_info(char * start,page_info * info)1910 bool os::get_page_info(char *start, page_info* info) {
1911 return false;
1912 }
1913
scan_pages(char * start,char * end,page_info * page_expected,page_info * page_found)1914 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
1915 return end;
1916 }
1917
1918
pd_uncommit_memory(char * addr,size_t size)1919 bool os::pd_uncommit_memory(char* addr, size_t size) {
1920 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
1921 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
1922 return res != (uintptr_t) MAP_FAILED;
1923 }
1924
pd_create_stack_guard_pages(char * addr,size_t size)1925 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
1926 return os::commit_memory(addr, size, !ExecMem);
1927 }
1928
1929 // If this is a growable mapping, remove the guard pages entirely by
1930 // munmap()ping them. If not, just call uncommit_memory().
remove_stack_guard_pages(char * addr,size_t size)1931 bool os::remove_stack_guard_pages(char* addr, size_t size) {
1932 return os::uncommit_memory(addr, size);
1933 }
1934
1935 // 'requested_addr' is only treated as a hint, the return value may or
1936 // may not start from the requested address. Unlike Bsd mmap(), this
1937 // function returns NULL to indicate failure.
anon_mmap(char * requested_addr,size_t bytes)1938 static char* anon_mmap(char* requested_addr, size_t bytes) {
1939 // MAP_FIXED is intentionally left out, to leave existing mappings intact.
1940 const int flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
1941
1942 // Map reserved/uncommitted pages PROT_NONE so we fail early if we
1943 // touch an uncommitted page. Otherwise, the read/write might
1944 // succeed if we have enough swap space to back the physical page.
1945 char* addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, flags, -1, 0);
1946
1947 return addr == MAP_FAILED ? NULL : addr;
1948 }
1949
anon_munmap(char * addr,size_t size)1950 static int anon_munmap(char * addr, size_t size) {
1951 return ::munmap(addr, size) == 0;
1952 }
1953
pd_reserve_memory(size_t bytes)1954 char* os::pd_reserve_memory(size_t bytes) {
1955 return anon_mmap(NULL /* addr */, bytes);
1956 }
1957
pd_release_memory(char * addr,size_t size)1958 bool os::pd_release_memory(char* addr, size_t size) {
1959 return anon_munmap(addr, size);
1960 }
1961
bsd_mprotect(char * addr,size_t size,int prot)1962 static bool bsd_mprotect(char* addr, size_t size, int prot) {
1963 // Bsd wants the mprotect address argument to be page aligned.
1964 char* bottom = (char*)align_down((intptr_t)addr, os::Bsd::page_size());
1965
1966 // According to SUSv3, mprotect() should only be used with mappings
1967 // established by mmap(), and mmap() always maps whole pages. Unaligned
1968 // 'addr' likely indicates problem in the VM (e.g. trying to change
1969 // protection of malloc'ed or statically allocated memory). Check the
1970 // caller if you hit this assert.
1971 assert(addr == bottom, "sanity check");
1972
1973 size = align_up(pointer_delta(addr, bottom, 1) + size, os::Bsd::page_size());
1974 Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);
1975 return ::mprotect(bottom, size, prot) == 0;
1976 }
1977
1978 // Set protections specified
protect_memory(char * addr,size_t bytes,ProtType prot,bool is_committed)1979 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
1980 bool is_committed) {
1981 unsigned int p = 0;
1982 switch (prot) {
1983 case MEM_PROT_NONE: p = PROT_NONE; break;
1984 case MEM_PROT_READ: p = PROT_READ; break;
1985 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
1986 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
1987 default:
1988 ShouldNotReachHere();
1989 }
1990 // is_committed is unused.
1991 return bsd_mprotect(addr, bytes, p);
1992 }
1993
guard_memory(char * addr,size_t size)1994 bool os::guard_memory(char* addr, size_t size) {
1995 return bsd_mprotect(addr, size, PROT_NONE);
1996 }
1997
unguard_memory(char * addr,size_t size)1998 bool os::unguard_memory(char* addr, size_t size) {
1999 return bsd_mprotect(addr, size, PROT_READ|PROT_WRITE);
2000 }
2001
hugetlbfs_sanity_check(bool warn,size_t page_size)2002 bool os::Bsd::hugetlbfs_sanity_check(bool warn, size_t page_size) {
2003 return false;
2004 }
2005
2006 // Large page support
2007
2008 static size_t _large_page_size = 0;
2009
large_page_init()2010 void os::large_page_init() {
2011 }
2012
2013
pd_reserve_memory_special(size_t bytes,size_t alignment,char * req_addr,bool exec)2014 char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
2015 fatal("os::reserve_memory_special should not be called on BSD.");
2016 return NULL;
2017 }
2018
pd_release_memory_special(char * base,size_t bytes)2019 bool os::pd_release_memory_special(char* base, size_t bytes) {
2020 fatal("os::release_memory_special should not be called on BSD.");
2021 return false;
2022 }
2023
large_page_size()2024 size_t os::large_page_size() {
2025 return _large_page_size;
2026 }
2027
can_commit_large_page_memory()2028 bool os::can_commit_large_page_memory() {
2029 // Does not matter, we do not support huge pages.
2030 return false;
2031 }
2032
can_execute_large_page_memory()2033 bool os::can_execute_large_page_memory() {
2034 // Does not matter, we do not support huge pages.
2035 return false;
2036 }
2037
pd_attempt_map_memory_to_file_at(char * requested_addr,size_t bytes,int file_desc)2038 char* os::pd_attempt_map_memory_to_file_at(char* requested_addr, size_t bytes, int file_desc) {
2039 assert(file_desc >= 0, "file_desc is not valid");
2040 char* result = pd_attempt_reserve_memory_at(requested_addr, bytes);
2041 if (result != NULL) {
2042 if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {
2043 vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
2044 }
2045 }
2046 return result;
2047 }
2048
2049 // Reserve memory at an arbitrary address, only if that area is
2050 // available (and not reserved for something else).
2051
pd_attempt_reserve_memory_at(char * requested_addr,size_t bytes)2052 char* os::pd_attempt_reserve_memory_at(char* requested_addr, size_t bytes) {
2053 // Assert only that the size is a multiple of the page size, since
2054 // that's all that mmap requires, and since that's all we really know
2055 // about at this low abstraction level. If we need higher alignment,
2056 // we can either pass an alignment to this method or verify alignment
2057 // in one of the methods further up the call chain. See bug 5044738.
2058 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2059
2060 // Repeatedly allocate blocks until the block is allocated at the
2061 // right spot.
2062
2063 // Bsd mmap allows caller to pass an address as hint; give it a try first,
2064 // if kernel honors the hint then we can return immediately.
2065 char * addr = anon_mmap(requested_addr, bytes);
2066 if (addr == requested_addr) {
2067 return requested_addr;
2068 }
2069
2070 if (addr != NULL) {
2071 // mmap() is successful but it fails to reserve at the requested address
2072 anon_munmap(addr, bytes);
2073 }
2074
2075 return NULL;
2076 }
2077
2078 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
infinite_sleep()2079 void os::infinite_sleep() {
2080 while (true) { // sleep forever ...
2081 ::sleep(100); // ... 100 seconds at a time
2082 }
2083 }
2084
2085 // Used to convert frequent JVM_Yield() to nops
dont_yield()2086 bool os::dont_yield() {
2087 return DontYieldALot;
2088 }
2089
naked_yield()2090 void os::naked_yield() {
2091 sched_yield();
2092 }
2093
2094 ////////////////////////////////////////////////////////////////////////////////
2095 // thread priority support
2096
2097 // Note: Normal Bsd applications are run with SCHED_OTHER policy. SCHED_OTHER
2098 // only supports dynamic priority, static priority must be zero. For real-time
2099 // applications, Bsd supports SCHED_RR which allows static priority (1-99).
2100 // However, for large multi-threaded applications, SCHED_RR is not only slower
2101 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
2102 // of 5 runs - Sep 2005).
2103 //
2104 // The following code actually changes the niceness of kernel-thread/LWP. It
2105 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
2106 // not the entire user process, and user level threads are 1:1 mapped to kernel
2107 // threads. It has always been the case, but could change in the future. For
2108 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
2109 // It is only used when ThreadPriorityPolicy=1 and may require system level permission
2110 // (e.g., root privilege or CAP_SYS_NICE capability).
2111
2112 #if !defined(__APPLE__)
2113 int os::java_to_os_priority[CriticalPriority + 1] = {
2114 19, // 0 Entry should never be used
2115
2116 0, // 1 MinPriority
2117 3, // 2
2118 6, // 3
2119
2120 10, // 4
2121 15, // 5 NormPriority
2122 18, // 6
2123
2124 21, // 7
2125 25, // 8
2126 28, // 9 NearMaxPriority
2127
2128 31, // 10 MaxPriority
2129
2130 31 // 11 CriticalPriority
2131 };
2132 #else
2133 // Using Mach high-level priority assignments
2134 int os::java_to_os_priority[CriticalPriority + 1] = {
2135 0, // 0 Entry should never be used (MINPRI_USER)
2136
2137 27, // 1 MinPriority
2138 28, // 2
2139 29, // 3
2140
2141 30, // 4
2142 31, // 5 NormPriority (BASEPRI_DEFAULT)
2143 32, // 6
2144
2145 33, // 7
2146 34, // 8
2147 35, // 9 NearMaxPriority
2148
2149 36, // 10 MaxPriority
2150
2151 36 // 11 CriticalPriority
2152 };
2153 #endif
2154
prio_init()2155 static int prio_init() {
2156 if (ThreadPriorityPolicy == 1) {
2157 if (geteuid() != 0) {
2158 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {
2159 warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \
2160 "e.g., being the root user. If the necessary permission is not " \
2161 "possessed, changes to priority will be silently ignored.");
2162 }
2163 }
2164 }
2165 if (UseCriticalJavaThreadPriority) {
2166 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
2167 }
2168 return 0;
2169 }
2170
set_native_priority(Thread * thread,int newpri)2171 OSReturn os::set_native_priority(Thread* thread, int newpri) {
2172 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
2173
2174 struct sched_param sp;
2175 int policy;
2176
2177 if (pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp) != 0) {
2178 return OS_ERR;
2179 }
2180
2181 sp.sched_priority = newpri;
2182 if (pthread_setschedparam(thread->osthread()->pthread_id(), policy, &sp) != 0) {
2183 return OS_ERR;
2184 }
2185
2186 return OS_OK;
2187 }
2188
get_native_priority(const Thread * const thread,int * priority_ptr)2189 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
2190 if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
2191 *priority_ptr = java_to_os_priority[NormPriority];
2192 return OS_OK;
2193 }
2194
2195 errno = 0;
2196 int policy;
2197 struct sched_param sp;
2198
2199 int res = pthread_getschedparam(thread->osthread()->pthread_id(), &policy, &sp);
2200 if (res != 0) {
2201 *priority_ptr = -1;
2202 return OS_ERR;
2203 } else {
2204 *priority_ptr = sp.sched_priority;
2205 return OS_OK;
2206 }
2207 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
2208 }
2209
2210 extern void report_error(char* file_name, int line_no, char* title,
2211 char* format, ...);
2212
2213 // this is called _before_ the most of global arguments have been parsed
init(void)2214 void os::init(void) {
2215 char dummy; // used to get a guess on initial stack address
2216
2217 clock_tics_per_sec = CLK_TCK;
2218
2219 Bsd::set_page_size(getpagesize());
2220 if (Bsd::page_size() == -1) {
2221 fatal("os_bsd.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
2222 }
2223 _page_sizes.add(Bsd::page_size());
2224
2225 Bsd::initialize_system_info();
2226
2227 // _main_thread points to the thread that created/loaded the JVM.
2228 Bsd::_main_thread = pthread_self();
2229
2230 Bsd::clock_init();
2231 initial_time_count = javaTimeNanos();
2232
2233 os::Posix::init();
2234 }
2235
2236 // To install functions for atexit system call
2237 extern "C" {
perfMemory_exit_helper()2238 static void perfMemory_exit_helper() {
2239 perfMemory_exit();
2240 }
2241 }
2242
2243 // this is called _after_ the global arguments have been parsed
init_2(void)2244 jint os::init_2(void) {
2245
2246 // This could be set after os::Posix::init() but all platforms
2247 // have to set it the same so we have to mirror Solaris.
2248 DEBUG_ONLY(os::set_mutex_init_done();)
2249
2250 os::Posix::init_2();
2251
2252 if (PosixSignals::init() == JNI_ERR) {
2253 return JNI_ERR;
2254 }
2255
2256 // Check and sets minimum stack sizes against command line options
2257 if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
2258 return JNI_ERR;
2259 }
2260
2261 // Not supported.
2262 FLAG_SET_ERGO(UseNUMA, false);
2263 FLAG_SET_ERGO(UseNUMAInterleaving, false);
2264
2265 if (MaxFDLimit) {
2266 // set the number of file descriptors to max. print out error
2267 // if getrlimit/setrlimit fails but continue regardless.
2268 struct rlimit nbr_files;
2269 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
2270 if (status != 0) {
2271 log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
2272 } else {
2273 nbr_files.rlim_cur = nbr_files.rlim_max;
2274
2275 #ifdef __APPLE__
2276 // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
2277 // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
2278 // be used instead
2279 nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
2280 #endif
2281
2282 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
2283 if (status != 0) {
2284 log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
2285 }
2286 }
2287 }
2288
2289 // at-exit methods are called in the reverse order of their registration.
2290 // atexit functions are called on return from main or as a result of a
2291 // call to exit(3C). There can be only 32 of these functions registered
2292 // and atexit() does not set errno.
2293
2294 if (PerfAllowAtExitRegistration) {
2295 // only register atexit functions if PerfAllowAtExitRegistration is set.
2296 // atexit functions can be delayed until process exit time, which
2297 // can be problematic for embedded VM situations. Embedded VMs should
2298 // call DestroyJavaVM() to assure that VM resources are released.
2299
2300 // note: perfMemory_exit_helper atexit function may be removed in
2301 // the future if the appropriate cleanup code can be added to the
2302 // VM_Exit VMOperation's doit method.
2303 if (atexit(perfMemory_exit_helper) != 0) {
2304 warning("os::init_2 atexit(perfMemory_exit_helper) failed");
2305 }
2306 }
2307
2308 // initialize thread priority policy
2309 prio_init();
2310
2311 #ifdef __APPLE__
2312 // dynamically link to objective c gc registration
2313 void *handleLibObjc = dlopen(OBJC_LIB, RTLD_LAZY);
2314 if (handleLibObjc != NULL) {
2315 objc_registerThreadWithCollectorFunction = (objc_registerThreadWithCollector_t) dlsym(handleLibObjc, OBJC_GCREGISTER);
2316 }
2317 #endif
2318
2319 return JNI_OK;
2320 }
2321
active_processor_count()2322 int os::active_processor_count() {
2323 // User has overridden the number of active processors
2324 if (ActiveProcessorCount > 0) {
2325 log_trace(os)("active_processor_count: "
2326 "active processor count set by user : %d",
2327 ActiveProcessorCount);
2328 return ActiveProcessorCount;
2329 }
2330
2331 #ifdef __FreeBSD__
2332 int online_cpus = 0;
2333 cpuset_t mask;
2334 if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(mask),
2335 &mask) == 0)
2336 for (u_int i = 0; i < sizeof(mask) / sizeof(long); i++)
2337 online_cpus += __builtin_popcountl(((long *)&mask)[i]);
2338 if (online_cpus > 0 && online_cpus <= _processor_count)
2339 return online_cpus;
2340 online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
2341 if (online_cpus >= 1)
2342 return online_cpus;
2343 #endif
2344
2345 #ifdef __DragonFly__
2346 return sysconf(_SC_NPROCESSORS_ONLN);
2347 #endif
2348
2349 return _processor_count;
2350 }
2351
2352 #ifdef __APPLE__
processor_id()2353 uint os::processor_id() {
2354 // Get the initial APIC id and return the associated processor id. The initial APIC
2355 // id is limited to 8-bits, which means we can have at most 256 unique APIC ids. If
2356 // the system has more processors (or the initial APIC ids are discontiguous) the
2357 // APIC id will be truncated and more than one processor will potentially share the
2358 // same processor id. This is not optimal, but unlikely to happen in practice. Should
2359 // this become a real problem we could switch to using x2APIC ids, which are 32-bit
2360 // wide. However, note that x2APIC is Intel-specific, and the wider number space
2361 // would require a more complicated mapping approach.
2362 uint eax = 0x1;
2363 uint ebx;
2364 uint ecx = 0;
2365 uint edx;
2366
2367 __asm__ ("cpuid\n\t" : "+a" (eax), "+b" (ebx), "+c" (ecx), "+d" (edx) : );
2368
2369 uint apic_id = (ebx >> 24) & (processor_id_map_size - 1);
2370 int processor_id = Atomic::load(&processor_id_map[apic_id]);
2371
2372 while (processor_id < 0) {
2373 // Assign processor id to APIC id
2374 processor_id = Atomic::cmpxchg(&processor_id_map[apic_id], processor_id_unassigned, processor_id_assigning);
2375 if (processor_id == processor_id_unassigned) {
2376 processor_id = Atomic::fetch_and_add(&processor_id_next, 1) % os::processor_count();
2377 Atomic::store(&processor_id_map[apic_id], processor_id);
2378 }
2379 }
2380
2381 assert(processor_id >= 0 && processor_id < os::processor_count(), "invalid processor id");
2382
2383 return (uint)processor_id;
2384 }
2385 #endif
2386
set_native_thread_name(const char * name)2387 void os::set_native_thread_name(const char *name) {
2388 if (name != NULL) {
2389 #if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
2390 // This is only supported in Snow Leopard and beyond
2391 // Add a "Java: " prefix to the name
2392 char buf[MAXTHREADNAMESIZE];
2393 snprintf(buf, sizeof(buf), "Java: %s", name);
2394 pthread_setname_np(buf);
2395 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
2396 pthread_set_name_np(pthread_self(), name);
2397 #elif defined(__NetBSD__)
2398 pthread_setname_np(pthread_self(), "%s", name);
2399 #endif
2400 }
2401 }
2402
bind_to_processor(uint processor_id)2403 bool os::bind_to_processor(uint processor_id) {
2404 // Not yet implemented.
2405 return false;
2406 }
2407
2408 ////////////////////////////////////////////////////////////////////////////////
2409 // debug support
2410
find(address addr,outputStream * st)2411 bool os::find(address addr, outputStream* st) {
2412 Dl_info dlinfo;
2413 memset(&dlinfo, 0, sizeof(dlinfo));
2414 if (dladdr(addr, &dlinfo) != 0) {
2415 st->print(INTPTR_FORMAT ": ", (intptr_t)addr);
2416 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
2417 st->print("%s+%#x", dlinfo.dli_sname,
2418 (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_saddr));
2419 } else if (dlinfo.dli_fbase != NULL) {
2420 st->print("<offset %#x>", (uint)((uintptr_t)addr - (uintptr_t)dlinfo.dli_fbase));
2421 } else {
2422 st->print("<absolute address>");
2423 }
2424 if (dlinfo.dli_fname != NULL) {
2425 st->print(" in %s", dlinfo.dli_fname);
2426 }
2427 if (dlinfo.dli_fbase != NULL) {
2428 st->print(" at " INTPTR_FORMAT, (intptr_t)dlinfo.dli_fbase);
2429 }
2430 st->cr();
2431
2432 if (Verbose) {
2433 // decode some bytes around the PC
2434 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
2435 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());
2436 address lowest = (address) dlinfo.dli_sname;
2437 if (!lowest) lowest = (address) dlinfo.dli_fbase;
2438 if (begin < lowest) begin = lowest;
2439 Dl_info dlinfo2;
2440 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
2441 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
2442 end = (address) dlinfo2.dli_saddr;
2443 }
2444 Disassembler::decode(begin, end, st);
2445 }
2446 return true;
2447 }
2448 return false;
2449 }
2450
2451 ////////////////////////////////////////////////////////////////////////////////
2452 // misc
2453
2454 // This does not do anything on Bsd. This is basically a hook for being
2455 // able to use structured exception handling (thread-local exception filters)
2456 // on, e.g., Win32.
os_exception_wrapper(java_call_t f,JavaValue * value,const methodHandle & method,JavaCallArguments * args,Thread * thread)2457 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
2458 const methodHandle& method, JavaCallArguments* args,
2459 Thread* thread) {
2460 f(value, method, args, thread);
2461 }
2462
print_statistics()2463 void os::print_statistics() {
2464 }
2465
message_box(const char * title,const char * message)2466 bool os::message_box(const char* title, const char* message) {
2467 int i;
2468 fdStream err(defaultStream::error_fd());
2469 for (i = 0; i < 78; i++) err.print_raw("=");
2470 err.cr();
2471 err.print_raw_cr(title);
2472 for (i = 0; i < 78; i++) err.print_raw("-");
2473 err.cr();
2474 err.print_raw_cr(message);
2475 for (i = 0; i < 78; i++) err.print_raw("=");
2476 err.cr();
2477
2478 char buf[16];
2479 // Prevent process from exiting upon "read error" without consuming all CPU
2480 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
2481
2482 return buf[0] == 'y' || buf[0] == 'Y';
2483 }
2484
2485 // Java thread:
2486 //
2487 // Low memory addresses
2488 // +------------------------+
2489 // | |\ Java thread created by VM does not have
2490 // | pthread guard page | - pthread guard, attached Java thread usually
2491 // | |/ has 1 pthread guard page.
2492 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
2493 // | |\
2494 // | HotSpot Guard Pages | - red, yellow and reserved pages
2495 // | |/
2496 // +------------------------+ StackOverflow::stack_reserved_zone_base()
2497 // | |\
2498 // | Normal Stack | -
2499 // | |/
2500 // P2 +------------------------+ Thread::stack_base()
2501 //
2502 // Non-Java thread:
2503 //
2504 // Low memory addresses
2505 // +------------------------+
2506 // | |\
2507 // | pthread guard page | - usually 1 page
2508 // | |/
2509 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
2510 // | |\
2511 // | Normal Stack | -
2512 // | |/
2513 // P2 +------------------------+ Thread::stack_base()
2514 //
2515 // ** P1 (aka bottom) and size ( P2 = P1 - size) are the address and stack size returned from
2516 // pthread_attr_getstack()
2517 #ifndef ZERO
current_stack_region(address * bottom,size_t * size)2518 static void current_stack_region(address * bottom, size_t * size) {
2519 #ifdef __APPLE__
2520 pthread_t self = pthread_self();
2521 void *stacktop = pthread_get_stackaddr_np(self);
2522 *size = pthread_get_stacksize_np(self);
2523 // workaround for OS X 10.9.0 (Mavericks)
2524 // pthread_get_stacksize_np returns 128 pages even though the actual size is 2048 pages
2525 if (pthread_main_np() == 1) {
2526 // At least on Mac OS 10.12 we have observed stack sizes not aligned
2527 // to pages boundaries. This can be provoked by e.g. setrlimit() (ulimit -s xxxx in the
2528 // shell). Apparently Mac OS actually rounds upwards to next multiple of page size,
2529 // however, we round downwards here to be on the safe side.
2530 *size = align_down(*size, getpagesize());
2531
2532 if ((*size) < (DEFAULT_MAIN_THREAD_STACK_PAGES * (size_t)getpagesize())) {
2533 char kern_osrelease[256];
2534 size_t kern_osrelease_size = sizeof(kern_osrelease);
2535 int ret = sysctlbyname("kern.osrelease", kern_osrelease, &kern_osrelease_size, NULL, 0);
2536 if (ret == 0) {
2537 // get the major number, atoi will ignore the minor amd micro portions of the version string
2538 if (atoi(kern_osrelease) >= OS_X_10_9_0_KERNEL_MAJOR_VERSION) {
2539 *size = (DEFAULT_MAIN_THREAD_STACK_PAGES*getpagesize());
2540 }
2541 }
2542 }
2543 }
2544 *bottom = (address) stacktop - *size;
2545 #elif defined(__OpenBSD__)
2546 stack_t ss;
2547 int rslt = pthread_stackseg_np(pthread_self(), &ss);
2548
2549 if (rslt != 0)
2550 fatal("pthread_stackseg_np failed with error = %d", rslt);
2551
2552 *bottom = (address)((char *)ss.ss_sp - ss.ss_size);
2553 *size = ss.ss_size;
2554 #else
2555 pthread_attr_t attr;
2556
2557 int rslt = pthread_attr_init(&attr);
2558
2559 // JVM needs to know exact stack location, abort if it fails
2560 if (rslt != 0)
2561 fatal("pthread_attr_init failed with error = %d", rslt);
2562
2563 rslt = pthread_attr_get_np(pthread_self(), &attr);
2564
2565 if (rslt != 0)
2566 fatal("pthread_attr_get_np failed with error = %d", rslt);
2567
2568 if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
2569 fatal("Can not locate current stack attributes!");
2570 }
2571
2572 pthread_attr_destroy(&attr);
2573 #endif
2574 assert(os::current_stack_pointer() >= *bottom &&
2575 os::current_stack_pointer() < *bottom + *size, "just checking");
2576 }
2577
current_stack_base()2578 address os::current_stack_base() {
2579 address bottom;
2580 size_t size;
2581 current_stack_region(&bottom, &size);
2582 return (bottom + size);
2583 }
2584
current_stack_size()2585 size_t os::current_stack_size() {
2586 // stack size includes normal stack and HotSpot guard pages
2587 address bottom;
2588 size_t size;
2589 current_stack_region(&bottom, &size);
2590 return size;
2591 }
2592 #endif // ZERO
2593
2594
get_mtime(const char * filename)2595 static inline struct timespec get_mtime(const char* filename) {
2596 struct stat st;
2597 int ret = os::stat(filename, &st);
2598 assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
2599 #ifdef __APPLE__
2600 return st.st_mtimespec;
2601 #else
2602 return st.st_mtim;
2603 #endif
2604 }
2605
compare_file_modified_times(const char * file1,const char * file2)2606 int os::compare_file_modified_times(const char* file1, const char* file2) {
2607 struct timespec filetime1 = get_mtime(file1);
2608 struct timespec filetime2 = get_mtime(file2);
2609 int diff = filetime1.tv_sec - filetime2.tv_sec;
2610 if (diff == 0) {
2611 return filetime1.tv_nsec - filetime2.tv_nsec;
2612 }
2613 return diff;
2614 }
2615
2616 // Is a (classpath) directory empty?
dir_is_empty(const char * path)2617 bool os::dir_is_empty(const char* path) {
2618 DIR *dir = NULL;
2619 struct dirent *ptr;
2620
2621 dir = opendir(path);
2622 if (dir == NULL) return true;
2623
2624 // Scan the directory
2625 bool result = true;
2626 while (result && (ptr = readdir(dir)) != NULL) {
2627 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
2628 result = false;
2629 }
2630 }
2631 closedir(dir);
2632 return result;
2633 }
2634
2635 // This code originates from JDK's sysOpen and open64_w
2636 // from src/solaris/hpi/src/system_md.c
2637
open(const char * path,int oflag,int mode)2638 int os::open(const char *path, int oflag, int mode) {
2639 if (strlen(path) > MAX_PATH - 1) {
2640 errno = ENAMETOOLONG;
2641 return -1;
2642 }
2643 int fd;
2644
2645 fd = ::open(path, oflag, mode);
2646 if (fd == -1) return -1;
2647
2648 // If the open succeeded, the file might still be a directory
2649 {
2650 struct stat buf;
2651 int ret = ::fstat(fd, &buf);
2652 int st_mode = buf.st_mode;
2653
2654 if (ret != -1) {
2655 if ((st_mode & S_IFMT) == S_IFDIR) {
2656 errno = EISDIR;
2657 ::close(fd);
2658 return -1;
2659 }
2660 } else {
2661 ::close(fd);
2662 return -1;
2663 }
2664 }
2665
2666 // All file descriptors that are opened in the JVM and not
2667 // specifically destined for a subprocess should have the
2668 // close-on-exec flag set. If we don't set it, then careless 3rd
2669 // party native code might fork and exec without closing all
2670 // appropriate file descriptors (e.g. as we do in closeDescriptors in
2671 // UNIXProcess.c), and this in turn might:
2672 //
2673 // - cause end-of-file to fail to be detected on some file
2674 // descriptors, resulting in mysterious hangs, or
2675 //
2676 // - might cause an fopen in the subprocess to fail on a system
2677 // suffering from bug 1085341.
2678 //
2679 // (Yes, the default setting of the close-on-exec flag is a Unix
2680 // design flaw)
2681 //
2682 // See:
2683 // 1085341: 32-bit stdio routines should support file descriptors >255
2684 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
2685 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
2686 //
2687 #ifdef FD_CLOEXEC
2688 {
2689 int flags = ::fcntl(fd, F_GETFD);
2690 if (flags != -1) {
2691 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
2692 }
2693 }
2694 #endif
2695
2696 return fd;
2697 }
2698
2699
2700 // create binary file, rewriting existing file if required
create_binary_file(const char * path,bool rewrite_existing)2701 int os::create_binary_file(const char* path, bool rewrite_existing) {
2702 int oflags = O_WRONLY | O_CREAT;
2703 if (!rewrite_existing) {
2704 oflags |= O_EXCL;
2705 }
2706 return ::open(path, oflags, S_IREAD | S_IWRITE);
2707 }
2708
2709 // return current position of file pointer
current_file_offset(int fd)2710 jlong os::current_file_offset(int fd) {
2711 return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
2712 }
2713
2714 // move file pointer to the specified offset
seek_to_file_offset(int fd,jlong offset)2715 jlong os::seek_to_file_offset(int fd, jlong offset) {
2716 return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
2717 }
2718
2719 // This code originates from JDK's sysAvailable
2720 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
2721
available(int fd,jlong * bytes)2722 int os::available(int fd, jlong *bytes) {
2723 jlong cur, end;
2724 int mode;
2725 struct stat buf;
2726
2727 if (::fstat(fd, &buf) >= 0) {
2728 mode = buf.st_mode;
2729 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
2730 int n;
2731 if (::ioctl(fd, FIONREAD, &n) >= 0) {
2732 *bytes = n;
2733 return 1;
2734 }
2735 }
2736 }
2737 if ((cur = ::lseek(fd, 0L, SEEK_CUR)) == -1) {
2738 return 0;
2739 } else if ((end = ::lseek(fd, 0L, SEEK_END)) == -1) {
2740 return 0;
2741 } else if (::lseek(fd, cur, SEEK_SET) == -1) {
2742 return 0;
2743 }
2744 *bytes = end - cur;
2745 return 1;
2746 }
2747
2748 // 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)2749 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
2750 char *addr, size_t bytes, bool read_only,
2751 bool allow_exec) {
2752 int prot;
2753 int flags;
2754
2755 if (read_only) {
2756 prot = PROT_READ;
2757 flags = MAP_SHARED;
2758 } else {
2759 prot = PROT_READ | PROT_WRITE;
2760 flags = MAP_PRIVATE;
2761 }
2762
2763 if (allow_exec) {
2764 prot |= PROT_EXEC;
2765 }
2766
2767 if (addr != NULL) {
2768 flags |= MAP_FIXED;
2769 }
2770
2771 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
2772 fd, file_offset);
2773 if (mapped_address == MAP_FAILED) {
2774 return NULL;
2775 }
2776 return mapped_address;
2777 }
2778
2779
2780 // 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)2781 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
2782 char *addr, size_t bytes, bool read_only,
2783 bool allow_exec) {
2784 // same as map_memory() on this OS
2785 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
2786 allow_exec);
2787 }
2788
2789
2790 // Unmap a block of memory.
pd_unmap_memory(char * addr,size_t bytes)2791 bool os::pd_unmap_memory(char* addr, size_t bytes) {
2792 return munmap(addr, bytes) == 0;
2793 }
2794
2795 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
2796 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
2797 // of a thread.
2798 //
2799 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
2800 // the fast estimate available on the platform.
2801
current_thread_cpu_time()2802 jlong os::current_thread_cpu_time() {
2803 return os::thread_cpu_time(Thread::current(), true /* user + sys */);
2804 }
2805
thread_cpu_time(Thread * thread)2806 jlong os::thread_cpu_time(Thread* thread) {
2807 return os::thread_cpu_time(thread, true /* user + sys */);
2808 }
2809
current_thread_cpu_time(bool user_sys_cpu_time)2810 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
2811 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
2812 }
2813
thread_cpu_time(Thread * thread,bool user_sys_cpu_time)2814 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
2815 #ifdef __APPLE__
2816 struct thread_basic_info tinfo;
2817 mach_msg_type_number_t tcount = THREAD_INFO_MAX;
2818 kern_return_t kr;
2819 thread_t mach_thread;
2820
2821 mach_thread = thread->osthread()->thread_id();
2822 kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
2823 if (kr != KERN_SUCCESS) {
2824 return -1;
2825 }
2826
2827 if (user_sys_cpu_time) {
2828 jlong nanos;
2829 nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
2830 nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
2831 return nanos;
2832 } else {
2833 return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
2834 }
2835 #else
2836 #if defined(__OpenBSD__)
2837 size_t length = 0;
2838 pid_t pid = getpid();
2839 struct kinfo_proc *ki;
2840
2841 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID|KERN_PROC_SHOW_THREADS, pid, sizeof(struct kinfo_proc), 0 };
2842 const u_int miblen = sizeof(mib) / sizeof(mib[0]);
2843
2844 if (sysctl(mib, miblen, NULL, &length, NULL, 0) < 0) {
2845 return -1;
2846 }
2847
2848 size_t num_threads = length / sizeof(*ki);
2849 ki = NEW_C_HEAP_ARRAY(struct kinfo_proc, num_threads, mtInternal);
2850
2851 mib[5] = num_threads;
2852
2853 if (sysctl(mib, miblen, ki, &length, NULL, 0) < 0) {
2854 FREE_C_HEAP_ARRAY(struct kinfo_proc, ki);
2855 return -1;
2856 }
2857
2858 num_threads = length / sizeof(*ki);
2859
2860 for (size_t i = 0; i < num_threads; i++) {
2861 if (ki[i].p_tid == thread->osthread()->thread_id()) {
2862 jlong nanos = (jlong)ki[i].p_uutime_sec * NANOSECS_PER_SEC;
2863 nanos += (jlong)ki[i].p_uutime_usec * 1000;
2864 if (user_sys_cpu_time) {
2865 nanos += (jlong)ki[i].p_ustime_sec * NANOSECS_PER_SEC;
2866 nanos += (jlong)ki[i].p_ustime_usec * 1000;
2867 }
2868 FREE_C_HEAP_ARRAY(struct kinfo_proc, ki);
2869 return nanos;
2870 }
2871 }
2872 FREE_C_HEAP_ARRAY(struct kinfo_proc, ki);
2873 return -1;
2874 #else /* !OpenBSD */
2875 if (user_sys_cpu_time && Bsd::_getcpuclockid != NULL) {
2876 struct timespec tp;
2877 clockid_t clockid;
2878 int ret;
2879
2880 /*
2881 * XXX This is essentially a copy of the Linux implementation,
2882 * but with fewer indirections.
2883 */
2884 ret = Bsd::_getcpuclockid(thread->osthread()->pthread_id(), &clockid);
2885 if (ret != 0)
2886 return -1;
2887 /* NB: _clock_gettime only needs to be valid for CLOCK_MONOTONIC. */
2888 ret = ::clock_gettime(clockid, &tp);
2889 if (ret != 0)
2890 return -1;
2891 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
2892 }
2893 #ifdef RUSAGE_THREAD
2894 if (thread == Thread::current()) {
2895 struct rusage usage;
2896 jlong nanos;
2897
2898 if (getrusage(RUSAGE_THREAD, &usage) != 0)
2899 return -1;
2900 nanos = (jlong)usage.ru_utime.tv_sec * NANOSECS_PER_SEC;
2901 nanos += (jlong)usage.ru_utime.tv_usec * 1000;
2902 if (user_sys_cpu_time) {
2903 nanos += (jlong)usage.ru_stime.tv_sec * NANOSECS_PER_SEC;
2904 nanos += (jlong)usage.ru_stime.tv_usec * 1000;
2905 }
2906 return nanos;
2907 }
2908 #endif
2909 return -1;
2910 #endif
2911 #endif
2912 }
2913
2914
current_thread_cpu_time_info(jvmtiTimerInfo * info_ptr)2915 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
2916 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
2917 info_ptr->may_skip_backward = false; // elapsed time not wall time
2918 info_ptr->may_skip_forward = false; // elapsed time not wall time
2919 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
2920 }
2921
thread_cpu_time_info(jvmtiTimerInfo * info_ptr)2922 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
2923 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
2924 info_ptr->may_skip_backward = false; // elapsed time not wall time
2925 info_ptr->may_skip_forward = false; // elapsed time not wall time
2926 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
2927 }
2928
is_thread_cpu_time_supported()2929 bool os::is_thread_cpu_time_supported() {
2930 #if defined(__APPLE__) || defined(__OpenBSD__)
2931 return true;
2932 #else
2933 return (Bsd::_getcpuclockid != NULL);
2934 #endif
2935 }
2936
2937 // System loadavg support. Returns -1 if load average cannot be obtained.
2938 // Bsd doesn't yet have a (official) notion of processor sets,
2939 // so just return the system wide load average.
loadavg(double loadavg[],int nelem)2940 int os::loadavg(double loadavg[], int nelem) {
2941 return ::getloadavg(loadavg, nelem);
2942 }
2943
pause()2944 void os::pause() {
2945 char filename[MAX_PATH];
2946 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
2947 jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
2948 } else {
2949 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
2950 }
2951
2952 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
2953 if (fd != -1) {
2954 struct stat buf;
2955 ::close(fd);
2956 while (::stat(filename, &buf) == 0) {
2957 (void)::poll(NULL, 0, 100);
2958 }
2959 } else {
2960 jio_fprintf(stderr,
2961 "Could not open pause file '%s', continuing immediately.\n", filename);
2962 }
2963 }
2964
2965 // Darwin has no "environ" in a dynamic library.
2966 #ifdef __APPLE__
2967 #include <crt_externs.h>
2968 #define environ (*_NSGetEnviron())
2969 #else
2970 extern char** environ;
2971 #endif
2972
2973 // Run the specified command in a separate process. Return its exit value,
2974 // or -1 on failure (e.g. can't fork a new process).
2975 // Unlike system(), this function can be called from signal handler. It
2976 // doesn't block SIGINT et al.
fork_and_exec(char * cmd,bool use_vfork_if_available)2977 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {
2978 const char * argv[4] = {"sh", "-c", cmd, NULL};
2979
2980 // fork() in BsdThreads/NPTL is not async-safe. It needs to run
2981 // pthread_atfork handlers and reset pthread library. All we need is a
2982 // separate process to execve. Make a direct syscall to fork process.
2983 // On IA64 there's no fork syscall, we have to use fork() and hope for
2984 // the best...
2985 pid_t pid = fork();
2986
2987 if (pid < 0) {
2988 // fork failed
2989 return -1;
2990
2991 } else if (pid == 0) {
2992 // child process
2993
2994 // execve() in BsdThreads will call pthread_kill_other_threads_np()
2995 // first to kill every thread on the thread list. Because this list is
2996 // not reset by fork() (see notes above), execve() will instead kill
2997 // every thread in the parent process. We know this is the only thread
2998 // in the new process, so make a system call directly.
2999 // IA64 should use normal execve() from glibc to match the glibc fork()
3000 // above.
3001 execve("/bin/sh", (char* const*)argv, environ);
3002
3003 // execve failed
3004 _exit(-1);
3005
3006 } else {
3007 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
3008 // care about the actual exit code, for now.
3009
3010 int status;
3011
3012 // Wait for the child process to exit. This returns immediately if
3013 // the child has already exited. */
3014 while (waitpid(pid, &status, 0) < 0) {
3015 switch (errno) {
3016 case ECHILD: return 0;
3017 case EINTR: break;
3018 default: return -1;
3019 }
3020 }
3021
3022 if (WIFEXITED(status)) {
3023 // The child exited normally; get its exit code.
3024 return WEXITSTATUS(status);
3025 } else if (WIFSIGNALED(status)) {
3026 // The child exited because of a signal
3027 // The best value to return is 0x80 + signal number,
3028 // because that is what all Unix shells do, and because
3029 // it allows callers to distinguish between process exit and
3030 // process death by signal.
3031 return 0x80 + WTERMSIG(status);
3032 } else {
3033 // Unknown exit code; pass it through
3034 return status;
3035 }
3036 }
3037 }
3038
3039 // Get the kern.corefile setting, or otherwise the default path to the core file
3040 // Returns the length of the string
get_core_path(char * buffer,size_t bufferSize)3041 int os::get_core_path(char* buffer, size_t bufferSize) {
3042 int n = 0;
3043 #ifdef __APPLE__
3044 char coreinfo[MAX_PATH];
3045 size_t sz = sizeof(coreinfo);
3046 int ret = sysctlbyname("kern.corefile", coreinfo, &sz, NULL, 0);
3047 if (ret == 0) {
3048 char *pid_pos = strstr(coreinfo, "%P");
3049 // skip over the "%P" to preserve any optional custom user pattern
3050 const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : "";
3051
3052 if (pid_pos != NULL) {
3053 *pid_pos = '\0';
3054 n = jio_snprintf(buffer, bufferSize, "%s%d%s", coreinfo, os::current_process_id(), tail);
3055 } else {
3056 n = jio_snprintf(buffer, bufferSize, "%s", coreinfo);
3057 }
3058 } else
3059 {
3060 n = jio_snprintf(buffer, bufferSize, "/cores/core.%d", os::current_process_id());
3061 }
3062 #else
3063 const char *p = get_current_directory(buffer, bufferSize);
3064
3065 if (p == NULL) {
3066 assert(p != NULL, "failed to get current directory");
3067 return 0;
3068 }
3069
3070 const char *q = getprogname();
3071
3072 if (q == NULL) {
3073 assert(q != NULL, "failed to get progname");
3074 return 0;
3075 }
3076
3077 n = strlen(buffer);
3078
3079 jio_snprintf(buffer + n, bufferSize - n, "/%s.core", q);
3080 n = strlen(buffer);
3081 #endif
3082 // Truncate if theoretical string was longer than bufferSize
3083 n = MIN2(n, (int)bufferSize);
3084
3085 return n;
3086 }
3087
supports_map_sync()3088 bool os::supports_map_sync() {
3089 return false;
3090 }
3091
3092 #ifndef PRODUCT
TestReserveMemorySpecial_test()3093 void TestReserveMemorySpecial_test() {
3094 // No tests available for this platform
3095 }
3096 #endif
3097
start_debugging(char * buf,int buflen)3098 bool os::start_debugging(char *buf, int buflen) {
3099 int len = (int)strlen(buf);
3100 char *p = &buf[len];
3101
3102 jio_snprintf(p, buflen-len,
3103 "\n\n"
3104 "Do you want to debug the problem?\n\n"
3105 "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " INTX_FORMAT " (" INTPTR_FORMAT ")\n"
3106 "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
3107 "Otherwise, press RETURN to abort...",
3108 os::current_process_id(), os::current_process_id(),
3109 os::current_thread_id(), os::current_thread_id());
3110
3111 bool yes = os::message_box("Unexpected Error", buf);
3112
3113 if (yes) {
3114 // yes, user asked VM to launch debugger
3115 jio_snprintf(buf, sizeof(buf), "gdb /proc/%d/exe %d",
3116 os::current_process_id(), os::current_process_id());
3117
3118 os::fork_and_exec(buf);
3119 yes = false;
3120 }
3121 return yes;
3122 }
3123
print_memory_mappings(char * addr,size_t bytes,outputStream * st)3124 void os::print_memory_mappings(char* addr, size_t bytes, outputStream* st) {}
3125
3126