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