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