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