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