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