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