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