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  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "code/vtableStubs.hpp"
  32 #include "gc_implementation/shared/vmGCOperations.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/allocation.inline.hpp"
  35 #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
  64 
  65 # include <signal.h>
  66 
  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];
  74 
  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
  80 
  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;
  96 
  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;
 120 
 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);
 147 
 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 }
 168 
 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
 179 
 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 }
 188 
 189 
 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;
 195 
 196   for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
 197   priority = (ThreadPriority)p;
 198   return OS_OK;
 199 }
 200 
 201 
 202 // --------------------- sun.misc.Signal (optional) ---------------------
 203 
 204 
 205 // SIGBREAK is sent by the keyboard to query the VM state
 206 #ifndef SIGBREAK
 207 #define SIGBREAK SIGQUIT
 208 #endif
 209 
 210 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
 211 
 212 
 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     }
 227 
 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 }
 296 
 297 
 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);
 305 
 306     const char thread_name[] = "Signal Dispatcher";
 307     Handle string = java_lang_String::create_from_str(thread_name, CHECK);
 308 
 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);
 319 
 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);
 328 
 329     os::signal_init_pd();
 330 
 331     { MutexLocker mu(Threads_lock);
 332       JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
 333 
 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       }
 342 
 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());
 346 
 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 }
 355 
 356 
 357 void os::terminate_signal_thread() {
 358   if (!ReduceSignalUsage)
 359     signal_notify(sigexitnum_pd());
 360 }
 361 
 362 
 363 // --------------------- loading libraries ---------------------
 364 
 365 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
 366 extern struct JavaVM_ main_vm;
 367 
 368 static void* _native_java_library = NULL;
 369 
 370 void* os::native_java_library() {
 371   if (_native_java_library == NULL) {
 372     char buffer[JVM_MAXPATHLEN];
 373     char ebuf[1024];
 374 
 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));
 380 
 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 }
 412 
 413 // --------------------- heap allocation utilities ---------------------
 414 
 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 }
 422 
 423 
 424 
 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 */
 442 
 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 }
 452 
 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 }
 462 
 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 }
 472 
 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   }
 492 
 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   }
 498 
 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 }
 513 
 514 
 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 }
 521 
 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
 540 
 541 void* os::malloc(size_t size) {
 542   NOT_PRODUCT(num_mallocs++);
 543   NOT_PRODUCT(alloc_bytes += size);
 544 
 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   }
 550 
 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 }
 573 
 574 
 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 }
 607 
 608 
 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 }
 641 
 642 void os::init_random(long initval) {
 643   _rand_seed = initval;
 644 }
 645 
 646 
 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");
 660 
 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;
 665 
 666   // if q overflowed, ignore the overflow and increment q
 667   if (lo > m) {
 668     lo &= m;
 669     ++lo;
 670   }
 671   lo += hi >> 15;
 672 
 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 }
 680 
 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.
 691 
 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 }
 699 
 700 //---------------------------------------------------------------------------
 701 // Helper functions for fatal error handler
 702 
 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");
 705 
 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   }
 715 
 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 }
 737 
 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:");
 742 
 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 }
 752 
 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 }
 762 
 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.
 767 
 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 }
 774 
 775 // moved from debug.cpp (used to be find()) but still called from there
 776 // The print_pc parameter is only set by the debug code in one case
 777 void os::print_location(outputStream* st, intptr_t x, bool print_pc) {
 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         i->print_on(st);
 786         return;
 787       }
 788       if (Interpreter::contains(addr)) {
 789         st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
 790                      " (not bytecode specific)", addr);
 791         return;
 792       }
 793       //
 794       if (AdapterHandlerLibrary::contains(b)) {
 795         st->print_cr("Printing AdapterHandler");
 796         AdapterHandlerLibrary::print_handler_on(st, b);
 797       }
 798       // the stubroutines are generated into a buffer blob
 799       StubCodeDesc* d = StubCodeDesc::desc_for(addr);
 800       if (d != NULL) {
 801         d->print_on(st);
 802         if (print_pc) st->cr();
 803         return;
 804       }
 805       if (StubRoutines::contains(addr)) {
 806         st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
 807                      "stub routine", addr);
 808         return;
 809       }
 810       // the InlineCacheBuffer is using stubs generated into a buffer blob
 811       if (InlineCacheBuffer::contains(addr)) {
 812         st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
 813         return;
 814       }
 815       VtableStub* v = VtableStubs::stub_containing(addr);
 816       if (v != NULL) {
 817         v->print_on(st);
 818         return;
 819       }
 820     }
 821     if (print_pc && b->is_nmethod()) {
 822       ResourceMark rm;
 823       st->print("%#p: Compiled ", addr);
 824       ((nmethod*)b)->method()->print_value_on(st);
 825       st->print("  = (CodeBlob*)" INTPTR_FORMAT, b);
 826       st->cr();
 827       return;
 828     }
 829     if ( b->is_nmethod()) {
 830       if (b->is_zombie()) {
 831         st->print_cr(INTPTR_FORMAT " is zombie nmethod", b);
 832       } else if (b->is_not_entrant()) {
 833         st->print_cr(INTPTR_FORMAT " is non-entrant nmethod", b);
 834       }
 835     }
 836     b->print_on(st);
 837     return;
 838   }
 839 
 840   if (Universe::heap()->is_in(addr)) {
 841     HeapWord* p = Universe::heap()->block_start(addr);
 842     bool print = false;
 843     // If we couldn't find it it just may mean that heap wasn't parseable
 844     // See if we were just given an oop directly
 845     if (p != NULL && Universe::heap()->block_is_obj(p)) {
 846       print = true;
 847     } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
 848       p = (HeapWord*) addr;
 849       print = true;
 850     }
 851     if (print) {
 852       oop(p)->print_on(st);
 853       if (p != (HeapWord*)x && oop(p)->is_constMethod() &&
 854           constMethodOop(p)->contains(addr)) {
 855         Thread *thread = Thread::current();
 856         HandleMark hm(thread);
 857         methodHandle mh (thread, constMethodOop(p)->method());
 858         if (!mh->is_native()) {
 859           st->print_cr("bci_from(%p) = %d; print_codes():",
 860                         addr, mh->bci_from(address(x)));
 861           mh->print_codes_on(st);
 862         }
 863       }
 864       return;
 865     }
 866   } else {
 867     if (Universe::heap()->is_in_reserved(addr)) {
 868       st->print_cr(INTPTR_FORMAT " is an unallocated location "
 869                    "in the heap", addr);
 870       return;
 871     }
 872   }
 873   if (JNIHandles::is_global_handle((jobject) addr)) {
 874     st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
 875     return;
 876   }
 877   if (JNIHandles::is_weak_global_handle((jobject) addr)) {
 878     st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
 879     return;
 880   }
 881 #ifndef PRODUCT
 882   // we don't keep the block list in product mode
 883   if (JNIHandleBlock::any_contains((jobject) addr)) {
 884     st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
 885     return;
 886   }
 887 #endif
 888 
 889   for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
 890     // Check for privilege stack
 891     if (thread->privileged_stack_top() != NULL &&
 892         thread->privileged_stack_top()->contains(addr)) {
 893       st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
 894                    "for thread: " INTPTR_FORMAT, addr, thread);
 895       thread->print_on(st);
 896       return;
 897     }
 898     // If the addr is a java thread print information about that.
 899     if (addr == (address)thread) {
 900       thread->print_on(st);
 901       return;
 902     }
 903     // If the addr is in the stack region for this thread then report that
 904     // and print thread info
 905     if (thread->stack_base() >= addr &&
 906         addr > (thread->stack_base() - thread->stack_size())) {
 907       st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
 908                    INTPTR_FORMAT, addr, thread);
 909       thread->print_on(st);
 910       return;
 911     }
 912 
 913   }
 914   // Try an OS specific find
 915   if (os::find(addr, st)) {
 916     return;
 917   }
 918 
 919   st->print_cr(INTPTR_FORMAT " is pointing to unknown location", addr);
 920 }
 921 
 922 // Looks like all platforms except IA64 can use the same function to check
 923 // if C stack is walkable beyond current frame. The check for fp() is not
 924 // necessary on Sparc, but it's harmless.
 925 bool os::is_first_C_frame(frame* fr) {
 926 #ifdef IA64
 927   // In order to walk native frames on Itanium, we need to access the unwind
 928   // table, which is inside ELF. We don't want to parse ELF after fatal error,
 929   // so return true for IA64. If we need to support C stack walking on IA64,
 930   // this function needs to be moved to CPU specific files, as fp() on IA64
 931   // is register stack, which grows towards higher memory address.
 932   return true;
 933 #endif
 934 
 935   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
 936   // Check usp first, because if that's bad the other accessors may fault
 937   // on some architectures.  Ditto ufp second, etc.
 938   uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
 939   // sp on amd can be 32 bit aligned.
 940   uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
 941 
 942   uintptr_t usp    = (uintptr_t)fr->sp();
 943   if ((usp & sp_align_mask) != 0) return true;
 944 
 945   uintptr_t ufp    = (uintptr_t)fr->fp();
 946   if ((ufp & fp_align_mask) != 0) return true;
 947 
 948   uintptr_t old_sp = (uintptr_t)fr->sender_sp();
 949   if ((old_sp & sp_align_mask) != 0) return true;
 950   if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
 951 
 952   uintptr_t old_fp = (uintptr_t)fr->link();
 953   if ((old_fp & fp_align_mask) != 0) return true;
 954   if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
 955 
 956   // stack grows downwards; if old_fp is below current fp or if the stack
 957   // frame is too large, either the stack is corrupted or fp is not saved
 958   // on stack (i.e. on x86, ebp may be used as general register). The stack
 959   // is not walkable beyond current frame.
 960   if (old_fp < ufp) return true;
 961   if (old_fp - ufp > 64 * K) return true;
 962 
 963   return false;
 964 }
 965 
 966 #ifdef ASSERT
 967 extern "C" void test_random() {
 968   const double m = 2147483647;
 969   double mean = 0.0, variance = 0.0, t;
 970   long reps = 10000;
 971   unsigned long seed = 1;
 972 
 973   tty->print_cr("seed %ld for %ld repeats...", seed, reps);
 974   os::init_random(seed);
 975   long num;
 976   for (int k = 0; k < reps; k++) {
 977     num = os::random();
 978     double u = (double)num / m;
 979     assert(u >= 0.0 && u <= 1.0, "bad random number!");
 980 
 981     // calculate mean and variance of the random sequence
 982     mean += u;
 983     variance += (u*u);
 984   }
 985   mean /= reps;
 986   variance /= (reps - 1);
 987 
 988   assert(num == 1043618065, "bad seed");
 989   tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
 990   tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
 991   const double eps = 0.0001;
 992   t = fabsd(mean - 0.5018);
 993   assert(t < eps, "bad mean");
 994   t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
 995   assert(t < eps, "bad variance");
 996 }
 997 #endif
 998 
 999 
1000 // Set up the boot classpath.
1001 
1002 char* os::format_boot_path(const char* format_string,
1003                            const char* home,
1004                            int home_len,
1005                            char fileSep,
1006                            char pathSep) {
1007     assert((fileSep == '/' && pathSep == ':') ||
1008            (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
1009 
1010     // Scan the format string to determine the length of the actual
1011     // boot classpath, and handle platform dependencies as well.
1012     int formatted_path_len = 0;
1013     const char* p;
1014     for (p = format_string; *p != 0; ++p) {
1015         if (*p == '%') formatted_path_len += home_len - 1;
1016         ++formatted_path_len;
1017     }
1018 
1019     char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1);
1020     if (formatted_path == NULL) {
1021         return NULL;
1022     }
1023 
1024     // Create boot classpath from format, substituting separator chars and
1025     // java home directory.
1026     char* q = formatted_path;
1027     for (p = format_string; *p != 0; ++p) {
1028         switch (*p) {
1029         case '%':
1030             strcpy(q, home);
1031             q += home_len;
1032             break;
1033         case '/':
1034             *q++ = fileSep;
1035             break;
1036         case ':':
1037             *q++ = pathSep;
1038             break;
1039         default:
1040             *q++ = *p;
1041         }
1042     }
1043     *q = '\0';
1044 
1045     assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1046     return formatted_path;
1047 }
1048 
1049 
1050 bool os::set_boot_path(char fileSep, char pathSep) {
1051     const char* home = Arguments::get_java_home();
1052     int home_len = (int)strlen(home);
1053 
1054     static const char* meta_index_dir_format = "%/lib/";
1055     static const char* meta_index_format = "%/lib/meta-index";
1056     char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
1057     if (meta_index == NULL) return false;
1058     char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
1059     if (meta_index_dir == NULL) return false;
1060     Arguments::set_meta_index_path(meta_index, meta_index_dir);
1061 
1062     // Any modification to the JAR-file list, for the boot classpath must be
1063     // aligned with install/install/make/common/Pack.gmk. Note: boot class
1064     // path class JARs, are stripped for StackMapTable to reduce download size.
1065     static const char classpath_format[] =
1066         "%/lib/resources.jar:"
1067         "%/lib/rt.jar:"
1068         "%/lib/sunrsasign.jar:"
1069         "%/lib/jsse.jar:"
1070         "%/lib/jce.jar:"
1071         "%/lib/charsets.jar:"
1072 
1073         // ## TEMPORARY hack to keep the legacy launcher working when
1074         // ## only the boot module is installed (cf. j.l.ClassLoader)
1075         "%/lib/modules/jdk.boot.jar:"
1076 
1077         "%/classes";
1078     char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
1079     if (sysclasspath == NULL) return false;
1080     Arguments::set_sysclasspath(sysclasspath);
1081 
1082     return true;
1083 }
1084 
1085 /*
1086  * Splits a path, based on its separator, the number of
1087  * elements is returned back in n.
1088  * It is the callers responsibility to:
1089  *   a> check the value of n, and n may be 0.
1090  *   b> ignore any empty path elements
1091  *   c> free up the data.
1092  */
1093 char** os::split_path(const char* path, int* n) {
1094   *n = 0;
1095   if (path == NULL || strlen(path) == 0) {
1096     return NULL;
1097   }
1098   const char psepchar = *os::path_separator();
1099   char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1);
1100   if (inpath == NULL) {
1101     return NULL;
1102   }
1103   strncpy(inpath, path, strlen(path));
1104   int count = 1;
1105   char* p = strchr(inpath, psepchar);
1106   // Get a count of elements to allocate memory
1107   while (p != NULL) {
1108     count++;
1109     p++;
1110     p = strchr(p, psepchar);
1111   }
1112   char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count);
1113   if (opath == NULL) {
1114     return NULL;
1115   }
1116 
1117   // do the actual splitting
1118   p = inpath;
1119   for (int i = 0 ; i < count ; i++) {
1120     size_t len = strcspn(p, os::path_separator());
1121     if (len > JVM_MAXPATHLEN) {
1122       return NULL;
1123     }
1124     // allocate the string and add terminator storage
1125     char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1);
1126     if (s == NULL) {
1127       return NULL;
1128     }
1129     strncpy(s, p, len);
1130     s[len] = '\0';
1131     opath[i] = s;
1132     p += len + 1;
1133   }
1134   FREE_C_HEAP_ARRAY(char, inpath);
1135   *n = count;
1136   return opath;
1137 }
1138 
1139 void os::set_memory_serialize_page(address page) {
1140   int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
1141   _mem_serialize_page = (volatile int32_t *)page;
1142   // We initialize the serialization page shift count here
1143   // We assume a cache line size of 64 bytes
1144   assert(SerializePageShiftCount == count,
1145          "thread size changed, fix SerializePageShiftCount constant");
1146   set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
1147 }
1148 
1149 static volatile intptr_t SerializePageLock = 0;
1150 
1151 // This method is called from signal handler when SIGSEGV occurs while the current
1152 // thread tries to store to the "read-only" memory serialize page during state
1153 // transition.
1154 void os::block_on_serialize_page_trap() {
1155   if (TraceSafepoint) {
1156     tty->print_cr("Block until the serialize page permission restored");
1157   }
1158   // When VMThread is holding the SerializePageLock during modifying the
1159   // access permission of the memory serialize page, the following call
1160   // will block until the permission of that page is restored to rw.
1161   // Generally, it is unsafe to manipulate locks in signal handlers, but in
1162   // this case, it's OK as the signal is synchronous and we know precisely when
1163   // it can occur.
1164   Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
1165   Thread::muxRelease(&SerializePageLock);
1166 }
1167 
1168 // Serialize all thread state variables
1169 void os::serialize_thread_states() {
1170   // On some platforms such as Solaris & Linux, the time duration of the page
1171   // permission restoration is observed to be much longer than expected  due to
1172   // scheduler starvation problem etc. To avoid the long synchronization
1173   // time and expensive page trap spinning, 'SerializePageLock' is used to block
1174   // the mutator thread if such case is encountered. See bug 6546278 for details.
1175   Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
1176   os::protect_memory((char *)os::get_memory_serialize_page(),
1177                      os::vm_page_size(), MEM_PROT_READ);
1178   os::protect_memory((char *)os::get_memory_serialize_page(),
1179                      os::vm_page_size(), MEM_PROT_RW);
1180   Thread::muxRelease(&SerializePageLock);
1181 }
1182 
1183 // Returns true if the current stack pointer is above the stack shadow
1184 // pages, false otherwise.
1185 
1186 bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
1187   assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
1188   address sp = current_stack_pointer();
1189   // Check if we have StackShadowPages above the yellow zone.  This parameter
1190   // is dependent on the depth of the maximum VM call stack possible from
1191   // the handler for stack overflow.  'instanceof' in the stack overflow
1192   // handler or a println uses at least 8k stack of VM and native code
1193   // respectively.
1194   const int framesize_in_bytes =
1195     Interpreter::size_top_interpreter_activation(method()) * wordSize;
1196   int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
1197                       * vm_page_size()) + framesize_in_bytes;
1198   // The very lower end of the stack
1199   address stack_limit = thread->stack_base() - thread->stack_size();
1200   return (sp > (stack_limit + reserved_area));
1201 }
1202 
1203 size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
1204                                 uint min_pages)
1205 {
1206   assert(min_pages > 0, "sanity");
1207   if (UseLargePages) {
1208     const size_t max_page_size = region_max_size / min_pages;
1209 
1210     for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
1211       const size_t sz = _page_sizes[i];
1212       const size_t mask = sz - 1;
1213       if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
1214         // The largest page size with no fragmentation.
1215         return sz;
1216       }
1217 
1218       if (sz <= max_page_size) {
1219         // The largest page size that satisfies the min_pages requirement.
1220         return sz;
1221       }
1222     }
1223   }
1224 
1225   return vm_page_size();
1226 }
1227 
1228 #ifndef PRODUCT
1229 void os::trace_page_sizes(const char* str, const size_t region_min_size,
1230                           const size_t region_max_size, const size_t page_size,
1231                           const char* base, const size_t size)
1232 {
1233   if (TracePageSizes) {
1234     tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
1235                   " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
1236                   " size=" SIZE_FORMAT,
1237                   str, region_min_size, region_max_size,
1238                   page_size, base, size);
1239   }
1240 }
1241 #endif  // #ifndef PRODUCT
1242 
1243 // This is the working definition of a server class machine:
1244 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1245 // because the graphics memory (?) sometimes masks physical memory.
1246 // If you want to change the definition of a server class machine
1247 // on some OS or platform, e.g., >=4GB on Windohs platforms,
1248 // then you'll have to parameterize this method based on that state,
1249 // as was done for logical processors here, or replicate and
1250 // specialize this method for each platform.  (Or fix os to have
1251 // some inheritance structure and use subclassing.  Sigh.)
1252 // If you want some platform to always or never behave as a server
1253 // class machine, change the setting of AlwaysActAsServerClassMachine
1254 // and NeverActAsServerClassMachine in globals*.hpp.
1255 bool os::is_server_class_machine() {
1256   // First check for the early returns
1257   if (NeverActAsServerClassMachine) {
1258     return false;
1259   }
1260   if (AlwaysActAsServerClassMachine) {
1261     return true;
1262   }
1263   // Then actually look at the machine
1264   bool         result            = false;
1265   const unsigned int    server_processors = 2;
1266   const julong server_memory     = 2UL * G;
1267   // We seem not to get our full complement of memory.
1268   //     We allow some part (1/8?) of the memory to be "missing",
1269   //     based on the sizes of DIMMs, and maybe graphics cards.
1270   const julong missing_memory   = 256UL * M;
1271 
1272   /* Is this a server class machine? */
1273   if ((os::active_processor_count() >= (int)server_processors) &&
1274       (os::physical_memory() >= (server_memory - missing_memory))) {
1275     const unsigned int logical_processors =
1276       VM_Version::logical_processors_per_package();
1277     if (logical_processors > 1) {
1278       const unsigned int physical_packages =
1279         os::active_processor_count() / logical_processors;
1280       if (physical_packages > server_processors) {
1281         result = true;
1282       }
1283     } else {
1284       result = true;
1285     }
1286   }
1287   return result;
1288 }