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