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