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