src/share/vm/runtime/os.cpp

Wed, 27 Aug 2014 08:19:12 -0400

author
zgu
date
Wed, 27 Aug 2014 08:19:12 -0400
changeset 7074
833b0f92429a
parent 7032
fa62fb12cdca
child 7177
ed3d653e4012
permissions
-rw-r--r--

8046598: Scalable Native memory tracking development
Summary: Enhance scalability of native memory tracking
Reviewed-by: coleenp, ctornqvi, gtriantafill

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

mercurial