1 /* 2 * Copyright (c) 1997, 2020, 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 #ifndef SHARE_RUNTIME_OS_HPP 26 #define SHARE_RUNTIME_OS_HPP 27 28 #include "jvm.h" 29 #include "metaprogramming/integralConstant.hpp" 30 #include "utilities/exceptions.hpp" 31 #include "utilities/ostream.hpp" 32 #include "utilities/macros.hpp" 33 #ifndef _WINDOWS 34 # include <setjmp.h> 35 #endif 36 #ifdef __APPLE__ 37 # include <mach/mach_time.h> 38 #endif 39 40 class AgentLibrary; 41 class frame; 42 43 // os defines the interface to operating system; this includes traditional 44 // OS services (time, I/O) as well as other functionality with system- 45 // dependent code. 46 47 class Thread; 48 class JavaThread; 49 class NativeCallStack; 50 class methodHandle; 51 class OSThread; 52 class Mutex; 53 54 struct jvmtiTimerInfo; 55 56 template<class E> class GrowableArray; 57 58 // %%%%% Moved ThreadState, START_FN, OSThread to new osThread.hpp. -- Rose 59 60 // Platform-independent error return values from OS functions 61 enum OSReturn { 62 OS_OK = 0, // Operation was successful 63 OS_ERR = -1, // Operation failed 64 OS_INTRPT = -2, // Operation was interrupted 65 OS_TIMEOUT = -3, // Operation timed out 66 OS_NOMEM = -5, // Operation failed for lack of memory 67 OS_NORESOURCE = -6 // Operation failed for lack of nonmemory resource 68 }; 69 70 enum ThreadPriority { // JLS 20.20.1-3 71 NoPriority = -1, // Initial non-priority value 72 MinPriority = 1, // Minimum priority 73 NormPriority = 5, // Normal (non-daemon) priority 74 NearMaxPriority = 9, // High priority, used for VMThread 75 MaxPriority = 10, // Highest priority, used for WatcherThread 76 // ensures that VMThread doesn't starve profiler 77 CriticalPriority = 11 // Critical thread priority 78 }; 79 80 // Executable parameter flag for os::commit_memory() and 81 // os::commit_memory_or_exit(). 82 const bool ExecMem = true; 83 84 // Typedef for structured exception handling support 85 typedef void (*java_call_t)(JavaValue* value, const methodHandle& method, JavaCallArguments* args, Thread* thread); 86 87 class MallocTracker; 88 89 class os: AllStatic { 90 friend class VMStructs; 91 friend class JVMCIVMStructs; 92 friend class MallocTracker; 93 94 #ifdef ASSERT 95 private: 96 static bool _mutex_init_done; 97 public: set_mutex_init_done()98 static void set_mutex_init_done() { _mutex_init_done = true; } mutex_init_done()99 static bool mutex_init_done() { return _mutex_init_done; } 100 #endif 101 102 public: 103 104 // A simple value class holding a set of page sizes (similar to sigset_t) 105 class PageSizes { 106 size_t _v; // actually a bitmap. 107 public: PageSizes()108 PageSizes() : _v(0) {} 109 void add(size_t pagesize); 110 bool contains(size_t pagesize) const; 111 // Given a page size, return the next smaller page size in this set, or 0. 112 size_t next_smaller(size_t pagesize) const; 113 // Given a page size, return the next larger page size in this set, or 0. 114 size_t next_larger(size_t pagesize) const; 115 // Returns the largest page size in this set, or 0 if set is empty. 116 size_t largest() const; 117 // Returns the smallest page size in this set, or 0 if set is empty. 118 size_t smallest() const; 119 // Prints one line of comma separated, human readable page sizes, "empty" if empty. 120 void print_on(outputStream* st) const; 121 }; 122 123 private: 124 static OSThread* _starting_thread; 125 static address _polling_page; 126 static PageSizes _page_sizes; 127 128 static char* pd_reserve_memory(size_t bytes); 129 130 static char* pd_attempt_reserve_memory_at(char* addr, size_t bytes); 131 132 static bool pd_commit_memory(char* addr, size_t bytes, bool executable); 133 static bool pd_commit_memory(char* addr, size_t size, size_t alignment_hint, 134 bool executable); 135 // Same as pd_commit_memory() that either succeeds or calls 136 // vm_exit_out_of_memory() with the specified mesg. 137 static void pd_commit_memory_or_exit(char* addr, size_t bytes, 138 bool executable, const char* mesg); 139 static void pd_commit_memory_or_exit(char* addr, size_t size, 140 size_t alignment_hint, 141 bool executable, const char* mesg); 142 static bool pd_uncommit_memory(char* addr, size_t bytes); 143 static bool pd_release_memory(char* addr, size_t bytes); 144 145 static char* pd_attempt_map_memory_to_file_at(char* addr, size_t bytes, int file_desc); 146 147 static char* pd_map_memory(int fd, const char* file_name, size_t file_offset, 148 char *addr, size_t bytes, bool read_only = false, 149 bool allow_exec = false); 150 static char* pd_remap_memory(int fd, const char* file_name, size_t file_offset, 151 char *addr, size_t bytes, bool read_only, 152 bool allow_exec); 153 static bool pd_unmap_memory(char *addr, size_t bytes); 154 static void pd_free_memory(char *addr, size_t bytes, size_t alignment_hint); 155 static void pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint); 156 157 static char* pd_reserve_memory_special(size_t size, size_t alignment, 158 char* addr, bool executable); 159 static bool pd_release_memory_special(char* addr, size_t bytes); 160 161 static size_t page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned); 162 163 // Get summary strings for system information in buffer provided 164 static void get_summary_cpu_info(char* buf, size_t buflen); 165 static void get_summary_os_info(char* buf, size_t buflen); 166 167 static void initialize_initial_active_processor_count(); 168 169 LINUX_ONLY(static void pd_init_container_support();) 170 171 public: 172 static void init(void); // Called before command line parsing 173 init_container_support()174 static void init_container_support() { // Called during command line parsing. 175 LINUX_ONLY(pd_init_container_support();) 176 } 177 178 static void init_before_ergo(void); // Called after command line parsing 179 // before VM ergonomics processing. 180 static jint init_2(void); // Called after command line parsing 181 // and VM ergonomics processing 182 183 // unset environment variable 184 static bool unsetenv(const char* name); 185 186 static bool have_special_privileges(); 187 188 static jlong javaTimeMillis(); 189 static jlong javaTimeNanos(); 190 static void javaTimeNanos_info(jvmtiTimerInfo *info_ptr); 191 static void javaTimeSystemUTC(jlong &seconds, jlong &nanos); 192 static void run_periodic_checks(); 193 static bool supports_monotonic_clock(); 194 195 // Returns the elapsed time in seconds since the vm started. 196 static double elapsedTime(); 197 198 // Returns real time in seconds since an arbitrary point 199 // in the past. 200 static bool getTimesSecs(double* process_real_time, 201 double* process_user_time, 202 double* process_system_time); 203 204 // Interface to the performance counter 205 static jlong elapsed_counter(); 206 static jlong elapsed_frequency(); 207 208 // The "virtual time" of a thread is the amount of time a thread has 209 // actually run. The first function indicates whether the OS supports 210 // this functionality for the current thread, and if so the second 211 // returns the elapsed virtual time for the current thread. 212 static bool supports_vtime(); 213 static double elapsedVTime(); 214 215 // Return current local time in a string (YYYY-MM-DD HH:MM:SS). 216 // It is MT safe, but not async-safe, as reading time zone 217 // information may require a lock on some platforms. 218 static char* local_time_string(char *buf, size_t buflen); 219 static struct tm* localtime_pd (const time_t* clock, struct tm* res); 220 static struct tm* gmtime_pd (const time_t* clock, struct tm* res); 221 // Fill in buffer with current local time as an ISO-8601 string. 222 // E.g., YYYY-MM-DDThh:mm:ss.mmm+zzzz. 223 // Returns buffer, or NULL if it failed. 224 static char* iso8601_time(char* buffer, size_t buffer_length, bool utc = false); 225 226 // Interface for detecting multiprocessor system is_MP()227 static inline bool is_MP() { 228 // During bootstrap if _processor_count is not yet initialized 229 // we claim to be MP as that is safest. If any platform has a 230 // stub generator that might be triggered in this phase and for 231 // which being declared MP when in fact not, is a problem - then 232 // the bootstrap routine for the stub generator needs to check 233 // the processor count directly and leave the bootstrap routine 234 // in place until called after initialization has ocurred. 235 return (_processor_count != 1); 236 } 237 238 static julong available_memory(); 239 static julong physical_memory(); 240 static bool has_allocatable_memory_limit(julong* limit); 241 static bool is_server_class_machine(); 242 243 // Returns the id of the processor on which the calling thread is currently executing. 244 // The returned value is guaranteed to be between 0 and (os::processor_count() - 1). 245 static uint processor_id(); 246 247 // number of CPUs processor_count()248 static int processor_count() { 249 return _processor_count; 250 } set_processor_count(int count)251 static void set_processor_count(int count) { _processor_count = count; } 252 253 // Returns the number of CPUs this process is currently allowed to run on. 254 // Note that on some OSes this can change dynamically. 255 static int active_processor_count(); 256 257 // At startup the number of active CPUs this process is allowed to run on. 258 // This value does not change dynamically. May be different from active_processor_count(). initial_active_processor_count()259 static int initial_active_processor_count() { 260 assert(_initial_active_processor_count > 0, "Initial active processor count not set yet."); 261 return _initial_active_processor_count; 262 } 263 264 // Binds the current process to a processor. 265 // Returns true if it worked, false if it didn't. 266 static bool bind_to_processor(uint processor_id); 267 268 // Give a name to the current thread. 269 static void set_native_thread_name(const char *name); 270 271 // Interface for stack banging (predetect possible stack overflow for 272 // exception processing) There are guard pages, and above that shadow 273 // pages for stack overflow checking. 274 static bool uses_stack_guard_pages(); 275 static bool must_commit_stack_guard_pages(); 276 static void map_stack_shadow_pages(address sp); 277 static bool stack_shadow_pages_available(Thread *thread, const methodHandle& method, address sp); 278 279 // Find committed memory region within specified range (start, start + size), 280 // return true if found any 281 static bool committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size); 282 283 // OS interface to Virtual Memory 284 285 // Return the default page size. 286 static int vm_page_size(); 287 288 // The set of page sizes which the VM is allowed to use (may be a subset of 289 // the page sizes actually available on the platform). page_sizes()290 static const PageSizes& page_sizes() { return _page_sizes; } 291 292 // Returns the page size to use for a region of memory. 293 // region_size / min_pages will always be greater than or equal to the 294 // returned value. The returned value will divide region_size. 295 static size_t page_size_for_region_aligned(size_t region_size, size_t min_pages); 296 297 // Returns the page size to use for a region of memory. 298 // region_size / min_pages will always be greater than or equal to the 299 // returned value. The returned value might not divide region_size. 300 static size_t page_size_for_region_unaligned(size_t region_size, size_t min_pages); 301 302 // Return the largest page size that can be used max_page_size()303 static size_t max_page_size() { return page_sizes().largest(); } 304 305 // Return a lower bound for page sizes. Also works before os::init completed. min_page_size()306 static size_t min_page_size() { return 4 * K; } 307 308 // Methods for tracing page sizes returned by the above method. 309 // The region_{min,max}_size parameters should be the values 310 // passed to page_size_for_region() and page_size should be the result of that 311 // call. The (optional) base and size parameters should come from the 312 // ReservedSpace base() and size() methods. 313 static void trace_page_sizes(const char* str, const size_t* page_sizes, int count); 314 static void trace_page_sizes(const char* str, 315 const size_t region_min_size, 316 const size_t region_max_size, 317 const size_t page_size, 318 const char* base, 319 const size_t size); 320 static void trace_page_sizes_for_requested_size(const char* str, 321 const size_t requested_size, 322 const size_t page_size, 323 const size_t alignment, 324 const char* base, 325 const size_t size); 326 327 static int vm_allocation_granularity(); 328 329 // Reserves virtual memory. 330 static char* reserve_memory(size_t bytes, MEMFLAGS flags = mtOther); 331 332 // Reserves virtual memory that starts at an address that is aligned to 'alignment'. 333 static char* reserve_memory_aligned(size_t size, size_t alignment); 334 335 // Attempts to reserve the virtual memory at [addr, addr + bytes). 336 // Does not overwrite existing mappings. 337 static char* attempt_reserve_memory_at(char* addr, size_t bytes); 338 339 // Split a reserved memory region [base, base+size) into two regions [base, base+split) and 340 // [base+split, base+size). 341 // This may remove the original mapping, so its content may be lost. 342 // Both base and split point must be aligned to allocation granularity; split point shall 343 // be >0 and <size. 344 // Splitting guarantees that the resulting two memory regions can be released independently 345 // from each other using os::release_memory(). It also means NMT will track these regions 346 // individually, allowing different tags to be set. 347 static void split_reserved_memory(char *base, size_t size, size_t split); 348 349 static bool commit_memory(char* addr, size_t bytes, bool executable); 350 static bool commit_memory(char* addr, size_t size, size_t alignment_hint, 351 bool executable); 352 // Same as commit_memory() that either succeeds or calls 353 // vm_exit_out_of_memory() with the specified mesg. 354 static void commit_memory_or_exit(char* addr, size_t bytes, 355 bool executable, const char* mesg); 356 static void commit_memory_or_exit(char* addr, size_t size, 357 size_t alignment_hint, 358 bool executable, const char* mesg); 359 static bool uncommit_memory(char* addr, size_t bytes); 360 static bool release_memory(char* addr, size_t bytes); 361 362 // A diagnostic function to print memory mappings in the given range. 363 static void print_memory_mappings(char* addr, size_t bytes, outputStream* st); 364 // Prints all mappings 365 static void print_memory_mappings(outputStream* st); 366 367 // Touch memory pages that cover the memory range from start to end (exclusive) 368 // to make the OS back the memory range with actual memory. 369 // Current implementation may not touch the last page if unaligned addresses 370 // are passed. 371 static void pretouch_memory(void* start, void* end, size_t page_size = vm_page_size()); 372 373 enum ProtType { MEM_PROT_NONE, MEM_PROT_READ, MEM_PROT_RW, MEM_PROT_RWX }; 374 static bool protect_memory(char* addr, size_t bytes, ProtType prot, 375 bool is_committed = true); 376 377 static bool guard_memory(char* addr, size_t bytes); 378 static bool unguard_memory(char* addr, size_t bytes); 379 static bool create_stack_guard_pages(char* addr, size_t bytes); 380 static bool pd_create_stack_guard_pages(char* addr, size_t bytes); 381 static bool remove_stack_guard_pages(char* addr, size_t bytes); 382 // Helper function to create a new file with template jvmheap.XXXXXX. 383 // Returns a valid fd on success or else returns -1 384 static int create_file_for_heap(const char* dir); 385 // Map memory to the file referred by fd. This function is slightly different from map_memory() 386 // and is added to be used for implementation of -XX:AllocateHeapAt 387 static char* map_memory_to_file(size_t size, int fd); 388 static char* map_memory_to_file_aligned(size_t size, size_t alignment, int fd); 389 static char* map_memory_to_file(char* base, size_t size, int fd); 390 static char* attempt_map_memory_to_file_at(char* base, size_t size, int fd); 391 // Replace existing reserved memory with file mapping 392 static char* replace_existing_mapping_with_file_mapping(char* base, size_t size, int fd); 393 394 static char* map_memory(int fd, const char* file_name, size_t file_offset, 395 char *addr, size_t bytes, bool read_only = false, 396 bool allow_exec = false, MEMFLAGS flags = mtNone); 397 static char* remap_memory(int fd, const char* file_name, size_t file_offset, 398 char *addr, size_t bytes, bool read_only, 399 bool allow_exec); 400 static bool unmap_memory(char *addr, size_t bytes); 401 static void free_memory(char *addr, size_t bytes, size_t alignment_hint); 402 static void realign_memory(char *addr, size_t bytes, size_t alignment_hint); 403 404 // NUMA-specific interface 405 static bool numa_has_static_binding(); 406 static bool numa_has_group_homing(); 407 static void numa_make_local(char *addr, size_t bytes, int lgrp_hint); 408 static void numa_make_global(char *addr, size_t bytes); 409 static size_t numa_get_groups_num(); 410 static size_t numa_get_leaf_groups(int *ids, size_t size); 411 static bool numa_topology_changed(); 412 static int numa_get_group_id(); 413 static int numa_get_group_id_for_address(const void* address); 414 415 // Page manipulation 416 struct page_info { 417 size_t size; 418 int lgrp_id; 419 }; 420 static bool get_page_info(char *start, page_info* info); 421 static char* scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found); 422 423 static char* non_memory_address_word(); 424 // reserve, commit and pin the entire memory region 425 static char* reserve_memory_special(size_t size, size_t alignment, 426 char* addr, bool executable); 427 static bool release_memory_special(char* addr, size_t bytes); 428 static void large_page_init(); 429 static size_t large_page_size(); 430 static bool can_commit_large_page_memory(); 431 static bool can_execute_large_page_memory(); 432 433 // Check if pointer points to readable memory (by 4-byte read access) 434 static bool is_readable_pointer(const void* p); 435 static bool is_readable_range(const void* from, const void* to); 436 437 // threads 438 439 enum ThreadType { 440 vm_thread, 441 cgc_thread, // Concurrent GC thread 442 pgc_thread, // Parallel GC thread 443 java_thread, // Java, CodeCacheSweeper, JVMTIAgent and Service threads. 444 compiler_thread, 445 watcher_thread, 446 os_thread 447 }; 448 449 static bool create_thread(Thread* thread, 450 ThreadType thr_type, 451 size_t req_stack_size = 0); 452 453 // The "main thread", also known as "starting thread", is the thread 454 // that loads/creates the JVM via JNI_CreateJavaVM. 455 static bool create_main_thread(JavaThread* thread); 456 457 // The primordial thread is the initial process thread. The java 458 // launcher never uses the primordial thread as the main thread, but 459 // applications that host the JVM directly may do so. Some platforms 460 // need special-case handling of the primordial thread if it attaches 461 // to the VM. is_primordial_thread(void)462 static bool is_primordial_thread(void) 463 #if defined(_WINDOWS) || defined(BSD) 464 // No way to identify the primordial thread. 465 { return false; } 466 #else 467 ; 468 #endif 469 470 static bool create_attached_thread(JavaThread* thread); 471 static void pd_start_thread(Thread* thread); 472 static void start_thread(Thread* thread); 473 474 // Returns true if successful. 475 static bool signal_thread(Thread* thread, int sig, const char* reason); 476 477 static void free_thread(OSThread* osthread); 478 479 // thread id on Linux/64bit is 64bit, on Windows it's 32bit 480 static intx current_thread_id(); 481 static int current_process_id(); 482 483 // Short standalone OS sleep routines suitable for slow path spin loop. 484 // Ignores safepoints/suspension/Thread.interrupt() (so keep it short). 485 // ms/ns = 0, will sleep for the least amount of time allowed by the OS. 486 // Maximum sleep time is just under 1 second. 487 static void naked_short_sleep(jlong ms); 488 static void naked_short_nanosleep(jlong ns); 489 // Longer standalone OS sleep routine - a convenience wrapper around 490 // multiple calls to naked_short_sleep. Only for use by non-JavaThreads. 491 static void naked_sleep(jlong millis); 492 // Never returns, use with CAUTION 493 static void infinite_sleep(); 494 static void naked_yield () ; 495 static OSReturn set_priority(Thread* thread, ThreadPriority priority); 496 static OSReturn get_priority(const Thread* const thread, ThreadPriority& priority); 497 498 static int pd_self_suspend_thread(Thread* thread); 499 500 static address fetch_frame_from_context(const void* ucVoid, intptr_t** sp, intptr_t** fp); 501 static frame fetch_frame_from_context(const void* ucVoid); 502 static frame fetch_compiled_frame_from_context(const void* ucVoid); 503 504 static void breakpoint(); 505 static bool start_debugging(char *buf, int buflen); 506 507 static address current_stack_pointer(); 508 static address current_stack_base(); 509 static size_t current_stack_size(); 510 511 static void verify_stack_alignment() PRODUCT_RETURN; 512 513 static bool message_box(const char* title, const char* message); 514 515 // run cmd in a separate process and return its exit code; or -1 on failures 516 static int fork_and_exec(char *cmd, bool use_vfork_if_available = false); 517 518 // Call ::exit() on all platforms but Windows 519 static void exit(int num); 520 521 // Terminate the VM, but don't exit the process 522 static void shutdown(); 523 524 // Terminate with an error. Default is to generate a core file on platforms 525 // that support such things. This calls shutdown() and then aborts. 526 static void abort(bool dump_core, void *siginfo, const void *context); 527 static void abort(bool dump_core = true); 528 529 // Die immediately, no exit hook, no abort hook, no cleanup. 530 // Dump a core file, if possible, for debugging. os::abort() is the 531 // preferred means to abort the VM on error. os::die() should only 532 // be called if something has gone badly wrong. CreateCoredumpOnCrash 533 // is intentionally not honored by this function. 534 static void die(); 535 536 // File i/o operations 537 static int open(const char *path, int oflag, int mode); 538 static FILE* open(int fd, const char* mode); 539 static FILE* fopen(const char* path, const char* mode); 540 static int close(int fd); 541 static jlong lseek(int fd, jlong offset, int whence); 542 // This function, on Windows, canonicalizes a given path (see os_windows.cpp for details). 543 // On Posix, this function is a noop: it does not change anything and just returns 544 // the input pointer. 545 static char* native_path(char *path); 546 static int ftruncate(int fd, jlong length); 547 static int fsync(int fd); 548 static int available(int fd, jlong *bytes); 549 static int get_fileno(FILE* fp); 550 static void flockfile(FILE* fp); 551 static void funlockfile(FILE* fp); 552 553 static int compare_file_modified_times(const char* file1, const char* file2); 554 555 static bool same_files(const char* file1, const char* file2); 556 557 //File i/o operations 558 559 static ssize_t read(int fd, void *buf, unsigned int nBytes); 560 static ssize_t read_at(int fd, void *buf, unsigned int nBytes, jlong offset); 561 static size_t write(int fd, const void *buf, unsigned int nBytes); 562 563 // Reading directories. 564 static DIR* opendir(const char* dirname); 565 static struct dirent* readdir(DIR* dirp); 566 static int closedir(DIR* dirp); 567 568 // Dynamic library extension 569 static const char* dll_file_extension(); 570 571 static const char* get_temp_directory(); 572 static const char* get_current_directory(char *buf, size_t buflen); 573 574 // Builds the platform-specific name of a library. 575 // Returns false if the buffer is too small. 576 static bool dll_build_name(char* buffer, size_t size, 577 const char* fname); 578 579 // Builds a platform-specific full library path given an ld path and 580 // unadorned library name. Returns true if the buffer contains a full 581 // path to an existing file, false otherwise. If pathname is empty, 582 // uses the path to the current directory. 583 static bool dll_locate_lib(char* buffer, size_t size, 584 const char* pathname, const char* fname); 585 586 // Symbol lookup, find nearest function name; basically it implements 587 // dladdr() for all platforms. Name of the nearest function is copied 588 // to buf. Distance from its base address is optionally returned as offset. 589 // If function name is not found, buf[0] is set to '\0' and offset is 590 // set to -1 (if offset is non-NULL). 591 static bool dll_address_to_function_name(address addr, char* buf, 592 int buflen, int* offset, 593 bool demangle = true); 594 595 // Locate DLL/DSO. On success, full path of the library is copied to 596 // buf, and offset is optionally set to be the distance between addr 597 // and the library's base address. On failure, buf[0] is set to '\0' 598 // and offset is set to -1 (if offset is non-NULL). 599 static bool dll_address_to_library_name(address addr, char* buf, 600 int buflen, int* offset); 601 602 // Find out whether the pc is in the static code for jvm.dll/libjvm.so. 603 static bool address_is_in_vm(address addr); 604 605 // Loads .dll/.so and 606 // in case of error it checks if .dll/.so was built for the 607 // same architecture as HotSpot is running on 608 // in case of an error NULL is returned and an error message is stored in ebuf 609 static void* dll_load(const char *name, char *ebuf, int ebuflen); 610 611 // lookup symbol in a shared library 612 static void* dll_lookup(void* handle, const char* name); 613 614 // Unload library 615 static void dll_unload(void *lib); 616 617 // Callback for loaded module information 618 // Input parameters: 619 // char* module_file_name, 620 // address module_base_addr, 621 // address module_top_addr, 622 // void* param 623 typedef int (*LoadedModulesCallbackFunc)(const char *, address, address, void *); 624 625 static int get_loaded_modules_info(LoadedModulesCallbackFunc callback, void *param); 626 627 // Return the handle of this process 628 static void* get_default_process_handle(); 629 630 // Check for static linked agent library 631 static bool find_builtin_agent(AgentLibrary *agent_lib, const char *syms[], 632 size_t syms_len); 633 634 // Find agent entry point 635 static void *find_agent_function(AgentLibrary *agent_lib, bool check_lib, 636 const char *syms[], size_t syms_len); 637 638 // Provide C99 compliant versions of these functions, since some versions 639 // of some platforms don't. 640 static int vsnprintf(char* buf, size_t len, const char* fmt, va_list args) ATTRIBUTE_PRINTF(3, 0); 641 static int snprintf(char* buf, size_t len, const char* fmt, ...) ATTRIBUTE_PRINTF(3, 4); 642 643 // Get host name in buffer provided 644 static bool get_host_name(char* buf, size_t buflen); 645 646 // Print out system information; they are called by fatal error handler. 647 // Output format may be different on different platforms. 648 static void print_os_info(outputStream* st); 649 static void print_os_info_brief(outputStream* st); 650 static void print_cpu_info(outputStream* st, char* buf, size_t buflen); 651 static void pd_print_cpu_info(outputStream* st, char* buf, size_t buflen); 652 static void print_summary_info(outputStream* st, char* buf, size_t buflen); 653 static void print_memory_info(outputStream* st); 654 static void print_dll_info(outputStream* st); 655 static void print_environment_variables(outputStream* st, const char** env_list); 656 static void print_context(outputStream* st, const void* context); 657 static void print_register_info(outputStream* st, const void* context); 658 static bool signal_sent_by_kill(const void* siginfo); 659 static void print_siginfo(outputStream* st, const void* siginfo); 660 static void print_signal_handlers(outputStream* st, char* buf, size_t buflen); 661 static void print_date_and_time(outputStream* st, char* buf, size_t buflen); 662 static void print_instructions(outputStream* st, address pc, int unitsize); 663 664 // helper for output of seconds in days , hours and months 665 static void print_dhm(outputStream* st, const char* startStr, long sec); 666 667 static void print_location(outputStream* st, intptr_t x, bool verbose = false); 668 static size_t lasterror(char *buf, size_t len); 669 static int get_last_error(); 670 671 // Replacement for strerror(). 672 // Will return the english description of the error (e.g. "File not found", as 673 // suggested in the POSIX standard. 674 // Will return "Unknown error" for an unknown errno value. 675 // Will not attempt to localize the returned string. 676 // Will always return a valid string which is a static constant. 677 // Will not change the value of errno. 678 static const char* strerror(int e); 679 680 // Will return the literalized version of the given errno (e.g. "EINVAL" 681 // for EINVAL). 682 // Will return "Unknown error" for an unknown errno value. 683 // Will always return a valid string which is a static constant. 684 // Will not change the value of errno. 685 static const char* errno_name(int e); 686 687 // wait for a key press if PauseAtExit is set 688 static void wait_for_keypress_at_exit(void); 689 690 // The following two functions are used by fatal error handler to trace 691 // native (C) frames. They are not part of frame.hpp/frame.cpp because 692 // frame.hpp/cpp assume thread is JavaThread, and also because different 693 // OS/compiler may have different convention or provide different API to 694 // walk C frames. 695 // 696 // We don't attempt to become a debugger, so we only follow frames if that 697 // does not require a lookup in the unwind table, which is part of the binary 698 // file but may be unsafe to read after a fatal error. So on x86, we can 699 // only walk stack if %ebp is used as frame pointer; on ia64, it's not 700 // possible to walk C stack without having the unwind table. 701 static bool is_first_C_frame(frame *fr); 702 static frame get_sender_for_C_frame(frame *fr); 703 704 // return current frame. pc() and sp() are set to NULL on failure. 705 static frame current_frame(); 706 707 static void print_hex_dump(outputStream* st, address start, address end, int unitsize, 708 int bytes_per_line, address logical_start); print_hex_dump(outputStream * st,address start,address end,int unitsize)709 static void print_hex_dump(outputStream* st, address start, address end, int unitsize) { 710 print_hex_dump(st, start, end, unitsize, /*bytes_per_line=*/16, /*logical_start=*/start); 711 } 712 713 // returns a string to describe the exception/signal; 714 // returns NULL if exception_code is not an OS exception/signal. 715 static const char* exception_name(int exception_code, char* buf, size_t buflen); 716 717 // Returns the signal number (e.g. 11) for a given signal name (SIGSEGV). 718 static int get_signal_number(const char* signal_name); 719 720 // Returns native Java library, loads if necessary 721 static void* native_java_library(); 722 723 // Fills in path to jvm.dll/libjvm.so (used by the Disassembler) 724 static void jvm_path(char *buf, jint buflen); 725 726 // JNI names 727 static void print_jni_name_prefix_on(outputStream* st, int args_size); 728 static void print_jni_name_suffix_on(outputStream* st, int args_size); 729 730 // Init os specific system properties values 731 static void init_system_properties_values(); 732 733 // IO operations, non-JVM_ version. 734 static int stat(const char* path, struct stat* sbuf); 735 static bool dir_is_empty(const char* path); 736 737 // IO operations on binary files 738 static int create_binary_file(const char* path, bool rewrite_existing); 739 static jlong current_file_offset(int fd); 740 static jlong seek_to_file_offset(int fd, jlong offset); 741 742 // Retrieve native stack frames. 743 // Parameter: 744 // stack: an array to storage stack pointers. 745 // frames: size of above array. 746 // toSkip: number of stack frames to skip at the beginning. 747 // Return: number of stack frames captured. 748 static int get_native_stack(address* stack, int size, int toSkip = 0); 749 750 // General allocation (must be MT-safe) 751 static void* malloc (size_t size, MEMFLAGS flags, const NativeCallStack& stack); 752 static void* malloc (size_t size, MEMFLAGS flags); 753 static void* realloc (void *memblock, size_t size, MEMFLAGS flag, const NativeCallStack& stack); 754 static void* realloc (void *memblock, size_t size, MEMFLAGS flag); 755 756 // handles NULL pointers 757 static void free (void *memblock); 758 static char* strdup(const char *, MEMFLAGS flags = mtInternal); // Like strdup 759 // Like strdup, but exit VM when strdup() returns NULL 760 static char* strdup_check_oom(const char*, MEMFLAGS flags = mtInternal); 761 762 #ifndef PRODUCT 763 static julong num_mallocs; // # of calls to malloc/realloc 764 static julong alloc_bytes; // # of bytes allocated 765 static julong num_frees; // # of calls to free 766 static julong free_bytes; // # of bytes freed 767 #endif 768 769 // SocketInterface (ex HPI SocketInterface ) 770 static int socket(int domain, int type, int protocol); 771 static int socket_close(int fd); 772 static int recv(int fd, char* buf, size_t nBytes, uint flags); 773 static int send(int fd, char* buf, size_t nBytes, uint flags); 774 static int raw_send(int fd, char* buf, size_t nBytes, uint flags); 775 static int connect(int fd, struct sockaddr* him, socklen_t len); 776 static struct hostent* get_host_by_name(char* name); 777 778 // Support for signals (see JVM_RaiseSignal, JVM_RegisterSignal) 779 static void initialize_jdk_signal_support(TRAPS); 780 static void signal_notify(int signal_number); 781 static void* signal(int signal_number, void* handler); 782 static void signal_raise(int signal_number); 783 static int signal_wait(); 784 static void* user_handler(); 785 static void terminate_signal_thread(); 786 static int sigexitnum_pd(); 787 788 // random number generation 789 static int random(); // return 32bit pseudorandom number 790 static int next_random(unsigned int rand_seed); // pure version of random() 791 static void init_random(unsigned int initval); // initialize random sequence 792 793 // Structured OS Exception support 794 static void os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method, JavaCallArguments* args, Thread* thread); 795 796 // On Posix compatible OS it will simply check core dump limits while on Windows 797 // it will check if dump file can be created. Check or prepare a core dump to be 798 // taken at a later point in the same thread in os::abort(). Use the caller 799 // provided buffer as a scratch buffer. The status message which will be written 800 // into the error log either is file location or a short error message, depending 801 // on the checking result. 802 static void check_dump_limit(char* buffer, size_t bufferSize); 803 804 // Get the default path to the core file 805 // Returns the length of the string 806 static int get_core_path(char* buffer, size_t bufferSize); 807 808 // JVMTI & JVM monitoring and management support 809 // The thread_cpu_time() and current_thread_cpu_time() are only 810 // supported if is_thread_cpu_time_supported() returns true. 811 812 // Thread CPU Time - return the fast estimate on a platform 813 // On Linux - fast clock_gettime where available - user+sys 814 // - otherwise: very slow /proc fs - user+sys 815 // On Windows - GetThreadTimes - user+sys 816 static jlong current_thread_cpu_time(); 817 static jlong thread_cpu_time(Thread* t); 818 819 // Thread CPU Time with user_sys_cpu_time parameter. 820 // 821 // If user_sys_cpu_time is true, user+sys time is returned. 822 // Otherwise, only user time is returned 823 static jlong current_thread_cpu_time(bool user_sys_cpu_time); 824 static jlong thread_cpu_time(Thread* t, bool user_sys_cpu_time); 825 826 // Return a bunch of info about the timers. 827 // Note that the returned info for these two functions may be different 828 // on some platforms 829 static void current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr); 830 static void thread_cpu_time_info(jvmtiTimerInfo *info_ptr); 831 832 static bool is_thread_cpu_time_supported(); 833 834 // System loadavg support. Returns -1 if load average cannot be obtained. 835 static int loadavg(double loadavg[], int nelem); 836 837 // Amount beyond the callee frame size that we bang the stack. 838 static int extra_bang_size_in_bytes(); 839 840 static char** split_path(const char* path, size_t* elements, size_t file_name_length); 841 842 // support for mapping non-volatile memory using MAP_SYNC 843 static bool supports_map_sync(); 844 845 public: 846 class CrashProtectionCallback : public StackObj { 847 public: 848 virtual void call() = 0; 849 }; 850 851 // Platform dependent stuff 852 #ifndef _WINDOWS 853 # include "os_posix.hpp" 854 #endif 855 #include OS_CPU_HEADER(os) 856 #include OS_HEADER(os) 857 858 #ifndef OS_NATIVE_THREAD_CREATION_FAILED_MSG 859 #define OS_NATIVE_THREAD_CREATION_FAILED_MSG "unable to create native thread: possibly out of memory or process/resource limits reached" 860 #endif 861 862 public: 863 #ifndef PLATFORM_PRINT_NATIVE_STACK 864 // No platform-specific code for printing the native stack. platform_print_native_stack(outputStream * st,const void * context,char * buf,int buf_size)865 static bool platform_print_native_stack(outputStream* st, const void* context, 866 char *buf, int buf_size) { 867 return false; 868 } 869 #endif 870 871 // debugging support (mostly used by debug.cpp but also fatal error handler) 872 static bool find(address pc, outputStream* st = tty); // OS specific function to make sense out of an address 873 874 static bool dont_yield(); // when true, JVM_Yield() is nop 875 static void print_statistics(); 876 877 // Thread priority helpers (implemented in OS-specific part) 878 static OSReturn set_native_priority(Thread* thread, int native_prio); 879 static OSReturn get_native_priority(const Thread* const thread, int* priority_ptr); 880 static int java_to_os_priority[CriticalPriority + 1]; 881 // Hint to the underlying OS that a task switch would not be good. 882 // Void return because it's a hint and can fail. native_thread_creation_failed_msg()883 static const char* native_thread_creation_failed_msg() { 884 return OS_NATIVE_THREAD_CREATION_FAILED_MSG; 885 } 886 887 // Used at creation if requested by the diagnostic flag PauseAtStartup. 888 // Causes the VM to wait until an external stimulus has been applied 889 // (for Unix, that stimulus is a signal, for Windows, an external 890 // ResumeThread call) 891 static void pause(); 892 893 // Builds a platform dependent Agent_OnLoad_<libname> function name 894 // which is used to find statically linked in agents. 895 static char* build_agent_function_name(const char *sym, const char *cname, 896 bool is_absolute_path); 897 898 class SuspendedThreadTaskContext { 899 public: SuspendedThreadTaskContext(Thread * thread,void * ucontext)900 SuspendedThreadTaskContext(Thread* thread, void *ucontext) : _thread(thread), _ucontext(ucontext) {} thread() const901 Thread* thread() const { return _thread; } ucontext() const902 void* ucontext() const { return _ucontext; } 903 private: 904 Thread* _thread; 905 void* _ucontext; 906 }; 907 908 class SuspendedThreadTask { 909 public: SuspendedThreadTask(Thread * thread)910 SuspendedThreadTask(Thread* thread) : _thread(thread), _done(false) {} 911 void run(); is_done()912 bool is_done() { return _done; } 913 virtual void do_task(const SuspendedThreadTaskContext& context) = 0; 914 protected: ~SuspendedThreadTask()915 ~SuspendedThreadTask() {} 916 private: 917 void internal_do_task(); 918 Thread* _thread; 919 bool _done; 920 }; 921 922 #ifndef _WINDOWS 923 // Suspend/resume support 924 // Protocol: 925 // 926 // a thread starts in SR_RUNNING 927 // 928 // SR_RUNNING can go to 929 // * SR_SUSPEND_REQUEST when the WatcherThread wants to suspend it 930 // SR_SUSPEND_REQUEST can go to 931 // * SR_RUNNING if WatcherThread decides it waited for SR_SUSPENDED too long (timeout) 932 // * SR_SUSPENDED if the stopped thread receives the signal and switches state 933 // SR_SUSPENDED can go to 934 // * SR_WAKEUP_REQUEST when the WatcherThread has done the work and wants to resume 935 // SR_WAKEUP_REQUEST can go to 936 // * SR_RUNNING when the stopped thread receives the signal 937 // * SR_WAKEUP_REQUEST on timeout (resend the signal and try again) 938 class SuspendResume { 939 public: 940 enum State { 941 SR_RUNNING, 942 SR_SUSPEND_REQUEST, 943 SR_SUSPENDED, 944 SR_WAKEUP_REQUEST 945 }; 946 947 private: 948 volatile State _state; 949 950 private: 951 /* try to switch state from state "from" to state "to" 952 * returns the state set after the method is complete 953 */ 954 State switch_state(State from, State to); 955 956 public: SuspendResume()957 SuspendResume() : _state(SR_RUNNING) { } 958 state() const959 State state() const { return _state; } 960 request_suspend()961 State request_suspend() { 962 return switch_state(SR_RUNNING, SR_SUSPEND_REQUEST); 963 } 964 cancel_suspend()965 State cancel_suspend() { 966 return switch_state(SR_SUSPEND_REQUEST, SR_RUNNING); 967 } 968 suspended()969 State suspended() { 970 return switch_state(SR_SUSPEND_REQUEST, SR_SUSPENDED); 971 } 972 request_wakeup()973 State request_wakeup() { 974 return switch_state(SR_SUSPENDED, SR_WAKEUP_REQUEST); 975 } 976 running()977 State running() { 978 return switch_state(SR_WAKEUP_REQUEST, SR_RUNNING); 979 } 980 is_running() const981 bool is_running() const { 982 return _state == SR_RUNNING; 983 } 984 is_suspended() const985 bool is_suspended() const { 986 return _state == SR_SUSPENDED; 987 } 988 }; 989 #endif // !WINDOWS 990 991 protected: 992 static volatile unsigned int _rand_seed; // seed for random number generator 993 static int _processor_count; // number of processors 994 static int _initial_active_processor_count; // number of active processors during initialization. 995 996 static char* format_boot_path(const char* format_string, 997 const char* home, 998 int home_len, 999 char fileSep, 1000 char pathSep); 1001 static bool set_boot_path(char fileSep, char pathSep); 1002 1003 }; 1004 1005 // Note that "PAUSE" is almost always used with synchronization 1006 // so arguably we should provide Atomic::SpinPause() instead 1007 // of the global SpinPause() with C linkage. 1008 // It'd also be eligible for inlining on many platforms. 1009 1010 extern "C" int SpinPause(); 1011 1012 #endif // SHARE_RUNTIME_OS_HPP 1013