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