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