0N/A/*
4552N/A * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
1472N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1472N/A * or visit www.oracle.com if you need additional information or have any
1472N/A * questions.
0N/A *
0N/A */
0N/A
1879N/A#include "precompiled.hpp"
1879N/A#include "classfile/classLoader.hpp"
1879N/A#include "classfile/javaClasses.hpp"
1879N/A#include "classfile/systemDictionary.hpp"
1879N/A#include "classfile/vmSymbols.hpp"
1879N/A#include "code/icBuffer.hpp"
1879N/A#include "code/vtableStubs.hpp"
1879N/A#include "gc_implementation/shared/vmGCOperations.hpp"
1879N/A#include "interpreter/interpreter.hpp"
1879N/A#include "memory/allocation.inline.hpp"
1879N/A#include "oops/oop.inline.hpp"
1879N/A#include "prims/jvm.h"
1879N/A#include "prims/jvm_misc.hpp"
1879N/A#include "prims/privilegedStack.hpp"
1879N/A#include "runtime/arguments.hpp"
1879N/A#include "runtime/frame.inline.hpp"
1879N/A#include "runtime/interfaceSupport.hpp"
1879N/A#include "runtime/java.hpp"
1879N/A#include "runtime/javaCalls.hpp"
1879N/A#include "runtime/mutexLocker.hpp"
1879N/A#include "runtime/os.hpp"
1879N/A#include "runtime/stubRoutines.hpp"
1879N/A#include "services/attachListener.hpp"
3863N/A#include "services/memTracker.hpp"
1879N/A#include "services/threadService.hpp"
1879N/A#include "utilities/defaultStream.hpp"
1879N/A#include "utilities/events.hpp"
1879N/A#ifdef TARGET_OS_FAMILY_linux
1879N/A# include "os_linux.inline.hpp"
1879N/A# include "thread_linux.inline.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_OS_FAMILY_solaris
1879N/A# include "os_solaris.inline.hpp"
1879N/A# include "thread_solaris.inline.hpp"
1879N/A#endif
1879N/A#ifdef TARGET_OS_FAMILY_windows
1879N/A# include "os_windows.inline.hpp"
1879N/A# include "thread_windows.inline.hpp"
1879N/A#endif
2796N/A#ifdef TARGET_OS_FAMILY_bsd
2796N/A# include "os_bsd.inline.hpp"
2796N/A# include "thread_bsd.inline.hpp"
2796N/A#endif
0N/A
0N/A# include <signal.h>
0N/A
0N/AOSThread* os::_starting_thread = NULL;
0N/Aaddress os::_polling_page = NULL;
0N/Avolatile int32_t* os::_mem_serialize_page = NULL;
0N/Auintptr_t os::_serialize_page_mask = 0;
0N/Along os::_rand_seed = 1;
0N/Aint os::_processor_count = 0;
0N/Asize_t os::_page_sizes[os::page_sizes_max];
0N/A
0N/A#ifndef PRODUCT
2122N/Ajulong os::num_mallocs = 0; // # of calls to malloc/realloc
2122N/Ajulong os::alloc_bytes = 0; // # of bytes allocated
2122N/Ajulong os::num_frees = 0; // # of calls to free
2122N/Ajulong os::free_bytes = 0; // # of bytes freed
0N/A#endif
0N/A
3029N/Avoid os_init_globals() {
3029N/A // Called from init_globals().
3029N/A // See Threads::create_vm() in thread.cpp, and init.cpp.
3029N/A os::init_globals();
3029N/A}
3029N/A
0N/A// Fill in buffer with current local time as an ISO-8601 string.
0N/A// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
0N/A// Returns buffer, or NULL if it failed.
0N/A// This would mostly be a call to
0N/A// strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
0N/A// except that on Windows the %z behaves badly, so we do it ourselves.
0N/A// Also, people wanted milliseconds on there,
0N/A// and strftime doesn't do milliseconds.
0N/Achar* os::iso8601_time(char* buffer, size_t buffer_length) {
0N/A // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
0N/A // 1 2
0N/A // 12345678901234567890123456789
0N/A static const char* iso8601_format =
0N/A "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
0N/A static const size_t needed_buffer = 29;
0N/A
0N/A // Sanity check the arguments
0N/A if (buffer == NULL) {
0N/A assert(false, "NULL buffer");
0N/A return NULL;
0N/A }
0N/A if (buffer_length < needed_buffer) {
0N/A assert(false, "buffer_length too small");
0N/A return NULL;
0N/A }
0N/A // Get the current time
61N/A jlong milliseconds_since_19700101 = javaTimeMillis();
0N/A const int milliseconds_per_microsecond = 1000;
0N/A const time_t seconds_since_19700101 =
0N/A milliseconds_since_19700101 / milliseconds_per_microsecond;
0N/A const int milliseconds_after_second =
0N/A milliseconds_since_19700101 % milliseconds_per_microsecond;
0N/A // Convert the time value to a tm and timezone variable
548N/A struct tm time_struct;
548N/A if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
548N/A assert(false, "Failed localtime_pd");
0N/A return NULL;
0N/A }
2796N/A#if defined(_ALLBSD_SOURCE)
2796N/A const time_t zone = (time_t) time_struct.tm_gmtoff;
2796N/A#else
0N/A const time_t zone = timezone;
2796N/A#endif
0N/A
0N/A // If daylight savings time is in effect,
0N/A // we are 1 hour East of our time zone
0N/A const time_t seconds_per_minute = 60;
0N/A const time_t minutes_per_hour = 60;
0N/A const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
0N/A time_t UTC_to_local = zone;
0N/A if (time_struct.tm_isdst > 0) {
0N/A UTC_to_local = UTC_to_local - seconds_per_hour;
0N/A }
0N/A // Compute the time zone offset.
548N/A // localtime_pd() sets timezone to the difference (in seconds)
0N/A // between UTC and and local time.
0N/A // ISO 8601 says we need the difference between local time and UTC,
548N/A // we change the sign of the localtime_pd() result.
0N/A const time_t local_to_UTC = -(UTC_to_local);
0N/A // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
0N/A char sign_local_to_UTC = '+';
0N/A time_t abs_local_to_UTC = local_to_UTC;
0N/A if (local_to_UTC < 0) {
0N/A sign_local_to_UTC = '-';
0N/A abs_local_to_UTC = -(abs_local_to_UTC);
0N/A }
0N/A // Convert time zone offset seconds to hours and minutes.
0N/A const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
0N/A const time_t zone_min =
0N/A ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
0N/A
0N/A // Print an ISO 8601 date and time stamp into the buffer
0N/A const int year = 1900 + time_struct.tm_year;
0N/A const int month = 1 + time_struct.tm_mon;
0N/A const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
0N/A year,
0N/A month,
0N/A time_struct.tm_mday,
0N/A time_struct.tm_hour,
0N/A time_struct.tm_min,
0N/A time_struct.tm_sec,
0N/A milliseconds_after_second,
0N/A sign_local_to_UTC,
0N/A zone_hours,
0N/A zone_min);
0N/A if (printed == 0) {
0N/A assert(false, "Failed jio_printf");
0N/A return NULL;
0N/A }
0N/A return buffer;
0N/A}
0N/A
0N/AOSReturn os::set_priority(Thread* thread, ThreadPriority p) {
0N/A#ifdef ASSERT
0N/A if (!(!thread->is_Java_thread() ||
0N/A Thread::current() == thread ||
0N/A Threads_lock->owned_by_self()
0N/A || thread->is_Compiler_thread()
0N/A )) {
0N/A assert(false, "possibility of dangling Thread pointer");
0N/A }
0N/A#endif
0N/A
0N/A if (p >= MinPriority && p <= MaxPriority) {
0N/A int priority = java_to_os_priority[p];
0N/A return set_native_priority(thread, priority);
0N/A } else {
0N/A assert(false, "Should not happen");
0N/A return OS_ERR;
0N/A }
0N/A}
0N/A
0N/A
0N/AOSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
0N/A int p;
0N/A int os_prio;
0N/A OSReturn ret = get_native_priority(thread, &os_prio);
0N/A if (ret != OS_OK) return ret;
0N/A
0N/A for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
0N/A priority = (ThreadPriority)p;
0N/A return OS_OK;
0N/A}
0N/A
0N/A
0N/A// --------------------- sun.misc.Signal (optional) ---------------------
0N/A
0N/A
0N/A// SIGBREAK is sent by the keyboard to query the VM state
0N/A#ifndef SIGBREAK
0N/A#define SIGBREAK SIGQUIT
0N/A#endif
0N/A
0N/A// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
0N/A
0N/A
0N/Astatic void signal_thread_entry(JavaThread* thread, TRAPS) {
0N/A os::set_priority(thread, NearMaxPriority);
0N/A while (true) {
0N/A int sig;
0N/A {
0N/A // FIXME : Currently we have not decieded what should be the status
0N/A // for this java thread blocked here. Once we decide about
0N/A // that we should fix this.
0N/A sig = os::signal_wait();
0N/A }
0N/A if (sig == os::sigexitnum_pd()) {
0N/A // Terminate the signal thread
0N/A return;
0N/A }
0N/A
0N/A switch (sig) {
0N/A case SIGBREAK: {
0N/A // Check if the signal is a trigger to start the Attach Listener - in that
0N/A // case don't print stack traces.
0N/A if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
0N/A continue;
0N/A }
0N/A // Print stack traces
0N/A // Any SIGBREAK operations added here should make sure to flush
0N/A // the output stream (e.g. tty->flush()) after output. See 4803766.
0N/A // Each module also prints an extra carriage return after its output.
0N/A VM_PrintThreads op;
0N/A VMThread::execute(&op);
0N/A VM_PrintJNI jni_op;
0N/A VMThread::execute(&jni_op);
0N/A VM_FindDeadlocks op1(tty);
0N/A VMThread::execute(&op1);
0N/A Universe::print_heap_at_SIGBREAK();
0N/A if (PrintClassHistogram) {
615N/A VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,
615N/A true /* need_prologue */);
0N/A VMThread::execute(&op1);
0N/A }
0N/A if (JvmtiExport::should_post_data_dump()) {
0N/A JvmtiExport::post_data_dump();
0N/A }
0N/A break;
0N/A }
0N/A default: {
0N/A // Dispatch the signal to java
0N/A HandleMark hm(THREAD);
2062N/A klassOop k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
0N/A KlassHandle klass (THREAD, k);
0N/A if (klass.not_null()) {
0N/A JavaValue result(T_VOID);
0N/A JavaCallArguments args;
0N/A args.push_int(sig);
0N/A JavaCalls::call_static(
0N/A &result,
0N/A klass,
2062N/A vmSymbols::dispatch_name(),
2062N/A vmSymbols::int_void_signature(),
0N/A &args,
0N/A THREAD
0N/A );
0N/A }
0N/A if (HAS_PENDING_EXCEPTION) {
0N/A // tty is initialized early so we don't expect it to be null, but
0N/A // if it is we can't risk doing an initialization that might
0N/A // trigger additional out-of-memory conditions
0N/A if (tty != NULL) {
0N/A char klass_name[256];
0N/A char tmp_sig_name[16];
0N/A const char* sig_name = "UNKNOWN";
0N/A instanceKlass::cast(PENDING_EXCEPTION->klass())->
0N/A name()->as_klass_external_name(klass_name, 256);
0N/A if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
0N/A sig_name = tmp_sig_name;
0N/A warning("Exception %s occurred dispatching signal %s to handler"
0N/A "- the VM may need to be forcibly terminated",
0N/A klass_name, sig_name );
0N/A }
0N/A CLEAR_PENDING_EXCEPTION;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/A
0N/Avoid os::signal_init() {
0N/A if (!ReduceSignalUsage) {
0N/A // Setup JavaThread for processing signals
0N/A EXCEPTION_MARK;
2062N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
0N/A instanceKlassHandle klass (THREAD, k);
0N/A instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
0N/A
0N/A const char thread_name[] = "Signal Dispatcher";
0N/A Handle string = java_lang_String::create_from_str(thread_name, CHECK);
0N/A
0N/A // Initialize thread_oop to put it into the system threadGroup
0N/A Handle thread_group (THREAD, Universe::system_thread_group());
0N/A JavaValue result(T_VOID);
0N/A JavaCalls::call_special(&result, thread_oop,
0N/A klass,
2062N/A vmSymbols::object_initializer_name(),
2062N/A vmSymbols::threadgroup_string_void_signature(),
0N/A thread_group,
0N/A string,
0N/A CHECK);
0N/A
1142N/A KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
0N/A JavaCalls::call_special(&result,
0N/A thread_group,
0N/A group,
2062N/A vmSymbols::add_method_name(),
2062N/A vmSymbols::thread_void_signature(),
0N/A thread_oop, // ARG 1
0N/A CHECK);
0N/A
0N/A os::signal_init_pd();
0N/A
0N/A { MutexLocker mu(Threads_lock);
0N/A JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
0N/A
0N/A // At this point it may be possible that no osthread was created for the
0N/A // JavaThread due to lack of memory. We would have to throw an exception
0N/A // in that case. However, since this must work and we do not allow
0N/A // exceptions anyway, check and abort if this fails.
0N/A if (signal_thread == NULL || signal_thread->osthread() == NULL) {
0N/A vm_exit_during_initialization("java.lang.OutOfMemoryError",
0N/A "unable to create new native thread");
0N/A }
0N/A
0N/A java_lang_Thread::set_thread(thread_oop(), signal_thread);
0N/A java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
0N/A java_lang_Thread::set_daemon(thread_oop());
0N/A
0N/A signal_thread->set_threadObj(thread_oop());
0N/A Threads::add(signal_thread);
0N/A Thread::start(signal_thread);
0N/A }
0N/A // Handle ^BREAK
0N/A os::signal(SIGBREAK, os::user_handler());
0N/A }
0N/A}
0N/A
0N/A
0N/Avoid os::terminate_signal_thread() {
0N/A if (!ReduceSignalUsage)
0N/A signal_notify(sigexitnum_pd());
0N/A}
0N/A
0N/A
0N/A// --------------------- loading libraries ---------------------
0N/A
0N/Atypedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
0N/Aextern struct JavaVM_ main_vm;
0N/A
0N/Astatic void* _native_java_library = NULL;
0N/A
0N/Avoid* os::native_java_library() {
0N/A if (_native_java_library == NULL) {
0N/A char buffer[JVM_MAXPATHLEN];
0N/A char ebuf[1024];
0N/A
242N/A // Try to load verify dll first. In 1.3 java dll depends on it and is not
242N/A // always able to find it when the loading executable is outside the JDK.
0N/A // In order to keep working with 1.2 we ignore any loading errors.
242N/A dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "verify");
242N/A dll_load(buffer, ebuf, sizeof(ebuf));
0N/A
0N/A // Load java dll
242N/A dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "java");
242N/A _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
0N/A if (_native_java_library == NULL) {
0N/A vm_exit_during_initialization("Unable to load native library", ebuf);
0N/A }
2796N/A
2796N/A#if defined(__OpenBSD__)
2796N/A // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
2796N/A // ignore errors
2796N/A dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "net");
2796N/A dll_load(buffer, ebuf, sizeof(ebuf));
2796N/A#endif
242N/A }
242N/A static jboolean onLoaded = JNI_FALSE;
242N/A if (onLoaded) {
242N/A // We may have to wait to fire OnLoad until TLS is initialized.
242N/A if (ThreadLocalStorage::is_initialized()) {
242N/A // The JNI_OnLoad handling is normally done by method load in
242N/A // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
242N/A // explicitly so we have to check for JNI_OnLoad as well
242N/A const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
242N/A JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
242N/A JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
242N/A if (JNI_OnLoad != NULL) {
242N/A JavaThread* thread = JavaThread::current();
242N/A ThreadToNativeFromVM ttn(thread);
242N/A HandleMark hm(thread);
242N/A jint ver = (*JNI_OnLoad)(&main_vm, NULL);
242N/A onLoaded = JNI_TRUE;
242N/A if (!Threads::is_supported_jni_version_including_1_1(ver)) {
242N/A vm_exit_during_initialization("Unsupported JNI version");
242N/A }
0N/A }
0N/A }
0N/A }
0N/A return _native_java_library;
0N/A}
0N/A
0N/A// --------------------- heap allocation utilities ---------------------
0N/A
3863N/Achar *os::strdup(const char *str, MEMFLAGS flags) {
0N/A size_t size = strlen(str);
3863N/A char *dup_str = (char *)malloc(size + 1, flags);
0N/A if (dup_str == NULL) return NULL;
0N/A strcpy(dup_str, str);
0N/A return dup_str;
0N/A}
0N/A
0N/A
0N/A
0N/A#ifdef ASSERT
0N/A#define space_before (MallocCushion + sizeof(double))
0N/A#define space_after MallocCushion
0N/A#define size_addr_from_base(p) (size_t*)(p + space_before - sizeof(size_t))
0N/A#define size_addr_from_obj(p) ((size_t*)p - 1)
0N/A// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
0N/A// NB: cannot be debug variable, because these aren't set from the command line until
0N/A// *after* the first few allocs already happened
0N/A#define MallocCushion 16
0N/A#else
0N/A#define space_before 0
0N/A#define space_after 0
0N/A#define size_addr_from_base(p) should not use w/o ASSERT
0N/A#define size_addr_from_obj(p) should not use w/o ASSERT
0N/A#define MallocCushion 0
0N/A#endif
0N/A#define paranoid 0 /* only set to 1 if you suspect checking code has bug */
0N/A
0N/A#ifdef ASSERT
0N/Ainline size_t get_size(void* obj) {
0N/A size_t size = *size_addr_from_obj(obj);
1410N/A if (size < 0) {
1410N/A fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten ("
1410N/A SIZE_FORMAT ")", obj, size));
1410N/A }
0N/A return size;
0N/A}
0N/A
0N/Au_char* find_cushion_backwards(u_char* start) {
0N/A u_char* p = start;
0N/A while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
0N/A p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
0N/A // ok, we have four consecutive marker bytes; find start
0N/A u_char* q = p - 4;
0N/A while (*q == badResourceValue) q--;
0N/A return q + 1;
0N/A}
0N/A
0N/Au_char* find_cushion_forwards(u_char* start) {
0N/A u_char* p = start;
0N/A while (p[0] != badResourceValue || p[1] != badResourceValue ||
0N/A p[2] != badResourceValue || p[3] != badResourceValue) p++;
0N/A // ok, we have four consecutive marker bytes; find end of cushion
0N/A u_char* q = p + 4;
0N/A while (*q == badResourceValue) q++;
0N/A return q - MallocCushion;
0N/A}
0N/A
0N/Avoid print_neighbor_blocks(void* ptr) {
0N/A // find block allocated before ptr (not entirely crash-proof)
0N/A if (MallocCushion < 4) {
0N/A tty->print_cr("### cannot find previous block (MallocCushion < 4)");
0N/A return;
0N/A }
0N/A u_char* start_of_this_block = (u_char*)ptr - space_before;
0N/A u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
0N/A // look for cushion in front of prev. block
0N/A u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
0N/A ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
0N/A u_char* obj = start_of_prev_block + space_before;
0N/A if (size <= 0 ) {
0N/A // start is bad; mayhave been confused by OS data inbetween objects
0N/A // search one more backwards
0N/A start_of_prev_block = find_cushion_backwards(start_of_prev_block);
0N/A size = *size_addr_from_base(start_of_prev_block);
0N/A obj = start_of_prev_block + space_before;
0N/A }
0N/A
0N/A if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
2122N/A tty->print_cr("### previous object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
0N/A } else {
2122N/A tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
0N/A }
0N/A
0N/A // now find successor block
0N/A u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
0N/A start_of_next_block = find_cushion_forwards(start_of_next_block);
0N/A u_char* next_obj = start_of_next_block + space_before;
0N/A ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
0N/A if (start_of_next_block[0] == badResourceValue &&
0N/A start_of_next_block[1] == badResourceValue &&
0N/A start_of_next_block[2] == badResourceValue &&
0N/A start_of_next_block[3] == badResourceValue) {
2122N/A tty->print_cr("### next object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
0N/A } else {
2122N/A tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
0N/A }
0N/A}
0N/A
0N/A
0N/Avoid report_heap_error(void* memblock, void* bad, const char* where) {
2122N/A tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
2122N/A tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock);
0N/A print_neighbor_blocks(memblock);
0N/A fatal("memory stomping error");
0N/A}
0N/A
0N/Avoid verify_block(void* memblock) {
0N/A size_t size = get_size(memblock);
0N/A if (MallocCushion) {
0N/A u_char* ptr = (u_char*)memblock - space_before;
0N/A for (int i = 0; i < MallocCushion; i++) {
0N/A if (ptr[i] != badResourceValue) {
0N/A report_heap_error(memblock, ptr+i, "in front of");
0N/A }
0N/A }
0N/A u_char* end = (u_char*)memblock + size + space_after;
0N/A for (int j = -MallocCushion; j < 0; j++) {
0N/A if (end[j] != badResourceValue) {
0N/A report_heap_error(memblock, end+j, "after");
0N/A }
0N/A }
0N/A }
0N/A}
0N/A#endif
0N/A
3863N/Avoid* os::malloc(size_t size, MEMFLAGS memflags, address caller) {
2122N/A NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
2122N/A NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
0N/A
0N/A if (size == 0) {
0N/A // return a valid pointer if size is zero
0N/A // if NULL is returned the calling functions assume out of memory.
0N/A size = 1;
0N/A }
0N/A
0N/A NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
0N/A u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
3863N/A
0N/A#ifdef ASSERT
0N/A if (ptr == NULL) return NULL;
0N/A if (MallocCushion) {
0N/A for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
0N/A u_char* end = ptr + space_before + size;
0N/A for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
0N/A for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
0N/A }
0N/A // put size just before data
0N/A *size_addr_from_base(ptr) = size;
0N/A#endif
0N/A u_char* memblock = ptr + space_before;
0N/A if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
2122N/A tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
0N/A breakpoint();
0N/A }
0N/A debug_only(if (paranoid) verify_block(memblock));
2122N/A if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
3863N/A
3863N/A // we do not track MallocCushion memory
3863N/A MemTracker::record_malloc((address)memblock, size, memflags, caller == 0 ? CALLER_PC : caller);
3863N/A
0N/A return memblock;
0N/A}
0N/A
0N/A
3863N/Avoid* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller) {
0N/A#ifndef ASSERT
2122N/A NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
2122N/A NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
4559N/A MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
3863N/A void* ptr = ::realloc(memblock, size);
4064N/A if (ptr != NULL) {
4559N/A tkr.record((address)memblock, (address)ptr, size, memflags,
3863N/A caller == 0 ? CALLER_PC : caller);
4559N/A } else {
4559N/A tkr.discard();
3863N/A }
3863N/A return ptr;
0N/A#else
0N/A if (memblock == NULL) {
3863N/A return malloc(size, memflags, (caller == 0 ? CALLER_PC : caller));
0N/A }
0N/A if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
2122N/A tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
0N/A breakpoint();
0N/A }
0N/A verify_block(memblock);
0N/A NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
0N/A if (size == 0) return NULL;
0N/A // always move the block
3863N/A void* ptr = malloc(size, memflags, caller == 0 ? CALLER_PC : caller);
2122N/A if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
0N/A // Copy to new memory if malloc didn't fail
0N/A if ( ptr != NULL ) {
0N/A memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
0N/A if (paranoid) verify_block(ptr);
0N/A if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
2122N/A tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
0N/A breakpoint();
0N/A }
0N/A free(memblock);
0N/A }
0N/A return ptr;
0N/A#endif
0N/A}
0N/A
0N/A
3863N/Avoid os::free(void *memblock, MEMFLAGS memflags) {
2122N/A NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
0N/A#ifdef ASSERT
0N/A if (memblock == NULL) return;
0N/A if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
2122N/A if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
0N/A breakpoint();
0N/A }
0N/A verify_block(memblock);
0N/A NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
0N/A // Added by detlefs.
0N/A if (MallocCushion) {
0N/A u_char* ptr = (u_char*)memblock - space_before;
0N/A for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
0N/A guarantee(*p == badResourceValue,
0N/A "Thing freed should be malloc result.");
0N/A *p = (u_char)freeBlockPad;
0N/A }
0N/A size_t size = get_size(memblock);
2122N/A inc_stat_counter(&free_bytes, size);
0N/A u_char* end = ptr + space_before + size;
0N/A for (u_char* q = end; q < end + MallocCushion; q++) {
0N/A guarantee(*q == badResourceValue,
0N/A "Thing freed should be malloc result.");
0N/A *q = (u_char)freeBlockPad;
0N/A }
2122N/A if (PrintMalloc && tty != NULL)
2180N/A fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock);
2122N/A } else if (PrintMalloc && tty != NULL) {
2122N/A // tty->print_cr("os::free %p", memblock);
2180N/A fprintf(stderr, "os::free " PTR_FORMAT "\n", (uintptr_t)memblock);
0N/A }
0N/A#endif
3863N/A MemTracker::record_free((address)memblock, memflags);
3863N/A
0N/A ::free((char*)memblock - space_before);
0N/A}
0N/A
0N/Avoid os::init_random(long initval) {
0N/A _rand_seed = initval;
0N/A}
0N/A
0N/A
0N/Along os::random() {
0N/A /* standard, well-known linear congruential random generator with
0N/A * next_rand = (16807*seed) mod (2**31-1)
0N/A * see
0N/A * (1) "Random Number Generators: Good Ones Are Hard to Find",
0N/A * S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
0N/A * (2) "Two Fast Implementations of the 'Minimal Standard' Random
0N/A * Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
0N/A */
0N/A const long a = 16807;
0N/A const unsigned long m = 2147483647;
0N/A const long q = m / a; assert(q == 127773, "weird math");
0N/A const long r = m % a; assert(r == 2836, "weird math");
0N/A
0N/A // compute az=2^31p+q
0N/A unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
0N/A unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
0N/A lo += (hi & 0x7FFF) << 16;
0N/A
0N/A // if q overflowed, ignore the overflow and increment q
0N/A if (lo > m) {
0N/A lo &= m;
0N/A ++lo;
0N/A }
0N/A lo += hi >> 15;
0N/A
0N/A // if (p+q) overflowed, ignore the overflow and increment (p+q)
0N/A if (lo > m) {
0N/A lo &= m;
0N/A ++lo;
0N/A }
0N/A return (_rand_seed = lo);
0N/A}
0N/A
0N/A// The INITIALIZED state is distinguished from the SUSPENDED state because the
0N/A// conditions in which a thread is first started are different from those in which
0N/A// a suspension is resumed. These differences make it hard for us to apply the
0N/A// tougher checks when starting threads that we want to do when resuming them.
0N/A// However, when start_thread is called as a result of Thread.start, on a Java
0N/A// thread, the operation is synchronized on the Java Thread object. So there
0N/A// cannot be a race to start the thread and hence for the thread to exit while
0N/A// we are working on it. Non-Java threads that start Java threads either have
0N/A// to do so in a context in which races are impossible, or should do appropriate
0N/A// locking.
0N/A
0N/Avoid os::start_thread(Thread* thread) {
0N/A // guard suspend/resume
0N/A MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
0N/A OSThread* osthread = thread->osthread();
0N/A osthread->set_state(RUNNABLE);
0N/A pd_start_thread(thread);
0N/A}
0N/A
0N/A//---------------------------------------------------------------------------
0N/A// Helper functions for fatal error handler
0N/A
0N/Avoid os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
0N/A assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
0N/A
0N/A int cols = 0;
0N/A int cols_per_line = 0;
0N/A switch (unitsize) {
0N/A case 1: cols_per_line = 16; break;
0N/A case 2: cols_per_line = 8; break;
0N/A case 4: cols_per_line = 4; break;
0N/A case 8: cols_per_line = 2; break;
0N/A default: return;
0N/A }
0N/A
0N/A address p = start;
0N/A st->print(PTR_FORMAT ": ", start);
0N/A while (p < end) {
0N/A switch (unitsize) {
0N/A case 1: st->print("%02x", *(u1*)p); break;
0N/A case 2: st->print("%04x", *(u2*)p); break;
0N/A case 4: st->print("%08x", *(u4*)p); break;
0N/A case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
0N/A }
0N/A p += unitsize;
0N/A cols++;
0N/A if (cols >= cols_per_line && p < end) {
0N/A cols = 0;
0N/A st->cr();
0N/A st->print(PTR_FORMAT ": ", p);
0N/A } else {
0N/A st->print(" ");
0N/A }
0N/A }
0N/A st->cr();
0N/A}
0N/A
0N/Avoid os::print_environment_variables(outputStream* st, const char** env_list,
0N/A char* buffer, int len) {
0N/A if (env_list) {
0N/A st->print_cr("Environment Variables:");
0N/A
0N/A for (int i = 0; env_list[i] != NULL; i++) {
0N/A if (getenv(env_list[i], buffer, len)) {
0N/A st->print(env_list[i]);
0N/A st->print("=");
0N/A st->print_cr(buffer);
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/Avoid os::print_cpu_info(outputStream* st) {
0N/A // cpu
0N/A st->print("CPU:");
0N/A st->print("total %d", os::processor_count());
0N/A // It's not safe to query number of active processors after crash
0N/A // st->print("(active %d)", os::active_processor_count());
0N/A st->print(" %s", VM_Version::cpu_features());
0N/A st->cr();
2625N/A pd_print_cpu_info(st);
0N/A}
0N/A
0N/Avoid os::print_date_and_time(outputStream *st) {
0N/A time_t tloc;
0N/A (void)time(&tloc);
0N/A st->print("time: %s", ctime(&tloc)); // ctime adds newline.
0N/A
0N/A double t = os::elapsedTime();
0N/A // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
0N/A // Linux. Must be a bug in glibc ? Workaround is to round "t" to int
0N/A // before printf. We lost some precision, but who cares?
0N/A st->print_cr("elapsed time: %d seconds", (int)t);
0N/A}
0N/A
1601N/A// moved from debug.cpp (used to be find()) but still called from there
1827N/A// The verbose parameter is only set by the debug code in one case
1827N/Avoid os::print_location(outputStream* st, intptr_t x, bool verbose) {
1601N/A address addr = (address)x;
1601N/A CodeBlob* b = CodeCache::find_blob_unsafe(addr);
1601N/A if (b != NULL) {
1601N/A if (b->is_buffer_blob()) {
1601N/A // the interpreter is generated into a buffer blob
1601N/A InterpreterCodelet* i = Interpreter::codelet_containing(addr);
1601N/A if (i != NULL) {
3932N/A st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
1601N/A i->print_on(st);
1601N/A return;
1601N/A }
1601N/A if (Interpreter::contains(addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
1601N/A " (not bytecode specific)", addr);
1601N/A return;
1601N/A }
1601N/A //
1601N/A if (AdapterHandlerLibrary::contains(b)) {
3932N/A st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
1601N/A AdapterHandlerLibrary::print_handler_on(st, b);
1601N/A }
1601N/A // the stubroutines are generated into a buffer blob
1601N/A StubCodeDesc* d = StubCodeDesc::desc_for(addr);
1601N/A if (d != NULL) {
3932N/A st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
1601N/A d->print_on(st);
3932N/A st->cr();
1601N/A return;
1601N/A }
1601N/A if (StubRoutines::contains(addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
1601N/A "stub routine", addr);
1601N/A return;
1601N/A }
1601N/A // the InlineCacheBuffer is using stubs generated into a buffer blob
1601N/A if (InlineCacheBuffer::contains(addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
1601N/A return;
1601N/A }
1601N/A VtableStub* v = VtableStubs::stub_containing(addr);
1601N/A if (v != NULL) {
3932N/A st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
1601N/A v->print_on(st);
3932N/A st->cr();
1601N/A return;
1601N/A }
1601N/A }
3932N/A nmethod* nm = b->as_nmethod_or_null();
3932N/A if (nm != NULL) {
1601N/A ResourceMark rm;
3932N/A st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
3932N/A addr, (int)(addr - nm->entry_point()), nm);
3932N/A if (verbose) {
3932N/A st->print(" for ");
3932N/A nm->method()->print_value_on(st);
3932N/A }
4203N/A st->cr();
3932N/A nm->print_nmethod(verbose);
1601N/A return;
1601N/A }
3932N/A st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
1601N/A b->print_on(st);
1601N/A return;
1601N/A }
1601N/A
1601N/A if (Universe::heap()->is_in(addr)) {
1601N/A HeapWord* p = Universe::heap()->block_start(addr);
1601N/A bool print = false;
1601N/A // If we couldn't find it it just may mean that heap wasn't parseable
1601N/A // See if we were just given an oop directly
1601N/A if (p != NULL && Universe::heap()->block_is_obj(p)) {
1601N/A print = true;
1601N/A } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
1601N/A p = (HeapWord*) addr;
1601N/A print = true;
1601N/A }
1601N/A if (print) {
4236N/A if (p == (HeapWord*) addr) {
4236N/A st->print_cr(INTPTR_FORMAT " is an oop", addr);
4236N/A } else {
4236N/A st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
4236N/A }
1601N/A oop(p)->print_on(st);
1601N/A if (p != (HeapWord*)x && oop(p)->is_constMethod() &&
1601N/A constMethodOop(p)->contains(addr)) {
1601N/A Thread *thread = Thread::current();
1601N/A HandleMark hm(thread);
1601N/A methodHandle mh (thread, constMethodOop(p)->method());
1601N/A if (!mh->is_native()) {
1601N/A st->print_cr("bci_from(%p) = %d; print_codes():",
1601N/A addr, mh->bci_from(address(x)));
1601N/A mh->print_codes_on(st);
1601N/A }
1601N/A }
1601N/A return;
1601N/A }
1601N/A } else {
1601N/A if (Universe::heap()->is_in_reserved(addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is an unallocated location "
1601N/A "in the heap", addr);
1601N/A return;
1601N/A }
1601N/A }
1601N/A if (JNIHandles::is_global_handle((jobject) addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
1601N/A return;
1601N/A }
1601N/A if (JNIHandles::is_weak_global_handle((jobject) addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
1601N/A return;
1601N/A }
1601N/A#ifndef PRODUCT
1601N/A // we don't keep the block list in product mode
1601N/A if (JNIHandleBlock::any_contains((jobject) addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
1601N/A return;
1601N/A }
1601N/A#endif
1601N/A
1601N/A for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
1601N/A // Check for privilege stack
1601N/A if (thread->privileged_stack_top() != NULL &&
1601N/A thread->privileged_stack_top()->contains(addr)) {
1601N/A st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
1601N/A "for thread: " INTPTR_FORMAT, addr, thread);
1827N/A if (verbose) thread->print_on(st);
1601N/A return;
1601N/A }
1601N/A // If the addr is a java thread print information about that.
1601N/A if (addr == (address)thread) {
1827N/A if (verbose) {
1827N/A thread->print_on(st);
1827N/A } else {
1827N/A st->print_cr(INTPTR_FORMAT " is a thread", addr);
1827N/A }
1601N/A return;
1601N/A }
1601N/A // If the addr is in the stack region for this thread then report that
1601N/A // and print thread info
1601N/A if (thread->stack_base() >= addr &&
1601N/A addr > (thread->stack_base() - thread->stack_size())) {
1601N/A st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1601N/A INTPTR_FORMAT, addr, thread);
1827N/A if (verbose) thread->print_on(st);
1601N/A return;
1601N/A }
1601N/A
1601N/A }
1601N/A // Try an OS specific find
1601N/A if (os::find(addr, st)) {
1601N/A return;
1601N/A }
1601N/A
1827N/A st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
1601N/A}
0N/A
0N/A// Looks like all platforms except IA64 can use the same function to check
0N/A// if C stack is walkable beyond current frame. The check for fp() is not
0N/A// necessary on Sparc, but it's harmless.
0N/Abool os::is_first_C_frame(frame* fr) {
0N/A#ifdef IA64
0N/A // In order to walk native frames on Itanium, we need to access the unwind
0N/A // table, which is inside ELF. We don't want to parse ELF after fatal error,
0N/A // so return true for IA64. If we need to support C stack walking on IA64,
0N/A // this function needs to be moved to CPU specific files, as fp() on IA64
0N/A // is register stack, which grows towards higher memory address.
0N/A return true;
0N/A#endif
0N/A
0N/A // Load up sp, fp, sender sp and sender fp, check for reasonable values.
0N/A // Check usp first, because if that's bad the other accessors may fault
0N/A // on some architectures. Ditto ufp second, etc.
0N/A uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
0N/A // sp on amd can be 32 bit aligned.
0N/A uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
0N/A
0N/A uintptr_t usp = (uintptr_t)fr->sp();
0N/A if ((usp & sp_align_mask) != 0) return true;
0N/A
0N/A uintptr_t ufp = (uintptr_t)fr->fp();
0N/A if ((ufp & fp_align_mask) != 0) return true;
0N/A
0N/A uintptr_t old_sp = (uintptr_t)fr->sender_sp();
0N/A if ((old_sp & sp_align_mask) != 0) return true;
0N/A if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
0N/A
0N/A uintptr_t old_fp = (uintptr_t)fr->link();
0N/A if ((old_fp & fp_align_mask) != 0) return true;
0N/A if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
0N/A
0N/A // stack grows downwards; if old_fp is below current fp or if the stack
0N/A // frame is too large, either the stack is corrupted or fp is not saved
0N/A // on stack (i.e. on x86, ebp may be used as general register). The stack
0N/A // is not walkable beyond current frame.
0N/A if (old_fp < ufp) return true;
0N/A if (old_fp - ufp > 64 * K) return true;
0N/A
0N/A return false;
0N/A}
0N/A
0N/A#ifdef ASSERT
0N/Aextern "C" void test_random() {
0N/A const double m = 2147483647;
0N/A double mean = 0.0, variance = 0.0, t;
0N/A long reps = 10000;
0N/A unsigned long seed = 1;
0N/A
0N/A tty->print_cr("seed %ld for %ld repeats...", seed, reps);
0N/A os::init_random(seed);
0N/A long num;
0N/A for (int k = 0; k < reps; k++) {
0N/A num = os::random();
0N/A double u = (double)num / m;
0N/A assert(u >= 0.0 && u <= 1.0, "bad random number!");
0N/A
0N/A // calculate mean and variance of the random sequence
0N/A mean += u;
0N/A variance += (u*u);
0N/A }
0N/A mean /= reps;
0N/A variance /= (reps - 1);
0N/A
0N/A assert(num == 1043618065, "bad seed");
0N/A tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
0N/A tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
0N/A const double eps = 0.0001;
0N/A t = fabsd(mean - 0.5018);
0N/A assert(t < eps, "bad mean");
0N/A t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
0N/A assert(t < eps, "bad variance");
0N/A}
0N/A#endif
0N/A
0N/A
0N/A// Set up the boot classpath.
0N/A
0N/Achar* os::format_boot_path(const char* format_string,
0N/A const char* home,
0N/A int home_len,
0N/A char fileSep,
0N/A char pathSep) {
0N/A assert((fileSep == '/' && pathSep == ':') ||
0N/A (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
0N/A
0N/A // Scan the format string to determine the length of the actual
0N/A // boot classpath, and handle platform dependencies as well.
0N/A int formatted_path_len = 0;
0N/A const char* p;
0N/A for (p = format_string; *p != 0; ++p) {
0N/A if (*p == '%') formatted_path_len += home_len - 1;
0N/A ++formatted_path_len;
0N/A }
0N/A
3863N/A char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
0N/A if (formatted_path == NULL) {
0N/A return NULL;
0N/A }
0N/A
0N/A // Create boot classpath from format, substituting separator chars and
0N/A // java home directory.
0N/A char* q = formatted_path;
0N/A for (p = format_string; *p != 0; ++p) {
0N/A switch (*p) {
0N/A case '%':
0N/A strcpy(q, home);
0N/A q += home_len;
0N/A break;
0N/A case '/':
0N/A *q++ = fileSep;
0N/A break;
0N/A case ':':
0N/A *q++ = pathSep;
0N/A break;
0N/A default:
0N/A *q++ = *p;
0N/A }
0N/A }
0N/A *q = '\0';
0N/A
0N/A assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
0N/A return formatted_path;
0N/A}
0N/A
0N/A
0N/Abool os::set_boot_path(char fileSep, char pathSep) {
0N/A const char* home = Arguments::get_java_home();
0N/A int home_len = (int)strlen(home);
0N/A
0N/A static const char* meta_index_dir_format = "%/lib/";
0N/A static const char* meta_index_format = "%/lib/meta-index";
0N/A char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
0N/A if (meta_index == NULL) return false;
0N/A char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
0N/A if (meta_index_dir == NULL) return false;
0N/A Arguments::set_meta_index_path(meta_index, meta_index_dir);
0N/A
0N/A // Any modification to the JAR-file list, for the boot classpath must be
0N/A // aligned with install/install/make/common/Pack.gmk. Note: boot class
0N/A // path class JARs, are stripped for StackMapTable to reduce download size.
0N/A static const char classpath_format[] =
0N/A "%/lib/resources.jar:"
0N/A "%/lib/rt.jar:"
0N/A "%/lib/sunrsasign.jar:"
0N/A "%/lib/jsse.jar:"
0N/A "%/lib/jce.jar:"
0N/A "%/lib/charsets.jar:"
3081N/A "%/lib/jfr.jar:"
2842N/A#ifdef __APPLE__
2842N/A "%/lib/JObjC.jar:"
2842N/A#endif
0N/A "%/classes";
0N/A char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
0N/A if (sysclasspath == NULL) return false;
0N/A Arguments::set_sysclasspath(sysclasspath);
0N/A
0N/A return true;
0N/A}
0N/A
691N/A/*
691N/A * Splits a path, based on its separator, the number of
691N/A * elements is returned back in n.
691N/A * It is the callers responsibility to:
691N/A * a> check the value of n, and n may be 0.
691N/A * b> ignore any empty path elements
691N/A * c> free up the data.
691N/A */
691N/Achar** os::split_path(const char* path, int* n) {
691N/A *n = 0;
691N/A if (path == NULL || strlen(path) == 0) {
691N/A return NULL;
691N/A }
691N/A const char psepchar = *os::path_separator();
3863N/A char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
691N/A if (inpath == NULL) {
691N/A return NULL;
691N/A }
691N/A strncpy(inpath, path, strlen(path));
691N/A int count = 1;
691N/A char* p = strchr(inpath, psepchar);
691N/A // Get a count of elements to allocate memory
691N/A while (p != NULL) {
691N/A count++;
691N/A p++;
691N/A p = strchr(p, psepchar);
691N/A }
3863N/A char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal);
691N/A if (opath == NULL) {
691N/A return NULL;
691N/A }
691N/A
691N/A // do the actual splitting
691N/A p = inpath;
691N/A for (int i = 0 ; i < count ; i++) {
691N/A size_t len = strcspn(p, os::path_separator());
691N/A if (len > JVM_MAXPATHLEN) {
691N/A return NULL;
691N/A }
691N/A // allocate the string and add terminator storage
3863N/A char* s = (char*)NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
691N/A if (s == NULL) {
691N/A return NULL;
691N/A }
691N/A strncpy(s, p, len);
691N/A s[len] = '\0';
691N/A opath[i] = s;
691N/A p += len + 1;
691N/A }
3863N/A FREE_C_HEAP_ARRAY(char, inpath, mtInternal);
691N/A *n = count;
691N/A return opath;
691N/A}
691N/A
0N/Avoid os::set_memory_serialize_page(address page) {
0N/A int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
0N/A _mem_serialize_page = (volatile int32_t *)page;
0N/A // We initialize the serialization page shift count here
0N/A // We assume a cache line size of 64 bytes
0N/A assert(SerializePageShiftCount == count,
0N/A "thread size changed, fix SerializePageShiftCount constant");
0N/A set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
0N/A}
0N/A
55N/Astatic volatile intptr_t SerializePageLock = 0;
55N/A
0N/A// This method is called from signal handler when SIGSEGV occurs while the current
0N/A// thread tries to store to the "read-only" memory serialize page during state
0N/A// transition.
0N/Avoid os::block_on_serialize_page_trap() {
0N/A if (TraceSafepoint) {
0N/A tty->print_cr("Block until the serialize page permission restored");
0N/A }
55N/A // When VMThread is holding the SerializePageLock during modifying the
0N/A // access permission of the memory serialize page, the following call
0N/A // will block until the permission of that page is restored to rw.
0N/A // Generally, it is unsafe to manipulate locks in signal handlers, but in
0N/A // this case, it's OK as the signal is synchronous and we know precisely when
55N/A // it can occur.
55N/A Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
55N/A Thread::muxRelease(&SerializePageLock);
0N/A}
0N/A
0N/A// Serialize all thread state variables
0N/Avoid os::serialize_thread_states() {
0N/A // On some platforms such as Solaris & Linux, the time duration of the page
0N/A // permission restoration is observed to be much longer than expected due to
0N/A // scheduler starvation problem etc. To avoid the long synchronization
55N/A // time and expensive page trap spinning, 'SerializePageLock' is used to block
55N/A // the mutator thread if such case is encountered. See bug 6546278 for details.
55N/A Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
237N/A os::protect_memory((char *)os::get_memory_serialize_page(),
477N/A os::vm_page_size(), MEM_PROT_READ);
477N/A os::protect_memory((char *)os::get_memory_serialize_page(),
477N/A os::vm_page_size(), MEM_PROT_RW);
55N/A Thread::muxRelease(&SerializePageLock);
0N/A}
0N/A
0N/A// Returns true if the current stack pointer is above the stack shadow
0N/A// pages, false otherwise.
0N/A
0N/Abool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
0N/A assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
0N/A address sp = current_stack_pointer();
0N/A // Check if we have StackShadowPages above the yellow zone. This parameter
605N/A // is dependent on the depth of the maximum VM call stack possible from
0N/A // the handler for stack overflow. 'instanceof' in the stack overflow
0N/A // handler or a println uses at least 8k stack of VM and native code
0N/A // respectively.
0N/A const int framesize_in_bytes =
0N/A Interpreter::size_top_interpreter_activation(method()) * wordSize;
0N/A int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
0N/A * vm_page_size()) + framesize_in_bytes;
0N/A // The very lower end of the stack
0N/A address stack_limit = thread->stack_base() - thread->stack_size();
0N/A return (sp > (stack_limit + reserved_area));
0N/A}
0N/A
0N/Asize_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
0N/A uint min_pages)
0N/A{
0N/A assert(min_pages > 0, "sanity");
0N/A if (UseLargePages) {
0N/A const size_t max_page_size = region_max_size / min_pages;
0N/A
0N/A for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
0N/A const size_t sz = _page_sizes[i];
0N/A const size_t mask = sz - 1;
0N/A if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
0N/A // The largest page size with no fragmentation.
0N/A return sz;
0N/A }
0N/A
0N/A if (sz <= max_page_size) {
0N/A // The largest page size that satisfies the min_pages requirement.
0N/A return sz;
0N/A }
0N/A }
0N/A }
0N/A
0N/A return vm_page_size();
0N/A}
0N/A
0N/A#ifndef PRODUCT
2684N/Avoid os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
2684N/A{
2684N/A if (TracePageSizes) {
2684N/A tty->print("%s: ", str);
2684N/A for (int i = 0; i < count; ++i) {
2684N/A tty->print(" " SIZE_FORMAT, page_sizes[i]);
2684N/A }
2684N/A tty->cr();
2684N/A }
2684N/A}
2684N/A
0N/Avoid os::trace_page_sizes(const char* str, const size_t region_min_size,
0N/A const size_t region_max_size, const size_t page_size,
0N/A const char* base, const size_t size)
0N/A{
0N/A if (TracePageSizes) {
0N/A tty->print_cr("%s: min=" SIZE_FORMAT " max=" SIZE_FORMAT
0N/A " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
0N/A " size=" SIZE_FORMAT,
0N/A str, region_min_size, region_max_size,
0N/A page_size, base, size);
0N/A }
0N/A}
0N/A#endif // #ifndef PRODUCT
0N/A
0N/A// This is the working definition of a server class machine:
0N/A// >= 2 physical CPU's and >=2GB of memory, with some fuzz
0N/A// because the graphics memory (?) sometimes masks physical memory.
0N/A// If you want to change the definition of a server class machine
0N/A// on some OS or platform, e.g., >=4GB on Windohs platforms,
0N/A// then you'll have to parameterize this method based on that state,
0N/A// as was done for logical processors here, or replicate and
0N/A// specialize this method for each platform. (Or fix os to have
0N/A// some inheritance structure and use subclassing. Sigh.)
0N/A// If you want some platform to always or never behave as a server
0N/A// class machine, change the setting of AlwaysActAsServerClassMachine
0N/A// and NeverActAsServerClassMachine in globals*.hpp.
0N/Abool os::is_server_class_machine() {
0N/A // First check for the early returns
0N/A if (NeverActAsServerClassMachine) {
0N/A return false;
0N/A }
0N/A if (AlwaysActAsServerClassMachine) {
0N/A return true;
0N/A }
0N/A // Then actually look at the machine
0N/A bool result = false;
0N/A const unsigned int server_processors = 2;
0N/A const julong server_memory = 2UL * G;
0N/A // We seem not to get our full complement of memory.
0N/A // We allow some part (1/8?) of the memory to be "missing",
0N/A // based on the sizes of DIMMs, and maybe graphics cards.
0N/A const julong missing_memory = 256UL * M;
0N/A
0N/A /* Is this a server class machine? */
0N/A if ((os::active_processor_count() >= (int)server_processors) &&
0N/A (os::physical_memory() >= (server_memory - missing_memory))) {
0N/A const unsigned int logical_processors =
0N/A VM_Version::logical_processors_per_package();
0N/A if (logical_processors > 1) {
0N/A const unsigned int physical_packages =
0N/A os::active_processor_count() / logical_processors;
0N/A if (physical_packages > server_processors) {
0N/A result = true;
0N/A }
0N/A } else {
0N/A result = true;
0N/A }
0N/A }
0N/A return result;
0N/A}
2316N/A
2316N/A// Read file line by line, if line is longer than bsize,
2316N/A// skip rest of line.
2316N/Aint os::get_line_chars(int fd, char* buf, const size_t bsize){
2316N/A size_t sz, i = 0;
2316N/A
2316N/A // read until EOF, EOL or buf is full
2657N/A while ((sz = (int) read(fd, &buf[i], 1)) == 1 && i < (bsize-2) && buf[i] != '\n') {
2316N/A ++i;
2316N/A }
2316N/A
2316N/A if (buf[i] == '\n') {
2316N/A // EOL reached so ignore EOL character and return
2316N/A
2316N/A buf[i] = 0;
2316N/A return (int) i;
2316N/A }
2316N/A
2316N/A buf[i+1] = 0;
2316N/A
2316N/A if (sz != 1) {
2316N/A // EOF reached. if we read chars before EOF return them and
2316N/A // return EOF on next call otherwise return EOF
2316N/A
2316N/A return (i == 0) ? -1 : (int) i;
2316N/A }
2316N/A
2316N/A // line is longer than size of buf, skip to EOL
2657N/A char ch;
2316N/A while (read(fd, &ch, 1) == 1 && ch != '\n') {
2316N/A // Do nothing
2316N/A }
2316N/A
2316N/A // return initial part of line that fits in buf.
2316N/A // If we reached EOF, it will be returned on next call.
2316N/A
2316N/A return (int) i;
2316N/A}
3863N/A
4141N/Avoid os::SuspendedThreadTask::run() {
4141N/A assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
4141N/A internal_do_task();
4141N/A _done = true;
4141N/A}
4141N/A
3863N/Abool os::create_stack_guard_pages(char* addr, size_t bytes) {
3863N/A return os::pd_create_stack_guard_pages(addr, bytes);
3863N/A}
3863N/A
3863N/Achar* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
3863N/A char* result = pd_reserve_memory(bytes, addr, alignment_hint);
4064N/A if (result != NULL) {
4559N/A MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
3863N/A }
3863N/A
3863N/A return result;
3863N/A}
4499N/A
4499N/Achar* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
4499N/A MEMFLAGS flags) {
4499N/A char* result = pd_reserve_memory(bytes, addr, alignment_hint);
4499N/A if (result != NULL) {
4559N/A MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
4499N/A MemTracker::record_virtual_memory_type((address)result, flags);
4499N/A }
4499N/A
4499N/A return result;
4499N/A}
4499N/A
3863N/Achar* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
3863N/A char* result = pd_attempt_reserve_memory_at(bytes, addr);
4064N/A if (result != NULL) {
4559N/A MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
3863N/A }
3863N/A return result;
3863N/A}
3863N/A
3863N/Avoid os::split_reserved_memory(char *base, size_t size,
3863N/A size_t split, bool realloc) {
3863N/A pd_split_reserved_memory(base, size, split, realloc);
3863N/A}
3863N/A
3863N/Abool os::commit_memory(char* addr, size_t bytes, bool executable) {
3863N/A bool res = pd_commit_memory(addr, bytes, executable);
4064N/A if (res) {
3863N/A MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
3863N/A }
3863N/A return res;
3863N/A}
3863N/A
3863N/Abool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
3863N/A bool executable) {
3863N/A bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
4064N/A if (res) {
3863N/A MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
3863N/A }
3863N/A return res;
3863N/A}
3863N/A
4552N/Avoid os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
4552N/A const char* mesg) {
4552N/A pd_commit_memory_or_exit(addr, bytes, executable, mesg);
4552N/A MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
4552N/A}
4552N/A
4552N/Avoid os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
4552N/A bool executable, const char* mesg) {
4552N/A os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
4552N/A MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
4552N/A}
4552N/A
3863N/Abool os::uncommit_memory(char* addr, size_t bytes) {
4559N/A MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
3863N/A bool res = pd_uncommit_memory(addr, bytes);
3863N/A if (res) {
4559N/A tkr.record((address)addr, bytes);
4559N/A } else {
4559N/A tkr.discard();
3863N/A }
3863N/A return res;
3863N/A}
3863N/A
3863N/Abool os::release_memory(char* addr, size_t bytes) {
4559N/A MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
3863N/A bool res = pd_release_memory(addr, bytes);
3863N/A if (res) {
4559N/A tkr.record((address)addr, bytes);
4559N/A } else {
4559N/A tkr.discard();
3863N/A }
3863N/A return res;
3863N/A}
3863N/A
4525N/Abool os::release_or_uncommit_partial_region(char * addr, size_t bytes) {
4525N/A if (can_release_partial_region()) {
4525N/A return release_memory(addr, bytes);
4525N/A }
4525N/A return uncommit_memory(addr, bytes);
4525N/A}
3863N/A
3863N/Achar* os::map_memory(int fd, const char* file_name, size_t file_offset,
3863N/A char *addr, size_t bytes, bool read_only,
3863N/A bool allow_exec) {
3863N/A char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
4064N/A if (result != NULL) {
4559N/A MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, mtNone, CALLER_PC);
3863N/A }
3863N/A return result;
3863N/A}
3863N/A
3863N/Achar* os::remap_memory(int fd, const char* file_name, size_t file_offset,
3863N/A char *addr, size_t bytes, bool read_only,
3863N/A bool allow_exec) {
3863N/A return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
3863N/A read_only, allow_exec);
3863N/A}
3863N/A
3863N/Abool os::unmap_memory(char *addr, size_t bytes) {
4559N/A MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
3863N/A bool result = pd_unmap_memory(addr, bytes);
3863N/A if (result) {
4559N/A tkr.record((address)addr, bytes);
4559N/A } else {
4559N/A tkr.discard();
3863N/A }
3863N/A return result;
3863N/A}
3863N/A
3863N/Avoid os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
3863N/A pd_free_memory(addr, bytes, alignment_hint);
3863N/A}
3863N/A
3863N/Avoid os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
3863N/A pd_realign_memory(addr, bytes, alignment_hint);
3863N/A}
3863N/A