1 /* 2 * Copyright (c) 1997, 2019, 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 "jvm.h" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/javaClasses.hpp" 29 #include "classfile/moduleEntry.hpp" 30 #include "classfile/systemDictionary.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/icBuffer.hpp" 34 #include "code/vtableStubs.hpp" 35 #include "gc/shared/gcVMOperations.hpp" 36 #include "logging/log.hpp" 37 #include "interpreter/interpreter.hpp" 38 #include "logging/log.hpp" 39 #include "logging/logStream.hpp" 40 #include "memory/allocation.inline.hpp" 41 #include "memory/guardedMemory.hpp" 42 #include "memory/resourceArea.hpp" 43 #include "memory/universe.hpp" 44 #include "oops/compressedOops.inline.hpp" 45 #include "oops/oop.inline.hpp" 46 #include "prims/jvm_misc.hpp" 47 #include "runtime/arguments.hpp" 48 #include "runtime/atomic.hpp" 49 #include "runtime/frame.inline.hpp" 50 #include "runtime/handles.inline.hpp" 51 #include "runtime/interfaceSupport.inline.hpp" 52 #include "runtime/java.hpp" 53 #include "runtime/javaCalls.hpp" 54 #include "runtime/mutexLocker.hpp" 55 #include "runtime/os.inline.hpp" 56 #include "runtime/sharedRuntime.hpp" 57 #include "runtime/stubRoutines.hpp" 58 #include "runtime/thread.inline.hpp" 59 #include "runtime/threadSMR.hpp" 60 #include "runtime/vm_version.hpp" 61 #include "services/attachListener.hpp" 62 #include "services/mallocTracker.hpp" 63 #include "services/memTracker.hpp" 64 #include "services/nmtCommon.hpp" 65 #include "services/threadService.hpp" 66 #include "utilities/align.hpp" 67 #include "utilities/defaultStream.hpp" 68 #include "utilities/events.hpp" 69 70 # include <signal.h> 71 # include <errno.h> 72 73 OSThread* os::_starting_thread = NULL; 74 address os::_polling_page = NULL; 75 volatile unsigned int os::_rand_seed = 1; 76 int os::_processor_count = 0; 77 int os::_initial_active_processor_count = 0; 78 size_t os::_page_sizes[os::page_sizes_max]; 79 80 #ifndef PRODUCT 81 julong os::num_mallocs = 0; // # of calls to malloc/realloc 82 julong os::alloc_bytes = 0; // # of bytes allocated 83 julong os::num_frees = 0; // # of calls to free 84 julong os::free_bytes = 0; // # of bytes freed 85 #endif 86 87 static size_t cur_malloc_words = 0; // current size for MallocMaxTestWords 88 89 DEBUG_ONLY(bool os::_mutex_init_done = false;) 90 91 void os_init_globals() { 92 // Called from init_globals(). 93 // See Threads::create_vm() in thread.cpp, and init.cpp. 94 os::init_globals(); 95 } 96 97 static time_t get_timezone(const struct tm* time_struct) { 98 #if defined(_ALLBSD_SOURCE) 99 return time_struct->tm_gmtoff; 100 #elif defined(_WINDOWS) 101 long zone; 102 _get_timezone(&zone); 103 return static_cast<time_t>(zone); 104 #else 105 return timezone; 106 #endif 107 } 108 109 int os::snprintf(char* buf, size_t len, const char* fmt, ...) { 110 va_list args; 111 va_start(args, fmt); 112 int result = os::vsnprintf(buf, len, fmt, args); 113 va_end(args); 114 return result; 115 } 116 117 // Fill in buffer with current local time as an ISO-8601 string. 118 // E.g., yyyy-mm-ddThh:mm:ss-zzzz. 119 // Returns buffer, or NULL if it failed. 120 // This would mostly be a call to 121 // strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....) 122 // except that on Windows the %z behaves badly, so we do it ourselves. 123 // Also, people wanted milliseconds on there, 124 // and strftime doesn't do milliseconds. 125 char* os::iso8601_time(char* buffer, size_t buffer_length, bool utc) { 126 // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0" 127 // 1 2 128 // 12345678901234567890123456789 129 // format string: "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d" 130 static const size_t needed_buffer = 29; 131 132 // Sanity check the arguments 133 if (buffer == NULL) { 134 assert(false, "NULL buffer"); 135 return NULL; 136 } 137 if (buffer_length < needed_buffer) { 138 assert(false, "buffer_length too small"); 139 return NULL; 140 } 141 // Get the current time 142 jlong milliseconds_since_19700101 = javaTimeMillis(); 143 const int milliseconds_per_microsecond = 1000; 144 const time_t seconds_since_19700101 = 145 milliseconds_since_19700101 / milliseconds_per_microsecond; 146 const int milliseconds_after_second = 147 milliseconds_since_19700101 % milliseconds_per_microsecond; 148 // Convert the time value to a tm and timezone variable 149 struct tm time_struct; 150 if (utc) { 151 if (gmtime_pd(&seconds_since_19700101, &time_struct) == NULL) { 152 assert(false, "Failed gmtime_pd"); 153 return NULL; 154 } 155 } else { 156 if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) { 157 assert(false, "Failed localtime_pd"); 158 return NULL; 159 } 160 } 161 const time_t zone = get_timezone(&time_struct); 162 163 // If daylight savings time is in effect, 164 // we are 1 hour East of our time zone 165 const time_t seconds_per_minute = 60; 166 const time_t minutes_per_hour = 60; 167 const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour; 168 time_t UTC_to_local = zone; 169 if (time_struct.tm_isdst > 0) { 170 UTC_to_local = UTC_to_local - seconds_per_hour; 171 } 172 173 // No offset when dealing with UTC 174 if (utc) { 175 UTC_to_local = 0; 176 } 177 178 // Compute the time zone offset. 179 // localtime_pd() sets timezone to the difference (in seconds) 180 // between UTC and and local time. 181 // ISO 8601 says we need the difference between local time and UTC, 182 // we change the sign of the localtime_pd() result. 183 const time_t local_to_UTC = -(UTC_to_local); 184 // Then we have to figure out if if we are ahead (+) or behind (-) UTC. 185 char sign_local_to_UTC = '+'; 186 time_t abs_local_to_UTC = local_to_UTC; 187 if (local_to_UTC < 0) { 188 sign_local_to_UTC = '-'; 189 abs_local_to_UTC = -(abs_local_to_UTC); 190 } 191 // Convert time zone offset seconds to hours and minutes. 192 const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour); 193 const time_t zone_min = 194 ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute); 195 196 // Print an ISO 8601 date and time stamp into the buffer 197 const int year = 1900 + time_struct.tm_year; 198 const int month = 1 + time_struct.tm_mon; 199 const int printed = jio_snprintf(buffer, buffer_length, 200 "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d", 201 year, 202 month, 203 time_struct.tm_mday, 204 time_struct.tm_hour, 205 time_struct.tm_min, 206 time_struct.tm_sec, 207 milliseconds_after_second, 208 sign_local_to_UTC, 209 zone_hours, 210 zone_min); 211 if (printed == 0) { 212 assert(false, "Failed jio_printf"); 213 return NULL; 214 } 215 return buffer; 216 } 217 218 OSReturn os::set_priority(Thread* thread, ThreadPriority p) { 219 debug_only(Thread::check_for_dangling_thread_pointer(thread);) 220 221 if ((p >= MinPriority && p <= MaxPriority) || 222 (p == CriticalPriority && thread->is_ConcurrentGC_thread())) { 223 int priority = java_to_os_priority[p]; 224 return set_native_priority(thread, priority); 225 } else { 226 assert(false, "Should not happen"); 227 return OS_ERR; 228 } 229 } 230 231 // The mapping from OS priority back to Java priority may be inexact because 232 // Java priorities can map M:1 with native priorities. If you want the definite 233 // Java priority then use JavaThread::java_priority() 234 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) { 235 int p; 236 int os_prio; 237 OSReturn ret = get_native_priority(thread, &os_prio); 238 if (ret != OS_OK) return ret; 239 240 if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) { 241 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ; 242 } else { 243 // niceness values are in reverse order 244 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ; 245 } 246 priority = (ThreadPriority)p; 247 return OS_OK; 248 } 249 250 bool os::dll_build_name(char* buffer, size_t size, const char* fname) { 251 int n = jio_snprintf(buffer, size, "%s%s%s", JNI_LIB_PREFIX, fname, JNI_LIB_SUFFIX); 252 return (n != -1); 253 } 254 255 #if !defined(LINUX) && !defined(_WINDOWS) 256 bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) { 257 committed_start = start; 258 committed_size = size; 259 return true; 260 } 261 #endif 262 263 // Helper for dll_locate_lib. 264 // Pass buffer and printbuffer as we already printed the path to buffer 265 // when we called get_current_directory. This way we avoid another buffer 266 // of size MAX_PATH. 267 static bool conc_path_file_and_check(char *buffer, char *printbuffer, size_t printbuflen, 268 const char* pname, char lastchar, const char* fname) { 269 270 // Concatenate path and file name, but don't print double path separators. 271 const char *filesep = (WINDOWS_ONLY(lastchar == ':' ||) lastchar == os::file_separator()[0]) ? 272 "" : os::file_separator(); 273 int ret = jio_snprintf(printbuffer, printbuflen, "%s%s%s", pname, filesep, fname); 274 // Check whether file exists. 275 if (ret != -1) { 276 struct stat statbuf; 277 return os::stat(buffer, &statbuf) == 0; 278 } 279 return false; 280 } 281 282 // Frees all memory allocated on the heap for the 283 // supplied array of arrays of chars (a), where n 284 // is the number of elements in the array. 285 static void free_array_of_char_arrays(char** a, size_t n) { 286 while (n > 0) { 287 n--; 288 if (a[n] != NULL) { 289 FREE_C_HEAP_ARRAY(char, a[n]); 290 } 291 } 292 FREE_C_HEAP_ARRAY(char*, a); 293 } 294 295 bool os::dll_locate_lib(char *buffer, size_t buflen, 296 const char* pname, const char* fname) { 297 bool retval = false; 298 299 size_t fullfnamelen = strlen(JNI_LIB_PREFIX) + strlen(fname) + strlen(JNI_LIB_SUFFIX); 300 char* fullfname = (char*)NEW_C_HEAP_ARRAY(char, fullfnamelen + 1, mtInternal); 301 if (dll_build_name(fullfname, fullfnamelen + 1, fname)) { 302 const size_t pnamelen = pname ? strlen(pname) : 0; 303 304 if (pnamelen == 0) { 305 // If no path given, use current working directory. 306 const char* p = get_current_directory(buffer, buflen); 307 if (p != NULL) { 308 const size_t plen = strlen(buffer); 309 const char lastchar = buffer[plen - 1]; 310 retval = conc_path_file_and_check(buffer, &buffer[plen], buflen - plen, 311 "", lastchar, fullfname); 312 } 313 } else if (strchr(pname, *os::path_separator()) != NULL) { 314 // A list of paths. Search for the path that contains the library. 315 size_t n; 316 char** pelements = split_path(pname, &n, fullfnamelen); 317 if (pelements != NULL) { 318 for (size_t i = 0; i < n; i++) { 319 char* path = pelements[i]; 320 // Really shouldn't be NULL, but check can't hurt. 321 size_t plen = (path == NULL) ? 0 : strlen(path); 322 if (plen == 0) { 323 continue; // Skip the empty path values. 324 } 325 const char lastchar = path[plen - 1]; 326 retval = conc_path_file_and_check(buffer, buffer, buflen, path, lastchar, fullfname); 327 if (retval) break; 328 } 329 // Release the storage allocated by split_path. 330 free_array_of_char_arrays(pelements, n); 331 } 332 } else { 333 // A definite path. 334 const char lastchar = pname[pnamelen-1]; 335 retval = conc_path_file_and_check(buffer, buffer, buflen, pname, lastchar, fullfname); 336 } 337 } 338 339 FREE_C_HEAP_ARRAY(char*, fullfname); 340 return retval; 341 } 342 343 // --------------------- sun.misc.Signal (optional) --------------------- 344 345 346 // SIGBREAK is sent by the keyboard to query the VM state 347 #ifndef SIGBREAK 348 #define SIGBREAK SIGQUIT 349 #endif 350 351 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread. 352 353 354 static void signal_thread_entry(JavaThread* thread, TRAPS) { 355 os::set_priority(thread, NearMaxPriority); 356 while (true) { 357 int sig; 358 { 359 // FIXME : Currently we have not decided what should be the status 360 // for this java thread blocked here. Once we decide about 361 // that we should fix this. 362 sig = os::signal_wait(); 363 } 364 if (sig == os::sigexitnum_pd()) { 365 // Terminate the signal thread 366 return; 367 } 368 369 switch (sig) { 370 case SIGBREAK: { 371 // Check if the signal is a trigger to start the Attach Listener - in that 372 // case don't print stack traces. 373 if (!DisableAttachMechanism && AttachListener::is_init_trigger()) { 374 continue; 375 } 376 // Print stack traces 377 // Any SIGBREAK operations added here should make sure to flush 378 // the output stream (e.g. tty->flush()) after output. See 4803766. 379 // Each module also prints an extra carriage return after its output. 380 VM_PrintThreads op; 381 VMThread::execute(&op); 382 VM_PrintJNI jni_op; 383 VMThread::execute(&jni_op); 384 VM_FindDeadlocks op1(tty); 385 VMThread::execute(&op1); 386 Universe::print_heap_at_SIGBREAK(); 387 if (PrintClassHistogram) { 388 VM_GC_HeapInspection op1(tty, true /* force full GC before heap inspection */); 389 VMThread::execute(&op1); 390 } 391 if (JvmtiExport::should_post_data_dump()) { 392 JvmtiExport::post_data_dump(); 393 } 394 break; 395 } 396 default: { 397 // Dispatch the signal to java 398 HandleMark hm(THREAD); 399 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_misc_Signal(), THREAD); 400 if (klass != NULL) { 401 JavaValue result(T_VOID); 402 JavaCallArguments args; 403 args.push_int(sig); 404 JavaCalls::call_static( 405 &result, 406 klass, 407 vmSymbols::dispatch_name(), 408 vmSymbols::int_void_signature(), 409 &args, 410 THREAD 411 ); 412 } 413 if (HAS_PENDING_EXCEPTION) { 414 // tty is initialized early so we don't expect it to be null, but 415 // if it is we can't risk doing an initialization that might 416 // trigger additional out-of-memory conditions 417 if (tty != NULL) { 418 char klass_name[256]; 419 char tmp_sig_name[16]; 420 const char* sig_name = "UNKNOWN"; 421 InstanceKlass::cast(PENDING_EXCEPTION->klass())-> 422 name()->as_klass_external_name(klass_name, 256); 423 if (os::exception_name(sig, tmp_sig_name, 16) != NULL) 424 sig_name = tmp_sig_name; 425 warning("Exception %s occurred dispatching signal %s to handler" 426 "- the VM may need to be forcibly terminated", 427 klass_name, sig_name ); 428 } 429 CLEAR_PENDING_EXCEPTION; 430 } 431 } 432 } 433 } 434 } 435 436 void os::init_before_ergo() { 437 initialize_initial_active_processor_count(); 438 // We need to initialize large page support here because ergonomics takes some 439 // decisions depending on large page support and the calculated large page size. 440 large_page_init(); 441 442 // We need to adapt the configured number of stack protection pages given 443 // in 4K pages to the actual os page size. We must do this before setting 444 // up minimal stack sizes etc. in os::init_2(). 445 JavaThread::set_stack_red_zone_size (align_up(StackRedPages * 4 * K, vm_page_size())); 446 JavaThread::set_stack_yellow_zone_size (align_up(StackYellowPages * 4 * K, vm_page_size())); 447 JavaThread::set_stack_reserved_zone_size(align_up(StackReservedPages * 4 * K, vm_page_size())); 448 JavaThread::set_stack_shadow_zone_size (align_up(StackShadowPages * 4 * K, vm_page_size())); 449 450 // VM version initialization identifies some characteristics of the 451 // platform that are used during ergonomic decisions. 452 VM_Version::init_before_ergo(); 453 } 454 455 void os::initialize_jdk_signal_support(TRAPS) { 456 if (!ReduceSignalUsage) { 457 // Setup JavaThread for processing signals 458 const char thread_name[] = "Signal Dispatcher"; 459 Handle string = java_lang_String::create_from_str(thread_name, CHECK); 460 461 // Initialize thread_oop to put it into the system threadGroup 462 Handle thread_group (THREAD, Universe::system_thread_group()); 463 Handle thread_oop = JavaCalls::construct_new_instance(SystemDictionary::Thread_klass(), 464 vmSymbols::threadgroup_string_void_signature(), 465 thread_group, 466 string, 467 CHECK); 468 469 Klass* group = SystemDictionary::ThreadGroup_klass(); 470 JavaValue result(T_VOID); 471 JavaCalls::call_special(&result, 472 thread_group, 473 group, 474 vmSymbols::add_method_name(), 475 vmSymbols::thread_void_signature(), 476 thread_oop, 477 CHECK); 478 479 { MutexLocker mu(Threads_lock); 480 JavaThread* signal_thread = new JavaThread(&signal_thread_entry); 481 482 // At this point it may be possible that no osthread was created for the 483 // JavaThread due to lack of memory. We would have to throw an exception 484 // in that case. However, since this must work and we do not allow 485 // exceptions anyway, check and abort if this fails. 486 if (signal_thread == NULL || signal_thread->osthread() == NULL) { 487 vm_exit_during_initialization("java.lang.OutOfMemoryError", 488 os::native_thread_creation_failed_msg()); 489 } 490 491 java_lang_Thread::set_thread(thread_oop(), signal_thread); 492 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority); 493 java_lang_Thread::set_daemon(thread_oop()); 494 495 signal_thread->set_threadObj(thread_oop()); 496 Threads::add(signal_thread); 497 Thread::start(signal_thread); 498 } 499 // Handle ^BREAK 500 os::signal(SIGBREAK, os::user_handler()); 501 } 502 } 503 504 505 void os::terminate_signal_thread() { 506 if (!ReduceSignalUsage) 507 signal_notify(sigexitnum_pd()); 508 } 509 510 511 // --------------------- loading libraries --------------------- 512 513 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *); 514 extern struct JavaVM_ main_vm; 515 516 static void* _native_java_library = NULL; 517 518 void* os::native_java_library() { 519 if (_native_java_library == NULL) { 520 char buffer[JVM_MAXPATHLEN]; 521 char ebuf[1024]; 522 523 // Try to load verify dll first. In 1.3 java dll depends on it and is not 524 // always able to find it when the loading executable is outside the JDK. 525 // In order to keep working with 1.2 we ignore any loading errors. 526 if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 527 "verify")) { 528 dll_load(buffer, ebuf, sizeof(ebuf)); 529 } 530 531 // Load java dll 532 if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 533 "java")) { 534 _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf)); 535 } 536 if (_native_java_library == NULL) { 537 vm_exit_during_initialization("Unable to load native library", ebuf); 538 } 539 540 #if defined(__OpenBSD__) 541 // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so 542 // ignore errors 543 if (dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 544 "net")) { 545 dll_load(buffer, ebuf, sizeof(ebuf)); 546 } 547 #endif 548 } 549 return _native_java_library; 550 } 551 552 /* 553 * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists. 554 * If check_lib == true then we are looking for an 555 * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if 556 * this library is statically linked into the image. 557 * If check_lib == false then we will look for the appropriate symbol in the 558 * executable if agent_lib->is_static_lib() == true or in the shared library 559 * referenced by 'handle'. 560 */ 561 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib, 562 const char *syms[], size_t syms_len) { 563 assert(agent_lib != NULL, "sanity check"); 564 const char *lib_name; 565 void *handle = agent_lib->os_lib(); 566 void *entryName = NULL; 567 char *agent_function_name; 568 size_t i; 569 570 // If checking then use the agent name otherwise test is_static_lib() to 571 // see how to process this lookup 572 lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL); 573 for (i = 0; i < syms_len; i++) { 574 agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path()); 575 if (agent_function_name == NULL) { 576 break; 577 } 578 entryName = dll_lookup(handle, agent_function_name); 579 FREE_C_HEAP_ARRAY(char, agent_function_name); 580 if (entryName != NULL) { 581 break; 582 } 583 } 584 return entryName; 585 } 586 587 // See if the passed in agent is statically linked into the VM image. 588 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[], 589 size_t syms_len) { 590 void *ret; 591 void *proc_handle; 592 void *save_handle; 593 594 assert(agent_lib != NULL, "sanity check"); 595 if (agent_lib->name() == NULL) { 596 return false; 597 } 598 proc_handle = get_default_process_handle(); 599 // Check for Agent_OnLoad/Attach_lib_name function 600 save_handle = agent_lib->os_lib(); 601 // We want to look in this process' symbol table. 602 agent_lib->set_os_lib(proc_handle); 603 ret = find_agent_function(agent_lib, true, syms, syms_len); 604 if (ret != NULL) { 605 // Found an entry point like Agent_OnLoad_lib_name so we have a static agent 606 agent_lib->set_valid(); 607 agent_lib->set_static_lib(true); 608 return true; 609 } 610 agent_lib->set_os_lib(save_handle); 611 return false; 612 } 613 614 // --------------------- heap allocation utilities --------------------- 615 616 char *os::strdup(const char *str, MEMFLAGS flags) { 617 size_t size = strlen(str); 618 char *dup_str = (char *)malloc(size + 1, flags); 619 if (dup_str == NULL) return NULL; 620 strcpy(dup_str, str); 621 return dup_str; 622 } 623 624 char* os::strdup_check_oom(const char* str, MEMFLAGS flags) { 625 char* p = os::strdup(str, flags); 626 if (p == NULL) { 627 vm_exit_out_of_memory(strlen(str) + 1, OOM_MALLOC_ERROR, "os::strdup_check_oom"); 628 } 629 return p; 630 } 631 632 633 #define paranoid 0 /* only set to 1 if you suspect checking code has bug */ 634 635 #ifdef ASSERT 636 637 static void verify_memory(void* ptr) { 638 GuardedMemory guarded(ptr); 639 if (!guarded.verify_guards()) { 640 LogTarget(Warning, malloc, free) lt; 641 ResourceMark rm; 642 LogStream ls(lt); 643 ls.print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees); 644 ls.print_cr("## memory stomp:"); 645 guarded.print_on(&ls); 646 fatal("memory stomping error"); 647 } 648 } 649 650 #endif 651 652 // 653 // This function supports testing of the malloc out of memory 654 // condition without really running the system out of memory. 655 // 656 static bool has_reached_max_malloc_test_peak(size_t alloc_size) { 657 if (MallocMaxTestWords > 0) { 658 size_t words = (alloc_size / BytesPerWord); 659 660 if ((cur_malloc_words + words) > MallocMaxTestWords) { 661 return true; 662 } 663 Atomic::add(words, &cur_malloc_words); 664 } 665 return false; 666 } 667 668 void* os::malloc(size_t size, MEMFLAGS flags) { 669 return os::malloc(size, flags, CALLER_PC); 670 } 671 672 void* os::malloc(size_t size, MEMFLAGS memflags, const NativeCallStack& stack) { 673 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1)); 674 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size)); 675 676 // Since os::malloc can be called when the libjvm.{dll,so} is 677 // first loaded and we don't have a thread yet we must accept NULL also here. 678 assert(!os::ThreadCrashProtection::is_crash_protected(Thread::current_or_null()), 679 "malloc() not allowed when crash protection is set"); 680 681 if (size == 0) { 682 // return a valid pointer if size is zero 683 // if NULL is returned the calling functions assume out of memory. 684 size = 1; 685 } 686 687 // NMT support 688 NMT_TrackingLevel level = MemTracker::tracking_level(); 689 size_t nmt_header_size = MemTracker::malloc_header_size(level); 690 691 #ifndef ASSERT 692 const size_t alloc_size = size + nmt_header_size; 693 #else 694 const size_t alloc_size = GuardedMemory::get_total_size(size + nmt_header_size); 695 if (size + nmt_header_size > alloc_size) { // Check for rollover. 696 return NULL; 697 } 698 #endif 699 700 // For the test flag -XX:MallocMaxTestWords 701 if (has_reached_max_malloc_test_peak(size)) { 702 return NULL; 703 } 704 705 u_char* ptr; 706 ptr = (u_char*)::malloc(alloc_size); 707 708 #ifdef ASSERT 709 if (ptr == NULL) { 710 return NULL; 711 } 712 // Wrap memory with guard 713 GuardedMemory guarded(ptr, size + nmt_header_size); 714 ptr = guarded.get_user_ptr(); 715 716 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) { 717 log_warning(malloc, free)("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, p2i(ptr)); 718 breakpoint(); 719 } 720 if (paranoid) { 721 verify_memory(ptr); 722 } 723 #endif 724 725 // we do not track guard memory 726 return MemTracker::record_malloc((address)ptr, size, memflags, stack, level); 727 } 728 729 void* os::realloc(void *memblock, size_t size, MEMFLAGS flags) { 730 return os::realloc(memblock, size, flags, CALLER_PC); 731 } 732 733 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, const NativeCallStack& stack) { 734 735 // For the test flag -XX:MallocMaxTestWords 736 if (has_reached_max_malloc_test_peak(size)) { 737 return NULL; 738 } 739 740 if (size == 0) { 741 // return a valid pointer if size is zero 742 // if NULL is returned the calling functions assume out of memory. 743 size = 1; 744 } 745 746 #ifndef ASSERT 747 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1)); 748 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size)); 749 // NMT support 750 void* membase = MemTracker::record_free(memblock); 751 NMT_TrackingLevel level = MemTracker::tracking_level(); 752 size_t nmt_header_size = MemTracker::malloc_header_size(level); 753 void* ptr = ::realloc(membase, size + nmt_header_size); 754 return MemTracker::record_malloc(ptr, size, memflags, stack, level); 755 #else 756 if (memblock == NULL) { 757 return os::malloc(size, memflags, stack); 758 } 759 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { 760 log_warning(malloc, free)("os::realloc caught " PTR_FORMAT, p2i(memblock)); 761 breakpoint(); 762 } 763 // NMT support 764 void* membase = MemTracker::malloc_base(memblock); 765 verify_memory(membase); 766 // always move the block 767 void* ptr = os::malloc(size, memflags, stack); 768 // Copy to new memory if malloc didn't fail 769 if (ptr != NULL ) { 770 GuardedMemory guarded(MemTracker::malloc_base(memblock)); 771 // Guard's user data contains NMT header 772 size_t memblock_size = guarded.get_user_size() - MemTracker::malloc_header_size(memblock); 773 memcpy(ptr, memblock, MIN2(size, memblock_size)); 774 if (paranoid) { 775 verify_memory(MemTracker::malloc_base(ptr)); 776 } 777 os::free(memblock); 778 } 779 return ptr; 780 #endif 781 } 782 783 784 void os::free(void *memblock) { 785 NOT_PRODUCT(inc_stat_counter(&num_frees, 1)); 786 #ifdef ASSERT 787 if (memblock == NULL) return; 788 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { 789 log_warning(malloc, free)("os::free caught " PTR_FORMAT, p2i(memblock)); 790 breakpoint(); 791 } 792 void* membase = MemTracker::record_free(memblock); 793 verify_memory(membase); 794 795 GuardedMemory guarded(membase); 796 size_t size = guarded.get_user_size(); 797 inc_stat_counter(&free_bytes, size); 798 membase = guarded.release_for_freeing(); 799 ::free(membase); 800 #else 801 void* membase = MemTracker::record_free(memblock); 802 ::free(membase); 803 #endif 804 } 805 806 void os::init_random(unsigned int initval) { 807 _rand_seed = initval; 808 } 809 810 811 static int random_helper(unsigned int rand_seed) { 812 /* standard, well-known linear congruential random generator with 813 * next_rand = (16807*seed) mod (2**31-1) 814 * see 815 * (1) "Random Number Generators: Good Ones Are Hard to Find", 816 * S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988), 817 * (2) "Two Fast Implementations of the 'Minimal Standard' Random 818 * Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88. 819 */ 820 const unsigned int a = 16807; 821 const unsigned int m = 2147483647; 822 const int q = m / a; assert(q == 127773, "weird math"); 823 const int r = m % a; assert(r == 2836, "weird math"); 824 825 // compute az=2^31p+q 826 unsigned int lo = a * (rand_seed & 0xFFFF); 827 unsigned int hi = a * (rand_seed >> 16); 828 lo += (hi & 0x7FFF) << 16; 829 830 // if q overflowed, ignore the overflow and increment q 831 if (lo > m) { 832 lo &= m; 833 ++lo; 834 } 835 lo += hi >> 15; 836 837 // if (p+q) overflowed, ignore the overflow and increment (p+q) 838 if (lo > m) { 839 lo &= m; 840 ++lo; 841 } 842 return lo; 843 } 844 845 int os::random() { 846 // Make updating the random seed thread safe. 847 while (true) { 848 unsigned int seed = _rand_seed; 849 unsigned int rand = random_helper(seed); 850 if (Atomic::cmpxchg(rand, &_rand_seed, seed) == seed) { 851 return static_cast<int>(rand); 852 } 853 } 854 } 855 856 // The INITIALIZED state is distinguished from the SUSPENDED state because the 857 // conditions in which a thread is first started are different from those in which 858 // a suspension is resumed. These differences make it hard for us to apply the 859 // tougher checks when starting threads that we want to do when resuming them. 860 // However, when start_thread is called as a result of Thread.start, on a Java 861 // thread, the operation is synchronized on the Java Thread object. So there 862 // cannot be a race to start the thread and hence for the thread to exit while 863 // we are working on it. Non-Java threads that start Java threads either have 864 // to do so in a context in which races are impossible, or should do appropriate 865 // locking. 866 867 void os::start_thread(Thread* thread) { 868 // guard suspend/resume 869 MutexLocker ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag); 870 OSThread* osthread = thread->osthread(); 871 osthread->set_state(RUNNABLE); 872 pd_start_thread(thread); 873 } 874 875 void os::abort(bool dump_core) { 876 abort(dump_core && CreateCoredumpOnCrash, NULL, NULL); 877 } 878 879 //--------------------------------------------------------------------------- 880 // Helper functions for fatal error handler 881 882 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) { 883 assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking"); 884 885 start = align_down(start, unitsize); 886 887 int cols = 0; 888 int cols_per_line = 0; 889 switch (unitsize) { 890 case 1: cols_per_line = 16; break; 891 case 2: cols_per_line = 8; break; 892 case 4: cols_per_line = 4; break; 893 case 8: cols_per_line = 2; break; 894 default: return; 895 } 896 897 address p = start; 898 st->print(PTR_FORMAT ": ", p2i(start)); 899 while (p < end) { 900 if (is_readable_pointer(p)) { 901 switch (unitsize) { 902 case 1: st->print("%02x", *(u1*)p); break; 903 case 2: st->print("%04x", *(u2*)p); break; 904 case 4: st->print("%08x", *(u4*)p); break; 905 case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break; 906 } 907 } else { 908 st->print("%*.*s", 2*unitsize, 2*unitsize, "????????????????"); 909 } 910 p += unitsize; 911 cols++; 912 if (cols >= cols_per_line && p < end) { 913 cols = 0; 914 st->cr(); 915 st->print(PTR_FORMAT ": ", p2i(p)); 916 } else { 917 st->print(" "); 918 } 919 } 920 st->cr(); 921 } 922 923 void os::print_instructions(outputStream* st, address pc, int unitsize) { 924 st->print_cr("Instructions: (pc=" PTR_FORMAT ")", p2i(pc)); 925 print_hex_dump(st, pc - 256, pc + 256, unitsize); 926 } 927 928 void os::print_environment_variables(outputStream* st, const char** env_list) { 929 if (env_list) { 930 st->print_cr("Environment Variables:"); 931 932 for (int i = 0; env_list[i] != NULL; i++) { 933 char *envvar = ::getenv(env_list[i]); 934 if (envvar != NULL) { 935 st->print("%s", env_list[i]); 936 st->print("="); 937 st->print_cr("%s", envvar); 938 } 939 } 940 } 941 } 942 943 void os::print_cpu_info(outputStream* st, char* buf, size_t buflen) { 944 // cpu 945 st->print("CPU:"); 946 st->print("total %d", os::processor_count()); 947 // It's not safe to query number of active processors after crash 948 // st->print("(active %d)", os::active_processor_count()); but we can 949 // print the initial number of active processors. 950 // We access the raw value here because the assert in the accessor will 951 // fail if the crash occurs before initialization of this value. 952 st->print(" (initial active %d)", _initial_active_processor_count); 953 st->print(" %s", VM_Version::features_string()); 954 st->cr(); 955 pd_print_cpu_info(st, buf, buflen); 956 } 957 958 // Print a one line string summarizing the cpu, number of cores, memory, and operating system version 959 void os::print_summary_info(outputStream* st, char* buf, size_t buflen) { 960 st->print("Host: "); 961 #ifndef PRODUCT 962 if (get_host_name(buf, buflen)) { 963 st->print("%s, ", buf); 964 } 965 #endif // PRODUCT 966 get_summary_cpu_info(buf, buflen); 967 st->print("%s, ", buf); 968 size_t mem = physical_memory()/G; 969 if (mem == 0) { // for low memory systems 970 mem = physical_memory()/M; 971 st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem); 972 } else { 973 st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem); 974 } 975 get_summary_os_info(buf, buflen); 976 st->print_raw(buf); 977 st->cr(); 978 } 979 980 void os::print_date_and_time(outputStream *st, char* buf, size_t buflen) { 981 const int secs_per_day = 86400; 982 const int secs_per_hour = 3600; 983 const int secs_per_min = 60; 984 985 time_t tloc; 986 (void)time(&tloc); 987 char* timestring = ctime(&tloc); // ctime adds newline. 988 // edit out the newline 989 char* nl = strchr(timestring, '\n'); 990 if (nl != NULL) { 991 *nl = '\0'; 992 } 993 994 struct tm tz; 995 if (localtime_pd(&tloc, &tz) != NULL) { 996 ::strftime(buf, buflen, "%Z", &tz); 997 st->print("Time: %s %s", timestring, buf); 998 } else { 999 st->print("Time: %s", timestring); 1000 } 1001 1002 double t = os::elapsedTime(); 1003 // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in 1004 // Linux. Must be a bug in glibc ? Workaround is to round "t" to int 1005 // before printf. We lost some precision, but who cares? 1006 int eltime = (int)t; // elapsed time in seconds 1007 1008 // print elapsed time in a human-readable format: 1009 int eldays = eltime / secs_per_day; 1010 int day_secs = eldays * secs_per_day; 1011 int elhours = (eltime - day_secs) / secs_per_hour; 1012 int hour_secs = elhours * secs_per_hour; 1013 int elmins = (eltime - day_secs - hour_secs) / secs_per_min; 1014 int minute_secs = elmins * secs_per_min; 1015 int elsecs = (eltime - day_secs - hour_secs - minute_secs); 1016 st->print_cr(" elapsed time: %d seconds (%dd %dh %dm %ds)", eltime, eldays, elhours, elmins, elsecs); 1017 } 1018 1019 1020 // Check if pointer can be read from (4-byte read access). 1021 // Helps to prove validity of a not-NULL pointer. 1022 // Returns true in very early stages of VM life when stub is not yet generated. 1023 #define SAFEFETCH_DEFAULT true 1024 bool os::is_readable_pointer(const void* p) { 1025 if (!CanUseSafeFetch32()) { 1026 return SAFEFETCH_DEFAULT; 1027 } 1028 int* const aligned = (int*) align_down((intptr_t)p, 4); 1029 int cafebabe = 0xcafebabe; // tester value 1 1030 int deadbeef = 0xdeadbeef; // tester value 2 1031 return (SafeFetch32(aligned, cafebabe) != cafebabe) || (SafeFetch32(aligned, deadbeef) != deadbeef); 1032 } 1033 1034 bool os::is_readable_range(const void* from, const void* to) { 1035 if ((uintptr_t)from >= (uintptr_t)to) return false; 1036 for (uintptr_t p = align_down((uintptr_t)from, min_page_size()); p < (uintptr_t)to; p += min_page_size()) { 1037 if (!is_readable_pointer((const void*)p)) { 1038 return false; 1039 } 1040 } 1041 return true; 1042 } 1043 1044 1045 // moved from debug.cpp (used to be find()) but still called from there 1046 // The verbose parameter is only set by the debug code in one case 1047 void os::print_location(outputStream* st, intptr_t x, bool verbose) { 1048 address addr = (address)x; 1049 // Handle NULL first, so later checks don't need to protect against it. 1050 if (addr == NULL) { 1051 st->print_cr("0x0 is NULL"); 1052 return; 1053 } 1054 1055 // Check if addr points into a code blob. 1056 CodeBlob* b = CodeCache::find_blob_unsafe(addr); 1057 if (b != NULL) { 1058 b->dump_for_addr(addr, st, verbose); 1059 return; 1060 } 1061 1062 // Check if addr points into Java heap. 1063 if (Universe::heap()->is_in(addr)) { 1064 oop o = oopDesc::oop_or_null(addr); 1065 if (o != NULL) { 1066 if ((HeapWord*)o == (HeapWord*)addr) { 1067 st->print(INTPTR_FORMAT " is an oop: ", p2i(addr)); 1068 } else { 1069 st->print(INTPTR_FORMAT " is pointing into object: " , p2i(addr)); 1070 } 1071 o->print_on(st); 1072 return; 1073 } 1074 } else if (Universe::heap()->is_in_reserved(addr)) { 1075 st->print_cr(INTPTR_FORMAT " is an unallocated location in the heap", p2i(addr)); 1076 return; 1077 } 1078 1079 // Compressed oop needs to be decoded first. 1080 #ifdef _LP64 1081 if (UseCompressedOops && ((uintptr_t)addr &~ (uintptr_t)max_juint) == 0) { 1082 narrowOop narrow_oop = (narrowOop)(uintptr_t)addr; 1083 oop o = CompressedOops::decode_raw(narrow_oop); 1084 1085 if (oopDesc::is_valid(o)) { 1086 st->print(UINT32_FORMAT " is a compressed pointer to object: ", narrow_oop); 1087 o->print_on(st); 1088 return; 1089 } 1090 } 1091 #endif 1092 1093 bool accessible = is_readable_pointer(addr); 1094 1095 // Check if addr is a JNI handle. 1096 if (align_down((intptr_t)addr, sizeof(intptr_t)) != 0 && accessible) { 1097 if (JNIHandles::is_global_handle((jobject) addr)) { 1098 st->print_cr(INTPTR_FORMAT " is a global jni handle", p2i(addr)); 1099 return; 1100 } 1101 if (JNIHandles::is_weak_global_handle((jobject) addr)) { 1102 st->print_cr(INTPTR_FORMAT " is a weak global jni handle", p2i(addr)); 1103 return; 1104 } 1105 #ifndef PRODUCT 1106 // we don't keep the block list in product mode 1107 if (JNIHandles::is_local_handle((jobject) addr)) { 1108 st->print_cr(INTPTR_FORMAT " is a local jni handle", p2i(addr)); 1109 return; 1110 } 1111 #endif 1112 } 1113 1114 // Check if addr belongs to a Java thread. 1115 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) { 1116 // If the addr is a java thread print information about that. 1117 if (addr == (address)thread) { 1118 if (verbose) { 1119 thread->print_on(st); 1120 } else { 1121 st->print_cr(INTPTR_FORMAT " is a thread", p2i(addr)); 1122 } 1123 return; 1124 } 1125 // If the addr is in the stack region for this thread then report that 1126 // and print thread info 1127 if (thread->on_local_stack(addr)) { 1128 st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: " 1129 INTPTR_FORMAT, p2i(addr), p2i(thread)); 1130 if (verbose) thread->print_on(st); 1131 return; 1132 } 1133 } 1134 1135 // Check if in metaspace and print types that have vptrs 1136 if (Metaspace::contains(addr)) { 1137 if (Klass::is_valid((Klass*)addr)) { 1138 st->print_cr(INTPTR_FORMAT " is a pointer to class: ", p2i(addr)); 1139 ((Klass*)addr)->print_on(st); 1140 } else if (Method::is_valid_method((const Method*)addr)) { 1141 ((Method*)addr)->print_value_on(st); 1142 st->cr(); 1143 } else { 1144 // Use addr->print() from the debugger instead (not here) 1145 st->print_cr(INTPTR_FORMAT " is pointing into metadata", p2i(addr)); 1146 } 1147 return; 1148 } 1149 1150 // Compressed klass needs to be decoded first. 1151 #ifdef _LP64 1152 if (UseCompressedClassPointers && ((uintptr_t)addr &~ (uintptr_t)max_juint) == 0) { 1153 narrowKlass narrow_klass = (narrowKlass)(uintptr_t)addr; 1154 Klass* k = CompressedKlassPointers::decode_raw(narrow_klass); 1155 1156 if (Klass::is_valid(k)) { 1157 st->print_cr(UINT32_FORMAT " is a compressed pointer to class: " INTPTR_FORMAT, narrow_klass, p2i((HeapWord*)k)); 1158 k->print_on(st); 1159 return; 1160 } 1161 } 1162 #endif 1163 1164 // Try an OS specific find 1165 if (os::find(addr, st)) { 1166 return; 1167 } 1168 1169 if (accessible) { 1170 st->print(INTPTR_FORMAT " points into unknown readable memory:", p2i(addr)); 1171 for (address p = addr; p < align_up(addr + 1, sizeof(intptr_t)); ++p) { 1172 st->print(" %02x", *(u1*)p); 1173 } 1174 st->cr(); 1175 return; 1176 } 1177 1178 st->print_cr(INTPTR_FORMAT " is an unknown value", p2i(addr)); 1179 } 1180 1181 // Looks like all platforms can use the same function to check if C 1182 // stack is walkable beyond current frame. The check for fp() is not 1183 // necessary on Sparc, but it's harmless. 1184 bool os::is_first_C_frame(frame* fr) { 1185 // Load up sp, fp, sender sp and sender fp, check for reasonable values. 1186 // Check usp first, because if that's bad the other accessors may fault 1187 // on some architectures. Ditto ufp second, etc. 1188 uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1); 1189 // sp on amd can be 32 bit aligned. 1190 uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1); 1191 1192 uintptr_t usp = (uintptr_t)fr->sp(); 1193 if ((usp & sp_align_mask) != 0) return true; 1194 1195 uintptr_t ufp = (uintptr_t)fr->fp(); 1196 if ((ufp & fp_align_mask) != 0) return true; 1197 1198 uintptr_t old_sp = (uintptr_t)fr->sender_sp(); 1199 if ((old_sp & sp_align_mask) != 0) return true; 1200 if (old_sp == 0 || old_sp == (uintptr_t)-1) return true; 1201 1202 uintptr_t old_fp = (uintptr_t)fr->link(); 1203 if ((old_fp & fp_align_mask) != 0) return true; 1204 if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true; 1205 1206 // stack grows downwards; if old_fp is below current fp or if the stack 1207 // frame is too large, either the stack is corrupted or fp is not saved 1208 // on stack (i.e. on x86, ebp may be used as general register). The stack 1209 // is not walkable beyond current frame. 1210 if (old_fp < ufp) return true; 1211 if (old_fp - ufp > 64 * K) return true; 1212 1213 return false; 1214 } 1215 1216 1217 // Set up the boot classpath. 1218 1219 char* os::format_boot_path(const char* format_string, 1220 const char* home, 1221 int home_len, 1222 char fileSep, 1223 char pathSep) { 1224 assert((fileSep == '/' && pathSep == ':') || 1225 (fileSep == '\\' && pathSep == ';'), "unexpected separator chars"); 1226 1227 // Scan the format string to determine the length of the actual 1228 // boot classpath, and handle platform dependencies as well. 1229 int formatted_path_len = 0; 1230 const char* p; 1231 for (p = format_string; *p != 0; ++p) { 1232 if (*p == '%') formatted_path_len += home_len - 1; 1233 ++formatted_path_len; 1234 } 1235 1236 char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal); 1237 if (formatted_path == NULL) { 1238 return NULL; 1239 } 1240 1241 // Create boot classpath from format, substituting separator chars and 1242 // java home directory. 1243 char* q = formatted_path; 1244 for (p = format_string; *p != 0; ++p) { 1245 switch (*p) { 1246 case '%': 1247 strcpy(q, home); 1248 q += home_len; 1249 break; 1250 case '/': 1251 *q++ = fileSep; 1252 break; 1253 case ':': 1254 *q++ = pathSep; 1255 break; 1256 default: 1257 *q++ = *p; 1258 } 1259 } 1260 *q = '\0'; 1261 1262 assert((q - formatted_path) == formatted_path_len, "formatted_path size botched"); 1263 return formatted_path; 1264 } 1265 1266 // This function is a proxy to fopen, it tries to add a non standard flag ('e' or 'N') 1267 // that ensures automatic closing of the file on exec. If it can not find support in 1268 // the underlying c library, it will make an extra system call (fcntl) to ensure automatic 1269 // closing of the file on exec. 1270 FILE* os::fopen(const char* path, const char* mode) { 1271 char modified_mode[20]; 1272 assert(strlen(mode) + 1 < sizeof(modified_mode), "mode chars plus one extra must fit in buffer"); 1273 sprintf(modified_mode, "%s" LINUX_ONLY("e") BSD_ONLY("e") WINDOWS_ONLY("N"), mode); 1274 FILE* file = ::fopen(path, modified_mode); 1275 1276 #if !(defined LINUX || defined BSD || defined _WINDOWS) 1277 // assume fcntl FD_CLOEXEC support as a backup solution when 'e' or 'N' 1278 // is not supported as mode in fopen 1279 if (file != NULL) { 1280 int fd = fileno(file); 1281 if (fd != -1) { 1282 int fd_flags = fcntl(fd, F_GETFD); 1283 if (fd_flags != -1) { 1284 fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC); 1285 } 1286 } 1287 } 1288 #endif 1289 1290 return file; 1291 } 1292 1293 bool os::set_boot_path(char fileSep, char pathSep) { 1294 const char* home = Arguments::get_java_home(); 1295 int home_len = (int)strlen(home); 1296 1297 struct stat st; 1298 1299 // modular image if "modules" jimage exists 1300 char* jimage = format_boot_path("%/lib/" MODULES_IMAGE_NAME, home, home_len, fileSep, pathSep); 1301 if (jimage == NULL) return false; 1302 bool has_jimage = (os::stat(jimage, &st) == 0); 1303 if (has_jimage) { 1304 Arguments::set_sysclasspath(jimage, true); 1305 FREE_C_HEAP_ARRAY(char, jimage); 1306 return true; 1307 } 1308 FREE_C_HEAP_ARRAY(char, jimage); 1309 1310 // check if developer build with exploded modules 1311 char* base_classes = format_boot_path("%/modules/" JAVA_BASE_NAME, home, home_len, fileSep, pathSep); 1312 if (base_classes == NULL) return false; 1313 if (os::stat(base_classes, &st) == 0) { 1314 Arguments::set_sysclasspath(base_classes, false); 1315 FREE_C_HEAP_ARRAY(char, base_classes); 1316 return true; 1317 } 1318 FREE_C_HEAP_ARRAY(char, base_classes); 1319 1320 return false; 1321 } 1322 1323 // Splits a path, based on its separator, the number of 1324 // elements is returned back in "elements". 1325 // file_name_length is used as a modifier for each path's 1326 // length when compared to JVM_MAXPATHLEN. So if you know 1327 // each returned path will have something appended when 1328 // in use, you can pass the length of that in 1329 // file_name_length, to ensure we detect if any path 1330 // exceeds the maximum path length once prepended onto 1331 // the sub-path/file name. 1332 // It is the callers responsibility to: 1333 // a> check the value of "elements", which may be 0. 1334 // b> ignore any empty path elements 1335 // c> free up the data. 1336 char** os::split_path(const char* path, size_t* elements, size_t file_name_length) { 1337 *elements = (size_t)0; 1338 if (path == NULL || strlen(path) == 0 || file_name_length == (size_t)NULL) { 1339 return NULL; 1340 } 1341 const char psepchar = *os::path_separator(); 1342 char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal); 1343 if (inpath == NULL) { 1344 return NULL; 1345 } 1346 strcpy(inpath, path); 1347 size_t count = 1; 1348 char* p = strchr(inpath, psepchar); 1349 // Get a count of elements to allocate memory 1350 while (p != NULL) { 1351 count++; 1352 p++; 1353 p = strchr(p, psepchar); 1354 } 1355 char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal); 1356 1357 // do the actual splitting 1358 p = inpath; 1359 for (size_t i = 0 ; i < count ; i++) { 1360 size_t len = strcspn(p, os::path_separator()); 1361 if (len + file_name_length > JVM_MAXPATHLEN) { 1362 // release allocated storage before exiting the vm 1363 free_array_of_char_arrays(opath, i++); 1364 vm_exit_during_initialization("The VM tried to use a path that exceeds the maximum path length for " 1365 "this system. Review path-containing parameters and properties, such as " 1366 "sun.boot.library.path, to identify potential sources for this path."); 1367 } 1368 // allocate the string and add terminator storage 1369 char* s = (char*)NEW_C_HEAP_ARRAY_RETURN_NULL(char, len + 1, mtInternal); 1370 if (s == NULL) { 1371 // release allocated storage before returning null 1372 free_array_of_char_arrays(opath, i++); 1373 return NULL; 1374 } 1375 strncpy(s, p, len); 1376 s[len] = '\0'; 1377 opath[i] = s; 1378 p += len + 1; 1379 } 1380 FREE_C_HEAP_ARRAY(char, inpath); 1381 *elements = count; 1382 return opath; 1383 } 1384 1385 // Returns true if the current stack pointer is above the stack shadow 1386 // pages, false otherwise. 1387 bool os::stack_shadow_pages_available(Thread *thread, const methodHandle& method, address sp) { 1388 if (!thread->is_Java_thread()) return false; 1389 // Check if we have StackShadowPages above the yellow zone. This parameter 1390 // is dependent on the depth of the maximum VM call stack possible from 1391 // the handler for stack overflow. 'instanceof' in the stack overflow 1392 // handler or a println uses at least 8k stack of VM and native code 1393 // respectively. 1394 const int framesize_in_bytes = 1395 Interpreter::size_top_interpreter_activation(method()) * wordSize; 1396 1397 address limit = ((JavaThread*)thread)->stack_end() + 1398 (JavaThread::stack_guard_zone_size() + JavaThread::stack_shadow_zone_size()); 1399 1400 return sp > (limit + framesize_in_bytes); 1401 } 1402 1403 size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) { 1404 assert(min_pages > 0, "sanity"); 1405 if (UseLargePages) { 1406 const size_t max_page_size = region_size / min_pages; 1407 1408 for (size_t i = 0; _page_sizes[i] != 0; ++i) { 1409 const size_t page_size = _page_sizes[i]; 1410 if (page_size <= max_page_size) { 1411 if (!must_be_aligned || is_aligned(region_size, page_size)) { 1412 return page_size; 1413 } 1414 } 1415 } 1416 } 1417 1418 return vm_page_size(); 1419 } 1420 1421 size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) { 1422 return page_size_for_region(region_size, min_pages, true); 1423 } 1424 1425 size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) { 1426 return page_size_for_region(region_size, min_pages, false); 1427 } 1428 1429 static const char* errno_to_string (int e, bool short_text) { 1430 #define ALL_SHARED_ENUMS(X) \ 1431 X(E2BIG, "Argument list too long") \ 1432 X(EACCES, "Permission denied") \ 1433 X(EADDRINUSE, "Address in use") \ 1434 X(EADDRNOTAVAIL, "Address not available") \ 1435 X(EAFNOSUPPORT, "Address family not supported") \ 1436 X(EAGAIN, "Resource unavailable, try again") \ 1437 X(EALREADY, "Connection already in progress") \ 1438 X(EBADF, "Bad file descriptor") \ 1439 X(EBADMSG, "Bad message") \ 1440 X(EBUSY, "Device or resource busy") \ 1441 X(ECANCELED, "Operation canceled") \ 1442 X(ECHILD, "No child processes") \ 1443 X(ECONNABORTED, "Connection aborted") \ 1444 X(ECONNREFUSED, "Connection refused") \ 1445 X(ECONNRESET, "Connection reset") \ 1446 X(EDEADLK, "Resource deadlock would occur") \ 1447 X(EDESTADDRREQ, "Destination address required") \ 1448 X(EDOM, "Mathematics argument out of domain of function") \ 1449 X(EEXIST, "File exists") \ 1450 X(EFAULT, "Bad address") \ 1451 X(EFBIG, "File too large") \ 1452 X(EHOSTUNREACH, "Host is unreachable") \ 1453 X(EIDRM, "Identifier removed") \ 1454 X(EILSEQ, "Illegal byte sequence") \ 1455 X(EINPROGRESS, "Operation in progress") \ 1456 X(EINTR, "Interrupted function") \ 1457 X(EINVAL, "Invalid argument") \ 1458 X(EIO, "I/O error") \ 1459 X(EISCONN, "Socket is connected") \ 1460 X(EISDIR, "Is a directory") \ 1461 X(ELOOP, "Too many levels of symbolic links") \ 1462 X(EMFILE, "Too many open files") \ 1463 X(EMLINK, "Too many links") \ 1464 X(EMSGSIZE, "Message too large") \ 1465 X(ENAMETOOLONG, "Filename too long") \ 1466 X(ENETDOWN, "Network is down") \ 1467 X(ENETRESET, "Connection aborted by network") \ 1468 X(ENETUNREACH, "Network unreachable") \ 1469 X(ENFILE, "Too many files open in system") \ 1470 X(ENOBUFS, "No buffer space available") \ 1471 X(ENODATA, "No message is available on the STREAM head read queue") \ 1472 X(ENODEV, "No such device") \ 1473 X(ENOENT, "No such file or directory") \ 1474 X(ENOEXEC, "Executable file format error") \ 1475 X(ENOLCK, "No locks available") \ 1476 X(ENOLINK, "Reserved") \ 1477 X(ENOMEM, "Not enough space") \ 1478 X(ENOMSG, "No message of the desired type") \ 1479 X(ENOPROTOOPT, "Protocol not available") \ 1480 X(ENOSPC, "No space left on device") \ 1481 X(ENOSR, "No STREAM resources") \ 1482 X(ENOSTR, "Not a STREAM") \ 1483 X(ENOSYS, "Function not supported") \ 1484 X(ENOTCONN, "The socket is not connected") \ 1485 X(ENOTDIR, "Not a directory") \ 1486 X(ENOTEMPTY, "Directory not empty") \ 1487 X(ENOTSOCK, "Not a socket") \ 1488 X(ENOTSUP, "Not supported") \ 1489 X(ENOTTY, "Inappropriate I/O control operation") \ 1490 X(ENXIO, "No such device or address") \ 1491 X(EOPNOTSUPP, "Operation not supported on socket") \ 1492 X(EOVERFLOW, "Value too large to be stored in data type") \ 1493 X(EPERM, "Operation not permitted") \ 1494 X(EPIPE, "Broken pipe") \ 1495 X(EPROTO, "Protocol error") \ 1496 X(EPROTONOSUPPORT, "Protocol not supported") \ 1497 X(EPROTOTYPE, "Protocol wrong type for socket") \ 1498 X(ERANGE, "Result too large") \ 1499 X(EROFS, "Read-only file system") \ 1500 X(ESPIPE, "Invalid seek") \ 1501 X(ESRCH, "No such process") \ 1502 X(ETIME, "Stream ioctl() timeout") \ 1503 X(ETIMEDOUT, "Connection timed out") \ 1504 X(ETXTBSY, "Text file busy") \ 1505 X(EWOULDBLOCK, "Operation would block") \ 1506 X(EXDEV, "Cross-device link") 1507 1508 #define DEFINE_ENTRY(e, text) { e, #e, text }, 1509 1510 static const struct { 1511 int v; 1512 const char* short_text; 1513 const char* long_text; 1514 } table [] = { 1515 1516 ALL_SHARED_ENUMS(DEFINE_ENTRY) 1517 1518 // The following enums are not defined on all platforms. 1519 #ifdef ESTALE 1520 DEFINE_ENTRY(ESTALE, "Reserved") 1521 #endif 1522 #ifdef EDQUOT 1523 DEFINE_ENTRY(EDQUOT, "Reserved") 1524 #endif 1525 #ifdef EMULTIHOP 1526 DEFINE_ENTRY(EMULTIHOP, "Reserved") 1527 #endif 1528 1529 // End marker. 1530 { -1, "Unknown errno", "Unknown error" } 1531 1532 }; 1533 1534 #undef DEFINE_ENTRY 1535 #undef ALL_FLAGS 1536 1537 int i = 0; 1538 while (table[i].v != -1 && table[i].v != e) { 1539 i ++; 1540 } 1541 1542 return short_text ? table[i].short_text : table[i].long_text; 1543 1544 } 1545 1546 const char* os::strerror(int e) { 1547 return errno_to_string(e, false); 1548 } 1549 1550 const char* os::errno_name(int e) { 1551 return errno_to_string(e, true); 1552 } 1553 1554 void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count) { 1555 LogTarget(Info, pagesize) log; 1556 if (log.is_enabled()) { 1557 LogStream out(log); 1558 1559 out.print("%s: ", str); 1560 for (int i = 0; i < count; ++i) { 1561 out.print(" " SIZE_FORMAT, page_sizes[i]); 1562 } 1563 out.cr(); 1564 } 1565 } 1566 1567 #define trace_page_size_params(size) byte_size_in_exact_unit(size), exact_unit_for_byte_size(size) 1568 1569 void os::trace_page_sizes(const char* str, 1570 const size_t region_min_size, 1571 const size_t region_max_size, 1572 const size_t page_size, 1573 const char* base, 1574 const size_t size) { 1575 1576 log_info(pagesize)("%s: " 1577 " min=" SIZE_FORMAT "%s" 1578 " max=" SIZE_FORMAT "%s" 1579 " base=" PTR_FORMAT 1580 " page_size=" SIZE_FORMAT "%s" 1581 " size=" SIZE_FORMAT "%s", 1582 str, 1583 trace_page_size_params(region_min_size), 1584 trace_page_size_params(region_max_size), 1585 p2i(base), 1586 trace_page_size_params(page_size), 1587 trace_page_size_params(size)); 1588 } 1589 1590 void os::trace_page_sizes_for_requested_size(const char* str, 1591 const size_t requested_size, 1592 const size_t page_size, 1593 const size_t alignment, 1594 const char* base, 1595 const size_t size) { 1596 1597 log_info(pagesize)("%s:" 1598 " req_size=" SIZE_FORMAT "%s" 1599 " base=" PTR_FORMAT 1600 " page_size=" SIZE_FORMAT "%s" 1601 " alignment=" SIZE_FORMAT "%s" 1602 " size=" SIZE_FORMAT "%s", 1603 str, 1604 trace_page_size_params(requested_size), 1605 p2i(base), 1606 trace_page_size_params(page_size), 1607 trace_page_size_params(alignment), 1608 trace_page_size_params(size)); 1609 } 1610 1611 1612 // This is the working definition of a server class machine: 1613 // >= 2 physical CPU's and >=2GB of memory, with some fuzz 1614 // because the graphics memory (?) sometimes masks physical memory. 1615 // If you want to change the definition of a server class machine 1616 // on some OS or platform, e.g., >=4GB on Windows platforms, 1617 // then you'll have to parameterize this method based on that state, 1618 // as was done for logical processors here, or replicate and 1619 // specialize this method for each platform. (Or fix os to have 1620 // some inheritance structure and use subclassing. Sigh.) 1621 // If you want some platform to always or never behave as a server 1622 // class machine, change the setting of AlwaysActAsServerClassMachine 1623 // and NeverActAsServerClassMachine in globals*.hpp. 1624 bool os::is_server_class_machine() { 1625 // First check for the early returns 1626 if (NeverActAsServerClassMachine) { 1627 return false; 1628 } 1629 if (AlwaysActAsServerClassMachine) { 1630 return true; 1631 } 1632 // Then actually look at the machine 1633 bool result = false; 1634 const unsigned int server_processors = 2; 1635 const julong server_memory = 2UL * G; 1636 // We seem not to get our full complement of memory. 1637 // We allow some part (1/8?) of the memory to be "missing", 1638 // based on the sizes of DIMMs, and maybe graphics cards. 1639 const julong missing_memory = 256UL * M; 1640 1641 /* Is this a server class machine? */ 1642 if ((os::active_processor_count() >= (int)server_processors) && 1643 (os::physical_memory() >= (server_memory - missing_memory))) { 1644 const unsigned int logical_processors = 1645 VM_Version::logical_processors_per_package(); 1646 if (logical_processors > 1) { 1647 const unsigned int physical_packages = 1648 os::active_processor_count() / logical_processors; 1649 if (physical_packages >= server_processors) { 1650 result = true; 1651 } 1652 } else { 1653 result = true; 1654 } 1655 } 1656 return result; 1657 } 1658 1659 void os::initialize_initial_active_processor_count() { 1660 assert(_initial_active_processor_count == 0, "Initial active processor count already set."); 1661 _initial_active_processor_count = active_processor_count(); 1662 log_debug(os)("Initial active processor count set to %d" , _initial_active_processor_count); 1663 } 1664 1665 void os::SuspendedThreadTask::run() { 1666 internal_do_task(); 1667 _done = true; 1668 } 1669 1670 bool os::create_stack_guard_pages(char* addr, size_t bytes) { 1671 return os::pd_create_stack_guard_pages(addr, bytes); 1672 } 1673 1674 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint, int file_desc) { 1675 char* result = NULL; 1676 1677 if (file_desc != -1) { 1678 // Could have called pd_reserve_memory() followed by replace_existing_mapping_with_file_mapping(), 1679 // but AIX may use SHM in which case its more trouble to detach the segment and remap memory to the file. 1680 result = os::map_memory_to_file(addr, bytes, file_desc); 1681 if (result != NULL) { 1682 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC); 1683 } 1684 } else { 1685 result = pd_reserve_memory(bytes, addr, alignment_hint); 1686 if (result != NULL) { 1687 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC); 1688 } 1689 } 1690 1691 return result; 1692 } 1693 1694 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint, 1695 MEMFLAGS flags) { 1696 char* result = pd_reserve_memory(bytes, addr, alignment_hint); 1697 if (result != NULL) { 1698 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC); 1699 MemTracker::record_virtual_memory_type((address)result, flags); 1700 } 1701 1702 return result; 1703 } 1704 1705 char* os::attempt_reserve_memory_at(size_t bytes, char* addr, int file_desc) { 1706 char* result = NULL; 1707 if (file_desc != -1) { 1708 result = pd_attempt_reserve_memory_at(bytes, addr, file_desc); 1709 if (result != NULL) { 1710 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC); 1711 } 1712 } else { 1713 result = pd_attempt_reserve_memory_at(bytes, addr); 1714 if (result != NULL) { 1715 MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC); 1716 } 1717 } 1718 return result; 1719 } 1720 1721 void os::split_reserved_memory(char *base, size_t size, 1722 size_t split, bool realloc) { 1723 pd_split_reserved_memory(base, size, split, realloc); 1724 } 1725 1726 bool os::commit_memory(char* addr, size_t bytes, bool executable) { 1727 bool res = pd_commit_memory(addr, bytes, executable); 1728 if (res) { 1729 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC); 1730 } 1731 return res; 1732 } 1733 1734 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint, 1735 bool executable) { 1736 bool res = os::pd_commit_memory(addr, size, alignment_hint, executable); 1737 if (res) { 1738 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC); 1739 } 1740 return res; 1741 } 1742 1743 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable, 1744 const char* mesg) { 1745 pd_commit_memory_or_exit(addr, bytes, executable, mesg); 1746 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC); 1747 } 1748 1749 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint, 1750 bool executable, const char* mesg) { 1751 os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg); 1752 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC); 1753 } 1754 1755 bool os::uncommit_memory(char* addr, size_t bytes) { 1756 bool res; 1757 if (MemTracker::tracking_level() > NMT_minimal) { 1758 Tracker tkr(Tracker::uncommit); 1759 res = pd_uncommit_memory(addr, bytes); 1760 if (res) { 1761 tkr.record((address)addr, bytes); 1762 } 1763 } else { 1764 res = pd_uncommit_memory(addr, bytes); 1765 } 1766 return res; 1767 } 1768 1769 bool os::release_memory(char* addr, size_t bytes) { 1770 bool res; 1771 if (MemTracker::tracking_level() > NMT_minimal) { 1772 Tracker tkr(Tracker::release); 1773 res = pd_release_memory(addr, bytes); 1774 if (res) { 1775 tkr.record((address)addr, bytes); 1776 } 1777 } else { 1778 res = pd_release_memory(addr, bytes); 1779 } 1780 return res; 1781 } 1782 1783 void os::pretouch_memory(void* start, void* end, size_t page_size) { 1784 for (volatile char *p = (char*)start; p < (char*)end; p += page_size) { 1785 *p = 0; 1786 } 1787 } 1788 1789 char* os::map_memory(int fd, const char* file_name, size_t file_offset, 1790 char *addr, size_t bytes, bool read_only, 1791 bool allow_exec) { 1792 char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec); 1793 if (result != NULL) { 1794 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, CALLER_PC); 1795 } 1796 return result; 1797 } 1798 1799 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, 1800 char *addr, size_t bytes, bool read_only, 1801 bool allow_exec) { 1802 return pd_remap_memory(fd, file_name, file_offset, addr, bytes, 1803 read_only, allow_exec); 1804 } 1805 1806 bool os::unmap_memory(char *addr, size_t bytes) { 1807 bool result; 1808 if (MemTracker::tracking_level() > NMT_minimal) { 1809 Tracker tkr(Tracker::release); 1810 result = pd_unmap_memory(addr, bytes); 1811 if (result) { 1812 tkr.record((address)addr, bytes); 1813 } 1814 } else { 1815 result = pd_unmap_memory(addr, bytes); 1816 } 1817 return result; 1818 } 1819 1820 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) { 1821 pd_free_memory(addr, bytes, alignment_hint); 1822 } 1823 1824 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 1825 pd_realign_memory(addr, bytes, alignment_hint); 1826 } 1827 1828 #ifndef _WINDOWS 1829 /* try to switch state from state "from" to state "to" 1830 * returns the state set after the method is complete 1831 */ 1832 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from, 1833 os::SuspendResume::State to) 1834 { 1835 os::SuspendResume::State result = Atomic::cmpxchg(to, &_state, from); 1836 if (result == from) { 1837 // success 1838 return to; 1839 } 1840 return result; 1841 } 1842 #endif