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