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