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