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