os.hpp revision 5966:e2722a66aba7
1/*
2 * Copyright (c) 1997, 2013, 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 "jvmtifiles/jvmti.h"
29#include "runtime/atomic.hpp"
30#include "runtime/extendedPC.hpp"
31#include "runtime/handles.hpp"
32#include "utilities/top.hpp"
33#ifdef TARGET_OS_FAMILY_linux
34# include "jvm_linux.h"
35# include <setjmp.h>
36#endif
37#ifdef TARGET_OS_FAMILY_solaris
38# include "jvm_solaris.h"
39# include <setjmp.h>
40#endif
41#ifdef TARGET_OS_FAMILY_windows
42# include "jvm_windows.h"
43#endif
44#ifdef TARGET_OS_FAMILY_aix
45# include "jvm_aix.h"
46# include <setjmp.h>
47#endif
48#ifdef TARGET_OS_FAMILY_bsd
49# include "jvm_bsd.h"
50# include <setjmp.h>
51#endif
52
53class AgentLibrary;
54
55// os defines the interface to operating system; this includes traditional
56// OS services (time, I/O) as well as other functionality with system-
57// dependent code.
58
59typedef void (*dll_func)(...);
60
61class Thread;
62class JavaThread;
63class Event;
64class DLL;
65class FileHandle;
66template<class E> class GrowableArray;
67
68// %%%%% Moved ThreadState, START_FN, OSThread to new osThread.hpp. -- Rose
69
70// Platform-independent error return values from OS functions
71enum OSReturn {
72  OS_OK         =  0,        // Operation was successful
73  OS_ERR        = -1,        // Operation failed
74  OS_INTRPT     = -2,        // Operation was interrupted
75  OS_TIMEOUT    = -3,        // Operation timed out
76  OS_NOMEM      = -5,        // Operation failed for lack of memory
77  OS_NORESOURCE = -6         // Operation failed for lack of nonmemory resource
78};
79
80enum ThreadPriority {        // JLS 20.20.1-3
81  NoPriority       = -1,     // Initial non-priority value
82  MinPriority      =  1,     // Minimum priority
83  NormPriority     =  5,     // Normal (non-daemon) priority
84  NearMaxPriority  =  9,     // High priority, used for VMThread
85  MaxPriority      = 10,     // Highest priority, used for WatcherThread
86                             // ensures that VMThread doesn't starve profiler
87  CriticalPriority = 11      // Critical thread priority
88};
89
90// Executable parameter flag for os::commit_memory() and
91// os::commit_memory_or_exit().
92const bool ExecMem = true;
93
94// Typedef for structured exception handling support
95typedef void (*java_call_t)(JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread);
96
97class os: AllStatic {
98 public:
99  enum { page_sizes_max = 9 }; // Size of _page_sizes array (8 plus a sentinel)
100
101 private:
102  static OSThread*          _starting_thread;
103  static address            _polling_page;
104  static volatile int32_t * _mem_serialize_page;
105  static uintptr_t          _serialize_page_mask;
106 public:
107  static size_t             _page_sizes[page_sizes_max];
108
109 private:
110  static void init_page_sizes(size_t default_page_size) {
111    _page_sizes[0] = default_page_size;
112    _page_sizes[1] = 0; // sentinel
113  }
114
115  static char*  pd_reserve_memory(size_t bytes, char* addr = 0,
116                               size_t alignment_hint = 0);
117  static char*  pd_attempt_reserve_memory_at(size_t bytes, char* addr);
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
144 public:
145  static void init(void);                      // Called before command line parsing
146  static jint init_2(void);                    // Called after command line parsing
147  static void init_globals(void) {             // Called from init_globals() in init.cpp
148    init_globals_ext();
149  }
150  static void init_3(void);                    // Called at the end of vm init
151
152  // File names are case-insensitive on windows only
153  // Override me as needed
154  static int    file_name_strcmp(const char* s1, const char* s2);
155
156  static bool getenv(const char* name, char* buffer, int len);
157  static bool have_special_privileges();
158
159  static jlong  javaTimeMillis();
160  static jlong  javaTimeNanos();
161  static void   javaTimeNanos_info(jvmtiTimerInfo *info_ptr);
162  static void   run_periodic_checks();
163
164
165  // Returns the elapsed time in seconds since the vm started.
166  static double elapsedTime();
167
168  // Returns real time in seconds since an arbitrary point
169  // in the past.
170  static bool getTimesSecs(double* process_real_time,
171                           double* process_user_time,
172                           double* process_system_time);
173
174  // Interface to the performance counter
175  static jlong elapsed_counter();
176  static jlong elapsed_frequency();
177
178  // The "virtual time" of a thread is the amount of time a thread has
179  // actually run.  The first function indicates whether the OS supports
180  // this functionality for the current thread, and if so:
181  //   * the second enables vtime tracking (if that is required).
182  //   * the third tells whether vtime is enabled.
183  //   * the fourth returns the elapsed virtual time for the current
184  //     thread.
185  static bool supports_vtime();
186  static bool enable_vtime();
187  static bool vtime_enabled();
188  static double elapsedVTime();
189
190  // Return current local time in a string (YYYY-MM-DD HH:MM:SS).
191  // It is MT safe, but not async-safe, as reading time zone
192  // information may require a lock on some platforms.
193  static char*      local_time_string(char *buf, size_t buflen);
194  static struct tm* localtime_pd     (const time_t* clock, struct tm*  res);
195  // Fill in buffer with current local time as an ISO-8601 string.
196  // E.g., YYYY-MM-DDThh:mm:ss.mmm+zzzz.
197  // Returns buffer, or NULL if it failed.
198  static char* iso8601_time(char* buffer, size_t buffer_length);
199
200  // Interface for detecting multiprocessor system
201  static inline bool is_MP() {
202    assert(_processor_count > 0, "invalid processor count");
203    return _processor_count > 1 || AssumeMP;
204  }
205  static julong available_memory();
206  static julong physical_memory();
207  static bool has_allocatable_memory_limit(julong* limit);
208  static bool is_server_class_machine();
209
210  // number of CPUs
211  static int processor_count() {
212    return _processor_count;
213  }
214  static void set_processor_count(int count) { _processor_count = count; }
215
216  // Returns the number of CPUs this process is currently allowed to run on.
217  // Note that on some OSes this can change dynamically.
218  static int active_processor_count();
219
220  // Bind processes to processors.
221  //     This is a two step procedure:
222  //     first you generate a distribution of processes to processors,
223  //     then you bind processes according to that distribution.
224  // Compute a distribution for number of processes to processors.
225  //    Stores the processor id's into the distribution array argument.
226  //    Returns true if it worked, false if it didn't.
227  static bool distribute_processes(uint length, uint* distribution);
228  // Binds the current process to a processor.
229  //    Returns true if it worked, false if it didn't.
230  static bool bind_to_processor(uint processor_id);
231
232  // Give a name to the current thread.
233  static void set_native_thread_name(const char *name);
234
235  // Interface for stack banging (predetect possible stack overflow for
236  // exception processing)  There are guard pages, and above that shadow
237  // pages for stack overflow checking.
238  static bool uses_stack_guard_pages();
239  static bool allocate_stack_guard_pages();
240  static void bang_stack_shadow_pages();
241  static bool stack_shadow_pages_available(Thread *thread, methodHandle method);
242
243  // OS interface to Virtual Memory
244
245  // Return the default page size.
246  static int    vm_page_size();
247
248  // Return the page size to use for a region of memory.  The min_pages argument
249  // is a hint intended to limit fragmentation; it says the returned page size
250  // should be <= region_max_size / min_pages.  Because min_pages is a hint,
251  // this routine may return a size larger than region_max_size / min_pages.
252  //
253  // The current implementation ignores min_pages if a larger page size is an
254  // exact multiple of both region_min_size and region_max_size.  This allows
255  // larger pages to be used when doing so would not cause fragmentation; in
256  // particular, a single page can be used when region_min_size ==
257  // region_max_size == a supported page size.
258  static size_t page_size_for_region(size_t region_min_size,
259                                     size_t region_max_size,
260                                     uint min_pages);
261
262  // Methods for tracing page sizes returned by the above method; enabled by
263  // TracePageSizes.  The region_{min,max}_size parameters should be the values
264  // passed to page_size_for_region() and page_size should be the result of that
265  // call.  The (optional) base and size parameters should come from the
266  // ReservedSpace base() and size() methods.
267  static void trace_page_sizes(const char* str, const size_t* page_sizes,
268                               int count) PRODUCT_RETURN;
269  static void trace_page_sizes(const char* str, const size_t region_min_size,
270                               const size_t region_max_size,
271                               const size_t page_size,
272                               const char* base = NULL,
273                               const size_t size = 0) PRODUCT_RETURN;
274
275  static int    vm_allocation_granularity();
276  static char*  reserve_memory(size_t bytes, char* addr = 0,
277                               size_t alignment_hint = 0);
278  static char*  reserve_memory(size_t bytes, char* addr,
279                               size_t alignment_hint, MEMFLAGS flags);
280  static char*  reserve_memory_aligned(size_t size, size_t alignment);
281  static char*  attempt_reserve_memory_at(size_t bytes, char* addr);
282  static void   split_reserved_memory(char *base, size_t size,
283                                      size_t split, bool realloc);
284  static bool   commit_memory(char* addr, size_t bytes, bool executable);
285  static bool   commit_memory(char* addr, size_t size, size_t alignment_hint,
286                              bool executable);
287  // Same as commit_memory() that either succeeds or calls
288  // vm_exit_out_of_memory() with the specified mesg.
289  static void   commit_memory_or_exit(char* addr, size_t bytes,
290                                      bool executable, const char* mesg);
291  static void   commit_memory_or_exit(char* addr, size_t size,
292                                      size_t alignment_hint,
293                                      bool executable, const char* mesg);
294  static bool   uncommit_memory(char* addr, size_t bytes);
295  static bool   release_memory(char* addr, size_t bytes);
296
297  enum ProtType { MEM_PROT_NONE, MEM_PROT_READ, MEM_PROT_RW, MEM_PROT_RWX };
298  static bool   protect_memory(char* addr, size_t bytes, ProtType prot,
299                               bool is_committed = true);
300
301  static bool   guard_memory(char* addr, size_t bytes);
302  static bool   unguard_memory(char* addr, size_t bytes);
303  static bool   create_stack_guard_pages(char* addr, size_t bytes);
304  static bool   pd_create_stack_guard_pages(char* addr, size_t bytes);
305  static bool   remove_stack_guard_pages(char* addr, size_t bytes);
306
307  static char*  map_memory(int fd, const char* file_name, size_t file_offset,
308                           char *addr, size_t bytes, bool read_only = false,
309                           bool allow_exec = false);
310  static char*  remap_memory(int fd, const char* file_name, size_t file_offset,
311                             char *addr, size_t bytes, bool read_only,
312                             bool allow_exec);
313  static bool   unmap_memory(char *addr, size_t bytes);
314  static void   free_memory(char *addr, size_t bytes, size_t alignment_hint);
315  static void   realign_memory(char *addr, size_t bytes, size_t alignment_hint);
316
317  // NUMA-specific interface
318  static bool   numa_has_static_binding();
319  static bool   numa_has_group_homing();
320  static void   numa_make_local(char *addr, size_t bytes, int lgrp_hint);
321  static void   numa_make_global(char *addr, size_t bytes);
322  static size_t numa_get_groups_num();
323  static size_t numa_get_leaf_groups(int *ids, size_t size);
324  static bool   numa_topology_changed();
325  static int    numa_get_group_id();
326
327  // Page manipulation
328  struct page_info {
329    size_t size;
330    int lgrp_id;
331  };
332  static bool   get_page_info(char *start, page_info* info);
333  static char*  scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found);
334
335  static char*  non_memory_address_word();
336  // reserve, commit and pin the entire memory region
337  static char*  reserve_memory_special(size_t size, size_t alignment,
338                                       char* addr, bool executable);
339  static bool   release_memory_special(char* addr, size_t bytes);
340  static void   large_page_init();
341  static size_t large_page_size();
342  static bool   can_commit_large_page_memory();
343  static bool   can_execute_large_page_memory();
344
345  // OS interface to polling page
346  static address get_polling_page()             { return _polling_page; }
347  static void    set_polling_page(address page) { _polling_page = page; }
348  static bool    is_poll_address(address addr)  { return addr >= _polling_page && addr < (_polling_page + os::vm_page_size()); }
349  static void    make_polling_page_unreadable();
350  static void    make_polling_page_readable();
351
352  // Routines used to serialize the thread state without using membars
353  static void    serialize_thread_states();
354
355  // Since we write to the serialize page from every thread, we
356  // want stores to be on unique cache lines whenever possible
357  // in order to minimize CPU cross talk.  We pre-compute the
358  // amount to shift the thread* to make this offset unique to
359  // each thread.
360  static int     get_serialize_page_shift_count() {
361    return SerializePageShiftCount;
362  }
363
364  static void     set_serialize_page_mask(uintptr_t mask) {
365    _serialize_page_mask = mask;
366  }
367
368  static unsigned int  get_serialize_page_mask() {
369    return _serialize_page_mask;
370  }
371
372  static void    set_memory_serialize_page(address page);
373
374  static address get_memory_serialize_page() {
375    return (address)_mem_serialize_page;
376  }
377
378  static inline void write_memory_serialize_page(JavaThread *thread) {
379    uintptr_t page_offset = ((uintptr_t)thread >>
380                            get_serialize_page_shift_count()) &
381                            get_serialize_page_mask();
382    *(volatile int32_t *)((uintptr_t)_mem_serialize_page+page_offset) = 1;
383  }
384
385  static bool    is_memory_serialize_page(JavaThread *thread, address addr) {
386    if (UseMembar) return false;
387    // Previously this function calculated the exact address of this
388    // thread's serialize page, and checked if the faulting address
389    // was equal.  However, some platforms mask off faulting addresses
390    // to the page size, so now we just check that the address is
391    // within the page.  This makes the thread argument unnecessary,
392    // but we retain the NULL check to preserve existing behaviour.
393    if (thread == NULL) return false;
394    address page = (address) _mem_serialize_page;
395    return addr >= page && addr < (page + os::vm_page_size());
396  }
397
398  static void block_on_serialize_page_trap();
399
400  // threads
401
402  enum ThreadType {
403    vm_thread,
404    cgc_thread,        // Concurrent GC thread
405    pgc_thread,        // Parallel GC thread
406    java_thread,
407    compiler_thread,
408    watcher_thread,
409    os_thread
410  };
411
412  static bool create_thread(Thread* thread,
413                            ThreadType thr_type,
414                            size_t stack_size = 0);
415  static bool create_main_thread(JavaThread* thread);
416  static bool create_attached_thread(JavaThread* thread);
417  static void pd_start_thread(Thread* thread);
418  static void start_thread(Thread* thread);
419
420  static void initialize_thread(Thread* thr);
421  static void free_thread(OSThread* osthread);
422
423  // thread id on Linux/64bit is 64bit, on Windows and Solaris, it's 32bit
424  static intx current_thread_id();
425  static int current_process_id();
426  static int sleep(Thread* thread, jlong ms, bool interruptable);
427  static int naked_sleep();
428  static void infinite_sleep(); // never returns, use with CAUTION
429  static void yield();        // Yields to all threads with same priority
430  enum YieldResult {
431    YIELD_SWITCHED = 1,         // caller descheduled, other ready threads exist & ran
432    YIELD_NONEREADY = 0,        // No other runnable/ready threads.
433                                // platform-specific yield return immediately
434    YIELD_UNKNOWN = -1          // Unknown: platform doesn't support _SWITCHED or _NONEREADY
435    // YIELD_SWITCHED and YIELD_NONREADY imply the platform supports a "strong"
436    // yield that can be used in lieu of blocking.
437  } ;
438  static YieldResult NakedYield () ;
439  static void yield_all(int attempts = 0); // Yields to all other threads including lower priority
440  static void loop_breaker(int attempts);  // called from within tight loops to possibly influence time-sharing
441  static OSReturn set_priority(Thread* thread, ThreadPriority priority);
442  static OSReturn get_priority(const Thread* const thread, ThreadPriority& priority);
443
444  static void interrupt(Thread* thread);
445  static bool is_interrupted(Thread* thread, bool clear_interrupted);
446
447  static int pd_self_suspend_thread(Thread* thread);
448
449  static ExtendedPC fetch_frame_from_context(void* ucVoid, intptr_t** sp, intptr_t** fp);
450  static frame      fetch_frame_from_context(void* ucVoid);
451
452  static ExtendedPC get_thread_pc(Thread *thread);
453  static void breakpoint();
454
455  static address current_stack_pointer();
456  static address current_stack_base();
457  static size_t current_stack_size();
458
459  static void verify_stack_alignment() PRODUCT_RETURN;
460
461  static int message_box(const char* title, const char* message);
462  static char* do_you_want_to_debug(const char* message);
463
464  // run cmd in a separate process and return its exit code; or -1 on failures
465  static int fork_and_exec(char *cmd);
466
467  // Set file to send error reports.
468  static void set_error_file(const char *logfile);
469
470  // os::exit() is merged with vm_exit()
471  // static void exit(int num);
472
473  // Terminate the VM, but don't exit the process
474  static void shutdown();
475
476  // Terminate with an error.  Default is to generate a core file on platforms
477  // that support such things.  This calls shutdown() and then aborts.
478  static void abort(bool dump_core = true);
479
480  // Die immediately, no exit hook, no abort hook, no cleanup.
481  static void die();
482
483  // File i/o operations
484  static const int default_file_open_flags();
485  static int open(const char *path, int oflag, int mode);
486  static FILE* open(int fd, const char* mode);
487  static int close(int fd);
488  static jlong lseek(int fd, jlong offset, int whence);
489  static char* native_path(char *path);
490  static int ftruncate(int fd, jlong length);
491  static int fsync(int fd);
492  static int available(int fd, jlong *bytes);
493
494  //File i/o operations
495
496  static size_t read(int fd, void *buf, unsigned int nBytes);
497  static size_t restartable_read(int fd, void *buf, unsigned int nBytes);
498  static size_t write(int fd, const void *buf, unsigned int nBytes);
499
500  // Reading directories.
501  static DIR*           opendir(const char* dirname);
502  static int            readdir_buf_size(const char *path);
503  static struct dirent* readdir(DIR* dirp, dirent* dbuf);
504  static int            closedir(DIR* dirp);
505
506  // Dynamic library extension
507  static const char*    dll_file_extension();
508
509  static const char*    get_temp_directory();
510  static const char*    get_current_directory(char *buf, size_t buflen);
511
512  // Builds a platform-specific full library path given a ld path and lib name
513  // Returns true if buffer contains full path to existing file, false otherwise
514  static bool           dll_build_name(char* buffer, size_t size,
515                                       const char* pathname, const char* fname);
516
517  // Symbol lookup, find nearest function name; basically it implements
518  // dladdr() for all platforms. Name of the nearest function is copied
519  // to buf. Distance from its base address is optionally returned as offset.
520  // If function name is not found, buf[0] is set to '\0' and offset is
521  // set to -1 (if offset is non-NULL).
522  static bool dll_address_to_function_name(address addr, char* buf,
523                                           int buflen, int* offset);
524
525  // Locate DLL/DSO. On success, full path of the library is copied to
526  // buf, and offset is optionally set to be the distance between addr
527  // and the library's base address. On failure, buf[0] is set to '\0'
528  // and offset is set to -1 (if offset is non-NULL).
529  static bool dll_address_to_library_name(address addr, char* buf,
530                                          int buflen, int* offset);
531
532  // Find out whether the pc is in the static code for jvm.dll/libjvm.so.
533  static bool address_is_in_vm(address addr);
534
535  // Loads .dll/.so and
536  // in case of error it checks if .dll/.so was built for the
537  // same architecture as Hotspot is running on
538  static void* dll_load(const char *name, char *ebuf, int ebuflen);
539
540  // lookup symbol in a shared library
541  static void* dll_lookup(void* handle, const char* name);
542
543  // Unload library
544  static void  dll_unload(void *lib);
545
546  // Return the handle of this process
547  static void* get_default_process_handle();
548
549  // Check for static linked agent library
550  static bool find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
551                                 size_t syms_len);
552
553  // Find agent entry point
554  static void *find_agent_function(AgentLibrary *agent_lib, bool check_lib,
555                                   const char *syms[], size_t syms_len);
556
557  // Print out system information; they are called by fatal error handler.
558  // Output format may be different on different platforms.
559  static void print_os_info(outputStream* st);
560  static void print_os_info_brief(outputStream* st);
561  static void print_cpu_info(outputStream* st);
562  static void pd_print_cpu_info(outputStream* st);
563  static void print_memory_info(outputStream* st);
564  static void print_dll_info(outputStream* st);
565  static void print_environment_variables(outputStream* st, const char** env_list, char* buffer, int len);
566  static void print_context(outputStream* st, void* context);
567  static void print_register_info(outputStream* st, void* context);
568  static void print_siginfo(outputStream* st, void* siginfo);
569  static void print_signal_handlers(outputStream* st, char* buf, size_t buflen);
570  static void print_date_and_time(outputStream* st);
571
572  static void print_location(outputStream* st, intptr_t x, bool verbose = false);
573  static size_t lasterror(char *buf, size_t len);
574  static int get_last_error();
575
576  // Determines whether the calling process is being debugged by a user-mode debugger.
577  static bool is_debugger_attached();
578
579  // wait for a key press if PauseAtExit is set
580  static void wait_for_keypress_at_exit(void);
581
582  // The following two functions are used by fatal error handler to trace
583  // native (C) frames. They are not part of frame.hpp/frame.cpp because
584  // frame.hpp/cpp assume thread is JavaThread, and also because different
585  // OS/compiler may have different convention or provide different API to
586  // walk C frames.
587  //
588  // We don't attempt to become a debugger, so we only follow frames if that
589  // does not require a lookup in the unwind table, which is part of the binary
590  // file but may be unsafe to read after a fatal error. So on x86, we can
591  // only walk stack if %ebp is used as frame pointer; on ia64, it's not
592  // possible to walk C stack without having the unwind table.
593  static bool is_first_C_frame(frame *fr);
594  static frame get_sender_for_C_frame(frame *fr);
595
596  // return current frame. pc() and sp() are set to NULL on failure.
597  static frame      current_frame();
598
599  static void print_hex_dump(outputStream* st, address start, address end, int unitsize);
600
601  // returns a string to describe the exception/signal;
602  // returns NULL if exception_code is not an OS exception/signal.
603  static const char* exception_name(int exception_code, char* buf, size_t buflen);
604
605  // Returns native Java library, loads if necessary
606  static void*    native_java_library();
607
608  // Fills in path to jvm.dll/libjvm.so (used by the Disassembler)
609  static void     jvm_path(char *buf, jint buflen);
610
611  // Returns true if we are running in a headless jre.
612  static bool     is_headless_jre();
613
614  // JNI names
615  static void     print_jni_name_prefix_on(outputStream* st, int args_size);
616  static void     print_jni_name_suffix_on(outputStream* st, int args_size);
617
618  // File conventions
619  static const char* file_separator();
620  static const char* line_separator();
621  static const char* path_separator();
622
623  // Init os specific system properties values
624  static void init_system_properties_values();
625
626  // IO operations, non-JVM_ version.
627  static int stat(const char* path, struct stat* sbuf);
628  static bool dir_is_empty(const char* path);
629
630  // IO operations on binary files
631  static int create_binary_file(const char* path, bool rewrite_existing);
632  static jlong current_file_offset(int fd);
633  static jlong seek_to_file_offset(int fd, jlong offset);
634
635  // Thread Local Storage
636  static int   allocate_thread_local_storage();
637  static void  thread_local_storage_at_put(int index, void* value);
638  static void* thread_local_storage_at(int index);
639  static void  free_thread_local_storage(int index);
640
641  // Stack walk
642  static address get_caller_pc(int n = 0);
643
644  // General allocation (must be MT-safe)
645  static void* malloc  (size_t size, MEMFLAGS flags, address caller_pc = 0);
646  static void* realloc (void *memblock, size_t size, MEMFLAGS flags, address caller_pc = 0);
647  static void  free    (void *memblock, MEMFLAGS flags = mtNone);
648  static bool  check_heap(bool force = false);      // verify C heap integrity
649  static char* strdup(const char *, MEMFLAGS flags = mtInternal);  // Like strdup
650
651#ifndef PRODUCT
652  static julong num_mallocs;         // # of calls to malloc/realloc
653  static julong alloc_bytes;         // # of bytes allocated
654  static julong num_frees;           // # of calls to free
655  static julong free_bytes;          // # of bytes freed
656#endif
657
658  // SocketInterface (ex HPI SocketInterface )
659  static int socket(int domain, int type, int protocol);
660  static int socket_close(int fd);
661  static int socket_shutdown(int fd, int howto);
662  static int recv(int fd, char* buf, size_t nBytes, uint flags);
663  static int send(int fd, char* buf, size_t nBytes, uint flags);
664  static int raw_send(int fd, char* buf, size_t nBytes, uint flags);
665  static int timeout(int fd, long timeout);
666  static int listen(int fd, int count);
667  static int connect(int fd, struct sockaddr* him, socklen_t len);
668  static int bind(int fd, struct sockaddr* him, socklen_t len);
669  static int accept(int fd, struct sockaddr* him, socklen_t* len);
670  static int recvfrom(int fd, char* buf, size_t nbytes, uint flags,
671                      struct sockaddr* from, socklen_t* fromlen);
672  static int get_sock_name(int fd, struct sockaddr* him, socklen_t* len);
673  static int sendto(int fd, char* buf, size_t len, uint flags,
674                    struct sockaddr* to, socklen_t tolen);
675  static int socket_available(int fd, jint* pbytes);
676
677  static int get_sock_opt(int fd, int level, int optname,
678                          char* optval, socklen_t* optlen);
679  static int set_sock_opt(int fd, int level, int optname,
680                          const char* optval, socklen_t optlen);
681  static int get_host_name(char* name, int namelen);
682
683  static struct hostent* get_host_by_name(char* name);
684
685  // Support for signals (see JVM_RaiseSignal, JVM_RegisterSignal)
686  static void  signal_init();
687  static void  signal_init_pd();
688  static void  signal_notify(int signal_number);
689  static void* signal(int signal_number, void* handler);
690  static void  signal_raise(int signal_number);
691  static int   signal_wait();
692  static int   signal_lookup();
693  static void* user_handler();
694  static void  terminate_signal_thread();
695  static int   sigexitnum_pd();
696
697  // random number generation
698  static long random();                    // return 32bit pseudorandom number
699  static void init_random(long initval);   // initialize random sequence
700
701  // Structured OS Exception support
702  static void os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread);
703
704  // On Windows this will create an actual minidump, on Linux/Solaris it will simply check core dump limits
705  static void check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize);
706
707  // Get the default path to the core file
708  // Returns the length of the string
709  static int get_core_path(char* buffer, size_t bufferSize);
710
711  // JVMTI & JVM monitoring and management support
712  // The thread_cpu_time() and current_thread_cpu_time() are only
713  // supported if is_thread_cpu_time_supported() returns true.
714  // They are not supported on Solaris T1.
715
716  // Thread CPU Time - return the fast estimate on a platform
717  // On Solaris - call gethrvtime (fast) - user time only
718  // On Linux   - fast clock_gettime where available - user+sys
719  //            - otherwise: very slow /proc fs - user+sys
720  // On Windows - GetThreadTimes - user+sys
721  static jlong current_thread_cpu_time();
722  static jlong thread_cpu_time(Thread* t);
723
724  // Thread CPU Time with user_sys_cpu_time parameter.
725  //
726  // If user_sys_cpu_time is true, user+sys time is returned.
727  // Otherwise, only user time is returned
728  static jlong current_thread_cpu_time(bool user_sys_cpu_time);
729  static jlong thread_cpu_time(Thread* t, bool user_sys_cpu_time);
730
731  // Return a bunch of info about the timers.
732  // Note that the returned info for these two functions may be different
733  // on some platforms
734  static void current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr);
735  static void thread_cpu_time_info(jvmtiTimerInfo *info_ptr);
736
737  static bool is_thread_cpu_time_supported();
738
739  // System loadavg support.  Returns -1 if load average cannot be obtained.
740  static int loadavg(double loadavg[], int nelem);
741
742  // Hook for os specific jvm options that we don't want to abort on seeing
743  static bool obsolete_option(const JavaVMOption *option);
744
745  // Read file line by line. If line is longer than bsize,
746  // rest of line is skipped. Returns number of bytes read or -1 on EOF
747  static int get_line_chars(int fd, char *buf, const size_t bsize);
748
749  // Extensions
750#include "runtime/os_ext.hpp"
751
752 public:
753  class CrashProtectionCallback : public StackObj {
754  public:
755    virtual void call() = 0;
756  };
757
758  // Platform dependent stuff
759#ifdef TARGET_OS_FAMILY_linux
760# include "os_linux.hpp"
761# include "os_posix.hpp"
762#endif
763#ifdef TARGET_OS_FAMILY_solaris
764# include "os_solaris.hpp"
765# include "os_posix.hpp"
766#endif
767#ifdef TARGET_OS_FAMILY_windows
768# include "os_windows.hpp"
769#endif
770#ifdef TARGET_OS_FAMILY_aix
771# include "os_aix.hpp"
772# include "os_posix.hpp"
773#endif
774#ifdef TARGET_OS_FAMILY_bsd
775# include "os_posix.hpp"
776# include "os_bsd.hpp"
777#endif
778#ifdef TARGET_OS_ARCH_linux_x86
779# include "os_linux_x86.hpp"
780#endif
781#ifdef TARGET_OS_ARCH_linux_sparc
782# include "os_linux_sparc.hpp"
783#endif
784#ifdef TARGET_OS_ARCH_linux_zero
785# include "os_linux_zero.hpp"
786#endif
787#ifdef TARGET_OS_ARCH_solaris_x86
788# include "os_solaris_x86.hpp"
789#endif
790#ifdef TARGET_OS_ARCH_solaris_sparc
791# include "os_solaris_sparc.hpp"
792#endif
793#ifdef TARGET_OS_ARCH_windows_x86
794# include "os_windows_x86.hpp"
795#endif
796#ifdef TARGET_OS_ARCH_linux_arm
797# include "os_linux_arm.hpp"
798#endif
799#ifdef TARGET_OS_ARCH_linux_ppc
800# include "os_linux_ppc.hpp"
801#endif
802#ifdef TARGET_OS_ARCH_aix_ppc
803# include "os_aix_ppc.hpp"
804#endif
805#ifdef TARGET_OS_ARCH_bsd_x86
806# include "os_bsd_x86.hpp"
807#endif
808#ifdef TARGET_OS_ARCH_bsd_zero
809# include "os_bsd_zero.hpp"
810#endif
811
812 public:
813  // debugging support (mostly used by debug.cpp but also fatal error handler)
814  static bool find(address pc, outputStream* st = tty); // OS specific function to make sense out of an address
815
816  static bool dont_yield();                     // when true, JVM_Yield() is nop
817  static void print_statistics();
818
819  // Thread priority helpers (implemented in OS-specific part)
820  static OSReturn set_native_priority(Thread* thread, int native_prio);
821  static OSReturn get_native_priority(const Thread* const thread, int* priority_ptr);
822  static int java_to_os_priority[CriticalPriority + 1];
823  // Hint to the underlying OS that a task switch would not be good.
824  // Void return because it's a hint and can fail.
825  static void hint_no_preempt();
826
827  // Used at creation if requested by the diagnostic flag PauseAtStartup.
828  // Causes the VM to wait until an external stimulus has been applied
829  // (for Unix, that stimulus is a signal, for Windows, an external
830  // ResumeThread call)
831  static void pause();
832
833  // Builds a platform dependent Agent_OnLoad_<libname> function name
834  // which is used to find statically linked in agents.
835  static char*  build_agent_function_name(const char *sym, const char *cname,
836                                          bool is_absolute_path);
837
838  class SuspendedThreadTaskContext {
839  public:
840    SuspendedThreadTaskContext(Thread* thread, void *ucontext) : _thread(thread), _ucontext(ucontext) {}
841    Thread* thread() const { return _thread; }
842    void* ucontext() const { return _ucontext; }
843  private:
844    Thread* _thread;
845    void* _ucontext;
846  };
847
848  class SuspendedThreadTask {
849  public:
850    SuspendedThreadTask(Thread* thread) : _thread(thread), _done(false) {}
851    virtual ~SuspendedThreadTask() {}
852    void run();
853    bool is_done() { return _done; }
854    virtual void do_task(const SuspendedThreadTaskContext& context) = 0;
855  protected:
856  private:
857    void internal_do_task();
858    Thread* _thread;
859    bool _done;
860  };
861
862#ifndef TARGET_OS_FAMILY_windows
863  // Suspend/resume support
864  // Protocol:
865  //
866  // a thread starts in SR_RUNNING
867  //
868  // SR_RUNNING can go to
869  //   * SR_SUSPEND_REQUEST when the WatcherThread wants to suspend it
870  // SR_SUSPEND_REQUEST can go to
871  //   * SR_RUNNING if WatcherThread decides it waited for SR_SUSPENDED too long (timeout)
872  //   * SR_SUSPENDED if the stopped thread receives the signal and switches state
873  // SR_SUSPENDED can go to
874  //   * SR_WAKEUP_REQUEST when the WatcherThread has done the work and wants to resume
875  // SR_WAKEUP_REQUEST can go to
876  //   * SR_RUNNING when the stopped thread receives the signal
877  //   * SR_WAKEUP_REQUEST on timeout (resend the signal and try again)
878  class SuspendResume {
879   public:
880    enum State {
881      SR_RUNNING,
882      SR_SUSPEND_REQUEST,
883      SR_SUSPENDED,
884      SR_WAKEUP_REQUEST
885    };
886
887  private:
888    volatile State _state;
889
890  private:
891    /* try to switch state from state "from" to state "to"
892     * returns the state set after the method is complete
893     */
894    State switch_state(State from, State to);
895
896  public:
897    SuspendResume() : _state(SR_RUNNING) { }
898
899    State state() const { return _state; }
900
901    State request_suspend() {
902      return switch_state(SR_RUNNING, SR_SUSPEND_REQUEST);
903    }
904
905    State cancel_suspend() {
906      return switch_state(SR_SUSPEND_REQUEST, SR_RUNNING);
907    }
908
909    State suspended() {
910      return switch_state(SR_SUSPEND_REQUEST, SR_SUSPENDED);
911    }
912
913    State request_wakeup() {
914      return switch_state(SR_SUSPENDED, SR_WAKEUP_REQUEST);
915    }
916
917    State running() {
918      return switch_state(SR_WAKEUP_REQUEST, SR_RUNNING);
919    }
920
921    bool is_running() const {
922      return _state == SR_RUNNING;
923    }
924
925    bool is_suspend_request() const {
926      return _state == SR_SUSPEND_REQUEST;
927    }
928
929    bool is_suspended() const {
930      return _state == SR_SUSPENDED;
931    }
932  };
933#endif
934
935
936 protected:
937  static long _rand_seed;                   // seed for random number generator
938  static int _processor_count;              // number of processors
939
940  static char* format_boot_path(const char* format_string,
941                                const char* home,
942                                int home_len,
943                                char fileSep,
944                                char pathSep);
945  static bool set_boot_path(char fileSep, char pathSep);
946  static char** split_path(const char* path, int* n);
947
948};
949
950// Note that "PAUSE" is almost always used with synchronization
951// so arguably we should provide Atomic::SpinPause() instead
952// of the global SpinPause() with C linkage.
953// It'd also be eligible for inlining on many platforms.
954
955extern "C" int SpinPause();
956
957#endif // SHARE_VM_RUNTIME_OS_HPP
958