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