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