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