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