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