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