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