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