-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathos.cpp
1718 lines (1534 loc) · 58.6 KB
/
os.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/icBuffer.hpp"
#include "code/vtableStubs.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
#include "interpreter/interpreter.hpp"
#include "memory/allocation.inline.hpp"
#ifdef ASSERT
#include "memory/guardedMemory.hpp"
#endif
#include "oops/oop.inline.hpp"
#include "prims/jvm.h"
#include "prims/jvm_misc.hpp"
#include "prims/privilegedStack.hpp"
#include "runtime/arguments.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/os.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.inline.hpp"
#include "services/attachListener.hpp"
#include "services/nmtCommon.hpp"
#include "services/mallocTracker.hpp"
#include "services/memTracker.hpp"
#include "services/threadService.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
# include <signal.h>
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
OSThread* os::_starting_thread = NULL;
address os::_polling_page = NULL;
volatile int32_t* os::_mem_serialize_page = NULL;
uintptr_t os::_serialize_page_mask = 0;
long os::_rand_seed = 1;
int os::_processor_count = 0;
int os::_initial_active_processor_count = 0;
size_t os::_page_sizes[os::page_sizes_max];
#ifndef PRODUCT
julong os::num_mallocs = 0; // # of calls to malloc/realloc
julong os::alloc_bytes = 0; // # of bytes allocated
julong os::num_frees = 0; // # of calls to free
julong os::free_bytes = 0; // # of bytes freed
#endif
static juint cur_malloc_words = 0; // current size for MallocMaxTestWords
void os_init_globals() {
// Called from init_globals().
// See Threads::create_vm() in thread.cpp, and init.cpp.
os::init_globals();
}
int os::snprintf(char* buf, size_t len, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
int result = os::vsnprintf(buf, len, fmt, args);
va_end(args);
return result;
}
// Fill in buffer with current local time as an ISO-8601 string.
// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
// Returns buffer, or NULL if it failed.
// This would mostly be a call to
// strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
// except that on Windows the %z behaves badly, so we do it ourselves.
// Also, people wanted milliseconds on there,
// and strftime doesn't do milliseconds.
char* os::iso8601_time(char* buffer, size_t buffer_length) {
// Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
// 1 2
// 12345678901234567890123456789
static const char* iso8601_format =
"%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
static const size_t needed_buffer = 29;
// Sanity check the arguments
if (buffer == NULL) {
assert(false, "NULL buffer");
return NULL;
}
if (buffer_length < needed_buffer) {
assert(false, "buffer_length too small");
return NULL;
}
// Get the current time
jlong milliseconds_since_19700101 = javaTimeMillis();
const int milliseconds_per_microsecond = 1000;
const time_t seconds_since_19700101 =
milliseconds_since_19700101 / milliseconds_per_microsecond;
const int milliseconds_after_second =
milliseconds_since_19700101 % milliseconds_per_microsecond;
// Convert the time value to a tm and timezone variable
struct tm time_struct;
if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
assert(false, "Failed localtime_pd");
return NULL;
}
const time_t seconds_per_minute = 60;
const time_t minutes_per_hour = 60;
const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
time_t UTC_to_local = 0;
#if defined(_ALLBSD_SOURCE) || defined(_GNU_SOURCE)
UTC_to_local = -(time_struct.tm_gmtoff);
#elif defined(_WINDOWS)
long zone;
_get_timezone(&zone);
UTC_to_local = static_cast<time_t>(zone);
#else
UTC_to_local = timezone;
#endif
// tm_gmtoff already includes adjustment for daylight saving
#if !defined(_ALLBSD_SOURCE) && !defined(_GNU_SOURCE)
// If daylight savings time is in effect,
// we are 1 hour East of our time zone
if (time_struct.tm_isdst > 0) {
UTC_to_local = UTC_to_local - seconds_per_hour;
}
#endif
// Compute the time zone offset.
// localtime_pd() sets timezone to the difference (in seconds)
// between UTC and and local time.
// ISO 8601 says we need the difference between local time and UTC,
// we change the sign of the localtime_pd() result.
const time_t local_to_UTC = -(UTC_to_local);
// Then we have to figure out if if we are ahead (+) or behind (-) UTC.
char sign_local_to_UTC = '+';
time_t abs_local_to_UTC = local_to_UTC;
if (local_to_UTC < 0) {
sign_local_to_UTC = '-';
abs_local_to_UTC = -(abs_local_to_UTC);
}
// Convert time zone offset seconds to hours and minutes.
const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
const time_t zone_min =
((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
// Print an ISO 8601 date and time stamp into the buffer
const int year = 1900 + time_struct.tm_year;
const int month = 1 + time_struct.tm_mon;
const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
year,
month,
time_struct.tm_mday,
time_struct.tm_hour,
time_struct.tm_min,
time_struct.tm_sec,
milliseconds_after_second,
sign_local_to_UTC,
zone_hours,
zone_min);
if (printed == 0) {
assert(false, "Failed jio_printf");
return NULL;
}
return buffer;
}
OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
#ifdef ASSERT
if (!(!thread->is_Java_thread() ||
Thread::current() == thread ||
Threads_lock->owned_by_self()
|| thread->is_Compiler_thread()
)) {
assert(false, "possibility of dangling Thread pointer");
}
#endif
if (p >= MinPriority && p <= MaxPriority) {
int priority = java_to_os_priority[p];
return set_native_priority(thread, priority);
} else {
assert(false, "Should not happen");
return OS_ERR;
}
}
// The mapping from OS priority back to Java priority may be inexact because
// Java priorities can map M:1 with native priorities. If you want the definite
// Java priority then use JavaThread::java_priority()
OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
int p;
int os_prio;
OSReturn ret = get_native_priority(thread, &os_prio);
if (ret != OS_OK) return ret;
if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
} else {
// niceness values are in reverse order
for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
}
priority = (ThreadPriority)p;
return OS_OK;
}
// --------------------- sun.misc.Signal (optional) ---------------------
// SIGBREAK is sent by the keyboard to query the VM state
#ifndef SIGBREAK
#define SIGBREAK SIGQUIT
#endif
// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
static void signal_thread_entry(JavaThread* thread, TRAPS) {
os::set_priority(thread, NearMaxPriority);
while (true) {
int sig;
{
// FIXME : Currently we have not decieded what should be the status
// for this java thread blocked here. Once we decide about
// that we should fix this.
sig = os::signal_wait();
}
if (sig == os::sigexitnum_pd()) {
// Terminate the signal thread
return;
}
switch (sig) {
case SIGBREAK: {
#if INCLUDE_SERVICES
// Check if the signal is a trigger to start the Attach Listener - in that
// case don't print stack traces.
if (!DisableAttachMechanism) {
// Attempt to transit state to AL_INITIALIZING.
jlong cur_state = AttachListener::transit_state(AL_INITIALIZING, AL_NOT_INITIALIZED);
if (cur_state == AL_INITIALIZING) {
// Attach Listener has been started to initialize. Ignore this signal.
continue;
} else if (cur_state == AL_NOT_INITIALIZED) {
// Start to initialize.
if (AttachListener::is_init_trigger()) {
// Attach Listener has been initialized.
// Accept subsequent request.
continue;
} else {
// Attach Listener could not be started.
// So we need to transit the state to AL_NOT_INITIALIZED.
AttachListener::set_state(AL_NOT_INITIALIZED);
}
} else if (AttachListener::check_socket_file()) {
// Attach Listener has been started, but unix domain socket file
// does not exist. So restart Attach Listener.
continue;
}
}
#endif
// Print stack traces
// Any SIGBREAK operations added here should make sure to flush
// the output stream (e.g. tty->flush()) after output. See 4803766.
// Each module also prints an extra carriage return after its output.
VM_PrintThreads op;
VMThread::execute(&op);
VM_PrintJNI jni_op;
VMThread::execute(&jni_op);
VM_FindDeadlocks op1(tty);
VMThread::execute(&op1);
Universe::print_heap_at_SIGBREAK();
if (PrintClassHistogram) {
VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
VMThread::execute(&op1);
}
if (JvmtiExport::should_post_data_dump()) {
JvmtiExport::post_data_dump();
}
break;
}
default: {
// Dispatch the signal to java
HandleMark hm(THREAD);
Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
KlassHandle klass (THREAD, k);
if (klass.not_null()) {
JavaValue result(T_VOID);
JavaCallArguments args;
args.push_int(sig);
JavaCalls::call_static(
&result,
klass,
vmSymbols::dispatch_name(),
vmSymbols::int_void_signature(),
&args,
THREAD
);
}
if (HAS_PENDING_EXCEPTION) {
// tty is initialized early so we don't expect it to be null, but
// if it is we can't risk doing an initialization that might
// trigger additional out-of-memory conditions
if (tty != NULL) {
char klass_name[256];
char tmp_sig_name[16];
const char* sig_name = "UNKNOWN";
InstanceKlass::cast(PENDING_EXCEPTION->klass())->
name()->as_klass_external_name(klass_name, 256);
if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
sig_name = tmp_sig_name;
warning("Exception %s occurred dispatching signal %s to handler"
"- the VM may need to be forcibly terminated",
klass_name, sig_name );
}
CLEAR_PENDING_EXCEPTION;
}
}
}
}
}
void os::init_before_ergo() {
initialize_initial_active_processor_count();
// We need to initialize large page support here because ergonomics takes some
// decisions depending on large page support and the calculated large page size.
large_page_init();
// VM version initialization identifies some characteristics of the
// the platform that are used during ergonomic decisions.
VM_Version::init_before_ergo();
}
void os::signal_init() {
if (!ReduceSignalUsage) {
// Setup JavaThread for processing signals
EXCEPTION_MARK;
Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
instanceKlassHandle klass (THREAD, k);
instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
const char thread_name[] = "Signal Dispatcher";
Handle string = java_lang_String::create_from_str(thread_name, CHECK);
// Initialize thread_oop to put it into the system threadGroup
Handle thread_group (THREAD, Universe::system_thread_group());
JavaValue result(T_VOID);
JavaCalls::call_special(&result, thread_oop,
klass,
vmSymbols::object_initializer_name(),
vmSymbols::threadgroup_string_void_signature(),
thread_group,
string,
CHECK);
KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
JavaCalls::call_special(&result,
thread_group,
group,
vmSymbols::add_method_name(),
vmSymbols::thread_void_signature(),
thread_oop, // ARG 1
CHECK);
os::signal_init_pd();
{ MutexLocker mu(Threads_lock);
JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
// At this point it may be possible that no osthread was created for the
// JavaThread due to lack of memory. We would have to throw an exception
// in that case. However, since this must work and we do not allow
// exceptions anyway, check and abort if this fails.
if (signal_thread == NULL || signal_thread->osthread() == NULL) {
vm_exit_during_initialization("java.lang.OutOfMemoryError",
"unable to create new native thread");
}
java_lang_Thread::set_thread(thread_oop(), signal_thread);
java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
java_lang_Thread::set_daemon(thread_oop());
signal_thread->set_threadObj(thread_oop());
Threads::add(signal_thread);
Thread::start(signal_thread);
}
// Handle ^BREAK
os::signal(SIGBREAK, os::user_handler());
}
}
void os::terminate_signal_thread() {
if (!ReduceSignalUsage)
signal_notify(sigexitnum_pd());
}
// --------------------- loading libraries ---------------------
typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
extern struct JavaVM_ main_vm;
static void* _native_java_library = NULL;
void* os::native_java_library() {
if (_native_java_library == NULL) {
char buffer[JVM_MAXPATHLEN];
char ebuf[1024];
// Try to load verify dll first. In 1.3 java dll depends on it and is not
// always able to find it when the loading executable is outside the JDK.
// In order to keep working with 1.2 we ignore any loading errors.
if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
"verify")) {
dll_load(buffer, ebuf, sizeof(ebuf));
}
// Load java dll
if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
"java")) {
_native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
}
if (_native_java_library == NULL) {
vm_exit_during_initialization("Unable to load native library", ebuf);
}
#if defined(__OpenBSD__)
// Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
// ignore errors
if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
"net")) {
dll_load(buffer, ebuf, sizeof(ebuf));
}
#endif
}
static jboolean onLoaded = JNI_FALSE;
if (onLoaded) {
// We may have to wait to fire OnLoad until TLS is initialized.
if (ThreadLocalStorage::is_initialized()) {
// The JNI_OnLoad handling is normally done by method load in
// java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
// explicitly so we have to check for JNI_OnLoad as well
const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
if (JNI_OnLoad != NULL) {
JavaThread* thread = JavaThread::current();
ThreadToNativeFromVM ttn(thread);
HandleMark hm(thread);
jint ver = (*JNI_OnLoad)(&main_vm, NULL);
onLoaded = JNI_TRUE;
if (!Threads::is_supported_jni_version_including_1_1(ver)) {
vm_exit_during_initialization("Unsupported JNI version");
}
}
}
}
return _native_java_library;
}
/*
* Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
* If check_lib == true then we are looking for an
* Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
* this library is statically linked into the image.
* If check_lib == false then we will look for the appropriate symbol in the
* executable if agent_lib->is_static_lib() == true or in the shared library
* referenced by 'handle'.
*/
void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
const char *syms[], size_t syms_len) {
assert(agent_lib != NULL, "sanity check");
const char *lib_name;
void *handle = agent_lib->os_lib();
void *entryName = NULL;
char *agent_function_name;
size_t i;
// If checking then use the agent name otherwise test is_static_lib() to
// see how to process this lookup
lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
for (i = 0; i < syms_len; i++) {
agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
if (agent_function_name == NULL) {
break;
}
entryName = dll_lookup(handle, agent_function_name);
FREE_C_HEAP_ARRAY(char, agent_function_name, mtThread);
if (entryName != NULL) {
break;
}
}
return entryName;
}
// See if the passed in agent is statically linked into the VM image.
bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
size_t syms_len) {
void *ret;
void *proc_handle;
void *save_handle;
assert(agent_lib != NULL, "sanity check");
if (agent_lib->name() == NULL) {
return false;
}
proc_handle = get_default_process_handle();
// Check for Agent_OnLoad/Attach_lib_name function
save_handle = agent_lib->os_lib();
// We want to look in this process' symbol table.
agent_lib->set_os_lib(proc_handle);
ret = find_agent_function(agent_lib, true, syms, syms_len);
if (ret != NULL) {
// Found an entry point like Agent_OnLoad_lib_name so we have a static agent
agent_lib->set_valid();
agent_lib->set_static_lib(true);
return true;
}
agent_lib->set_os_lib(save_handle);
return false;
}
// --------------------- heap allocation utilities ---------------------
char *os::strdup(const char *str, MEMFLAGS flags) {
size_t size = strlen(str);
char *dup_str = (char *)malloc(size + 1, flags);
if (dup_str == NULL) return NULL;
strcpy(dup_str, str);
return dup_str;
}
#define paranoid 0 /* only set to 1 if you suspect checking code has bug */
#ifdef ASSERT
static void verify_memory(void* ptr) {
GuardedMemory guarded(ptr);
if (!guarded.verify_guards()) {
tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
tty->print_cr("## memory stomp:");
guarded.print_on(tty);
fatal("memory stomping error");
}
}
#endif
//
// This function supports testing of the malloc out of memory
// condition without really running the system out of memory.
//
static u_char* testMalloc(size_t alloc_size) {
assert(MallocMaxTestWords > 0, "sanity check");
if ((cur_malloc_words + (alloc_size / BytesPerWord)) > MallocMaxTestWords) {
return NULL;
}
u_char* ptr = (u_char*)::malloc(alloc_size);
if (ptr != NULL) {
Atomic::add(((jint) (alloc_size / BytesPerWord)),
(volatile jint *) &cur_malloc_words);
}
return ptr;
}
void* os::malloc(size_t size, MEMFLAGS flags) {
return os::malloc(size, flags, CALLER_PC);
}
void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
// Since os::malloc can be called when the libjvm.{dll,so} is
// first loaded and we don't have a thread yet we must accept NULL also here.
assert(!os::ThreadCrashProtection::is_crash_protected(ThreadLocalStorage::thread()),
"malloc() not allowed when crash protection is set");
if (size == 0) {
// return a valid pointer if size is zero
// if NULL is returned the calling functions assume out of memory.
size = 1;
}
// NMT support
NMT_TrackingLevel level = MemTracker::tracking_level();
size_t nmt_header_size = MemTracker::malloc_header_size(level);
#ifndef ASSERT
const size_t alloc_size = size + nmt_header_size;
#else
const size_t alloc_size = GuardedMemory::get_total_size(size + nmt_header_size);
if (size + nmt_header_size > alloc_size) { // Check for rollover.
return NULL;
}
#endif
NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
u_char* ptr;
if (MallocMaxTestWords > 0) {
ptr = testMalloc(alloc_size);
} else {
ptr = (u_char*)::malloc(alloc_size);
}
#ifdef ASSERT
if (ptr == NULL) {
return NULL;
}
// Wrap memory with guard
GuardedMemory guarded(ptr, size + nmt_header_size);
ptr = guarded.get_user_ptr();
#endif
if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
breakpoint();
}
debug_only(if (paranoid) verify_memory(ptr));
if (PrintMalloc && tty != NULL) {
tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
}
// we do not track guard memory
return MemTracker::record_malloc((address)ptr, size, memflags, stack, level);
}
void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
return os::realloc(memblock, size, flags, CALLER_PC);
}
void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
#ifndef ASSERT
NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
// NMT support
void* membase = MemTracker::record_free(memblock);
NMT_TrackingLevel level = MemTracker::tracking_level();
size_t nmt_header_size = MemTracker::malloc_header_size(level);
void* ptr = ::realloc(membase, size + nmt_header_size);
return MemTracker::record_malloc(ptr, size, memflags, stack, level);
#else
if (memblock == NULL) {
return os::malloc(size, memflags, stack);
}
if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
breakpoint();
}
// NMT support
void* membase = MemTracker::malloc_base(memblock);
verify_memory(membase);
NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
if (size == 0) {
return NULL;
}
// always move the block
void* ptr = os::malloc(size, memflags, stack);
if (PrintMalloc) {
tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
}
// Copy to new memory if malloc didn't fail
if ( ptr != NULL ) {
GuardedMemory guarded(MemTracker::malloc_base(memblock));
// Guard's user data contains NMT header
size_t memblock_size = guarded.get_user_size() - MemTracker::malloc_header_size(memblock);
memcpy(ptr, memblock, MIN2(size, memblock_size));
if (paranoid) verify_memory(MemTracker::malloc_base(ptr));
if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
breakpoint();
}
os::free(memblock);
}
return ptr;
#endif
}
void os::free(void *memblock, MEMFLAGS memflags) {
NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
#ifdef ASSERT
if (memblock == NULL) return;
if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
breakpoint();
}
void* membase = MemTracker::record_free(memblock);
verify_memory(membase);
NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
GuardedMemory guarded(membase);
size_t size = guarded.get_user_size();
inc_stat_counter(&free_bytes, size);
membase = guarded.release_for_freeing();
if (PrintMalloc && tty != NULL) {
fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)membase);
}
::free(membase);
#else
void* membase = MemTracker::record_free(memblock);
::free(membase);
#endif
}
void os::init_random(long initval) {
_rand_seed = initval;
}
long os::random() {
/* standard, well-known linear congruential random generator with
* next_rand = (16807*seed) mod (2**31-1)
* see
* (1) "Random Number Generators: Good Ones Are Hard to Find",
* S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
* (2) "Two Fast Implementations of the 'Minimal Standard' Random
* Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
*/
const long a = 16807;
const unsigned long m = 2147483647;
const long q = m / a; assert(q == 127773, "weird math");
const long r = m % a; assert(r == 2836, "weird math");
// compute az=2^31p+q
unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
lo += (hi & 0x7FFF) << 16;
// if q overflowed, ignore the overflow and increment q
if (lo > m) {
lo &= m;
++lo;
}
lo += hi >> 15;
// if (p+q) overflowed, ignore the overflow and increment (p+q)
if (lo > m) {
lo &= m;
++lo;
}
return (_rand_seed = lo);
}
// The INITIALIZED state is distinguished from the SUSPENDED state because the
// conditions in which a thread is first started are different from those in which
// a suspension is resumed. These differences make it hard for us to apply the
// tougher checks when starting threads that we want to do when resuming them.
// However, when start_thread is called as a result of Thread.start, on a Java
// thread, the operation is synchronized on the Java Thread object. So there
// cannot be a race to start the thread and hence for the thread to exit while
// we are working on it. Non-Java threads that start Java threads either have
// to do so in a context in which races are impossible, or should do appropriate
// locking.
void os::start_thread(Thread* thread) {
// guard suspend/resume
MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
OSThread* osthread = thread->osthread();
osthread->set_state(RUNNABLE);
pd_start_thread(thread);
}
//---------------------------------------------------------------------------
// Helper functions for fatal error handler
void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
int cols = 0;
int cols_per_line = 0;
switch (unitsize) {
case 1: cols_per_line = 16; break;
case 2: cols_per_line = 8; break;
case 4: cols_per_line = 4; break;
case 8: cols_per_line = 2; break;
default: return;
}
address p = start;
st->print(PTR_FORMAT ": ", start);
while (p < end) {
switch (unitsize) {
case 1: st->print("%02x", *(u1*)p); break;
case 2: st->print("%04x", *(u2*)p); break;
case 4: st->print("%08x", *(u4*)p); break;
case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
}
p += unitsize;
cols++;
if (cols >= cols_per_line && p < end) {
cols = 0;
st->cr();
st->print(PTR_FORMAT ": ", p);
} else {
st->print(" ");
}
}
st->cr();
}
void os::print_environment_variables(outputStream* st, const char** env_list,
char* buffer, int len) {
if (env_list) {
st->print_cr("Environment Variables:");
for (int i = 0; env_list[i] != NULL; i++) {
if (getenv(env_list[i], buffer, len)) {
st->print("%s", env_list[i]);
st->print("=");
st->print_cr("%s", buffer);
}
}
}
}
void os::print_cpu_info(outputStream* st) {
// cpu
st->print("CPU:");
st->print("total %d", os::processor_count());
// It's not safe to query number of active processors after crash
// st->print("(active %d)", os::active_processor_count()); but we can
// print the initial number of active processors.
// We access the raw value here because the assert in the accessor will
// fail if the crash occurs before initialization of this value.
st->print(" (initial active %d)", _initial_active_processor_count);
st->print(" %s", VM_Version::cpu_features());
st->cr();
pd_print_cpu_info(st);
}
void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
const int secs_per_day = 86400;
const int secs_per_hour = 3600;
const int secs_per_min = 60;
time_t tloc;
(void)time(&tloc);
st->print("time: %s", ctime(&tloc)); // ctime adds newline.
struct tm tz;
if (localtime_pd(&tloc, &tz) != NULL) {
::strftime(buf, buflen, "%Z", &tz);
st->print_cr("timezone: %s", buf);
}
double t = os::elapsedTime();
// NOTE: a crash using printf("%f",...) on Linux was historically noted here.
int eltime = (int)t; // elapsed time in seconds
int eltimeFraction = (int) ((t - eltime) * 1000000);
// print elapsed time in a human-readable format:
int eldays = eltime / secs_per_day;
int day_secs = eldays * secs_per_day;
int elhours = (eltime - day_secs) / secs_per_hour;
int hour_secs = elhours * secs_per_hour;
int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
int minute_secs = elmins * secs_per_min;
int elsecs = (eltime - day_secs - hour_secs - minute_secs);
st->print_cr("elapsed time: %d.%06d seconds (%dd %dh %dm %ds)", eltime, eltimeFraction, eldays, elhours, elmins, elsecs);
}
// moved from debug.cpp (used to be find()) but still called from there
// The verbose parameter is only set by the debug code in one case
void os::print_location(outputStream* st, intptr_t x, bool verbose) {
address addr = (address)x;
CodeBlob* b = CodeCache::find_blob_unsafe(addr);
if (b != NULL) {
if (b->is_buffer_blob()) {
// the interpreter is generated into a buffer blob
InterpreterCodelet* i = Interpreter::codelet_containing(addr);
if (i != NULL) {
st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
i->print_on(st);
return;
}
if (Interpreter::contains(addr)) {
st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
" (not bytecode specific)", addr);
return;
}
//
if (AdapterHandlerLibrary::contains(b)) {
st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
AdapterHandlerLibrary::print_handler_on(st, b);
}
// the stubroutines are generated into a buffer blob
StubCodeDesc* d = StubCodeDesc::desc_for(addr);
if (d != NULL) {
st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
d->print_on(st);
st->cr();
return;
}
if (StubRoutines::contains(addr)) {
st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
"stub routine", addr);
return;
}
// the InlineCacheBuffer is using stubs generated into a buffer blob
if (InlineCacheBuffer::contains(addr)) {
st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
return;
}
VtableStub* v = VtableStubs::stub_containing(addr);
if (v != NULL) {
st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
v->print_on(st);
st->cr();
return;
}
}
nmethod* nm = b->as_nmethod_or_null();
if (nm != NULL) {
ResourceMark rm;
st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
addr, (int)(addr - nm->entry_point()), nm);
if (verbose) {
st->print(" for ");
nm->method()->print_value_on(st);
}
st->cr();
nm->print_nmethod(verbose);
return;
}
st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
b->print_on(st);
return;
}
if (Universe::heap()->is_in(addr)) {
HeapWord* p = Universe::heap()->block_start(addr);
bool print = false;
// If we couldn't find it it just may mean that heap wasn't parseable
// See if we were just given an oop directly
if (p != NULL && Universe::heap()->block_is_obj(p)) {
print = true;
} else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
p = (HeapWord*) addr;
print = true;
}
if (print) {
if (p == (HeapWord*) addr) {
st->print_cr(INTPTR_FORMAT " is an oop", addr);
} else {
st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
}
oop(p)->print_on(st);
return;
}
} else {
if (Universe::heap()->is_in_reserved(addr)) {
st->print_cr(INTPTR_FORMAT " is an unallocated location "