src/share/vm/runtime/os.cpp

changeset 0
f90c822e73f8
child 6876
710a3c8b516e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/vm/runtime/os.cpp	Wed Apr 27 01:25:04 2016 +0800
     1.3 @@ -0,0 +1,1655 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.
    1.11 + *
    1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.15 + * version 2 for more details (a copy is included in the LICENSE file that
    1.16 + * accompanied this code).
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License version
    1.19 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.21 + *
    1.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.23 + * or visit www.oracle.com if you need additional information or have any
    1.24 + * questions.
    1.25 + *
    1.26 + */
    1.27 +
    1.28 +#include "precompiled.hpp"
    1.29 +#include "classfile/classLoader.hpp"
    1.30 +#include "classfile/javaClasses.hpp"
    1.31 +#include "classfile/systemDictionary.hpp"
    1.32 +#include "classfile/vmSymbols.hpp"
    1.33 +#include "code/icBuffer.hpp"
    1.34 +#include "code/vtableStubs.hpp"
    1.35 +#include "gc_implementation/shared/vmGCOperations.hpp"
    1.36 +#include "interpreter/interpreter.hpp"
    1.37 +#include "memory/allocation.inline.hpp"
    1.38 +#include "oops/oop.inline.hpp"
    1.39 +#include "prims/jvm.h"
    1.40 +#include "prims/jvm_misc.hpp"
    1.41 +#include "prims/privilegedStack.hpp"
    1.42 +#include "runtime/arguments.hpp"
    1.43 +#include "runtime/frame.inline.hpp"
    1.44 +#include "runtime/interfaceSupport.hpp"
    1.45 +#include "runtime/java.hpp"
    1.46 +#include "runtime/javaCalls.hpp"
    1.47 +#include "runtime/mutexLocker.hpp"
    1.48 +#include "runtime/os.hpp"
    1.49 +#include "runtime/stubRoutines.hpp"
    1.50 +#include "runtime/thread.inline.hpp"
    1.51 +#include "services/attachListener.hpp"
    1.52 +#include "services/memTracker.hpp"
    1.53 +#include "services/threadService.hpp"
    1.54 +#include "utilities/defaultStream.hpp"
    1.55 +#include "utilities/events.hpp"
    1.56 +#ifdef TARGET_OS_FAMILY_linux
    1.57 +# include "os_linux.inline.hpp"
    1.58 +#endif
    1.59 +#ifdef TARGET_OS_FAMILY_solaris
    1.60 +# include "os_solaris.inline.hpp"
    1.61 +#endif
    1.62 +#ifdef TARGET_OS_FAMILY_windows
    1.63 +# include "os_windows.inline.hpp"
    1.64 +#endif
    1.65 +#ifdef TARGET_OS_FAMILY_bsd
    1.66 +# include "os_bsd.inline.hpp"
    1.67 +#endif
    1.68 +
    1.69 +# include <signal.h>
    1.70 +
    1.71 +PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    1.72 +
    1.73 +OSThread*         os::_starting_thread    = NULL;
    1.74 +address           os::_polling_page       = NULL;
    1.75 +volatile int32_t* os::_mem_serialize_page = NULL;
    1.76 +uintptr_t         os::_serialize_page_mask = 0;
    1.77 +long              os::_rand_seed          = 1;
    1.78 +int               os::_processor_count    = 0;
    1.79 +size_t            os::_page_sizes[os::page_sizes_max];
    1.80 +
    1.81 +#ifndef PRODUCT
    1.82 +julong os::num_mallocs = 0;         // # of calls to malloc/realloc
    1.83 +julong os::alloc_bytes = 0;         // # of bytes allocated
    1.84 +julong os::num_frees = 0;           // # of calls to free
    1.85 +julong os::free_bytes = 0;          // # of bytes freed
    1.86 +#endif
    1.87 +
    1.88 +static juint cur_malloc_words = 0;  // current size for MallocMaxTestWords
    1.89 +
    1.90 +void os_init_globals() {
    1.91 +  // Called from init_globals().
    1.92 +  // See Threads::create_vm() in thread.cpp, and init.cpp.
    1.93 +  os::init_globals();
    1.94 +}
    1.95 +
    1.96 +// Fill in buffer with current local time as an ISO-8601 string.
    1.97 +// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
    1.98 +// Returns buffer, or NULL if it failed.
    1.99 +// This would mostly be a call to
   1.100 +//     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
   1.101 +// except that on Windows the %z behaves badly, so we do it ourselves.
   1.102 +// Also, people wanted milliseconds on there,
   1.103 +// and strftime doesn't do milliseconds.
   1.104 +char* os::iso8601_time(char* buffer, size_t buffer_length) {
   1.105 +  // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
   1.106 +  //                                      1         2
   1.107 +  //                             12345678901234567890123456789
   1.108 +  static const char* iso8601_format =
   1.109 +    "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
   1.110 +  static const size_t needed_buffer = 29;
   1.111 +
   1.112 +  // Sanity check the arguments
   1.113 +  if (buffer == NULL) {
   1.114 +    assert(false, "NULL buffer");
   1.115 +    return NULL;
   1.116 +  }
   1.117 +  if (buffer_length < needed_buffer) {
   1.118 +    assert(false, "buffer_length too small");
   1.119 +    return NULL;
   1.120 +  }
   1.121 +  // Get the current time
   1.122 +  jlong milliseconds_since_19700101 = javaTimeMillis();
   1.123 +  const int milliseconds_per_microsecond = 1000;
   1.124 +  const time_t seconds_since_19700101 =
   1.125 +    milliseconds_since_19700101 / milliseconds_per_microsecond;
   1.126 +  const int milliseconds_after_second =
   1.127 +    milliseconds_since_19700101 % milliseconds_per_microsecond;
   1.128 +  // Convert the time value to a tm and timezone variable
   1.129 +  struct tm time_struct;
   1.130 +  if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
   1.131 +    assert(false, "Failed localtime_pd");
   1.132 +    return NULL;
   1.133 +  }
   1.134 +#if defined(_ALLBSD_SOURCE)
   1.135 +  const time_t zone = (time_t) time_struct.tm_gmtoff;
   1.136 +#else
   1.137 +  const time_t zone = timezone;
   1.138 +#endif
   1.139 +
   1.140 +  // If daylight savings time is in effect,
   1.141 +  // we are 1 hour East of our time zone
   1.142 +  const time_t seconds_per_minute = 60;
   1.143 +  const time_t minutes_per_hour = 60;
   1.144 +  const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
   1.145 +  time_t UTC_to_local = zone;
   1.146 +  if (time_struct.tm_isdst > 0) {
   1.147 +    UTC_to_local = UTC_to_local - seconds_per_hour;
   1.148 +  }
   1.149 +  // Compute the time zone offset.
   1.150 +  //    localtime_pd() sets timezone to the difference (in seconds)
   1.151 +  //    between UTC and and local time.
   1.152 +  //    ISO 8601 says we need the difference between local time and UTC,
   1.153 +  //    we change the sign of the localtime_pd() result.
   1.154 +  const time_t local_to_UTC = -(UTC_to_local);
   1.155 +  // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
   1.156 +  char sign_local_to_UTC = '+';
   1.157 +  time_t abs_local_to_UTC = local_to_UTC;
   1.158 +  if (local_to_UTC < 0) {
   1.159 +    sign_local_to_UTC = '-';
   1.160 +    abs_local_to_UTC = -(abs_local_to_UTC);
   1.161 +  }
   1.162 +  // Convert time zone offset seconds to hours and minutes.
   1.163 +  const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
   1.164 +  const time_t zone_min =
   1.165 +    ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
   1.166 +
   1.167 +  // Print an ISO 8601 date and time stamp into the buffer
   1.168 +  const int year = 1900 + time_struct.tm_year;
   1.169 +  const int month = 1 + time_struct.tm_mon;
   1.170 +  const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
   1.171 +                                   year,
   1.172 +                                   month,
   1.173 +                                   time_struct.tm_mday,
   1.174 +                                   time_struct.tm_hour,
   1.175 +                                   time_struct.tm_min,
   1.176 +                                   time_struct.tm_sec,
   1.177 +                                   milliseconds_after_second,
   1.178 +                                   sign_local_to_UTC,
   1.179 +                                   zone_hours,
   1.180 +                                   zone_min);
   1.181 +  if (printed == 0) {
   1.182 +    assert(false, "Failed jio_printf");
   1.183 +    return NULL;
   1.184 +  }
   1.185 +  return buffer;
   1.186 +}
   1.187 +
   1.188 +OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
   1.189 +#ifdef ASSERT
   1.190 +  if (!(!thread->is_Java_thread() ||
   1.191 +         Thread::current() == thread  ||
   1.192 +         Threads_lock->owned_by_self()
   1.193 +         || thread->is_Compiler_thread()
   1.194 +        )) {
   1.195 +    assert(false, "possibility of dangling Thread pointer");
   1.196 +  }
   1.197 +#endif
   1.198 +
   1.199 +  if (p >= MinPriority && p <= MaxPriority) {
   1.200 +    int priority = java_to_os_priority[p];
   1.201 +    return set_native_priority(thread, priority);
   1.202 +  } else {
   1.203 +    assert(false, "Should not happen");
   1.204 +    return OS_ERR;
   1.205 +  }
   1.206 +}
   1.207 +
   1.208 +// The mapping from OS priority back to Java priority may be inexact because
   1.209 +// Java priorities can map M:1 with native priorities. If you want the definite
   1.210 +// Java priority then use JavaThread::java_priority()
   1.211 +OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
   1.212 +  int p;
   1.213 +  int os_prio;
   1.214 +  OSReturn ret = get_native_priority(thread, &os_prio);
   1.215 +  if (ret != OS_OK) return ret;
   1.216 +
   1.217 +  if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
   1.218 +    for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
   1.219 +  } else {
   1.220 +    // niceness values are in reverse order
   1.221 +    for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
   1.222 +  }
   1.223 +  priority = (ThreadPriority)p;
   1.224 +  return OS_OK;
   1.225 +}
   1.226 +
   1.227 +
   1.228 +// --------------------- sun.misc.Signal (optional) ---------------------
   1.229 +
   1.230 +
   1.231 +// SIGBREAK is sent by the keyboard to query the VM state
   1.232 +#ifndef SIGBREAK
   1.233 +#define SIGBREAK SIGQUIT
   1.234 +#endif
   1.235 +
   1.236 +// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
   1.237 +
   1.238 +
   1.239 +static void signal_thread_entry(JavaThread* thread, TRAPS) {
   1.240 +  os::set_priority(thread, NearMaxPriority);
   1.241 +  while (true) {
   1.242 +    int sig;
   1.243 +    {
   1.244 +      // FIXME : Currently we have not decieded what should be the status
   1.245 +      //         for this java thread blocked here. Once we decide about
   1.246 +      //         that we should fix this.
   1.247 +      sig = os::signal_wait();
   1.248 +    }
   1.249 +    if (sig == os::sigexitnum_pd()) {
   1.250 +       // Terminate the signal thread
   1.251 +       return;
   1.252 +    }
   1.253 +
   1.254 +    switch (sig) {
   1.255 +      case SIGBREAK: {
   1.256 +        // Check if the signal is a trigger to start the Attach Listener - in that
   1.257 +        // case don't print stack traces.
   1.258 +        if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
   1.259 +          continue;
   1.260 +        }
   1.261 +        // Print stack traces
   1.262 +        // Any SIGBREAK operations added here should make sure to flush
   1.263 +        // the output stream (e.g. tty->flush()) after output.  See 4803766.
   1.264 +        // Each module also prints an extra carriage return after its output.
   1.265 +        VM_PrintThreads op;
   1.266 +        VMThread::execute(&op);
   1.267 +        VM_PrintJNI jni_op;
   1.268 +        VMThread::execute(&jni_op);
   1.269 +        VM_FindDeadlocks op1(tty);
   1.270 +        VMThread::execute(&op1);
   1.271 +        Universe::print_heap_at_SIGBREAK();
   1.272 +        if (PrintClassHistogram) {
   1.273 +          VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
   1.274 +          VMThread::execute(&op1);
   1.275 +        }
   1.276 +        if (JvmtiExport::should_post_data_dump()) {
   1.277 +          JvmtiExport::post_data_dump();
   1.278 +        }
   1.279 +        break;
   1.280 +      }
   1.281 +      default: {
   1.282 +        // Dispatch the signal to java
   1.283 +        HandleMark hm(THREAD);
   1.284 +        Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
   1.285 +        KlassHandle klass (THREAD, k);
   1.286 +        if (klass.not_null()) {
   1.287 +          JavaValue result(T_VOID);
   1.288 +          JavaCallArguments args;
   1.289 +          args.push_int(sig);
   1.290 +          JavaCalls::call_static(
   1.291 +            &result,
   1.292 +            klass,
   1.293 +            vmSymbols::dispatch_name(),
   1.294 +            vmSymbols::int_void_signature(),
   1.295 +            &args,
   1.296 +            THREAD
   1.297 +          );
   1.298 +        }
   1.299 +        if (HAS_PENDING_EXCEPTION) {
   1.300 +          // tty is initialized early so we don't expect it to be null, but
   1.301 +          // if it is we can't risk doing an initialization that might
   1.302 +          // trigger additional out-of-memory conditions
   1.303 +          if (tty != NULL) {
   1.304 +            char klass_name[256];
   1.305 +            char tmp_sig_name[16];
   1.306 +            const char* sig_name = "UNKNOWN";
   1.307 +            InstanceKlass::cast(PENDING_EXCEPTION->klass())->
   1.308 +              name()->as_klass_external_name(klass_name, 256);
   1.309 +            if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
   1.310 +              sig_name = tmp_sig_name;
   1.311 +            warning("Exception %s occurred dispatching signal %s to handler"
   1.312 +                    "- the VM may need to be forcibly terminated",
   1.313 +                    klass_name, sig_name );
   1.314 +          }
   1.315 +          CLEAR_PENDING_EXCEPTION;
   1.316 +        }
   1.317 +      }
   1.318 +    }
   1.319 +  }
   1.320 +}
   1.321 +
   1.322 +void os::init_before_ergo() {
   1.323 +  // We need to initialize large page support here because ergonomics takes some
   1.324 +  // decisions depending on large page support and the calculated large page size.
   1.325 +  large_page_init();
   1.326 +}
   1.327 +
   1.328 +void os::signal_init() {
   1.329 +  if (!ReduceSignalUsage) {
   1.330 +    // Setup JavaThread for processing signals
   1.331 +    EXCEPTION_MARK;
   1.332 +    Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
   1.333 +    instanceKlassHandle klass (THREAD, k);
   1.334 +    instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
   1.335 +
   1.336 +    const char thread_name[] = "Signal Dispatcher";
   1.337 +    Handle string = java_lang_String::create_from_str(thread_name, CHECK);
   1.338 +
   1.339 +    // Initialize thread_oop to put it into the system threadGroup
   1.340 +    Handle thread_group (THREAD, Universe::system_thread_group());
   1.341 +    JavaValue result(T_VOID);
   1.342 +    JavaCalls::call_special(&result, thread_oop,
   1.343 +                           klass,
   1.344 +                           vmSymbols::object_initializer_name(),
   1.345 +                           vmSymbols::threadgroup_string_void_signature(),
   1.346 +                           thread_group,
   1.347 +                           string,
   1.348 +                           CHECK);
   1.349 +
   1.350 +    KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
   1.351 +    JavaCalls::call_special(&result,
   1.352 +                            thread_group,
   1.353 +                            group,
   1.354 +                            vmSymbols::add_method_name(),
   1.355 +                            vmSymbols::thread_void_signature(),
   1.356 +                            thread_oop,         // ARG 1
   1.357 +                            CHECK);
   1.358 +
   1.359 +    os::signal_init_pd();
   1.360 +
   1.361 +    { MutexLocker mu(Threads_lock);
   1.362 +      JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
   1.363 +
   1.364 +      // At this point it may be possible that no osthread was created for the
   1.365 +      // JavaThread due to lack of memory. We would have to throw an exception
   1.366 +      // in that case. However, since this must work and we do not allow
   1.367 +      // exceptions anyway, check and abort if this fails.
   1.368 +      if (signal_thread == NULL || signal_thread->osthread() == NULL) {
   1.369 +        vm_exit_during_initialization("java.lang.OutOfMemoryError",
   1.370 +                                      "unable to create new native thread");
   1.371 +      }
   1.372 +
   1.373 +      java_lang_Thread::set_thread(thread_oop(), signal_thread);
   1.374 +      java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   1.375 +      java_lang_Thread::set_daemon(thread_oop());
   1.376 +
   1.377 +      signal_thread->set_threadObj(thread_oop());
   1.378 +      Threads::add(signal_thread);
   1.379 +      Thread::start(signal_thread);
   1.380 +    }
   1.381 +    // Handle ^BREAK
   1.382 +    os::signal(SIGBREAK, os::user_handler());
   1.383 +  }
   1.384 +}
   1.385 +
   1.386 +
   1.387 +void os::terminate_signal_thread() {
   1.388 +  if (!ReduceSignalUsage)
   1.389 +    signal_notify(sigexitnum_pd());
   1.390 +}
   1.391 +
   1.392 +
   1.393 +// --------------------- loading libraries ---------------------
   1.394 +
   1.395 +typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
   1.396 +extern struct JavaVM_ main_vm;
   1.397 +
   1.398 +static void* _native_java_library = NULL;
   1.399 +
   1.400 +void* os::native_java_library() {
   1.401 +  if (_native_java_library == NULL) {
   1.402 +    char buffer[JVM_MAXPATHLEN];
   1.403 +    char ebuf[1024];
   1.404 +
   1.405 +    // Try to load verify dll first. In 1.3 java dll depends on it and is not
   1.406 +    // always able to find it when the loading executable is outside the JDK.
   1.407 +    // In order to keep working with 1.2 we ignore any loading errors.
   1.408 +    if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
   1.409 +                       "verify")) {
   1.410 +      dll_load(buffer, ebuf, sizeof(ebuf));
   1.411 +    }
   1.412 +
   1.413 +    // Load java dll
   1.414 +    if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
   1.415 +                       "java")) {
   1.416 +      _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
   1.417 +    }
   1.418 +    if (_native_java_library == NULL) {
   1.419 +      vm_exit_during_initialization("Unable to load native library", ebuf);
   1.420 +    }
   1.421 +
   1.422 +#if defined(__OpenBSD__)
   1.423 +    // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
   1.424 +    // ignore errors
   1.425 +    if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
   1.426 +                       "net")) {
   1.427 +      dll_load(buffer, ebuf, sizeof(ebuf));
   1.428 +    }
   1.429 +#endif
   1.430 +  }
   1.431 +  static jboolean onLoaded = JNI_FALSE;
   1.432 +  if (onLoaded) {
   1.433 +    // We may have to wait to fire OnLoad until TLS is initialized.
   1.434 +    if (ThreadLocalStorage::is_initialized()) {
   1.435 +      // The JNI_OnLoad handling is normally done by method load in
   1.436 +      // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
   1.437 +      // explicitly so we have to check for JNI_OnLoad as well
   1.438 +      const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
   1.439 +      JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
   1.440 +          JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
   1.441 +      if (JNI_OnLoad != NULL) {
   1.442 +        JavaThread* thread = JavaThread::current();
   1.443 +        ThreadToNativeFromVM ttn(thread);
   1.444 +        HandleMark hm(thread);
   1.445 +        jint ver = (*JNI_OnLoad)(&main_vm, NULL);
   1.446 +        onLoaded = JNI_TRUE;
   1.447 +        if (!Threads::is_supported_jni_version_including_1_1(ver)) {
   1.448 +          vm_exit_during_initialization("Unsupported JNI version");
   1.449 +        }
   1.450 +      }
   1.451 +    }
   1.452 +  }
   1.453 +  return _native_java_library;
   1.454 +}
   1.455 +
   1.456 +/*
   1.457 + * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
   1.458 + * If check_lib == true then we are looking for an
   1.459 + * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
   1.460 + * this library is statically linked into the image.
   1.461 + * If check_lib == false then we will look for the appropriate symbol in the
   1.462 + * executable if agent_lib->is_static_lib() == true or in the shared library
   1.463 + * referenced by 'handle'.
   1.464 + */
   1.465 +void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
   1.466 +                              const char *syms[], size_t syms_len) {
   1.467 +  assert(agent_lib != NULL, "sanity check");
   1.468 +  const char *lib_name;
   1.469 +  void *handle = agent_lib->os_lib();
   1.470 +  void *entryName = NULL;
   1.471 +  char *agent_function_name;
   1.472 +  size_t i;
   1.473 +
   1.474 +  // If checking then use the agent name otherwise test is_static_lib() to
   1.475 +  // see how to process this lookup
   1.476 +  lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
   1.477 +  for (i = 0; i < syms_len; i++) {
   1.478 +    agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
   1.479 +    if (agent_function_name == NULL) {
   1.480 +      break;
   1.481 +    }
   1.482 +    entryName = dll_lookup(handle, agent_function_name);
   1.483 +    FREE_C_HEAP_ARRAY(char, agent_function_name, mtThread);
   1.484 +    if (entryName != NULL) {
   1.485 +      break;
   1.486 +    }
   1.487 +  }
   1.488 +  return entryName;
   1.489 +}
   1.490 +
   1.491 +// See if the passed in agent is statically linked into the VM image.
   1.492 +bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
   1.493 +                            size_t syms_len) {
   1.494 +  void *ret;
   1.495 +  void *proc_handle;
   1.496 +  void *save_handle;
   1.497 +
   1.498 +  assert(agent_lib != NULL, "sanity check");
   1.499 +  if (agent_lib->name() == NULL) {
   1.500 +    return false;
   1.501 +  }
   1.502 +  proc_handle = get_default_process_handle();
   1.503 +  // Check for Agent_OnLoad/Attach_lib_name function
   1.504 +  save_handle = agent_lib->os_lib();
   1.505 +  // We want to look in this process' symbol table.
   1.506 +  agent_lib->set_os_lib(proc_handle);
   1.507 +  ret = find_agent_function(agent_lib, true, syms, syms_len);
   1.508 +  if (ret != NULL) {
   1.509 +    // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
   1.510 +    agent_lib->set_valid();
   1.511 +    agent_lib->set_static_lib(true);
   1.512 +    return true;
   1.513 +  }
   1.514 +  agent_lib->set_os_lib(save_handle);
   1.515 +  return false;
   1.516 +}
   1.517 +
   1.518 +// --------------------- heap allocation utilities ---------------------
   1.519 +
   1.520 +char *os::strdup(const char *str, MEMFLAGS flags) {
   1.521 +  size_t size = strlen(str);
   1.522 +  char *dup_str = (char *)malloc(size + 1, flags);
   1.523 +  if (dup_str == NULL) return NULL;
   1.524 +  strcpy(dup_str, str);
   1.525 +  return dup_str;
   1.526 +}
   1.527 +
   1.528 +
   1.529 +
   1.530 +#ifdef ASSERT
   1.531 +#define space_before             (MallocCushion + sizeof(double))
   1.532 +#define space_after              MallocCushion
   1.533 +#define size_addr_from_base(p)   (size_t*)(p + space_before - sizeof(size_t))
   1.534 +#define size_addr_from_obj(p)    ((size_t*)p - 1)
   1.535 +// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
   1.536 +// NB: cannot be debug variable, because these aren't set from the command line until
   1.537 +// *after* the first few allocs already happened
   1.538 +#define MallocCushion            16
   1.539 +#else
   1.540 +#define space_before             0
   1.541 +#define space_after              0
   1.542 +#define size_addr_from_base(p)   should not use w/o ASSERT
   1.543 +#define size_addr_from_obj(p)    should not use w/o ASSERT
   1.544 +#define MallocCushion            0
   1.545 +#endif
   1.546 +#define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
   1.547 +
   1.548 +#ifdef ASSERT
   1.549 +inline size_t get_size(void* obj) {
   1.550 +  size_t size = *size_addr_from_obj(obj);
   1.551 +  if (size < 0) {
   1.552 +    fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten ("
   1.553 +                  SIZE_FORMAT ")", obj, size));
   1.554 +  }
   1.555 +  return size;
   1.556 +}
   1.557 +
   1.558 +u_char* find_cushion_backwards(u_char* start) {
   1.559 +  u_char* p = start;
   1.560 +  while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
   1.561 +         p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
   1.562 +  // ok, we have four consecutive marker bytes; find start
   1.563 +  u_char* q = p - 4;
   1.564 +  while (*q == badResourceValue) q--;
   1.565 +  return q + 1;
   1.566 +}
   1.567 +
   1.568 +u_char* find_cushion_forwards(u_char* start) {
   1.569 +  u_char* p = start;
   1.570 +  while (p[0] != badResourceValue || p[1] != badResourceValue ||
   1.571 +         p[2] != badResourceValue || p[3] != badResourceValue) p++;
   1.572 +  // ok, we have four consecutive marker bytes; find end of cushion
   1.573 +  u_char* q = p + 4;
   1.574 +  while (*q == badResourceValue) q++;
   1.575 +  return q - MallocCushion;
   1.576 +}
   1.577 +
   1.578 +void print_neighbor_blocks(void* ptr) {
   1.579 +  // find block allocated before ptr (not entirely crash-proof)
   1.580 +  if (MallocCushion < 4) {
   1.581 +    tty->print_cr("### cannot find previous block (MallocCushion < 4)");
   1.582 +    return;
   1.583 +  }
   1.584 +  u_char* start_of_this_block = (u_char*)ptr - space_before;
   1.585 +  u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
   1.586 +  // look for cushion in front of prev. block
   1.587 +  u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
   1.588 +  ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
   1.589 +  u_char* obj = start_of_prev_block + space_before;
   1.590 +  if (size <= 0 ) {
   1.591 +    // start is bad; mayhave been confused by OS data inbetween objects
   1.592 +    // search one more backwards
   1.593 +    start_of_prev_block = find_cushion_backwards(start_of_prev_block);
   1.594 +    size = *size_addr_from_base(start_of_prev_block);
   1.595 +    obj = start_of_prev_block + space_before;
   1.596 +  }
   1.597 +
   1.598 +  if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
   1.599 +    tty->print_cr("### previous object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
   1.600 +  } else {
   1.601 +    tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size);
   1.602 +  }
   1.603 +
   1.604 +  // now find successor block
   1.605 +  u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
   1.606 +  start_of_next_block = find_cushion_forwards(start_of_next_block);
   1.607 +  u_char* next_obj = start_of_next_block + space_before;
   1.608 +  ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
   1.609 +  if (start_of_next_block[0] == badResourceValue &&
   1.610 +      start_of_next_block[1] == badResourceValue &&
   1.611 +      start_of_next_block[2] == badResourceValue &&
   1.612 +      start_of_next_block[3] == badResourceValue) {
   1.613 +    tty->print_cr("### next object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
   1.614 +  } else {
   1.615 +    tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size);
   1.616 +  }
   1.617 +}
   1.618 +
   1.619 +
   1.620 +void report_heap_error(void* memblock, void* bad, const char* where) {
   1.621 +  tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
   1.622 +  tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock);
   1.623 +  print_neighbor_blocks(memblock);
   1.624 +  fatal("memory stomping error");
   1.625 +}
   1.626 +
   1.627 +void verify_block(void* memblock) {
   1.628 +  size_t size = get_size(memblock);
   1.629 +  if (MallocCushion) {
   1.630 +    u_char* ptr = (u_char*)memblock - space_before;
   1.631 +    for (int i = 0; i < MallocCushion; i++) {
   1.632 +      if (ptr[i] != badResourceValue) {
   1.633 +        report_heap_error(memblock, ptr+i, "in front of");
   1.634 +      }
   1.635 +    }
   1.636 +    u_char* end = (u_char*)memblock + size + space_after;
   1.637 +    for (int j = -MallocCushion; j < 0; j++) {
   1.638 +      if (end[j] != badResourceValue) {
   1.639 +        report_heap_error(memblock, end+j, "after");
   1.640 +      }
   1.641 +    }
   1.642 +  }
   1.643 +}
   1.644 +#endif
   1.645 +
   1.646 +//
   1.647 +// This function supports testing of the malloc out of memory
   1.648 +// condition without really running the system out of memory.
   1.649 +//
   1.650 +static u_char* testMalloc(size_t alloc_size) {
   1.651 +  assert(MallocMaxTestWords > 0, "sanity check");
   1.652 +
   1.653 +  if ((cur_malloc_words + (alloc_size / BytesPerWord)) > MallocMaxTestWords) {
   1.654 +    return NULL;
   1.655 +  }
   1.656 +
   1.657 +  u_char* ptr = (u_char*)::malloc(alloc_size);
   1.658 +
   1.659 +  if (ptr != NULL) {
   1.660 +    Atomic::add(((jint) (alloc_size / BytesPerWord)),
   1.661 +                (volatile jint *) &cur_malloc_words);
   1.662 +  }
   1.663 +  return ptr;
   1.664 +}
   1.665 +
   1.666 +void* os::malloc(size_t size, MEMFLAGS memflags, address caller) {
   1.667 +  NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   1.668 +  NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
   1.669 +
   1.670 +#ifdef ASSERT
   1.671 +  // checking for the WatcherThread and crash_protection first
   1.672 +  // since os::malloc can be called when the libjvm.{dll,so} is
   1.673 +  // first loaded and we don't have a thread yet.
   1.674 +  // try to find the thread after we see that the watcher thread
   1.675 +  // exists and has crash protection.
   1.676 +  WatcherThread *wt = WatcherThread::watcher_thread();
   1.677 +  if (wt != NULL && wt->has_crash_protection()) {
   1.678 +    Thread* thread = ThreadLocalStorage::get_thread_slow();
   1.679 +    if (thread == wt) {
   1.680 +      assert(!wt->has_crash_protection(),
   1.681 +          "Can't malloc with crash protection from WatcherThread");
   1.682 +    }
   1.683 +  }
   1.684 +#endif
   1.685 +
   1.686 +  if (size == 0) {
   1.687 +    // return a valid pointer if size is zero
   1.688 +    // if NULL is returned the calling functions assume out of memory.
   1.689 +    size = 1;
   1.690 +  }
   1.691 +
   1.692 +  const size_t alloc_size = size + space_before + space_after;
   1.693 +
   1.694 +  if (size > alloc_size) { // Check for rollover.
   1.695 +    return NULL;
   1.696 +  }
   1.697 +
   1.698 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.699 +
   1.700 +  u_char* ptr;
   1.701 +
   1.702 +  if (MallocMaxTestWords > 0) {
   1.703 +    ptr = testMalloc(alloc_size);
   1.704 +  } else {
   1.705 +    ptr = (u_char*)::malloc(alloc_size);
   1.706 +  }
   1.707 +
   1.708 +#ifdef ASSERT
   1.709 +  if (ptr == NULL) return NULL;
   1.710 +  if (MallocCushion) {
   1.711 +    for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
   1.712 +    u_char* end = ptr + space_before + size;
   1.713 +    for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
   1.714 +    for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
   1.715 +  }
   1.716 +  // put size just before data
   1.717 +  *size_addr_from_base(ptr) = size;
   1.718 +#endif
   1.719 +  u_char* memblock = ptr + space_before;
   1.720 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.721 +    tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
   1.722 +    breakpoint();
   1.723 +  }
   1.724 +  debug_only(if (paranoid) verify_block(memblock));
   1.725 +  if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock);
   1.726 +
   1.727 +  // we do not track MallocCushion memory
   1.728 +    MemTracker::record_malloc((address)memblock, size, memflags, caller == 0 ? CALLER_PC : caller);
   1.729 +
   1.730 +  return memblock;
   1.731 +}
   1.732 +
   1.733 +
   1.734 +void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller) {
   1.735 +#ifndef ASSERT
   1.736 +  NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   1.737 +  NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
   1.738 +  MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
   1.739 +  void* ptr = ::realloc(memblock, size);
   1.740 +  if (ptr != NULL) {
   1.741 +    tkr.record((address)memblock, (address)ptr, size, memflags,
   1.742 +     caller == 0 ? CALLER_PC : caller);
   1.743 +  } else {
   1.744 +    tkr.discard();
   1.745 +  }
   1.746 +  return ptr;
   1.747 +#else
   1.748 +  if (memblock == NULL) {
   1.749 +    return malloc(size, memflags, (caller == 0 ? CALLER_PC : caller));
   1.750 +  }
   1.751 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.752 +    tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
   1.753 +    breakpoint();
   1.754 +  }
   1.755 +  verify_block(memblock);
   1.756 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.757 +  if (size == 0) return NULL;
   1.758 +  // always move the block
   1.759 +  void* ptr = malloc(size, memflags, caller == 0 ? CALLER_PC : caller);
   1.760 +  if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
   1.761 +  // Copy to new memory if malloc didn't fail
   1.762 +  if ( ptr != NULL ) {
   1.763 +    memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
   1.764 +    if (paranoid) verify_block(ptr);
   1.765 +    if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
   1.766 +      tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
   1.767 +      breakpoint();
   1.768 +    }
   1.769 +    free(memblock);
   1.770 +  }
   1.771 +  return ptr;
   1.772 +#endif
   1.773 +}
   1.774 +
   1.775 +
   1.776 +void  os::free(void *memblock, MEMFLAGS memflags) {
   1.777 +  NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
   1.778 +#ifdef ASSERT
   1.779 +  if (memblock == NULL) return;
   1.780 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.781 +    if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
   1.782 +    breakpoint();
   1.783 +  }
   1.784 +  verify_block(memblock);
   1.785 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.786 +  // Added by detlefs.
   1.787 +  if (MallocCushion) {
   1.788 +    u_char* ptr = (u_char*)memblock - space_before;
   1.789 +    for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
   1.790 +      guarantee(*p == badResourceValue,
   1.791 +                "Thing freed should be malloc result.");
   1.792 +      *p = (u_char)freeBlockPad;
   1.793 +    }
   1.794 +    size_t size = get_size(memblock);
   1.795 +    inc_stat_counter(&free_bytes, size);
   1.796 +    u_char* end = ptr + space_before + size;
   1.797 +    for (u_char* q = end; q < end + MallocCushion; q++) {
   1.798 +      guarantee(*q == badResourceValue,
   1.799 +                "Thing freed should be malloc result.");
   1.800 +      *q = (u_char)freeBlockPad;
   1.801 +    }
   1.802 +    if (PrintMalloc && tty != NULL)
   1.803 +      fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock);
   1.804 +  } else if (PrintMalloc && tty != NULL) {
   1.805 +    // tty->print_cr("os::free %p", memblock);
   1.806 +    fprintf(stderr, "os::free " PTR_FORMAT "\n", (uintptr_t)memblock);
   1.807 +  }
   1.808 +#endif
   1.809 +  MemTracker::record_free((address)memblock, memflags);
   1.810 +
   1.811 +  ::free((char*)memblock - space_before);
   1.812 +}
   1.813 +
   1.814 +void os::init_random(long initval) {
   1.815 +  _rand_seed = initval;
   1.816 +}
   1.817 +
   1.818 +
   1.819 +long os::random() {
   1.820 +  /* standard, well-known linear congruential random generator with
   1.821 +   * next_rand = (16807*seed) mod (2**31-1)
   1.822 +   * see
   1.823 +   * (1) "Random Number Generators: Good Ones Are Hard to Find",
   1.824 +   *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
   1.825 +   * (2) "Two Fast Implementations of the 'Minimal Standard' Random
   1.826 +   *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
   1.827 +  */
   1.828 +  const long a = 16807;
   1.829 +  const unsigned long m = 2147483647;
   1.830 +  const long q = m / a;        assert(q == 127773, "weird math");
   1.831 +  const long r = m % a;        assert(r == 2836, "weird math");
   1.832 +
   1.833 +  // compute az=2^31p+q
   1.834 +  unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
   1.835 +  unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
   1.836 +  lo += (hi & 0x7FFF) << 16;
   1.837 +
   1.838 +  // if q overflowed, ignore the overflow and increment q
   1.839 +  if (lo > m) {
   1.840 +    lo &= m;
   1.841 +    ++lo;
   1.842 +  }
   1.843 +  lo += hi >> 15;
   1.844 +
   1.845 +  // if (p+q) overflowed, ignore the overflow and increment (p+q)
   1.846 +  if (lo > m) {
   1.847 +    lo &= m;
   1.848 +    ++lo;
   1.849 +  }
   1.850 +  return (_rand_seed = lo);
   1.851 +}
   1.852 +
   1.853 +// The INITIALIZED state is distinguished from the SUSPENDED state because the
   1.854 +// conditions in which a thread is first started are different from those in which
   1.855 +// a suspension is resumed.  These differences make it hard for us to apply the
   1.856 +// tougher checks when starting threads that we want to do when resuming them.
   1.857 +// However, when start_thread is called as a result of Thread.start, on a Java
   1.858 +// thread, the operation is synchronized on the Java Thread object.  So there
   1.859 +// cannot be a race to start the thread and hence for the thread to exit while
   1.860 +// we are working on it.  Non-Java threads that start Java threads either have
   1.861 +// to do so in a context in which races are impossible, or should do appropriate
   1.862 +// locking.
   1.863 +
   1.864 +void os::start_thread(Thread* thread) {
   1.865 +  // guard suspend/resume
   1.866 +  MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
   1.867 +  OSThread* osthread = thread->osthread();
   1.868 +  osthread->set_state(RUNNABLE);
   1.869 +  pd_start_thread(thread);
   1.870 +}
   1.871 +
   1.872 +//---------------------------------------------------------------------------
   1.873 +// Helper functions for fatal error handler
   1.874 +
   1.875 +void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
   1.876 +  assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
   1.877 +
   1.878 +  int cols = 0;
   1.879 +  int cols_per_line = 0;
   1.880 +  switch (unitsize) {
   1.881 +    case 1: cols_per_line = 16; break;
   1.882 +    case 2: cols_per_line = 8;  break;
   1.883 +    case 4: cols_per_line = 4;  break;
   1.884 +    case 8: cols_per_line = 2;  break;
   1.885 +    default: return;
   1.886 +  }
   1.887 +
   1.888 +  address p = start;
   1.889 +  st->print(PTR_FORMAT ":   ", start);
   1.890 +  while (p < end) {
   1.891 +    switch (unitsize) {
   1.892 +      case 1: st->print("%02x", *(u1*)p); break;
   1.893 +      case 2: st->print("%04x", *(u2*)p); break;
   1.894 +      case 4: st->print("%08x", *(u4*)p); break;
   1.895 +      case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
   1.896 +    }
   1.897 +    p += unitsize;
   1.898 +    cols++;
   1.899 +    if (cols >= cols_per_line && p < end) {
   1.900 +       cols = 0;
   1.901 +       st->cr();
   1.902 +       st->print(PTR_FORMAT ":   ", p);
   1.903 +    } else {
   1.904 +       st->print(" ");
   1.905 +    }
   1.906 +  }
   1.907 +  st->cr();
   1.908 +}
   1.909 +
   1.910 +void os::print_environment_variables(outputStream* st, const char** env_list,
   1.911 +                                     char* buffer, int len) {
   1.912 +  if (env_list) {
   1.913 +    st->print_cr("Environment Variables:");
   1.914 +
   1.915 +    for (int i = 0; env_list[i] != NULL; i++) {
   1.916 +      if (getenv(env_list[i], buffer, len)) {
   1.917 +        st->print("%s", env_list[i]);
   1.918 +        st->print("=");
   1.919 +        st->print_cr("%s", buffer);
   1.920 +      }
   1.921 +    }
   1.922 +  }
   1.923 +}
   1.924 +
   1.925 +void os::print_cpu_info(outputStream* st) {
   1.926 +  // cpu
   1.927 +  st->print("CPU:");
   1.928 +  st->print("total %d", os::processor_count());
   1.929 +  // It's not safe to query number of active processors after crash
   1.930 +  // st->print("(active %d)", os::active_processor_count());
   1.931 +  st->print(" %s", VM_Version::cpu_features());
   1.932 +  st->cr();
   1.933 +  pd_print_cpu_info(st);
   1.934 +}
   1.935 +
   1.936 +void os::print_date_and_time(outputStream *st) {
   1.937 +  const int secs_per_day  = 86400;
   1.938 +  const int secs_per_hour = 3600;
   1.939 +  const int secs_per_min  = 60;
   1.940 +
   1.941 +  time_t tloc;
   1.942 +  (void)time(&tloc);
   1.943 +  st->print("time: %s", ctime(&tloc));  // ctime adds newline.
   1.944 +
   1.945 +  double t = os::elapsedTime();
   1.946 +  // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
   1.947 +  //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
   1.948 +  //       before printf. We lost some precision, but who cares?
   1.949 +  int eltime = (int)t;  // elapsed time in seconds
   1.950 +
   1.951 +  // print elapsed time in a human-readable format:
   1.952 +  int eldays = eltime / secs_per_day;
   1.953 +  int day_secs = eldays * secs_per_day;
   1.954 +  int elhours = (eltime - day_secs) / secs_per_hour;
   1.955 +  int hour_secs = elhours * secs_per_hour;
   1.956 +  int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
   1.957 +  int minute_secs = elmins * secs_per_min;
   1.958 +  int elsecs = (eltime - day_secs - hour_secs - minute_secs);
   1.959 +  st->print_cr("elapsed time: %d seconds (%dd %dh %dm %ds)", eltime, eldays, elhours, elmins, elsecs);
   1.960 +}
   1.961 +
   1.962 +// moved from debug.cpp (used to be find()) but still called from there
   1.963 +// The verbose parameter is only set by the debug code in one case
   1.964 +void os::print_location(outputStream* st, intptr_t x, bool verbose) {
   1.965 +  address addr = (address)x;
   1.966 +  CodeBlob* b = CodeCache::find_blob_unsafe(addr);
   1.967 +  if (b != NULL) {
   1.968 +    if (b->is_buffer_blob()) {
   1.969 +      // the interpreter is generated into a buffer blob
   1.970 +      InterpreterCodelet* i = Interpreter::codelet_containing(addr);
   1.971 +      if (i != NULL) {
   1.972 +        st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
   1.973 +        i->print_on(st);
   1.974 +        return;
   1.975 +      }
   1.976 +      if (Interpreter::contains(addr)) {
   1.977 +        st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
   1.978 +                     " (not bytecode specific)", addr);
   1.979 +        return;
   1.980 +      }
   1.981 +      //
   1.982 +      if (AdapterHandlerLibrary::contains(b)) {
   1.983 +        st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
   1.984 +        AdapterHandlerLibrary::print_handler_on(st, b);
   1.985 +      }
   1.986 +      // the stubroutines are generated into a buffer blob
   1.987 +      StubCodeDesc* d = StubCodeDesc::desc_for(addr);
   1.988 +      if (d != NULL) {
   1.989 +        st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
   1.990 +        d->print_on(st);
   1.991 +        st->cr();
   1.992 +        return;
   1.993 +      }
   1.994 +      if (StubRoutines::contains(addr)) {
   1.995 +        st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
   1.996 +                     "stub routine", addr);
   1.997 +        return;
   1.998 +      }
   1.999 +      // the InlineCacheBuffer is using stubs generated into a buffer blob
  1.1000 +      if (InlineCacheBuffer::contains(addr)) {
  1.1001 +        st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
  1.1002 +        return;
  1.1003 +      }
  1.1004 +      VtableStub* v = VtableStubs::stub_containing(addr);
  1.1005 +      if (v != NULL) {
  1.1006 +        st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
  1.1007 +        v->print_on(st);
  1.1008 +        st->cr();
  1.1009 +        return;
  1.1010 +      }
  1.1011 +    }
  1.1012 +    nmethod* nm = b->as_nmethod_or_null();
  1.1013 +    if (nm != NULL) {
  1.1014 +      ResourceMark rm;
  1.1015 +      st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
  1.1016 +                addr, (int)(addr - nm->entry_point()), nm);
  1.1017 +      if (verbose) {
  1.1018 +        st->print(" for ");
  1.1019 +        nm->method()->print_value_on(st);
  1.1020 +      }
  1.1021 +      st->cr();
  1.1022 +      nm->print_nmethod(verbose);
  1.1023 +      return;
  1.1024 +    }
  1.1025 +    st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
  1.1026 +    b->print_on(st);
  1.1027 +    return;
  1.1028 +  }
  1.1029 +
  1.1030 +  if (Universe::heap()->is_in(addr)) {
  1.1031 +    HeapWord* p = Universe::heap()->block_start(addr);
  1.1032 +    bool print = false;
  1.1033 +    // If we couldn't find it it just may mean that heap wasn't parseable
  1.1034 +    // See if we were just given an oop directly
  1.1035 +    if (p != NULL && Universe::heap()->block_is_obj(p)) {
  1.1036 +      print = true;
  1.1037 +    } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
  1.1038 +      p = (HeapWord*) addr;
  1.1039 +      print = true;
  1.1040 +    }
  1.1041 +    if (print) {
  1.1042 +      if (p == (HeapWord*) addr) {
  1.1043 +        st->print_cr(INTPTR_FORMAT " is an oop", addr);
  1.1044 +      } else {
  1.1045 +        st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
  1.1046 +      }
  1.1047 +      oop(p)->print_on(st);
  1.1048 +      return;
  1.1049 +    }
  1.1050 +  } else {
  1.1051 +    if (Universe::heap()->is_in_reserved(addr)) {
  1.1052 +      st->print_cr(INTPTR_FORMAT " is an unallocated location "
  1.1053 +                   "in the heap", addr);
  1.1054 +      return;
  1.1055 +    }
  1.1056 +  }
  1.1057 +  if (JNIHandles::is_global_handle((jobject) addr)) {
  1.1058 +    st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
  1.1059 +    return;
  1.1060 +  }
  1.1061 +  if (JNIHandles::is_weak_global_handle((jobject) addr)) {
  1.1062 +    st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
  1.1063 +    return;
  1.1064 +  }
  1.1065 +#ifndef PRODUCT
  1.1066 +  // we don't keep the block list in product mode
  1.1067 +  if (JNIHandleBlock::any_contains((jobject) addr)) {
  1.1068 +    st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
  1.1069 +    return;
  1.1070 +  }
  1.1071 +#endif
  1.1072 +
  1.1073 +  for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
  1.1074 +    // Check for privilege stack
  1.1075 +    if (thread->privileged_stack_top() != NULL &&
  1.1076 +        thread->privileged_stack_top()->contains(addr)) {
  1.1077 +      st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
  1.1078 +                   "for thread: " INTPTR_FORMAT, addr, thread);
  1.1079 +      if (verbose) thread->print_on(st);
  1.1080 +      return;
  1.1081 +    }
  1.1082 +    // If the addr is a java thread print information about that.
  1.1083 +    if (addr == (address)thread) {
  1.1084 +      if (verbose) {
  1.1085 +        thread->print_on(st);
  1.1086 +      } else {
  1.1087 +        st->print_cr(INTPTR_FORMAT " is a thread", addr);
  1.1088 +      }
  1.1089 +      return;
  1.1090 +    }
  1.1091 +    // If the addr is in the stack region for this thread then report that
  1.1092 +    // and print thread info
  1.1093 +    if (thread->stack_base() >= addr &&
  1.1094 +        addr > (thread->stack_base() - thread->stack_size())) {
  1.1095 +      st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
  1.1096 +                   INTPTR_FORMAT, addr, thread);
  1.1097 +      if (verbose) thread->print_on(st);
  1.1098 +      return;
  1.1099 +    }
  1.1100 +
  1.1101 +  }
  1.1102 +
  1.1103 +  // Check if in metaspace and print types that have vptrs (only method now)
  1.1104 +  if (Metaspace::contains(addr)) {
  1.1105 +    if (Method::has_method_vptr((const void*)addr)) {
  1.1106 +      ((Method*)addr)->print_value_on(st);
  1.1107 +      st->cr();
  1.1108 +    } else {
  1.1109 +      // Use addr->print() from the debugger instead (not here)
  1.1110 +      st->print_cr(INTPTR_FORMAT " is pointing into metadata", addr);
  1.1111 +    }
  1.1112 +    return;
  1.1113 +  }
  1.1114 +
  1.1115 +  // Try an OS specific find
  1.1116 +  if (os::find(addr, st)) {
  1.1117 +    return;
  1.1118 +  }
  1.1119 +
  1.1120 +  st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
  1.1121 +}
  1.1122 +
  1.1123 +// Looks like all platforms except IA64 can use the same function to check
  1.1124 +// if C stack is walkable beyond current frame. The check for fp() is not
  1.1125 +// necessary on Sparc, but it's harmless.
  1.1126 +bool os::is_first_C_frame(frame* fr) {
  1.1127 +#if (defined(IA64) && !defined(AIX)) && !defined(_WIN32)
  1.1128 +  // On IA64 we have to check if the callers bsp is still valid
  1.1129 +  // (i.e. within the register stack bounds).
  1.1130 +  // Notice: this only works for threads created by the VM and only if
  1.1131 +  // we walk the current stack!!! If we want to be able to walk
  1.1132 +  // arbitrary other threads, we'll have to somehow store the thread
  1.1133 +  // object in the frame.
  1.1134 +  Thread *thread = Thread::current();
  1.1135 +  if ((address)fr->fp() <=
  1.1136 +      thread->register_stack_base() HPUX_ONLY(+ 0x0) LINUX_ONLY(+ 0x50)) {
  1.1137 +    // This check is a little hacky, because on Linux the first C
  1.1138 +    // frame's ('start_thread') register stack frame starts at
  1.1139 +    // "register_stack_base + 0x48" while on HPUX, the first C frame's
  1.1140 +    // ('__pthread_bound_body') register stack frame seems to really
  1.1141 +    // start at "register_stack_base".
  1.1142 +    return true;
  1.1143 +  } else {
  1.1144 +    return false;
  1.1145 +  }
  1.1146 +#elif defined(IA64) && defined(_WIN32)
  1.1147 +  return true;
  1.1148 +#else
  1.1149 +  // Load up sp, fp, sender sp and sender fp, check for reasonable values.
  1.1150 +  // Check usp first, because if that's bad the other accessors may fault
  1.1151 +  // on some architectures.  Ditto ufp second, etc.
  1.1152 +  uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
  1.1153 +  // sp on amd can be 32 bit aligned.
  1.1154 +  uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
  1.1155 +
  1.1156 +  uintptr_t usp    = (uintptr_t)fr->sp();
  1.1157 +  if ((usp & sp_align_mask) != 0) return true;
  1.1158 +
  1.1159 +  uintptr_t ufp    = (uintptr_t)fr->fp();
  1.1160 +  if ((ufp & fp_align_mask) != 0) return true;
  1.1161 +
  1.1162 +  uintptr_t old_sp = (uintptr_t)fr->sender_sp();
  1.1163 +  if ((old_sp & sp_align_mask) != 0) return true;
  1.1164 +  if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
  1.1165 +
  1.1166 +  uintptr_t old_fp = (uintptr_t)fr->link();
  1.1167 +  if ((old_fp & fp_align_mask) != 0) return true;
  1.1168 +  if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
  1.1169 +
  1.1170 +  // stack grows downwards; if old_fp is below current fp or if the stack
  1.1171 +  // frame is too large, either the stack is corrupted or fp is not saved
  1.1172 +  // on stack (i.e. on x86, ebp may be used as general register). The stack
  1.1173 +  // is not walkable beyond current frame.
  1.1174 +  if (old_fp < ufp) return true;
  1.1175 +  if (old_fp - ufp > 64 * K) return true;
  1.1176 +
  1.1177 +  return false;
  1.1178 +#endif
  1.1179 +}
  1.1180 +
  1.1181 +#ifdef ASSERT
  1.1182 +extern "C" void test_random() {
  1.1183 +  const double m = 2147483647;
  1.1184 +  double mean = 0.0, variance = 0.0, t;
  1.1185 +  long reps = 10000;
  1.1186 +  unsigned long seed = 1;
  1.1187 +
  1.1188 +  tty->print_cr("seed %ld for %ld repeats...", seed, reps);
  1.1189 +  os::init_random(seed);
  1.1190 +  long num;
  1.1191 +  for (int k = 0; k < reps; k++) {
  1.1192 +    num = os::random();
  1.1193 +    double u = (double)num / m;
  1.1194 +    assert(u >= 0.0 && u <= 1.0, "bad random number!");
  1.1195 +
  1.1196 +    // calculate mean and variance of the random sequence
  1.1197 +    mean += u;
  1.1198 +    variance += (u*u);
  1.1199 +  }
  1.1200 +  mean /= reps;
  1.1201 +  variance /= (reps - 1);
  1.1202 +
  1.1203 +  assert(num == 1043618065, "bad seed");
  1.1204 +  tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
  1.1205 +  tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
  1.1206 +  const double eps = 0.0001;
  1.1207 +  t = fabsd(mean - 0.5018);
  1.1208 +  assert(t < eps, "bad mean");
  1.1209 +  t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
  1.1210 +  assert(t < eps, "bad variance");
  1.1211 +}
  1.1212 +#endif
  1.1213 +
  1.1214 +
  1.1215 +// Set up the boot classpath.
  1.1216 +
  1.1217 +char* os::format_boot_path(const char* format_string,
  1.1218 +                           const char* home,
  1.1219 +                           int home_len,
  1.1220 +                           char fileSep,
  1.1221 +                           char pathSep) {
  1.1222 +    assert((fileSep == '/' && pathSep == ':') ||
  1.1223 +           (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
  1.1224 +
  1.1225 +    // Scan the format string to determine the length of the actual
  1.1226 +    // boot classpath, and handle platform dependencies as well.
  1.1227 +    int formatted_path_len = 0;
  1.1228 +    const char* p;
  1.1229 +    for (p = format_string; *p != 0; ++p) {
  1.1230 +        if (*p == '%') formatted_path_len += home_len - 1;
  1.1231 +        ++formatted_path_len;
  1.1232 +    }
  1.1233 +
  1.1234 +    char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
  1.1235 +    if (formatted_path == NULL) {
  1.1236 +        return NULL;
  1.1237 +    }
  1.1238 +
  1.1239 +    // Create boot classpath from format, substituting separator chars and
  1.1240 +    // java home directory.
  1.1241 +    char* q = formatted_path;
  1.1242 +    for (p = format_string; *p != 0; ++p) {
  1.1243 +        switch (*p) {
  1.1244 +        case '%':
  1.1245 +            strcpy(q, home);
  1.1246 +            q += home_len;
  1.1247 +            break;
  1.1248 +        case '/':
  1.1249 +            *q++ = fileSep;
  1.1250 +            break;
  1.1251 +        case ':':
  1.1252 +            *q++ = pathSep;
  1.1253 +            break;
  1.1254 +        default:
  1.1255 +            *q++ = *p;
  1.1256 +        }
  1.1257 +    }
  1.1258 +    *q = '\0';
  1.1259 +
  1.1260 +    assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
  1.1261 +    return formatted_path;
  1.1262 +}
  1.1263 +
  1.1264 +
  1.1265 +bool os::set_boot_path(char fileSep, char pathSep) {
  1.1266 +    const char* home = Arguments::get_java_home();
  1.1267 +    int home_len = (int)strlen(home);
  1.1268 +
  1.1269 +    static const char* meta_index_dir_format = "%/lib/";
  1.1270 +    static const char* meta_index_format = "%/lib/meta-index";
  1.1271 +    char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
  1.1272 +    if (meta_index == NULL) return false;
  1.1273 +    char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
  1.1274 +    if (meta_index_dir == NULL) return false;
  1.1275 +    Arguments::set_meta_index_path(meta_index, meta_index_dir);
  1.1276 +
  1.1277 +    // Any modification to the JAR-file list, for the boot classpath must be
  1.1278 +    // aligned with install/install/make/common/Pack.gmk. Note: boot class
  1.1279 +    // path class JARs, are stripped for StackMapTable to reduce download size.
  1.1280 +    static const char classpath_format[] =
  1.1281 +        "%/lib/resources.jar:"
  1.1282 +        "%/lib/rt.jar:"
  1.1283 +        "%/lib/sunrsasign.jar:"
  1.1284 +        "%/lib/jsse.jar:"
  1.1285 +        "%/lib/jce.jar:"
  1.1286 +        "%/lib/charsets.jar:"
  1.1287 +        "%/lib/jfr.jar:"
  1.1288 +        "%/classes";
  1.1289 +    char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
  1.1290 +    if (sysclasspath == NULL) return false;
  1.1291 +    Arguments::set_sysclasspath(sysclasspath);
  1.1292 +
  1.1293 +    return true;
  1.1294 +}
  1.1295 +
  1.1296 +/*
  1.1297 + * Splits a path, based on its separator, the number of
  1.1298 + * elements is returned back in n.
  1.1299 + * It is the callers responsibility to:
  1.1300 + *   a> check the value of n, and n may be 0.
  1.1301 + *   b> ignore any empty path elements
  1.1302 + *   c> free up the data.
  1.1303 + */
  1.1304 +char** os::split_path(const char* path, int* n) {
  1.1305 +  *n = 0;
  1.1306 +  if (path == NULL || strlen(path) == 0) {
  1.1307 +    return NULL;
  1.1308 +  }
  1.1309 +  const char psepchar = *os::path_separator();
  1.1310 +  char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
  1.1311 +  if (inpath == NULL) {
  1.1312 +    return NULL;
  1.1313 +  }
  1.1314 +  strcpy(inpath, path);
  1.1315 +  int count = 1;
  1.1316 +  char* p = strchr(inpath, psepchar);
  1.1317 +  // Get a count of elements to allocate memory
  1.1318 +  while (p != NULL) {
  1.1319 +    count++;
  1.1320 +    p++;
  1.1321 +    p = strchr(p, psepchar);
  1.1322 +  }
  1.1323 +  char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal);
  1.1324 +  if (opath == NULL) {
  1.1325 +    return NULL;
  1.1326 +  }
  1.1327 +
  1.1328 +  // do the actual splitting
  1.1329 +  p = inpath;
  1.1330 +  for (int i = 0 ; i < count ; i++) {
  1.1331 +    size_t len = strcspn(p, os::path_separator());
  1.1332 +    if (len > JVM_MAXPATHLEN) {
  1.1333 +      return NULL;
  1.1334 +    }
  1.1335 +    // allocate the string and add terminator storage
  1.1336 +    char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
  1.1337 +    if (s == NULL) {
  1.1338 +      return NULL;
  1.1339 +    }
  1.1340 +    strncpy(s, p, len);
  1.1341 +    s[len] = '\0';
  1.1342 +    opath[i] = s;
  1.1343 +    p += len + 1;
  1.1344 +  }
  1.1345 +  FREE_C_HEAP_ARRAY(char, inpath, mtInternal);
  1.1346 +  *n = count;
  1.1347 +  return opath;
  1.1348 +}
  1.1349 +
  1.1350 +void os::set_memory_serialize_page(address page) {
  1.1351 +  int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
  1.1352 +  _mem_serialize_page = (volatile int32_t *)page;
  1.1353 +  // We initialize the serialization page shift count here
  1.1354 +  // We assume a cache line size of 64 bytes
  1.1355 +  assert(SerializePageShiftCount == count,
  1.1356 +         "thread size changed, fix SerializePageShiftCount constant");
  1.1357 +  set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
  1.1358 +}
  1.1359 +
  1.1360 +static volatile intptr_t SerializePageLock = 0;
  1.1361 +
  1.1362 +// This method is called from signal handler when SIGSEGV occurs while the current
  1.1363 +// thread tries to store to the "read-only" memory serialize page during state
  1.1364 +// transition.
  1.1365 +void os::block_on_serialize_page_trap() {
  1.1366 +  if (TraceSafepoint) {
  1.1367 +    tty->print_cr("Block until the serialize page permission restored");
  1.1368 +  }
  1.1369 +  // When VMThread is holding the SerializePageLock during modifying the
  1.1370 +  // access permission of the memory serialize page, the following call
  1.1371 +  // will block until the permission of that page is restored to rw.
  1.1372 +  // Generally, it is unsafe to manipulate locks in signal handlers, but in
  1.1373 +  // this case, it's OK as the signal is synchronous and we know precisely when
  1.1374 +  // it can occur.
  1.1375 +  Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
  1.1376 +  Thread::muxRelease(&SerializePageLock);
  1.1377 +}
  1.1378 +
  1.1379 +// Serialize all thread state variables
  1.1380 +void os::serialize_thread_states() {
  1.1381 +  // On some platforms such as Solaris & Linux, the time duration of the page
  1.1382 +  // permission restoration is observed to be much longer than expected  due to
  1.1383 +  // scheduler starvation problem etc. To avoid the long synchronization
  1.1384 +  // time and expensive page trap spinning, 'SerializePageLock' is used to block
  1.1385 +  // the mutator thread if such case is encountered. See bug 6546278 for details.
  1.1386 +  Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
  1.1387 +  os::protect_memory((char *)os::get_memory_serialize_page(),
  1.1388 +                     os::vm_page_size(), MEM_PROT_READ);
  1.1389 +  os::protect_memory((char *)os::get_memory_serialize_page(),
  1.1390 +                     os::vm_page_size(), MEM_PROT_RW);
  1.1391 +  Thread::muxRelease(&SerializePageLock);
  1.1392 +}
  1.1393 +
  1.1394 +// Returns true if the current stack pointer is above the stack shadow
  1.1395 +// pages, false otherwise.
  1.1396 +
  1.1397 +bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
  1.1398 +  assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
  1.1399 +  address sp = current_stack_pointer();
  1.1400 +  // Check if we have StackShadowPages above the yellow zone.  This parameter
  1.1401 +  // is dependent on the depth of the maximum VM call stack possible from
  1.1402 +  // the handler for stack overflow.  'instanceof' in the stack overflow
  1.1403 +  // handler or a println uses at least 8k stack of VM and native code
  1.1404 +  // respectively.
  1.1405 +  const int framesize_in_bytes =
  1.1406 +    Interpreter::size_top_interpreter_activation(method()) * wordSize;
  1.1407 +  int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
  1.1408 +                      * vm_page_size()) + framesize_in_bytes;
  1.1409 +  // The very lower end of the stack
  1.1410 +  address stack_limit = thread->stack_base() - thread->stack_size();
  1.1411 +  return (sp > (stack_limit + reserved_area));
  1.1412 +}
  1.1413 +
  1.1414 +size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
  1.1415 +                                uint min_pages)
  1.1416 +{
  1.1417 +  assert(min_pages > 0, "sanity");
  1.1418 +  if (UseLargePages) {
  1.1419 +    const size_t max_page_size = region_max_size / min_pages;
  1.1420 +
  1.1421 +    for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
  1.1422 +      const size_t sz = _page_sizes[i];
  1.1423 +      const size_t mask = sz - 1;
  1.1424 +      if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
  1.1425 +        // The largest page size with no fragmentation.
  1.1426 +        return sz;
  1.1427 +      }
  1.1428 +
  1.1429 +      if (sz <= max_page_size) {
  1.1430 +        // The largest page size that satisfies the min_pages requirement.
  1.1431 +        return sz;
  1.1432 +      }
  1.1433 +    }
  1.1434 +  }
  1.1435 +
  1.1436 +  return vm_page_size();
  1.1437 +}
  1.1438 +
  1.1439 +#ifndef PRODUCT
  1.1440 +void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
  1.1441 +{
  1.1442 +  if (TracePageSizes) {
  1.1443 +    tty->print("%s: ", str);
  1.1444 +    for (int i = 0; i < count; ++i) {
  1.1445 +      tty->print(" " SIZE_FORMAT, page_sizes[i]);
  1.1446 +    }
  1.1447 +    tty->cr();
  1.1448 +  }
  1.1449 +}
  1.1450 +
  1.1451 +void os::trace_page_sizes(const char* str, const size_t region_min_size,
  1.1452 +                          const size_t region_max_size, const size_t page_size,
  1.1453 +                          const char* base, const size_t size)
  1.1454 +{
  1.1455 +  if (TracePageSizes) {
  1.1456 +    tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
  1.1457 +                  " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
  1.1458 +                  " size=" SIZE_FORMAT,
  1.1459 +                  str, region_min_size, region_max_size,
  1.1460 +                  page_size, base, size);
  1.1461 +  }
  1.1462 +}
  1.1463 +#endif  // #ifndef PRODUCT
  1.1464 +
  1.1465 +// This is the working definition of a server class machine:
  1.1466 +// >= 2 physical CPU's and >=2GB of memory, with some fuzz
  1.1467 +// because the graphics memory (?) sometimes masks physical memory.
  1.1468 +// If you want to change the definition of a server class machine
  1.1469 +// on some OS or platform, e.g., >=4GB on Windohs platforms,
  1.1470 +// then you'll have to parameterize this method based on that state,
  1.1471 +// as was done for logical processors here, or replicate and
  1.1472 +// specialize this method for each platform.  (Or fix os to have
  1.1473 +// some inheritance structure and use subclassing.  Sigh.)
  1.1474 +// If you want some platform to always or never behave as a server
  1.1475 +// class machine, change the setting of AlwaysActAsServerClassMachine
  1.1476 +// and NeverActAsServerClassMachine in globals*.hpp.
  1.1477 +bool os::is_server_class_machine() {
  1.1478 +  // First check for the early returns
  1.1479 +  if (NeverActAsServerClassMachine) {
  1.1480 +    return false;
  1.1481 +  }
  1.1482 +  if (AlwaysActAsServerClassMachine) {
  1.1483 +    return true;
  1.1484 +  }
  1.1485 +  // Then actually look at the machine
  1.1486 +  bool         result            = false;
  1.1487 +  const unsigned int    server_processors = 2;
  1.1488 +  const julong server_memory     = 2UL * G;
  1.1489 +  // We seem not to get our full complement of memory.
  1.1490 +  //     We allow some part (1/8?) of the memory to be "missing",
  1.1491 +  //     based on the sizes of DIMMs, and maybe graphics cards.
  1.1492 +  const julong missing_memory   = 256UL * M;
  1.1493 +
  1.1494 +  /* Is this a server class machine? */
  1.1495 +  if ((os::active_processor_count() >= (int)server_processors) &&
  1.1496 +      (os::physical_memory() >= (server_memory - missing_memory))) {
  1.1497 +    const unsigned int logical_processors =
  1.1498 +      VM_Version::logical_processors_per_package();
  1.1499 +    if (logical_processors > 1) {
  1.1500 +      const unsigned int physical_packages =
  1.1501 +        os::active_processor_count() / logical_processors;
  1.1502 +      if (physical_packages > server_processors) {
  1.1503 +        result = true;
  1.1504 +      }
  1.1505 +    } else {
  1.1506 +      result = true;
  1.1507 +    }
  1.1508 +  }
  1.1509 +  return result;
  1.1510 +}
  1.1511 +
  1.1512 +void os::SuspendedThreadTask::run() {
  1.1513 +  assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
  1.1514 +  internal_do_task();
  1.1515 +  _done = true;
  1.1516 +}
  1.1517 +
  1.1518 +bool os::create_stack_guard_pages(char* addr, size_t bytes) {
  1.1519 +  return os::pd_create_stack_guard_pages(addr, bytes);
  1.1520 +}
  1.1521 +
  1.1522 +char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
  1.1523 +  char* result = pd_reserve_memory(bytes, addr, alignment_hint);
  1.1524 +  if (result != NULL) {
  1.1525 +    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
  1.1526 +  }
  1.1527 +
  1.1528 +  return result;
  1.1529 +}
  1.1530 +
  1.1531 +char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
  1.1532 +   MEMFLAGS flags) {
  1.1533 +  char* result = pd_reserve_memory(bytes, addr, alignment_hint);
  1.1534 +  if (result != NULL) {
  1.1535 +    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
  1.1536 +    MemTracker::record_virtual_memory_type((address)result, flags);
  1.1537 +  }
  1.1538 +
  1.1539 +  return result;
  1.1540 +}
  1.1541 +
  1.1542 +char* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
  1.1543 +  char* result = pd_attempt_reserve_memory_at(bytes, addr);
  1.1544 +  if (result != NULL) {
  1.1545 +    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
  1.1546 +  }
  1.1547 +  return result;
  1.1548 +}
  1.1549 +
  1.1550 +void os::split_reserved_memory(char *base, size_t size,
  1.1551 +                                 size_t split, bool realloc) {
  1.1552 +  pd_split_reserved_memory(base, size, split, realloc);
  1.1553 +}
  1.1554 +
  1.1555 +bool os::commit_memory(char* addr, size_t bytes, bool executable) {
  1.1556 +  bool res = pd_commit_memory(addr, bytes, executable);
  1.1557 +  if (res) {
  1.1558 +    MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
  1.1559 +  }
  1.1560 +  return res;
  1.1561 +}
  1.1562 +
  1.1563 +bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
  1.1564 +                              bool executable) {
  1.1565 +  bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
  1.1566 +  if (res) {
  1.1567 +    MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
  1.1568 +  }
  1.1569 +  return res;
  1.1570 +}
  1.1571 +
  1.1572 +void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
  1.1573 +                               const char* mesg) {
  1.1574 +  pd_commit_memory_or_exit(addr, bytes, executable, mesg);
  1.1575 +  MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
  1.1576 +}
  1.1577 +
  1.1578 +void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
  1.1579 +                               bool executable, const char* mesg) {
  1.1580 +  os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
  1.1581 +  MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
  1.1582 +}
  1.1583 +
  1.1584 +bool os::uncommit_memory(char* addr, size_t bytes) {
  1.1585 +  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
  1.1586 +  bool res = pd_uncommit_memory(addr, bytes);
  1.1587 +  if (res) {
  1.1588 +    tkr.record((address)addr, bytes);
  1.1589 +  } else {
  1.1590 +    tkr.discard();
  1.1591 +  }
  1.1592 +  return res;
  1.1593 +}
  1.1594 +
  1.1595 +bool os::release_memory(char* addr, size_t bytes) {
  1.1596 +  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
  1.1597 +  bool res = pd_release_memory(addr, bytes);
  1.1598 +  if (res) {
  1.1599 +    tkr.record((address)addr, bytes);
  1.1600 +  } else {
  1.1601 +    tkr.discard();
  1.1602 +  }
  1.1603 +  return res;
  1.1604 +}
  1.1605 +
  1.1606 +
  1.1607 +char* os::map_memory(int fd, const char* file_name, size_t file_offset,
  1.1608 +                           char *addr, size_t bytes, bool read_only,
  1.1609 +                           bool allow_exec) {
  1.1610 +  char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
  1.1611 +  if (result != NULL) {
  1.1612 +    MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, mtNone, CALLER_PC);
  1.1613 +  }
  1.1614 +  return result;
  1.1615 +}
  1.1616 +
  1.1617 +char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
  1.1618 +                             char *addr, size_t bytes, bool read_only,
  1.1619 +                             bool allow_exec) {
  1.1620 +  return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
  1.1621 +                    read_only, allow_exec);
  1.1622 +}
  1.1623 +
  1.1624 +bool os::unmap_memory(char *addr, size_t bytes) {
  1.1625 +  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
  1.1626 +  bool result = pd_unmap_memory(addr, bytes);
  1.1627 +  if (result) {
  1.1628 +    tkr.record((address)addr, bytes);
  1.1629 +  } else {
  1.1630 +    tkr.discard();
  1.1631 +  }
  1.1632 +  return result;
  1.1633 +}
  1.1634 +
  1.1635 +void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
  1.1636 +  pd_free_memory(addr, bytes, alignment_hint);
  1.1637 +}
  1.1638 +
  1.1639 +void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
  1.1640 +  pd_realign_memory(addr, bytes, alignment_hint);
  1.1641 +}
  1.1642 +
  1.1643 +#ifndef TARGET_OS_FAMILY_windows
  1.1644 +/* try to switch state from state "from" to state "to"
  1.1645 + * returns the state set after the method is complete
  1.1646 + */
  1.1647 +os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
  1.1648 +                                                         os::SuspendResume::State to)
  1.1649 +{
  1.1650 +  os::SuspendResume::State result =
  1.1651 +    (os::SuspendResume::State) Atomic::cmpxchg((jint) to, (jint *) &_state, (jint) from);
  1.1652 +  if (result == from) {
  1.1653 +    // success
  1.1654 +    return to;
  1.1655 +  }
  1.1656 +  return result;
  1.1657 +}
  1.1658 +#endif

mercurial