os_posix.cpp revision 5966:e2722a66aba7
1/*
2* Copyright (c) 1999, 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#include "utilities/globalDefinitions.hpp"
26#include "prims/jvm.h"
27#include "runtime/frame.inline.hpp"
28#include "runtime/os.hpp"
29#include "utilities/vmError.hpp"
30
31#include <signal.h>
32#include <unistd.h>
33#include <sys/resource.h>
34#include <sys/utsname.h>
35
36// Todo: provide a os::get_max_process_id() or similar. Number of processes
37// may have been configured, can be read more accurately from proc fs etc.
38#ifndef MAX_PID
39#define MAX_PID INT_MAX
40#endif
41#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
42
43// Check core dump limit and report possible place where core can be found
44void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* buffer, size_t bufferSize) {
45  int n;
46  struct rlimit rlim;
47  bool success;
48
49  n = get_core_path(buffer, bufferSize);
50
51  if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
52    jio_snprintf(buffer + n, bufferSize - n, "/core or core.%d (may not exist)", current_process_id());
53    success = true;
54  } else {
55    switch(rlim.rlim_cur) {
56      case RLIM_INFINITY:
57        jio_snprintf(buffer + n, bufferSize - n, "/core or core.%d", current_process_id());
58        success = true;
59        break;
60      case 0:
61        jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
62        success = false;
63        break;
64      default:
65        jio_snprintf(buffer + n, bufferSize - n, "/core or core.%d (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", current_process_id(), (unsigned long)(rlim.rlim_cur >> 10));
66        success = true;
67        break;
68    }
69  }
70  VMError::report_coredump_status(buffer, success);
71}
72
73address os::get_caller_pc(int n) {
74#ifdef _NMT_NOINLINE_
75  n ++;
76#endif
77  frame fr = os::current_frame();
78  while (n > 0 && fr.pc() &&
79    !os::is_first_C_frame(&fr) && fr.sender_pc()) {
80    fr = os::get_sender_for_C_frame(&fr);
81    n --;
82  }
83  if (n == 0) {
84    return fr.pc();
85  } else {
86    return NULL;
87  }
88}
89
90int os::get_last_error() {
91  return errno;
92}
93
94bool os::is_debugger_attached() {
95  // not implemented
96  return false;
97}
98
99void os::wait_for_keypress_at_exit(void) {
100  // don't do anything on posix platforms
101  return;
102}
103
104// Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
105// so on posix, unmap the section at the start and at the end of the chunk that we mapped
106// rather than unmapping and remapping the whole chunk to get requested alignment.
107char* os::reserve_memory_aligned(size_t size, size_t alignment) {
108  assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
109      "Alignment must be a multiple of allocation granularity (page size)");
110  assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
111
112  size_t extra_size = size + alignment;
113  assert(extra_size >= size, "overflow, size is too large to allow alignment");
114
115  char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
116
117  if (extra_base == NULL) {
118    return NULL;
119  }
120
121  // Do manual alignment
122  char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
123
124  // [  |                                       |  ]
125  // ^ extra_base
126  //    ^ extra_base + begin_offset == aligned_base
127  //     extra_base + begin_offset + size       ^
128  //                       extra_base + extra_size ^
129  // |<>| == begin_offset
130  //                              end_offset == |<>|
131  size_t begin_offset = aligned_base - extra_base;
132  size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
133
134  if (begin_offset > 0) {
135      os::release_memory(extra_base, begin_offset);
136  }
137
138  if (end_offset > 0) {
139      os::release_memory(extra_base + begin_offset + size, end_offset);
140  }
141
142  return aligned_base;
143}
144
145void os::Posix::print_load_average(outputStream* st) {
146  st->print("load average:");
147  double loadavg[3];
148  os::loadavg(loadavg, 3);
149  st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
150  st->cr();
151}
152
153void os::Posix::print_rlimit_info(outputStream* st) {
154  st->print("rlimit:");
155  struct rlimit rlim;
156
157  st->print(" STACK ");
158  getrlimit(RLIMIT_STACK, &rlim);
159  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
160  else st->print("%uk", rlim.rlim_cur >> 10);
161
162  st->print(", CORE ");
163  getrlimit(RLIMIT_CORE, &rlim);
164  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
165  else st->print("%uk", rlim.rlim_cur >> 10);
166
167  // Isn't there on solaris
168#if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix)
169  st->print(", NPROC ");
170  getrlimit(RLIMIT_NPROC, &rlim);
171  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
172  else st->print("%d", rlim.rlim_cur);
173#endif
174
175  st->print(", NOFILE ");
176  getrlimit(RLIMIT_NOFILE, &rlim);
177  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
178  else st->print("%d", rlim.rlim_cur);
179
180  st->print(", AS ");
181  getrlimit(RLIMIT_AS, &rlim);
182  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
183  else st->print("%uk", rlim.rlim_cur >> 10);
184  st->cr();
185}
186
187void os::Posix::print_uname_info(outputStream* st) {
188  // kernel
189  st->print("uname:");
190  struct utsname name;
191  uname(&name);
192  st->print(name.sysname); st->print(" ");
193  st->print(name.release); st->print(" ");
194  st->print(name.version); st->print(" ");
195  st->print(name.machine);
196  st->cr();
197}
198
199bool os::has_allocatable_memory_limit(julong* limit) {
200  struct rlimit rlim;
201  int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
202  // if there was an error when calling getrlimit, assume that there is no limitation
203  // on virtual memory.
204  bool result;
205  if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
206    result = false;
207  } else {
208    *limit = (julong)rlim.rlim_cur;
209    result = true;
210  }
211#ifdef _LP64
212  return result;
213#else
214  // arbitrary virtual space limit for 32 bit Unices found by testing. If
215  // getrlimit above returned a limit, bound it with this limit. Otherwise
216  // directly use it.
217  const julong max_virtual_limit = (julong)3800*M;
218  if (result) {
219    *limit = MIN2(*limit, max_virtual_limit);
220  } else {
221    *limit = max_virtual_limit;
222  }
223
224  // bound by actually allocatable memory. The algorithm uses two bounds, an
225  // upper and a lower limit. The upper limit is the current highest amount of
226  // memory that could not be allocated, the lower limit is the current highest
227  // amount of memory that could be allocated.
228  // The algorithm iteratively refines the result by halving the difference
229  // between these limits, updating either the upper limit (if that value could
230  // not be allocated) or the lower limit (if the that value could be allocated)
231  // until the difference between these limits is "small".
232
233  // the minimum amount of memory we care about allocating.
234  const julong min_allocation_size = M;
235
236  julong upper_limit = *limit;
237
238  // first check a few trivial cases
239  if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
240    *limit = upper_limit;
241  } else if (!is_allocatable(min_allocation_size)) {
242    // we found that not even min_allocation_size is allocatable. Return it
243    // anyway. There is no point to search for a better value any more.
244    *limit = min_allocation_size;
245  } else {
246    // perform the binary search.
247    julong lower_limit = min_allocation_size;
248    while ((upper_limit - lower_limit) > min_allocation_size) {
249      julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
250      temp_limit = align_size_down_(temp_limit, min_allocation_size);
251      if (is_allocatable(temp_limit)) {
252        lower_limit = temp_limit;
253      } else {
254        upper_limit = temp_limit;
255      }
256    }
257    *limit = lower_limit;
258  }
259  return true;
260#endif
261}
262
263const char* os::get_current_directory(char *buf, size_t buflen) {
264  return getcwd(buf, buflen);
265}
266
267FILE* os::open(int fd, const char* mode) {
268  return ::fdopen(fd, mode);
269}
270
271void* os::get_default_process_handle() {
272  return (void*)::dlopen(NULL, RTLD_LAZY);
273}
274
275// Builds a platform dependent Agent_OnLoad_<lib_name> function name
276// which is used to find statically linked in agents.
277// Parameters:
278//            sym_name: Symbol in library we are looking for
279//            lib_name: Name of library to look in, NULL for shared libs.
280//            is_absolute_path == true if lib_name is absolute path to agent
281//                                     such as "/a/b/libL.so"
282//            == false if only the base name of the library is passed in
283//               such as "L"
284char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
285                                    bool is_absolute_path) {
286  char *agent_entry_name;
287  size_t len;
288  size_t name_len;
289  size_t prefix_len = strlen(JNI_LIB_PREFIX);
290  size_t suffix_len = strlen(JNI_LIB_SUFFIX);
291  const char *start;
292
293  if (lib_name != NULL) {
294    len = name_len = strlen(lib_name);
295    if (is_absolute_path) {
296      // Need to strip path, prefix and suffix
297      if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
298        lib_name = ++start;
299      }
300      if (len <= (prefix_len + suffix_len)) {
301        return NULL;
302      }
303      lib_name += prefix_len;
304      name_len = strlen(lib_name) - suffix_len;
305    }
306  }
307  len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
308  agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
309  if (agent_entry_name == NULL) {
310    return NULL;
311  }
312  strcpy(agent_entry_name, sym_name);
313  if (lib_name != NULL) {
314    strcat(agent_entry_name, "_");
315    strncat(agent_entry_name, lib_name, name_len);
316  }
317  return agent_entry_name;
318}
319
320// Returned string is a constant. For unknown signals "UNKNOWN" is returned.
321const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
322
323  static const struct {
324    int sig; const char* name;
325  }
326  info[] =
327  {
328    {  SIGABRT,     "SIGABRT" },
329#ifdef SIGAIO
330    {  SIGAIO,      "SIGAIO" },
331#endif
332    {  SIGALRM,     "SIGALRM" },
333#ifdef SIGALRM1
334    {  SIGALRM1,    "SIGALRM1" },
335#endif
336    {  SIGBUS,      "SIGBUS" },
337#ifdef SIGCANCEL
338    {  SIGCANCEL,   "SIGCANCEL" },
339#endif
340    {  SIGCHLD,     "SIGCHLD" },
341#ifdef SIGCLD
342    {  SIGCLD,      "SIGCLD" },
343#endif
344    {  SIGCONT,     "SIGCONT" },
345#ifdef SIGCPUFAIL
346    {  SIGCPUFAIL,  "SIGCPUFAIL" },
347#endif
348#ifdef SIGDANGER
349    {  SIGDANGER,   "SIGDANGER" },
350#endif
351#ifdef SIGDIL
352    {  SIGDIL,      "SIGDIL" },
353#endif
354#ifdef SIGEMT
355    {  SIGEMT,      "SIGEMT" },
356#endif
357    {  SIGFPE,      "SIGFPE" },
358#ifdef SIGFREEZE
359    {  SIGFREEZE,   "SIGFREEZE" },
360#endif
361#ifdef SIGGFAULT
362    {  SIGGFAULT,   "SIGGFAULT" },
363#endif
364#ifdef SIGGRANT
365    {  SIGGRANT,    "SIGGRANT" },
366#endif
367    {  SIGHUP,      "SIGHUP" },
368    {  SIGILL,      "SIGILL" },
369    {  SIGINT,      "SIGINT" },
370#ifdef SIGIO
371    {  SIGIO,       "SIGIO" },
372#endif
373#ifdef SIGIOINT
374    {  SIGIOINT,    "SIGIOINT" },
375#endif
376#ifdef SIGIOT
377  // SIGIOT is there for BSD compatibility, but on most Unices just a
378  // synonym for SIGABRT. The result should be "SIGABRT", not
379  // "SIGIOT".
380  #if (SIGIOT != SIGABRT )
381    {  SIGIOT,      "SIGIOT" },
382  #endif
383#endif
384#ifdef SIGKAP
385    {  SIGKAP,      "SIGKAP" },
386#endif
387    {  SIGKILL,     "SIGKILL" },
388#ifdef SIGLOST
389    {  SIGLOST,     "SIGLOST" },
390#endif
391#ifdef SIGLWP
392    {  SIGLWP,      "SIGLWP" },
393#endif
394#ifdef SIGLWPTIMER
395    {  SIGLWPTIMER, "SIGLWPTIMER" },
396#endif
397#ifdef SIGMIGRATE
398    {  SIGMIGRATE,  "SIGMIGRATE" },
399#endif
400#ifdef SIGMSG
401    {  SIGMSG,      "SIGMSG" },
402#endif
403    {  SIGPIPE,     "SIGPIPE" },
404#ifdef SIGPOLL
405    {  SIGPOLL,     "SIGPOLL" },
406#endif
407#ifdef SIGPRE
408    {  SIGPRE,      "SIGPRE" },
409#endif
410    {  SIGPROF,     "SIGPROF" },
411#ifdef SIGPTY
412    {  SIGPTY,      "SIGPTY" },
413#endif
414#ifdef SIGPWR
415    {  SIGPWR,      "SIGPWR" },
416#endif
417    {  SIGQUIT,     "SIGQUIT" },
418#ifdef SIGRECONFIG
419    {  SIGRECONFIG, "SIGRECONFIG" },
420#endif
421#ifdef SIGRECOVERY
422    {  SIGRECOVERY, "SIGRECOVERY" },
423#endif
424#ifdef SIGRESERVE
425    {  SIGRESERVE,  "SIGRESERVE" },
426#endif
427#ifdef SIGRETRACT
428    {  SIGRETRACT,  "SIGRETRACT" },
429#endif
430#ifdef SIGSAK
431    {  SIGSAK,      "SIGSAK" },
432#endif
433    {  SIGSEGV,     "SIGSEGV" },
434#ifdef SIGSOUND
435    {  SIGSOUND,    "SIGSOUND" },
436#endif
437    {  SIGSTOP,     "SIGSTOP" },
438    {  SIGSYS,      "SIGSYS" },
439#ifdef SIGSYSERROR
440    {  SIGSYSERROR, "SIGSYSERROR" },
441#endif
442#ifdef SIGTALRM
443    {  SIGTALRM,    "SIGTALRM" },
444#endif
445    {  SIGTERM,     "SIGTERM" },
446#ifdef SIGTHAW
447    {  SIGTHAW,     "SIGTHAW" },
448#endif
449    {  SIGTRAP,     "SIGTRAP" },
450#ifdef SIGTSTP
451    {  SIGTSTP,     "SIGTSTP" },
452#endif
453    {  SIGTTIN,     "SIGTTIN" },
454    {  SIGTTOU,     "SIGTTOU" },
455#ifdef SIGURG
456    {  SIGURG,      "SIGURG" },
457#endif
458    {  SIGUSR1,     "SIGUSR1" },
459    {  SIGUSR2,     "SIGUSR2" },
460#ifdef SIGVIRT
461    {  SIGVIRT,     "SIGVIRT" },
462#endif
463    {  SIGVTALRM,   "SIGVTALRM" },
464#ifdef SIGWAITING
465    {  SIGWAITING,  "SIGWAITING" },
466#endif
467#ifdef SIGWINCH
468    {  SIGWINCH,    "SIGWINCH" },
469#endif
470#ifdef SIGWINDOW
471    {  SIGWINDOW,   "SIGWINDOW" },
472#endif
473    {  SIGXCPU,     "SIGXCPU" },
474    {  SIGXFSZ,     "SIGXFSZ" },
475#ifdef SIGXRES
476    {  SIGXRES,     "SIGXRES" },
477#endif
478    { -1, NULL }
479  };
480
481  const char* ret = NULL;
482
483#ifdef SIGRTMIN
484  if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
485    if (sig == SIGRTMIN) {
486      ret = "SIGRTMIN";
487    } else if (sig == SIGRTMAX) {
488      ret = "SIGRTMAX";
489    } else {
490      jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
491      return out;
492    }
493  }
494#endif
495
496  if (sig > 0) {
497    for (int idx = 0; info[idx].sig != -1; idx ++) {
498      if (info[idx].sig == sig) {
499        ret = info[idx].name;
500        break;
501      }
502    }
503  }
504
505  if (!ret) {
506    if (!is_valid_signal(sig)) {
507      ret = "INVALID";
508    } else {
509      ret = "UNKNOWN";
510    }
511  }
512
513  jio_snprintf(out, outlen, ret);
514  return out;
515}
516
517// Returns true if signal number is valid.
518bool os::Posix::is_valid_signal(int sig) {
519  // MacOS not really POSIX compliant: sigaddset does not return
520  // an error for invalid signal numbers. However, MacOS does not
521  // support real time signals and simply seems to have just 33
522  // signals with no holes in the signal range.
523#ifdef __APPLE__
524  return sig >= 1 && sig < NSIG;
525#else
526  // Use sigaddset to check for signal validity.
527  sigset_t set;
528  if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
529    return false;
530  }
531  return true;
532#endif
533}
534
535#define NUM_IMPORTANT_SIGS 32
536// Returns one-line short description of a signal set in a user provided buffer.
537const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
538  assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
539  // Note: for shortness, just print out the first 32. That should
540  // cover most of the useful ones, apart from realtime signals.
541  for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
542    const int rc = sigismember(set, sig);
543    if (rc == -1 && errno == EINVAL) {
544      buffer[sig-1] = '?';
545    } else {
546      buffer[sig-1] = rc == 0 ? '0' : '1';
547    }
548  }
549  buffer[NUM_IMPORTANT_SIGS] = 0;
550  return buffer;
551}
552
553// Prints one-line description of a signal set.
554void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
555  char buf[NUM_IMPORTANT_SIGS + 1];
556  os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
557  st->print(buf);
558}
559
560// Writes one-line description of a combination of sigaction.sa_flags into a user
561// provided buffer. Returns that buffer.
562const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
563  char* p = buffer;
564  size_t remaining = size;
565  bool first = true;
566  int idx = 0;
567
568  assert(buffer, "invalid argument");
569
570  if (size == 0) {
571    return buffer;
572  }
573
574  strncpy(buffer, "none", size);
575
576  const struct {
577    int i;
578    const char* s;
579  } flaginfo [] = {
580    { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
581    { SA_ONSTACK,   "SA_ONSTACK"   },
582    { SA_RESETHAND, "SA_RESETHAND" },
583    { SA_RESTART,   "SA_RESTART"   },
584    { SA_SIGINFO,   "SA_SIGINFO"   },
585    { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
586    { SA_NODEFER,   "SA_NODEFER"   },
587#ifdef AIX
588    { SA_ONSTACK,   "SA_ONSTACK"   },
589    { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
590#endif
591    { 0, NULL }
592  };
593
594  for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
595    if (flags & flaginfo[idx].i) {
596      if (first) {
597        jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
598        first = false;
599      } else {
600        jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
601      }
602      const size_t len = strlen(p);
603      p += len;
604      remaining -= len;
605    }
606  }
607
608  buffer[size - 1] = '\0';
609
610  return buffer;
611}
612
613// Prints one-line description of a combination of sigaction.sa_flags.
614void os::Posix::print_sa_flags(outputStream* st, int flags) {
615  char buffer[0x100];
616  os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
617  st->print(buffer);
618}
619
620// Helper function for os::Posix::print_siginfo_...():
621// return a textual description for signal code.
622struct enum_sigcode_desc_t {
623  const char* s_name;
624  const char* s_desc;
625};
626
627static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
628
629  const struct {
630    int sig; int code; const char* s_code; const char* s_desc;
631  } t1 [] = {
632    { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
633    { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
634    { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
635    { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
636    { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
637    { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
638    { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
639    { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
640#if defined(IA64) && defined(LINUX)
641    { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
642    { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
643#endif
644    { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
645    { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
646    { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
647    { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
648    { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
649    { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
650    { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
651    { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
652    { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
653    { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
654#ifdef AIX
655    // no explanation found what keyerr would be
656    { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
657#endif
658#if defined(IA64) && !defined(AIX)
659    { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
660#endif
661    { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
662    { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
663    { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
664    { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
665    { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
666    { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
667    { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
668    { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
669    { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
670    { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
671    { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
672#ifdef SIGPOLL
673    { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
674    { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
675    { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
676    { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
677    { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
678#endif
679    { -1, -1, NULL, NULL }
680  };
681
682  // Codes valid in any signal context.
683  const struct {
684    int code; const char* s_code; const char* s_desc;
685  } t2 [] = {
686    { SI_USER,      "SI_USER",     "Signal sent by kill()." },
687    { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
688    { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
689    { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
690    { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
691    // Linux specific
692#ifdef SI_TKILL
693    { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
694#endif
695#ifdef SI_DETHREAD
696    { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
697#endif
698#ifdef SI_KERNEL
699    { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
700#endif
701#ifdef SI_SIGIO
702    { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
703#endif
704
705#ifdef AIX
706    { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
707    { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
708#endif
709
710#ifdef __sun
711    { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
712    { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
713    { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
714#endif
715
716    { -1, NULL, NULL }
717  };
718
719  const char* s_code = NULL;
720  const char* s_desc = NULL;
721
722  for (int i = 0; t1[i].sig != -1; i ++) {
723    if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
724      s_code = t1[i].s_code;
725      s_desc = t1[i].s_desc;
726      break;
727    }
728  }
729
730  if (s_code == NULL) {
731    for (int i = 0; t2[i].s_code != NULL; i ++) {
732      if (t2[i].code == si->si_code) {
733        s_code = t2[i].s_code;
734        s_desc = t2[i].s_desc;
735      }
736    }
737  }
738
739  if (s_code == NULL) {
740    out->s_name = "unknown";
741    out->s_desc = "unknown";
742    return false;
743  }
744
745  out->s_name = s_code;
746  out->s_desc = s_desc;
747
748  return true;
749}
750
751// A POSIX conform, platform-independend siginfo print routine.
752// Short print out on one line.
753void os::Posix::print_siginfo_brief(outputStream* os, const siginfo_t* si) {
754  char buf[20];
755  os->print("siginfo: ");
756
757  if (!si) {
758    os->print("<null>");
759    return;
760  }
761
762  // See print_siginfo_full() for details.
763  const int sig = si->si_signo;
764
765  os->print("si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
766
767  enum_sigcode_desc_t ed;
768  if (get_signal_code_description(si, &ed)) {
769    os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
770  } else {
771    os->print(", si_code: %d (unknown)", si->si_code);
772  }
773
774  if (si->si_errno) {
775    os->print(", si_errno: %d", si->si_errno);
776  }
777
778  const int me = (int) ::getpid();
779  const int pid = (int) si->si_pid;
780
781  if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
782    if (IS_VALID_PID(pid) && pid != me) {
783      os->print(", sent from pid: %d (uid: %d)", pid, (int) si->si_uid);
784    }
785  } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
786             sig == SIGTRAP || sig == SIGFPE) {
787    os->print(", si_addr: " PTR_FORMAT, si->si_addr);
788#ifdef SIGPOLL
789  } else if (sig == SIGPOLL) {
790    os->print(", si_band: " PTR64_FORMAT, (uint64_t)si->si_band);
791#endif
792  } else if (sig == SIGCHLD) {
793    os->print_cr(", si_pid: %d, si_uid: %d, si_status: %d", (int) si->si_pid, si->si_uid, si->si_status);
794  }
795}
796
797os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
798  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
799}
800
801/*
802 * See the caveats for this class in os_posix.hpp
803 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
804 * method and returns false. If none of the signals are raised, returns true.
805 * The callback is supposed to provide the method that should be protected.
806 */
807bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
808  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
809  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
810      "crash_protection already set?");
811
812  if (sigsetjmp(_jmpbuf, 1) == 0) {
813    // make sure we can see in the signal handler that we have crash protection
814    // installed
815    WatcherThread::watcher_thread()->set_crash_protection(this);
816    cb.call();
817    // and clear the crash protection
818    WatcherThread::watcher_thread()->set_crash_protection(NULL);
819    return true;
820  }
821  // this happens when we siglongjmp() back
822  WatcherThread::watcher_thread()->set_crash_protection(NULL);
823  return false;
824}
825
826void os::WatcherThreadCrashProtection::restore() {
827  assert(WatcherThread::watcher_thread()->has_crash_protection(),
828      "must have crash protection");
829
830  siglongjmp(_jmpbuf, 1);
831}
832
833void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
834    Thread* thread) {
835
836  if (thread != NULL &&
837      thread->is_Watcher_thread() &&
838      WatcherThread::watcher_thread()->has_crash_protection()) {
839
840    if (sig == SIGSEGV || sig == SIGBUS) {
841      WatcherThread::watcher_thread()->crash_protection()->restore();
842    }
843  }
844}
845