os.cpp revision 8554:d89dc667352b
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
64PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
65
66OSThread*         os::_starting_thread    = NULL;
67address           os::_polling_page       = NULL;
68volatile int32_t* os::_mem_serialize_page = NULL;
69uintptr_t         os::_serialize_page_mask = 0;
70long              os::_rand_seed          = 1;
71int               os::_processor_count    = 0;
72size_t            os::_page_sizes[os::page_sizes_max];
73
74#ifndef PRODUCT
75julong os::num_mallocs = 0;         // # of calls to malloc/realloc
76julong os::alloc_bytes = 0;         // # of bytes allocated
77julong os::num_frees = 0;           // # of calls to free
78julong os::free_bytes = 0;          // # of bytes freed
79#endif
80
81static juint cur_malloc_words = 0;  // current size for MallocMaxTestWords
82
83void 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.
97char* 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
181OSReturn 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()
204OSReturn 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
232static 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
315void 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
321void 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
380void os::terminate_signal_thread() {
381  if (!ReduceSignalUsage)
382    signal_notify(sigexitnum_pd());
383}
384
385
386// --------------------- loading libraries ---------------------
387
388typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
389extern struct JavaVM_ main_vm;
390
391static void* _native_java_library = NULL;
392
393void* 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 */
458void* 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.
485bool 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
513char *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
521char* 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
534static 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//
550static 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
562void* os::malloc(size_t size, MEMFLAGS flags) {
563  return os::malloc(size, flags, CALLER_PC);
564}
565
566void* 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
636void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) {
637  return os::realloc(memblock, size, flags, CALLER_PC);
638}
639
640void* 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 && tty != NULL) {
674    tty->print_cr("os::realloc " 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
694void  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
720void os::init_random(long initval) {
721  _rand_seed = initval;
722}
723
724
725long 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
770void 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
778void os::abort(bool dump_core) {
779  abort(dump_core && CreateCoredumpOnCrash, NULL, NULL);
780}
781
782//---------------------------------------------------------------------------
783// Helper functions for fatal error handler
784
785void 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
820void 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
835void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) {
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, buf, buflen);
844}
845
846void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) {
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  struct tm tz;
856  if (localtime_pd(&tloc, &tz) != NULL) {
857    ::strftime(buf, buflen, "%Z", &tz);
858    st->print_cr("timezone: %s", buf);
859  }
860
861  double t = os::elapsedTime();
862  // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
863  //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
864  //       before printf. We lost some precision, but who cares?
865  int eltime = (int)t;  // elapsed time in seconds
866
867  // print elapsed time in a human-readable format:
868  int eldays = eltime / secs_per_day;
869  int day_secs = eldays * secs_per_day;
870  int elhours = (eltime - day_secs) / secs_per_hour;
871  int hour_secs = elhours * secs_per_hour;
872  int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
873  int minute_secs = elmins * secs_per_min;
874  int elsecs = (eltime - day_secs - hour_secs - minute_secs);
875  st->print_cr("elapsed time: %d seconds (%dd %dh %dm %ds)", eltime, eldays, elhours, elmins, elsecs);
876}
877
878// moved from debug.cpp (used to be find()) but still called from there
879// The verbose parameter is only set by the debug code in one case
880void os::print_location(outputStream* st, intptr_t x, bool verbose) {
881  address addr = (address)x;
882  CodeBlob* b = CodeCache::find_blob_unsafe(addr);
883  if (b != NULL) {
884    if (b->is_buffer_blob()) {
885      // the interpreter is generated into a buffer blob
886      InterpreterCodelet* i = Interpreter::codelet_containing(addr);
887      if (i != NULL) {
888        st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
889        i->print_on(st);
890        return;
891      }
892      if (Interpreter::contains(addr)) {
893        st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
894                     " (not bytecode specific)", addr);
895        return;
896      }
897      //
898      if (AdapterHandlerLibrary::contains(b)) {
899        st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
900        AdapterHandlerLibrary::print_handler_on(st, b);
901      }
902      // the stubroutines are generated into a buffer blob
903      StubCodeDesc* d = StubCodeDesc::desc_for(addr);
904      if (d != NULL) {
905        st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
906        d->print_on(st);
907        st->cr();
908        return;
909      }
910      if (StubRoutines::contains(addr)) {
911        st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
912                     "stub routine", addr);
913        return;
914      }
915      // the InlineCacheBuffer is using stubs generated into a buffer blob
916      if (InlineCacheBuffer::contains(addr)) {
917        st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
918        return;
919      }
920      VtableStub* v = VtableStubs::stub_containing(addr);
921      if (v != NULL) {
922        st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
923        v->print_on(st);
924        st->cr();
925        return;
926      }
927    }
928    nmethod* nm = b->as_nmethod_or_null();
929    if (nm != NULL) {
930      ResourceMark rm;
931      st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
932                addr, (int)(addr - nm->entry_point()), nm);
933      if (verbose) {
934        st->print(" for ");
935        nm->method()->print_value_on(st);
936      }
937      st->cr();
938      nm->print_nmethod(verbose);
939      return;
940    }
941    st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
942    b->print_on(st);
943    return;
944  }
945
946  if (Universe::heap()->is_in(addr)) {
947    HeapWord* p = Universe::heap()->block_start(addr);
948    bool print = false;
949    // If we couldn't find it it just may mean that heap wasn't parsable
950    // See if we were just given an oop directly
951    if (p != NULL && Universe::heap()->block_is_obj(p)) {
952      print = true;
953    } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
954      p = (HeapWord*) addr;
955      print = true;
956    }
957    if (print) {
958      if (p == (HeapWord*) addr) {
959        st->print_cr(INTPTR_FORMAT " is an oop", addr);
960      } else {
961        st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
962      }
963      oop(p)->print_on(st);
964      return;
965    }
966  } else {
967    if (Universe::heap()->is_in_reserved(addr)) {
968      st->print_cr(INTPTR_FORMAT " is an unallocated location "
969                   "in the heap", addr);
970      return;
971    }
972  }
973  if (JNIHandles::is_global_handle((jobject) addr)) {
974    st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
975    return;
976  }
977  if (JNIHandles::is_weak_global_handle((jobject) addr)) {
978    st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
979    return;
980  }
981#ifndef PRODUCT
982  // we don't keep the block list in product mode
983  if (JNIHandleBlock::any_contains((jobject) addr)) {
984    st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
985    return;
986  }
987#endif
988
989  for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
990    // Check for privilege stack
991    if (thread->privileged_stack_top() != NULL &&
992        thread->privileged_stack_top()->contains(addr)) {
993      st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
994                   "for thread: " INTPTR_FORMAT, addr, thread);
995      if (verbose) thread->print_on(st);
996      return;
997    }
998    // If the addr is a java thread print information about that.
999    if (addr == (address)thread) {
1000      if (verbose) {
1001        thread->print_on(st);
1002      } else {
1003        st->print_cr(INTPTR_FORMAT " is a thread", addr);
1004      }
1005      return;
1006    }
1007    // If the addr is in the stack region for this thread then report that
1008    // and print thread info
1009    if (thread->stack_base() >= addr &&
1010        addr > (thread->stack_base() - thread->stack_size())) {
1011      st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
1012                   INTPTR_FORMAT, addr, thread);
1013      if (verbose) thread->print_on(st);
1014      return;
1015    }
1016
1017  }
1018
1019  // Check if in metaspace and print types that have vptrs (only method now)
1020  if (Metaspace::contains(addr)) {
1021    if (Method::has_method_vptr((const void*)addr)) {
1022      ((Method*)addr)->print_value_on(st);
1023      st->cr();
1024    } else {
1025      // Use addr->print() from the debugger instead (not here)
1026      st->print_cr(INTPTR_FORMAT " is pointing into metadata", addr);
1027    }
1028    return;
1029  }
1030
1031  // Try an OS specific find
1032  if (os::find(addr, st)) {
1033    return;
1034  }
1035
1036  st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
1037}
1038
1039// Looks like all platforms except IA64 can use the same function to check
1040// if C stack is walkable beyond current frame. The check for fp() is not
1041// necessary on Sparc, but it's harmless.
1042bool os::is_first_C_frame(frame* fr) {
1043#if (defined(IA64) && !defined(AIX)) && !defined(_WIN32)
1044  // On IA64 we have to check if the callers bsp is still valid
1045  // (i.e. within the register stack bounds).
1046  // Notice: this only works for threads created by the VM and only if
1047  // we walk the current stack!!! If we want to be able to walk
1048  // arbitrary other threads, we'll have to somehow store the thread
1049  // object in the frame.
1050  Thread *thread = Thread::current();
1051  if ((address)fr->fp() <=
1052      thread->register_stack_base() HPUX_ONLY(+ 0x0) LINUX_ONLY(+ 0x50)) {
1053    // This check is a little hacky, because on Linux the first C
1054    // frame's ('start_thread') register stack frame starts at
1055    // "register_stack_base + 0x48" while on HPUX, the first C frame's
1056    // ('__pthread_bound_body') register stack frame seems to really
1057    // start at "register_stack_base".
1058    return true;
1059  } else {
1060    return false;
1061  }
1062#elif defined(IA64) && defined(_WIN32)
1063  return true;
1064#else
1065  // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1066  // Check usp first, because if that's bad the other accessors may fault
1067  // on some architectures.  Ditto ufp second, etc.
1068  uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
1069  // sp on amd can be 32 bit aligned.
1070  uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
1071
1072  uintptr_t usp    = (uintptr_t)fr->sp();
1073  if ((usp & sp_align_mask) != 0) return true;
1074
1075  uintptr_t ufp    = (uintptr_t)fr->fp();
1076  if ((ufp & fp_align_mask) != 0) return true;
1077
1078  uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1079  if ((old_sp & sp_align_mask) != 0) return true;
1080  if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
1081
1082  uintptr_t old_fp = (uintptr_t)fr->link();
1083  if ((old_fp & fp_align_mask) != 0) return true;
1084  if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
1085
1086  // stack grows downwards; if old_fp is below current fp or if the stack
1087  // frame is too large, either the stack is corrupted or fp is not saved
1088  // on stack (i.e. on x86, ebp may be used as general register). The stack
1089  // is not walkable beyond current frame.
1090  if (old_fp < ufp) return true;
1091  if (old_fp - ufp > 64 * K) return true;
1092
1093  return false;
1094#endif
1095}
1096
1097#ifdef ASSERT
1098extern "C" void test_random() {
1099  const double m = 2147483647;
1100  double mean = 0.0, variance = 0.0, t;
1101  long reps = 10000;
1102  unsigned long seed = 1;
1103
1104  tty->print_cr("seed %ld for %ld repeats...", seed, reps);
1105  os::init_random(seed);
1106  long num;
1107  for (int k = 0; k < reps; k++) {
1108    num = os::random();
1109    double u = (double)num / m;
1110    assert(u >= 0.0 && u <= 1.0, "bad random number!");
1111
1112    // calculate mean and variance of the random sequence
1113    mean += u;
1114    variance += (u*u);
1115  }
1116  mean /= reps;
1117  variance /= (reps - 1);
1118
1119  assert(num == 1043618065, "bad seed");
1120  tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
1121  tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
1122  const double eps = 0.0001;
1123  t = fabsd(mean - 0.5018);
1124  assert(t < eps, "bad mean");
1125  t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
1126  assert(t < eps, "bad variance");
1127}
1128#endif
1129
1130
1131// Set up the boot classpath.
1132
1133char* os::format_boot_path(const char* format_string,
1134                           const char* home,
1135                           int home_len,
1136                           char fileSep,
1137                           char pathSep) {
1138    assert((fileSep == '/' && pathSep == ':') ||
1139           (fileSep == '\\' && pathSep == ';'), "unexpected separator chars");
1140
1141    // Scan the format string to determine the length of the actual
1142    // boot classpath, and handle platform dependencies as well.
1143    int formatted_path_len = 0;
1144    const char* p;
1145    for (p = format_string; *p != 0; ++p) {
1146        if (*p == '%') formatted_path_len += home_len - 1;
1147        ++formatted_path_len;
1148    }
1149
1150    char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1151    if (formatted_path == NULL) {
1152        return NULL;
1153    }
1154
1155    // Create boot classpath from format, substituting separator chars and
1156    // java home directory.
1157    char* q = formatted_path;
1158    for (p = format_string; *p != 0; ++p) {
1159        switch (*p) {
1160        case '%':
1161            strcpy(q, home);
1162            q += home_len;
1163            break;
1164        case '/':
1165            *q++ = fileSep;
1166            break;
1167        case ':':
1168            *q++ = pathSep;
1169            break;
1170        default:
1171            *q++ = *p;
1172        }
1173    }
1174    *q = '\0';
1175
1176    assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1177    return formatted_path;
1178}
1179
1180// returns a PATH of all entries in the given directory that do not start with a '.'
1181static char* expand_entries_to_path(char* directory, char fileSep, char pathSep) {
1182  DIR* dir = os::opendir(directory);
1183  if (dir == NULL) return NULL;
1184
1185  char* path = NULL;
1186  size_t path_len = 0;  // path length including \0 terminator
1187
1188  size_t directory_len = strlen(directory);
1189  struct dirent *entry;
1190  char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtInternal);
1191  while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
1192    const char* name = entry->d_name;
1193    if (name[0] == '.') continue;
1194
1195    size_t name_len = strlen(name);
1196    size_t needed = directory_len + name_len + 2;
1197    size_t new_len = path_len + needed;
1198    if (path == NULL) {
1199      path = NEW_C_HEAP_ARRAY(char, new_len, mtInternal);
1200    } else {
1201      path = REALLOC_C_HEAP_ARRAY(char, path, new_len, mtInternal);
1202    }
1203    if (path == NULL)
1204      break;
1205
1206    // append <pathSep>directory<fileSep>name
1207    char* p = path;
1208    if (path_len > 0) {
1209      p += (path_len -1);
1210      *p = pathSep;
1211      p++;
1212    }
1213
1214    strcpy(p, directory);
1215    p += directory_len;
1216
1217    *p = fileSep;
1218    p++;
1219
1220    strcpy(p, name);
1221    p += name_len;
1222
1223    path_len = new_len;
1224  }
1225
1226  FREE_C_HEAP_ARRAY(char, dbuf);
1227  os::closedir(dir);
1228
1229  return path;
1230}
1231
1232bool os::set_boot_path(char fileSep, char pathSep) {
1233  const char* home = Arguments::get_java_home();
1234  int home_len = (int)strlen(home);
1235
1236  char* sysclasspath = NULL;
1237  struct stat st;
1238
1239  // modular image if bootmodules.jimage exists
1240  char* jimage = format_boot_path("%/lib/modules/bootmodules.jimage", home, home_len, fileSep, pathSep);
1241  if (jimage == NULL) return false;
1242  bool has_jimage = (os::stat(jimage, &st) == 0);
1243  if (has_jimage) {
1244    Arguments::set_sysclasspath(jimage);
1245    return true;
1246  }
1247  FREE_C_HEAP_ARRAY(char, jimage);
1248
1249  // check if developer build with exploded modules
1250  char* modules_dir = format_boot_path("%/modules", home, home_len, fileSep, pathSep);
1251  if (os::stat(modules_dir, &st) == 0) {
1252    if ((st.st_mode & S_IFDIR) == S_IFDIR) {
1253      sysclasspath = expand_entries_to_path(modules_dir, fileSep, pathSep);
1254    }
1255  }
1256
1257  // fallback to classes
1258  if (sysclasspath == NULL)
1259    sysclasspath = format_boot_path("%/classes", home, home_len, fileSep, pathSep);
1260
1261  if (sysclasspath == NULL) return false;
1262  Arguments::set_sysclasspath(sysclasspath);
1263
1264  return true;
1265}
1266
1267/*
1268 * Splits a path, based on its separator, the number of
1269 * elements is returned back in n.
1270 * It is the callers responsibility to:
1271 *   a> check the value of n, and n may be 0.
1272 *   b> ignore any empty path elements
1273 *   c> free up the data.
1274 */
1275char** os::split_path(const char* path, int* n) {
1276  *n = 0;
1277  if (path == NULL || strlen(path) == 0) {
1278    return NULL;
1279  }
1280  const char psepchar = *os::path_separator();
1281  char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1282  if (inpath == NULL) {
1283    return NULL;
1284  }
1285  strcpy(inpath, path);
1286  int count = 1;
1287  char* p = strchr(inpath, psepchar);
1288  // Get a count of elements to allocate memory
1289  while (p != NULL) {
1290    count++;
1291    p++;
1292    p = strchr(p, psepchar);
1293  }
1294  char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1295  if (opath == NULL) {
1296    return NULL;
1297  }
1298
1299  // do the actual splitting
1300  p = inpath;
1301  for (int i = 0 ; i < count ; i++) {
1302    size_t len = strcspn(p, os::path_separator());
1303    if (len > JVM_MAXPATHLEN) {
1304      return NULL;
1305    }
1306    // allocate the string and add terminator storage
1307    char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1308    if (s == NULL) {
1309      return NULL;
1310    }
1311    strncpy(s, p, len);
1312    s[len] = '\0';
1313    opath[i] = s;
1314    p += len + 1;
1315  }
1316  FREE_C_HEAP_ARRAY(char, inpath);
1317  *n = count;
1318  return opath;
1319}
1320
1321void os::set_memory_serialize_page(address page) {
1322  int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
1323  _mem_serialize_page = (volatile int32_t *)page;
1324  // We initialize the serialization page shift count here
1325  // We assume a cache line size of 64 bytes
1326  assert(SerializePageShiftCount == count,
1327         "thread size changed, fix SerializePageShiftCount constant");
1328  set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
1329}
1330
1331static volatile intptr_t SerializePageLock = 0;
1332
1333// This method is called from signal handler when SIGSEGV occurs while the current
1334// thread tries to store to the "read-only" memory serialize page during state
1335// transition.
1336void os::block_on_serialize_page_trap() {
1337  if (TraceSafepoint) {
1338    tty->print_cr("Block until the serialize page permission restored");
1339  }
1340  // When VMThread is holding the SerializePageLock during modifying the
1341  // access permission of the memory serialize page, the following call
1342  // will block until the permission of that page is restored to rw.
1343  // Generally, it is unsafe to manipulate locks in signal handlers, but in
1344  // this case, it's OK as the signal is synchronous and we know precisely when
1345  // it can occur.
1346  Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
1347  Thread::muxRelease(&SerializePageLock);
1348}
1349
1350// Serialize all thread state variables
1351void os::serialize_thread_states() {
1352  // On some platforms such as Solaris & Linux, the time duration of the page
1353  // permission restoration is observed to be much longer than expected  due to
1354  // scheduler starvation problem etc. To avoid the long synchronization
1355  // time and expensive page trap spinning, 'SerializePageLock' is used to block
1356  // the mutator thread if such case is encountered. See bug 6546278 for details.
1357  Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
1358  os::protect_memory((char *)os::get_memory_serialize_page(),
1359                     os::vm_page_size(), MEM_PROT_READ);
1360  os::protect_memory((char *)os::get_memory_serialize_page(),
1361                     os::vm_page_size(), MEM_PROT_RW);
1362  Thread::muxRelease(&SerializePageLock);
1363}
1364
1365// Returns true if the current stack pointer is above the stack shadow
1366// pages, false otherwise.
1367
1368bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
1369  assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
1370  address sp = current_stack_pointer();
1371  // Check if we have StackShadowPages above the yellow zone.  This parameter
1372  // is dependent on the depth of the maximum VM call stack possible from
1373  // the handler for stack overflow.  'instanceof' in the stack overflow
1374  // handler or a println uses at least 8k stack of VM and native code
1375  // respectively.
1376  const int framesize_in_bytes =
1377    Interpreter::size_top_interpreter_activation(method()) * wordSize;
1378  int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
1379                      * vm_page_size()) + framesize_in_bytes;
1380  // The very lower end of the stack
1381  address stack_limit = thread->stack_base() - thread->stack_size();
1382  return (sp > (stack_limit + reserved_area));
1383}
1384
1385size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) {
1386  assert(min_pages > 0, "sanity");
1387  if (UseLargePages) {
1388    const size_t max_page_size = region_size / min_pages;
1389
1390    for (size_t i = 0; _page_sizes[i] != 0; ++i) {
1391      const size_t page_size = _page_sizes[i];
1392      if (page_size <= max_page_size) {
1393        if (!must_be_aligned || is_size_aligned(region_size, page_size)) {
1394          return page_size;
1395        }
1396      }
1397    }
1398  }
1399
1400  return vm_page_size();
1401}
1402
1403size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) {
1404  return page_size_for_region(region_size, min_pages, true);
1405}
1406
1407size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) {
1408  return page_size_for_region(region_size, min_pages, false);
1409}
1410
1411#ifndef PRODUCT
1412void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
1413{
1414  if (TracePageSizes) {
1415    tty->print("%s: ", str);
1416    for (int i = 0; i < count; ++i) {
1417      tty->print(" " SIZE_FORMAT, page_sizes[i]);
1418    }
1419    tty->cr();
1420  }
1421}
1422
1423void os::trace_page_sizes(const char* str, const size_t region_min_size,
1424                          const size_t region_max_size, const size_t page_size,
1425                          const char* base, const size_t size)
1426{
1427  if (TracePageSizes) {
1428    tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
1429                  " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
1430                  " size=" SIZE_FORMAT,
1431                  str, region_min_size, region_max_size,
1432                  page_size, base, size);
1433  }
1434}
1435#endif  // #ifndef PRODUCT
1436
1437// This is the working definition of a server class machine:
1438// >= 2 physical CPU's and >=2GB of memory, with some fuzz
1439// because the graphics memory (?) sometimes masks physical memory.
1440// If you want to change the definition of a server class machine
1441// on some OS or platform, e.g., >=4GB on Windows platforms,
1442// then you'll have to parameterize this method based on that state,
1443// as was done for logical processors here, or replicate and
1444// specialize this method for each platform.  (Or fix os to have
1445// some inheritance structure and use subclassing.  Sigh.)
1446// If you want some platform to always or never behave as a server
1447// class machine, change the setting of AlwaysActAsServerClassMachine
1448// and NeverActAsServerClassMachine in globals*.hpp.
1449bool os::is_server_class_machine() {
1450  // First check for the early returns
1451  if (NeverActAsServerClassMachine) {
1452    return false;
1453  }
1454  if (AlwaysActAsServerClassMachine) {
1455    return true;
1456  }
1457  // Then actually look at the machine
1458  bool         result            = false;
1459  const unsigned int    server_processors = 2;
1460  const julong server_memory     = 2UL * G;
1461  // We seem not to get our full complement of memory.
1462  //     We allow some part (1/8?) of the memory to be "missing",
1463  //     based on the sizes of DIMMs, and maybe graphics cards.
1464  const julong missing_memory   = 256UL * M;
1465
1466  /* Is this a server class machine? */
1467  if ((os::active_processor_count() >= (int)server_processors) &&
1468      (os::physical_memory() >= (server_memory - missing_memory))) {
1469    const unsigned int logical_processors =
1470      VM_Version::logical_processors_per_package();
1471    if (logical_processors > 1) {
1472      const unsigned int physical_packages =
1473        os::active_processor_count() / logical_processors;
1474      if (physical_packages > server_processors) {
1475        result = true;
1476      }
1477    } else {
1478      result = true;
1479    }
1480  }
1481  return result;
1482}
1483
1484void os::SuspendedThreadTask::run() {
1485  assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
1486  internal_do_task();
1487  _done = true;
1488}
1489
1490bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1491  return os::pd_create_stack_guard_pages(addr, bytes);
1492}
1493
1494char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
1495  char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1496  if (result != NULL) {
1497    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1498  }
1499
1500  return result;
1501}
1502
1503char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
1504   MEMFLAGS flags) {
1505  char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1506  if (result != NULL) {
1507    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1508    MemTracker::record_virtual_memory_type((address)result, flags);
1509  }
1510
1511  return result;
1512}
1513
1514char* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
1515  char* result = pd_attempt_reserve_memory_at(bytes, addr);
1516  if (result != NULL) {
1517    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
1518  }
1519  return result;
1520}
1521
1522void os::split_reserved_memory(char *base, size_t size,
1523                                 size_t split, bool realloc) {
1524  pd_split_reserved_memory(base, size, split, realloc);
1525}
1526
1527bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1528  bool res = pd_commit_memory(addr, bytes, executable);
1529  if (res) {
1530    MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1531  }
1532  return res;
1533}
1534
1535bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1536                              bool executable) {
1537  bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1538  if (res) {
1539    MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1540  }
1541  return res;
1542}
1543
1544void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1545                               const char* mesg) {
1546  pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1547  MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1548}
1549
1550void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1551                               bool executable, const char* mesg) {
1552  os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1553  MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1554}
1555
1556bool os::uncommit_memory(char* addr, size_t bytes) {
1557  bool res;
1558  if (MemTracker::tracking_level() > NMT_minimal) {
1559    Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
1560    res = pd_uncommit_memory(addr, bytes);
1561    if (res) {
1562      tkr.record((address)addr, bytes);
1563    }
1564  } else {
1565    res = pd_uncommit_memory(addr, bytes);
1566  }
1567  return res;
1568}
1569
1570bool os::release_memory(char* addr, size_t bytes) {
1571  bool res;
1572  if (MemTracker::tracking_level() > NMT_minimal) {
1573    Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1574    res = pd_release_memory(addr, bytes);
1575    if (res) {
1576      tkr.record((address)addr, bytes);
1577    }
1578  } else {
1579    res = pd_release_memory(addr, bytes);
1580  }
1581  return res;
1582}
1583
1584void os::pretouch_memory(char* start, char* end) {
1585  for (volatile char *p = start; p < end; p += os::vm_page_size()) {
1586    *p = 0;
1587  }
1588}
1589
1590char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1591                           char *addr, size_t bytes, bool read_only,
1592                           bool allow_exec) {
1593  char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1594  if (result != NULL) {
1595    MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC);
1596  }
1597  return result;
1598}
1599
1600char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1601                             char *addr, size_t bytes, bool read_only,
1602                             bool allow_exec) {
1603  return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1604                    read_only, allow_exec);
1605}
1606
1607bool os::unmap_memory(char *addr, size_t bytes) {
1608  bool result;
1609  if (MemTracker::tracking_level() > NMT_minimal) {
1610    Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1611    result = pd_unmap_memory(addr, bytes);
1612    if (result) {
1613      tkr.record((address)addr, bytes);
1614    }
1615  } else {
1616    result = pd_unmap_memory(addr, bytes);
1617  }
1618  return result;
1619}
1620
1621void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1622  pd_free_memory(addr, bytes, alignment_hint);
1623}
1624
1625void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1626  pd_realign_memory(addr, bytes, alignment_hint);
1627}
1628
1629#ifndef TARGET_OS_FAMILY_windows
1630/* try to switch state from state "from" to state "to"
1631 * returns the state set after the method is complete
1632 */
1633os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1634                                                         os::SuspendResume::State to)
1635{
1636  os::SuspendResume::State result =
1637    (os::SuspendResume::State) Atomic::cmpxchg((jint) to, (jint *) &_state, (jint) from);
1638  if (result == from) {
1639    // success
1640    return to;
1641  }
1642  return result;
1643}
1644#endif
1645
1646/////////////// Unit tests ///////////////
1647
1648#ifndef PRODUCT
1649
1650#define assert_eq(a,b) assert(a == b, err_msg(SIZE_FORMAT " != " SIZE_FORMAT, a, b))
1651
1652class TestOS : AllStatic {
1653  static size_t small_page_size() {
1654    return os::vm_page_size();
1655  }
1656
1657  static size_t large_page_size() {
1658    const size_t large_page_size_example = 4 * M;
1659    return os::page_size_for_region_aligned(large_page_size_example, 1);
1660  }
1661
1662  static void test_page_size_for_region_aligned() {
1663    if (UseLargePages) {
1664      const size_t small_page = small_page_size();
1665      const size_t large_page = large_page_size();
1666
1667      if (large_page > small_page) {
1668        size_t num_small_pages_in_large = large_page / small_page;
1669        size_t page = os::page_size_for_region_aligned(large_page, num_small_pages_in_large);
1670
1671        assert_eq(page, small_page);
1672      }
1673    }
1674  }
1675
1676  static void test_page_size_for_region_alignment() {
1677    if (UseLargePages) {
1678      const size_t small_page = small_page_size();
1679      const size_t large_page = large_page_size();
1680      if (large_page > small_page) {
1681        const size_t unaligned_region = large_page + 17;
1682        size_t page = os::page_size_for_region_aligned(unaligned_region, 1);
1683        assert_eq(page, small_page);
1684
1685        const size_t num_pages = 5;
1686        const size_t aligned_region = large_page * num_pages;
1687        page = os::page_size_for_region_aligned(aligned_region, num_pages);
1688        assert_eq(page, large_page);
1689      }
1690    }
1691  }
1692
1693  static void test_page_size_for_region_unaligned() {
1694    if (UseLargePages) {
1695      // Given exact page size, should return that page size.
1696      for (size_t i = 0; os::_page_sizes[i] != 0; i++) {
1697        size_t expected = os::_page_sizes[i];
1698        size_t actual = os::page_size_for_region_unaligned(expected, 1);
1699        assert_eq(expected, actual);
1700      }
1701
1702      // Given slightly larger size than a page size, return the page size.
1703      for (size_t i = 0; os::_page_sizes[i] != 0; i++) {
1704        size_t expected = os::_page_sizes[i];
1705        size_t actual = os::page_size_for_region_unaligned(expected + 17, 1);
1706        assert_eq(expected, actual);
1707      }
1708
1709      // Given a slightly smaller size than a page size,
1710      // return the next smaller page size.
1711      if (os::_page_sizes[1] > os::_page_sizes[0]) {
1712        size_t expected = os::_page_sizes[0];
1713        size_t actual = os::page_size_for_region_unaligned(os::_page_sizes[1] - 17, 1);
1714        assert_eq(actual, expected);
1715      }
1716
1717      // Return small page size for values less than a small page.
1718      size_t small_page = small_page_size();
1719      size_t actual = os::page_size_for_region_unaligned(small_page - 17, 1);
1720      assert_eq(small_page, actual);
1721    }
1722  }
1723
1724 public:
1725  static void run_tests() {
1726    test_page_size_for_region_aligned();
1727    test_page_size_for_region_alignment();
1728    test_page_size_for_region_unaligned();
1729  }
1730};
1731
1732void TestOS_test() {
1733  TestOS::run_tests();
1734}
1735
1736#endif // PRODUCT
1737