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