os_posix.cpp revision 11658:8a5735c11a84
1/*
2 * Copyright (c) 1999, 2016, 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 "semaphore_posix.hpp"
28#include "runtime/frame.inline.hpp"
29#include "runtime/interfaceSupport.hpp"
30#include "runtime/os.hpp"
31#include "utilities/macros.hpp"
32#include "utilities/vmError.hpp"
33
34#include <signal.h>
35#include <unistd.h>
36#include <sys/resource.h>
37#include <sys/utsname.h>
38#include <pthread.h>
39#include <semaphore.h>
40#include <signal.h>
41
42// Todo: provide a os::get_max_process_id() or similar. Number of processes
43// may have been configured, can be read more accurately from proc fs etc.
44#ifndef MAX_PID
45#define MAX_PID INT_MAX
46#endif
47#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
48
49// Check core dump limit and report possible place where core can be found
50void os::check_dump_limit(char* buffer, size_t bufferSize) {
51  if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
52    jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
53    VMError::record_coredump_status(buffer, false);
54    return;
55  }
56
57  int n;
58  struct rlimit rlim;
59  bool success;
60
61  char core_path[PATH_MAX];
62  n = get_core_path(core_path, PATH_MAX);
63
64  if (n <= 0) {
65    jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
66    success = true;
67#ifdef LINUX
68  } else if (core_path[0] == '"') { // redirect to user process
69    jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
70    success = true;
71#endif
72  } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
73    jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
74    success = true;
75  } else {
76    switch(rlim.rlim_cur) {
77      case RLIM_INFINITY:
78        jio_snprintf(buffer, bufferSize, "%s", core_path);
79        success = true;
80        break;
81      case 0:
82        jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
83        success = false;
84        break;
85      default:
86        jio_snprintf(buffer, bufferSize, "%s (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, (unsigned long)(rlim.rlim_cur >> 10));
87        success = true;
88        break;
89    }
90  }
91
92  VMError::record_coredump_status(buffer, success);
93}
94
95int os::get_native_stack(address* stack, int frames, int toSkip) {
96#ifdef _NMT_NOINLINE_
97  toSkip++;
98#endif
99
100  int frame_idx = 0;
101  int num_of_frames;  // number of frames captured
102  frame fr = os::current_frame();
103  while (fr.pc() && frame_idx < frames) {
104    if (toSkip > 0) {
105      toSkip --;
106    } else {
107      stack[frame_idx ++] = fr.pc();
108    }
109    if (fr.fp() == NULL || fr.cb() != NULL ||
110        fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
111
112    if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
113      fr = os::get_sender_for_C_frame(&fr);
114    } else {
115      break;
116    }
117  }
118  num_of_frames = frame_idx;
119  for (; frame_idx < frames; frame_idx ++) {
120    stack[frame_idx] = NULL;
121  }
122
123  return num_of_frames;
124}
125
126
127bool os::unsetenv(const char* name) {
128  assert(name != NULL, "Null pointer");
129  return (::unsetenv(name) == 0);
130}
131
132int os::get_last_error() {
133  return errno;
134}
135
136bool os::is_debugger_attached() {
137  // not implemented
138  return false;
139}
140
141void os::wait_for_keypress_at_exit(void) {
142  // don't do anything on posix platforms
143  return;
144}
145
146// Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
147// so on posix, unmap the section at the start and at the end of the chunk that we mapped
148// rather than unmapping and remapping the whole chunk to get requested alignment.
149char* os::reserve_memory_aligned(size_t size, size_t alignment) {
150  assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
151      "Alignment must be a multiple of allocation granularity (page size)");
152  assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
153
154  size_t extra_size = size + alignment;
155  assert(extra_size >= size, "overflow, size is too large to allow alignment");
156
157  char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
158
159  if (extra_base == NULL) {
160    return NULL;
161  }
162
163  // Do manual alignment
164  char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
165
166  // [  |                                       |  ]
167  // ^ extra_base
168  //    ^ extra_base + begin_offset == aligned_base
169  //     extra_base + begin_offset + size       ^
170  //                       extra_base + extra_size ^
171  // |<>| == begin_offset
172  //                              end_offset == |<>|
173  size_t begin_offset = aligned_base - extra_base;
174  size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
175
176  if (begin_offset > 0) {
177      os::release_memory(extra_base, begin_offset);
178  }
179
180  if (end_offset > 0) {
181      os::release_memory(extra_base + begin_offset + size, end_offset);
182  }
183
184  return aligned_base;
185}
186
187int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
188    return vsnprintf(buf, len, fmt, args);
189}
190
191int os::get_fileno(FILE* fp) {
192  return NOT_AIX(::)fileno(fp);
193}
194
195void os::Posix::print_load_average(outputStream* st) {
196  st->print("load average:");
197  double loadavg[3];
198  os::loadavg(loadavg, 3);
199  st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
200  st->cr();
201}
202
203void os::Posix::print_rlimit_info(outputStream* st) {
204  st->print("rlimit:");
205  struct rlimit rlim;
206
207  st->print(" STACK ");
208  getrlimit(RLIMIT_STACK, &rlim);
209  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
210  else st->print("%luk", rlim.rlim_cur >> 10);
211
212  st->print(", CORE ");
213  getrlimit(RLIMIT_CORE, &rlim);
214  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
215  else st->print("%luk", rlim.rlim_cur >> 10);
216
217  // Isn't there on solaris
218#if !defined(SOLARIS) && !defined(AIX)
219  st->print(", NPROC ");
220  getrlimit(RLIMIT_NPROC, &rlim);
221  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
222  else st->print("%lu", rlim.rlim_cur);
223#endif
224
225  st->print(", NOFILE ");
226  getrlimit(RLIMIT_NOFILE, &rlim);
227  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
228  else st->print("%lu", rlim.rlim_cur);
229
230  st->print(", AS ");
231  getrlimit(RLIMIT_AS, &rlim);
232  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
233  else st->print("%luk", rlim.rlim_cur >> 10);
234  st->cr();
235}
236
237void os::Posix::print_uname_info(outputStream* st) {
238  // kernel
239  st->print("uname:");
240  struct utsname name;
241  uname(&name);
242  st->print("%s ", name.sysname);
243#ifdef ASSERT
244  st->print("%s ", name.nodename);
245#endif
246  st->print("%s ", name.release);
247  st->print("%s ", name.version);
248  st->print("%s", name.machine);
249  st->cr();
250}
251
252bool os::get_host_name(char* buf, size_t buflen) {
253  struct utsname name;
254  uname(&name);
255  jio_snprintf(buf, buflen, "%s", name.nodename);
256  return true;
257}
258
259bool os::has_allocatable_memory_limit(julong* limit) {
260  struct rlimit rlim;
261  int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
262  // if there was an error when calling getrlimit, assume that there is no limitation
263  // on virtual memory.
264  bool result;
265  if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
266    result = false;
267  } else {
268    *limit = (julong)rlim.rlim_cur;
269    result = true;
270  }
271#ifdef _LP64
272  return result;
273#else
274  // arbitrary virtual space limit for 32 bit Unices found by testing. If
275  // getrlimit above returned a limit, bound it with this limit. Otherwise
276  // directly use it.
277  const julong max_virtual_limit = (julong)3800*M;
278  if (result) {
279    *limit = MIN2(*limit, max_virtual_limit);
280  } else {
281    *limit = max_virtual_limit;
282  }
283
284  // bound by actually allocatable memory. The algorithm uses two bounds, an
285  // upper and a lower limit. The upper limit is the current highest amount of
286  // memory that could not be allocated, the lower limit is the current highest
287  // amount of memory that could be allocated.
288  // The algorithm iteratively refines the result by halving the difference
289  // between these limits, updating either the upper limit (if that value could
290  // not be allocated) or the lower limit (if the that value could be allocated)
291  // until the difference between these limits is "small".
292
293  // the minimum amount of memory we care about allocating.
294  const julong min_allocation_size = M;
295
296  julong upper_limit = *limit;
297
298  // first check a few trivial cases
299  if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
300    *limit = upper_limit;
301  } else if (!is_allocatable(min_allocation_size)) {
302    // we found that not even min_allocation_size is allocatable. Return it
303    // anyway. There is no point to search for a better value any more.
304    *limit = min_allocation_size;
305  } else {
306    // perform the binary search.
307    julong lower_limit = min_allocation_size;
308    while ((upper_limit - lower_limit) > min_allocation_size) {
309      julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
310      temp_limit = align_size_down_(temp_limit, min_allocation_size);
311      if (is_allocatable(temp_limit)) {
312        lower_limit = temp_limit;
313      } else {
314        upper_limit = temp_limit;
315      }
316    }
317    *limit = lower_limit;
318  }
319  return true;
320#endif
321}
322
323const char* os::get_current_directory(char *buf, size_t buflen) {
324  return getcwd(buf, buflen);
325}
326
327FILE* os::open(int fd, const char* mode) {
328  return ::fdopen(fd, mode);
329}
330
331void os::flockfile(FILE* fp) {
332  ::flockfile(fp);
333}
334
335void os::funlockfile(FILE* fp) {
336  ::funlockfile(fp);
337}
338
339// Builds a platform dependent Agent_OnLoad_<lib_name> function name
340// which is used to find statically linked in agents.
341// Parameters:
342//            sym_name: Symbol in library we are looking for
343//            lib_name: Name of library to look in, NULL for shared libs.
344//            is_absolute_path == true if lib_name is absolute path to agent
345//                                     such as "/a/b/libL.so"
346//            == false if only the base name of the library is passed in
347//               such as "L"
348char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
349                                    bool is_absolute_path) {
350  char *agent_entry_name;
351  size_t len;
352  size_t name_len;
353  size_t prefix_len = strlen(JNI_LIB_PREFIX);
354  size_t suffix_len = strlen(JNI_LIB_SUFFIX);
355  const char *start;
356
357  if (lib_name != NULL) {
358    name_len = strlen(lib_name);
359    if (is_absolute_path) {
360      // Need to strip path, prefix and suffix
361      if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
362        lib_name = ++start;
363      }
364      if (strlen(lib_name) <= (prefix_len + suffix_len)) {
365        return NULL;
366      }
367      lib_name += prefix_len;
368      name_len = strlen(lib_name) - suffix_len;
369    }
370  }
371  len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
372  agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
373  if (agent_entry_name == NULL) {
374    return NULL;
375  }
376  strcpy(agent_entry_name, sym_name);
377  if (lib_name != NULL) {
378    strcat(agent_entry_name, "_");
379    strncat(agent_entry_name, lib_name, name_len);
380  }
381  return agent_entry_name;
382}
383
384int os::sleep(Thread* thread, jlong millis, bool interruptible) {
385  assert(thread == Thread::current(),  "thread consistency check");
386
387  ParkEvent * const slp = thread->_SleepEvent ;
388  slp->reset() ;
389  OrderAccess::fence() ;
390
391  if (interruptible) {
392    jlong prevtime = javaTimeNanos();
393
394    for (;;) {
395      if (os::is_interrupted(thread, true)) {
396        return OS_INTRPT;
397      }
398
399      jlong newtime = javaTimeNanos();
400
401      if (newtime - prevtime < 0) {
402        // time moving backwards, should only happen if no monotonic clock
403        // not a guarantee() because JVM should not abort on kernel/glibc bugs
404        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
405      } else {
406        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
407      }
408
409      if (millis <= 0) {
410        return OS_OK;
411      }
412
413      prevtime = newtime;
414
415      {
416        assert(thread->is_Java_thread(), "sanity check");
417        JavaThread *jt = (JavaThread *) thread;
418        ThreadBlockInVM tbivm(jt);
419        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
420
421        jt->set_suspend_equivalent();
422        // cleared by handle_special_suspend_equivalent_condition() or
423        // java_suspend_self() via check_and_wait_while_suspended()
424
425        slp->park(millis);
426
427        // were we externally suspended while we were waiting?
428        jt->check_and_wait_while_suspended();
429      }
430    }
431  } else {
432    OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
433    jlong prevtime = javaTimeNanos();
434
435    for (;;) {
436      // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
437      // the 1st iteration ...
438      jlong newtime = javaTimeNanos();
439
440      if (newtime - prevtime < 0) {
441        // time moving backwards, should only happen if no monotonic clock
442        // not a guarantee() because JVM should not abort on kernel/glibc bugs
443        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
444      } else {
445        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
446      }
447
448      if (millis <= 0) break ;
449
450      prevtime = newtime;
451      slp->park(millis);
452    }
453    return OS_OK ;
454  }
455}
456
457////////////////////////////////////////////////////////////////////////////////
458// interrupt support
459
460void os::interrupt(Thread* thread) {
461  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
462    "possibility of dangling Thread pointer");
463
464  OSThread* osthread = thread->osthread();
465
466  if (!osthread->interrupted()) {
467    osthread->set_interrupted(true);
468    // More than one thread can get here with the same value of osthread,
469    // resulting in multiple notifications.  We do, however, want the store
470    // to interrupted() to be visible to other threads before we execute unpark().
471    OrderAccess::fence();
472    ParkEvent * const slp = thread->_SleepEvent ;
473    if (slp != NULL) slp->unpark() ;
474  }
475
476  // For JSR166. Unpark even if interrupt status already was set
477  if (thread->is_Java_thread())
478    ((JavaThread*)thread)->parker()->unpark();
479
480  ParkEvent * ev = thread->_ParkEvent ;
481  if (ev != NULL) ev->unpark() ;
482
483}
484
485bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
486  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
487    "possibility of dangling Thread pointer");
488
489  OSThread* osthread = thread->osthread();
490
491  bool interrupted = osthread->interrupted();
492
493  // NOTE that since there is no "lock" around the interrupt and
494  // is_interrupted operations, there is the possibility that the
495  // interrupted flag (in osThread) will be "false" but that the
496  // low-level events will be in the signaled state. This is
497  // intentional. The effect of this is that Object.wait() and
498  // LockSupport.park() will appear to have a spurious wakeup, which
499  // is allowed and not harmful, and the possibility is so rare that
500  // it is not worth the added complexity to add yet another lock.
501  // For the sleep event an explicit reset is performed on entry
502  // to os::sleep, so there is no early return. It has also been
503  // recommended not to put the interrupted flag into the "event"
504  // structure because it hides the issue.
505  if (interrupted && clear_interrupted) {
506    osthread->set_interrupted(false);
507    // consider thread->_SleepEvent->reset() ... optional optimization
508  }
509
510  return interrupted;
511}
512
513
514
515static const struct {
516  int sig; const char* name;
517}
518 g_signal_info[] =
519  {
520  {  SIGABRT,     "SIGABRT" },
521#ifdef SIGAIO
522  {  SIGAIO,      "SIGAIO" },
523#endif
524  {  SIGALRM,     "SIGALRM" },
525#ifdef SIGALRM1
526  {  SIGALRM1,    "SIGALRM1" },
527#endif
528  {  SIGBUS,      "SIGBUS" },
529#ifdef SIGCANCEL
530  {  SIGCANCEL,   "SIGCANCEL" },
531#endif
532  {  SIGCHLD,     "SIGCHLD" },
533#ifdef SIGCLD
534  {  SIGCLD,      "SIGCLD" },
535#endif
536  {  SIGCONT,     "SIGCONT" },
537#ifdef SIGCPUFAIL
538  {  SIGCPUFAIL,  "SIGCPUFAIL" },
539#endif
540#ifdef SIGDANGER
541  {  SIGDANGER,   "SIGDANGER" },
542#endif
543#ifdef SIGDIL
544  {  SIGDIL,      "SIGDIL" },
545#endif
546#ifdef SIGEMT
547  {  SIGEMT,      "SIGEMT" },
548#endif
549  {  SIGFPE,      "SIGFPE" },
550#ifdef SIGFREEZE
551  {  SIGFREEZE,   "SIGFREEZE" },
552#endif
553#ifdef SIGGFAULT
554  {  SIGGFAULT,   "SIGGFAULT" },
555#endif
556#ifdef SIGGRANT
557  {  SIGGRANT,    "SIGGRANT" },
558#endif
559  {  SIGHUP,      "SIGHUP" },
560  {  SIGILL,      "SIGILL" },
561  {  SIGINT,      "SIGINT" },
562#ifdef SIGIO
563  {  SIGIO,       "SIGIO" },
564#endif
565#ifdef SIGIOINT
566  {  SIGIOINT,    "SIGIOINT" },
567#endif
568#ifdef SIGIOT
569// SIGIOT is there for BSD compatibility, but on most Unices just a
570// synonym for SIGABRT. The result should be "SIGABRT", not
571// "SIGIOT".
572#if (SIGIOT != SIGABRT )
573  {  SIGIOT,      "SIGIOT" },
574#endif
575#endif
576#ifdef SIGKAP
577  {  SIGKAP,      "SIGKAP" },
578#endif
579  {  SIGKILL,     "SIGKILL" },
580#ifdef SIGLOST
581  {  SIGLOST,     "SIGLOST" },
582#endif
583#ifdef SIGLWP
584  {  SIGLWP,      "SIGLWP" },
585#endif
586#ifdef SIGLWPTIMER
587  {  SIGLWPTIMER, "SIGLWPTIMER" },
588#endif
589#ifdef SIGMIGRATE
590  {  SIGMIGRATE,  "SIGMIGRATE" },
591#endif
592#ifdef SIGMSG
593  {  SIGMSG,      "SIGMSG" },
594#endif
595  {  SIGPIPE,     "SIGPIPE" },
596#ifdef SIGPOLL
597  {  SIGPOLL,     "SIGPOLL" },
598#endif
599#ifdef SIGPRE
600  {  SIGPRE,      "SIGPRE" },
601#endif
602  {  SIGPROF,     "SIGPROF" },
603#ifdef SIGPTY
604  {  SIGPTY,      "SIGPTY" },
605#endif
606#ifdef SIGPWR
607  {  SIGPWR,      "SIGPWR" },
608#endif
609  {  SIGQUIT,     "SIGQUIT" },
610#ifdef SIGRECONFIG
611  {  SIGRECONFIG, "SIGRECONFIG" },
612#endif
613#ifdef SIGRECOVERY
614  {  SIGRECOVERY, "SIGRECOVERY" },
615#endif
616#ifdef SIGRESERVE
617  {  SIGRESERVE,  "SIGRESERVE" },
618#endif
619#ifdef SIGRETRACT
620  {  SIGRETRACT,  "SIGRETRACT" },
621#endif
622#ifdef SIGSAK
623  {  SIGSAK,      "SIGSAK" },
624#endif
625  {  SIGSEGV,     "SIGSEGV" },
626#ifdef SIGSOUND
627  {  SIGSOUND,    "SIGSOUND" },
628#endif
629#ifdef SIGSTKFLT
630  {  SIGSTKFLT,    "SIGSTKFLT" },
631#endif
632  {  SIGSTOP,     "SIGSTOP" },
633  {  SIGSYS,      "SIGSYS" },
634#ifdef SIGSYSERROR
635  {  SIGSYSERROR, "SIGSYSERROR" },
636#endif
637#ifdef SIGTALRM
638  {  SIGTALRM,    "SIGTALRM" },
639#endif
640  {  SIGTERM,     "SIGTERM" },
641#ifdef SIGTHAW
642  {  SIGTHAW,     "SIGTHAW" },
643#endif
644  {  SIGTRAP,     "SIGTRAP" },
645#ifdef SIGTSTP
646  {  SIGTSTP,     "SIGTSTP" },
647#endif
648  {  SIGTTIN,     "SIGTTIN" },
649  {  SIGTTOU,     "SIGTTOU" },
650#ifdef SIGURG
651  {  SIGURG,      "SIGURG" },
652#endif
653  {  SIGUSR1,     "SIGUSR1" },
654  {  SIGUSR2,     "SIGUSR2" },
655#ifdef SIGVIRT
656  {  SIGVIRT,     "SIGVIRT" },
657#endif
658  {  SIGVTALRM,   "SIGVTALRM" },
659#ifdef SIGWAITING
660  {  SIGWAITING,  "SIGWAITING" },
661#endif
662#ifdef SIGWINCH
663  {  SIGWINCH,    "SIGWINCH" },
664#endif
665#ifdef SIGWINDOW
666  {  SIGWINDOW,   "SIGWINDOW" },
667#endif
668  {  SIGXCPU,     "SIGXCPU" },
669  {  SIGXFSZ,     "SIGXFSZ" },
670#ifdef SIGXRES
671  {  SIGXRES,     "SIGXRES" },
672#endif
673  { -1, NULL }
674};
675
676// Returned string is a constant. For unknown signals "UNKNOWN" is returned.
677const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
678
679  const char* ret = NULL;
680
681#ifdef SIGRTMIN
682  if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
683    if (sig == SIGRTMIN) {
684      ret = "SIGRTMIN";
685    } else if (sig == SIGRTMAX) {
686      ret = "SIGRTMAX";
687    } else {
688      jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
689      return out;
690    }
691  }
692#endif
693
694  if (sig > 0) {
695    for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
696      if (g_signal_info[idx].sig == sig) {
697        ret = g_signal_info[idx].name;
698        break;
699      }
700    }
701  }
702
703  if (!ret) {
704    if (!is_valid_signal(sig)) {
705      ret = "INVALID";
706    } else {
707      ret = "UNKNOWN";
708    }
709  }
710
711  if (out && outlen > 0) {
712    strncpy(out, ret, outlen);
713    out[outlen - 1] = '\0';
714  }
715  return out;
716}
717
718int os::Posix::get_signal_number(const char* signal_name) {
719  char tmp[30];
720  const char* s = signal_name;
721  if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
722    jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
723    s = tmp;
724  }
725  for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
726    if (strcmp(g_signal_info[idx].name, s) == 0) {
727      return g_signal_info[idx].sig;
728    }
729  }
730  return -1;
731}
732
733int os::get_signal_number(const char* signal_name) {
734  return os::Posix::get_signal_number(signal_name);
735}
736
737// Returns true if signal number is valid.
738bool os::Posix::is_valid_signal(int sig) {
739  // MacOS not really POSIX compliant: sigaddset does not return
740  // an error for invalid signal numbers. However, MacOS does not
741  // support real time signals and simply seems to have just 33
742  // signals with no holes in the signal range.
743#ifdef __APPLE__
744  return sig >= 1 && sig < NSIG;
745#else
746  // Use sigaddset to check for signal validity.
747  sigset_t set;
748  if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
749    return false;
750  }
751  return true;
752#endif
753}
754
755// Returns:
756// NULL for an invalid signal number
757// "SIG<num>" for a valid but unknown signal number
758// signal name otherwise.
759const char* os::exception_name(int sig, char* buf, size_t size) {
760  if (!os::Posix::is_valid_signal(sig)) {
761    return NULL;
762  }
763  const char* const name = os::Posix::get_signal_name(sig, buf, size);
764  if (strcmp(name, "UNKNOWN") == 0) {
765    jio_snprintf(buf, size, "SIG%d", sig);
766  }
767  return buf;
768}
769
770#define NUM_IMPORTANT_SIGS 32
771// Returns one-line short description of a signal set in a user provided buffer.
772const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
773  assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
774  // Note: for shortness, just print out the first 32. That should
775  // cover most of the useful ones, apart from realtime signals.
776  for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
777    const int rc = sigismember(set, sig);
778    if (rc == -1 && errno == EINVAL) {
779      buffer[sig-1] = '?';
780    } else {
781      buffer[sig-1] = rc == 0 ? '0' : '1';
782    }
783  }
784  buffer[NUM_IMPORTANT_SIGS] = 0;
785  return buffer;
786}
787
788// Prints one-line description of a signal set.
789void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
790  char buf[NUM_IMPORTANT_SIGS + 1];
791  os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
792  st->print("%s", buf);
793}
794
795// Writes one-line description of a combination of sigaction.sa_flags into a user
796// provided buffer. Returns that buffer.
797const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
798  char* p = buffer;
799  size_t remaining = size;
800  bool first = true;
801  int idx = 0;
802
803  assert(buffer, "invalid argument");
804
805  if (size == 0) {
806    return buffer;
807  }
808
809  strncpy(buffer, "none", size);
810
811  const struct {
812    // NB: i is an unsigned int here because SA_RESETHAND is on some
813    // systems 0x80000000, which is implicitly unsigned.  Assignining
814    // it to an int field would be an overflow in unsigned-to-signed
815    // conversion.
816    unsigned int i;
817    const char* s;
818  } flaginfo [] = {
819    { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
820    { SA_ONSTACK,   "SA_ONSTACK"   },
821    { SA_RESETHAND, "SA_RESETHAND" },
822    { SA_RESTART,   "SA_RESTART"   },
823    { SA_SIGINFO,   "SA_SIGINFO"   },
824    { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
825    { SA_NODEFER,   "SA_NODEFER"   },
826#ifdef AIX
827    { SA_ONSTACK,   "SA_ONSTACK"   },
828    { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
829#endif
830    { 0, NULL }
831  };
832
833  for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
834    if (flags & flaginfo[idx].i) {
835      if (first) {
836        jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
837        first = false;
838      } else {
839        jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
840      }
841      const size_t len = strlen(p);
842      p += len;
843      remaining -= len;
844    }
845  }
846
847  buffer[size - 1] = '\0';
848
849  return buffer;
850}
851
852// Prints one-line description of a combination of sigaction.sa_flags.
853void os::Posix::print_sa_flags(outputStream* st, int flags) {
854  char buffer[0x100];
855  os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
856  st->print("%s", buffer);
857}
858
859// Helper function for os::Posix::print_siginfo_...():
860// return a textual description for signal code.
861struct enum_sigcode_desc_t {
862  const char* s_name;
863  const char* s_desc;
864};
865
866static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
867
868  const struct {
869    int sig; int code; const char* s_code; const char* s_desc;
870  } t1 [] = {
871    { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
872    { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
873    { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
874    { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
875    { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
876    { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
877    { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
878    { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
879#if defined(IA64) && defined(LINUX)
880    { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
881    { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
882#endif
883    { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
884    { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
885    { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
886    { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
887    { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
888    { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
889    { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
890    { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
891    { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
892    { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
893#ifdef AIX
894    // no explanation found what keyerr would be
895    { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
896#endif
897#if defined(IA64) && !defined(AIX)
898    { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
899#endif
900#if defined(__sparc) && defined(SOLARIS)
901// define Solaris Sparc M7 ADI SEGV signals
902#if !defined(SEGV_ACCADI)
903#define SEGV_ACCADI 3
904#endif
905    { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
906#if !defined(SEGV_ACCDERR)
907#define SEGV_ACCDERR 4
908#endif
909    { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
910#if !defined(SEGV_ACCPERR)
911#define SEGV_ACCPERR 5
912#endif
913    { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
914#endif // defined(__sparc) && defined(SOLARIS)
915    { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
916    { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
917    { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
918    { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
919    { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
920    { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
921    { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
922    { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
923    { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
924    { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
925    { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
926#ifdef SIGPOLL
927    { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
928    { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
929    { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
930    { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
931    { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
932#endif
933    { -1, -1, NULL, NULL }
934  };
935
936  // Codes valid in any signal context.
937  const struct {
938    int code; const char* s_code; const char* s_desc;
939  } t2 [] = {
940    { SI_USER,      "SI_USER",     "Signal sent by kill()." },
941    { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
942    { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
943    { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
944    { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
945    // Linux specific
946#ifdef SI_TKILL
947    { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
948#endif
949#ifdef SI_DETHREAD
950    { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
951#endif
952#ifdef SI_KERNEL
953    { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
954#endif
955#ifdef SI_SIGIO
956    { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
957#endif
958
959#ifdef AIX
960    { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
961    { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
962#endif
963
964#ifdef __sun
965    { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
966    { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
967    { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
968#endif
969
970    { -1, NULL, NULL }
971  };
972
973  const char* s_code = NULL;
974  const char* s_desc = NULL;
975
976  for (int i = 0; t1[i].sig != -1; i ++) {
977    if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
978      s_code = t1[i].s_code;
979      s_desc = t1[i].s_desc;
980      break;
981    }
982  }
983
984  if (s_code == NULL) {
985    for (int i = 0; t2[i].s_code != NULL; i ++) {
986      if (t2[i].code == si->si_code) {
987        s_code = t2[i].s_code;
988        s_desc = t2[i].s_desc;
989      }
990    }
991  }
992
993  if (s_code == NULL) {
994    out->s_name = "unknown";
995    out->s_desc = "unknown";
996    return false;
997  }
998
999  out->s_name = s_code;
1000  out->s_desc = s_desc;
1001
1002  return true;
1003}
1004
1005void os::print_siginfo(outputStream* os, const void* si0) {
1006
1007  const siginfo_t* const si = (const siginfo_t*) si0;
1008
1009  char buf[20];
1010  os->print("siginfo:");
1011
1012  if (!si) {
1013    os->print(" <null>");
1014    return;
1015  }
1016
1017  const int sig = si->si_signo;
1018
1019  os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
1020
1021  enum_sigcode_desc_t ed;
1022  get_signal_code_description(si, &ed);
1023  os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1024
1025  if (si->si_errno) {
1026    os->print(", si_errno: %d", si->si_errno);
1027  }
1028
1029  // Output additional information depending on the signal code.
1030
1031  // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1032  // so it depends on the context which member to use. For synchronous error signals,
1033  // we print si_addr, unless the signal was sent by another process or thread, in
1034  // which case we print out pid or tid of the sender.
1035  if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
1036    const pid_t pid = si->si_pid;
1037    os->print(", si_pid: %ld", (long) pid);
1038    if (IS_VALID_PID(pid)) {
1039      const pid_t me = getpid();
1040      if (me == pid) {
1041        os->print(" (current process)");
1042      }
1043    } else {
1044      os->print(" (invalid)");
1045    }
1046    os->print(", si_uid: %ld", (long) si->si_uid);
1047    if (sig == SIGCHLD) {
1048      os->print(", si_status: %d", si->si_status);
1049    }
1050  } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1051             sig == SIGTRAP || sig == SIGFPE) {
1052    os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1053#ifdef SIGPOLL
1054  } else if (sig == SIGPOLL) {
1055    os->print(", si_band: %ld", si->si_band);
1056#endif
1057  }
1058
1059}
1060
1061int os::Posix::unblock_thread_signal_mask(const sigset_t *set) {
1062  return pthread_sigmask(SIG_UNBLOCK, set, NULL);
1063}
1064
1065address os::Posix::ucontext_get_pc(const ucontext_t* ctx) {
1066#if defined(AIX)
1067   return Aix::ucontext_get_pc(ctx);
1068#elif defined(BSD)
1069   return Bsd::ucontext_get_pc(ctx);
1070#elif defined(LINUX)
1071   return Linux::ucontext_get_pc(ctx);
1072#elif defined(SOLARIS)
1073   return Solaris::ucontext_get_pc(ctx);
1074#else
1075   VMError::report_and_die("unimplemented ucontext_get_pc");
1076#endif
1077}
1078
1079void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) {
1080#if defined(AIX)
1081   Aix::ucontext_set_pc(ctx, pc);
1082#elif defined(BSD)
1083   Bsd::ucontext_set_pc(ctx, pc);
1084#elif defined(LINUX)
1085   Linux::ucontext_set_pc(ctx, pc);
1086#elif defined(SOLARIS)
1087   Solaris::ucontext_set_pc(ctx, pc);
1088#else
1089   VMError::report_and_die("unimplemented ucontext_get_pc");
1090#endif
1091}
1092
1093char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
1094  size_t stack_size = 0;
1095  size_t guard_size = 0;
1096  int detachstate = 0;
1097  pthread_attr_getstacksize(attr, &stack_size);
1098  pthread_attr_getguardsize(attr, &guard_size);
1099  pthread_attr_getdetachstate(attr, &detachstate);
1100  jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
1101    stack_size / 1024, guard_size / 1024,
1102    (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
1103  return buf;
1104}
1105
1106
1107os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
1108  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
1109}
1110
1111/*
1112 * See the caveats for this class in os_posix.hpp
1113 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1114 * method and returns false. If none of the signals are raised, returns true.
1115 * The callback is supposed to provide the method that should be protected.
1116 */
1117bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1118  sigset_t saved_sig_mask;
1119
1120  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
1121  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
1122      "crash_protection already set?");
1123
1124  // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1125  // since on at least some systems (OS X) siglongjmp will restore the mask
1126  // for the process, not the thread
1127  pthread_sigmask(0, NULL, &saved_sig_mask);
1128  if (sigsetjmp(_jmpbuf, 0) == 0) {
1129    // make sure we can see in the signal handler that we have crash protection
1130    // installed
1131    WatcherThread::watcher_thread()->set_crash_protection(this);
1132    cb.call();
1133    // and clear the crash protection
1134    WatcherThread::watcher_thread()->set_crash_protection(NULL);
1135    return true;
1136  }
1137  // this happens when we siglongjmp() back
1138  pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1139  WatcherThread::watcher_thread()->set_crash_protection(NULL);
1140  return false;
1141}
1142
1143void os::WatcherThreadCrashProtection::restore() {
1144  assert(WatcherThread::watcher_thread()->has_crash_protection(),
1145      "must have crash protection");
1146
1147  siglongjmp(_jmpbuf, 1);
1148}
1149
1150void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1151    Thread* thread) {
1152
1153  if (thread != NULL &&
1154      thread->is_Watcher_thread() &&
1155      WatcherThread::watcher_thread()->has_crash_protection()) {
1156
1157    if (sig == SIGSEGV || sig == SIGBUS) {
1158      WatcherThread::watcher_thread()->crash_protection()->restore();
1159    }
1160  }
1161}
1162
1163#define check_with_errno(check_type, cond, msg)                             \
1164  do {                                                                      \
1165    int err = errno;                                                        \
1166    check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
1167               os::errno_name(err));                                        \
1168} while (false)
1169
1170#define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1171#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1172
1173// POSIX unamed semaphores are not supported on OS X.
1174#ifndef __APPLE__
1175
1176PosixSemaphore::PosixSemaphore(uint value) {
1177  int ret = sem_init(&_semaphore, 0, value);
1178
1179  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1180}
1181
1182PosixSemaphore::~PosixSemaphore() {
1183  sem_destroy(&_semaphore);
1184}
1185
1186void PosixSemaphore::signal(uint count) {
1187  for (uint i = 0; i < count; i++) {
1188    int ret = sem_post(&_semaphore);
1189
1190    assert_with_errno(ret == 0, "sem_post failed");
1191  }
1192}
1193
1194void PosixSemaphore::wait() {
1195  int ret;
1196
1197  do {
1198    ret = sem_wait(&_semaphore);
1199  } while (ret != 0 && errno == EINTR);
1200
1201  assert_with_errno(ret == 0, "sem_wait failed");
1202}
1203
1204bool PosixSemaphore::trywait() {
1205  int ret;
1206
1207  do {
1208    ret = sem_trywait(&_semaphore);
1209  } while (ret != 0 && errno == EINTR);
1210
1211  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1212
1213  return ret == 0;
1214}
1215
1216bool PosixSemaphore::timedwait(struct timespec ts) {
1217  while (true) {
1218    int result = sem_timedwait(&_semaphore, &ts);
1219    if (result == 0) {
1220      return true;
1221    } else if (errno == EINTR) {
1222      continue;
1223    } else if (errno == ETIMEDOUT) {
1224      return false;
1225    } else {
1226      assert_with_errno(false, "timedwait failed");
1227      return false;
1228    }
1229  }
1230}
1231
1232#endif // __APPLE__
1233