src/share/vm/runtime/os.cpp

Tue, 23 Nov 2010 13:22:55 -0800

author
stefank
date
Tue, 23 Nov 2010 13:22:55 -0800
changeset 2314
f95d63e2154a
parent 2262
1e9a9d2e6509
child 2322
828eafbd85cc
permissions
-rw-r--r--

6989984: Use standard include model for Hospot
Summary: Replaced MakeDeps and the includeDB files with more standardized solutions.
Reviewed-by: coleenp, kvn, kamg

     1 /*
     2  * Copyright (c) 1997, 2010, 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 #include "oops/oop.inline.hpp"
    36 #include "prims/jvm.h"
    37 #include "prims/jvm_misc.hpp"
    38 #include "prims/privilegedStack.hpp"
    39 #include "runtime/arguments.hpp"
    40 #include "runtime/frame.inline.hpp"
    41 #include "runtime/hpi.hpp"
    42 #include "runtime/interfaceSupport.hpp"
    43 #include "runtime/java.hpp"
    44 #include "runtime/javaCalls.hpp"
    45 #include "runtime/mutexLocker.hpp"
    46 #include "runtime/os.hpp"
    47 #include "runtime/stubRoutines.hpp"
    48 #include "services/attachListener.hpp"
    49 #include "services/threadService.hpp"
    50 #include "utilities/defaultStream.hpp"
    51 #include "utilities/events.hpp"
    52 #ifdef TARGET_OS_FAMILY_linux
    53 # include "os_linux.inline.hpp"
    54 # include "thread_linux.inline.hpp"
    55 #endif
    56 #ifdef TARGET_OS_FAMILY_solaris
    57 # include "os_solaris.inline.hpp"
    58 # include "thread_solaris.inline.hpp"
    59 #endif
    60 #ifdef TARGET_OS_FAMILY_windows
    61 # include "os_windows.inline.hpp"
    62 # include "thread_windows.inline.hpp"
    63 #endif
    65 # include <signal.h>
    67 OSThread*         os::_starting_thread    = NULL;
    68 address           os::_polling_page       = NULL;
    69 volatile int32_t* os::_mem_serialize_page = NULL;
    70 uintptr_t         os::_serialize_page_mask = 0;
    71 long              os::_rand_seed          = 1;
    72 int               os::_processor_count    = 0;
    73 size_t            os::_page_sizes[os::page_sizes_max];
    75 #ifndef PRODUCT
    76 int os::num_mallocs = 0;            // # of calls to malloc/realloc
    77 size_t os::alloc_bytes = 0;         // # of bytes allocated
    78 int os::num_frees = 0;              // # of calls to free
    79 #endif
    81 // Fill in buffer with current local time as an ISO-8601 string.
    82 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
    83 // Returns buffer, or NULL if it failed.
    84 // This would mostly be a call to
    85 //     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
    86 // except that on Windows the %z behaves badly, so we do it ourselves.
    87 // Also, people wanted milliseconds on there,
    88 // and strftime doesn't do milliseconds.
    89 char* os::iso8601_time(char* buffer, size_t buffer_length) {
    90   // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
    91   //                                      1         2
    92   //                             12345678901234567890123456789
    93   static const char* iso8601_format =
    94     "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
    95   static const size_t needed_buffer = 29;
    97   // Sanity check the arguments
    98   if (buffer == NULL) {
    99     assert(false, "NULL buffer");
   100     return NULL;
   101   }
   102   if (buffer_length < needed_buffer) {
   103     assert(false, "buffer_length too small");
   104     return NULL;
   105   }
   106   // Get the current time
   107   jlong milliseconds_since_19700101 = javaTimeMillis();
   108   const int milliseconds_per_microsecond = 1000;
   109   const time_t seconds_since_19700101 =
   110     milliseconds_since_19700101 / milliseconds_per_microsecond;
   111   const int milliseconds_after_second =
   112     milliseconds_since_19700101 % milliseconds_per_microsecond;
   113   // Convert the time value to a tm and timezone variable
   114   struct tm time_struct;
   115   if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
   116     assert(false, "Failed localtime_pd");
   117     return NULL;
   118   }
   119   const time_t zone = timezone;
   121   // If daylight savings time is in effect,
   122   // we are 1 hour East of our time zone
   123   const time_t seconds_per_minute = 60;
   124   const time_t minutes_per_hour = 60;
   125   const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
   126   time_t UTC_to_local = zone;
   127   if (time_struct.tm_isdst > 0) {
   128     UTC_to_local = UTC_to_local - seconds_per_hour;
   129   }
   130   // Compute the time zone offset.
   131   //    localtime_pd() sets timezone to the difference (in seconds)
   132   //    between UTC and and local time.
   133   //    ISO 8601 says we need the difference between local time and UTC,
   134   //    we change the sign of the localtime_pd() result.
   135   const time_t local_to_UTC = -(UTC_to_local);
   136   // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
   137   char sign_local_to_UTC = '+';
   138   time_t abs_local_to_UTC = local_to_UTC;
   139   if (local_to_UTC < 0) {
   140     sign_local_to_UTC = '-';
   141     abs_local_to_UTC = -(abs_local_to_UTC);
   142   }
   143   // Convert time zone offset seconds to hours and minutes.
   144   const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
   145   const time_t zone_min =
   146     ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
   148   // Print an ISO 8601 date and time stamp into the buffer
   149   const int year = 1900 + time_struct.tm_year;
   150   const int month = 1 + time_struct.tm_mon;
   151   const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
   152                                    year,
   153                                    month,
   154                                    time_struct.tm_mday,
   155                                    time_struct.tm_hour,
   156                                    time_struct.tm_min,
   157                                    time_struct.tm_sec,
   158                                    milliseconds_after_second,
   159                                    sign_local_to_UTC,
   160                                    zone_hours,
   161                                    zone_min);
   162   if (printed == 0) {
   163     assert(false, "Failed jio_printf");
   164     return NULL;
   165   }
   166   return buffer;
   167 }
   169 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
   170 #ifdef ASSERT
   171   if (!(!thread->is_Java_thread() ||
   172          Thread::current() == thread  ||
   173          Threads_lock->owned_by_self()
   174          || thread->is_Compiler_thread()
   175         )) {
   176     assert(false, "possibility of dangling Thread pointer");
   177   }
   178 #endif
   180   if (p >= MinPriority && p <= MaxPriority) {
   181     int priority = java_to_os_priority[p];
   182     return set_native_priority(thread, priority);
   183   } else {
   184     assert(false, "Should not happen");
   185     return OS_ERR;
   186   }
   187 }
   190 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
   191   int p;
   192   int os_prio;
   193   OSReturn ret = get_native_priority(thread, &os_prio);
   194   if (ret != OS_OK) return ret;
   196   for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
   197   priority = (ThreadPriority)p;
   198   return OS_OK;
   199 }
   202 // --------------------- sun.misc.Signal (optional) ---------------------
   205 // SIGBREAK is sent by the keyboard to query the VM state
   206 #ifndef SIGBREAK
   207 #define SIGBREAK SIGQUIT
   208 #endif
   210 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
   213 static void signal_thread_entry(JavaThread* thread, TRAPS) {
   214   os::set_priority(thread, NearMaxPriority);
   215   while (true) {
   216     int sig;
   217     {
   218       // FIXME : Currently we have not decieded what should be the status
   219       //         for this java thread blocked here. Once we decide about
   220       //         that we should fix this.
   221       sig = os::signal_wait();
   222     }
   223     if (sig == os::sigexitnum_pd()) {
   224        // Terminate the signal thread
   225        return;
   226     }
   228     switch (sig) {
   229       case SIGBREAK: {
   230         // Check if the signal is a trigger to start the Attach Listener - in that
   231         // case don't print stack traces.
   232         if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
   233           continue;
   234         }
   235         // Print stack traces
   236         // Any SIGBREAK operations added here should make sure to flush
   237         // the output stream (e.g. tty->flush()) after output.  See 4803766.
   238         // Each module also prints an extra carriage return after its output.
   239         VM_PrintThreads op;
   240         VMThread::execute(&op);
   241         VM_PrintJNI jni_op;
   242         VMThread::execute(&jni_op);
   243         VM_FindDeadlocks op1(tty);
   244         VMThread::execute(&op1);
   245         Universe::print_heap_at_SIGBREAK();
   246         if (PrintClassHistogram) {
   247           VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,
   248                                    true /* need_prologue */);
   249           VMThread::execute(&op1);
   250         }
   251         if (JvmtiExport::should_post_data_dump()) {
   252           JvmtiExport::post_data_dump();
   253         }
   254         break;
   255       }
   256       default: {
   257         // Dispatch the signal to java
   258         HandleMark hm(THREAD);
   259         klassOop k = SystemDictionary::resolve_or_null(vmSymbolHandles::sun_misc_Signal(), THREAD);
   260         KlassHandle klass (THREAD, k);
   261         if (klass.not_null()) {
   262           JavaValue result(T_VOID);
   263           JavaCallArguments args;
   264           args.push_int(sig);
   265           JavaCalls::call_static(
   266             &result,
   267             klass,
   268             vmSymbolHandles::dispatch_name(),
   269             vmSymbolHandles::int_void_signature(),
   270             &args,
   271             THREAD
   272           );
   273         }
   274         if (HAS_PENDING_EXCEPTION) {
   275           // tty is initialized early so we don't expect it to be null, but
   276           // if it is we can't risk doing an initialization that might
   277           // trigger additional out-of-memory conditions
   278           if (tty != NULL) {
   279             char klass_name[256];
   280             char tmp_sig_name[16];
   281             const char* sig_name = "UNKNOWN";
   282             instanceKlass::cast(PENDING_EXCEPTION->klass())->
   283               name()->as_klass_external_name(klass_name, 256);
   284             if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
   285               sig_name = tmp_sig_name;
   286             warning("Exception %s occurred dispatching signal %s to handler"
   287                     "- the VM may need to be forcibly terminated",
   288                     klass_name, sig_name );
   289           }
   290           CLEAR_PENDING_EXCEPTION;
   291         }
   292       }
   293     }
   294   }
   295 }
   298 void os::signal_init() {
   299   if (!ReduceSignalUsage) {
   300     // Setup JavaThread for processing signals
   301     EXCEPTION_MARK;
   302     klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(), true, CHECK);
   303     instanceKlassHandle klass (THREAD, k);
   304     instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
   306     const char thread_name[] = "Signal Dispatcher";
   307     Handle string = java_lang_String::create_from_str(thread_name, CHECK);
   309     // Initialize thread_oop to put it into the system threadGroup
   310     Handle thread_group (THREAD, Universe::system_thread_group());
   311     JavaValue result(T_VOID);
   312     JavaCalls::call_special(&result, thread_oop,
   313                            klass,
   314                            vmSymbolHandles::object_initializer_name(),
   315                            vmSymbolHandles::threadgroup_string_void_signature(),
   316                            thread_group,
   317                            string,
   318                            CHECK);
   320     KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
   321     JavaCalls::call_special(&result,
   322                             thread_group,
   323                             group,
   324                             vmSymbolHandles::add_method_name(),
   325                             vmSymbolHandles::thread_void_signature(),
   326                             thread_oop,         // ARG 1
   327                             CHECK);
   329     os::signal_init_pd();
   331     { MutexLocker mu(Threads_lock);
   332       JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
   334       // At this point it may be possible that no osthread was created for the
   335       // JavaThread due to lack of memory. We would have to throw an exception
   336       // in that case. However, since this must work and we do not allow
   337       // exceptions anyway, check and abort if this fails.
   338       if (signal_thread == NULL || signal_thread->osthread() == NULL) {
   339         vm_exit_during_initialization("java.lang.OutOfMemoryError",
   340                                       "unable to create new native thread");
   341       }
   343       java_lang_Thread::set_thread(thread_oop(), signal_thread);
   344       java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   345       java_lang_Thread::set_daemon(thread_oop());
   347       signal_thread->set_threadObj(thread_oop());
   348       Threads::add(signal_thread);
   349       Thread::start(signal_thread);
   350     }
   351     // Handle ^BREAK
   352     os::signal(SIGBREAK, os::user_handler());
   353   }
   354 }
   357 void os::terminate_signal_thread() {
   358   if (!ReduceSignalUsage)
   359     signal_notify(sigexitnum_pd());
   360 }
   363 // --------------------- loading libraries ---------------------
   365 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
   366 extern struct JavaVM_ main_vm;
   368 static void* _native_java_library = NULL;
   370 void* os::native_java_library() {
   371   if (_native_java_library == NULL) {
   372     char buffer[JVM_MAXPATHLEN];
   373     char ebuf[1024];
   375     // Try to load verify dll first. In 1.3 java dll depends on it and is not
   376     // always able to find it when the loading executable is outside the JDK.
   377     // In order to keep working with 1.2 we ignore any loading errors.
   378     dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "verify");
   379     dll_load(buffer, ebuf, sizeof(ebuf));
   381     // Load java dll
   382     dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "java");
   383     _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
   384     if (_native_java_library == NULL) {
   385       vm_exit_during_initialization("Unable to load native library", ebuf);
   386     }
   387   }
   388   static jboolean onLoaded = JNI_FALSE;
   389   if (onLoaded) {
   390     // We may have to wait to fire OnLoad until TLS is initialized.
   391     if (ThreadLocalStorage::is_initialized()) {
   392       // The JNI_OnLoad handling is normally done by method load in
   393       // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
   394       // explicitly so we have to check for JNI_OnLoad as well
   395       const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
   396       JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
   397           JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
   398       if (JNI_OnLoad != NULL) {
   399         JavaThread* thread = JavaThread::current();
   400         ThreadToNativeFromVM ttn(thread);
   401         HandleMark hm(thread);
   402         jint ver = (*JNI_OnLoad)(&main_vm, NULL);
   403         onLoaded = JNI_TRUE;
   404         if (!Threads::is_supported_jni_version_including_1_1(ver)) {
   405           vm_exit_during_initialization("Unsupported JNI version");
   406         }
   407       }
   408     }
   409   }
   410   return _native_java_library;
   411 }
   413 // --------------------- heap allocation utilities ---------------------
   415 char *os::strdup(const char *str) {
   416   size_t size = strlen(str);
   417   char *dup_str = (char *)malloc(size + 1);
   418   if (dup_str == NULL) return NULL;
   419   strcpy(dup_str, str);
   420   return dup_str;
   421 }
   425 #ifdef ASSERT
   426 #define space_before             (MallocCushion + sizeof(double))
   427 #define space_after              MallocCushion
   428 #define size_addr_from_base(p)   (size_t*)(p + space_before - sizeof(size_t))
   429 #define size_addr_from_obj(p)    ((size_t*)p - 1)
   430 // MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
   431 // NB: cannot be debug variable, because these aren't set from the command line until
   432 // *after* the first few allocs already happened
   433 #define MallocCushion            16
   434 #else
   435 #define space_before             0
   436 #define space_after              0
   437 #define size_addr_from_base(p)   should not use w/o ASSERT
   438 #define size_addr_from_obj(p)    should not use w/o ASSERT
   439 #define MallocCushion            0
   440 #endif
   441 #define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
   443 #ifdef ASSERT
   444 inline size_t get_size(void* obj) {
   445   size_t size = *size_addr_from_obj(obj);
   446   if (size < 0) {
   447     fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten ("
   448                   SIZE_FORMAT ")", obj, size));
   449   }
   450   return size;
   451 }
   453 u_char* find_cushion_backwards(u_char* start) {
   454   u_char* p = start;
   455   while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
   456          p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
   457   // ok, we have four consecutive marker bytes; find start
   458   u_char* q = p - 4;
   459   while (*q == badResourceValue) q--;
   460   return q + 1;
   461 }
   463 u_char* find_cushion_forwards(u_char* start) {
   464   u_char* p = start;
   465   while (p[0] != badResourceValue || p[1] != badResourceValue ||
   466          p[2] != badResourceValue || p[3] != badResourceValue) p++;
   467   // ok, we have four consecutive marker bytes; find end of cushion
   468   u_char* q = p + 4;
   469   while (*q == badResourceValue) q++;
   470   return q - MallocCushion;
   471 }
   473 void print_neighbor_blocks(void* ptr) {
   474   // find block allocated before ptr (not entirely crash-proof)
   475   if (MallocCushion < 4) {
   476     tty->print_cr("### cannot find previous block (MallocCushion < 4)");
   477     return;
   478   }
   479   u_char* start_of_this_block = (u_char*)ptr - space_before;
   480   u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
   481   // look for cushion in front of prev. block
   482   u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
   483   ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
   484   u_char* obj = start_of_prev_block + space_before;
   485   if (size <= 0 ) {
   486     // start is bad; mayhave been confused by OS data inbetween objects
   487     // search one more backwards
   488     start_of_prev_block = find_cushion_backwards(start_of_prev_block);
   489     size = *size_addr_from_base(start_of_prev_block);
   490     obj = start_of_prev_block + space_before;
   491   }
   493   if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
   494     tty->print_cr("### previous object: %p (%ld bytes)", obj, size);
   495   } else {
   496     tty->print_cr("### previous object (not sure if correct): %p (%ld bytes)", obj, size);
   497   }
   499   // now find successor block
   500   u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
   501   start_of_next_block = find_cushion_forwards(start_of_next_block);
   502   u_char* next_obj = start_of_next_block + space_before;
   503   ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
   504   if (start_of_next_block[0] == badResourceValue &&
   505       start_of_next_block[1] == badResourceValue &&
   506       start_of_next_block[2] == badResourceValue &&
   507       start_of_next_block[3] == badResourceValue) {
   508     tty->print_cr("### next object: %p (%ld bytes)", next_obj, next_size);
   509   } else {
   510     tty->print_cr("### next object (not sure if correct): %p (%ld bytes)", next_obj, next_size);
   511   }
   512 }
   515 void report_heap_error(void* memblock, void* bad, const char* where) {
   516   tty->print_cr("## nof_mallocs = %d, nof_frees = %d", os::num_mallocs, os::num_frees);
   517   tty->print_cr("## memory stomp: byte at %p %s object %p", bad, where, memblock);
   518   print_neighbor_blocks(memblock);
   519   fatal("memory stomping error");
   520 }
   522 void verify_block(void* memblock) {
   523   size_t size = get_size(memblock);
   524   if (MallocCushion) {
   525     u_char* ptr = (u_char*)memblock - space_before;
   526     for (int i = 0; i < MallocCushion; i++) {
   527       if (ptr[i] != badResourceValue) {
   528         report_heap_error(memblock, ptr+i, "in front of");
   529       }
   530     }
   531     u_char* end = (u_char*)memblock + size + space_after;
   532     for (int j = -MallocCushion; j < 0; j++) {
   533       if (end[j] != badResourceValue) {
   534         report_heap_error(memblock, end+j, "after");
   535       }
   536     }
   537   }
   538 }
   539 #endif
   541 void* os::malloc(size_t size) {
   542   NOT_PRODUCT(num_mallocs++);
   543   NOT_PRODUCT(alloc_bytes += size);
   545   if (size == 0) {
   546     // return a valid pointer if size is zero
   547     // if NULL is returned the calling functions assume out of memory.
   548     size = 1;
   549   }
   551   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   552   u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
   553 #ifdef ASSERT
   554   if (ptr == NULL) return NULL;
   555   if (MallocCushion) {
   556     for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
   557     u_char* end = ptr + space_before + size;
   558     for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
   559     for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
   560   }
   561   // put size just before data
   562   *size_addr_from_base(ptr) = size;
   563 #endif
   564   u_char* memblock = ptr + space_before;
   565   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   566     tty->print_cr("os::malloc caught, %lu bytes --> %p", size, memblock);
   567     breakpoint();
   568   }
   569   debug_only(if (paranoid) verify_block(memblock));
   570   if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc %lu bytes --> %p", size, memblock);
   571   return memblock;
   572 }
   575 void* os::realloc(void *memblock, size_t size) {
   576   NOT_PRODUCT(num_mallocs++);
   577   NOT_PRODUCT(alloc_bytes += size);
   578 #ifndef ASSERT
   579   return ::realloc(memblock, size);
   580 #else
   581   if (memblock == NULL) {
   582     return os::malloc(size);
   583   }
   584   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   585     tty->print_cr("os::realloc caught %p", memblock);
   586     breakpoint();
   587   }
   588   verify_block(memblock);
   589   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   590   if (size == 0) return NULL;
   591   // always move the block
   592   void* ptr = malloc(size);
   593   if (PrintMalloc) tty->print_cr("os::remalloc %lu bytes, %p --> %p", size, memblock, ptr);
   594   // Copy to new memory if malloc didn't fail
   595   if ( ptr != NULL ) {
   596     memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
   597     if (paranoid) verify_block(ptr);
   598     if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
   599       tty->print_cr("os::realloc caught, %lu bytes --> %p", size, ptr);
   600       breakpoint();
   601     }
   602     free(memblock);
   603   }
   604   return ptr;
   605 #endif
   606 }
   609 void  os::free(void *memblock) {
   610   NOT_PRODUCT(num_frees++);
   611 #ifdef ASSERT
   612   if (memblock == NULL) return;
   613   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   614     if (tty != NULL) tty->print_cr("os::free caught %p", memblock);
   615     breakpoint();
   616   }
   617   verify_block(memblock);
   618   if (PrintMalloc && tty != NULL)
   619     // tty->print_cr("os::free %p", memblock);
   620     fprintf(stderr, "os::free %p\n", memblock);
   621   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   622   // Added by detlefs.
   623   if (MallocCushion) {
   624     u_char* ptr = (u_char*)memblock - space_before;
   625     for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
   626       guarantee(*p == badResourceValue,
   627                 "Thing freed should be malloc result.");
   628       *p = (u_char)freeBlockPad;
   629     }
   630     size_t size = get_size(memblock);
   631     u_char* end = ptr + space_before + size;
   632     for (u_char* q = end; q < end + MallocCushion; q++) {
   633       guarantee(*q == badResourceValue,
   634                 "Thing freed should be malloc result.");
   635       *q = (u_char)freeBlockPad;
   636     }
   637   }
   638 #endif
   639   ::free((char*)memblock - space_before);
   640 }
   642 void os::init_random(long initval) {
   643   _rand_seed = initval;
   644 }
   647 long os::random() {
   648   /* standard, well-known linear congruential random generator with
   649    * next_rand = (16807*seed) mod (2**31-1)
   650    * see
   651    * (1) "Random Number Generators: Good Ones Are Hard to Find",
   652    *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
   653    * (2) "Two Fast Implementations of the 'Minimal Standard' Random
   654    *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
   655   */
   656   const long a = 16807;
   657   const unsigned long m = 2147483647;
   658   const long q = m / a;        assert(q == 127773, "weird math");
   659   const long r = m % a;        assert(r == 2836, "weird math");
   661   // compute az=2^31p+q
   662   unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
   663   unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
   664   lo += (hi & 0x7FFF) << 16;
   666   // if q overflowed, ignore the overflow and increment q
   667   if (lo > m) {
   668     lo &= m;
   669     ++lo;
   670   }
   671   lo += hi >> 15;
   673   // if (p+q) overflowed, ignore the overflow and increment (p+q)
   674   if (lo > m) {
   675     lo &= m;
   676     ++lo;
   677   }
   678   return (_rand_seed = lo);
   679 }
   681 // The INITIALIZED state is distinguished from the SUSPENDED state because the
   682 // conditions in which a thread is first started are different from those in which
   683 // a suspension is resumed.  These differences make it hard for us to apply the
   684 // tougher checks when starting threads that we want to do when resuming them.
   685 // However, when start_thread is called as a result of Thread.start, on a Java
   686 // thread, the operation is synchronized on the Java Thread object.  So there
   687 // cannot be a race to start the thread and hence for the thread to exit while
   688 // we are working on it.  Non-Java threads that start Java threads either have
   689 // to do so in a context in which races are impossible, or should do appropriate
   690 // locking.
   692 void os::start_thread(Thread* thread) {
   693   // guard suspend/resume
   694   MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
   695   OSThread* osthread = thread->osthread();
   696   osthread->set_state(RUNNABLE);
   697   pd_start_thread(thread);
   698 }
   700 //---------------------------------------------------------------------------
   701 // Helper functions for fatal error handler
   703 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
   704   assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
   706   int cols = 0;
   707   int cols_per_line = 0;
   708   switch (unitsize) {
   709     case 1: cols_per_line = 16; break;
   710     case 2: cols_per_line = 8;  break;
   711     case 4: cols_per_line = 4;  break;
   712     case 8: cols_per_line = 2;  break;
   713     default: return;
   714   }
   716   address p = start;
   717   st->print(PTR_FORMAT ":   ", start);
   718   while (p < end) {
   719     switch (unitsize) {
   720       case 1: st->print("%02x", *(u1*)p); break;
   721       case 2: st->print("%04x", *(u2*)p); break;
   722       case 4: st->print("%08x", *(u4*)p); break;
   723       case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
   724     }
   725     p += unitsize;
   726     cols++;
   727     if (cols >= cols_per_line && p < end) {
   728        cols = 0;
   729        st->cr();
   730        st->print(PTR_FORMAT ":   ", p);
   731     } else {
   732        st->print(" ");
   733     }
   734   }
   735   st->cr();
   736 }
   738 void os::print_environment_variables(outputStream* st, const char** env_list,
   739                                      char* buffer, int len) {
   740   if (env_list) {
   741     st->print_cr("Environment Variables:");
   743     for (int i = 0; env_list[i] != NULL; i++) {
   744       if (getenv(env_list[i], buffer, len)) {
   745         st->print(env_list[i]);
   746         st->print("=");
   747         st->print_cr(buffer);
   748       }
   749     }
   750   }
   751 }
   753 void os::print_cpu_info(outputStream* st) {
   754   // cpu
   755   st->print("CPU:");
   756   st->print("total %d", os::processor_count());
   757   // It's not safe to query number of active processors after crash
   758   // st->print("(active %d)", os::active_processor_count());
   759   st->print(" %s", VM_Version::cpu_features());
   760   st->cr();
   761 }
   763 void os::print_date_and_time(outputStream *st) {
   764   time_t tloc;
   765   (void)time(&tloc);
   766   st->print("time: %s", ctime(&tloc));  // ctime adds newline.
   768   double t = os::elapsedTime();
   769   // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
   770   //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
   771   //       before printf. We lost some precision, but who cares?
   772   st->print_cr("elapsed time: %d seconds", (int)t);
   773 }
   775 // moved from debug.cpp (used to be find()) but still called from there
   776 // The verbose parameter is only set by the debug code in one case
   777 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
   778   address addr = (address)x;
   779   CodeBlob* b = CodeCache::find_blob_unsafe(addr);
   780   if (b != NULL) {
   781     if (b->is_buffer_blob()) {
   782       // the interpreter is generated into a buffer blob
   783       InterpreterCodelet* i = Interpreter::codelet_containing(addr);
   784       if (i != NULL) {
   785         st->print_cr(INTPTR_FORMAT " is an Interpreter codelet", addr);
   786         i->print_on(st);
   787         return;
   788       }
   789       if (Interpreter::contains(addr)) {
   790         st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
   791                      " (not bytecode specific)", addr);
   792         return;
   793       }
   794       //
   795       if (AdapterHandlerLibrary::contains(b)) {
   796         st->print_cr(INTPTR_FORMAT " is an AdapterHandler", addr);
   797         AdapterHandlerLibrary::print_handler_on(st, b);
   798       }
   799       // the stubroutines are generated into a buffer blob
   800       StubCodeDesc* d = StubCodeDesc::desc_for(addr);
   801       if (d != NULL) {
   802         d->print_on(st);
   803         if (verbose) st->cr();
   804         return;
   805       }
   806       if (StubRoutines::contains(addr)) {
   807         st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
   808                      "stub routine", addr);
   809         return;
   810       }
   811       // the InlineCacheBuffer is using stubs generated into a buffer blob
   812       if (InlineCacheBuffer::contains(addr)) {
   813         st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
   814         return;
   815       }
   816       VtableStub* v = VtableStubs::stub_containing(addr);
   817       if (v != NULL) {
   818         v->print_on(st);
   819         return;
   820       }
   821     }
   822     if (verbose && b->is_nmethod()) {
   823       ResourceMark rm;
   824       st->print("%#p: Compiled ", addr);
   825       ((nmethod*)b)->method()->print_value_on(st);
   826       st->print("  = (CodeBlob*)" INTPTR_FORMAT, b);
   827       st->cr();
   828       return;
   829     }
   830     st->print(INTPTR_FORMAT " ", b);
   831     if ( b->is_nmethod()) {
   832       if (b->is_zombie()) {
   833         st->print_cr("is zombie nmethod");
   834       } else if (b->is_not_entrant()) {
   835         st->print_cr("is non-entrant nmethod");
   836       }
   837     }
   838     b->print_on(st);
   839     return;
   840   }
   842   if (Universe::heap()->is_in(addr)) {
   843     HeapWord* p = Universe::heap()->block_start(addr);
   844     bool print = false;
   845     // If we couldn't find it it just may mean that heap wasn't parseable
   846     // See if we were just given an oop directly
   847     if (p != NULL && Universe::heap()->block_is_obj(p)) {
   848       print = true;
   849     } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
   850       p = (HeapWord*) addr;
   851       print = true;
   852     }
   853     if (print) {
   854       st->print_cr(INTPTR_FORMAT " is an oop", addr);
   855       oop(p)->print_on(st);
   856       if (p != (HeapWord*)x && oop(p)->is_constMethod() &&
   857           constMethodOop(p)->contains(addr)) {
   858         Thread *thread = Thread::current();
   859         HandleMark hm(thread);
   860         methodHandle mh (thread, constMethodOop(p)->method());
   861         if (!mh->is_native()) {
   862           st->print_cr("bci_from(%p) = %d; print_codes():",
   863                         addr, mh->bci_from(address(x)));
   864           mh->print_codes_on(st);
   865         }
   866       }
   867       return;
   868     }
   869   } else {
   870     if (Universe::heap()->is_in_reserved(addr)) {
   871       st->print_cr(INTPTR_FORMAT " is an unallocated location "
   872                    "in the heap", addr);
   873       return;
   874     }
   875   }
   876   if (JNIHandles::is_global_handle((jobject) addr)) {
   877     st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
   878     return;
   879   }
   880   if (JNIHandles::is_weak_global_handle((jobject) addr)) {
   881     st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
   882     return;
   883   }
   884 #ifndef PRODUCT
   885   // we don't keep the block list in product mode
   886   if (JNIHandleBlock::any_contains((jobject) addr)) {
   887     st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
   888     return;
   889   }
   890 #endif
   892   for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
   893     // Check for privilege stack
   894     if (thread->privileged_stack_top() != NULL &&
   895         thread->privileged_stack_top()->contains(addr)) {
   896       st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
   897                    "for thread: " INTPTR_FORMAT, addr, thread);
   898       if (verbose) thread->print_on(st);
   899       return;
   900     }
   901     // If the addr is a java thread print information about that.
   902     if (addr == (address)thread) {
   903       if (verbose) {
   904         thread->print_on(st);
   905       } else {
   906         st->print_cr(INTPTR_FORMAT " is a thread", addr);
   907       }
   908       return;
   909     }
   910     // If the addr is in the stack region for this thread then report that
   911     // and print thread info
   912     if (thread->stack_base() >= addr &&
   913         addr > (thread->stack_base() - thread->stack_size())) {
   914       st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
   915                    INTPTR_FORMAT, addr, thread);
   916       if (verbose) thread->print_on(st);
   917       return;
   918     }
   920   }
   921   // Try an OS specific find
   922   if (os::find(addr, st)) {
   923     return;
   924   }
   926   st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
   927 }
   929 // Looks like all platforms except IA64 can use the same function to check
   930 // if C stack is walkable beyond current frame. The check for fp() is not
   931 // necessary on Sparc, but it's harmless.
   932 bool os::is_first_C_frame(frame* fr) {
   933 #ifdef IA64
   934   // In order to walk native frames on Itanium, we need to access the unwind
   935   // table, which is inside ELF. We don't want to parse ELF after fatal error,
   936   // so return true for IA64. If we need to support C stack walking on IA64,
   937   // this function needs to be moved to CPU specific files, as fp() on IA64
   938   // is register stack, which grows towards higher memory address.
   939   return true;
   940 #endif
   942   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
   943   // Check usp first, because if that's bad the other accessors may fault
   944   // on some architectures.  Ditto ufp second, etc.
   945   uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
   946   // sp on amd can be 32 bit aligned.
   947   uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
   949   uintptr_t usp    = (uintptr_t)fr->sp();
   950   if ((usp & sp_align_mask) != 0) return true;
   952   uintptr_t ufp    = (uintptr_t)fr->fp();
   953   if ((ufp & fp_align_mask) != 0) return true;
   955   uintptr_t old_sp = (uintptr_t)fr->sender_sp();
   956   if ((old_sp & sp_align_mask) != 0) return true;
   957   if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
   959   uintptr_t old_fp = (uintptr_t)fr->link();
   960   if ((old_fp & fp_align_mask) != 0) return true;
   961   if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
   963   // stack grows downwards; if old_fp is below current fp or if the stack
   964   // frame is too large, either the stack is corrupted or fp is not saved
   965   // on stack (i.e. on x86, ebp may be used as general register). The stack
   966   // is not walkable beyond current frame.
   967   if (old_fp < ufp) return true;
   968   if (old_fp - ufp > 64 * K) return true;
   970   return false;
   971 }
   973 #ifdef ASSERT
   974 extern "C" void test_random() {
   975   const double m = 2147483647;
   976   double mean = 0.0, variance = 0.0, t;
   977   long reps = 10000;
   978   unsigned long seed = 1;
   980   tty->print_cr("seed %ld for %ld repeats...", seed, reps);
   981   os::init_random(seed);
   982   long num;
   983   for (int k = 0; k < reps; k++) {
   984     num = os::random();
   985     double u = (double)num / m;
   986     assert(u >= 0.0 && u <= 1.0, "bad random number!");
   988     // calculate mean and variance of the random sequence
   989     mean += u;
   990     variance += (u*u);
   991   }
   992   mean /= reps;
   993   variance /= (reps - 1);
   995   assert(num == 1043618065, "bad seed");
   996   tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
   997   tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
   998   const double eps = 0.0001;
   999   t = fabsd(mean - 0.5018);
  1000   assert(t < eps, "bad mean");
  1001   t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
  1002   assert(t < eps, "bad variance");
  1004 #endif
  1007 // Set up the boot classpath.
  1009 char* os::format_boot_path(const char* format_string,
  1010                            const char* home,
  1011                            int home_len,
  1012                            char fileSep,
  1013                            char pathSep) {
  1014     assert((fileSep == '/' && pathSep == ':') ||
  1015            (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
  1017     // Scan the format string to determine the length of the actual
  1018     // boot classpath, and handle platform dependencies as well.
  1019     int formatted_path_len = 0;
  1020     const char* p;
  1021     for (p = format_string; *p != 0; ++p) {
  1022         if (*p == '%') formatted_path_len += home_len - 1;
  1023         ++formatted_path_len;
  1026     char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1);
  1027     if (formatted_path == NULL) {
  1028         return NULL;
  1031     // Create boot classpath from format, substituting separator chars and
  1032     // java home directory.
  1033     char* q = formatted_path;
  1034     for (p = format_string; *p != 0; ++p) {
  1035         switch (*p) {
  1036         case '%':
  1037             strcpy(q, home);
  1038             q += home_len;
  1039             break;
  1040         case '/':
  1041             *q++ = fileSep;
  1042             break;
  1043         case ':':
  1044             *q++ = pathSep;
  1045             break;
  1046         default:
  1047             *q++ = *p;
  1050     *q = '\0';
  1052     assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
  1053     return formatted_path;
  1057 bool os::set_boot_path(char fileSep, char pathSep) {
  1058     const char* home = Arguments::get_java_home();
  1059     int home_len = (int)strlen(home);
  1061     static const char* meta_index_dir_format = "%/lib/";
  1062     static const char* meta_index_format = "%/lib/meta-index";
  1063     char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
  1064     if (meta_index == NULL) return false;
  1065     char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
  1066     if (meta_index_dir == NULL) return false;
  1067     Arguments::set_meta_index_path(meta_index, meta_index_dir);
  1069     // Any modification to the JAR-file list, for the boot classpath must be
  1070     // aligned with install/install/make/common/Pack.gmk. Note: boot class
  1071     // path class JARs, are stripped for StackMapTable to reduce download size.
  1072     static const char classpath_format[] =
  1073         "%/lib/resources.jar:"
  1074         "%/lib/rt.jar:"
  1075         "%/lib/sunrsasign.jar:"
  1076         "%/lib/jsse.jar:"
  1077         "%/lib/jce.jar:"
  1078         "%/lib/charsets.jar:"
  1080         // ## TEMPORARY hack to keep the legacy launcher working when
  1081         // ## only the boot module is installed (cf. j.l.ClassLoader)
  1082         "%/lib/modules/jdk.boot.jar:"
  1084         "%/classes";
  1085     char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
  1086     if (sysclasspath == NULL) return false;
  1087     Arguments::set_sysclasspath(sysclasspath);
  1089     return true;
  1092 /*
  1093  * Splits a path, based on its separator, the number of
  1094  * elements is returned back in n.
  1095  * It is the callers responsibility to:
  1096  *   a> check the value of n, and n may be 0.
  1097  *   b> ignore any empty path elements
  1098  *   c> free up the data.
  1099  */
  1100 char** os::split_path(const char* path, int* n) {
  1101   *n = 0;
  1102   if (path == NULL || strlen(path) == 0) {
  1103     return NULL;
  1105   const char psepchar = *os::path_separator();
  1106   char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1);
  1107   if (inpath == NULL) {
  1108     return NULL;
  1110   strncpy(inpath, path, strlen(path));
  1111   int count = 1;
  1112   char* p = strchr(inpath, psepchar);
  1113   // Get a count of elements to allocate memory
  1114   while (p != NULL) {
  1115     count++;
  1116     p++;
  1117     p = strchr(p, psepchar);
  1119   char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count);
  1120   if (opath == NULL) {
  1121     return NULL;
  1124   // do the actual splitting
  1125   p = inpath;
  1126   for (int i = 0 ; i < count ; i++) {
  1127     size_t len = strcspn(p, os::path_separator());
  1128     if (len > JVM_MAXPATHLEN) {
  1129       return NULL;
  1131     // allocate the string and add terminator storage
  1132     char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1);
  1133     if (s == NULL) {
  1134       return NULL;
  1136     strncpy(s, p, len);
  1137     s[len] = '\0';
  1138     opath[i] = s;
  1139     p += len + 1;
  1141   FREE_C_HEAP_ARRAY(char, inpath);
  1142   *n = count;
  1143   return opath;
  1146 void os::set_memory_serialize_page(address page) {
  1147   int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
  1148   _mem_serialize_page = (volatile int32_t *)page;
  1149   // We initialize the serialization page shift count here
  1150   // We assume a cache line size of 64 bytes
  1151   assert(SerializePageShiftCount == count,
  1152          "thread size changed, fix SerializePageShiftCount constant");
  1153   set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
  1156 static volatile intptr_t SerializePageLock = 0;
  1158 // This method is called from signal handler when SIGSEGV occurs while the current
  1159 // thread tries to store to the "read-only" memory serialize page during state
  1160 // transition.
  1161 void os::block_on_serialize_page_trap() {
  1162   if (TraceSafepoint) {
  1163     tty->print_cr("Block until the serialize page permission restored");
  1165   // When VMThread is holding the SerializePageLock during modifying the
  1166   // access permission of the memory serialize page, the following call
  1167   // will block until the permission of that page is restored to rw.
  1168   // Generally, it is unsafe to manipulate locks in signal handlers, but in
  1169   // this case, it's OK as the signal is synchronous and we know precisely when
  1170   // it can occur.
  1171   Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
  1172   Thread::muxRelease(&SerializePageLock);
  1175 // Serialize all thread state variables
  1176 void os::serialize_thread_states() {
  1177   // On some platforms such as Solaris & Linux, the time duration of the page
  1178   // permission restoration is observed to be much longer than expected  due to
  1179   // scheduler starvation problem etc. To avoid the long synchronization
  1180   // time and expensive page trap spinning, 'SerializePageLock' is used to block
  1181   // the mutator thread if such case is encountered. See bug 6546278 for details.
  1182   Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
  1183   os::protect_memory((char *)os::get_memory_serialize_page(),
  1184                      os::vm_page_size(), MEM_PROT_READ);
  1185   os::protect_memory((char *)os::get_memory_serialize_page(),
  1186                      os::vm_page_size(), MEM_PROT_RW);
  1187   Thread::muxRelease(&SerializePageLock);
  1190 // Returns true if the current stack pointer is above the stack shadow
  1191 // pages, false otherwise.
  1193 bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
  1194   assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
  1195   address sp = current_stack_pointer();
  1196   // Check if we have StackShadowPages above the yellow zone.  This parameter
  1197   // is dependent on the depth of the maximum VM call stack possible from
  1198   // the handler for stack overflow.  'instanceof' in the stack overflow
  1199   // handler or a println uses at least 8k stack of VM and native code
  1200   // respectively.
  1201   const int framesize_in_bytes =
  1202     Interpreter::size_top_interpreter_activation(method()) * wordSize;
  1203   int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
  1204                       * vm_page_size()) + framesize_in_bytes;
  1205   // The very lower end of the stack
  1206   address stack_limit = thread->stack_base() - thread->stack_size();
  1207   return (sp > (stack_limit + reserved_area));
  1210 size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
  1211                                 uint min_pages)
  1213   assert(min_pages > 0, "sanity");
  1214   if (UseLargePages) {
  1215     const size_t max_page_size = region_max_size / min_pages;
  1217     for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
  1218       const size_t sz = _page_sizes[i];
  1219       const size_t mask = sz - 1;
  1220       if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
  1221         // The largest page size with no fragmentation.
  1222         return sz;
  1225       if (sz <= max_page_size) {
  1226         // The largest page size that satisfies the min_pages requirement.
  1227         return sz;
  1232   return vm_page_size();
  1235 #ifndef PRODUCT
  1236 void os::trace_page_sizes(const char* str, const size_t region_min_size,
  1237                           const size_t region_max_size, const size_t page_size,
  1238                           const char* base, const size_t size)
  1240   if (TracePageSizes) {
  1241     tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
  1242                   " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
  1243                   " size=" SIZE_FORMAT,
  1244                   str, region_min_size, region_max_size,
  1245                   page_size, base, size);
  1248 #endif  // #ifndef PRODUCT
  1250 // This is the working definition of a server class machine:
  1251 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
  1252 // because the graphics memory (?) sometimes masks physical memory.
  1253 // If you want to change the definition of a server class machine
  1254 // on some OS or platform, e.g., >=4GB on Windohs platforms,
  1255 // then you'll have to parameterize this method based on that state,
  1256 // as was done for logical processors here, or replicate and
  1257 // specialize this method for each platform.  (Or fix os to have
  1258 // some inheritance structure and use subclassing.  Sigh.)
  1259 // If you want some platform to always or never behave as a server
  1260 // class machine, change the setting of AlwaysActAsServerClassMachine
  1261 // and NeverActAsServerClassMachine in globals*.hpp.
  1262 bool os::is_server_class_machine() {
  1263   // First check for the early returns
  1264   if (NeverActAsServerClassMachine) {
  1265     return false;
  1267   if (AlwaysActAsServerClassMachine) {
  1268     return true;
  1270   // Then actually look at the machine
  1271   bool         result            = false;
  1272   const unsigned int    server_processors = 2;
  1273   const julong server_memory     = 2UL * G;
  1274   // We seem not to get our full complement of memory.
  1275   //     We allow some part (1/8?) of the memory to be "missing",
  1276   //     based on the sizes of DIMMs, and maybe graphics cards.
  1277   const julong missing_memory   = 256UL * M;
  1279   /* Is this a server class machine? */
  1280   if ((os::active_processor_count() >= (int)server_processors) &&
  1281       (os::physical_memory() >= (server_memory - missing_memory))) {
  1282     const unsigned int logical_processors =
  1283       VM_Version::logical_processors_per_package();
  1284     if (logical_processors > 1) {
  1285       const unsigned int physical_packages =
  1286         os::active_processor_count() / logical_processors;
  1287       if (physical_packages > server_processors) {
  1288         result = true;
  1290     } else {
  1291       result = true;
  1294   return result;

mercurial