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