src/share/vm/runtime/os.cpp

Fri, 06 Dec 2019 12:42:29 +0100

author
mbaesken
date
Fri, 06 Dec 2019 12:42:29 +0100
changeset 9946
103d1261f1f4
parent 9891
4904bded9702
child 9931
fd44df5e3bc3
child 9950
f3ceb2e8bd21
permissions
-rw-r--r--

8235243: handle VS2017 15.9 and VS2019 in abstract_vm_version
8235325: build failure on Linux after 8235243
Reviewed-by: dholmes, mdoerr

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

mercurial