/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/icBuffer.hpp"
#include "code/vtableStubs.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
#include "interpreter/interpreter.hpp"
#include "memory/allocation.inline.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvm_misc.hpp"
#include "prims/privilegedStack.hpp"
#include "runtime/arguments.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/stubRoutines.hpp"
#include "services/attachListener.hpp"
#include "services/memTracker.hpp"
#include "services/threadService.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/events.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
# include "thread_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
# include "thread_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
# include "thread_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
# include "thread_bsd.inline.hpp"
#endif
# include <signal.h>
#ifndef PRODUCT
#endif
void os_init_globals() {
// Called from init_globals().
// See Threads::create_vm() in thread.cpp, and init.cpp.
os::init_globals();
}
// Fill in buffer with current local time as an ISO-8601 string.
// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
// Returns buffer, or NULL if it failed.
// This would mostly be a call to
// strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
// except that on Windows the %z behaves badly, so we do it ourselves.
// Also, people wanted milliseconds on there,
// and strftime doesn't do milliseconds.
// Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
// 1 2
// 12345678901234567890123456789
static const char* iso8601_format =
"%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
// Sanity check the arguments
assert(false, "NULL buffer");
return NULL;
}
if (buffer_length < needed_buffer) {
assert(false, "buffer_length too small");
return NULL;
}
// Get the current time
const int milliseconds_after_second =
// Convert the time value to a tm and timezone variable
assert(false, "Failed localtime_pd");
return NULL;
}
#if defined(_ALLBSD_SOURCE)
#else
#endif
// If daylight savings time is in effect,
// we are 1 hour East of our time zone
if (time_struct.tm_isdst > 0) {
}
// Compute the time zone offset.
// localtime_pd() sets timezone to the difference (in seconds)
// between UTC and and local time.
// ISO 8601 says we need the difference between local time and UTC,
// we change the sign of the localtime_pd() result.
// Then we have to figure out if if we are ahead (+) or behind (-) UTC.
if (local_to_UTC < 0) {
sign_local_to_UTC = '-';
}
// Convert time zone offset seconds to hours and minutes.
// Print an ISO 8601 date and time stamp into the buffer
year,
zone_min);
if (printed == 0) {
assert(false, "Failed jio_printf");
return NULL;
}
return buffer;
}
#ifdef ASSERT
if (!(!thread->is_Java_thread() ||
|| thread->is_Compiler_thread()
)) {
assert(false, "possibility of dangling Thread pointer");
}
#endif
if (p >= MinPriority && p <= MaxPriority) {
} else {
assert(false, "Should not happen");
return OS_ERR;
}
}
int p;
int os_prio;
priority = (ThreadPriority)p;
return OS_OK;
}
// --------------------- sun.misc.Signal (optional) ---------------------
// SIGBREAK is sent by the keyboard to query the VM state
#ifndef SIGBREAK
#endif
// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
while (true) {
int sig;
{
// FIXME : Currently we have not decieded what should be the status
// for this java thread blocked here. Once we decide about
// that we should fix this.
}
// Terminate the signal thread
return;
}
switch (sig) {
case SIGBREAK: {
// Check if the signal is a trigger to start the Attach Listener - in that
// case don't print stack traces.
continue;
}
// Print stack traces
// Any SIGBREAK operations added here should make sure to flush
// the output stream (e.g. tty->flush()) after output. See 4803766.
// Each module also prints an extra carriage return after its output.
if (PrintClassHistogram) {
true /* need_prologue */);
}
if (JvmtiExport::should_post_data_dump()) {
}
break;
}
default: {
// Dispatch the signal to java
&result,
&args,
);
}
if (HAS_PENDING_EXCEPTION) {
// tty is initialized early so we don't expect it to be null, but
// if it is we can't risk doing an initialization that might
// trigger additional out-of-memory conditions
warning("Exception %s occurred dispatching signal %s to handler"
"- the VM may need to be forcibly terminated",
klass_name, sig_name );
}
}
}
}
}
}
if (!ReduceSignalUsage) {
// Setup JavaThread for processing signals
// Initialize thread_oop to put it into the system threadGroup
CHECK);
thread_oop, // ARG 1
CHECK);
os::signal_init_pd();
// At this point it may be possible that no osthread was created for the
// JavaThread due to lack of memory. We would have to throw an exception
// in that case. However, since this must work and we do not allow
// exceptions anyway, check and abort if this fails.
vm_exit_during_initialization("java.lang.OutOfMemoryError",
"unable to create new native thread");
}
}
// Handle ^BREAK
}
}
if (!ReduceSignalUsage)
}
// --------------------- loading libraries ---------------------
if (_native_java_library == NULL) {
// Try to load verify dll first. In 1.3 java dll depends on it and is not
// always able to find it when the loading executable is outside the JDK.
// In order to keep working with 1.2 we ignore any loading errors.
// Load java dll
if (_native_java_library == NULL) {
}
#if defined(__OpenBSD__)
// Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
// ignore errors
#endif
}
if (onLoaded) {
// We may have to wait to fire OnLoad until TLS is initialized.
if (ThreadLocalStorage::is_initialized()) {
// The JNI_OnLoad handling is normally done by method load in
// java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
// explicitly so we have to check for JNI_OnLoad as well
if (JNI_OnLoad != NULL) {
vm_exit_during_initialization("Unsupported JNI version");
}
}
}
}
return _native_java_library;
}
// --------------------- heap allocation utilities ---------------------
return dup_str;
}
#ifdef ASSERT
// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
// NB: cannot be debug variable, because these aren't set from the command line until
// *after* the first few allocs already happened
#else
#define space_before 0
#define space_after 0
#define MallocCushion 0
#endif
#ifdef ASSERT
if (size < 0) {
}
return size;
}
// ok, we have four consecutive marker bytes; find start
u_char* q = p - 4;
while (*q == badResourceValue) q--;
return q + 1;
}
// ok, we have four consecutive marker bytes; find end of cushion
u_char* q = p + 4;
while (*q == badResourceValue) q++;
return q - MallocCushion;
}
// find block allocated before ptr (not entirely crash-proof)
if (MallocCushion < 4) {
return;
}
// look for cushion in front of prev. block
if (size <= 0 ) {
// start is bad; mayhave been confused by OS data inbetween objects
// search one more backwards
}
} else {
tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
}
// now find successor block
if (start_of_next_block[0] == badResourceValue &&
} else {
tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
}
}
tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock);
fatal("memory stomping error");
}
if (MallocCushion) {
for (int i = 0; i < MallocCushion; i++) {
if (ptr[i] != badResourceValue) {
}
}
for (int j = -MallocCushion; j < 0; j++) {
if (end[j] != badResourceValue) {
}
}
}
}
#endif
if (size == 0) {
// return a valid pointer if size is zero
// if NULL is returned the calling functions assume out of memory.
size = 1;
}
#ifdef ASSERT
if (MallocCushion) {
}
// put size just before data
#endif
breakpoint();
}
if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
// we do not track MallocCushion memory
return memblock;
}
#ifndef ASSERT
} else {
}
return ptr;
#else
}
breakpoint();
}
// always move the block
if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
// Copy to new memory if malloc didn't fail
breakpoint();
}
}
return ptr;
#endif
}
#ifdef ASSERT
breakpoint();
}
// Added by detlefs.
if (MallocCushion) {
guarantee(*p == badResourceValue,
"Thing freed should be malloc result.");
*p = (u_char)freeBlockPad;
}
guarantee(*q == badResourceValue,
"Thing freed should be malloc result.");
*q = (u_char)freeBlockPad;
}
// tty->print_cr("os::free %p", memblock);
}
#endif
}
}
/* standard, well-known linear congruential random generator with
* next_rand = (16807*seed) mod (2**31-1)
* see
* (1) "Random Number Generators: Good Ones Are Hard to Find",
* S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
* (2) "Two Fast Implementations of the 'Minimal Standard' Random
* Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
*/
const long a = 16807;
const unsigned long m = 2147483647;
// compute az=2^31p+q
// if q overflowed, ignore the overflow and increment q
if (lo > m) {
lo &= m;
++lo;
}
// if (p+q) overflowed, ignore the overflow and increment (p+q)
if (lo > m) {
lo &= m;
++lo;
}
return (_rand_seed = lo);
}
// The INITIALIZED state is distinguished from the SUSPENDED state because the
// conditions in which a thread is first started are different from those in which
// a suspension is resumed. These differences make it hard for us to apply the
// tougher checks when starting threads that we want to do when resuming them.
// However, when start_thread is called as a result of Thread.start, on a Java
// thread, the operation is synchronized on the Java Thread object. So there
// cannot be a race to start the thread and hence for the thread to exit while
// we are working on it. Non-Java threads that start Java threads either have
// to do so in a context in which races are impossible, or should do appropriate
// locking.
}
//---------------------------------------------------------------------------
// Helper functions for fatal error handler
int cols = 0;
int cols_per_line = 0;
switch (unitsize) {
default: return;
}
while (p < end) {
switch (unitsize) {
}
p += unitsize;
cols++;
cols = 0;
} else {
}
}
}
if (env_list) {
}
}
}
}
// cpu
// It's not safe to query number of active processors after crash
// st->print("(active %d)", os::active_processor_count());
}
double t = os::elapsedTime();
// NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
// Linux. Must be a bug in glibc ? Workaround is to round "t" to int
// before printf. We lost some precision, but who cares?
}
// moved from debug.cpp (used to be find()) but still called from there
// The verbose parameter is only set by the debug code in one case
if (b != NULL) {
if (b->is_buffer_blob()) {
// the interpreter is generated into a buffer blob
if (i != NULL) {
st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
return;
}
" (not bytecode specific)", addr);
return;
}
//
if (AdapterHandlerLibrary::contains(b)) {
st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
}
// the stubroutines are generated into a buffer blob
if (d != NULL) {
return;
}
"stub routine", addr);
return;
}
// the InlineCacheBuffer is using stubs generated into a buffer blob
return;
}
if (v != NULL) {
st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
return;
}
}
if (verbose) {
}
return;
}
return;
}
bool print = false;
// If we couldn't find it it just may mean that heap wasn't parseable
// See if we were just given an oop directly
print = true;
print = true;
}
if (print) {
} else {
}
}
}
return;
}
} else {
"in the heap", addr);
return;
}
}
return;
}
return;
}
#ifndef PRODUCT
// we don't keep the block list in product mode
return;
}
#endif
// Check for privilege stack
return;
}
// If the addr is a java thread print information about that.
if (verbose) {
} else {
}
return;
}
// If the addr is in the stack region for this thread then report that
// and print thread info
return;
}
}
// Try an OS specific find
return;
}
}
// Looks like all platforms except IA64 can use the same function to check
// if C stack is walkable beyond current frame. The check for fp() is not
// necessary on Sparc, but it's harmless.
#ifdef IA64
// In order to walk native frames on Itanium, we need to access the unwind
// table, which is inside ELF. We don't want to parse ELF after fatal error,
// so return true for IA64. If we need to support C stack walking on IA64,
// this function needs to be moved to CPU specific files, as fp() on IA64
// is register stack, which grows towards higher memory address.
return true;
#endif
// Load up sp, fp, sender sp and sender fp, check for reasonable values.
// Check usp first, because if that's bad the other accessors may fault
// on some architectures. Ditto ufp second, etc.
// sp on amd can be 32 bit aligned.
if ((usp & sp_align_mask) != 0) return true;
if ((ufp & fp_align_mask) != 0) return true;
if ((old_sp & sp_align_mask) != 0) return true;
if ((old_fp & fp_align_mask) != 0) return true;
// stack grows downwards; if old_fp is below current fp or if the stack
// frame is too large, either the stack is corrupted or fp is not saved
// on stack (i.e. on x86, ebp may be used as general register). The stack
// is not walkable beyond current frame.
return false;
}
#ifdef ASSERT
const double m = 2147483647;
long num;
for (int k = 0; k < reps; k++) {
double u = (double)num / m;
// calculate mean and variance of the random sequence
mean += u;
variance += (u*u);
}
}
#endif
// Set up the boot classpath.
const char* home,
int home_len,
char fileSep,
char pathSep) {
// Scan the format string to determine the length of the actual
// boot classpath, and handle platform dependencies as well.
int formatted_path_len = 0;
const char* p;
for (p = format_string; *p != 0; ++p) {
}
if (formatted_path == NULL) {
return NULL;
}
// Create boot classpath from format, substituting separator chars and
// java home directory.
char* q = formatted_path;
for (p = format_string; *p != 0; ++p) {
switch (*p) {
case '%':
q += home_len;
break;
case '/':
*q++ = fileSep;
break;
case ':':
*q++ = pathSep;
break;
default:
*q++ = *p;
}
}
*q = '\0';
return formatted_path;
}
static const char* meta_index_dir_format = "%/lib/";
static const char* meta_index_format = "%/lib/meta-index";
if (meta_index == NULL) return false;
if (meta_index_dir == NULL) return false;
// Any modification to the JAR-file list, for the boot classpath must be
// path class JARs, are stripped for StackMapTable to reduce download size.
static const char classpath_format[] =
"%/lib/resources.jar:"
"%/lib/sunrsasign.jar:"
"%/lib/charsets.jar:"
#ifdef __APPLE__
#endif
"%/classes";
if (sysclasspath == NULL) return false;
return true;
}
/*
* Splits a path, based on its separator, the number of
* elements is returned back in n.
* It is the callers responsibility to:
* a> check the value of n, and n may be 0.
* b> ignore any empty path elements
* c> free up the data.
*/
*n = 0;
return NULL;
}
return NULL;
}
int count = 1;
// Get a count of elements to allocate memory
while (p != NULL) {
count++;
p++;
}
return NULL;
}
// do the actual splitting
p = inpath;
for (int i = 0 ; i < count ; i++) {
if (len > JVM_MAXPATHLEN) {
return NULL;
}
// allocate the string and add terminator storage
if (s == NULL) {
return NULL;
}
s[len] = '\0';
opath[i] = s;
p += len + 1;
}
*n = count;
return opath;
}
// We initialize the serialization page shift count here
// We assume a cache line size of 64 bytes
"thread size changed, fix SerializePageShiftCount constant");
}
static volatile intptr_t SerializePageLock = 0;
// This method is called from signal handler when SIGSEGV occurs while the current
// thread tries to store to the "read-only" memory serialize page during state
// transition.
void os::block_on_serialize_page_trap() {
if (TraceSafepoint) {
}
// When VMThread is holding the SerializePageLock during modifying the
// access permission of the memory serialize page, the following call
// will block until the permission of that page is restored to rw.
// Generally, it is unsafe to manipulate locks in signal handlers, but in
// this case, it's OK as the signal is synchronous and we know precisely when
// it can occur.
}
// Serialize all thread state variables
void os::serialize_thread_states() {
// On some platforms such as Solaris & Linux, the time duration of the page
// permission restoration is observed to be much longer than expected due to
// scheduler starvation problem etc. To avoid the long synchronization
// time and expensive page trap spinning, 'SerializePageLock' is used to block
// the mutator thread if such case is encountered. See bug 6546278 for details.
}
// Returns true if the current stack pointer is above the stack shadow
// pages, false otherwise.
// Check if we have StackShadowPages above the yellow zone. This parameter
// is dependent on the depth of the maximum VM call stack possible from
// the handler for stack overflow. 'instanceof' in the stack overflow
// handler or a println uses at least 8k stack of VM and native code
// respectively.
const int framesize_in_bytes =
* vm_page_size()) + framesize_in_bytes;
// The very lower end of the stack
}
{
if (UseLargePages) {
for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
// The largest page size with no fragmentation.
return sz;
}
if (sz <= max_page_size) {
// The largest page size that satisfies the min_pages requirement.
return sz;
}
}
}
return vm_page_size();
}
#ifndef PRODUCT
{
if (TracePageSizes) {
for (int i = 0; i < count; ++i) {
}
}
}
{
if (TracePageSizes) {
" size=" SIZE_FORMAT,
}
}
#endif // #ifndef PRODUCT
// This is the working definition of a server class machine:
// >= 2 physical CPU's and >=2GB of memory, with some fuzz
// because the graphics memory (?) sometimes masks physical memory.
// If you want to change the definition of a server class machine
// on some OS or platform, e.g., >=4GB on Windohs platforms,
// then you'll have to parameterize this method based on that state,
// as was done for logical processors here, or replicate and
// specialize this method for each platform. (Or fix os to have
// some inheritance structure and use subclassing. Sigh.)
// If you want some platform to always or never behave as a server
// class machine, change the setting of AlwaysActAsServerClassMachine
// and NeverActAsServerClassMachine in globals*.hpp.
// First check for the early returns
if (NeverActAsServerClassMachine) {
return false;
}
return true;
}
// Then actually look at the machine
bool result = false;
// We seem not to get our full complement of memory.
// We allow some part (1/8?) of the memory to be "missing",
// based on the sizes of DIMMs, and maybe graphics cards.
/* Is this a server class machine? */
const unsigned int logical_processors =
if (logical_processors > 1) {
const unsigned int physical_packages =
if (physical_packages > server_processors) {
result = true;
}
} else {
result = true;
}
}
return result;
}
// Read file line by line, if line is longer than bsize,
// skip rest of line.
// read until EOF, EOL or buf is full
++i;
}
if (buf[i] == '\n') {
// EOL reached so ignore EOL character and return
buf[i] = 0;
return (int) i;
}
buf[i+1] = 0;
if (sz != 1) {
// EOF reached. if we read chars before EOF return them and
// return EOF on next call otherwise return EOF
return (i == 0) ? -1 : (int) i;
}
// line is longer than size of buf, skip to EOL
char ch;
// Do nothing
}
// return initial part of line that fits in buf.
// If we reached EOF, it will be returned on next call.
return (int) i;
}
assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
_done = true;
}
}
}
return result;
}
}
return result;
}
}
return result;
}
}
if (res) {
}
return res;
}
bool executable) {
if (res) {
}
return res;
}
const char* mesg) {
}
bool executable, const char* mesg) {
}
if (res) {
} else {
}
return res;
}
if (res) {
} else {
}
return res;
}
if (can_release_partial_region()) {
}
}
bool allow_exec) {
}
return result;
}
bool allow_exec) {
}
if (result) {
} else {
}
return result;
}
}
}