1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "gc/shared/vmGCOperations.hpp"
  36 #include "logging/log.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #ifdef ASSERT
  42 #include "memory/guardedMemory.hpp"
  43 #endif
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "prims/jvm_misc.hpp"
  47 #include "prims/privilegedStack.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/atomic.hpp"
  50 #include "runtime/frame.inline.hpp"
  51 #include "runtime/interfaceSupport.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/javaCalls.hpp"
  54 #include "runtime/mutexLocker.hpp"
  55 #include "runtime/os.inline.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "runtime/thread.inline.hpp"
  58 #include "runtime/threadSMR.hpp"
  59 #include "runtime/vm_version.hpp"
  60 #include "services/attachListener.hpp"
  61 #include "services/mallocTracker.hpp"
  62 #include "services/memTracker.hpp"
  63 #include "services/nmtCommon.hpp"
  64 #include "services/threadService.hpp"
  65 #include "utilities/align.hpp"
  66 #include "utilities/defaultStream.hpp"
  67 #include "utilities/events.hpp"
  68 
  69 # include <signal.h>
  70 # include <errno.h>
  71 
  72 OSThread*         os::_starting_thread    = NULL;
  73 address           os::_polling_page       = NULL;
  74 volatile int32_t* os::_mem_serialize_page = NULL;
  75 uintptr_t         os::_serialize_page_mask = 0;
  76 volatile unsigned int os::_rand_seed      = 1;
  77 int               os::_processor_count    = 0;
  78 int               os::_initial_active_processor_count = 0;
  79 size_t            os::_page_sizes[os::page_sizes_max];
  80 
  81 #ifndef PRODUCT
  82 julong os::num_mallocs = 0;         // # of calls to malloc/realloc
  83 julong os::alloc_bytes = 0;         // # of bytes allocated
  84 julong os::num_frees = 0;           // # of calls to free
  85 julong os::free_bytes = 0;          // # of bytes freed
  86 #endif
  87 
  88 static size_t cur_malloc_words = 0;  // current size for MallocMaxTestWords
  89 
  90 void os_init_globals() {
  91   // Called from init_globals().
  92   // See Threads::create_vm() in thread.cpp, and init.cpp.
  93   os::init_globals();
  94 }
  95 
  96 // Fill in buffer with current local time as an ISO-8601 string.
  97 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
  98 // Returns buffer, or NULL if it failed.
  99 // This would mostly be a call to
 100 //     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
 101 // except that on Windows the %z behaves badly, so we do it ourselves.
 102 // Also, people wanted milliseconds on there,
 103 // and strftime doesn't do milliseconds.
 104 char* os::iso8601_time(char* buffer, size_t buffer_length, bool utc) {
 105   // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
 106   //                                      1         2
 107   //                             12345678901234567890123456789
 108   // format string: "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d"
 109   static const size_t needed_buffer = 29;
 110 
 111   // Sanity check the arguments
 112   if (buffer == NULL) {
 113     assert(false, "NULL buffer");
 114     return NULL;
 115   }
 116   if (buffer_length < needed_buffer) {
 117     assert(false, "buffer_length too small");
 118     return NULL;
 119   }
 120   // Get the current time
 121   jlong milliseconds_since_19700101 = javaTimeMillis();
 122   const int milliseconds_per_microsecond = 1000;
 123   const time_t seconds_since_19700101 =
 124     milliseconds_since_19700101 / milliseconds_per_microsecond;
 125   const int milliseconds_after_second =
 126     milliseconds_since_19700101 % milliseconds_per_microsecond;
 127   // Convert the time value to a tm and timezone variable
 128   struct tm time_struct;
 129   if (utc) {
 130     if (gmtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
 131       assert(false, "Failed gmtime_pd");
 132       return NULL;
 133     }
 134   } else {
 135     if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
 136       assert(false, "Failed localtime_pd");
 137       return NULL;
 138     }
 139   }
 140 #if defined(_ALLBSD_SOURCE)
 141   const time_t zone = (time_t) time_struct.tm_gmtoff;
 142 #else
 143   const time_t zone = timezone;
 144 #endif
 145 
 146   // If daylight savings time is in effect,
 147   // we are 1 hour East of our time zone
 148   const time_t seconds_per_minute = 60;
 149   const time_t minutes_per_hour = 60;
 150   const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
 151   time_t UTC_to_local = zone;
 152   if (time_struct.tm_isdst > 0) {
 153     UTC_to_local = UTC_to_local - seconds_per_hour;
 154   }
 155 
 156   // No offset when dealing with UTC
 157   if (utc) {
 158     UTC_to_local = 0;
 159   }
 160 
 161   // Compute the time zone offset.
 162   //    localtime_pd() sets timezone to the difference (in seconds)
 163   //    between UTC and and local time.
 164   //    ISO 8601 says we need the difference between local time and UTC,
 165   //    we change the sign of the localtime_pd() result.
 166   const time_t local_to_UTC = -(UTC_to_local);
 167   // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
 168   char sign_local_to_UTC = '+';
 169   time_t abs_local_to_UTC = local_to_UTC;
 170   if (local_to_UTC < 0) {
 171     sign_local_to_UTC = '-';
 172     abs_local_to_UTC = -(abs_local_to_UTC);
 173   }
 174   // Convert time zone offset seconds to hours and minutes.
 175   const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
 176   const time_t zone_min =
 177     ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
 178 
 179   // Print an ISO 8601 date and time stamp into the buffer
 180   const int year = 1900 + time_struct.tm_year;
 181   const int month = 1 + time_struct.tm_mon;
 182   const int printed = jio_snprintf(buffer, buffer_length,
 183                                    "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d",
 184                                    year,
 185                                    month,
 186                                    time_struct.tm_mday,
 187                                    time_struct.tm_hour,
 188                                    time_struct.tm_min,
 189                                    time_struct.tm_sec,
 190                                    milliseconds_after_second,
 191                                    sign_local_to_UTC,
 192                                    zone_hours,
 193                                    zone_min);
 194   if (printed == 0) {
 195     assert(false, "Failed jio_printf");
 196     return NULL;
 197   }
 198   return buffer;
 199 }
 200 
 201 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
 202   debug_only(Thread::check_for_dangling_thread_pointer(thread);)
 203 
 204   if (p >= MinPriority && p <= MaxPriority) {
 205     int priority = java_to_os_priority[p];
 206     return set_native_priority(thread, priority);
 207   } else {
 208     assert(false, "Should not happen");
 209     return OS_ERR;
 210   }
 211 }
 212 
 213 // The mapping from OS priority back to Java priority may be inexact because
 214 // Java priorities can map M:1 with native priorities. If you want the definite
 215 // Java priority then use JavaThread::java_priority()
 216 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
 217   int p;
 218   int os_prio;
 219   OSReturn ret = get_native_priority(thread, &os_prio);
 220   if (ret != OS_OK) return ret;
 221 
 222   if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
 223     for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
 224   } else {
 225     // niceness values are in reverse order
 226     for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
 227   }
 228   priority = (ThreadPriority)p;
 229   return OS_OK;
 230 }
 231 
 232 bool os::dll_build_name(char* buffer, size_t size, const char* fname) {
 233   int n = jio_snprintf(buffer, size, "%s%s%s", JNI_LIB_PREFIX, fname, JNI_LIB_SUFFIX);
 234   return (n != -1);
 235 }
 236 
 237 // Helper for dll_locate_lib.
 238 // Pass buffer and printbuffer as we already printed the path to buffer
 239 // when we called get_current_directory. This way we avoid another buffer
 240 // of size MAX_PATH.
 241 static bool conc_path_file_and_check(char *buffer, char *printbuffer, size_t printbuflen,
 242                                      const char* pname, char lastchar, const char* fname) {
 243 
 244   // Concatenate path and file name, but don't print double path separators.
 245   const char *filesep = (WINDOWS_ONLY(lastchar == ':' ||) lastchar == os::file_separator()[0]) ?
 246                         "" : os::file_separator();
 247   int ret = jio_snprintf(printbuffer, printbuflen, "%s%s%s", pname, filesep, fname);
 248   // Check whether file exists.
 249   if (ret != -1) {
 250     struct stat statbuf;
 251     return os::stat(buffer, &statbuf) == 0;
 252   }
 253   return false;
 254 }
 255 
 256 bool os::dll_locate_lib(char *buffer, size_t buflen,
 257                         const char* pname, const char* fname) {
 258   bool retval = false;
 259 
 260   size_t fullfnamelen = strlen(JNI_LIB_PREFIX) + strlen(fname) + strlen(JNI_LIB_SUFFIX);
 261   char* fullfname = (char*)NEW_C_HEAP_ARRAY(char, fullfnamelen + 1, mtInternal);
 262   if (dll_build_name(fullfname, fullfnamelen + 1, fname)) {
 263     const size_t pnamelen = pname ? strlen(pname) : 0;
 264 
 265     if (pnamelen == 0) {
 266       // If no path given, use current working directory.
 267       const char* p = get_current_directory(buffer, buflen);
 268       if (p != NULL) {
 269         const size_t plen = strlen(buffer);
 270         const char lastchar = buffer[plen - 1];
 271         retval = conc_path_file_and_check(buffer, &buffer[plen], buflen - plen,
 272                                           "", lastchar, fullfname);
 273       }
 274     } else if (strchr(pname, *os::path_separator()) != NULL) {
 275       // A list of paths. Search for the path that contains the library.
 276       int n;
 277       char** pelements = split_path(pname, &n);
 278       if (pelements != NULL) {
 279         for (int i = 0; i < n; i++) {
 280           char* path = pelements[i];
 281           // Really shouldn't be NULL, but check can't hurt.
 282           size_t plen = (path == NULL) ? 0 : strlen(path);
 283           if (plen == 0) {
 284             continue; // Skip the empty path values.
 285           }
 286           const char lastchar = path[plen - 1];
 287           retval = conc_path_file_and_check(buffer, buffer, buflen, path, lastchar, fullfname);
 288           if (retval) break;
 289         }
 290         // Release the storage allocated by split_path.
 291         for (int i = 0; i < n; i++) {
 292           if (pelements[i] != NULL) {
 293             FREE_C_HEAP_ARRAY(char, pelements[i]);
 294           }
 295         }
 296         FREE_C_HEAP_ARRAY(char*, pelements);
 297       }
 298     } else {
 299       // A definite path.
 300       const char lastchar = pname[pnamelen-1];
 301       retval = conc_path_file_and_check(buffer, buffer, buflen, pname, lastchar, fullfname);
 302     }
 303   }
 304 
 305   FREE_C_HEAP_ARRAY(char*, fullfname);
 306   return retval;
 307 }
 308 
 309 // --------------------- sun.misc.Signal (optional) ---------------------
 310 
 311 
 312 // SIGBREAK is sent by the keyboard to query the VM state
 313 #ifndef SIGBREAK
 314 #define SIGBREAK SIGQUIT
 315 #endif
 316 
 317 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
 318 
 319 
 320 static void signal_thread_entry(JavaThread* thread, TRAPS) {
 321   os::set_priority(thread, NearMaxPriority);
 322   while (true) {
 323     int sig;
 324     {
 325       // FIXME : Currently we have not decided what should be the status
 326       //         for this java thread blocked here. Once we decide about
 327       //         that we should fix this.
 328       sig = os::signal_wait();
 329     }
 330     if (sig == os::sigexitnum_pd()) {
 331        // Terminate the signal thread
 332        return;
 333     }
 334 
 335     switch (sig) {
 336       case SIGBREAK: {
 337         // Check if the signal is a trigger to start the Attach Listener - in that
 338         // case don't print stack traces.
 339         if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
 340           continue;
 341         }
 342         // Print stack traces
 343         // Any SIGBREAK operations added here should make sure to flush
 344         // the output stream (e.g. tty->flush()) after output.  See 4803766.
 345         // Each module also prints an extra carriage return after its output.
 346         VM_PrintThreads op;
 347         VMThread::execute(&op);
 348         VM_PrintJNI jni_op;
 349         VMThread::execute(&jni_op);
 350         VM_FindDeadlocks op1(tty);
 351         VMThread::execute(&op1);
 352         Universe::print_heap_at_SIGBREAK();
 353         if (PrintClassHistogram) {
 354           VM_GC_HeapInspection op1(tty, true /* force full GC before heap inspection */);
 355           VMThread::execute(&op1);
 356         }
 357         if (JvmtiExport::should_post_data_dump()) {
 358           JvmtiExport::post_data_dump();
 359         }
 360         break;
 361       }
 362       default: {
 363         // Dispatch the signal to java
 364         HandleMark hm(THREAD);
 365         Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_misc_Signal(), THREAD);
 366         if (klass != NULL) {
 367           JavaValue result(T_VOID);
 368           JavaCallArguments args;
 369           args.push_int(sig);
 370           JavaCalls::call_static(
 371             &result,
 372             klass,
 373             vmSymbols::dispatch_name(),
 374             vmSymbols::int_void_signature(),
 375             &args,
 376             THREAD
 377           );
 378         }
 379         if (HAS_PENDING_EXCEPTION) {
 380           // tty is initialized early so we don't expect it to be null, but
 381           // if it is we can't risk doing an initialization that might
 382           // trigger additional out-of-memory conditions
 383           if (tty != NULL) {
 384             char klass_name[256];
 385             char tmp_sig_name[16];
 386             const char* sig_name = "UNKNOWN";
 387             InstanceKlass::cast(PENDING_EXCEPTION->klass())->
 388               name()->as_klass_external_name(klass_name, 256);
 389             if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
 390               sig_name = tmp_sig_name;
 391             warning("Exception %s occurred dispatching signal %s to handler"
 392                     "- the VM may need to be forcibly terminated",
 393                     klass_name, sig_name );
 394           }
 395           CLEAR_PENDING_EXCEPTION;
 396         }
 397       }
 398     }
 399   }
 400 }
 401 
 402 void os::init_before_ergo() {
 403   initialize_initial_active_processor_count();
 404   // We need to initialize large page support here because ergonomics takes some
 405   // decisions depending on large page support and the calculated large page size.
 406   large_page_init();
 407 
 408   // We need to adapt the configured number of stack protection pages given
 409   // in 4K pages to the actual os page size. We must do this before setting
 410   // up minimal stack sizes etc. in os::init_2().
 411   JavaThread::set_stack_red_zone_size     (align_up(StackRedPages      * 4 * K, vm_page_size()));
 412   JavaThread::set_stack_yellow_zone_size  (align_up(StackYellowPages   * 4 * K, vm_page_size()));
 413   JavaThread::set_stack_reserved_zone_size(align_up(StackReservedPages * 4 * K, vm_page_size()));
 414   JavaThread::set_stack_shadow_zone_size  (align_up(StackShadowPages   * 4 * K, vm_page_size()));
 415 
 416   // VM version initialization identifies some characteristics of the
 417   // platform that are used during ergonomic decisions.
 418   VM_Version::init_before_ergo();
 419 }
 420 
 421 void os::signal_init(TRAPS) {
 422   if (!ReduceSignalUsage) {
 423     // Setup JavaThread for processing signals
 424     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
 425     InstanceKlass* ik = InstanceKlass::cast(k);
 426     instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 427 
 428     const char thread_name[] = "Signal Dispatcher";
 429     Handle string = java_lang_String::create_from_str(thread_name, CHECK);
 430 
 431     // Initialize thread_oop to put it into the system threadGroup
 432     Handle thread_group (THREAD, Universe::system_thread_group());
 433     JavaValue result(T_VOID);
 434     JavaCalls::call_special(&result, thread_oop,
 435                            ik,
 436                            vmSymbols::object_initializer_name(),
 437                            vmSymbols::threadgroup_string_void_signature(),
 438                            thread_group,
 439                            string,
 440                            CHECK);
 441 
 442     Klass* group = SystemDictionary::ThreadGroup_klass();
 443     JavaCalls::call_special(&result,
 444                             thread_group,
 445                             group,
 446                             vmSymbols::add_method_name(),
 447                             vmSymbols::thread_void_signature(),
 448                             thread_oop,         // ARG 1
 449                             CHECK);
 450 
 451     os::signal_init_pd();
 452 
 453     { MutexLocker mu(Threads_lock);
 454       JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
 455 
 456       // At this point it may be possible that no osthread was created for the
 457       // JavaThread due to lack of memory. We would have to throw an exception
 458       // in that case. However, since this must work and we do not allow
 459       // exceptions anyway, check and abort if this fails.
 460       if (signal_thread == NULL || signal_thread->osthread() == NULL) {
 461         vm_exit_during_initialization("java.lang.OutOfMemoryError",
 462                                       os::native_thread_creation_failed_msg());
 463       }
 464 
 465       java_lang_Thread::set_thread(thread_oop(), signal_thread);
 466       java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
 467       java_lang_Thread::set_daemon(thread_oop());
 468 
 469       signal_thread->set_threadObj(thread_oop());
 470       Threads::add(signal_thread);
 471       Thread::start(signal_thread);
 472     }
 473     // Handle ^BREAK
 474     os::signal(SIGBREAK, os::user_handler());
 475   }
 476 }
 477 
 478 
 479 void os::terminate_signal_thread() {
 480   if (!ReduceSignalUsage)
 481     signal_notify(sigexitnum_pd());
 482 }
 483 
 484 
 485 // --------------------- loading libraries ---------------------
 486 
 487 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
 488 extern struct JavaVM_ main_vm;
 489 
 490 static void* _native_java_library = NULL;
 491 
 492 void* os::native_java_library() {
 493   if (_native_java_library == NULL) {
 494     char buffer[JVM_MAXPATHLEN];
 495     char ebuf[1024];
 496 
 497     // Try to load verify dll first. In 1.3 java dll depends on it and is not
 498     // always able to find it when the loading executable is outside the JDK.
 499     // In order to keep working with 1.2 we ignore any loading errors.
 500     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 501                        "verify")) {
 502       dll_load(buffer, ebuf, sizeof(ebuf));
 503     }
 504 
 505     // Load java dll
 506     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 507                        "java")) {
 508       _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
 509     }
 510     if (_native_java_library == NULL) {
 511       vm_exit_during_initialization("Unable to load native library", ebuf);
 512     }
 513 
 514 #if defined(__OpenBSD__)
 515     // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
 516     // ignore errors
 517     if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
 518                        "net")) {
 519       dll_load(buffer, ebuf, sizeof(ebuf));
 520     }
 521 #endif
 522   }
 523   return _native_java_library;
 524 }
 525 
 526 /*
 527  * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
 528  * If check_lib == true then we are looking for an
 529  * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
 530  * this library is statically linked into the image.
 531  * If check_lib == false then we will look for the appropriate symbol in the
 532  * executable if agent_lib->is_static_lib() == true or in the shared library
 533  * referenced by 'handle'.
 534  */
 535 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
 536                               const char *syms[], size_t syms_len) {
 537   assert(agent_lib != NULL, "sanity check");
 538   const char *lib_name;
 539   void *handle = agent_lib->os_lib();
 540   void *entryName = NULL;
 541   char *agent_function_name;
 542   size_t i;
 543 
 544   // If checking then use the agent name otherwise test is_static_lib() to
 545   // see how to process this lookup
 546   lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
 547   for (i = 0; i < syms_len; i++) {
 548     agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
 549     if (agent_function_name == NULL) {
 550       break;
 551     }
 552     entryName = dll_lookup(handle, agent_function_name);
 553     FREE_C_HEAP_ARRAY(char, agent_function_name);
 554     if (entryName != NULL) {
 555       break;
 556     }
 557   }
 558   return entryName;
 559 }
 560 
 561 // See if the passed in agent is statically linked into the VM image.
 562 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
 563                             size_t syms_len) {
 564   void *ret;
 565   void *proc_handle;
 566   void *save_handle;
 567 
 568   assert(agent_lib != NULL, "sanity check");
 569   if (agent_lib->name() == NULL) {
 570     return false;
 571   }
 572   proc_handle = get_default_process_handle();
 573   // Check for Agent_OnLoad/Attach_lib_name function
 574   save_handle = agent_lib->os_lib();
 575   // We want to look in this process' symbol table.
 576   agent_lib->set_os_lib(proc_handle);
 577   ret = find_agent_function(agent_lib, true, syms, syms_len);
 578   if (ret != NULL) {
 579     // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
 580     agent_lib->set_valid();
 581     agent_lib->set_static_lib(true);
 582     return true;
 583   }
 584   agent_lib->set_os_lib(save_handle);
 585   return false;
 586 }
 587 
 588 // --------------------- heap allocation utilities ---------------------
 589 
 590 char *os::strdup(const char *str, MEMFLAGS flags) {
 591   size_t size = strlen(str);
 592   char *dup_str = (char *)malloc(size + 1, flags);
 593   if (dup_str == NULL) return NULL;
 594   strcpy(dup_str, str);
 595   return dup_str;
 596 }
 597 
 598 char* os::strdup_check_oom(const char* str, MEMFLAGS flags) {
 599   char* p = os::strdup(str, flags);
 600   if (p == NULL) {
 601     vm_exit_out_of_memory(strlen(str) + 1, OOM_MALLOC_ERROR, "os::strdup_check_oom");
 602   }
 603   return p;
 604 }
 605 
 606 
 607 #define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
 608 
 609 #ifdef ASSERT
 610 
 611 static void verify_memory(void* ptr) {
 612   GuardedMemory guarded(ptr);
 613   if (!guarded.verify_guards()) {
 614     LogTarget(Warning, malloc, free) lt;
 615     ResourceMark rm;
 616     LogStream ls(lt);
 617     ls.print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
 618     ls.print_cr("## memory stomp:");
 619     guarded.print_on(&ls);
 620     fatal("memory stomping error");
 621   }
 622 }
 623 
 624 #endif
 625 
 626 //
 627 // This function supports testing of the malloc out of memory
 628 // condition without really running the system out of memory.
 629 //
 630 static bool has_reached_max_malloc_test_peak(size_t alloc_size) {
 631   if (MallocMaxTestWords > 0) {
 632     size_t words = (alloc_size / BytesPerWord);
 633 
 634     if ((cur_malloc_words + words) > MallocMaxTestWords) {
 635       return true;
 636     }
 637     Atomic::add(words, &cur_malloc_words);
 638   }
 639   return false;
 640 }
 641 
 642 void* os::malloc(size_t size, MEMFLAGS flags) {
 643   return os::malloc(size, flags, CALLER_PC);
 644 }
 645 
 646 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 647   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
 648   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
 649 
 650   // Since os::malloc can be called when the libjvm.{dll,so} is
 651   // first loaded and we don't have a thread yet we must accept NULL also here.
 652   assert(!os::ThreadCrashProtection::is_crash_protected(Thread::current_or_null()),
 653          "malloc() not allowed when crash protection is set");
 654 
 655   if (size == 0) {
 656     // return a valid pointer if size is zero
 657     // if NULL is returned the calling functions assume out of memory.
 658     size = 1;
 659   }
 660 
 661   // NMT support
 662   NMT_TrackingLevel level = MemTracker::tracking_level();
 663   size_t            nmt_header_size = MemTracker::malloc_header_size(level);
 664 
 665 #ifndef ASSERT
 666   const size_t alloc_size = size + nmt_header_size;
 667 #else
 668   const size_t alloc_size = GuardedMemory::get_total_size(size + nmt_header_size);
 669   if (size + nmt_header_size > alloc_size) { // Check for rollover.
 670     return NULL;
 671   }
 672 #endif
 673 
 674   // For the test flag -XX:MallocMaxTestWords
 675   if (has_reached_max_malloc_test_peak(size)) {
 676     return NULL;
 677   }
 678 
 679   u_char* ptr;
 680   ptr = (u_char*)::malloc(alloc_size);
 681 
 682 #ifdef ASSERT
 683   if (ptr == NULL) {
 684     return NULL;
 685   }
 686   // Wrap memory with guard
 687   GuardedMemory guarded(ptr, size + nmt_header_size);
 688   ptr = guarded.get_user_ptr();
 689 #endif
 690   if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
 691     log_warning(malloc, free)("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, p2i(ptr));
 692     breakpoint();
 693   }
 694   debug_only(if (paranoid) verify_memory(ptr));
 695 
 696   // we do not track guard memory
 697   return MemTracker::record_malloc((address)ptr, size, memflags, stack, level);
 698 }
 699 
 700 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
 701   return os::realloc(memblock, size, flags, CALLER_PC);
 702 }
 703 
 704 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) {
 705 
 706   // For the test flag -XX:MallocMaxTestWords
 707   if (has_reached_max_malloc_test_peak(size)) {
 708     return NULL;
 709   }
 710 
 711   if (size == 0) {
 712     // return a valid pointer if size is zero
 713     // if NULL is returned the calling functions assume out of memory.
 714     size = 1;
 715   }
 716 
 717 #ifndef ASSERT
 718   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
 719   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
 720    // NMT support
 721   void* membase = MemTracker::record_free(memblock);
 722   NMT_TrackingLevel level = MemTracker::tracking_level();
 723   size_t  nmt_header_size = MemTracker::malloc_header_size(level);
 724   void* ptr = ::realloc(membase, size + nmt_header_size);
 725   return MemTracker::record_malloc(ptr, size, memflags, stack, level);
 726 #else
 727   if (memblock == NULL) {
 728     return os::malloc(size, memflags, stack);
 729   }
 730   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
 731     log_warning(malloc, free)("os::realloc caught " PTR_FORMAT, p2i(memblock));
 732     breakpoint();
 733   }
 734   // NMT support
 735   void* membase = MemTracker::malloc_base(memblock);
 736   verify_memory(membase);
 737   // always move the block
 738   void* ptr = os::malloc(size, memflags, stack);
 739   // Copy to new memory if malloc didn't fail
 740   if (ptr != NULL ) {
 741     GuardedMemory guarded(MemTracker::malloc_base(memblock));
 742     // Guard's user data contains NMT header
 743     size_t memblock_size = guarded.get_user_size() - MemTracker::malloc_header_size(memblock);
 744     memcpy(ptr, memblock, MIN2(size, memblock_size));
 745     if (paranoid) verify_memory(MemTracker::malloc_base(ptr));
 746     if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
 747       log_warning(malloc, free)("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, p2i(ptr));
 748       breakpoint();
 749     }
 750     os::free(memblock);
 751   }
 752   return ptr;
 753 #endif
 754 }
 755 
 756 
 757 void  os::free(void *memblock) {
 758   NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
 759 #ifdef ASSERT
 760   if (memblock == NULL) return;
 761   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
 762     log_warning(malloc, free)("os::free caught " PTR_FORMAT, p2i(memblock));
 763     breakpoint();
 764   }
 765   void* membase = MemTracker::record_free(memblock);
 766   verify_memory(membase);
 767 
 768   GuardedMemory guarded(membase);
 769   size_t size = guarded.get_user_size();
 770   inc_stat_counter(&free_bytes, size);
 771   membase = guarded.release_for_freeing();
 772   ::free(membase);
 773 #else
 774   void* membase = MemTracker::record_free(memblock);
 775   ::free(membase);
 776 #endif
 777 }
 778 
 779 void os::init_random(unsigned int initval) {
 780   _rand_seed = initval;
 781 }
 782 
 783 
 784 static int random_helper(unsigned int rand_seed) {
 785   /* standard, well-known linear congruential random generator with
 786    * next_rand = (16807*seed) mod (2**31-1)
 787    * see
 788    * (1) "Random Number Generators: Good Ones Are Hard to Find",
 789    *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
 790    * (2) "Two Fast Implementations of the 'Minimal Standard' Random
 791    *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
 792   */
 793   const unsigned int a = 16807;
 794   const unsigned int m = 2147483647;
 795   const int q = m / a;        assert(q == 127773, "weird math");
 796   const int r = m % a;        assert(r == 2836, "weird math");
 797 
 798   // compute az=2^31p+q
 799   unsigned int lo = a * (rand_seed & 0xFFFF);
 800   unsigned int hi = a * (rand_seed >> 16);
 801   lo += (hi & 0x7FFF) << 16;
 802 
 803   // if q overflowed, ignore the overflow and increment q
 804   if (lo > m) {
 805     lo &= m;
 806     ++lo;
 807   }
 808   lo += hi >> 15;
 809 
 810   // if (p+q) overflowed, ignore the overflow and increment (p+q)
 811   if (lo > m) {
 812     lo &= m;
 813     ++lo;
 814   }
 815   return lo;
 816 }
 817 
 818 int os::random() {
 819   // Make updating the random seed thread safe.
 820   while (true) {
 821     unsigned int seed = _rand_seed;
 822     unsigned int rand = random_helper(seed);
 823     if (Atomic::cmpxchg(rand, &_rand_seed, seed) == seed) {
 824       return static_cast<int>(rand);
 825     }
 826   }
 827 }
 828 
 829 // The INITIALIZED state is distinguished from the SUSPENDED state because the
 830 // conditions in which a thread is first started are different from those in which
 831 // a suspension is resumed.  These differences make it hard for us to apply the
 832 // tougher checks when starting threads that we want to do when resuming them.
 833 // However, when start_thread is called as a result of Thread.start, on a Java
 834 // thread, the operation is synchronized on the Java Thread object.  So there
 835 // cannot be a race to start the thread and hence for the thread to exit while
 836 // we are working on it.  Non-Java threads that start Java threads either have
 837 // to do so in a context in which races are impossible, or should do appropriate
 838 // locking.
 839 
 840 void os::start_thread(Thread* thread) {
 841   // guard suspend/resume
 842   MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
 843   OSThread* osthread = thread->osthread();
 844   osthread->set_state(RUNNABLE);
 845   pd_start_thread(thread);
 846 }
 847 
 848 void os::abort(bool dump_core) {
 849   abort(dump_core && CreateCoredumpOnCrash, NULL, NULL);
 850 }
 851 
 852 //---------------------------------------------------------------------------
 853 // Helper functions for fatal error handler
 854 
 855 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
 856   assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
 857 
 858   int cols = 0;
 859   int cols_per_line = 0;
 860   switch (unitsize) {
 861     case 1: cols_per_line = 16; break;
 862     case 2: cols_per_line = 8;  break;
 863     case 4: cols_per_line = 4;  break;
 864     case 8: cols_per_line = 2;  break;
 865     default: return;
 866   }
 867 
 868   address p = start;
 869   st->print(PTR_FORMAT ":   ", p2i(start));
 870   while (p < end) {
 871     switch (unitsize) {
 872       case 1: st->print("%02x", *(u1*)p); break;
 873       case 2: st->print("%04x", *(u2*)p); break;
 874       case 4: st->print("%08x", *(u4*)p); break;
 875       case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
 876     }
 877     p += unitsize;
 878     cols++;
 879     if (cols >= cols_per_line && p < end) {
 880        cols = 0;
 881        st->cr();
 882        st->print(PTR_FORMAT ":   ", p2i(p));
 883     } else {
 884        st->print(" ");
 885     }
 886   }
 887   st->cr();
 888 }
 889 
 890 void os::print_environment_variables(outputStream* st, const char** env_list) {
 891   if (env_list) {
 892     st->print_cr("Environment Variables:");
 893 
 894     for (int i = 0; env_list[i] != NULL; i++) {
 895       char *envvar = ::getenv(env_list[i]);
 896       if (envvar != NULL) {
 897         st->print("%s", env_list[i]);
 898         st->print("=");
 899         st->print_cr("%s", envvar);
 900       }
 901     }
 902   }
 903 }
 904 
 905 void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) {
 906   // cpu
 907   st->print("CPU:");
 908   st->print("total %d", os::processor_count());
 909   // It's not safe to query number of active processors after crash
 910   // st->print("(active %d)", os::active_processor_count()); but we can
 911   // print the initial number of active processors.
 912   // We access the raw value here because the assert in the accessor will
 913   // fail if the crash occurs before initialization of this value.
 914   st->print(" (initial active %d)", _initial_active_processor_count);
 915   st->print(" %s", VM_Version::features_string());
 916   st->cr();
 917   pd_print_cpu_info(st, buf, buflen);
 918 }
 919 
 920 // Print a one line string summarizing the cpu, number of cores, memory, and operating system version
 921 void os::print_summary_info(outputStream* st, char* buf, size_t buflen) {
 922   st->print("Host: ");
 923 #ifndef PRODUCT
 924   if (get_host_name(buf, buflen)) {
 925     st->print("%s, ", buf);
 926   }
 927 #endif // PRODUCT
 928   get_summary_cpu_info(buf, buflen);
 929   st->print("%s, ", buf);
 930   size_t mem = physical_memory()/G;
 931   if (mem == 0) {  // for low memory systems
 932     mem = physical_memory()/M;
 933     st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem);
 934   } else {
 935     st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem);
 936   }
 937   get_summary_os_info(buf, buflen);
 938   st->print_raw(buf);
 939   st->cr();
 940 }
 941 
 942 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
 943   const int secs_per_day  = 86400;
 944   const int secs_per_hour = 3600;
 945   const int secs_per_min  = 60;
 946 
 947   time_t tloc;
 948   (void)time(&tloc);
 949   char* timestring = ctime(&tloc);  // ctime adds newline.
 950   // edit out the newline
 951   char* nl = strchr(timestring, '\n');
 952   if (nl != NULL) {
 953     *nl = '\0';
 954   }
 955 
 956   struct tm tz;
 957   if (localtime_pd(&tloc, &tz) != NULL) {
 958     ::strftime(buf, buflen, "%Z", &tz);
 959     st->print("Time: %s %s", timestring, buf);
 960   } else {
 961     st->print("Time: %s", timestring);
 962   }
 963 
 964   double t = os::elapsedTime();
 965   // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
 966   //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
 967   //       before printf. We lost some precision, but who cares?
 968   int eltime = (int)t;  // elapsed time in seconds
 969 
 970   // print elapsed time in a human-readable format:
 971   int eldays = eltime / secs_per_day;
 972   int day_secs = eldays * secs_per_day;
 973   int elhours = (eltime - day_secs) / secs_per_hour;
 974   int hour_secs = elhours * secs_per_hour;
 975   int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
 976   int minute_secs = elmins * secs_per_min;
 977   int elsecs = (eltime - day_secs - hour_secs - minute_secs);
 978   st->print_cr(" elapsed time: %d seconds (%dd %dh %dm %ds)", eltime, eldays, elhours, elmins, elsecs);
 979 }
 980 
 981 // moved from debug.cpp (used to be find()) but still called from there
 982 // The verbose parameter is only set by the debug code in one case
 983 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
 984   address addr = (address)x;
 985   // Handle NULL first, so later checks don't need to protect against it.
 986   if (addr == NULL) {
 987     st->print_cr("0x0 is NULL");
 988     return;
 989   }
 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 (JNIHandles::is_local_handle((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, int file_desc) {
1669   char* result = NULL;
1670 
1671   if (file_desc != -1) {
1672     // Could have called pd_reserve_memory() followed by replace_existing_mapping_with_file_mapping(),
1673     // but AIX may use SHM in which case its more trouble to detach the segment and remap memory to the file.
1674     result = os::map_memory_to_file(addr, bytes, file_desc);
1675     if (result != NULL) {
1676       MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1677     }
1678   } else {
1679     result = pd_reserve_memory(bytes, addr, alignment_hint);
1680     if (result != NULL) {
1681       MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1682     }
1683   }
1684 
1685   return result;
1686 }
1687 
1688 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
1689    MEMFLAGS flags) {
1690   char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1691   if (result != NULL) {
1692     MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1693     MemTracker::record_virtual_memory_type((address)result, flags);
1694   }
1695 
1696   return result;
1697 }
1698 
1699 char* os::attempt_reserve_memory_at(size_t bytes, char* addr, int file_desc) {
1700   char* result = NULL;
1701   if (file_desc != -1) {
1702     result = pd_attempt_reserve_memory_at(bytes, addr, file_desc);
1703     if (result != NULL) {
1704       MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1705     }
1706   } else {
1707     result = pd_attempt_reserve_memory_at(bytes, addr);
1708     if (result != NULL) {
1709       MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1710     }
1711   }
1712   return result;
1713 }
1714 
1715 void os::split_reserved_memory(char *base, size_t size,
1716                                  size_t split, bool realloc) {
1717   pd_split_reserved_memory(base, size, split, realloc);
1718 }
1719 
1720 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1721   bool res = pd_commit_memory(addr, bytes, executable);
1722   if (res) {
1723     MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1724   }
1725   return res;
1726 }
1727 
1728 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1729                               bool executable) {
1730   bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1731   if (res) {
1732     MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1733   }
1734   return res;
1735 }
1736 
1737 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1738                                const char* mesg) {
1739   pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1740   MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1741 }
1742 
1743 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1744                                bool executable, const char* mesg) {
1745   os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1746   MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1747 }
1748 
1749 bool os::uncommit_memory(char* addr, size_t bytes) {
1750   bool res;
1751   if (MemTracker::tracking_level() > NMT_minimal) {
1752     Tracker tkr(Tracker::uncommit);
1753     res = pd_uncommit_memory(addr, bytes);
1754     if (res) {
1755       tkr.record((address)addr, bytes);
1756     }
1757   } else {
1758     res = pd_uncommit_memory(addr, bytes);
1759   }
1760   return res;
1761 }
1762 
1763 bool os::release_memory(char* addr, size_t bytes) {
1764   bool res;
1765   if (MemTracker::tracking_level() > NMT_minimal) {
1766     Tracker tkr(Tracker::release);
1767     res = pd_release_memory(addr, bytes);
1768     if (res) {
1769       tkr.record((address)addr, bytes);
1770     }
1771   } else {
1772     res = pd_release_memory(addr, bytes);
1773   }
1774   return res;
1775 }
1776 
1777 void os::pretouch_memory(void* start, void* end, size_t page_size) {
1778   for (volatile char *p = (char*)start; p < (char*)end; p += page_size) {
1779     *p = 0;
1780   }
1781 }
1782 
1783 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1784                            char *addr, size_t bytes, bool read_only,
1785                            bool allow_exec) {
1786   char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1787   if (result != NULL) {
1788     MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1789   }
1790   return result;
1791 }
1792 
1793 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1794                              char *addr, size_t bytes, bool read_only,
1795                              bool allow_exec) {
1796   return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1797                     read_only, allow_exec);
1798 }
1799 
1800 bool os::unmap_memory(char *addr, size_t bytes) {
1801   bool result;
1802   if (MemTracker::tracking_level() > NMT_minimal) {
1803     Tracker tkr(Tracker::release);
1804     result = pd_unmap_memory(addr, bytes);
1805     if (result) {
1806       tkr.record((address)addr, bytes);
1807     }
1808   } else {
1809     result = pd_unmap_memory(addr, bytes);
1810   }
1811   return result;
1812 }
1813 
1814 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1815   pd_free_memory(addr, bytes, alignment_hint);
1816 }
1817 
1818 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1819   pd_realign_memory(addr, bytes, alignment_hint);
1820 }
1821 
1822 #ifndef _WINDOWS
1823 /* try to switch state from state "from" to state "to"
1824  * returns the state set after the method is complete
1825  */
1826 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1827                                                          os::SuspendResume::State to)
1828 {
1829   os::SuspendResume::State result = Atomic::cmpxchg(to, &_state, from);
1830   if (result == from) {
1831     // success
1832     return to;
1833   }
1834   return result;
1835 }
1836 #endif