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