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