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