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