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