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