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