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