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