Mon, 09 Mar 2020 12:54:53 +0000
8240295: hs_err elapsed time in seconds is not accurate enough
Reviewed-by: dholmes, sspitsyn
1 /*
2 * Copyright (c) 1997, 2018, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/icBuffer.hpp"
31 #include "code/vtableStubs.hpp"
32 #include "gc_implementation/shared/vmGCOperations.hpp"
33 #include "interpreter/interpreter.hpp"
34 #include "memory/allocation.inline.hpp"
35 #ifdef ASSERT
36 #include "memory/guardedMemory.hpp"
37 #endif
38 #include "oops/oop.inline.hpp"
39 #include "prims/jvm.h"
40 #include "prims/jvm_misc.hpp"
41 #include "prims/privilegedStack.hpp"
42 #include "runtime/arguments.hpp"
43 #include "runtime/frame.inline.hpp"
44 #include "runtime/interfaceSupport.hpp"
45 #include "runtime/java.hpp"
46 #include "runtime/javaCalls.hpp"
47 #include "runtime/mutexLocker.hpp"
48 #include "runtime/os.hpp"
49 #include "runtime/stubRoutines.hpp"
50 #include "runtime/thread.inline.hpp"
51 #include "services/attachListener.hpp"
52 #include "services/nmtCommon.hpp"
53 #include "services/mallocTracker.hpp"
54 #include "services/memTracker.hpp"
55 #include "services/threadService.hpp"
56 #include "utilities/defaultStream.hpp"
57 #include "utilities/events.hpp"
58 #ifdef TARGET_OS_FAMILY_linux
59 # include "os_linux.inline.hpp"
60 #endif
61 #ifdef TARGET_OS_FAMILY_solaris
62 # include "os_solaris.inline.hpp"
63 #endif
64 #ifdef TARGET_OS_FAMILY_windows
65 # include "os_windows.inline.hpp"
66 #endif
67 #ifdef TARGET_OS_FAMILY_bsd
68 # include "os_bsd.inline.hpp"
69 #endif
71 # include <signal.h>
73 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
75 OSThread* os::_starting_thread = NULL;
76 address os::_polling_page = NULL;
77 volatile int32_t* os::_mem_serialize_page = NULL;
78 uintptr_t os::_serialize_page_mask = 0;
79 long os::_rand_seed = 1;
80 int os::_processor_count = 0;
81 int os::_initial_active_processor_count = 0;
82 size_t os::_page_sizes[os::page_sizes_max];
84 #ifndef PRODUCT
85 julong os::num_mallocs = 0; // # of calls to malloc/realloc
86 julong os::alloc_bytes = 0; // # of bytes allocated
87 julong os::num_frees = 0; // # of calls to free
88 julong os::free_bytes = 0; // # of bytes freed
89 #endif
91 static juint cur_malloc_words = 0; // current size for MallocMaxTestWords
93 void os_init_globals() {
94 // Called from init_globals().
95 // See Threads::create_vm() in thread.cpp, and init.cpp.
96 os::init_globals();
97 }
99 static time_t get_timezone(const struct tm* time_struct) {
100 #if defined(_ALLBSD_SOURCE)
101 return time_struct->tm_gmtoff;
102 #elif defined(_WINDOWS)
103 long zone;
104 _get_timezone(&zone);
105 return static_cast<time_t>(zone);
106 #else
107 return timezone;
108 #endif
109 }
111 int os::snprintf(char* buf, size_t len, const char* fmt, ...) {
112 va_list args;
113 va_start(args, fmt);
114 int result = os::vsnprintf(buf, len, fmt, args);
115 va_end(args);
116 return result;
117 }
119 // Fill in buffer with current local time as an ISO-8601 string.
120 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
121 // Returns buffer, or NULL if it failed.
122 // This would mostly be a call to
123 // strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
124 // except that on Windows the %z behaves badly, so we do it ourselves.
125 // Also, people wanted milliseconds on there,
126 // and strftime doesn't do milliseconds.
127 char* os::iso8601_time(char* buffer, size_t buffer_length) {
128 // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
129 // 1 2
130 // 12345678901234567890123456789
131 static const char* iso8601_format =
132 "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
133 static const size_t needed_buffer = 29;
135 // Sanity check the arguments
136 if (buffer == NULL) {
137 assert(false, "NULL buffer");
138 return NULL;
139 }
140 if (buffer_length < needed_buffer) {
141 assert(false, "buffer_length too small");
142 return NULL;
143 }
144 // Get the current time
145 jlong milliseconds_since_19700101 = javaTimeMillis();
146 const int milliseconds_per_microsecond = 1000;
147 const time_t seconds_since_19700101 =
148 milliseconds_since_19700101 / milliseconds_per_microsecond;
149 const int milliseconds_after_second =
150 milliseconds_since_19700101 % milliseconds_per_microsecond;
151 // Convert the time value to a tm and timezone variable
152 struct tm time_struct;
153 if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
154 assert(false, "Failed localtime_pd");
155 return NULL;
156 }
157 const time_t zone = get_timezone(&time_struct);
159 // If daylight savings time is in effect,
160 // we are 1 hour East of our time zone
161 const time_t seconds_per_minute = 60;
162 const time_t minutes_per_hour = 60;
163 const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
164 time_t UTC_to_local = zone;
165 if (time_struct.tm_isdst > 0) {
166 UTC_to_local = UTC_to_local - seconds_per_hour;
167 }
168 // Compute the time zone offset.
169 // localtime_pd() sets timezone to the difference (in seconds)
170 // between UTC and and local time.
171 // ISO 8601 says we need the difference between local time and UTC,
172 // we change the sign of the localtime_pd() result.
173 const time_t local_to_UTC = -(UTC_to_local);
174 // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
175 char sign_local_to_UTC = '+';
176 time_t abs_local_to_UTC = local_to_UTC;
177 if (local_to_UTC < 0) {
178 sign_local_to_UTC = '-';
179 abs_local_to_UTC = -(abs_local_to_UTC);
180 }
181 // Convert time zone offset seconds to hours and minutes.
182 const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
183 const time_t zone_min =
184 ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
186 // Print an ISO 8601 date and time stamp into the buffer
187 const int year = 1900 + time_struct.tm_year;
188 const int month = 1 + time_struct.tm_mon;
189 const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
190 year,
191 month,
192 time_struct.tm_mday,
193 time_struct.tm_hour,
194 time_struct.tm_min,
195 time_struct.tm_sec,
196 milliseconds_after_second,
197 sign_local_to_UTC,
198 zone_hours,
199 zone_min);
200 if (printed == 0) {
201 assert(false, "Failed jio_printf");
202 return NULL;
203 }
204 return buffer;
205 }
207 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
208 #ifdef ASSERT
209 if (!(!thread->is_Java_thread() ||
210 Thread::current() == thread ||
211 Threads_lock->owned_by_self()
212 || thread->is_Compiler_thread()
213 )) {
214 assert(false, "possibility of dangling Thread pointer");
215 }
216 #endif
218 if (p >= MinPriority && p <= MaxPriority) {
219 int priority = java_to_os_priority[p];
220 return set_native_priority(thread, priority);
221 } else {
222 assert(false, "Should not happen");
223 return OS_ERR;
224 }
225 }
227 // The mapping from OS priority back to Java priority may be inexact because
228 // Java priorities can map M:1 with native priorities. If you want the definite
229 // Java priority then use JavaThread::java_priority()
230 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
231 int p;
232 int os_prio;
233 OSReturn ret = get_native_priority(thread, &os_prio);
234 if (ret != OS_OK) return ret;
236 if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
237 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
238 } else {
239 // niceness values are in reverse order
240 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
241 }
242 priority = (ThreadPriority)p;
243 return OS_OK;
244 }
247 // --------------------- sun.misc.Signal (optional) ---------------------
250 // SIGBREAK is sent by the keyboard to query the VM state
251 #ifndef SIGBREAK
252 #define SIGBREAK SIGQUIT
253 #endif
255 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
258 static void signal_thread_entry(JavaThread* thread, TRAPS) {
259 os::set_priority(thread, NearMaxPriority);
260 while (true) {
261 int sig;
262 {
263 // FIXME : Currently we have not decieded what should be the status
264 // for this java thread blocked here. Once we decide about
265 // that we should fix this.
266 sig = os::signal_wait();
267 }
268 if (sig == os::sigexitnum_pd()) {
269 // Terminate the signal thread
270 return;
271 }
273 switch (sig) {
274 case SIGBREAK: {
275 // Check if the signal is a trigger to start the Attach Listener - in that
276 // case don't print stack traces.
277 if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
278 continue;
279 }
280 // Print stack traces
281 // Any SIGBREAK operations added here should make sure to flush
282 // the output stream (e.g. tty->flush()) after output. See 4803766.
283 // Each module also prints an extra carriage return after its output.
284 VM_PrintThreads op;
285 VMThread::execute(&op);
286 VM_PrintJNI jni_op;
287 VMThread::execute(&jni_op);
288 VM_FindDeadlocks op1(tty);
289 VMThread::execute(&op1);
290 Universe::print_heap_at_SIGBREAK();
291 if (PrintClassHistogram) {
292 VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
293 VMThread::execute(&op1);
294 }
295 if (JvmtiExport::should_post_data_dump()) {
296 JvmtiExport::post_data_dump();
297 }
298 break;
299 }
300 default: {
301 // Dispatch the signal to java
302 HandleMark hm(THREAD);
303 Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
304 KlassHandle klass (THREAD, k);
305 if (klass.not_null()) {
306 JavaValue result(T_VOID);
307 JavaCallArguments args;
308 args.push_int(sig);
309 JavaCalls::call_static(
310 &result,
311 klass,
312 vmSymbols::dispatch_name(),
313 vmSymbols::int_void_signature(),
314 &args,
315 THREAD
316 );
317 }
318 if (HAS_PENDING_EXCEPTION) {
319 // tty is initialized early so we don't expect it to be null, but
320 // if it is we can't risk doing an initialization that might
321 // trigger additional out-of-memory conditions
322 if (tty != NULL) {
323 char klass_name[256];
324 char tmp_sig_name[16];
325 const char* sig_name = "UNKNOWN";
326 InstanceKlass::cast(PENDING_EXCEPTION->klass())->
327 name()->as_klass_external_name(klass_name, 256);
328 if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
329 sig_name = tmp_sig_name;
330 warning("Exception %s occurred dispatching signal %s to handler"
331 "- the VM may need to be forcibly terminated",
332 klass_name, sig_name );
333 }
334 CLEAR_PENDING_EXCEPTION;
335 }
336 }
337 }
338 }
339 }
341 void os::init_before_ergo() {
342 initialize_initial_active_processor_count();
343 // We need to initialize large page support here because ergonomics takes some
344 // decisions depending on large page support and the calculated large page size.
345 large_page_init();
347 // VM version initialization identifies some characteristics of the
348 // the platform that are used during ergonomic decisions.
349 VM_Version::init_before_ergo();
350 }
352 void os::signal_init() {
353 if (!ReduceSignalUsage) {
354 // Setup JavaThread for processing signals
355 EXCEPTION_MARK;
356 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
357 instanceKlassHandle klass (THREAD, k);
358 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
360 const char thread_name[] = "Signal Dispatcher";
361 Handle string = java_lang_String::create_from_str(thread_name, CHECK);
363 // Initialize thread_oop to put it into the system threadGroup
364 Handle thread_group (THREAD, Universe::system_thread_group());
365 JavaValue result(T_VOID);
366 JavaCalls::call_special(&result, thread_oop,
367 klass,
368 vmSymbols::object_initializer_name(),
369 vmSymbols::threadgroup_string_void_signature(),
370 thread_group,
371 string,
372 CHECK);
374 KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
375 JavaCalls::call_special(&result,
376 thread_group,
377 group,
378 vmSymbols::add_method_name(),
379 vmSymbols::thread_void_signature(),
380 thread_oop, // ARG 1
381 CHECK);
383 os::signal_init_pd();
385 { MutexLocker mu(Threads_lock);
386 JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
388 // At this point it may be possible that no osthread was created for the
389 // JavaThread due to lack of memory. We would have to throw an exception
390 // in that case. However, since this must work and we do not allow
391 // exceptions anyway, check and abort if this fails.
392 if (signal_thread == NULL || signal_thread->osthread() == NULL) {
393 vm_exit_during_initialization("java.lang.OutOfMemoryError",
394 "unable to create new native thread");
395 }
397 java_lang_Thread::set_thread(thread_oop(), signal_thread);
398 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
399 java_lang_Thread::set_daemon(thread_oop());
401 signal_thread->set_threadObj(thread_oop());
402 Threads::add(signal_thread);
403 Thread::start(signal_thread);
404 }
405 // Handle ^BREAK
406 os::signal(SIGBREAK, os::user_handler());
407 }
408 }
411 void os::terminate_signal_thread() {
412 if (!ReduceSignalUsage)
413 signal_notify(sigexitnum_pd());
414 }
417 // --------------------- loading libraries ---------------------
419 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
420 extern struct JavaVM_ main_vm;
422 static void* _native_java_library = NULL;
424 void* os::native_java_library() {
425 if (_native_java_library == NULL) {
426 char buffer[JVM_MAXPATHLEN];
427 char ebuf[1024];
429 // Try to load verify dll first. In 1.3 java dll depends on it and is not
430 // always able to find it when the loading executable is outside the JDK.
431 // In order to keep working with 1.2 we ignore any loading errors.
432 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
433 "verify")) {
434 dll_load(buffer, ebuf, sizeof(ebuf));
435 }
437 // Load java dll
438 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
439 "java")) {
440 _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
441 }
442 if (_native_java_library == NULL) {
443 vm_exit_during_initialization("Unable to load native library", ebuf);
444 }
446 #if defined(__OpenBSD__)
447 // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
448 // ignore errors
449 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
450 "net")) {
451 dll_load(buffer, ebuf, sizeof(ebuf));
452 }
453 #endif
454 }
455 static jboolean onLoaded = JNI_FALSE;
456 if (onLoaded) {
457 // We may have to wait to fire OnLoad until TLS is initialized.
458 if (ThreadLocalStorage::is_initialized()) {
459 // The JNI_OnLoad handling is normally done by method load in
460 // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
461 // explicitly so we have to check for JNI_OnLoad as well
462 const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
463 JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
464 JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
465 if (JNI_OnLoad != NULL) {
466 JavaThread* thread = JavaThread::current();
467 ThreadToNativeFromVM ttn(thread);
468 HandleMark hm(thread);
469 jint ver = (*JNI_OnLoad)(&main_vm, NULL);
470 onLoaded = JNI_TRUE;
471 if (!Threads::is_supported_jni_version_including_1_1(ver)) {
472 vm_exit_during_initialization("Unsupported JNI version");
473 }
474 }
475 }
476 }
477 return _native_java_library;
478 }
480 /*
481 * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
482 * If check_lib == true then we are looking for an
483 * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
484 * this library is statically linked into the image.
485 * If check_lib == false then we will look for the appropriate symbol in the
486 * executable if agent_lib->is_static_lib() == true or in the shared library
487 * referenced by 'handle'.
488 */
489 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
490 const char *syms[], size_t syms_len) {
491 assert(agent_lib != NULL, "sanity check");
492 const char *lib_name;
493 void *handle = agent_lib->os_lib();
494 void *entryName = NULL;
495 char *agent_function_name;
496 size_t i;
498 // If checking then use the agent name otherwise test is_static_lib() to
499 // see how to process this lookup
500 lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
501 for (i = 0; i < syms_len; i++) {
502 agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
503 if (agent_function_name == NULL) {
504 break;
505 }
506 entryName = dll_lookup(handle, agent_function_name);
507 FREE_C_HEAP_ARRAY(char, agent_function_name, mtThread);
508 if (entryName != NULL) {
509 break;
510 }
511 }
512 return entryName;
513 }
515 // See if the passed in agent is statically linked into the VM image.
516 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
517 size_t syms_len) {
518 void *ret;
519 void *proc_handle;
520 void *save_handle;
522 assert(agent_lib != NULL, "sanity check");
523 if (agent_lib->name() == NULL) {
524 return false;
525 }
526 proc_handle = get_default_process_handle();
527 // Check for Agent_OnLoad/Attach_lib_name function
528 save_handle = agent_lib->os_lib();
529 // We want to look in this process' symbol table.
530 agent_lib->set_os_lib(proc_handle);
531 ret = find_agent_function(agent_lib, true, syms, syms_len);
532 if (ret != NULL) {
533 // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
534 agent_lib->set_valid();
535 agent_lib->set_static_lib(true);
536 return true;
537 }
538 agent_lib->set_os_lib(save_handle);
539 return false;
540 }
542 // --------------------- heap allocation utilities ---------------------
544 char *os::strdup(const char *str, MEMFLAGS flags) {
545 size_t size = strlen(str);
546 char *dup_str = (char *)malloc(size + 1, flags);
547 if (dup_str == NULL) return NULL;
548 strcpy(dup_str, str);
549 return dup_str;
550 }
554 #define paranoid 0 /* only set to 1 if you suspect checking code has bug */
556 #ifdef ASSERT
557 static void verify_memory(void* ptr) {
558 GuardedMemory guarded(ptr);
559 if (!guarded.verify_guards()) {
560 tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
561 tty->print_cr("## memory stomp:");
562 guarded.print_on(tty);
563 fatal("memory stomping error");
564 }
565 }
566 #endif
568 //
569 // This function supports testing of the malloc out of memory
570 // condition without really running the system out of memory.
571 //
572 static u_char* testMalloc(size_t alloc_size) {
573 assert(MallocMaxTestWords > 0, "sanity check");
575 if ((cur_malloc_words + (alloc_size / BytesPerWord)) > MallocMaxTestWords) {
576 return NULL;
577 }
579 u_char* ptr = (u_char*)::malloc(alloc_size);
581 if (ptr != NULL) {
582 Atomic::add(((jint) (alloc_size / BytesPerWord)),
583 (volatile jint *) &cur_malloc_words);
584 }
585 return ptr;
586 }
588 void* os::malloc(size_t size, MEMFLAGS flags) {
589 return os::malloc(size, flags, CALLER_PC);
590 }
592 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
593 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
594 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
596 // Since os::malloc can be called when the libjvm.{dll,so} is
597 // first loaded and we don't have a thread yet we must accept NULL also here.
598 assert(!os::ThreadCrashProtection::is_crash_protected(ThreadLocalStorage::thread()),
599 "malloc() not allowed when crash protection is set");
601 if (size == 0) {
602 // return a valid pointer if size is zero
603 // if NULL is returned the calling functions assume out of memory.
604 size = 1;
605 }
607 // NMT support
608 NMT_TrackingLevel level = MemTracker::tracking_level();
609 size_t nmt_header_size = MemTracker::malloc_header_size(level);
611 #ifndef ASSERT
612 const size_t alloc_size = size + nmt_header_size;
613 #else
614 const size_t alloc_size = GuardedMemory::get_total_size(size + nmt_header_size);
615 if (size + nmt_header_size > alloc_size) { // Check for rollover.
616 return NULL;
617 }
618 #endif
620 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
622 u_char* ptr;
623 if (MallocMaxTestWords > 0) {
624 ptr = testMalloc(alloc_size);
625 } else {
626 ptr = (u_char*)::malloc(alloc_size);
627 }
629 #ifdef ASSERT
630 if (ptr == NULL) {
631 return NULL;
632 }
633 // Wrap memory with guard
634 GuardedMemory guarded(ptr, size + nmt_header_size);
635 ptr = guarded.get_user_ptr();
636 #endif
637 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
638 tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
639 breakpoint();
640 }
641 debug_only(if (paranoid) verify_memory(ptr));
642 if (PrintMalloc && tty != NULL) {
643 tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
644 }
646 // we do not track guard memory
647 return MemTracker::record_malloc((address)ptr, size, memflags, stack, level);
648 }
650 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
651 return os::realloc(memblock, size, flags, CALLER_PC);
652 }
654 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
656 #ifndef ASSERT
657 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
658 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
659 // NMT support
660 void* membase = MemTracker::record_free(memblock);
661 NMT_TrackingLevel level = MemTracker::tracking_level();
662 size_t nmt_header_size = MemTracker::malloc_header_size(level);
663 void* ptr = ::realloc(membase, size + nmt_header_size);
664 return MemTracker::record_malloc(ptr, size, memflags, stack, level);
665 #else
666 if (memblock == NULL) {
667 return os::malloc(size, memflags, stack);
668 }
669 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
670 tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
671 breakpoint();
672 }
673 // NMT support
674 void* membase = MemTracker::malloc_base(memblock);
675 verify_memory(membase);
676 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
677 if (size == 0) {
678 return NULL;
679 }
680 // always move the block
681 void* ptr = os::malloc(size, memflags, stack);
682 if (PrintMalloc) {
683 tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
684 }
685 // Copy to new memory if malloc didn't fail
686 if ( ptr != NULL ) {
687 GuardedMemory guarded(MemTracker::malloc_base(memblock));
688 // Guard's user data contains NMT header
689 size_t memblock_size = guarded.get_user_size() - MemTracker::malloc_header_size(memblock);
690 memcpy(ptr, memblock, MIN2(size, memblock_size));
691 if (paranoid) verify_memory(MemTracker::malloc_base(ptr));
692 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
693 tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
694 breakpoint();
695 }
696 os::free(memblock);
697 }
698 return ptr;
699 #endif
700 }
703 void os::free(void *memblock, MEMFLAGS memflags) {
704 NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
705 #ifdef ASSERT
706 if (memblock == NULL) return;
707 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
708 if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
709 breakpoint();
710 }
711 void* membase = MemTracker::record_free(memblock);
712 verify_memory(membase);
713 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
715 GuardedMemory guarded(membase);
716 size_t size = guarded.get_user_size();
717 inc_stat_counter(&free_bytes, size);
718 membase = guarded.release_for_freeing();
719 if (PrintMalloc && tty != NULL) {
720 fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)membase);
721 }
722 ::free(membase);
723 #else
724 void* membase = MemTracker::record_free(memblock);
725 ::free(membase);
726 #endif
727 }
729 void os::init_random(long initval) {
730 _rand_seed = initval;
731 }
734 long os::random() {
735 /* standard, well-known linear congruential random generator with
736 * next_rand = (16807*seed) mod (2**31-1)
737 * see
738 * (1) "Random Number Generators: Good Ones Are Hard to Find",
739 * S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
740 * (2) "Two Fast Implementations of the 'Minimal Standard' Random
741 * Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
742 */
743 const long a = 16807;
744 const unsigned long m = 2147483647;
745 const long q = m / a; assert(q == 127773, "weird math");
746 const long r = m % a; assert(r == 2836, "weird math");
748 // compute az=2^31p+q
749 unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
750 unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
751 lo += (hi & 0x7FFF) << 16;
753 // if q overflowed, ignore the overflow and increment q
754 if (lo > m) {
755 lo &= m;
756 ++lo;
757 }
758 lo += hi >> 15;
760 // if (p+q) overflowed, ignore the overflow and increment (p+q)
761 if (lo > m) {
762 lo &= m;
763 ++lo;
764 }
765 return (_rand_seed = lo);
766 }
768 // The INITIALIZED state is distinguished from the SUSPENDED state because the
769 // conditions in which a thread is first started are different from those in which
770 // a suspension is resumed. These differences make it hard for us to apply the
771 // tougher checks when starting threads that we want to do when resuming them.
772 // However, when start_thread is called as a result of Thread.start, on a Java
773 // thread, the operation is synchronized on the Java Thread object. So there
774 // cannot be a race to start the thread and hence for the thread to exit while
775 // we are working on it. Non-Java threads that start Java threads either have
776 // to do so in a context in which races are impossible, or should do appropriate
777 // locking.
779 void os::start_thread(Thread* thread) {
780 // guard suspend/resume
781 MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
782 OSThread* osthread = thread->osthread();
783 osthread->set_state(RUNNABLE);
784 pd_start_thread(thread);
785 }
787 //---------------------------------------------------------------------------
788 // Helper functions for fatal error handler
790 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
791 assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
793 int cols = 0;
794 int cols_per_line = 0;
795 switch (unitsize) {
796 case 1: cols_per_line = 16; break;
797 case 2: cols_per_line = 8; break;
798 case 4: cols_per_line = 4; break;
799 case 8: cols_per_line = 2; break;
800 default: return;
801 }
803 address p = start;
804 st->print(PTR_FORMAT ": ", start);
805 while (p < end) {
806 switch (unitsize) {
807 case 1: st->print("%02x", *(u1*)p); break;
808 case 2: st->print("%04x", *(u2*)p); break;
809 case 4: st->print("%08x", *(u4*)p); break;
810 case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
811 }
812 p += unitsize;
813 cols++;
814 if (cols >= cols_per_line && p < end) {
815 cols = 0;
816 st->cr();
817 st->print(PTR_FORMAT ": ", p);
818 } else {
819 st->print(" ");
820 }
821 }
822 st->cr();
823 }
825 void os::print_environment_variables(outputStream* st, const char** env_list,
826 char* buffer, int len) {
827 if (env_list) {
828 st->print_cr("Environment Variables:");
830 for (int i = 0; env_list[i] != NULL; i++) {
831 if (getenv(env_list[i], buffer, len)) {
832 st->print("%s", env_list[i]);
833 st->print("=");
834 st->print_cr("%s", buffer);
835 }
836 }
837 }
838 }
840 void os::print_cpu_info(outputStream* st) {
841 // cpu
842 st->print("CPU:");
843 st->print("total %d", os::processor_count());
844 // It's not safe to query number of active processors after crash
845 // st->print("(active %d)", os::active_processor_count()); but we can
846 // print the initial number of active processors.
847 // We access the raw value here because the assert in the accessor will
848 // fail if the crash occurs before initialization of this value.
849 st->print(" (initial active %d)", _initial_active_processor_count);
850 st->print(" %s", VM_Version::cpu_features());
851 st->cr();
852 pd_print_cpu_info(st);
853 }
855 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
856 const int secs_per_day = 86400;
857 const int secs_per_hour = 3600;
858 const int secs_per_min = 60;
860 time_t tloc;
861 (void)time(&tloc);
862 st->print("time: %s", ctime(&tloc)); // ctime adds newline.
864 struct tm tz;
865 if (localtime_pd(&tloc, &tz) != NULL) {
866 ::strftime(buf, buflen, "%Z", &tz);
867 st->print_cr("timezone: %s", buf);
868 }
870 double t = os::elapsedTime();
871 // NOTE: a crash using printf("%f",...) on Linux was historically noted here.
872 int eltime = (int)t; // elapsed time in seconds
873 int eltimeFraction = (int) ((t - eltime) * 1000000);
875 // print elapsed time in a human-readable format:
876 int eldays = eltime / secs_per_day;
877 int day_secs = eldays * secs_per_day;
878 int elhours = (eltime - day_secs) / secs_per_hour;
879 int hour_secs = elhours * secs_per_hour;
880 int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
881 int minute_secs = elmins * secs_per_min;
882 int elsecs = (eltime - day_secs - hour_secs - minute_secs);
883 st->print_cr(" elapsed time: %d.%06d seconds (%dd %dh %dm %ds)", eltime, eltimeFraction, eldays, elhours, elmins, elsecs);
884 }
886 // moved from debug.cpp (used to be find()) but still called from there
887 // The verbose parameter is only set by the debug code in one case
888 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
889 address addr = (address)x;
890 CodeBlob* b = CodeCache::find_blob_unsafe(addr);
891 if (b != NULL) {
892 if (b->is_buffer_blob()) {
893 // the interpreter is generated into a buffer blob
894 InterpreterCodelet* i = Interpreter::codelet_containing(addr);
895 if (i != NULL) {
896 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
897 i->print_on(st);
898 return;
899 }
900 if (Interpreter::contains(addr)) {
901 st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
902 " (not bytecode specific)", addr);
903 return;
904 }
905 //
906 if (AdapterHandlerLibrary::contains(b)) {
907 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
908 AdapterHandlerLibrary::print_handler_on(st, b);
909 }
910 // the stubroutines are generated into a buffer blob
911 StubCodeDesc* d = StubCodeDesc::desc_for(addr);
912 if (d != NULL) {
913 st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
914 d->print_on(st);
915 st->cr();
916 return;
917 }
918 if (StubRoutines::contains(addr)) {
919 st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
920 "stub routine", addr);
921 return;
922 }
923 // the InlineCacheBuffer is using stubs generated into a buffer blob
924 if (InlineCacheBuffer::contains(addr)) {
925 st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
926 return;
927 }
928 VtableStub* v = VtableStubs::stub_containing(addr);
929 if (v != NULL) {
930 st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
931 v->print_on(st);
932 st->cr();
933 return;
934 }
935 }
936 nmethod* nm = b->as_nmethod_or_null();
937 if (nm != NULL) {
938 ResourceMark rm;
939 st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
940 addr, (int)(addr - nm->entry_point()), nm);
941 if (verbose) {
942 st->print(" for ");
943 nm->method()->print_value_on(st);
944 }
945 st->cr();
946 nm->print_nmethod(verbose);
947 return;
948 }
949 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
950 b->print_on(st);
951 return;
952 }
954 if (Universe::heap()->is_in(addr)) {
955 HeapWord* p = Universe::heap()->block_start(addr);
956 bool print = false;
957 // If we couldn't find it it just may mean that heap wasn't parseable
958 // See if we were just given an oop directly
959 if (p != NULL && Universe::heap()->block_is_obj(p)) {
960 print = true;
961 } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
962 p = (HeapWord*) addr;
963 print = true;
964 }
965 if (print) {
966 if (p == (HeapWord*) addr) {
967 st->print_cr(INTPTR_FORMAT " is an oop", addr);
968 } else {
969 st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
970 }
971 oop(p)->print_on(st);
972 return;
973 }
974 } else {
975 if (Universe::heap()->is_in_reserved(addr)) {
976 st->print_cr(INTPTR_FORMAT " is an unallocated location "
977 "in the heap", addr);
978 return;
979 }
980 }
981 if (JNIHandles::is_global_handle((jobject) addr)) {
982 st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
983 return;
984 }
985 if (JNIHandles::is_weak_global_handle((jobject) addr)) {
986 st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
987 return;
988 }
989 #ifndef PRODUCT
990 // we don't keep the block list in product mode
991 if (JNIHandleBlock::any_contains((jobject) addr)) {
992 st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
993 return;
994 }
995 #endif
997 for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
998 // Check for privilege stack
999 if (thread->privileged_stack_top() != NULL &&
1000 thread->privileged_stack_top()->contains(addr)) {
1001 st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
1002 "for thread: " INTPTR_FORMAT, addr, thread);
1003 if (verbose) thread->print_on(st);
1004 return;
1005 }
1006 // If the addr is a java thread print information about that.
1007 if (addr == (address)thread) {
1008 if (verbose) {
1009 thread->print_on(st);
1010 } else {
1011 st->print_cr(INTPTR_FORMAT " is a thread", addr);
1012 }
1013 return;
1014 }
1015 // If the addr is in the stack region for this thread then report that
1016 // and print thread info
1017 if (thread->stack_base() >= addr &&
1018 addr > (thread->stack_base() - thread->stack_size())) {
1019 st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1020 INTPTR_FORMAT, addr, thread);
1021 if (verbose) thread->print_on(st);
1022 return;
1023 }
1025 }
1027 // Check if in metaspace and print types that have vptrs (only method now)
1028 if (Metaspace::contains(addr)) {
1029 if (Method::has_method_vptr((const void*)addr)) {
1030 ((Method*)addr)->print_value_on(st);
1031 st->cr();
1032 } else {
1033 // Use addr->print() from the debugger instead (not here)
1034 st->print_cr(INTPTR_FORMAT " is pointing into metadata", addr);
1035 }
1036 return;
1037 }
1039 // Try an OS specific find
1040 if (os::find(addr, st)) {
1041 return;
1042 }
1044 st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
1045 }
1047 // Looks like all platforms except IA64 can use the same function to check
1048 // if C stack is walkable beyond current frame. The check for fp() is not
1049 // necessary on Sparc, but it's harmless.
1050 bool os::is_first_C_frame(frame* fr) {
1051 #if (defined(IA64) && !defined(AIX)) && !defined(_WIN32)
1052 // On IA64 we have to check if the callers bsp is still valid
1053 // (i.e. within the register stack bounds).
1054 // Notice: this only works for threads created by the VM and only if
1055 // we walk the current stack!!! If we want to be able to walk
1056 // arbitrary other threads, we'll have to somehow store the thread
1057 // object in the frame.
1058 Thread *thread = Thread::current();
1059 if ((address)fr->fp() <=
1060 thread->register_stack_base() HPUX_ONLY(+ 0x0) LINUX_ONLY(+ 0x50)) {
1061 // This check is a little hacky, because on Linux the first C
1062 // frame's ('start_thread') register stack frame starts at
1063 // "register_stack_base + 0x48" while on HPUX, the first C frame's
1064 // ('__pthread_bound_body') register stack frame seems to really
1065 // start at "register_stack_base".
1066 return true;
1067 } else {
1068 return false;
1069 }
1070 #elif defined(IA64) && defined(_WIN32)
1071 return true;
1072 #else
1073 // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1074 // Check usp first, because if that's bad the other accessors may fault
1075 // on some architectures. Ditto ufp second, etc.
1076 uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
1077 // sp on amd can be 32 bit aligned.
1078 uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
1080 uintptr_t usp = (uintptr_t)fr->sp();
1081 if ((usp & sp_align_mask) != 0) return true;
1083 uintptr_t ufp = (uintptr_t)fr->fp();
1084 if ((ufp & fp_align_mask) != 0) return true;
1086 uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1087 if ((old_sp & sp_align_mask) != 0) return true;
1088 if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
1090 uintptr_t old_fp = (uintptr_t)fr->link();
1091 if ((old_fp & fp_align_mask) != 0) return true;
1092 if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
1094 // stack grows downwards; if old_fp is below current fp or if the stack
1095 // frame is too large, either the stack is corrupted or fp is not saved
1096 // on stack (i.e. on x86, ebp may be used as general register). The stack
1097 // is not walkable beyond current frame.
1098 if (old_fp < ufp) return true;
1099 if (old_fp - ufp > 64 * K) return true;
1101 return false;
1102 #endif
1103 }
1105 #ifdef ASSERT
1106 extern "C" void test_random() {
1107 const double m = 2147483647;
1108 double mean = 0.0, variance = 0.0, t;
1109 long reps = 10000;
1110 unsigned long seed = 1;
1112 tty->print_cr("seed %ld for %ld repeats...", seed, reps);
1113 os::init_random(seed);
1114 long num;
1115 for (int k = 0; k < reps; k++) {
1116 num = os::random();
1117 double u = (double)num / m;
1118 assert(u >= 0.0 && u <= 1.0, "bad random number!");
1120 // calculate mean and variance of the random sequence
1121 mean += u;
1122 variance += (u*u);
1123 }
1124 mean /= reps;
1125 variance /= (reps - 1);
1127 assert(num == 1043618065, "bad seed");
1128 tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
1129 tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
1130 const double eps = 0.0001;
1131 t = fabsd(mean - 0.5018);
1132 assert(t < eps, "bad mean");
1133 t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
1134 assert(t < eps, "bad variance");
1135 }
1136 #endif
1139 // Set up the boot classpath.
1141 char* os::format_boot_path(const char* format_string,
1142 const char* home,
1143 int home_len,
1144 char fileSep,
1145 char pathSep) {
1146 assert((fileSep == '/' && pathSep == ':') ||
1147 (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
1149 // Scan the format string to determine the length of the actual
1150 // boot classpath, and handle platform dependencies as well.
1151 int formatted_path_len = 0;
1152 const char* p;
1153 for (p = format_string; *p != 0; ++p) {
1154 if (*p == '%') formatted_path_len += home_len - 1;
1155 ++formatted_path_len;
1156 }
1158 char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1159 if (formatted_path == NULL) {
1160 return NULL;
1161 }
1163 // Create boot classpath from format, substituting separator chars and
1164 // java home directory.
1165 char* q = formatted_path;
1166 for (p = format_string; *p != 0; ++p) {
1167 switch (*p) {
1168 case '%':
1169 strcpy(q, home);
1170 q += home_len;
1171 break;
1172 case '/':
1173 *q++ = fileSep;
1174 break;
1175 case ':':
1176 *q++ = pathSep;
1177 break;
1178 default:
1179 *q++ = *p;
1180 }
1181 }
1182 *q = '\0';
1184 assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1185 return formatted_path;
1186 }
1189 bool os::set_boot_path(char fileSep, char pathSep) {
1190 const char* home = Arguments::get_java_home();
1191 int home_len = (int)strlen(home);
1193 static const char* meta_index_dir_format = "%/lib/";
1194 static const char* meta_index_format = "%/lib/meta-index";
1195 char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
1196 if (meta_index == NULL) return false;
1197 char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
1198 if (meta_index_dir == NULL) return false;
1199 Arguments::set_meta_index_path(meta_index, meta_index_dir);
1201 // Any modification to the JAR-file list, for the boot classpath must be
1202 // aligned with install/install/make/common/Pack.gmk. Note: boot class
1203 // path class JARs, are stripped for StackMapTable to reduce download size.
1204 static const char classpath_format[] =
1205 "%/lib/resources.jar:"
1206 "%/lib/rt.jar:"
1207 "%/lib/sunrsasign.jar:"
1208 "%/lib/jsse.jar:"
1209 "%/lib/jce.jar:"
1210 "%/lib/charsets.jar:"
1211 "%/lib/jfr.jar:"
1212 "%/classes";
1213 char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
1214 if (sysclasspath == NULL) return false;
1215 Arguments::set_sysclasspath(sysclasspath);
1217 return true;
1218 }
1220 /*
1221 * Splits a path, based on its separator, the number of
1222 * elements is returned back in n.
1223 * It is the callers responsibility to:
1224 * a> check the value of n, and n may be 0.
1225 * b> ignore any empty path elements
1226 * c> free up the data.
1227 */
1228 char** os::split_path(const char* path, int* n) {
1229 *n = 0;
1230 if (path == NULL || strlen(path) == 0) {
1231 return NULL;
1232 }
1233 const char psepchar = *os::path_separator();
1234 char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1235 if (inpath == NULL) {
1236 return NULL;
1237 }
1238 strcpy(inpath, path);
1239 int count = 1;
1240 char* p = strchr(inpath, psepchar);
1241 // Get a count of elements to allocate memory
1242 while (p != NULL) {
1243 count++;
1244 p++;
1245 p = strchr(p, psepchar);
1246 }
1247 char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1248 if (opath == NULL) {
1249 return NULL;
1250 }
1252 // do the actual splitting
1253 p = inpath;
1254 for (int i = 0 ; i < count ; i++) {
1255 size_t len = strcspn(p, os::path_separator());
1256 if (len > JVM_MAXPATHLEN) {
1257 return NULL;
1258 }
1259 // allocate the string and add terminator storage
1260 char* s = (char*)NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1261 if (s == NULL) {
1262 return NULL;
1263 }
1264 strncpy(s, p, len);
1265 s[len] = '\0';
1266 opath[i] = s;
1267 p += len + 1;
1268 }
1269 FREE_C_HEAP_ARRAY(char, inpath, mtInternal);
1270 *n = count;
1271 return opath;
1272 }
1274 void os::set_memory_serialize_page(address page) {
1275 int count = log2_intptr(sizeof(class JavaThread)) - log2_int(64);
1276 _mem_serialize_page = (volatile int32_t *)page;
1277 // We initialize the serialization page shift count here
1278 // We assume a cache line size of 64 bytes
1279 assert(SerializePageShiftCount == count,
1280 "thread size changed, fix SerializePageShiftCount constant");
1281 set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
1282 }
1284 static volatile intptr_t SerializePageLock = 0;
1286 // This method is called from signal handler when SIGSEGV occurs while the current
1287 // thread tries to store to the "read-only" memory serialize page during state
1288 // transition.
1289 void os::block_on_serialize_page_trap() {
1290 if (TraceSafepoint) {
1291 tty->print_cr("Block until the serialize page permission restored");
1292 }
1293 // When VMThread is holding the SerializePageLock during modifying the
1294 // access permission of the memory serialize page, the following call
1295 // will block until the permission of that page is restored to rw.
1296 // Generally, it is unsafe to manipulate locks in signal handlers, but in
1297 // this case, it's OK as the signal is synchronous and we know precisely when
1298 // it can occur.
1299 Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
1300 Thread::muxRelease(&SerializePageLock);
1301 }
1303 // Serialize all thread state variables
1304 void os::serialize_thread_states() {
1305 // On some platforms such as Solaris & Linux, the time duration of the page
1306 // permission restoration is observed to be much longer than expected due to
1307 // scheduler starvation problem etc. To avoid the long synchronization
1308 // time and expensive page trap spinning, 'SerializePageLock' is used to block
1309 // the mutator thread if such case is encountered. See bug 6546278 for details.
1310 Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
1311 os::protect_memory((char *)os::get_memory_serialize_page(),
1312 os::vm_page_size(), MEM_PROT_READ);
1313 os::protect_memory((char *)os::get_memory_serialize_page(),
1314 os::vm_page_size(), MEM_PROT_RW);
1315 Thread::muxRelease(&SerializePageLock);
1316 }
1318 // Returns true if the current stack pointer is above the stack shadow
1319 // pages, false otherwise.
1321 bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
1322 assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
1323 address sp = current_stack_pointer();
1324 // Check if we have StackShadowPages above the yellow zone. This parameter
1325 // is dependent on the depth of the maximum VM call stack possible from
1326 // the handler for stack overflow. 'instanceof' in the stack overflow
1327 // handler or a println uses at least 8k stack of VM and native code
1328 // respectively.
1329 const int framesize_in_bytes =
1330 Interpreter::size_top_interpreter_activation(method()) * wordSize;
1331 int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
1332 * vm_page_size()) + framesize_in_bytes;
1333 // The very lower end of the stack
1334 address stack_limit = thread->stack_base() - thread->stack_size();
1335 return (sp > (stack_limit + reserved_area));
1336 }
1338 size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) {
1339 assert(min_pages > 0, "sanity");
1340 if (UseLargePages) {
1341 const size_t max_page_size = region_size / min_pages;
1343 for (size_t i = 0; _page_sizes[i] != 0; ++i) {
1344 const size_t page_size = _page_sizes[i];
1345 if (page_size <= max_page_size) {
1346 if (!must_be_aligned || is_size_aligned(region_size, page_size)) {
1347 return page_size;
1348 }
1349 }
1350 }
1351 }
1353 return vm_page_size();
1354 }
1356 size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) {
1357 return page_size_for_region(region_size, min_pages, true);
1358 }
1360 size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) {
1361 return page_size_for_region(region_size, min_pages, false);
1362 }
1364 #ifndef PRODUCT
1365 void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
1366 {
1367 if (TracePageSizes) {
1368 tty->print("%s: ", str);
1369 for (int i = 0; i < count; ++i) {
1370 tty->print(" " SIZE_FORMAT, page_sizes[i]);
1371 }
1372 tty->cr();
1373 }
1374 }
1376 void os::trace_page_sizes(const char* str, const size_t region_min_size,
1377 const size_t region_max_size, const size_t page_size,
1378 const char* base, const size_t size)
1379 {
1380 if (TracePageSizes) {
1381 tty->print_cr("%s: min=" SIZE_FORMAT " max=" SIZE_FORMAT
1382 " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
1383 " size=" SIZE_FORMAT,
1384 str, region_min_size, region_max_size,
1385 page_size, base, size);
1386 }
1387 }
1388 #endif // #ifndef PRODUCT
1390 // This is the working definition of a server class machine:
1391 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1392 // because the graphics memory (?) sometimes masks physical memory.
1393 // If you want to change the definition of a server class machine
1394 // on some OS or platform, e.g., >=4GB on Windohs platforms,
1395 // then you'll have to parameterize this method based on that state,
1396 // as was done for logical processors here, or replicate and
1397 // specialize this method for each platform. (Or fix os to have
1398 // some inheritance structure and use subclassing. Sigh.)
1399 // If you want some platform to always or never behave as a server
1400 // class machine, change the setting of AlwaysActAsServerClassMachine
1401 // and NeverActAsServerClassMachine in globals*.hpp.
1402 bool os::is_server_class_machine() {
1403 // First check for the early returns
1404 if (NeverActAsServerClassMachine) {
1405 return false;
1406 }
1407 if (AlwaysActAsServerClassMachine) {
1408 return true;
1409 }
1410 // Then actually look at the machine
1411 bool result = false;
1412 const unsigned int server_processors = 2;
1413 const julong server_memory = 2UL * G;
1414 // We seem not to get our full complement of memory.
1415 // We allow some part (1/8?) of the memory to be "missing",
1416 // based on the sizes of DIMMs, and maybe graphics cards.
1417 const julong missing_memory = 256UL * M;
1419 /* Is this a server class machine? */
1420 if ((os::active_processor_count() >= (int)server_processors) &&
1421 (os::physical_memory() >= (server_memory - missing_memory))) {
1422 const unsigned int logical_processors =
1423 VM_Version::logical_processors_per_package();
1424 if (logical_processors > 1) {
1425 const unsigned int physical_packages =
1426 os::active_processor_count() / logical_processors;
1427 if (physical_packages > server_processors) {
1428 result = true;
1429 }
1430 } else {
1431 result = true;
1432 }
1433 }
1434 return result;
1435 }
1437 void os::initialize_initial_active_processor_count() {
1438 assert(_initial_active_processor_count == 0, "Initial active processor count already set.");
1439 _initial_active_processor_count = active_processor_count();
1440 }
1442 void os::SuspendedThreadTask::run() {
1443 assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
1444 internal_do_task();
1445 _done = true;
1446 }
1448 bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1449 return os::pd_create_stack_guard_pages(addr, bytes);
1450 }
1452 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
1453 char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1454 if (result != NULL) {
1455 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1456 }
1458 return result;
1459 }
1461 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
1462 MEMFLAGS flags) {
1463 char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1464 if (result != NULL) {
1465 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1466 MemTracker::record_virtual_memory_type((address)result, flags);
1467 }
1469 return result;
1470 }
1472 char* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
1473 char* result = pd_attempt_reserve_memory_at(bytes, addr);
1474 if (result != NULL) {
1475 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1476 }
1477 return result;
1478 }
1480 void os::split_reserved_memory(char *base, size_t size,
1481 size_t split, bool realloc) {
1482 pd_split_reserved_memory(base, size, split, realloc);
1483 }
1485 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1486 bool res = pd_commit_memory(addr, bytes, executable);
1487 if (res) {
1488 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1489 }
1490 return res;
1491 }
1493 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1494 bool executable) {
1495 bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1496 if (res) {
1497 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1498 }
1499 return res;
1500 }
1502 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1503 const char* mesg) {
1504 pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1505 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1506 }
1508 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1509 bool executable, const char* mesg) {
1510 os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1511 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1512 }
1514 bool os::uncommit_memory(char* addr, size_t bytes) {
1515 bool res;
1516 if (MemTracker::tracking_level() > NMT_minimal) {
1517 Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
1518 res = pd_uncommit_memory(addr, bytes);
1519 if (res) {
1520 tkr.record((address)addr, bytes);
1521 }
1522 } else {
1523 res = pd_uncommit_memory(addr, bytes);
1524 }
1525 return res;
1526 }
1528 bool os::release_memory(char* addr, size_t bytes) {
1529 bool res;
1530 if (MemTracker::tracking_level() > NMT_minimal) {
1531 Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1532 res = pd_release_memory(addr, bytes);
1533 if (res) {
1534 tkr.record((address)addr, bytes);
1535 }
1536 } else {
1537 res = pd_release_memory(addr, bytes);
1538 }
1539 return res;
1540 }
1542 void os::pretouch_memory(char* start, char* end) {
1543 for (volatile char *p = start; p < end; p += os::vm_page_size()) {
1544 *p = 0;
1545 }
1546 }
1548 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1549 char *addr, size_t bytes, bool read_only,
1550 bool allow_exec) {
1551 char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1552 if (result != NULL) {
1553 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1554 }
1555 return result;
1556 }
1558 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1559 char *addr, size_t bytes, bool read_only,
1560 bool allow_exec) {
1561 return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1562 read_only, allow_exec);
1563 }
1565 bool os::unmap_memory(char *addr, size_t bytes) {
1566 bool result;
1567 if (MemTracker::tracking_level() > NMT_minimal) {
1568 Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1569 result = pd_unmap_memory(addr, bytes);
1570 if (result) {
1571 tkr.record((address)addr, bytes);
1572 }
1573 } else {
1574 result = pd_unmap_memory(addr, bytes);
1575 }
1576 return result;
1577 }
1579 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1580 pd_free_memory(addr, bytes, alignment_hint);
1581 }
1583 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1584 pd_realign_memory(addr, bytes, alignment_hint);
1585 }
1587 #ifndef TARGET_OS_FAMILY_windows
1588 /* try to switch state from state "from" to state "to"
1589 * returns the state set after the method is complete
1590 */
1591 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1592 os::SuspendResume::State to)
1593 {
1594 os::SuspendResume::State result =
1595 (os::SuspendResume::State) Atomic::cmpxchg((jint) to, (jint *) &_state, (jint) from);
1596 if (result == from) {
1597 // success
1598 return to;
1599 }
1600 return result;
1601 }
1602 #endif
1604 /////////////// Unit tests ///////////////
1606 #ifndef PRODUCT
1608 #define assert_eq(a,b) assert(a == b, err_msg(SIZE_FORMAT " != " SIZE_FORMAT, a, b))
1610 class TestOS : AllStatic {
1611 static size_t small_page_size() {
1612 return os::vm_page_size();
1613 }
1615 static size_t large_page_size() {
1616 const size_t large_page_size_example = 4 * M;
1617 return os::page_size_for_region_aligned(large_page_size_example, 1);
1618 }
1620 static void test_page_size_for_region_aligned() {
1621 if (UseLargePages) {
1622 const size_t small_page = small_page_size();
1623 const size_t large_page = large_page_size();
1625 if (large_page > small_page) {
1626 size_t num_small_pages_in_large = large_page / small_page;
1627 size_t page = os::page_size_for_region_aligned(large_page, num_small_pages_in_large);
1629 assert_eq(page, small_page);
1630 }
1631 }
1632 }
1634 static void test_page_size_for_region_alignment() {
1635 if (UseLargePages) {
1636 const size_t small_page = small_page_size();
1637 const size_t large_page = large_page_size();
1638 if (large_page > small_page) {
1639 const size_t unaligned_region = large_page + 17;
1640 size_t page = os::page_size_for_region_aligned(unaligned_region, 1);
1641 assert_eq(page, small_page);
1643 const size_t num_pages = 5;
1644 const size_t aligned_region = large_page * num_pages;
1645 page = os::page_size_for_region_aligned(aligned_region, num_pages);
1646 assert_eq(page, large_page);
1647 }
1648 }
1649 }
1651 static void test_page_size_for_region_unaligned() {
1652 if (UseLargePages) {
1653 // Given exact page size, should return that page size.
1654 for (size_t i = 0; os::_page_sizes[i] != 0; i++) {
1655 size_t expected = os::_page_sizes[i];
1656 size_t actual = os::page_size_for_region_unaligned(expected, 1);
1657 assert_eq(expected, actual);
1658 }
1660 // Given slightly larger size than a page size, return the page size.
1661 for (size_t i = 0; os::_page_sizes[i] != 0; i++) {
1662 size_t expected = os::_page_sizes[i];
1663 size_t actual = os::page_size_for_region_unaligned(expected + 17, 1);
1664 assert_eq(expected, actual);
1665 }
1667 // Given a slightly smaller size than a page size,
1668 // return the next smaller page size.
1669 if (os::_page_sizes[1] > os::_page_sizes[0]) {
1670 size_t expected = os::_page_sizes[0];
1671 size_t actual = os::page_size_for_region_unaligned(os::_page_sizes[1] - 17, 1);
1672 assert_eq(actual, expected);
1673 }
1675 // Return small page size for values less than a small page.
1676 size_t small_page = small_page_size();
1677 size_t actual = os::page_size_for_region_unaligned(small_page - 17, 1);
1678 assert_eq(small_page, actual);
1679 }
1680 }
1682 public:
1683 static void run_tests() {
1684 test_page_size_for_region_aligned();
1685 test_page_size_for_region_alignment();
1686 test_page_size_for_region_unaligned();
1687 }
1688 };
1690 void TestOS_test() {
1691 TestOS::run_tests();
1692 }
1694 #endif // PRODUCT