1 /*
   2  * Copyright (c) 1997, 2022, 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 "jvm.h"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/moduleEntry.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "gc/shared/gcVMOperations.hpp"
  36 #include "logging/log.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "memory/universe.hpp"
  43 #include "oops/compressedOops.inline.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "prims/jvm_misc.hpp"
  46 #include "runtime/arguments.hpp"
  47 #include "runtime/atomic.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/handles.inline.hpp"
  50 #include "runtime/interfaceSupport.inline.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/jniHandles.hpp"
  54 #include "runtime/mutexLocker.hpp"
  55 #include "runtime/os.inline.hpp"
  56 #include "runtime/osThread.hpp"
  57 #include "runtime/safefetch.hpp"
  58 #include "runtime/sharedRuntime.hpp"
  59 #include "runtime/thread.inline.hpp"
  60 #include "runtime/threadSMR.hpp"
  61 #include "runtime/vmOperations.hpp"
  62 #include "runtime/vm_version.hpp"
  63 #include "services/attachListener.hpp"
  64 #include "services/mallocTracker.hpp"
  65 #include "services/memTracker.hpp"
  66 #include "services/nmtPreInit.hpp"
  67 #include "services/nmtCommon.hpp"
  68 #include "services/threadService.hpp"
  69 #include "utilities/align.hpp"
  70 #include "utilities/count_trailing_zeros.hpp"
  71 #include "utilities/defaultStream.hpp"
  72 #include "utilities/events.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 #ifndef _WINDOWS
  76 # include <poll.h>
  77 #endif
  78 
  79 # include <signal.h>
  80 # include <errno.h>
  81 
  82 OSThread*         os::_starting_thread    = NULL;
  83 address           os::_polling_page       = NULL;
  84 volatile unsigned int os::_rand_seed      = 1234567;
  85 int               os::_processor_count    = 0;
  86 int               os::_initial_active_processor_count = 0;
  87 os::PageSizes     os::_page_sizes;
  88 
  89 static size_t cur_malloc_words = 0;  // current size for MallocMaxTestWords
  90 
  91 DEBUG_ONLY(bool os::_mutex_init_done = false;)
  92 
  93 int os::snprintf(char* buf, size_t len, const char* fmt, ...) {
  94   va_list args;
  95   va_start(args, fmt);
  96   int result = os::vsnprintf(buf, len, fmt, args);
  97   va_end(args);
  98   return result;
  99 }
 100 
 101 // Fill in buffer with current local time as an ISO-8601 string.
 102 // E.g., YYYY-MM-DDThh:mm:ss.mmm+zzzz.
 103 // Returns buffer, or NULL if it failed.
 104 char* os::iso8601_time(char* buffer, size_t buffer_length, bool utc) {
 105   const jlong now = javaTimeMillis();
 106   return os::iso8601_time(now, buffer, buffer_length, utc);
 107 }
 108 
 109 // Fill in buffer with an ISO-8601 string corresponding to the given javaTimeMillis value
 110 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
 111 // Returns buffer, or NULL if it failed.
 112 // This would mostly be a call to
 113 //     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
 114 // except that on Windows the %z behaves badly, so we do it ourselves.
 115 // Also, people wanted milliseconds on there,
 116 // and strftime doesn't do milliseconds.
 117 char* os::iso8601_time(jlong milliseconds_since_19700101, char* buffer, size_t buffer_length, bool utc) {
 118   // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
 119 
 120   // Sanity check the arguments
 121   if (buffer == NULL) {
 122     assert(false, "NULL buffer");
 123     return NULL;
 124   }
 125   if (buffer_length < os::iso8601_timestamp_size) {
 126     assert(false, "buffer_length too small");
 127     return NULL;
 128   }
 129   const int milliseconds_per_microsecond = 1000;
 130   const time_t seconds_since_19700101 =
 131     milliseconds_since_19700101 / milliseconds_per_microsecond;
 132   const int milliseconds_after_second =
 133     milliseconds_since_19700101 % milliseconds_per_microsecond;
 134   // Convert the time value to a tm and timezone variable
 135   struct tm time_struct;
 136   if (utc) {
 137     if (gmtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
 138       assert(false, "Failed gmtime_pd");
 139       return NULL;
 140     }
 141   } else {
 142     if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
 143       assert(false, "Failed localtime_pd");
 144       return NULL;
 145     }
 146   }
 147 
 148   const time_t seconds_per_minute = 60;
 149   const time_t minutes_per_hour = 60;
 150   const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
 151 
 152   // No offset when dealing with UTC
 153   time_t UTC_to_local = 0;
 154   if (!utc) {
 155 #if defined(_ALLBSD_SOURCE) || defined(_GNU_SOURCE)
 156     UTC_to_local = -(time_struct.tm_gmtoff);
 157 #elif defined(_WINDOWS)
 158     long zone;
 159     _get_timezone(&zone);
 160     UTC_to_local = static_cast<time_t>(zone);
 161 #else
 162     UTC_to_local = timezone;
 163 #endif
 164 
 165     // tm_gmtoff already includes adjustment for daylight saving
 166 #if !defined(_ALLBSD_SOURCE) && !defined(_GNU_SOURCE)
 167     // If daylight savings time is in effect,
 168     // we are 1 hour East of our time zone
 169     if (time_struct.tm_isdst > 0) {
 170       UTC_to_local = UTC_to_local - seconds_per_hour;
 171     }
 172 #endif
 173   }
 174 
 175   // Compute the time zone offset.
 176   //    localtime_pd() sets timezone to the difference (in seconds)
 177   //    between UTC and and local time.
 178   //    ISO 8601 says we need the difference between local time and UTC,
 179   //    we change the sign of the localtime_pd() result.
 180   const time_t local_to_UTC = -(UTC_to_local);
 181   // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
 182   char sign_local_to_UTC = '+';
 183   time_t abs_local_to_UTC = local_to_UTC;
 184   if (local_to_UTC < 0) {
 185     sign_local_to_UTC = '-';
 186     abs_local_to_UTC = -(abs_local_to_UTC);
 187   }
 188   // Convert time zone offset seconds to hours and minutes.
 189   const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
 190   const time_t zone_min =
 191     ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
 192 
 193   // Print an ISO 8601 date and time stamp into the buffer
 194   const int year = 1900 + time_struct.tm_year;
 195   const int month = 1 + time_struct.tm_mon;
 196   const int printed = jio_snprintf(buffer, buffer_length,
 197                                    "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d",
 198                                    year,
 199                                    month,
 200                                    time_struct.tm_mday,
 201                                    time_struct.tm_hour,
 202                                    time_struct.tm_min,
 203                                    time_struct.tm_sec,
 204                                    milliseconds_after_second,
 205                                    sign_local_to_UTC,
 206                                    zone_hours,
 207                                    zone_min);
 208   if (printed == 0) {
 209     assert(false, "Failed jio_printf");
 210     return NULL;
 211   }
 212   return buffer;
 213 }
 214 
 215 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
 216   debug_only(Thread::check_for_dangling_thread_pointer(thread);)
 217 
 218   if ((p >= MinPriority && p <= MaxPriority) ||
 219       (p == CriticalPriority && thread->is_ConcurrentGC_thread())) {
 220     int priority = java_to_os_priority[p];
 221     return set_native_priority(thread, priority);
 222   } else {
 223     assert(false, "Should not happen");
 224     return OS_ERR;
 225   }
 226 }
 227 
 228 // The mapping from OS priority back to Java priority may be inexact because
 229 // Java priorities can map M:1 with native priorities. If you want the definite
 230 // Java priority then use JavaThread::java_priority()
 231 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
 232   int p;
 233   int os_prio;
 234   OSReturn ret = get_native_priority(thread, &os_prio);
 235   if (ret != OS_OK) return ret;
 236 
 237   if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
 238     for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
 239   } else {
 240     // niceness values are in reverse order
 241     for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
 242   }
 243   priority = (ThreadPriority)p;
 244   return OS_OK;
 245 }
 246 
 247 bool os::dll_build_name(char* buffer, size_t size, const char* fname) {
 248   int n = jio_snprintf(buffer, size, "%s%s%s", JNI_LIB_PREFIX, fname, JNI_LIB_SUFFIX);
 249   return (n != -1);
 250 }
 251 
 252 #if !defined(LINUX) && !defined(_WINDOWS)
 253 bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) {
 254   committed_start = start;
 255   committed_size = size;
 256   return true;
 257 }
 258 #endif
 259 
 260 // Helper for dll_locate_lib.
 261 // Pass buffer and printbuffer as we already printed the path to buffer
 262 // when we called get_current_directory. This way we avoid another buffer
 263 // of size MAX_PATH.
 264 static bool conc_path_file_and_check(char *buffer, char *printbuffer, size_t printbuflen,
 265                                      const char* pname, char lastchar, const char* fname) {
 266 
 267   // Concatenate path and file name, but don't print double path separators.
 268   const char *filesep = (WINDOWS_ONLY(lastchar == ':' ||) lastchar == os::file_separator()[0]) ?
 269                         "" : os::file_separator();
 270   int ret = jio_snprintf(printbuffer, printbuflen, "%s%s%s", pname, filesep, fname);
 271   // Check whether file exists.
 272   if (ret != -1) {
 273     struct stat statbuf;
 274     return os::stat(buffer, &statbuf) == 0;
 275   }
 276   return false;
 277 }
 278 
 279 // Frees all memory allocated on the heap for the
 280 // supplied array of arrays of chars (a), where n
 281 // is the number of elements in the array.
 282 static void free_array_of_char_arrays(char** a, size_t n) {
 283       while (n > 0) {
 284           n--;
 285           if (a[n] != NULL) {
 286             FREE_C_HEAP_ARRAY(char, a[n]);
 287           }
 288       }
 289       FREE_C_HEAP_ARRAY(char*, a);
 290 }
 291 
 292 bool os::dll_locate_lib(char *buffer, size_t buflen,
 293                         const char* pname, const char* fname) {
 294   bool retval = false;
 295 
 296   size_t fullfnamelen = strlen(JNI_LIB_PREFIX) + strlen(fname) + strlen(JNI_LIB_SUFFIX);
 297   char* fullfname = NEW_C_HEAP_ARRAY(char, fullfnamelen + 1, mtInternal);
 298   if (dll_build_name(fullfname, fullfnamelen + 1, fname)) {
 299     const size_t pnamelen = pname ? strlen(pname) : 0;
 300 
 301     if (pnamelen == 0) {
 302       // If no path given, use current working directory.
 303       const char* p = get_current_directory(buffer, buflen);
 304       if (p != NULL) {
 305         const size_t plen = strlen(buffer);
 306         const char lastchar = buffer[plen - 1];
 307         retval = conc_path_file_and_check(buffer, &buffer[plen], buflen - plen,
 308                                           "", lastchar, fullfname);
 309       }
 310     } else if (strchr(pname, *os::path_separator()) != NULL) {
 311       // A list of paths. Search for the path that contains the library.
 312       size_t n;
 313       char** pelements = split_path(pname, &n, fullfnamelen);
 314       if (pelements != NULL) {
 315         for (size_t i = 0; i < n; i++) {
 316           char* path = pelements[i];
 317           // Really shouldn't be NULL, but check can't hurt.
 318           size_t plen = (path == NULL) ? 0 : strlen(path);
 319           if (plen == 0) {
 320             continue; // Skip the empty path values.
 321           }
 322           const char lastchar = path[plen - 1];
 323           retval = conc_path_file_and_check(buffer, buffer, buflen, path, lastchar, fullfname);
 324           if (retval) break;
 325         }
 326         // Release the storage allocated by split_path.
 327         free_array_of_char_arrays(pelements, n);
 328       }
 329     } else {
 330       // A definite path.
 331       const char lastchar = pname[pnamelen-1];
 332       retval = conc_path_file_and_check(buffer, buffer, buflen, pname, lastchar, fullfname);
 333     }
 334   }
 335 
 336   FREE_C_HEAP_ARRAY(char*, fullfname);
 337   return retval;
 338 }
 339 
 340 // --------------------- sun.misc.Signal (optional) ---------------------
 341 
 342 
 343 // SIGBREAK is sent by the keyboard to query the VM state
 344 #ifndef SIGBREAK
 345 #define SIGBREAK SIGQUIT
 346 #endif
 347 
 348 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
 349 
 350 
 351 static void signal_thread_entry(JavaThread* thread, TRAPS) {
 352   os::set_priority(thread, NearMaxPriority);
 353   while (true) {
 354     int sig;
 355     {
 356       // FIXME : Currently we have not decided what should be the status
 357       //         for this java thread blocked here. Once we decide about
 358       //         that we should fix this.
 359       sig = os::signal_wait();
 360     }
 361     if (sig == os::sigexitnum_pd()) {
 362        // Terminate the signal thread
 363        return;
 364     }
 365 
 366     switch (sig) {
 367       case SIGBREAK: {
 368 #if INCLUDE_SERVICES
 369         // Check if the signal is a trigger to start the Attach Listener - in that
 370         // case don't print stack traces.
 371         if (!DisableAttachMechanism) {
 372           // Attempt to transit state to AL_INITIALIZING.
 373           AttachListenerState cur_state = AttachListener::transit_state(AL_INITIALIZING, AL_NOT_INITIALIZED);
 374           if (cur_state == AL_INITIALIZING) {
 375             // Attach Listener has been started to initialize. Ignore this signal.
 376             continue;
 377           } else if (cur_state == AL_NOT_INITIALIZED) {
 378             // Start to initialize.
 379             if (AttachListener::is_init_trigger()) {
 380               // Attach Listener has been initialized.
 381               // Accept subsequent request.
 382               continue;
 383             } else {
 384               // Attach Listener could not be started.
 385               // So we need to transit the state to AL_NOT_INITIALIZED.
 386               AttachListener::set_state(AL_NOT_INITIALIZED);
 387             }
 388           } else if (AttachListener::check_socket_file()) {
 389             // Attach Listener has been started, but unix domain socket file
 390             // does not exist. So restart Attach Listener.
 391             continue;
 392           }
 393         }
 394 #endif
 395         // Print stack traces
 396         // Any SIGBREAK operations added here should make sure to flush
 397         // the output stream (e.g. tty->flush()) after output.  See 4803766.
 398         // Each module also prints an extra carriage return after its output.
 399         VM_PrintThreads op(tty, PrintConcurrentLocks, false /* no extended info */, true /* print JNI handle info */);
 400         VMThread::execute(&op);
 401         VM_FindDeadlocks op1(tty);
 402         VMThread::execute(&op1);
 403         Universe::print_heap_at_SIGBREAK();
 404         if (PrintClassHistogram) {
 405           VM_GC_HeapInspection op1(tty, true /* force full GC before heap inspection */);
 406           VMThread::execute(&op1);
 407         }
 408         if (JvmtiExport::should_post_data_dump()) {
 409           JvmtiExport::post_data_dump();
 410         }
 411         break;
 412       }
 413       default: {
 414         // Dispatch the signal to java
 415         HandleMark hm(THREAD);
 416         Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_misc_Signal(), THREAD);
 417         if (klass != NULL) {
 418           JavaValue result(T_VOID);
 419           JavaCallArguments args;
 420           args.push_int(sig);
 421           JavaCalls::call_static(
 422             &result,
 423             klass,
 424             vmSymbols::dispatch_name(),
 425             vmSymbols::int_void_signature(),
 426             &args,
 427             THREAD
 428           );
 429         }
 430         if (HAS_PENDING_EXCEPTION) {
 431           // tty is initialized early so we don't expect it to be null, but
 432           // if it is we can't risk doing an initialization that might
 433           // trigger additional out-of-memory conditions
 434           if (tty != NULL) {
 435             char klass_name[256];
 436             char tmp_sig_name[16];
 437             const char* sig_name = "UNKNOWN";
 438             InstanceKlass::cast(PENDING_EXCEPTION->klass())->
 439               name()->as_klass_external_name(klass_name, 256);
 440             if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
 441               sig_name = tmp_sig_name;
 442             warning("Exception %s occurred dispatching signal %s to handler"
 443                     "- the VM may need to be forcibly terminated",
 444                     klass_name, sig_name );
 445           }
 446           CLEAR_PENDING_EXCEPTION;
 447         }
 448       }
 449     }
 450   }
 451 }
 452 
 453 void os::init_before_ergo() {
 454   initialize_initial_active_processor_count();
 455   // We need to initialize large page support here because ergonomics takes some
 456   // decisions depending on large page support and the calculated large page size.
 457   large_page_init();
 458 
 459   StackOverflow::initialize_stack_zone_sizes();
 460 
 461   // VM version initialization identifies some characteristics of the
 462   // platform that are used during ergonomic decisions.
 463   VM_Version::init_before_ergo();
 464 }
 465 
 466 void os::initialize_jdk_signal_support(TRAPS) {
 467   if (!ReduceSignalUsage) {
 468     // Setup JavaThread for processing signals
 469     const char* name = "Signal Dispatcher";
 470     Handle thread_oop = JavaThread::create_system_thread_object(name, true /* visible */, CHECK);
 471 
 472     JavaThread* thread = new JavaThread(&signal_thread_entry);
 473     JavaThread::vm_exit_on_osthread_failure(thread);
 474 
 475     JavaThread::start_internal_daemon(THREAD, thread, thread_oop, NearMaxPriority);
 476 
 477     // Handle ^BREAK
 478     os::signal(SIGBREAK, os::user_handler());
 479   }
 480 }
 481 
 482 
 483 void os::terminate_signal_thread() {
 484   if (!ReduceSignalUsage)
 485     signal_notify(sigexitnum_pd());
 486 }
 487 
 488 
 489 // --------------------- loading libraries ---------------------
 490 
 491 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
 492 extern struct JavaVM_ main_vm;
 493 
 494 static void* _native_java_library = NULL;
 495 
 496 void* os::native_java_library() {
 497   if (_native_java_library == NULL) {
 498     char buffer[JVM_MAXPATHLEN];
 499     char ebuf[1024];
 500 
 501     // Load java dll
 502     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 503                        "java")) {
 504       _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
 505     }
 506     if (_native_java_library == NULL) {
 507       vm_exit_during_initialization("Unable to load native library", ebuf);
 508     }
 509 
 510 #if defined(__OpenBSD__)
 511     // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
 512     // ignore errors
 513     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 514                        "net")) {
 515       dll_load(buffer, ebuf, sizeof(ebuf));
 516     }
 517 #endif
 518   }
 519   return _native_java_library;
 520 }
 521 
 522 /*
 523  * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
 524  * If check_lib == true then we are looking for an
 525  * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
 526  * this library is statically linked into the image.
 527  * If check_lib == false then we will look for the appropriate symbol in the
 528  * executable if agent_lib->is_static_lib() == true or in the shared library
 529  * referenced by 'handle'.
 530  */
 531 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
 532                               const char *syms[], size_t syms_len) {
 533   assert(agent_lib != NULL, "sanity check");
 534   const char *lib_name;
 535   void *handle = agent_lib->os_lib();
 536   void *entryName = NULL;
 537   char *agent_function_name;
 538   size_t i;
 539 
 540   // If checking then use the agent name otherwise test is_static_lib() to
 541   // see how to process this lookup
 542   lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
 543   for (i = 0; i < syms_len; i++) {
 544     agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
 545     if (agent_function_name == NULL) {
 546       break;
 547     }
 548     entryName = dll_lookup(handle, agent_function_name);
 549     FREE_C_HEAP_ARRAY(char, agent_function_name);
 550     if (entryName != NULL) {
 551       break;
 552     }
 553   }
 554   return entryName;
 555 }
 556 
 557 // See if the passed in agent is statically linked into the VM image.
 558 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
 559                             size_t syms_len) {
 560   void *ret;
 561   void *proc_handle;
 562   void *save_handle;
 563 
 564   assert(agent_lib != NULL, "sanity check");
 565   if (agent_lib->name() == NULL) {
 566     return false;
 567   }
 568   proc_handle = get_default_process_handle();
 569   // Check for Agent_OnLoad/Attach_lib_name function
 570   save_handle = agent_lib->os_lib();
 571   // We want to look in this process' symbol table.
 572   agent_lib->set_os_lib(proc_handle);
 573   ret = find_agent_function(agent_lib, true, syms, syms_len);
 574   if (ret != NULL) {
 575     // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
 576     agent_lib->set_valid();
 577     agent_lib->set_static_lib(true);
 578     return true;
 579   }
 580   agent_lib->set_os_lib(save_handle);
 581   return false;
 582 }
 583 
 584 // --------------------- heap allocation utilities ---------------------
 585 
 586 char *os::strdup(const char *str, MEMFLAGS flags) {
 587   size_t size = strlen(str);
 588   char *dup_str = (char *)malloc(size + 1, flags);
 589   if (dup_str == NULL) return NULL;
 590   strcpy(dup_str, str);
 591   return dup_str;
 592 }
 593 
 594 char* os::strdup_check_oom(const char* str, MEMFLAGS flags) {
 595   char* p = os::strdup(str, flags);
 596   if (p == NULL) {
 597     vm_exit_out_of_memory(strlen(str) + 1, OOM_MALLOC_ERROR, "os::strdup_check_oom");
 598   }
 599   return p;
 600 }
 601 
 602 //
 603 // This function supports testing of the malloc out of memory
 604 // condition without really running the system out of memory.
 605 //
 606 
 607 static bool has_reached_max_malloc_test_peak(size_t alloc_size) {
 608   if (MallocMaxTestWords > 0) {
 609     size_t words = (alloc_size / BytesPerWord);
 610 
 611     if ((cur_malloc_words + words) > MallocMaxTestWords) {
 612       return true;
 613     }
 614     Atomic::add(&cur_malloc_words, words);
 615   }
 616   return false;
 617 }
 618 
 619 #ifdef ASSERT
 620 static void check_crash_protection() {
 621   assert(!os::ThreadCrashProtection::is_crash_protected(Thread::current_or_null()),
 622          "not allowed when crash protection is set");
 623 }
 624 static void break_if_ptr_caught(void* ptr) {
 625   if (p2i(ptr) == (intptr_t)MallocCatchPtr) {
 626     log_warning(malloc, free)("ptr caught: " PTR_FORMAT, p2i(ptr));
 627     breakpoint();
 628   }
 629 }
 630 #endif // ASSERT
 631 
 632 void* os::malloc(size_t size, MEMFLAGS flags) {
 633   return os::malloc(size, flags, CALLER_PC);
 634 }
 635 
 636 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 637 
 638   // Special handling for NMT preinit phase before arguments are parsed
 639   void* rc = NULL;
 640   if (NMTPreInit::handle_malloc(&rc, size)) {
 641     // No need to fill with 0 because DumpSharedSpaces doesn't use these
 642     // early allocations.
 643     return rc;
 644   }
 645 
 646   DEBUG_ONLY(check_crash_protection());
 647 
 648   // On malloc(0), implementations of malloc(3) have the choice to return either
 649   // NULL or a unique non-NULL pointer. To unify libc behavior across our platforms
 650   // we chose the latter.
 651   size = MAX2((size_t)1, size);
 652 
 653   // For the test flag -XX:MallocMaxTestWords
 654   if (has_reached_max_malloc_test_peak(size)) {
 655     return NULL;
 656   }
 657 
 658   const size_t outer_size = size + MemTracker::overhead_per_malloc();
 659 
 660   void* const outer_ptr = ::malloc(outer_size);
 661   if (outer_ptr == NULL) {
 662     return NULL;
 663   }
 664 
 665   void* const inner_ptr = MemTracker::record_malloc((address)outer_ptr, size, memflags, stack);
 666 
 667   if (DumpSharedSpaces) {
 668     // Need to deterministically fill all the alignment gaps in C++ structures.
 669     ::memset(inner_ptr, 0, size);
 670   } else {
 671     DEBUG_ONLY(::memset(inner_ptr, uninitBlockPad, size);)
 672   }
 673   DEBUG_ONLY(break_if_ptr_caught(inner_ptr);)
 674   return inner_ptr;
 675 }
 676 
 677 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
 678   return os::realloc(memblock, size, flags, CALLER_PC);
 679 }
 680 
 681 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 682 
 683   // Special handling for NMT preinit phase before arguments are parsed
 684   void* rc = NULL;
 685   if (NMTPreInit::handle_realloc(&rc, memblock, size)) {
 686     return rc;
 687   }
 688 
 689   if (memblock == NULL) {
 690     return os::malloc(size, memflags, stack);
 691   }
 692 
 693   DEBUG_ONLY(check_crash_protection());
 694 
 695   // On realloc(p, 0), implementers of realloc(3) have the choice to return either
 696   // NULL or a unique non-NULL pointer. To unify libc behavior across our platforms
 697   // we chose the latter.
 698   size = MAX2((size_t)1, size);
 699 
 700   // For the test flag -XX:MallocMaxTestWords
 701   if (has_reached_max_malloc_test_peak(size)) {
 702     return NULL;
 703   }
 704 
 705   const size_t new_outer_size = size + MemTracker::overhead_per_malloc();
 706 
 707   // If NMT is enabled, this checks for heap overwrites, then de-accounts the old block.
 708   void* const old_outer_ptr = MemTracker::record_free(memblock);
 709 
 710   void* const new_outer_ptr = ::realloc(old_outer_ptr, new_outer_size);
 711   if (new_outer_ptr == NULL) {
 712     return NULL;
 713   }
 714 
 715   void* const new_inner_ptr = MemTracker::record_malloc(new_outer_ptr, size, memflags, stack);
 716 
 717   DEBUG_ONLY(break_if_ptr_caught(new_inner_ptr);)
 718 
 719   return new_inner_ptr;
 720 }
 721 
 722 void  os::free(void *memblock) {
 723 
 724   // Special handling for NMT preinit phase before arguments are parsed
 725   if (NMTPreInit::handle_free(memblock)) {
 726     return;
 727   }
 728 
 729   if (memblock == NULL) {
 730     return;
 731   }
 732 
 733   DEBUG_ONLY(break_if_ptr_caught(memblock);)
 734 
 735   // If NMT is enabled, this checks for heap overwrites, then de-accounts the old block.
 736   void* const old_outer_ptr = MemTracker::record_free(memblock);
 737 
 738   ::free(old_outer_ptr);
 739 }
 740 
 741 void os::init_random(unsigned int initval) {
 742   _rand_seed = initval;
 743 }
 744 
 745 
 746 int os::next_random(unsigned int rand_seed) {
 747   /* standard, well-known linear congruential random generator with
 748    * next_rand = (16807*seed) mod (2**31-1)
 749    * see
 750    * (1) "Random Number Generators: Good Ones Are Hard to Find",
 751    *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
 752    * (2) "Two Fast Implementations of the 'Minimal Standard' Random
 753    *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
 754   */
 755   const unsigned int a = 16807;
 756   const unsigned int m = 2147483647;
 757   const int q = m / a;        assert(q == 127773, "weird math");
 758   const int r = m % a;        assert(r == 2836, "weird math");
 759 
 760   // compute az=2^31p+q
 761   unsigned int lo = a * (rand_seed & 0xFFFF);
 762   unsigned int hi = a * (rand_seed >> 16);
 763   lo += (hi & 0x7FFF) << 16;
 764 
 765   // if q overflowed, ignore the overflow and increment q
 766   if (lo > m) {
 767     lo &= m;
 768     ++lo;
 769   }
 770   lo += hi >> 15;
 771 
 772   // if (p+q) overflowed, ignore the overflow and increment (p+q)
 773   if (lo > m) {
 774     lo &= m;
 775     ++lo;
 776   }
 777   return lo;
 778 }
 779 
 780 int os::random() {
 781   // Make updating the random seed thread safe.
 782   while (true) {
 783     unsigned int seed = _rand_seed;
 784     unsigned int rand = next_random(seed);
 785     if (Atomic::cmpxchg(&_rand_seed, seed, rand, memory_order_relaxed) == seed) {
 786       return static_cast<int>(rand);
 787     }
 788   }
 789 }
 790 
 791 // The INITIALIZED state is distinguished from the SUSPENDED state because the
 792 // conditions in which a thread is first started are different from those in which
 793 // a suspension is resumed.  These differences make it hard for us to apply the
 794 // tougher checks when starting threads that we want to do when resuming them.
 795 // However, when start_thread is called as a result of Thread.start, on a Java
 796 // thread, the operation is synchronized on the Java Thread object.  So there
 797 // cannot be a race to start the thread and hence for the thread to exit while
 798 // we are working on it.  Non-Java threads that start Java threads either have
 799 // to do so in a context in which races are impossible, or should do appropriate
 800 // locking.
 801 
 802 void os::start_thread(Thread* thread) {
 803   OSThread* osthread = thread->osthread();
 804   osthread->set_state(RUNNABLE);
 805   pd_start_thread(thread);
 806 }
 807 
 808 void os::abort(bool dump_core) {
 809   abort(dump_core && CreateCoredumpOnCrash, NULL, NULL);
 810 }
 811 
 812 //---------------------------------------------------------------------------
 813 // Helper functions for fatal error handler
 814 
 815 bool os::print_function_and_library_name(outputStream* st,
 816                                          address addr,
 817                                          char* buf, int buflen,
 818                                          bool shorten_paths,
 819                                          bool demangle,
 820                                          bool strip_arguments) {
 821   // If no scratch buffer given, allocate one here on stack.
 822   // (used during error handling; its a coin toss, really, if on-stack allocation
 823   //  is worse than (raw) C-heap allocation in that case).
 824   char* p = buf;
 825   if (p == NULL) {
 826     p = (char*)::alloca(O_BUFLEN);
 827     buflen = O_BUFLEN;
 828   }
 829   int offset = 0;
 830   bool have_function_name = dll_address_to_function_name(addr, p, buflen,
 831                                                          &offset, demangle);
 832   bool is_function_descriptor = false;
 833 #ifdef HAVE_FUNCTION_DESCRIPTORS
 834   // When we deal with a function descriptor instead of a real code pointer, try to
 835   // resolve it. There is a small chance that a random pointer given to this function
 836   // may just happen to look like a valid descriptor, but this is rare and worth the
 837   // risk to see resolved function names. But we will print a little suffix to mark
 838   // this as a function descriptor for the reader (see below).
 839   if (!have_function_name && os::is_readable_pointer(addr)) {
 840     address addr2 = (address)os::resolve_function_descriptor(addr);
 841     if (have_function_name = is_function_descriptor =
 842         dll_address_to_function_name(addr2, p, buflen, &offset, demangle)) {
 843       addr = addr2;
 844     }
 845   }
 846 #endif // HAVE_FUNCTION_DESCRIPTORS
 847 
 848   if (have_function_name) {
 849     // Print function name, optionally demangled
 850     if (demangle && strip_arguments) {
 851       char* args_start = strchr(p, '(');
 852       if (args_start != NULL) {
 853         *args_start = '\0';
 854       }
 855     }
 856     // Print offset. Omit printing if offset is zero, which makes the output
 857     // more readable if we print function pointers.
 858     if (offset == 0) {
 859       st->print("%s", p);
 860     } else {
 861       st->print("%s+%d", p, offset);
 862     }
 863   } else {
 864     st->print(PTR_FORMAT, p2i(addr));
 865   }
 866   offset = 0;
 867 
 868   const bool have_library_name = dll_address_to_library_name(addr, p, buflen, &offset);
 869   if (have_library_name) {
 870     // Cut path parts
 871     if (shorten_paths) {
 872       char* p2 = strrchr(p, os::file_separator()[0]);
 873       if (p2 != NULL) {
 874         p = p2 + 1;
 875       }
 876     }
 877     st->print(" in %s", p);
 878     if (!have_function_name) { // Omit offset if we already printed the function offset
 879       st->print("+%d", offset);
 880     }
 881   }
 882 
 883   // Write a trailing marker if this was a function descriptor
 884   if (have_function_name && is_function_descriptor) {
 885     st->print_raw(" (FD)");
 886   }
 887 
 888   return have_function_name || have_library_name;
 889 }
 890 
 891 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize,
 892                         int bytes_per_line, address logical_start) {
 893   assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
 894 
 895   start = align_down(start, unitsize);
 896   logical_start = align_down(logical_start, unitsize);
 897   bytes_per_line = align_up(bytes_per_line, 8);
 898 
 899   int cols = 0;
 900   int cols_per_line = bytes_per_line / unitsize;
 901 
 902   address p = start;
 903   address logical_p = logical_start;
 904 
 905   // Print out the addresses as if we were starting from logical_start.
 906   st->print(PTR_FORMAT ":   ", p2i(logical_p));
 907   while (p < end) {
 908     if (is_readable_pointer(p)) {
 909       switch (unitsize) {
 910         case 1: st->print("%02x", *(u1*)p); break;
 911         case 2: st->print("%04x", *(u2*)p); break;
 912         case 4: st->print("%08x", *(u4*)p); break;
 913         case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
 914       }
 915     } else {
 916       st->print("%*.*s", 2*unitsize, 2*unitsize, "????????????????");
 917     }
 918     p += unitsize;
 919     logical_p += unitsize;
 920     cols++;
 921     if (cols >= cols_per_line && p < end) {
 922        cols = 0;
 923        st->cr();
 924        st->print(PTR_FORMAT ":   ", p2i(logical_p));
 925     } else {
 926        st->print(" ");
 927     }
 928   }
 929   st->cr();
 930 }
 931 
 932 void os::print_dhm(outputStream* st, const char* startStr, long sec) {
 933   long days    = sec/86400;
 934   long hours   = (sec/3600) - (days * 24);
 935   long minutes = (sec/60) - (days * 1440) - (hours * 60);
 936   if (startStr == NULL) startStr = "";
 937   st->print_cr("%s %ld days %ld:%02ld hours", startStr, days, hours, minutes);
 938 }
 939 
 940 void os::print_instructions(outputStream* st, address pc, int unitsize) {
 941   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc));
 942   print_hex_dump(st, pc - 256, pc + 256, unitsize);
 943 }
 944 
 945 void os::print_environment_variables(outputStream* st, const char** env_list) {
 946   if (env_list) {
 947     st->print_cr("Environment Variables:");
 948 
 949     for (int i = 0; env_list[i] != NULL; i++) {
 950       char *envvar = ::getenv(env_list[i]);
 951       if (envvar != NULL) {
 952         st->print("%s", env_list[i]);
 953         st->print("=");
 954         st->print("%s", envvar);
 955         // Use separate cr() printing to avoid unnecessary buffer operations that might cause truncation.
 956         st->cr();
 957       }
 958     }
 959   }
 960 }
 961 
 962 void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) {
 963   // cpu
 964   st->print("CPU:");
 965 #if defined(__APPLE__) && !defined(ZERO)
 966    if (VM_Version::is_cpu_emulated()) {
 967      st->print(" (EMULATED)");
 968    }
 969 #endif
 970   st->print(" total %d", os::processor_count());
 971   // It's not safe to query number of active processors after crash
 972   // st->print("(active %d)", os::active_processor_count()); but we can
 973   // print the initial number of active processors.
 974   // We access the raw value here because the assert in the accessor will
 975   // fail if the crash occurs before initialization of this value.
 976   st->print(" (initial active %d)", _initial_active_processor_count);
 977   st->print(" %s", VM_Version::features_string());
 978   st->cr();
 979   pd_print_cpu_info(st, buf, buflen);
 980 }
 981 
 982 // Print a one line string summarizing the cpu, number of cores, memory, and operating system version
 983 void os::print_summary_info(outputStream* st, char* buf, size_t buflen) {
 984   st->print("Host: ");
 985 #ifndef PRODUCT
 986   if (get_host_name(buf, buflen)) {
 987     st->print("%s, ", buf);
 988   }
 989 #endif // PRODUCT
 990   get_summary_cpu_info(buf, buflen);
 991   st->print("%s, ", buf);
 992   size_t mem = physical_memory()/G;
 993   if (mem == 0) {  // for low memory systems
 994     mem = physical_memory()/M;
 995     st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem);
 996   } else {
 997     st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem);
 998   }
 999   get_summary_os_info(buf, buflen);
1000   st->print_raw(buf);
1001   st->cr();
1002 }
1003 
1004 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
1005   const int secs_per_day  = 86400;
1006   const int secs_per_hour = 3600;
1007   const int secs_per_min  = 60;
1008 
1009   time_t tloc;
1010   (void)time(&tloc);
1011   char* timestring = ctime(&tloc);  // ctime adds newline.
1012   // edit out the newline
1013   char* nl = strchr(timestring, '\n');
1014   if (nl != NULL) {
1015     *nl = '\0';
1016   }
1017 
1018   struct tm tz;
1019   if (localtime_pd(&tloc, &tz) != NULL) {
1020     wchar_t w_buf[80];
1021     size_t n = ::wcsftime(w_buf, 80, L"%Z", &tz);
1022     if (n > 0) {
1023       ::wcstombs(buf, w_buf, buflen);
1024       st->print("Time: %s %s", timestring, buf);
1025     } else {
1026       st->print("Time: %s", timestring);
1027     }
1028   } else {
1029     st->print("Time: %s", timestring);
1030   }
1031 
1032   double t = os::elapsedTime();
1033   // NOTE: a crash using printf("%f",...) on Linux was historically noted here.
1034   int eltime = (int)t;  // elapsed time in seconds
1035   int eltimeFraction = (int) ((t - eltime) * 1000000);
1036 
1037   // print elapsed time in a human-readable format:
1038   int eldays = eltime / secs_per_day;
1039   int day_secs = eldays * secs_per_day;
1040   int elhours = (eltime - day_secs) / secs_per_hour;
1041   int hour_secs = elhours * secs_per_hour;
1042   int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
1043   int minute_secs = elmins * secs_per_min;
1044   int elsecs = (eltime - day_secs - hour_secs - minute_secs);
1045   st->print_cr(" elapsed time: %d.%06d seconds (%dd %dh %dm %ds)", eltime, eltimeFraction, eldays, elhours, elmins, elsecs);
1046 }
1047 
1048 
1049 // Check if pointer can be read from (4-byte read access).
1050 // Helps to prove validity of a not-NULL pointer.
1051 // Returns true in very early stages of VM life when stub is not yet generated.
1052 bool os::is_readable_pointer(const void* p) {
1053   int* const aligned = (int*) align_down((intptr_t)p, 4);
1054   int cafebabe = 0xcafebabe;  // tester value 1
1055   int deadbeef = 0xdeadbeef;  // tester value 2
1056   return (SafeFetch32(aligned, cafebabe) != cafebabe) || (SafeFetch32(aligned, deadbeef) != deadbeef);
1057 }
1058 
1059 bool os::is_readable_range(const void* from, const void* to) {
1060   if ((uintptr_t)from >= (uintptr_t)to) return false;
1061   for (uintptr_t p = align_down((uintptr_t)from, min_page_size()); p < (uintptr_t)to; p += min_page_size()) {
1062     if (!is_readable_pointer((const void*)p)) {
1063       return false;
1064     }
1065   }
1066   return true;
1067 }
1068 
1069 
1070 // moved from debug.cpp (used to be find()) but still called from there
1071 // The verbose parameter is only set by the debug code in one case
1072 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
1073   address addr = (address)x;
1074   // Handle NULL first, so later checks don't need to protect against it.
1075   if (addr == NULL) {
1076     st->print_cr("0x0 is NULL");
1077     return;
1078   }
1079 
1080   // Check if addr points into a code blob.
1081   CodeBlob* b = CodeCache::find_blob_unsafe(addr);
1082   if (b != NULL) {
1083     b->dump_for_addr(addr, st, verbose);
1084     return;
1085   }
1086 
1087   // Check if addr points into Java heap.
1088   if (Universe::heap()->print_location(st, addr)) {
1089     return;
1090   }
1091 
1092   bool accessible = is_readable_pointer(addr);
1093 
1094   // Check if addr is a JNI handle.
1095   if (align_down((intptr_t)addr, sizeof(intptr_t)) != 0 && accessible) {
1096     if (JNIHandles::is_global_handle((jobject) addr)) {
1097       st->print_cr(INTPTR_FORMAT " is a global jni handle", p2i(addr));
1098       return;
1099     }
1100     if (JNIHandles::is_weak_global_handle((jobject) addr)) {
1101       st->print_cr(INTPTR_FORMAT " is a weak global jni handle", p2i(addr));
1102       return;
1103     }
1104   }
1105 
1106   // Check if addr belongs to a Java thread.
1107   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
1108     // If the addr is a java thread print information about that.
1109     if (addr == (address)thread) {
1110       if (verbose) {
1111         thread->print_on(st);
1112       } else {
1113         st->print_cr(INTPTR_FORMAT " is a thread", p2i(addr));
1114       }
1115       return;
1116     }
1117     // If the addr is in the stack region for this thread then report that
1118     // and print thread info
1119     if (thread->is_in_full_stack(addr)) {
1120       st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1121                    INTPTR_FORMAT, p2i(addr), p2i(thread));
1122       if (verbose) thread->print_on(st);
1123       return;
1124     }
1125   }
1126 
1127   // Check if in metaspace and print types that have vptrs
1128   if (Metaspace::contains(addr)) {
1129     if (Klass::is_valid((Klass*)addr)) {
1130       st->print_cr(INTPTR_FORMAT " is a pointer to class: ", p2i(addr));
1131       ((Klass*)addr)->print_on(st);
1132     } else if (Method::is_valid_method((const Method*)addr)) {
1133       ((Method*)addr)->print_value_on(st);
1134       st->cr();
1135     } else {
1136       // Use addr->print() from the debugger instead (not here)
1137       st->print_cr(INTPTR_FORMAT " is pointing into metadata", p2i(addr));
1138     }
1139     return;
1140   }
1141 
1142   // Compressed klass needs to be decoded first.
1143 #ifdef _LP64
1144   if (UseCompressedClassPointers && ((uintptr_t)addr &~ (uintptr_t)max_juint) == 0) {
1145     narrowKlass narrow_klass = (narrowKlass)(uintptr_t)addr;
1146     Klass* k = CompressedKlassPointers::decode_raw(narrow_klass);
1147 
1148     if (Klass::is_valid(k)) {
1149       st->print_cr(UINT32_FORMAT " is a compressed pointer to class: " INTPTR_FORMAT, narrow_klass, p2i((HeapWord*)k));
1150       k->print_on(st);
1151       return;
1152     }
1153   }
1154 #endif
1155 
1156   // Try an OS specific find
1157   if (os::find(addr, st)) {
1158     return;
1159   }
1160 
1161   if (accessible) {
1162     st->print(INTPTR_FORMAT " points into unknown readable memory:", p2i(addr));
1163     if (is_aligned(addr, sizeof(intptr_t))) {
1164       st->print(" " PTR_FORMAT " |", *(intptr_t*)addr);
1165     }
1166     for (address p = addr; p < align_up(addr + 1, sizeof(intptr_t)); ++p) {
1167       st->print(" %02x", *(u1*)p);
1168     }
1169     st->cr();
1170     return;
1171   }
1172 
1173   st->print_cr(INTPTR_FORMAT " is an unknown value", p2i(addr));
1174 }
1175 
1176 bool is_pointer_bad(intptr_t* ptr) {
1177   return !is_aligned(ptr, sizeof(uintptr_t)) || !os::is_readable_pointer(ptr);
1178 }
1179 
1180 // Looks like all platforms can use the same function to check if C
1181 // stack is walkable beyond current frame.
1182 // Returns true if this is not the case, i.e. the frame is possibly
1183 // the first C frame on the stack.
1184 bool os::is_first_C_frame(frame* fr) {
1185 
1186 #ifdef _WINDOWS
1187   return true; // native stack isn't walkable on windows this way.
1188 #endif
1189   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1190   // Check usp first, because if that's bad the other accessors may fault
1191   // on some architectures.  Ditto ufp second, etc.
1192 
1193   if (is_pointer_bad(fr->sp())) return true;
1194 
1195   uintptr_t ufp    = (uintptr_t)fr->fp();
1196   if (is_pointer_bad(fr->fp())) return true;
1197 
1198   uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1199   if ((uintptr_t)fr->sender_sp() == (uintptr_t)-1 || is_pointer_bad(fr->sender_sp())) return true;
1200 
1201   uintptr_t old_fp = (uintptr_t)fr->link_or_null();
1202   if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp ||
1203     is_pointer_bad(fr->link_or_null())) return true;
1204 
1205   // stack grows downwards; if old_fp is below current fp or if the stack
1206   // frame is too large, either the stack is corrupted or fp is not saved
1207   // on stack (i.e. on x86, ebp may be used as general register). The stack
1208   // is not walkable beyond current frame.
1209   if (old_fp < ufp) return true;
1210   if (old_fp - ufp > 64 * K) return true;
1211 
1212   return false;
1213 }
1214 
1215 // Set up the boot classpath.
1216 
1217 char* os::format_boot_path(const char* format_string,
1218                            const char* home,
1219                            int home_len,
1220                            char fileSep,
1221                            char pathSep) {
1222     assert((fileSep == '/' && pathSep == ':') ||
1223            (fileSep == '\\' && pathSep == ';'), "unexpected separator chars");
1224 
1225     // Scan the format string to determine the length of the actual
1226     // boot classpath, and handle platform dependencies as well.
1227     int formatted_path_len = 0;
1228     const char* p;
1229     for (p = format_string; *p != 0; ++p) {
1230         if (*p == '%') formatted_path_len += home_len - 1;
1231         ++formatted_path_len;
1232     }
1233 
1234     char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1235 
1236     // Create boot classpath from format, substituting separator chars and
1237     // java home directory.
1238     char* q = formatted_path;
1239     for (p = format_string; *p != 0; ++p) {
1240         switch (*p) {
1241         case '%':
1242             strcpy(q, home);
1243             q += home_len;
1244             break;
1245         case '/':
1246             *q++ = fileSep;
1247             break;
1248         case ':':
1249             *q++ = pathSep;
1250             break;
1251         default:
1252             *q++ = *p;
1253         }
1254     }
1255     *q = '\0';
1256 
1257     assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1258     return formatted_path;
1259 }
1260 
1261 // This function is a proxy to fopen, it tries to add a non standard flag ('e' or 'N')
1262 // that ensures automatic closing of the file on exec. If it can not find support in
1263 // the underlying c library, it will make an extra system call (fcntl) to ensure automatic
1264 // closing of the file on exec.
1265 FILE* os::fopen(const char* path, const char* mode) {
1266   char modified_mode[20];
1267   assert(strlen(mode) + 1 < sizeof(modified_mode), "mode chars plus one extra must fit in buffer");
1268   sprintf(modified_mode, "%s" LINUX_ONLY("e") BSD_ONLY("e") WINDOWS_ONLY("N"), mode);
1269   FILE* file = ::fopen(path, modified_mode);
1270 
1271 #if !(defined LINUX || defined BSD || defined _WINDOWS)
1272   // assume fcntl FD_CLOEXEC support as a backup solution when 'e' or 'N'
1273   // is not supported as mode in fopen
1274   if (file != NULL) {
1275     int fd = fileno(file);
1276     if (fd != -1) {
1277       int fd_flags = fcntl(fd, F_GETFD);
1278       if (fd_flags != -1) {
1279         fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC);
1280       }
1281     }
1282   }
1283 #endif
1284 
1285   return file;
1286 }
1287 
1288 bool os::set_boot_path(char fileSep, char pathSep) {
1289   const char* home = Arguments::get_java_home();
1290   int home_len = (int)strlen(home);
1291 
1292   struct stat st;
1293 
1294   // modular image if "modules" jimage exists
1295   char* jimage = format_boot_path("%/lib/" MODULES_IMAGE_NAME, home, home_len, fileSep, pathSep);
1296   if (jimage == NULL) return false;
1297   bool has_jimage = (os::stat(jimage, &st) == 0);
1298   if (has_jimage) {
1299     Arguments::set_sysclasspath(jimage, true);
1300     FREE_C_HEAP_ARRAY(char, jimage);
1301     return true;
1302   }
1303   FREE_C_HEAP_ARRAY(char, jimage);
1304 
1305   // check if developer build with exploded modules
1306   char* base_classes = format_boot_path("%/modules/" JAVA_BASE_NAME, home, home_len, fileSep, pathSep);
1307   if (base_classes == NULL) return false;
1308   if (os::stat(base_classes, &st) == 0) {
1309     Arguments::set_sysclasspath(base_classes, false);
1310     FREE_C_HEAP_ARRAY(char, base_classes);
1311     return true;
1312   }
1313   FREE_C_HEAP_ARRAY(char, base_classes);
1314 
1315   return false;
1316 }
1317 
1318 bool os::file_exists(const char* filename) {
1319   struct stat statbuf;
1320   if (filename == NULL || strlen(filename) == 0) {
1321     return false;
1322   }
1323   return os::stat(filename, &statbuf) == 0;
1324 }
1325 
1326 // Splits a path, based on its separator, the number of
1327 // elements is returned back in "elements".
1328 // file_name_length is used as a modifier for each path's
1329 // length when compared to JVM_MAXPATHLEN. So if you know
1330 // each returned path will have something appended when
1331 // in use, you can pass the length of that in
1332 // file_name_length, to ensure we detect if any path
1333 // exceeds the maximum path length once prepended onto
1334 // the sub-path/file name.
1335 // It is the callers responsibility to:
1336 //   a> check the value of "elements", which may be 0.
1337 //   b> ignore any empty path elements
1338 //   c> free up the data.
1339 char** os::split_path(const char* path, size_t* elements, size_t file_name_length) {
1340   *elements = (size_t)0;
1341   if (path == NULL || strlen(path) == 0 || file_name_length == (size_t)NULL) {
1342     return NULL;
1343   }
1344   const char psepchar = *os::path_separator();
1345   char* inpath = NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1346   strcpy(inpath, path);
1347   size_t count = 1;
1348   char* p = strchr(inpath, psepchar);
1349   // Get a count of elements to allocate memory
1350   while (p != NULL) {
1351     count++;
1352     p++;
1353     p = strchr(p, psepchar);
1354   }
1355 
1356   char** opath = NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1357 
1358   // do the actual splitting
1359   p = inpath;
1360   for (size_t i = 0 ; i < count ; i++) {
1361     size_t len = strcspn(p, os::path_separator());
1362     if (len + file_name_length > JVM_MAXPATHLEN) {
1363       // release allocated storage before exiting the vm
1364       free_array_of_char_arrays(opath, i++);
1365       vm_exit_during_initialization("The VM tried to use a path that exceeds the maximum path length for "
1366                                     "this system. Review path-containing parameters and properties, such as "
1367                                     "sun.boot.library.path, to identify potential sources for this path.");
1368     }
1369     // allocate the string and add terminator storage
1370     char* s = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1371     strncpy(s, p, len);
1372     s[len] = '\0';
1373     opath[i] = s;
1374     p += len + 1;
1375   }
1376   FREE_C_HEAP_ARRAY(char, inpath);
1377   *elements = count;
1378   return opath;
1379 }
1380 
1381 // Returns true if the current stack pointer is above the stack shadow
1382 // pages, false otherwise.
1383 bool os::stack_shadow_pages_available(Thread *thread, const methodHandle& method, address sp) {
1384   if (!thread->is_Java_thread()) return false;
1385   // Check if we have StackShadowPages above the guard zone. This parameter
1386   // is dependent on the depth of the maximum VM call stack possible from
1387   // the handler for stack overflow.  'instanceof' in the stack overflow
1388   // handler or a println uses at least 8k stack of VM and native code
1389   // respectively.
1390   const int framesize_in_bytes =
1391     Interpreter::size_top_interpreter_activation(method()) * wordSize;
1392 
1393   address limit = JavaThread::cast(thread)->stack_overflow_state()->shadow_zone_safe_limit();
1394   return sp > (limit + framesize_in_bytes);
1395 }
1396 
1397 size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) {
1398   assert(min_pages > 0, "sanity");
1399   if (UseLargePages) {
1400     const size_t max_page_size = region_size / min_pages;
1401 
1402     for (size_t page_size = page_sizes().largest(); page_size != 0;
1403          page_size = page_sizes().next_smaller(page_size)) {
1404       if (page_size <= max_page_size) {
1405         if (!must_be_aligned || is_aligned(region_size, page_size)) {
1406           return page_size;
1407         }
1408       }
1409     }
1410   }
1411 
1412   return vm_page_size();
1413 }
1414 
1415 size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) {
1416   return page_size_for_region(region_size, min_pages, true);
1417 }
1418 
1419 size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) {
1420   return page_size_for_region(region_size, min_pages, false);
1421 }
1422 
1423 #ifndef MAX_PATH
1424 #define MAX_PATH    (2 * K)
1425 #endif
1426 
1427 void os::pause() {
1428   char filename[MAX_PATH];
1429   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
1430     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
1431   } else {
1432     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
1433   }
1434 
1435   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
1436   if (fd != -1) {
1437     struct stat buf;
1438     ::close(fd);
1439     while (::stat(filename, &buf) == 0) {
1440 #if defined(_WINDOWS)
1441       Sleep(100);
1442 #else
1443       (void)::poll(NULL, 0, 100);
1444 #endif
1445     }
1446   } else {
1447     jio_fprintf(stderr,
1448                 "Could not open pause file '%s', continuing immediately.\n", filename);
1449   }
1450 }
1451 
1452 static const char* errno_to_string (int e, bool short_text) {
1453   #define ALL_SHARED_ENUMS(X) \
1454     X(E2BIG, "Argument list too long") \
1455     X(EACCES, "Permission denied") \
1456     X(EADDRINUSE, "Address in use") \
1457     X(EADDRNOTAVAIL, "Address not available") \
1458     X(EAFNOSUPPORT, "Address family not supported") \
1459     X(EAGAIN, "Resource unavailable, try again") \
1460     X(EALREADY, "Connection already in progress") \
1461     X(EBADF, "Bad file descriptor") \
1462     X(EBADMSG, "Bad message") \
1463     X(EBUSY, "Device or resource busy") \
1464     X(ECANCELED, "Operation canceled") \
1465     X(ECHILD, "No child processes") \
1466     X(ECONNABORTED, "Connection aborted") \
1467     X(ECONNREFUSED, "Connection refused") \
1468     X(ECONNRESET, "Connection reset") \
1469     X(EDEADLK, "Resource deadlock would occur") \
1470     X(EDESTADDRREQ, "Destination address required") \
1471     X(EDOM, "Mathematics argument out of domain of function") \
1472     X(EEXIST, "File exists") \
1473     X(EFAULT, "Bad address") \
1474     X(EFBIG, "File too large") \
1475     X(EHOSTUNREACH, "Host is unreachable") \
1476     X(EIDRM, "Identifier removed") \
1477     X(EILSEQ, "Illegal byte sequence") \
1478     X(EINPROGRESS, "Operation in progress") \
1479     X(EINTR, "Interrupted function") \
1480     X(EINVAL, "Invalid argument") \
1481     X(EIO, "I/O error") \
1482     X(EISCONN, "Socket is connected") \
1483     X(EISDIR, "Is a directory") \
1484     X(ELOOP, "Too many levels of symbolic links") \
1485     X(EMFILE, "Too many open files") \
1486     X(EMLINK, "Too many links") \
1487     X(EMSGSIZE, "Message too large") \
1488     X(ENAMETOOLONG, "Filename too long") \
1489     X(ENETDOWN, "Network is down") \
1490     X(ENETRESET, "Connection aborted by network") \
1491     X(ENETUNREACH, "Network unreachable") \
1492     X(ENFILE, "Too many files open in system") \
1493     X(ENOBUFS, "No buffer space available") \
1494     X(ENODATA, "No message is available on the STREAM head read queue") \
1495     X(ENODEV, "No such device") \
1496     X(ENOENT, "No such file or directory") \
1497     X(ENOEXEC, "Executable file format error") \
1498     X(ENOLCK, "No locks available") \
1499     X(ENOLINK, "Reserved") \
1500     X(ENOMEM, "Not enough space") \
1501     X(ENOMSG, "No message of the desired type") \
1502     X(ENOPROTOOPT, "Protocol not available") \
1503     X(ENOSPC, "No space left on device") \
1504     X(ENOSR, "No STREAM resources") \
1505     X(ENOSTR, "Not a STREAM") \
1506     X(ENOSYS, "Function not supported") \
1507     X(ENOTCONN, "The socket is not connected") \
1508     X(ENOTDIR, "Not a directory") \
1509     X(ENOTEMPTY, "Directory not empty") \
1510     X(ENOTSOCK, "Not a socket") \
1511     X(ENOTSUP, "Not supported") \
1512     X(ENOTTY, "Inappropriate I/O control operation") \
1513     X(ENXIO, "No such device or address") \
1514     X(EOPNOTSUPP, "Operation not supported on socket") \
1515     X(EOVERFLOW, "Value too large to be stored in data type") \
1516     X(EPERM, "Operation not permitted") \
1517     X(EPIPE, "Broken pipe") \
1518     X(EPROTO, "Protocol error") \
1519     X(EPROTONOSUPPORT, "Protocol not supported") \
1520     X(EPROTOTYPE, "Protocol wrong type for socket") \
1521     X(ERANGE, "Result too large") \
1522     X(EROFS, "Read-only file system") \
1523     X(ESPIPE, "Invalid seek") \
1524     X(ESRCH, "No such process") \
1525     X(ETIME, "Stream ioctl() timeout") \
1526     X(ETIMEDOUT, "Connection timed out") \
1527     X(ETXTBSY, "Text file busy") \
1528     X(EWOULDBLOCK, "Operation would block") \
1529     X(EXDEV, "Cross-device link")
1530 
1531   #define DEFINE_ENTRY(e, text) { e, #e, text },
1532 
1533   static const struct {
1534     int v;
1535     const char* short_text;
1536     const char* long_text;
1537   } table [] = {
1538 
1539     ALL_SHARED_ENUMS(DEFINE_ENTRY)
1540 
1541     // The following enums are not defined on all platforms.
1542     #ifdef ESTALE
1543     DEFINE_ENTRY(ESTALE, "Reserved")
1544     #endif
1545     #ifdef EDQUOT
1546     DEFINE_ENTRY(EDQUOT, "Reserved")
1547     #endif
1548     #ifdef EMULTIHOP
1549     DEFINE_ENTRY(EMULTIHOP, "Reserved")
1550     #endif
1551 
1552     // End marker.
1553     { -1, "Unknown errno", "Unknown error" }
1554 
1555   };
1556 
1557   #undef DEFINE_ENTRY
1558   #undef ALL_FLAGS
1559 
1560   int i = 0;
1561   while (table[i].v != -1 && table[i].v != e) {
1562     i ++;
1563   }
1564 
1565   return short_text ? table[i].short_text : table[i].long_text;
1566 
1567 }
1568 
1569 const char* os::strerror(int e) {
1570   return errno_to_string(e, false);
1571 }
1572 
1573 const char* os::errno_name(int e) {
1574   return errno_to_string(e, true);
1575 }
1576 
1577 #define trace_page_size_params(size) byte_size_in_exact_unit(size), exact_unit_for_byte_size(size)
1578 
1579 void os::trace_page_sizes(const char* str,
1580                           const size_t region_min_size,
1581                           const size_t region_max_size,
1582                           const size_t page_size,
1583                           const char* base,
1584                           const size_t size) {
1585 
1586   log_info(pagesize)("%s: "
1587                      " min=" SIZE_FORMAT "%s"
1588                      " max=" SIZE_FORMAT "%s"
1589                      " base=" PTR_FORMAT
1590                      " page_size=" SIZE_FORMAT "%s"
1591                      " size=" SIZE_FORMAT "%s",
1592                      str,
1593                      trace_page_size_params(region_min_size),
1594                      trace_page_size_params(region_max_size),
1595                      p2i(base),
1596                      trace_page_size_params(page_size),
1597                      trace_page_size_params(size));
1598 }
1599 
1600 void os::trace_page_sizes_for_requested_size(const char* str,
1601                                              const size_t requested_size,
1602                                              const size_t page_size,
1603                                              const size_t alignment,
1604                                              const char* base,
1605                                              const size_t size) {
1606 
1607   log_info(pagesize)("%s:"
1608                      " req_size=" SIZE_FORMAT "%s"
1609                      " base=" PTR_FORMAT
1610                      " page_size=" SIZE_FORMAT "%s"
1611                      " alignment=" SIZE_FORMAT "%s"
1612                      " size=" SIZE_FORMAT "%s",
1613                      str,
1614                      trace_page_size_params(requested_size),
1615                      p2i(base),
1616                      trace_page_size_params(page_size),
1617                      trace_page_size_params(alignment),
1618                      trace_page_size_params(size));
1619 }
1620 
1621 
1622 // This is the working definition of a server class machine:
1623 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1624 // because the graphics memory (?) sometimes masks physical memory.
1625 // If you want to change the definition of a server class machine
1626 // on some OS or platform, e.g., >=4GB on Windows platforms,
1627 // then you'll have to parameterize this method based on that state,
1628 // as was done for logical processors here, or replicate and
1629 // specialize this method for each platform.  (Or fix os to have
1630 // some inheritance structure and use subclassing.  Sigh.)
1631 // If you want some platform to always or never behave as a server
1632 // class machine, change the setting of AlwaysActAsServerClassMachine
1633 // and NeverActAsServerClassMachine in globals*.hpp.
1634 bool os::is_server_class_machine() {
1635   // First check for the early returns
1636   if (NeverActAsServerClassMachine) {
1637     return false;
1638   }
1639   if (AlwaysActAsServerClassMachine) {
1640     return true;
1641   }
1642   // Then actually look at the machine
1643   bool         result            = false;
1644   const unsigned int    server_processors = 2;
1645   const julong server_memory     = 2UL * G;
1646   // We seem not to get our full complement of memory.
1647   //     We allow some part (1/8?) of the memory to be "missing",
1648   //     based on the sizes of DIMMs, and maybe graphics cards.
1649   const julong missing_memory   = 256UL * M;
1650 
1651   /* Is this a server class machine? */
1652   if ((os::active_processor_count() >= (int)server_processors) &&
1653       (os::physical_memory() >= (server_memory - missing_memory))) {
1654     const unsigned int logical_processors =
1655       VM_Version::logical_processors_per_package();
1656     if (logical_processors > 1) {
1657       const unsigned int physical_packages =
1658         os::active_processor_count() / logical_processors;
1659       if (physical_packages >= server_processors) {
1660         result = true;
1661       }
1662     } else {
1663       result = true;
1664     }
1665   }
1666   return result;
1667 }
1668 
1669 void os::initialize_initial_active_processor_count() {
1670   assert(_initial_active_processor_count == 0, "Initial active processor count already set.");
1671   _initial_active_processor_count = active_processor_count();
1672   log_debug(os)("Initial active processor count set to %d" , _initial_active_processor_count);
1673 }
1674 
1675 void os::SuspendedThreadTask::run() {
1676   internal_do_task();
1677   _done = true;
1678 }
1679 
1680 bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1681   return os::pd_create_stack_guard_pages(addr, bytes);
1682 }
1683 
1684 char* os::reserve_memory(size_t bytes, bool executable, MEMFLAGS flags) {
1685   char* result = pd_reserve_memory(bytes, executable);
1686   if (result != NULL) {
1687     MemTracker::record_virtual_memory_reserve(result, bytes, CALLER_PC);
1688     if (flags != mtOther) {
1689       MemTracker::record_virtual_memory_type(result, flags);
1690     }
1691   }
1692 
1693   return result;
1694 }
1695 
1696 char* os::attempt_reserve_memory_at(char* addr, size_t bytes, bool executable) {
1697   char* result = pd_attempt_reserve_memory_at(addr, bytes, executable);
1698   if (result != NULL) {
1699     MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1700   } else {
1701     log_debug(os)("Attempt to reserve memory at " INTPTR_FORMAT " for "
1702                  SIZE_FORMAT " bytes failed, errno %d", p2i(addr), bytes, get_last_error());
1703   }
1704   return result;
1705 }
1706 
1707 static void assert_nonempty_range(const char* addr, size_t bytes) {
1708   assert(addr != nullptr && bytes > 0, "invalid range [" PTR_FORMAT ", " PTR_FORMAT ")",
1709          p2i(addr), p2i(addr) + bytes);
1710 }
1711 
1712 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1713   assert_nonempty_range(addr, bytes);
1714   bool res = pd_commit_memory(addr, bytes, executable);
1715   if (res) {
1716     MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1717   }
1718   return res;
1719 }
1720 
1721 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1722                               bool executable) {
1723   assert_nonempty_range(addr, size);
1724   bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1725   if (res) {
1726     MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1727   }
1728   return res;
1729 }
1730 
1731 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1732                                const char* mesg) {
1733   assert_nonempty_range(addr, bytes);
1734   pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1735   MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1736 }
1737 
1738 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1739                                bool executable, const char* mesg) {
1740   assert_nonempty_range(addr, size);
1741   os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1742   MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1743 }
1744 
1745 bool os::uncommit_memory(char* addr, size_t bytes, bool executable) {
1746   assert_nonempty_range(addr, bytes);
1747   bool res;
1748   if (MemTracker::enabled()) {
1749     Tracker tkr(Tracker::uncommit);
1750     res = pd_uncommit_memory(addr, bytes, executable);
1751     if (res) {
1752       tkr.record((address)addr, bytes);
1753     }
1754   } else {
1755     res = pd_uncommit_memory(addr, bytes, executable);
1756   }
1757   return res;
1758 }
1759 
1760 bool os::release_memory(char* addr, size_t bytes) {
1761   assert_nonempty_range(addr, bytes);
1762   bool res;
1763   if (MemTracker::enabled()) {
1764     // Note: Tracker contains a ThreadCritical.
1765     Tracker tkr(Tracker::release);
1766     res = pd_release_memory(addr, bytes);
1767     if (res) {
1768       tkr.record((address)addr, bytes);
1769     }
1770   } else {
1771     res = pd_release_memory(addr, bytes);
1772   }
1773   if (!res) {
1774     log_info(os)("os::release_memory failed (" PTR_FORMAT ", " SIZE_FORMAT ")", p2i(addr), bytes);
1775   }
1776   return res;
1777 }
1778 
1779 // Prints all mappings
1780 void os::print_memory_mappings(outputStream* st) {
1781   os::print_memory_mappings(nullptr, (size_t)-1, st);
1782 }
1783 
1784 // Pretouching must use a store, not just a load.  On many OSes loads from
1785 // fresh memory would be satisfied from a single mapped page containing all
1786 // zeros.  We need to store something to each page to get them backed by
1787 // their own memory, which is the effect we want here.  An atomic add of
1788 // zero is used instead of a simple store, allowing the memory to be used
1789 // while pretouch is in progress, rather than requiring users of the memory
1790 // to wait until the entire range has been touched.  This is technically
1791 // a UB data race, but doesn't cause any problems for us.
1792 void os::pretouch_memory(void* start, void* end, size_t page_size) {
1793   assert(start <= end, "invalid range: " PTR_FORMAT " -> " PTR_FORMAT, p2i(start), p2i(end));
1794   assert(is_power_of_2(page_size), "page size misaligned: %zu", page_size);
1795   assert(page_size >= sizeof(int), "page size too small: %zu", page_size);
1796   if (start < end) {
1797     // We're doing concurrent-safe touch and memory state has page
1798     // granularity, so we can touch anywhere in a page.  Touch at the
1799     // beginning of each page to simplify iteration.
1800     char* cur = static_cast<char*>(align_down(start, page_size));
1801     void* last = align_down(static_cast<char*>(end) - 1, page_size);
1802     assert(cur <= last, "invariant");
1803     // Iterate from first page through last (inclusive), being careful to
1804     // avoid overflow if the last page abuts the end of the address range.
1805     for ( ; true; cur += page_size) {
1806       Atomic::add(reinterpret_cast<int*>(cur), 0, memory_order_relaxed);
1807       if (cur >= last) break;
1808     }
1809   }
1810 }
1811 
1812 char* os::map_memory_to_file(size_t bytes, int file_desc) {
1813   // Could have called pd_reserve_memory() followed by replace_existing_mapping_with_file_mapping(),
1814   // but AIX may use SHM in which case its more trouble to detach the segment and remap memory to the file.
1815   // On all current implementations NULL is interpreted as any available address.
1816   char* result = os::map_memory_to_file(NULL /* addr */, bytes, file_desc);
1817   if (result != NULL) {
1818     MemTracker::record_virtual_memory_reserve_and_commit(result, bytes, CALLER_PC);
1819   }
1820   return result;
1821 }
1822 
1823 char* os::attempt_map_memory_to_file_at(char* addr, size_t bytes, int file_desc) {
1824   char* result = pd_attempt_map_memory_to_file_at(addr, bytes, file_desc);
1825   if (result != NULL) {
1826     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1827   }
1828   return result;
1829 }
1830 
1831 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1832                            char *addr, size_t bytes, bool read_only,
1833                            bool allow_exec, MEMFLAGS flags) {
1834   char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1835   if (result != NULL) {
1836     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC, flags);
1837   }
1838   return result;
1839 }
1840 
1841 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1842                              char *addr, size_t bytes, bool read_only,
1843                              bool allow_exec) {
1844   return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1845                     read_only, allow_exec);
1846 }
1847 
1848 bool os::unmap_memory(char *addr, size_t bytes) {
1849   bool result;
1850   if (MemTracker::enabled()) {
1851     Tracker tkr(Tracker::release);
1852     result = pd_unmap_memory(addr, bytes);
1853     if (result) {
1854       tkr.record((address)addr, bytes);
1855     }
1856   } else {
1857     result = pd_unmap_memory(addr, bytes);
1858   }
1859   return result;
1860 }
1861 
1862 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1863   pd_free_memory(addr, bytes, alignment_hint);
1864 }
1865 
1866 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1867   pd_realign_memory(addr, bytes, alignment_hint);
1868 }
1869 
1870 char* os::reserve_memory_special(size_t size, size_t alignment, size_t page_size,
1871                                  char* addr, bool executable) {
1872 
1873   assert(is_aligned(addr, alignment), "Unaligned request address");
1874 
1875   char* result = pd_reserve_memory_special(size, alignment, page_size, addr, executable);
1876   if (result != NULL) {
1877     // The memory is committed
1878     MemTracker::record_virtual_memory_reserve_and_commit((address)result, size, CALLER_PC);
1879   }
1880 
1881   return result;
1882 }
1883 
1884 bool os::release_memory_special(char* addr, size_t bytes) {
1885   bool res;
1886   if (MemTracker::enabled()) {
1887     // Note: Tracker contains a ThreadCritical.
1888     Tracker tkr(Tracker::release);
1889     res = pd_release_memory_special(addr, bytes);
1890     if (res) {
1891       tkr.record((address)addr, bytes);
1892     }
1893   } else {
1894     res = pd_release_memory_special(addr, bytes);
1895   }
1896   return res;
1897 }
1898 
1899 #ifndef _WINDOWS
1900 /* try to switch state from state "from" to state "to"
1901  * returns the state set after the method is complete
1902  */
1903 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1904                                                          os::SuspendResume::State to)
1905 {
1906   os::SuspendResume::State result = Atomic::cmpxchg(&_state, from, to);
1907   if (result == from) {
1908     // success
1909     return to;
1910   }
1911   return result;
1912 }
1913 #endif
1914 
1915 // Convenience wrapper around naked_short_sleep to allow for longer sleep
1916 // times. Only for use by non-JavaThreads.
1917 void os::naked_sleep(jlong millis) {
1918   assert(!Thread::current()->is_Java_thread(), "not for use by JavaThreads");
1919   const jlong limit = 999;
1920   while (millis > limit) {
1921     naked_short_sleep(limit);
1922     millis -= limit;
1923   }
1924   naked_short_sleep(millis);
1925 }
1926 
1927 
1928 ////// Implementation of PageSizes
1929 
1930 void os::PageSizes::add(size_t page_size) {
1931   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_HEX, page_size);
1932   _v |= page_size;
1933 }
1934 
1935 bool os::PageSizes::contains(size_t page_size) const {
1936   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_HEX, page_size);
1937   return (_v & page_size) != 0;
1938 }
1939 
1940 size_t os::PageSizes::next_smaller(size_t page_size) const {
1941   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_HEX, page_size);
1942   size_t v2 = _v & (page_size - 1);
1943   if (v2 == 0) {
1944     return 0;
1945   }
1946   return round_down_power_of_2(v2);
1947 }
1948 
1949 size_t os::PageSizes::next_larger(size_t page_size) const {
1950   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_HEX, page_size);
1951   if (page_size == max_power_of_2<size_t>()) { // Shift by 32/64 would be UB
1952     return 0;
1953   }
1954   // Remove current and smaller page sizes
1955   size_t v2 = _v & ~(page_size + (page_size - 1));
1956   if (v2 == 0) {
1957     return 0;
1958   }
1959   return (size_t)1 << count_trailing_zeros(v2);
1960 }
1961 
1962 size_t os::PageSizes::largest() const {
1963   const size_t max = max_power_of_2<size_t>();
1964   if (contains(max)) {
1965     return max;
1966   }
1967   return next_smaller(max);
1968 }
1969 
1970 size_t os::PageSizes::smallest() const {
1971   // Strictly speaking the set should not contain sizes < os::vm_page_size().
1972   // But this is not enforced.
1973   return next_larger(1);
1974 }
1975 
1976 void os::PageSizes::print_on(outputStream* st) const {
1977   bool first = true;
1978   for (size_t sz = smallest(); sz != 0; sz = next_larger(sz)) {
1979     if (first) {
1980       first = false;
1981     } else {
1982       st->print_raw(", ");
1983     }
1984     if (sz < M) {
1985       st->print(SIZE_FORMAT "k", sz / K);
1986     } else if (sz < G) {
1987       st->print(SIZE_FORMAT "M", sz / M);
1988     } else {
1989       st->print(SIZE_FORMAT "G", sz / G);
1990     }
1991   }
1992   if (first) {
1993     st->print("empty");
1994   }
1995 }