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