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