1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/moduleEntry.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "gc/shared/gcVMOperations.hpp"
  36 #include "logging/log.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "memory/universe.hpp"
  43 #include "oops/compressedOops.inline.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "prims/jvm_misc.hpp"
  46 #include "runtime/arguments.hpp"
  47 #include "runtime/atomic.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/handles.inline.hpp"
  50 #include "runtime/interfaceSupport.inline.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/javaThread.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/threadCrashProtection.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 }
 479 
 480 
 481 void os::terminate_signal_thread() {
 482   if (!ReduceSignalUsage)
 483     signal_notify(sigexitnum_pd());
 484 }
 485 
 486 
 487 // --------------------- loading libraries ---------------------
 488 
 489 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
 490 extern struct JavaVM_ main_vm;
 491 
 492 static void* _native_java_library = NULL;
 493 
 494 void* os::native_java_library() {
 495   if (_native_java_library == NULL) {
 496     char buffer[JVM_MAXPATHLEN];
 497     char ebuf[1024];
 498 
 499     // Load java dll
 500     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 501                        "java")) {
 502       _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
 503     }
 504     if (_native_java_library == NULL) {
 505       vm_exit_during_initialization("Unable to load native library", ebuf);
 506     }
 507 
 508 #if defined(__OpenBSD__)
 509     // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
 510     // ignore errors
 511     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 512                        "net")) {
 513       dll_load(buffer, ebuf, sizeof(ebuf));
 514     }
 515 #endif
 516   }
 517   return _native_java_library;
 518 }
 519 
 520 /*
 521  * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
 522  * If check_lib == true then we are looking for an
 523  * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
 524  * this library is statically linked into the image.
 525  * If check_lib == false then we will look for the appropriate symbol in the
 526  * executable if agent_lib->is_static_lib() == true or in the shared library
 527  * referenced by 'handle'.
 528  */
 529 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
 530                               const char *syms[], size_t syms_len) {
 531   assert(agent_lib != NULL, "sanity check");
 532   const char *lib_name;
 533   void *handle = agent_lib->os_lib();
 534   void *entryName = NULL;
 535   char *agent_function_name;
 536   size_t i;
 537 
 538   // If checking then use the agent name otherwise test is_static_lib() to
 539   // see how to process this lookup
 540   lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
 541   for (i = 0; i < syms_len; i++) {
 542     agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
 543     if (agent_function_name == NULL) {
 544       break;
 545     }
 546     entryName = dll_lookup(handle, agent_function_name);
 547     FREE_C_HEAP_ARRAY(char, agent_function_name);
 548     if (entryName != NULL) {
 549       break;
 550     }
 551   }
 552   return entryName;
 553 }
 554 
 555 // See if the passed in agent is statically linked into the VM image.
 556 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
 557                             size_t syms_len) {
 558   void *ret;
 559   void *proc_handle;
 560   void *save_handle;
 561 
 562   assert(agent_lib != NULL, "sanity check");
 563   if (agent_lib->name() == NULL) {
 564     return false;
 565   }
 566   proc_handle = get_default_process_handle();
 567   // Check for Agent_OnLoad/Attach_lib_name function
 568   save_handle = agent_lib->os_lib();
 569   // We want to look in this process' symbol table.
 570   agent_lib->set_os_lib(proc_handle);
 571   ret = find_agent_function(agent_lib, true, syms, syms_len);
 572   if (ret != NULL) {
 573     // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
 574     agent_lib->set_valid();
 575     agent_lib->set_static_lib(true);
 576     return true;
 577   }
 578   agent_lib->set_os_lib(save_handle);
 579   return false;
 580 }
 581 
 582 // --------------------- heap allocation utilities ---------------------
 583 
 584 char *os::strdup(const char *str, MEMFLAGS flags) {
 585   size_t size = strlen(str);
 586   char *dup_str = (char *)malloc(size + 1, flags);
 587   if (dup_str == NULL) return NULL;
 588   strcpy(dup_str, str);
 589   return dup_str;
 590 }
 591 
 592 char* os::strdup_check_oom(const char* str, MEMFLAGS flags) {
 593   char* p = os::strdup(str, flags);
 594   if (p == NULL) {
 595     vm_exit_out_of_memory(strlen(str) + 1, OOM_MALLOC_ERROR, "os::strdup_check_oom");
 596   }
 597   return p;
 598 }
 599 
 600 //
 601 // This function supports testing of the malloc out of memory
 602 // condition without really running the system out of memory.
 603 //
 604 
 605 static bool has_reached_max_malloc_test_peak(size_t alloc_size) {
 606   if (MallocMaxTestWords > 0) {
 607     size_t words = (alloc_size / BytesPerWord);
 608 
 609     if ((cur_malloc_words + words) > MallocMaxTestWords) {
 610       return true;
 611     }
 612     Atomic::add(&cur_malloc_words, words);
 613   }
 614   return false;
 615 }
 616 
 617 #ifdef ASSERT
 618 static void check_crash_protection() {
 619   assert(!ThreadCrashProtection::is_crash_protected(Thread::current_or_null()),
 620          "not allowed when crash protection is set");
 621 }
 622 static void break_if_ptr_caught(void* ptr) {
 623   if (p2i(ptr) == (intptr_t)MallocCatchPtr) {
 624     log_warning(malloc, free)("ptr caught: " PTR_FORMAT, p2i(ptr));
 625     breakpoint();
 626   }
 627 }
 628 #endif // ASSERT
 629 
 630 void* os::malloc(size_t size, MEMFLAGS flags) {
 631   return os::malloc(size, flags, CALLER_PC);
 632 }
 633 
 634 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 635 
 636   // Special handling for NMT preinit phase before arguments are parsed
 637   void* rc = NULL;
 638   if (NMTPreInit::handle_malloc(&rc, size)) {
 639     // No need to fill with 0 because DumpSharedSpaces doesn't use these
 640     // early allocations.
 641     return rc;
 642   }
 643 
 644   DEBUG_ONLY(check_crash_protection());
 645 
 646   // On malloc(0), implementations of malloc(3) have the choice to return either
 647   // NULL or a unique non-NULL pointer. To unify libc behavior across our platforms
 648   // we chose the latter.
 649   size = MAX2((size_t)1, size);
 650 
 651   // For the test flag -XX:MallocMaxTestWords
 652   if (has_reached_max_malloc_test_peak(size)) {
 653     return NULL;
 654   }
 655 
 656   const size_t outer_size = size + MemTracker::overhead_per_malloc();
 657 
 658   ALLOW_C_FUNCTION(::malloc, void* const outer_ptr = ::malloc(outer_size);)
 659   if (outer_ptr == NULL) {
 660     return NULL;
 661   }
 662 
 663   void* const inner_ptr = MemTracker::record_malloc((address)outer_ptr, size, memflags, stack);
 664 
 665   if (DumpSharedSpaces) {
 666     // Need to deterministically fill all the alignment gaps in C++ structures.
 667     ::memset(inner_ptr, 0, size);
 668   } else {
 669     DEBUG_ONLY(::memset(inner_ptr, uninitBlockPad, size);)
 670   }
 671   DEBUG_ONLY(break_if_ptr_caught(inner_ptr);)
 672   return inner_ptr;
 673 }
 674 
 675 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
 676   return os::realloc(memblock, size, flags, CALLER_PC);
 677 }
 678 
 679 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 680 
 681   // Special handling for NMT preinit phase before arguments are parsed
 682   void* rc = NULL;
 683   if (NMTPreInit::handle_realloc(&rc, memblock, size)) {
 684     return rc;
 685   }
 686 
 687   if (memblock == NULL) {
 688     return os::malloc(size, memflags, stack);
 689   }
 690 
 691   DEBUG_ONLY(check_crash_protection());
 692 
 693   // On realloc(p, 0), implementers of realloc(3) have the choice to return either
 694   // NULL or a unique non-NULL pointer. To unify libc behavior across our platforms
 695   // we chose the latter.
 696   size = MAX2((size_t)1, size);
 697 
 698   // For the test flag -XX:MallocMaxTestWords
 699   if (has_reached_max_malloc_test_peak(size)) {
 700     return NULL;
 701   }
 702 
 703   const size_t new_outer_size = size + MemTracker::overhead_per_malloc();
 704 
 705   // If NMT is enabled, this checks for heap overwrites, then de-accounts the old block.
 706   void* const old_outer_ptr = MemTracker::record_free(memblock);
 707 
 708   ALLOW_C_FUNCTION(::realloc, void* const new_outer_ptr = ::realloc(old_outer_ptr, new_outer_size);)
 709   if (new_outer_ptr == NULL) {
 710     return NULL;
 711   }
 712 
 713   void* const new_inner_ptr = MemTracker::record_malloc(new_outer_ptr, size, memflags, stack);
 714 
 715   DEBUG_ONLY(break_if_ptr_caught(new_inner_ptr);)
 716 
 717   return new_inner_ptr;
 718 }
 719 
 720 void  os::free(void *memblock) {
 721 
 722   // Special handling for NMT preinit phase before arguments are parsed
 723   if (NMTPreInit::handle_free(memblock)) {
 724     return;
 725   }
 726 
 727   if (memblock == NULL) {
 728     return;
 729   }
 730 
 731   DEBUG_ONLY(break_if_ptr_caught(memblock);)
 732 
 733   // If NMT is enabled, this checks for heap overwrites, then de-accounts the old block.
 734   void* const old_outer_ptr = MemTracker::record_free(memblock);
 735 
 736   ALLOW_C_FUNCTION(::free, ::free(old_outer_ptr);)
 737 }
 738 
 739 void os::init_random(unsigned int initval) {
 740   _rand_seed = initval;
 741 }
 742 
 743 
 744 int os::next_random(unsigned int rand_seed) {
 745   /* standard, well-known linear congruential random generator with
 746    * next_rand = (16807*seed) mod (2**31-1)
 747    * see
 748    * (1) "Random Number Generators: Good Ones Are Hard to Find",
 749    *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
 750    * (2) "Two Fast Implementations of the 'Minimal Standard' Random
 751    *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
 752   */
 753   const unsigned int a = 16807;
 754   const unsigned int m = 2147483647;
 755   const int q = m / a;        assert(q == 127773, "weird math");
 756   const int r = m % a;        assert(r == 2836, "weird math");
 757 
 758   // compute az=2^31p+q
 759   unsigned int lo = a * (rand_seed & 0xFFFF);
 760   unsigned int hi = a * (rand_seed >> 16);
 761   lo += (hi & 0x7FFF) << 16;
 762 
 763   // if q overflowed, ignore the overflow and increment q
 764   if (lo > m) {
 765     lo &= m;
 766     ++lo;
 767   }
 768   lo += hi >> 15;
 769 
 770   // if (p+q) overflowed, ignore the overflow and increment (p+q)
 771   if (lo > m) {
 772     lo &= m;
 773     ++lo;
 774   }
 775   return lo;
 776 }
 777 
 778 int os::random() {
 779   // Make updating the random seed thread safe.
 780   while (true) {
 781     unsigned int seed = _rand_seed;
 782     unsigned int rand = next_random(seed);
 783     if (Atomic::cmpxchg(&_rand_seed, seed, rand, memory_order_relaxed) == seed) {
 784       return static_cast<int>(rand);
 785     }
 786   }
 787 }
 788 
 789 // The INITIALIZED state is distinguished from the SUSPENDED state because the
 790 // conditions in which a thread is first started are different from those in which
 791 // a suspension is resumed.  These differences make it hard for us to apply the
 792 // tougher checks when starting threads that we want to do when resuming them.
 793 // However, when start_thread is called as a result of Thread.start, on a Java
 794 // thread, the operation is synchronized on the Java Thread object.  So there
 795 // cannot be a race to start the thread and hence for the thread to exit while
 796 // we are working on it.  Non-Java threads that start Java threads either have
 797 // to do so in a context in which races are impossible, or should do appropriate
 798 // locking.
 799 
 800 void os::start_thread(Thread* thread) {
 801   OSThread* osthread = thread->osthread();
 802   osthread->set_state(RUNNABLE);
 803   pd_start_thread(thread);
 804 }
 805 
 806 void os::abort(bool dump_core) {
 807   abort(dump_core && CreateCoredumpOnCrash, NULL, NULL);
 808 }
 809 
 810 //---------------------------------------------------------------------------
 811 // Helper functions for fatal error handler
 812 
 813 bool os::print_function_and_library_name(outputStream* st,
 814                                          address addr,
 815                                          char* buf, int buflen,
 816                                          bool shorten_paths,
 817                                          bool demangle,
 818                                          bool strip_arguments) {
 819   // If no scratch buffer given, allocate one here on stack.
 820   // (used during error handling; its a coin toss, really, if on-stack allocation
 821   //  is worse than (raw) C-heap allocation in that case).
 822   char* p = buf;
 823   if (p == NULL) {
 824     p = (char*)::alloca(O_BUFLEN);
 825     buflen = O_BUFLEN;
 826   }
 827   int offset = 0;
 828   bool have_function_name = dll_address_to_function_name(addr, p, buflen,
 829                                                          &offset, demangle);
 830   bool is_function_descriptor = false;
 831 #ifdef HAVE_FUNCTION_DESCRIPTORS
 832   // When we deal with a function descriptor instead of a real code pointer, try to
 833   // resolve it. There is a small chance that a random pointer given to this function
 834   // may just happen to look like a valid descriptor, but this is rare and worth the
 835   // risk to see resolved function names. But we will print a little suffix to mark
 836   // this as a function descriptor for the reader (see below).
 837   if (!have_function_name && os::is_readable_pointer(addr)) {
 838     address addr2 = (address)os::resolve_function_descriptor(addr);
 839     if (have_function_name = is_function_descriptor =
 840         dll_address_to_function_name(addr2, p, buflen, &offset, demangle)) {
 841       addr = addr2;
 842     }
 843   }
 844 #endif // HAVE_FUNCTION_DESCRIPTORS
 845 
 846   if (have_function_name) {
 847     // Print function name, optionally demangled
 848     if (demangle && strip_arguments) {
 849       char* args_start = strchr(p, '(');
 850       if (args_start != NULL) {
 851         *args_start = '\0';
 852       }
 853     }
 854     // Print offset. Omit printing if offset is zero, which makes the output
 855     // more readable if we print function pointers.
 856     if (offset == 0) {
 857       st->print("%s", p);
 858     } else {
 859       st->print("%s+%d", p, offset);
 860     }
 861   } else {
 862     st->print(PTR_FORMAT, p2i(addr));
 863   }
 864   offset = 0;
 865 
 866   const bool have_library_name = dll_address_to_library_name(addr, p, buflen, &offset);
 867   if (have_library_name) {
 868     // Cut path parts
 869     if (shorten_paths) {
 870       char* p2 = strrchr(p, os::file_separator()[0]);
 871       if (p2 != NULL) {
 872         p = p2 + 1;
 873       }
 874     }
 875     st->print(" in %s", p);
 876     if (!have_function_name) { // Omit offset if we already printed the function offset
 877       st->print("+%d", offset);
 878     }
 879   }
 880 
 881   // Write a trailing marker if this was a function descriptor
 882   if (have_function_name && is_function_descriptor) {
 883     st->print_raw(" (FD)");
 884   }
 885 
 886   return have_function_name || have_library_name;
 887 }
 888 
 889 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize,
 890                         int bytes_per_line, address logical_start) {
 891   assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
 892 
 893   start = align_down(start, unitsize);
 894   logical_start = align_down(logical_start, unitsize);
 895   bytes_per_line = align_up(bytes_per_line, 8);
 896 
 897   int cols = 0;
 898   int cols_per_line = bytes_per_line / unitsize;
 899 
 900   address p = start;
 901   address logical_p = logical_start;
 902 
 903   // Print out the addresses as if we were starting from logical_start.
 904   st->print(PTR_FORMAT ":   ", p2i(logical_p));
 905   while (p < end) {
 906     if (is_readable_pointer(p)) {
 907       switch (unitsize) {
 908         case 1: st->print("%02x", *(u1*)p); break;
 909         case 2: st->print("%04x", *(u2*)p); break;
 910         case 4: st->print("%08x", *(u4*)p); break;
 911         case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
 912       }
 913     } else {
 914       st->print("%*.*s", 2*unitsize, 2*unitsize, "????????????????");
 915     }
 916     p += unitsize;
 917     logical_p += unitsize;
 918     cols++;
 919     if (cols >= cols_per_line && p < end) {
 920        cols = 0;
 921        st->cr();
 922        st->print(PTR_FORMAT ":   ", p2i(logical_p));
 923     } else {
 924        st->print(" ");
 925     }
 926   }
 927   st->cr();
 928 }
 929 
 930 void os::print_dhm(outputStream* st, const char* startStr, long sec) {
 931   long days    = sec/86400;
 932   long hours   = (sec/3600) - (days * 24);
 933   long minutes = (sec/60) - (days * 1440) - (hours * 60);
 934   if (startStr == NULL) startStr = "";
 935   st->print_cr("%s %ld days %ld:%02ld hours", startStr, days, hours, minutes);
 936 }
 937 
 938 void os::print_tos(outputStream* st, address sp) {
 939   st->print_cr("Top of Stack: (sp=" PTR_FORMAT ")", p2i(sp));
 940   print_hex_dump(st, sp, sp + 512, sizeof(intptr_t));
 941 }
 942 
 943 void os::print_instructions(outputStream* st, address pc, int unitsize) {
 944   st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc));
 945   print_hex_dump(st, pc - 256, pc + 256, unitsize);
 946 }
 947 
 948 void os::print_environment_variables(outputStream* st, const char** env_list) {
 949   if (env_list) {
 950     st->print_cr("Environment Variables:");
 951 
 952     for (int i = 0; env_list[i] != NULL; i++) {
 953       char *envvar = ::getenv(env_list[i]);
 954       if (envvar != NULL) {
 955         st->print("%s", env_list[i]);
 956         st->print("=");
 957         st->print("%s", envvar);
 958         // Use separate cr() printing to avoid unnecessary buffer operations that might cause truncation.
 959         st->cr();
 960       }
 961     }
 962   }
 963 }
 964 
 965 void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) {
 966   // cpu
 967   st->print("CPU:");
 968 #if defined(__APPLE__) && !defined(ZERO)
 969    if (VM_Version::is_cpu_emulated()) {
 970      st->print(" (EMULATED)");
 971    }
 972 #endif
 973   st->print(" total %d", os::processor_count());
 974   // It's not safe to query number of active processors after crash
 975   // st->print("(active %d)", os::active_processor_count()); but we can
 976   // print the initial number of active processors.
 977   // We access the raw value here because the assert in the accessor will
 978   // fail if the crash occurs before initialization of this value.
 979   st->print(" (initial active %d)", _initial_active_processor_count);
 980   st->print(" %s", VM_Version::features_string());
 981   st->cr();
 982   pd_print_cpu_info(st, buf, buflen);
 983 }
 984 
 985 // Print a one line string summarizing the cpu, number of cores, memory, and operating system version
 986 void os::print_summary_info(outputStream* st, char* buf, size_t buflen) {
 987   st->print("Host: ");
 988 #ifndef PRODUCT
 989   if (get_host_name(buf, buflen)) {
 990     st->print("%s, ", buf);
 991   }
 992 #endif // PRODUCT
 993   get_summary_cpu_info(buf, buflen);
 994   st->print("%s, ", buf);
 995   size_t mem = physical_memory()/G;
 996   if (mem == 0) {  // for low memory systems
 997     mem = physical_memory()/M;
 998     st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem);
 999   } else {
1000     st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem);
1001   }
1002   get_summary_os_info(buf, buflen);
1003   st->print_raw(buf);
1004   st->cr();
1005 }
1006 
1007 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
1008   const int secs_per_day  = 86400;
1009   const int secs_per_hour = 3600;
1010   const int secs_per_min  = 60;
1011 
1012   time_t tloc;
1013   (void)time(&tloc);
1014   char* timestring = ctime(&tloc);  // ctime adds newline.
1015   // edit out the newline
1016   char* nl = strchr(timestring, '\n');
1017   if (nl != NULL) {
1018     *nl = '\0';
1019   }
1020 
1021   struct tm tz;
1022   if (localtime_pd(&tloc, &tz) != NULL) {
1023     wchar_t w_buf[80];
1024     size_t n = ::wcsftime(w_buf, 80, L"%Z", &tz);
1025     if (n > 0) {
1026       ::wcstombs(buf, w_buf, buflen);
1027       st->print("Time: %s %s", timestring, buf);
1028     } else {
1029       st->print("Time: %s", timestring);
1030     }
1031   } else {
1032     st->print("Time: %s", timestring);
1033   }
1034 
1035   double t = os::elapsedTime();
1036   // NOTE: a crash using printf("%f",...) on Linux was historically noted here.
1037   int eltime = (int)t;  // elapsed time in seconds
1038   int eltimeFraction = (int) ((t - eltime) * 1000000);
1039 
1040   // print elapsed time in a human-readable format:
1041   int eldays = eltime / secs_per_day;
1042   int day_secs = eldays * secs_per_day;
1043   int elhours = (eltime - day_secs) / secs_per_hour;
1044   int hour_secs = elhours * secs_per_hour;
1045   int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
1046   int minute_secs = elmins * secs_per_min;
1047   int elsecs = (eltime - day_secs - hour_secs - minute_secs);
1048   st->print_cr(" elapsed time: %d.%06d seconds (%dd %dh %dm %ds)", eltime, eltimeFraction, eldays, elhours, elmins, elsecs);
1049 }
1050 
1051 
1052 // Check if pointer can be read from (4-byte read access).
1053 // Helps to prove validity of a not-NULL pointer.
1054 // Returns true in very early stages of VM life when stub is not yet generated.
1055 bool os::is_readable_pointer(const void* p) {
1056   int* const aligned = (int*) align_down((intptr_t)p, 4);
1057   int cafebabe = 0xcafebabe;  // tester value 1
1058   int deadbeef = 0xdeadbeef;  // tester value 2
1059   return (SafeFetch32(aligned, cafebabe) != cafebabe) || (SafeFetch32(aligned, deadbeef) != deadbeef);
1060 }
1061 
1062 bool os::is_readable_range(const void* from, const void* to) {
1063   if ((uintptr_t)from >= (uintptr_t)to) return false;
1064   for (uintptr_t p = align_down((uintptr_t)from, min_page_size()); p < (uintptr_t)to; p += min_page_size()) {
1065     if (!is_readable_pointer((const void*)p)) {
1066       return false;
1067     }
1068   }
1069   return true;
1070 }
1071 
1072 
1073 // moved from debug.cpp (used to be find()) but still called from there
1074 // The verbose parameter is only set by the debug code in one case
1075 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
1076   address addr = (address)x;
1077   // Handle NULL first, so later checks don't need to protect against it.
1078   if (addr == NULL) {
1079     st->print_cr("0x0 is NULL");
1080     return;
1081   }
1082 
1083   // Check if addr points into a code blob.
1084   CodeBlob* b = CodeCache::find_blob(addr);
1085   if (b != NULL) {
1086     b->dump_for_addr(addr, st, verbose);
1087     return;
1088   }
1089 
1090   // Check if addr points into Java heap.
1091   if (Universe::heap()->print_location(st, addr)) {
1092     return;
1093   }
1094 
1095   bool accessible = is_readable_pointer(addr);
1096 
1097   // Check if addr is a JNI handle.
1098   if (align_down((intptr_t)addr, sizeof(intptr_t)) != 0 && accessible) {
1099     if (JNIHandles::is_global_handle((jobject) addr)) {
1100       st->print_cr(INTPTR_FORMAT " is a global jni handle", p2i(addr));
1101       return;
1102     }
1103     if (JNIHandles::is_weak_global_handle((jobject) addr)) {
1104       st->print_cr(INTPTR_FORMAT " is a weak global jni handle", p2i(addr));
1105       return;
1106     }
1107   }
1108 
1109   // Check if addr belongs to a Java thread.
1110   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
1111     // If the addr is a java thread print information about that.
1112     if (addr == (address)thread) {
1113       if (verbose) {
1114         thread->print_on(st);
1115       } else {
1116         st->print_cr(INTPTR_FORMAT " is a thread", p2i(addr));
1117       }
1118       return;
1119     }
1120     // If the addr is in the stack region for this thread then report that
1121     // and print thread info
1122     if (thread->is_in_full_stack(addr)) {
1123       st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1124                    INTPTR_FORMAT, p2i(addr), p2i(thread));
1125       if (verbose) thread->print_on(st);
1126       return;
1127     }
1128   }
1129 
1130   // Check if in metaspace and print types that have vptrs
1131   if (Metaspace::contains(addr)) {
1132     if (Klass::is_valid((Klass*)addr)) {
1133       st->print_cr(INTPTR_FORMAT " is a pointer to class: ", p2i(addr));
1134       ((Klass*)addr)->print_on(st);
1135     } else if (Method::is_valid_method((const Method*)addr)) {
1136       ((Method*)addr)->print_value_on(st);
1137       st->cr();
1138     } else {
1139       // Use addr->print() from the debugger instead (not here)
1140       st->print_cr(INTPTR_FORMAT " is pointing into metadata", p2i(addr));
1141     }
1142     return;
1143   }
1144 
1145   // Compressed klass needs to be decoded first.
1146 #ifdef _LP64
1147   if (UseCompressedClassPointers && ((uintptr_t)addr &~ (uintptr_t)max_juint) == 0) {
1148     narrowKlass narrow_klass = (narrowKlass)(uintptr_t)addr;
1149     Klass* k = CompressedKlassPointers::decode_raw(narrow_klass);
1150 
1151     if (Klass::is_valid(k)) {
1152       st->print_cr(UINT32_FORMAT " is a compressed pointer to class: " INTPTR_FORMAT, narrow_klass, p2i((HeapWord*)k));
1153       k->print_on(st);
1154       return;
1155     }
1156   }
1157 #endif
1158 
1159   // Try an OS specific find
1160   if (os::find(addr, st)) {
1161     return;
1162   }
1163 
1164   if (accessible) {
1165     st->print(INTPTR_FORMAT " points into unknown readable memory:", p2i(addr));
1166     if (is_aligned(addr, sizeof(intptr_t))) {
1167       st->print(" " PTR_FORMAT " |", *(intptr_t*)addr);
1168     }
1169     for (address p = addr; p < align_up(addr + 1, sizeof(intptr_t)); ++p) {
1170       st->print(" %02x", *(u1*)p);
1171     }
1172     st->cr();
1173     return;
1174   }
1175 
1176   st->print_cr(INTPTR_FORMAT " is an unknown value", p2i(addr));
1177 }
1178 
1179 bool is_pointer_bad(intptr_t* ptr) {
1180   return !is_aligned(ptr, sizeof(uintptr_t)) || !os::is_readable_pointer(ptr);
1181 }
1182 
1183 // Looks like all platforms can use the same function to check if C
1184 // stack is walkable beyond current frame.
1185 // Returns true if this is not the case, i.e. the frame is possibly
1186 // the first C frame on the stack.
1187 bool os::is_first_C_frame(frame* fr) {
1188 
1189 #ifdef _WINDOWS
1190   return true; // native stack isn't walkable on windows this way.
1191 #endif
1192   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1193   // Check usp first, because if that's bad the other accessors may fault
1194   // on some architectures.  Ditto ufp second, etc.
1195 
1196   if (is_pointer_bad(fr->sp())) return true;
1197 
1198   uintptr_t ufp    = (uintptr_t)fr->fp();
1199   if (is_pointer_bad(fr->fp())) return true;
1200 
1201   uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1202   if ((uintptr_t)fr->sender_sp() == (uintptr_t)-1 || is_pointer_bad(fr->sender_sp())) return true;
1203 
1204   uintptr_t old_fp = (uintptr_t)fr->link_or_null();
1205   if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp ||
1206     is_pointer_bad(fr->link_or_null())) return true;
1207 
1208   // stack grows downwards; if old_fp is below current fp or if the stack
1209   // frame is too large, either the stack is corrupted or fp is not saved
1210   // on stack (i.e. on x86, ebp may be used as general register). The stack
1211   // is not walkable beyond current frame.
1212   if (old_fp < ufp) return true;
1213   if (old_fp - ufp > 64 * K) return true;
1214 
1215   return false;
1216 }
1217 
1218 // Set up the boot classpath.
1219 
1220 char* os::format_boot_path(const char* format_string,
1221                            const char* home,
1222                            int home_len,
1223                            char fileSep,
1224                            char pathSep) {
1225     assert((fileSep == '/' && pathSep == ':') ||
1226            (fileSep == '\\' && pathSep == ';'), "unexpected separator chars");
1227 
1228     // Scan the format string to determine the length of the actual
1229     // boot classpath, and handle platform dependencies as well.
1230     int formatted_path_len = 0;
1231     const char* p;
1232     for (p = format_string; *p != 0; ++p) {
1233         if (*p == '%') formatted_path_len += home_len - 1;
1234         ++formatted_path_len;
1235     }
1236 
1237     char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1238 
1239     // Create boot classpath from format, substituting separator chars and
1240     // java home directory.
1241     char* q = formatted_path;
1242     for (p = format_string; *p != 0; ++p) {
1243         switch (*p) {
1244         case '%':
1245             strcpy(q, home);
1246             q += home_len;
1247             break;
1248         case '/':
1249             *q++ = fileSep;
1250             break;
1251         case ':':
1252             *q++ = pathSep;
1253             break;
1254         default:
1255             *q++ = *p;
1256         }
1257     }
1258     *q = '\0';
1259 
1260     assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1261     return formatted_path;
1262 }
1263 
1264 // This function is a proxy to fopen, it tries to add a non standard flag ('e' or 'N')
1265 // that ensures automatic closing of the file on exec. If it can not find support in
1266 // the underlying c library, it will make an extra system call (fcntl) to ensure automatic
1267 // closing of the file on exec.
1268 FILE* os::fopen(const char* path, const char* mode) {
1269   char modified_mode[20];
1270   assert(strlen(mode) + 1 < sizeof(modified_mode), "mode chars plus one extra must fit in buffer");
1271   sprintf(modified_mode, "%s" LINUX_ONLY("e") BSD_ONLY("e") WINDOWS_ONLY("N"), mode);
1272   FILE* file = ::fopen(path, modified_mode);
1273 
1274 #if !(defined LINUX || defined BSD || defined _WINDOWS)
1275   // assume fcntl FD_CLOEXEC support as a backup solution when 'e' or 'N'
1276   // is not supported as mode in fopen
1277   if (file != NULL) {
1278     int fd = fileno(file);
1279     if (fd != -1) {
1280       int fd_flags = fcntl(fd, F_GETFD);
1281       if (fd_flags != -1) {
1282         fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC);
1283       }
1284     }
1285   }
1286 #endif
1287 
1288   return file;
1289 }
1290 
1291 bool os::set_boot_path(char fileSep, char pathSep) {
1292   const char* home = Arguments::get_java_home();
1293   int home_len = (int)strlen(home);
1294 
1295   struct stat st;
1296 
1297   // modular image if "modules" jimage exists
1298   char* jimage = format_boot_path("%/lib/" MODULES_IMAGE_NAME, home, home_len, fileSep, pathSep);
1299   if (jimage == NULL) return false;
1300   bool has_jimage = (os::stat(jimage, &st) == 0);
1301   if (has_jimage) {
1302     Arguments::set_boot_class_path(jimage, true);
1303     FREE_C_HEAP_ARRAY(char, jimage);
1304     return true;
1305   }
1306   FREE_C_HEAP_ARRAY(char, jimage);
1307 
1308   // check if developer build with exploded modules
1309   char* base_classes = format_boot_path("%/modules/" JAVA_BASE_NAME, home, home_len, fileSep, pathSep);
1310   if (base_classes == NULL) return false;
1311   if (os::stat(base_classes, &st) == 0) {
1312     Arguments::set_boot_class_path(base_classes, false);
1313     FREE_C_HEAP_ARRAY(char, base_classes);
1314     return true;
1315   }
1316   FREE_C_HEAP_ARRAY(char, base_classes);
1317 
1318   return false;
1319 }
1320 
1321 bool os::file_exists(const char* filename) {
1322   struct stat statbuf;
1323   if (filename == NULL || strlen(filename) == 0) {
1324     return false;
1325   }
1326   return os::stat(filename, &statbuf) == 0;
1327 }
1328 
1329 // Splits a path, based on its separator, the number of
1330 // elements is returned back in "elements".
1331 // file_name_length is used as a modifier for each path's
1332 // length when compared to JVM_MAXPATHLEN. So if you know
1333 // each returned path will have something appended when
1334 // in use, you can pass the length of that in
1335 // file_name_length, to ensure we detect if any path
1336 // exceeds the maximum path length once prepended onto
1337 // the sub-path/file name.
1338 // It is the callers responsibility to:
1339 //   a> check the value of "elements", which may be 0.
1340 //   b> ignore any empty path elements
1341 //   c> free up the data.
1342 char** os::split_path(const char* path, size_t* elements, size_t file_name_length) {
1343   *elements = (size_t)0;
1344   if (path == NULL || strlen(path) == 0 || file_name_length == (size_t)NULL) {
1345     return NULL;
1346   }
1347   const char psepchar = *os::path_separator();
1348   char* inpath = NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1349   strcpy(inpath, path);
1350   size_t count = 1;
1351   char* p = strchr(inpath, psepchar);
1352   // Get a count of elements to allocate memory
1353   while (p != NULL) {
1354     count++;
1355     p++;
1356     p = strchr(p, psepchar);
1357   }
1358 
1359   char** opath = NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1360 
1361   // do the actual splitting
1362   p = inpath;
1363   for (size_t i = 0 ; i < count ; i++) {
1364     size_t len = strcspn(p, os::path_separator());
1365     if (len + file_name_length > JVM_MAXPATHLEN) {
1366       // release allocated storage before exiting the vm
1367       free_array_of_char_arrays(opath, i++);
1368       vm_exit_during_initialization("The VM tried to use a path that exceeds the maximum path length for "
1369                                     "this system. Review path-containing parameters and properties, such as "
1370                                     "sun.boot.library.path, to identify potential sources for this path.");
1371     }
1372     // allocate the string and add terminator storage
1373     char* s = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1374     strncpy(s, p, len);
1375     s[len] = '\0';
1376     opath[i] = s;
1377     p += len + 1;
1378   }
1379   FREE_C_HEAP_ARRAY(char, inpath);
1380   *elements = count;
1381   return opath;
1382 }
1383 
1384 // Returns true if the current stack pointer is above the stack shadow
1385 // pages, false otherwise.
1386 bool os::stack_shadow_pages_available(Thread *thread, const methodHandle& method, address sp) {
1387   if (!thread->is_Java_thread()) return false;
1388   // Check if we have StackShadowPages above the guard zone. This parameter
1389   // is dependent on the depth of the maximum VM call stack possible from
1390   // the handler for stack overflow.  'instanceof' in the stack overflow
1391   // handler or a println uses at least 8k stack of VM and native code
1392   // respectively.
1393   const int framesize_in_bytes =
1394     Interpreter::size_top_interpreter_activation(method()) * wordSize;
1395 
1396   address limit = JavaThread::cast(thread)->stack_overflow_state()->shadow_zone_safe_limit();
1397   return sp > (limit + framesize_in_bytes);
1398 }
1399 
1400 size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) {
1401   assert(min_pages > 0, "sanity");
1402   if (UseLargePages) {
1403     const size_t max_page_size = region_size / min_pages;
1404 
1405     for (size_t page_size = page_sizes().largest(); page_size != 0;
1406          page_size = page_sizes().next_smaller(page_size)) {
1407       if (page_size <= max_page_size) {
1408         if (!must_be_aligned || is_aligned(region_size, page_size)) {
1409           return page_size;
1410         }
1411       }
1412     }
1413   }
1414 
1415   return vm_page_size();
1416 }
1417 
1418 size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) {
1419   return page_size_for_region(region_size, min_pages, true);
1420 }
1421 
1422 size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) {
1423   return page_size_for_region(region_size, min_pages, false);
1424 }
1425 
1426 #ifndef MAX_PATH
1427 #define MAX_PATH    (2 * K)
1428 #endif
1429 
1430 void os::pause() {
1431   char filename[MAX_PATH];
1432   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
1433     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
1434   } else {
1435     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
1436   }
1437 
1438   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
1439   if (fd != -1) {
1440     struct stat buf;
1441     ::close(fd);
1442     while (::stat(filename, &buf) == 0) {
1443 #if defined(_WINDOWS)
1444       Sleep(100);
1445 #else
1446       (void)::poll(NULL, 0, 100);
1447 #endif
1448     }
1449   } else {
1450     jio_fprintf(stderr,
1451                 "Could not open pause file '%s', continuing immediately.\n", filename);
1452   }
1453 }
1454 
1455 static const char* errno_to_string (int e, bool short_text) {
1456   #define ALL_SHARED_ENUMS(X) \
1457     X(E2BIG, "Argument list too long") \
1458     X(EACCES, "Permission denied") \
1459     X(EADDRINUSE, "Address in use") \
1460     X(EADDRNOTAVAIL, "Address not available") \
1461     X(EAFNOSUPPORT, "Address family not supported") \
1462     X(EAGAIN, "Resource unavailable, try again") \
1463     X(EALREADY, "Connection already in progress") \
1464     X(EBADF, "Bad file descriptor") \
1465     X(EBADMSG, "Bad message") \
1466     X(EBUSY, "Device or resource busy") \
1467     X(ECANCELED, "Operation canceled") \
1468     X(ECHILD, "No child processes") \
1469     X(ECONNABORTED, "Connection aborted") \
1470     X(ECONNREFUSED, "Connection refused") \
1471     X(ECONNRESET, "Connection reset") \
1472     X(EDEADLK, "Resource deadlock would occur") \
1473     X(EDESTADDRREQ, "Destination address required") \
1474     X(EDOM, "Mathematics argument out of domain of function") \
1475     X(EEXIST, "File exists") \
1476     X(EFAULT, "Bad address") \
1477     X(EFBIG, "File too large") \
1478     X(EHOSTUNREACH, "Host is unreachable") \
1479     X(EIDRM, "Identifier removed") \
1480     X(EILSEQ, "Illegal byte sequence") \
1481     X(EINPROGRESS, "Operation in progress") \
1482     X(EINTR, "Interrupted function") \
1483     X(EINVAL, "Invalid argument") \
1484     X(EIO, "I/O error") \
1485     X(EISCONN, "Socket is connected") \
1486     X(EISDIR, "Is a directory") \
1487     X(ELOOP, "Too many levels of symbolic links") \
1488     X(EMFILE, "Too many open files") \
1489     X(EMLINK, "Too many links") \
1490     X(EMSGSIZE, "Message too large") \
1491     X(ENAMETOOLONG, "Filename too long") \
1492     X(ENETDOWN, "Network is down") \
1493     X(ENETRESET, "Connection aborted by network") \
1494     X(ENETUNREACH, "Network unreachable") \
1495     X(ENFILE, "Too many files open in system") \
1496     X(ENOBUFS, "No buffer space available") \
1497     X(ENODATA, "No message is available on the STREAM head read queue") \
1498     X(ENODEV, "No such device") \
1499     X(ENOENT, "No such file or directory") \
1500     X(ENOEXEC, "Executable file format error") \
1501     X(ENOLCK, "No locks available") \
1502     X(ENOLINK, "Reserved") \
1503     X(ENOMEM, "Not enough space") \
1504     X(ENOMSG, "No message of the desired type") \
1505     X(ENOPROTOOPT, "Protocol not available") \
1506     X(ENOSPC, "No space left on device") \
1507     X(ENOSR, "No STREAM resources") \
1508     X(ENOSTR, "Not a STREAM") \
1509     X(ENOSYS, "Function not supported") \
1510     X(ENOTCONN, "The socket is not connected") \
1511     X(ENOTDIR, "Not a directory") \
1512     X(ENOTEMPTY, "Directory not empty") \
1513     X(ENOTSOCK, "Not a socket") \
1514     X(ENOTSUP, "Not supported") \
1515     X(ENOTTY, "Inappropriate I/O control operation") \
1516     X(ENXIO, "No such device or address") \
1517     X(EOPNOTSUPP, "Operation not supported on socket") \
1518     X(EOVERFLOW, "Value too large to be stored in data type") \
1519     X(EPERM, "Operation not permitted") \
1520     X(EPIPE, "Broken pipe") \
1521     X(EPROTO, "Protocol error") \
1522     X(EPROTONOSUPPORT, "Protocol not supported") \
1523     X(EPROTOTYPE, "Protocol wrong type for socket") \
1524     X(ERANGE, "Result too large") \
1525     X(EROFS, "Read-only file system") \
1526     X(ESPIPE, "Invalid seek") \
1527     X(ESRCH, "No such process") \
1528     X(ETIME, "Stream ioctl() timeout") \
1529     X(ETIMEDOUT, "Connection timed out") \
1530     X(ETXTBSY, "Text file busy") \
1531     X(EWOULDBLOCK, "Operation would block") \
1532     X(EXDEV, "Cross-device link")
1533 
1534   #define DEFINE_ENTRY(e, text) { e, #e, text },
1535 
1536   static const struct {
1537     int v;
1538     const char* short_text;
1539     const char* long_text;
1540   } table [] = {
1541 
1542     ALL_SHARED_ENUMS(DEFINE_ENTRY)
1543 
1544     // The following enums are not defined on all platforms.
1545     #ifdef ESTALE
1546     DEFINE_ENTRY(ESTALE, "Reserved")
1547     #endif
1548     #ifdef EDQUOT
1549     DEFINE_ENTRY(EDQUOT, "Reserved")
1550     #endif
1551     #ifdef EMULTIHOP
1552     DEFINE_ENTRY(EMULTIHOP, "Reserved")
1553     #endif
1554 
1555     // End marker.
1556     { -1, "Unknown errno", "Unknown error" }
1557 
1558   };
1559 
1560   #undef DEFINE_ENTRY
1561   #undef ALL_FLAGS
1562 
1563   int i = 0;
1564   while (table[i].v != -1 && table[i].v != e) {
1565     i ++;
1566   }
1567 
1568   return short_text ? table[i].short_text : table[i].long_text;
1569 
1570 }
1571 
1572 const char* os::strerror(int e) {
1573   return errno_to_string(e, false);
1574 }
1575 
1576 const char* os::errno_name(int e) {
1577   return errno_to_string(e, true);
1578 }
1579 
1580 #define trace_page_size_params(size) byte_size_in_exact_unit(size), exact_unit_for_byte_size(size)
1581 
1582 void os::trace_page_sizes(const char* str,
1583                           const size_t region_min_size,
1584                           const size_t region_max_size,
1585                           const size_t page_size,
1586                           const char* base,
1587                           const size_t size) {
1588 
1589   log_info(pagesize)("%s: "
1590                      " min=" SIZE_FORMAT "%s"
1591                      " max=" SIZE_FORMAT "%s"
1592                      " base=" PTR_FORMAT
1593                      " page_size=" SIZE_FORMAT "%s"
1594                      " size=" SIZE_FORMAT "%s",
1595                      str,
1596                      trace_page_size_params(region_min_size),
1597                      trace_page_size_params(region_max_size),
1598                      p2i(base),
1599                      trace_page_size_params(page_size),
1600                      trace_page_size_params(size));
1601 }
1602 
1603 void os::trace_page_sizes_for_requested_size(const char* str,
1604                                              const size_t requested_size,
1605                                              const size_t page_size,
1606                                              const size_t alignment,
1607                                              const char* base,
1608                                              const size_t size) {
1609 
1610   log_info(pagesize)("%s:"
1611                      " req_size=" SIZE_FORMAT "%s"
1612                      " base=" PTR_FORMAT
1613                      " page_size=" SIZE_FORMAT "%s"
1614                      " alignment=" SIZE_FORMAT "%s"
1615                      " size=" SIZE_FORMAT "%s",
1616                      str,
1617                      trace_page_size_params(requested_size),
1618                      p2i(base),
1619                      trace_page_size_params(page_size),
1620                      trace_page_size_params(alignment),
1621                      trace_page_size_params(size));
1622 }
1623 
1624 
1625 // This is the working definition of a server class machine:
1626 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1627 // because the graphics memory (?) sometimes masks physical memory.
1628 // If you want to change the definition of a server class machine
1629 // on some OS or platform, e.g., >=4GB on Windows platforms,
1630 // then you'll have to parameterize this method based on that state,
1631 // as was done for logical processors here, or replicate and
1632 // specialize this method for each platform.  (Or fix os to have
1633 // some inheritance structure and use subclassing.  Sigh.)
1634 // If you want some platform to always or never behave as a server
1635 // class machine, change the setting of AlwaysActAsServerClassMachine
1636 // and NeverActAsServerClassMachine in globals*.hpp.
1637 bool os::is_server_class_machine() {
1638   // First check for the early returns
1639   if (NeverActAsServerClassMachine) {
1640     return false;
1641   }
1642   if (AlwaysActAsServerClassMachine) {
1643     return true;
1644   }
1645   // Then actually look at the machine
1646   bool         result            = false;
1647   const unsigned int    server_processors = 2;
1648   const julong server_memory     = 2UL * G;
1649   // We seem not to get our full complement of memory.
1650   //     We allow some part (1/8?) of the memory to be "missing",
1651   //     based on the sizes of DIMMs, and maybe graphics cards.
1652   const julong missing_memory   = 256UL * M;
1653 
1654   /* Is this a server class machine? */
1655   if ((os::active_processor_count() >= (int)server_processors) &&
1656       (os::physical_memory() >= (server_memory - missing_memory))) {
1657     const unsigned int logical_processors =
1658       VM_Version::logical_processors_per_package();
1659     if (logical_processors > 1) {
1660       const unsigned int physical_packages =
1661         os::active_processor_count() / logical_processors;
1662       if (physical_packages >= server_processors) {
1663         result = true;
1664       }
1665     } else {
1666       result = true;
1667     }
1668   }
1669   return result;
1670 }
1671 
1672 void os::initialize_initial_active_processor_count() {
1673   assert(_initial_active_processor_count == 0, "Initial active processor count already set.");
1674   _initial_active_processor_count = active_processor_count();
1675   log_debug(os)("Initial active processor count set to %d" , _initial_active_processor_count);
1676 }
1677 
1678 bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1679   return os::pd_create_stack_guard_pages(addr, bytes);
1680 }
1681 
1682 char* os::reserve_memory(size_t bytes, bool executable, MEMFLAGS flags) {
1683   char* result = pd_reserve_memory(bytes, executable);
1684   if (result != NULL) {
1685     MemTracker::record_virtual_memory_reserve(result, bytes, CALLER_PC, flags);
1686   }
1687   return result;
1688 }
1689 
1690 char* os::attempt_reserve_memory_at(char* addr, size_t bytes, bool executable) {
1691   char* result = pd_attempt_reserve_memory_at(addr, bytes, executable);
1692   if (result != NULL) {
1693     MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1694   } else {
1695     log_debug(os)("Attempt to reserve memory at " INTPTR_FORMAT " for "
1696                  SIZE_FORMAT " bytes failed, errno %d", p2i(addr), bytes, get_last_error());
1697   }
1698   return result;
1699 }
1700 
1701 static void assert_nonempty_range(const char* addr, size_t bytes) {
1702   assert(addr != nullptr && bytes > 0, "invalid range [" PTR_FORMAT ", " PTR_FORMAT ")",
1703          p2i(addr), p2i(addr) + bytes);
1704 }
1705 
1706 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1707   assert_nonempty_range(addr, bytes);
1708   bool res = pd_commit_memory(addr, bytes, executable);
1709   if (res) {
1710     MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1711   }
1712   return res;
1713 }
1714 
1715 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1716                               bool executable) {
1717   assert_nonempty_range(addr, size);
1718   bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1719   if (res) {
1720     MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1721   }
1722   return res;
1723 }
1724 
1725 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1726                                const char* mesg) {
1727   assert_nonempty_range(addr, bytes);
1728   pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1729   MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1730 }
1731 
1732 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1733                                bool executable, const char* mesg) {
1734   assert_nonempty_range(addr, size);
1735   os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1736   MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1737 }
1738 
1739 bool os::uncommit_memory(char* addr, size_t bytes, bool executable) {
1740   assert_nonempty_range(addr, bytes);
1741   bool res;
1742   if (MemTracker::enabled()) {
1743     Tracker tkr(Tracker::uncommit);
1744     res = pd_uncommit_memory(addr, bytes, executable);
1745     if (res) {
1746       tkr.record((address)addr, bytes);
1747     }
1748   } else {
1749     res = pd_uncommit_memory(addr, bytes, executable);
1750   }
1751   return res;
1752 }
1753 
1754 bool os::release_memory(char* addr, size_t bytes) {
1755   assert_nonempty_range(addr, bytes);
1756   bool res;
1757   if (MemTracker::enabled()) {
1758     // Note: Tracker contains a ThreadCritical.
1759     Tracker tkr(Tracker::release);
1760     res = pd_release_memory(addr, bytes);
1761     if (res) {
1762       tkr.record((address)addr, bytes);
1763     }
1764   } else {
1765     res = pd_release_memory(addr, bytes);
1766   }
1767   if (!res) {
1768     log_info(os)("os::release_memory failed (" PTR_FORMAT ", " SIZE_FORMAT ")", p2i(addr), bytes);
1769   }
1770   return res;
1771 }
1772 
1773 // Prints all mappings
1774 void os::print_memory_mappings(outputStream* st) {
1775   os::print_memory_mappings(nullptr, (size_t)-1, st);
1776 }
1777 
1778 // Pretouching must use a store, not just a load.  On many OSes loads from
1779 // fresh memory would be satisfied from a single mapped page containing all
1780 // zeros.  We need to store something to each page to get them backed by
1781 // their own memory, which is the effect we want here.  An atomic add of
1782 // zero is used instead of a simple store, allowing the memory to be used
1783 // while pretouch is in progress, rather than requiring users of the memory
1784 // to wait until the entire range has been touched.  This is technically
1785 // a UB data race, but doesn't cause any problems for us.
1786 void os::pretouch_memory(void* start, void* end, size_t page_size) {
1787   assert(start <= end, "invalid range: " PTR_FORMAT " -> " PTR_FORMAT, p2i(start), p2i(end));
1788   assert(is_power_of_2(page_size), "page size misaligned: %zu", page_size);
1789   assert(page_size >= sizeof(int), "page size too small: %zu", page_size);
1790   if (start < end) {
1791     // We're doing concurrent-safe touch and memory state has page
1792     // granularity, so we can touch anywhere in a page.  Touch at the
1793     // beginning of each page to simplify iteration.
1794     char* cur = static_cast<char*>(align_down(start, page_size));
1795     void* last = align_down(static_cast<char*>(end) - 1, page_size);
1796     assert(cur <= last, "invariant");
1797     // Iterate from first page through last (inclusive), being careful to
1798     // avoid overflow if the last page abuts the end of the address range.
1799     for ( ; true; cur += page_size) {
1800       Atomic::add(reinterpret_cast<int*>(cur), 0, memory_order_relaxed);
1801       if (cur >= last) break;
1802     }
1803   }
1804 }
1805 
1806 char* os::map_memory_to_file(size_t bytes, int file_desc) {
1807   // Could have called pd_reserve_memory() followed by replace_existing_mapping_with_file_mapping(),
1808   // but AIX may use SHM in which case its more trouble to detach the segment and remap memory to the file.
1809   // On all current implementations NULL is interpreted as any available address.
1810   char* result = os::map_memory_to_file(NULL /* addr */, bytes, file_desc);
1811   if (result != NULL) {
1812     MemTracker::record_virtual_memory_reserve_and_commit(result, bytes, CALLER_PC);
1813   }
1814   return result;
1815 }
1816 
1817 char* os::attempt_map_memory_to_file_at(char* addr, size_t bytes, int file_desc) {
1818   char* result = pd_attempt_map_memory_to_file_at(addr, bytes, file_desc);
1819   if (result != NULL) {
1820     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1821   }
1822   return result;
1823 }
1824 
1825 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1826                            char *addr, size_t bytes, bool read_only,
1827                            bool allow_exec, MEMFLAGS flags) {
1828   char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1829   if (result != NULL) {
1830     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC, flags);
1831   }
1832   return result;
1833 }
1834 
1835 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1836                              char *addr, size_t bytes, bool read_only,
1837                              bool allow_exec) {
1838   return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1839                     read_only, allow_exec);
1840 }
1841 
1842 bool os::unmap_memory(char *addr, size_t bytes) {
1843   bool result;
1844   if (MemTracker::enabled()) {
1845     Tracker tkr(Tracker::release);
1846     result = pd_unmap_memory(addr, bytes);
1847     if (result) {
1848       tkr.record((address)addr, bytes);
1849     }
1850   } else {
1851     result = pd_unmap_memory(addr, bytes);
1852   }
1853   return result;
1854 }
1855 
1856 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1857   pd_free_memory(addr, bytes, alignment_hint);
1858 }
1859 
1860 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1861   pd_realign_memory(addr, bytes, alignment_hint);
1862 }
1863 
1864 char* os::reserve_memory_special(size_t size, size_t alignment, size_t page_size,
1865                                  char* addr, bool executable) {
1866 
1867   assert(is_aligned(addr, alignment), "Unaligned request address");
1868 
1869   char* result = pd_reserve_memory_special(size, alignment, page_size, addr, executable);
1870   if (result != NULL) {
1871     // The memory is committed
1872     MemTracker::record_virtual_memory_reserve_and_commit((address)result, size, CALLER_PC);
1873   }
1874 
1875   return result;
1876 }
1877 
1878 bool os::release_memory_special(char* addr, size_t bytes) {
1879   bool res;
1880   if (MemTracker::enabled()) {
1881     // Note: Tracker contains a ThreadCritical.
1882     Tracker tkr(Tracker::release);
1883     res = pd_release_memory_special(addr, bytes);
1884     if (res) {
1885       tkr.record((address)addr, bytes);
1886     }
1887   } else {
1888     res = pd_release_memory_special(addr, bytes);
1889   }
1890   return res;
1891 }
1892 
1893 // Convenience wrapper around naked_short_sleep to allow for longer sleep
1894 // times. Only for use by non-JavaThreads.
1895 void os::naked_sleep(jlong millis) {
1896   assert(!Thread::current()->is_Java_thread(), "not for use by JavaThreads");
1897   const jlong limit = 999;
1898   while (millis > limit) {
1899     naked_short_sleep(limit);
1900     millis -= limit;
1901   }
1902   naked_short_sleep(millis);
1903 }
1904 
1905 
1906 ////// Implementation of PageSizes
1907 
1908 void os::PageSizes::add(size_t page_size) {
1909   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_X, page_size);
1910   _v |= page_size;
1911 }
1912 
1913 bool os::PageSizes::contains(size_t page_size) const {
1914   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_X, page_size);
1915   return (_v & page_size) != 0;
1916 }
1917 
1918 size_t os::PageSizes::next_smaller(size_t page_size) const {
1919   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_X, page_size);
1920   size_t v2 = _v & (page_size - 1);
1921   if (v2 == 0) {
1922     return 0;
1923   }
1924   return round_down_power_of_2(v2);
1925 }
1926 
1927 size_t os::PageSizes::next_larger(size_t page_size) const {
1928   assert(is_power_of_2(page_size), "page_size must be a power of 2: " SIZE_FORMAT_X, page_size);
1929   if (page_size == max_power_of_2<size_t>()) { // Shift by 32/64 would be UB
1930     return 0;
1931   }
1932   // Remove current and smaller page sizes
1933   size_t v2 = _v & ~(page_size + (page_size - 1));
1934   if (v2 == 0) {
1935     return 0;
1936   }
1937   return (size_t)1 << count_trailing_zeros(v2);
1938 }
1939 
1940 size_t os::PageSizes::largest() const {
1941   const size_t max = max_power_of_2<size_t>();
1942   if (contains(max)) {
1943     return max;
1944   }
1945   return next_smaller(max);
1946 }
1947 
1948 size_t os::PageSizes::smallest() const {
1949   // Strictly speaking the set should not contain sizes < os::vm_page_size().
1950   // But this is not enforced.
1951   return next_larger(1);
1952 }
1953 
1954 void os::PageSizes::print_on(outputStream* st) const {
1955   bool first = true;
1956   for (size_t sz = smallest(); sz != 0; sz = next_larger(sz)) {
1957     if (first) {
1958       first = false;
1959     } else {
1960       st->print_raw(", ");
1961     }
1962     if (sz < M) {
1963       st->print(SIZE_FORMAT "k", sz / K);
1964     } else if (sz < G) {
1965       st->print(SIZE_FORMAT "M", sz / M);
1966     } else {
1967       st->print(SIZE_FORMAT "G", sz / G);
1968     }
1969   }
1970   if (first) {
1971     st->print("empty");
1972   }
1973 }
1974 
1975 // Check minimum allowable stack sizes for thread creation and to initialize
1976 // the java system classes, including StackOverflowError - depends on page
1977 // size.
1978 // The space needed for frames during startup is platform dependent. It
1979 // depends on word size, platform calling conventions, C frame layout and
1980 // interpreter/C1/C2 design decisions. Therefore this is given in a
1981 // platform (os/cpu) dependent constant.
1982 // To this, space for guard mechanisms is added, which depends on the
1983 // page size which again depends on the concrete system the VM is running
1984 // on. Space for libc guard pages is not included in this size.
1985 jint os::set_minimum_stack_sizes() {
1986 
1987   _java_thread_min_stack_allowed = _java_thread_min_stack_allowed +
1988                                    StackOverflow::stack_guard_zone_size() +
1989                                    StackOverflow::stack_shadow_zone_size();
1990 
1991   _java_thread_min_stack_allowed = align_up(_java_thread_min_stack_allowed, vm_page_size());
1992   _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, _os_min_stack_allowed);
1993 
1994   size_t stack_size_in_bytes = ThreadStackSize * K;
1995   if (stack_size_in_bytes != 0 &&
1996       stack_size_in_bytes < _java_thread_min_stack_allowed) {
1997     // The '-Xss' and '-XX:ThreadStackSize=N' options both set
1998     // ThreadStackSize so we go with "Java thread stack size" instead
1999     // of "ThreadStackSize" to be more friendly.
2000     tty->print_cr("\nThe Java thread stack size specified is too small. "
2001                   "Specify at least " SIZE_FORMAT "k",
2002                   _java_thread_min_stack_allowed / K);
2003     return JNI_ERR;
2004   }
2005 
2006   // Make the stack size a multiple of the page size so that
2007   // the yellow/red zones can be guarded.
2008   JavaThread::set_stack_size_at_create(align_up(stack_size_in_bytes, vm_page_size()));
2009 
2010   // Reminder: a compiler thread is a Java thread.
2011   _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed +
2012                                        StackOverflow::stack_guard_zone_size() +
2013                                        StackOverflow::stack_shadow_zone_size();
2014 
2015   _compiler_thread_min_stack_allowed = align_up(_compiler_thread_min_stack_allowed, vm_page_size());
2016   _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, _os_min_stack_allowed);
2017 
2018   stack_size_in_bytes = CompilerThreadStackSize * K;
2019   if (stack_size_in_bytes != 0 &&
2020       stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
2021     tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
2022                   "Specify at least " SIZE_FORMAT "k",
2023                   _compiler_thread_min_stack_allowed / K);
2024     return JNI_ERR;
2025   }
2026 
2027   _vm_internal_thread_min_stack_allowed = align_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
2028   _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, _os_min_stack_allowed);
2029 
2030   stack_size_in_bytes = VMThreadStackSize * K;
2031   if (stack_size_in_bytes != 0 &&
2032       stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
2033     tty->print_cr("\nThe VMThreadStackSize specified is too small. "
2034                   "Specify at least " SIZE_FORMAT "k",
2035                   _vm_internal_thread_min_stack_allowed / K);
2036     return JNI_ERR;
2037   }
2038   return JNI_OK;
2039 }