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