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