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