os_posix.cpp revision 9099:115188e14c15
1275963Srpaulo/*
2275963Srpaulo * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
3275963Srpaulo * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4275963Srpaulo *
5275963Srpaulo * This code is free software; you can redistribute it and/or modify it
6275963Srpaulo * under the terms of the GNU General Public License version 2 only, as
7275963Srpaulo * published by the Free Software Foundation.
8275963Srpaulo *
9275963Srpaulo * This code is distributed in the hope that it will be useful, but WITHOUT
10275963Srpaulo * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11275963Srpaulo * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12275963Srpaulo * version 2 for more details (a copy is included in the LICENSE file that
13275963Srpaulo * accompanied this code).
14275963Srpaulo *
15275963Srpaulo * You should have received a copy of the GNU General Public License version
16275963Srpaulo * 2 along with this work; if not, write to the Free Software Foundation,
17275963Srpaulo * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18275963Srpaulo *
19275963Srpaulo * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20275963Srpaulo * or visit www.oracle.com if you need additional information or have any
21275963Srpaulo * questions.
22275963Srpaulo *
23275963Srpaulo */
24275963Srpaulo
25275963Srpaulo#include "utilities/globalDefinitions.hpp"
26275963Srpaulo#include "prims/jvm.h"
27275963Srpaulo#include "semaphore_posix.hpp"
28275963Srpaulo#include "runtime/frame.inline.hpp"
29275963Srpaulo#include "runtime/interfaceSupport.hpp"
30275963Srpaulo#include "runtime/os.hpp"
31275963Srpaulo#include "utilities/vmError.hpp"
32275963Srpaulo
33275963Srpaulo#include <signal.h>
34275963Srpaulo#include <unistd.h>
35275963Srpaulo#include <sys/resource.h>
36275963Srpaulo#include <sys/utsname.h>
37275963Srpaulo#include <pthread.h>
38275963Srpaulo#include <semaphore.h>
39275963Srpaulo#include <signal.h>
40275963Srpaulo
41275963Srpaulo// Todo: provide a os::get_max_process_id() or similar. Number of processes
42275963Srpaulo// may have been configured, can be read more accurately from proc fs etc.
43275963Srpaulo#ifndef MAX_PID
44275963Srpaulo#define MAX_PID INT_MAX
45275963Srpaulo#endif
46275963Srpaulo#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
47275963Srpaulo
48275963Srpaulo// Check core dump limit and report possible place where core can be found
49275963Srpaulovoid os::check_dump_limit(char* buffer, size_t bufferSize) {
50275963Srpaulo  int n;
51275963Srpaulo  struct rlimit rlim;
52275963Srpaulo  bool success;
53275963Srpaulo
54275963Srpaulo  char core_path[PATH_MAX];
55275963Srpaulo  n = get_core_path(core_path, PATH_MAX);
56275963Srpaulo
57275963Srpaulo  if (n <= 0) {
58275963Srpaulo    jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
59275963Srpaulo    success = true;
60275963Srpaulo#ifdef LINUX
61275963Srpaulo  } else if (core_path[0] == '"') { // redirect to user process
62275963Srpaulo    jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
63275963Srpaulo    success = true;
64275963Srpaulo#endif
65275963Srpaulo  } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
66275963Srpaulo    jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
67275963Srpaulo    success = true;
68275963Srpaulo  } else {
69275963Srpaulo    switch(rlim.rlim_cur) {
70275963Srpaulo      case RLIM_INFINITY:
71275963Srpaulo        jio_snprintf(buffer, bufferSize, "%s", core_path);
72275963Srpaulo        success = true;
73275963Srpaulo        break;
74275963Srpaulo      case 0:
75275963Srpaulo        jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
76275963Srpaulo        success = false;
77275963Srpaulo        break;
78275963Srpaulo      default:
79275963Srpaulo        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));
80275963Srpaulo        success = true;
81275963Srpaulo        break;
82275963Srpaulo    }
83275963Srpaulo  }
84275963Srpaulo
85275963Srpaulo  VMError::record_coredump_status(buffer, success);
86275963Srpaulo}
87275963Srpaulo
88275963Srpauloint os::get_native_stack(address* stack, int frames, int toSkip) {
89275963Srpaulo#ifdef _NMT_NOINLINE_
90275963Srpaulo  toSkip++;
91275963Srpaulo#endif
92275963Srpaulo
93275963Srpaulo  int frame_idx = 0;
94275963Srpaulo  int num_of_frames;  // number of frames captured
95275963Srpaulo  frame fr = os::current_frame();
96275963Srpaulo  while (fr.pc() && frame_idx < frames) {
97275963Srpaulo    if (toSkip > 0) {
98275963Srpaulo      toSkip --;
99275963Srpaulo    } else {
100275963Srpaulo      stack[frame_idx ++] = fr.pc();
101275963Srpaulo    }
102275963Srpaulo    if (fr.fp() == NULL || fr.cb() != NULL ||
103275963Srpaulo        fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
104275963Srpaulo
105275963Srpaulo    if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
106275963Srpaulo      fr = os::get_sender_for_C_frame(&fr);
107275963Srpaulo    } else {
108275963Srpaulo      break;
109275963Srpaulo    }
110275963Srpaulo  }
111275963Srpaulo  num_of_frames = frame_idx;
112275963Srpaulo  for (; frame_idx < frames; frame_idx ++) {
113275963Srpaulo    stack[frame_idx] = NULL;
114275963Srpaulo  }
115275963Srpaulo
116275963Srpaulo  return num_of_frames;
117275963Srpaulo}
118275963Srpaulo
119275963Srpaulo
120275963Srpaulobool os::unsetenv(const char* name) {
121275963Srpaulo  assert(name != NULL, "Null pointer");
122275963Srpaulo  return (::unsetenv(name) == 0);
123275963Srpaulo}
124275963Srpaulo
125275963Srpauloint os::get_last_error() {
126275963Srpaulo  return errno;
127275963Srpaulo}
128275963Srpaulo
129275963Srpaulobool os::is_debugger_attached() {
130275963Srpaulo  // not implemented
131275963Srpaulo  return false;
132275963Srpaulo}
133275963Srpaulo
134275963Srpaulovoid os::wait_for_keypress_at_exit(void) {
135275963Srpaulo  // don't do anything on posix platforms
136275963Srpaulo  return;
137275963Srpaulo}
138275963Srpaulo
139275963Srpaulo// Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
140275963Srpaulo// so on posix, unmap the section at the start and at the end of the chunk that we mapped
141275963Srpaulo// rather than unmapping and remapping the whole chunk to get requested alignment.
142275963Srpaulochar* os::reserve_memory_aligned(size_t size, size_t alignment) {
143275963Srpaulo  assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
144275963Srpaulo      "Alignment must be a multiple of allocation granularity (page size)");
145275963Srpaulo  assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
146275963Srpaulo
147275963Srpaulo  size_t extra_size = size + alignment;
148275963Srpaulo  assert(extra_size >= size, "overflow, size is too large to allow alignment");
149275963Srpaulo
150275963Srpaulo  char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
151275963Srpaulo
152275963Srpaulo  if (extra_base == NULL) {
153275963Srpaulo    return NULL;
154275963Srpaulo  }
155275963Srpaulo
156275963Srpaulo  // Do manual alignment
157275963Srpaulo  char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment);
158275963Srpaulo
159275963Srpaulo  // [  |                                       |  ]
160275963Srpaulo  // ^ extra_base
161275963Srpaulo  //    ^ extra_base + begin_offset == aligned_base
162275963Srpaulo  //     extra_base + begin_offset + size       ^
163275963Srpaulo  //                       extra_base + extra_size ^
164275963Srpaulo  // |<>| == begin_offset
165275963Srpaulo  //                              end_offset == |<>|
166275963Srpaulo  size_t begin_offset = aligned_base - extra_base;
167275963Srpaulo  size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
168275963Srpaulo
169275963Srpaulo  if (begin_offset > 0) {
170275963Srpaulo      os::release_memory(extra_base, begin_offset);
171275963Srpaulo  }
172275963Srpaulo
173275963Srpaulo  if (end_offset > 0) {
174275963Srpaulo      os::release_memory(extra_base + begin_offset + size, end_offset);
175275963Srpaulo  }
176275963Srpaulo
177275963Srpaulo  return aligned_base;
178275963Srpaulo}
179275963Srpaulo
180275963Srpaulovoid os::Posix::print_load_average(outputStream* st) {
181275963Srpaulo  st->print("load average:");
182275963Srpaulo  double loadavg[3];
183275963Srpaulo  os::loadavg(loadavg, 3);
184275963Srpaulo  st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
185275963Srpaulo  st->cr();
186275963Srpaulo}
187275963Srpaulo
188275963Srpaulovoid os::Posix::print_rlimit_info(outputStream* st) {
189275963Srpaulo  st->print("rlimit:");
190275963Srpaulo  struct rlimit rlim;
191275963Srpaulo
192275963Srpaulo  st->print(" STACK ");
193275963Srpaulo  getrlimit(RLIMIT_STACK, &rlim);
194275963Srpaulo  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
195275963Srpaulo  else st->print("%luk", rlim.rlim_cur >> 10);
196275963Srpaulo
197275963Srpaulo  st->print(", CORE ");
198275963Srpaulo  getrlimit(RLIMIT_CORE, &rlim);
199275963Srpaulo  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
200275963Srpaulo  else st->print("%luk", rlim.rlim_cur >> 10);
201275963Srpaulo
202275963Srpaulo  // Isn't there on solaris
203275963Srpaulo#if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix)
204275963Srpaulo  st->print(", NPROC ");
205275963Srpaulo  getrlimit(RLIMIT_NPROC, &rlim);
206275963Srpaulo  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
207275963Srpaulo  else st->print("%lu", rlim.rlim_cur);
208275963Srpaulo#endif
209275963Srpaulo
210275963Srpaulo  st->print(", NOFILE ");
211275963Srpaulo  getrlimit(RLIMIT_NOFILE, &rlim);
212275963Srpaulo  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
213275963Srpaulo  else st->print("%lu", rlim.rlim_cur);
214275963Srpaulo
215275963Srpaulo  st->print(", AS ");
216275963Srpaulo  getrlimit(RLIMIT_AS, &rlim);
217275963Srpaulo  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
218275963Srpaulo  else st->print("%luk", rlim.rlim_cur >> 10);
219275963Srpaulo  st->cr();
220275963Srpaulo}
221275963Srpaulo
222275963Srpaulovoid os::Posix::print_uname_info(outputStream* st) {
223275963Srpaulo  // kernel
224275963Srpaulo  st->print("uname:");
225275963Srpaulo  struct utsname name;
226275963Srpaulo  uname(&name);
227275963Srpaulo  st->print("%s ", name.sysname);
228275963Srpaulo#ifdef ASSERT
229275963Srpaulo  st->print("%s ", name.nodename);
230275963Srpaulo#endif
231275963Srpaulo  st->print("%s ", name.release);
232275963Srpaulo  st->print("%s ", name.version);
233275963Srpaulo  st->print("%s", name.machine);
234275963Srpaulo  st->cr();
235275963Srpaulo}
236275963Srpaulo
237275963Srpaulo#ifndef PRODUCT
238275963Srpaulobool os::get_host_name(char* buf, size_t buflen) {
239275963Srpaulo  struct utsname name;
240275963Srpaulo  uname(&name);
241275963Srpaulo  jio_snprintf(buf, buflen, "%s", name.nodename);
242275963Srpaulo  return true;
243275963Srpaulo}
244275963Srpaulo#endif // PRODUCT
245275963Srpaulo
246275963Srpaulobool os::has_allocatable_memory_limit(julong* limit) {
247275963Srpaulo  struct rlimit rlim;
248275963Srpaulo  int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
249275963Srpaulo  // if there was an error when calling getrlimit, assume that there is no limitation
250275963Srpaulo  // on virtual memory.
251275963Srpaulo  bool result;
252275963Srpaulo  if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
253275963Srpaulo    result = false;
254275963Srpaulo  } else {
255275963Srpaulo    *limit = (julong)rlim.rlim_cur;
256275963Srpaulo    result = true;
257275963Srpaulo  }
258275963Srpaulo#ifdef _LP64
259275963Srpaulo  return result;
260275963Srpaulo#else
261275963Srpaulo  // arbitrary virtual space limit for 32 bit Unices found by testing. If
262275963Srpaulo  // getrlimit above returned a limit, bound it with this limit. Otherwise
263275963Srpaulo  // directly use it.
264275963Srpaulo  const julong max_virtual_limit = (julong)3800*M;
265275963Srpaulo  if (result) {
266275963Srpaulo    *limit = MIN2(*limit, max_virtual_limit);
267275963Srpaulo  } else {
268275963Srpaulo    *limit = max_virtual_limit;
269275963Srpaulo  }
270275963Srpaulo
271275963Srpaulo  // bound by actually allocatable memory. The algorithm uses two bounds, an
272275963Srpaulo  // upper and a lower limit. The upper limit is the current highest amount of
273275963Srpaulo  // memory that could not be allocated, the lower limit is the current highest
274  // amount of memory that could be allocated.
275  // The algorithm iteratively refines the result by halving the difference
276  // between these limits, updating either the upper limit (if that value could
277  // not be allocated) or the lower limit (if the that value could be allocated)
278  // until the difference between these limits is "small".
279
280  // the minimum amount of memory we care about allocating.
281  const julong min_allocation_size = M;
282
283  julong upper_limit = *limit;
284
285  // first check a few trivial cases
286  if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
287    *limit = upper_limit;
288  } else if (!is_allocatable(min_allocation_size)) {
289    // we found that not even min_allocation_size is allocatable. Return it
290    // anyway. There is no point to search for a better value any more.
291    *limit = min_allocation_size;
292  } else {
293    // perform the binary search.
294    julong lower_limit = min_allocation_size;
295    while ((upper_limit - lower_limit) > min_allocation_size) {
296      julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
297      temp_limit = align_size_down_(temp_limit, min_allocation_size);
298      if (is_allocatable(temp_limit)) {
299        lower_limit = temp_limit;
300      } else {
301        upper_limit = temp_limit;
302      }
303    }
304    *limit = lower_limit;
305  }
306  return true;
307#endif
308}
309
310const char* os::get_current_directory(char *buf, size_t buflen) {
311  return getcwd(buf, buflen);
312}
313
314FILE* os::open(int fd, const char* mode) {
315  return ::fdopen(fd, mode);
316}
317
318// Builds a platform dependent Agent_OnLoad_<lib_name> function name
319// which is used to find statically linked in agents.
320// Parameters:
321//            sym_name: Symbol in library we are looking for
322//            lib_name: Name of library to look in, NULL for shared libs.
323//            is_absolute_path == true if lib_name is absolute path to agent
324//                                     such as "/a/b/libL.so"
325//            == false if only the base name of the library is passed in
326//               such as "L"
327char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
328                                    bool is_absolute_path) {
329  char *agent_entry_name;
330  size_t len;
331  size_t name_len;
332  size_t prefix_len = strlen(JNI_LIB_PREFIX);
333  size_t suffix_len = strlen(JNI_LIB_SUFFIX);
334  const char *start;
335
336  if (lib_name != NULL) {
337    len = name_len = strlen(lib_name);
338    if (is_absolute_path) {
339      // Need to strip path, prefix and suffix
340      if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
341        lib_name = ++start;
342      }
343      if (len <= (prefix_len + suffix_len)) {
344        return NULL;
345      }
346      lib_name += prefix_len;
347      name_len = strlen(lib_name) - suffix_len;
348    }
349  }
350  len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
351  agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
352  if (agent_entry_name == NULL) {
353    return NULL;
354  }
355  strcpy(agent_entry_name, sym_name);
356  if (lib_name != NULL) {
357    strcat(agent_entry_name, "_");
358    strncat(agent_entry_name, lib_name, name_len);
359  }
360  return agent_entry_name;
361}
362
363int os::sleep(Thread* thread, jlong millis, bool interruptible) {
364  assert(thread == Thread::current(),  "thread consistency check");
365
366  ParkEvent * const slp = thread->_SleepEvent ;
367  slp->reset() ;
368  OrderAccess::fence() ;
369
370  if (interruptible) {
371    jlong prevtime = javaTimeNanos();
372
373    for (;;) {
374      if (os::is_interrupted(thread, true)) {
375        return OS_INTRPT;
376      }
377
378      jlong newtime = javaTimeNanos();
379
380      if (newtime - prevtime < 0) {
381        // time moving backwards, should only happen if no monotonic clock
382        // not a guarantee() because JVM should not abort on kernel/glibc bugs
383        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
384      } else {
385        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
386      }
387
388      if (millis <= 0) {
389        return OS_OK;
390      }
391
392      prevtime = newtime;
393
394      {
395        assert(thread->is_Java_thread(), "sanity check");
396        JavaThread *jt = (JavaThread *) thread;
397        ThreadBlockInVM tbivm(jt);
398        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
399
400        jt->set_suspend_equivalent();
401        // cleared by handle_special_suspend_equivalent_condition() or
402        // java_suspend_self() via check_and_wait_while_suspended()
403
404        slp->park(millis);
405
406        // were we externally suspended while we were waiting?
407        jt->check_and_wait_while_suspended();
408      }
409    }
410  } else {
411    OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
412    jlong prevtime = javaTimeNanos();
413
414    for (;;) {
415      // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
416      // the 1st iteration ...
417      jlong newtime = javaTimeNanos();
418
419      if (newtime - prevtime < 0) {
420        // time moving backwards, should only happen if no monotonic clock
421        // not a guarantee() because JVM should not abort on kernel/glibc bugs
422        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
423      } else {
424        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
425      }
426
427      if (millis <= 0) break ;
428
429      prevtime = newtime;
430      slp->park(millis);
431    }
432    return OS_OK ;
433  }
434}
435
436////////////////////////////////////////////////////////////////////////////////
437// interrupt support
438
439void os::interrupt(Thread* thread) {
440  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
441    "possibility of dangling Thread pointer");
442
443  OSThread* osthread = thread->osthread();
444
445  if (!osthread->interrupted()) {
446    osthread->set_interrupted(true);
447    // More than one thread can get here with the same value of osthread,
448    // resulting in multiple notifications.  We do, however, want the store
449    // to interrupted() to be visible to other threads before we execute unpark().
450    OrderAccess::fence();
451    ParkEvent * const slp = thread->_SleepEvent ;
452    if (slp != NULL) slp->unpark() ;
453  }
454
455  // For JSR166. Unpark even if interrupt status already was set
456  if (thread->is_Java_thread())
457    ((JavaThread*)thread)->parker()->unpark();
458
459  ParkEvent * ev = thread->_ParkEvent ;
460  if (ev != NULL) ev->unpark() ;
461
462}
463
464bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
465  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
466    "possibility of dangling Thread pointer");
467
468  OSThread* osthread = thread->osthread();
469
470  bool interrupted = osthread->interrupted();
471
472  // NOTE that since there is no "lock" around the interrupt and
473  // is_interrupted operations, there is the possibility that the
474  // interrupted flag (in osThread) will be "false" but that the
475  // low-level events will be in the signaled state. This is
476  // intentional. The effect of this is that Object.wait() and
477  // LockSupport.park() will appear to have a spurious wakeup, which
478  // is allowed and not harmful, and the possibility is so rare that
479  // it is not worth the added complexity to add yet another lock.
480  // For the sleep event an explicit reset is performed on entry
481  // to os::sleep, so there is no early return. It has also been
482  // recommended not to put the interrupted flag into the "event"
483  // structure because it hides the issue.
484  if (interrupted && clear_interrupted) {
485    osthread->set_interrupted(false);
486    // consider thread->_SleepEvent->reset() ... optional optimization
487  }
488
489  return interrupted;
490}
491
492// Returned string is a constant. For unknown signals "UNKNOWN" is returned.
493const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
494
495  static const struct {
496    int sig; const char* name;
497  }
498  info[] =
499  {
500    {  SIGABRT,     "SIGABRT" },
501#ifdef SIGAIO
502    {  SIGAIO,      "SIGAIO" },
503#endif
504    {  SIGALRM,     "SIGALRM" },
505#ifdef SIGALRM1
506    {  SIGALRM1,    "SIGALRM1" },
507#endif
508    {  SIGBUS,      "SIGBUS" },
509#ifdef SIGCANCEL
510    {  SIGCANCEL,   "SIGCANCEL" },
511#endif
512    {  SIGCHLD,     "SIGCHLD" },
513#ifdef SIGCLD
514    {  SIGCLD,      "SIGCLD" },
515#endif
516    {  SIGCONT,     "SIGCONT" },
517#ifdef SIGCPUFAIL
518    {  SIGCPUFAIL,  "SIGCPUFAIL" },
519#endif
520#ifdef SIGDANGER
521    {  SIGDANGER,   "SIGDANGER" },
522#endif
523#ifdef SIGDIL
524    {  SIGDIL,      "SIGDIL" },
525#endif
526#ifdef SIGEMT
527    {  SIGEMT,      "SIGEMT" },
528#endif
529    {  SIGFPE,      "SIGFPE" },
530#ifdef SIGFREEZE
531    {  SIGFREEZE,   "SIGFREEZE" },
532#endif
533#ifdef SIGGFAULT
534    {  SIGGFAULT,   "SIGGFAULT" },
535#endif
536#ifdef SIGGRANT
537    {  SIGGRANT,    "SIGGRANT" },
538#endif
539    {  SIGHUP,      "SIGHUP" },
540    {  SIGILL,      "SIGILL" },
541    {  SIGINT,      "SIGINT" },
542#ifdef SIGIO
543    {  SIGIO,       "SIGIO" },
544#endif
545#ifdef SIGIOINT
546    {  SIGIOINT,    "SIGIOINT" },
547#endif
548#ifdef SIGIOT
549  // SIGIOT is there for BSD compatibility, but on most Unices just a
550  // synonym for SIGABRT. The result should be "SIGABRT", not
551  // "SIGIOT".
552  #if (SIGIOT != SIGABRT )
553    {  SIGIOT,      "SIGIOT" },
554  #endif
555#endif
556#ifdef SIGKAP
557    {  SIGKAP,      "SIGKAP" },
558#endif
559    {  SIGKILL,     "SIGKILL" },
560#ifdef SIGLOST
561    {  SIGLOST,     "SIGLOST" },
562#endif
563#ifdef SIGLWP
564    {  SIGLWP,      "SIGLWP" },
565#endif
566#ifdef SIGLWPTIMER
567    {  SIGLWPTIMER, "SIGLWPTIMER" },
568#endif
569#ifdef SIGMIGRATE
570    {  SIGMIGRATE,  "SIGMIGRATE" },
571#endif
572#ifdef SIGMSG
573    {  SIGMSG,      "SIGMSG" },
574#endif
575    {  SIGPIPE,     "SIGPIPE" },
576#ifdef SIGPOLL
577    {  SIGPOLL,     "SIGPOLL" },
578#endif
579#ifdef SIGPRE
580    {  SIGPRE,      "SIGPRE" },
581#endif
582    {  SIGPROF,     "SIGPROF" },
583#ifdef SIGPTY
584    {  SIGPTY,      "SIGPTY" },
585#endif
586#ifdef SIGPWR
587    {  SIGPWR,      "SIGPWR" },
588#endif
589    {  SIGQUIT,     "SIGQUIT" },
590#ifdef SIGRECONFIG
591    {  SIGRECONFIG, "SIGRECONFIG" },
592#endif
593#ifdef SIGRECOVERY
594    {  SIGRECOVERY, "SIGRECOVERY" },
595#endif
596#ifdef SIGRESERVE
597    {  SIGRESERVE,  "SIGRESERVE" },
598#endif
599#ifdef SIGRETRACT
600    {  SIGRETRACT,  "SIGRETRACT" },
601#endif
602#ifdef SIGSAK
603    {  SIGSAK,      "SIGSAK" },
604#endif
605    {  SIGSEGV,     "SIGSEGV" },
606#ifdef SIGSOUND
607    {  SIGSOUND,    "SIGSOUND" },
608#endif
609    {  SIGSTOP,     "SIGSTOP" },
610    {  SIGSYS,      "SIGSYS" },
611#ifdef SIGSYSERROR
612    {  SIGSYSERROR, "SIGSYSERROR" },
613#endif
614#ifdef SIGTALRM
615    {  SIGTALRM,    "SIGTALRM" },
616#endif
617    {  SIGTERM,     "SIGTERM" },
618#ifdef SIGTHAW
619    {  SIGTHAW,     "SIGTHAW" },
620#endif
621    {  SIGTRAP,     "SIGTRAP" },
622#ifdef SIGTSTP
623    {  SIGTSTP,     "SIGTSTP" },
624#endif
625    {  SIGTTIN,     "SIGTTIN" },
626    {  SIGTTOU,     "SIGTTOU" },
627#ifdef SIGURG
628    {  SIGURG,      "SIGURG" },
629#endif
630    {  SIGUSR1,     "SIGUSR1" },
631    {  SIGUSR2,     "SIGUSR2" },
632#ifdef SIGVIRT
633    {  SIGVIRT,     "SIGVIRT" },
634#endif
635    {  SIGVTALRM,   "SIGVTALRM" },
636#ifdef SIGWAITING
637    {  SIGWAITING,  "SIGWAITING" },
638#endif
639#ifdef SIGWINCH
640    {  SIGWINCH,    "SIGWINCH" },
641#endif
642#ifdef SIGWINDOW
643    {  SIGWINDOW,   "SIGWINDOW" },
644#endif
645    {  SIGXCPU,     "SIGXCPU" },
646    {  SIGXFSZ,     "SIGXFSZ" },
647#ifdef SIGXRES
648    {  SIGXRES,     "SIGXRES" },
649#endif
650    { -1, NULL }
651  };
652
653  const char* ret = NULL;
654
655#ifdef SIGRTMIN
656  if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
657    if (sig == SIGRTMIN) {
658      ret = "SIGRTMIN";
659    } else if (sig == SIGRTMAX) {
660      ret = "SIGRTMAX";
661    } else {
662      jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
663      return out;
664    }
665  }
666#endif
667
668  if (sig > 0) {
669    for (int idx = 0; info[idx].sig != -1; idx ++) {
670      if (info[idx].sig == sig) {
671        ret = info[idx].name;
672        break;
673      }
674    }
675  }
676
677  if (!ret) {
678    if (!is_valid_signal(sig)) {
679      ret = "INVALID";
680    } else {
681      ret = "UNKNOWN";
682    }
683  }
684
685  if (out && outlen > 0) {
686    strncpy(out, ret, outlen);
687    out[outlen - 1] = '\0';
688  }
689  return out;
690}
691
692// Returns true if signal number is valid.
693bool os::Posix::is_valid_signal(int sig) {
694  // MacOS not really POSIX compliant: sigaddset does not return
695  // an error for invalid signal numbers. However, MacOS does not
696  // support real time signals and simply seems to have just 33
697  // signals with no holes in the signal range.
698#ifdef __APPLE__
699  return sig >= 1 && sig < NSIG;
700#else
701  // Use sigaddset to check for signal validity.
702  sigset_t set;
703  if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
704    return false;
705  }
706  return true;
707#endif
708}
709
710#define NUM_IMPORTANT_SIGS 32
711// Returns one-line short description of a signal set in a user provided buffer.
712const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
713  assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
714  // Note: for shortness, just print out the first 32. That should
715  // cover most of the useful ones, apart from realtime signals.
716  for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
717    const int rc = sigismember(set, sig);
718    if (rc == -1 && errno == EINVAL) {
719      buffer[sig-1] = '?';
720    } else {
721      buffer[sig-1] = rc == 0 ? '0' : '1';
722    }
723  }
724  buffer[NUM_IMPORTANT_SIGS] = 0;
725  return buffer;
726}
727
728// Prints one-line description of a signal set.
729void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
730  char buf[NUM_IMPORTANT_SIGS + 1];
731  os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
732  st->print("%s", buf);
733}
734
735// Writes one-line description of a combination of sigaction.sa_flags into a user
736// provided buffer. Returns that buffer.
737const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
738  char* p = buffer;
739  size_t remaining = size;
740  bool first = true;
741  int idx = 0;
742
743  assert(buffer, "invalid argument");
744
745  if (size == 0) {
746    return buffer;
747  }
748
749  strncpy(buffer, "none", size);
750
751  const struct {
752    int i;
753    const char* s;
754  } flaginfo [] = {
755    { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
756    { SA_ONSTACK,   "SA_ONSTACK"   },
757    { SA_RESETHAND, "SA_RESETHAND" },
758    { SA_RESTART,   "SA_RESTART"   },
759    { SA_SIGINFO,   "SA_SIGINFO"   },
760    { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
761    { SA_NODEFER,   "SA_NODEFER"   },
762#ifdef AIX
763    { SA_ONSTACK,   "SA_ONSTACK"   },
764    { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
765#endif
766    { 0, NULL }
767  };
768
769  for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
770    if (flags & flaginfo[idx].i) {
771      if (first) {
772        jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
773        first = false;
774      } else {
775        jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
776      }
777      const size_t len = strlen(p);
778      p += len;
779      remaining -= len;
780    }
781  }
782
783  buffer[size - 1] = '\0';
784
785  return buffer;
786}
787
788// Prints one-line description of a combination of sigaction.sa_flags.
789void os::Posix::print_sa_flags(outputStream* st, int flags) {
790  char buffer[0x100];
791  os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
792  st->print("%s", buffer);
793}
794
795// Helper function for os::Posix::print_siginfo_...():
796// return a textual description for signal code.
797struct enum_sigcode_desc_t {
798  const char* s_name;
799  const char* s_desc;
800};
801
802static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
803
804  const struct {
805    int sig; int code; const char* s_code; const char* s_desc;
806  } t1 [] = {
807    { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
808    { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
809    { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
810    { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
811    { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
812    { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
813    { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
814    { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
815#if defined(IA64) && defined(LINUX)
816    { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
817    { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
818#endif
819    { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
820    { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
821    { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
822    { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
823    { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
824    { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
825    { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
826    { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
827    { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
828    { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
829#ifdef AIX
830    // no explanation found what keyerr would be
831    { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
832#endif
833#if defined(IA64) && !defined(AIX)
834    { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
835#endif
836    { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
837    { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
838    { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
839    { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
840    { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
841    { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
842    { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
843    { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
844    { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
845    { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
846    { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
847#ifdef SIGPOLL
848    { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
849    { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
850    { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
851    { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
852    { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
853#endif
854    { -1, -1, NULL, NULL }
855  };
856
857  // Codes valid in any signal context.
858  const struct {
859    int code; const char* s_code; const char* s_desc;
860  } t2 [] = {
861    { SI_USER,      "SI_USER",     "Signal sent by kill()." },
862    { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
863    { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
864    { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
865    { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
866    // Linux specific
867#ifdef SI_TKILL
868    { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
869#endif
870#ifdef SI_DETHREAD
871    { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
872#endif
873#ifdef SI_KERNEL
874    { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
875#endif
876#ifdef SI_SIGIO
877    { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
878#endif
879
880#ifdef AIX
881    { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
882    { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
883#endif
884
885#ifdef __sun
886    { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
887    { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
888    { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
889#endif
890
891    { -1, NULL, NULL }
892  };
893
894  const char* s_code = NULL;
895  const char* s_desc = NULL;
896
897  for (int i = 0; t1[i].sig != -1; i ++) {
898    if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
899      s_code = t1[i].s_code;
900      s_desc = t1[i].s_desc;
901      break;
902    }
903  }
904
905  if (s_code == NULL) {
906    for (int i = 0; t2[i].s_code != NULL; i ++) {
907      if (t2[i].code == si->si_code) {
908        s_code = t2[i].s_code;
909        s_desc = t2[i].s_desc;
910      }
911    }
912  }
913
914  if (s_code == NULL) {
915    out->s_name = "unknown";
916    out->s_desc = "unknown";
917    return false;
918  }
919
920  out->s_name = s_code;
921  out->s_desc = s_desc;
922
923  return true;
924}
925
926// A POSIX conform, platform-independend siginfo print routine.
927// Short print out on one line.
928void os::Posix::print_siginfo_brief(outputStream* os, const siginfo_t* si) {
929  char buf[20];
930  os->print("siginfo: ");
931
932  if (!si) {
933    os->print("<null>");
934    return;
935  }
936
937  // See print_siginfo_full() for details.
938  const int sig = si->si_signo;
939
940  os->print("si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
941
942  enum_sigcode_desc_t ed;
943  if (get_signal_code_description(si, &ed)) {
944    os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
945  } else {
946    os->print(", si_code: %d (unknown)", si->si_code);
947  }
948
949  if (si->si_errno) {
950    os->print(", si_errno: %d", si->si_errno);
951  }
952
953  const int me = (int) ::getpid();
954  const int pid = (int) si->si_pid;
955
956  if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
957    if (IS_VALID_PID(pid) && pid != me) {
958      os->print(", sent from pid: %d (uid: %d)", pid, (int) si->si_uid);
959    }
960  } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
961             sig == SIGTRAP || sig == SIGFPE) {
962    os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
963#ifdef SIGPOLL
964  } else if (sig == SIGPOLL) {
965    os->print(", si_band: " PTR64_FORMAT, (uint64_t)si->si_band);
966#endif
967  } else if (sig == SIGCHLD) {
968    os->print_cr(", si_pid: %d, si_uid: %d, si_status: %d", (int) si->si_pid, si->si_uid, si->si_status);
969  }
970}
971
972os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
973  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
974}
975
976/*
977 * See the caveats for this class in os_posix.hpp
978 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
979 * method and returns false. If none of the signals are raised, returns true.
980 * The callback is supposed to provide the method that should be protected.
981 */
982bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
983  sigset_t saved_sig_mask;
984
985  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
986  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
987      "crash_protection already set?");
988
989  // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
990  // since on at least some systems (OS X) siglongjmp will restore the mask
991  // for the process, not the thread
992  pthread_sigmask(0, NULL, &saved_sig_mask);
993  if (sigsetjmp(_jmpbuf, 0) == 0) {
994    // make sure we can see in the signal handler that we have crash protection
995    // installed
996    WatcherThread::watcher_thread()->set_crash_protection(this);
997    cb.call();
998    // and clear the crash protection
999    WatcherThread::watcher_thread()->set_crash_protection(NULL);
1000    return true;
1001  }
1002  // this happens when we siglongjmp() back
1003  pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1004  WatcherThread::watcher_thread()->set_crash_protection(NULL);
1005  return false;
1006}
1007
1008void os::WatcherThreadCrashProtection::restore() {
1009  assert(WatcherThread::watcher_thread()->has_crash_protection(),
1010      "must have crash protection");
1011
1012  siglongjmp(_jmpbuf, 1);
1013}
1014
1015void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
1016    Thread* thread) {
1017
1018  if (thread != NULL &&
1019      thread->is_Watcher_thread() &&
1020      WatcherThread::watcher_thread()->has_crash_protection()) {
1021
1022    if (sig == SIGSEGV || sig == SIGBUS) {
1023      WatcherThread::watcher_thread()->crash_protection()->restore();
1024    }
1025  }
1026}
1027
1028#define check_with_errno(check_type, cond, msg)                             \
1029  do {                                                                      \
1030    int err = errno;                                                        \
1031    check_type(cond, "%s; error='%s' (errno=%d)", msg, strerror(err), err); \
1032} while (false)
1033
1034#define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1035#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1036
1037// POSIX unamed semaphores are not supported on OS X.
1038#ifndef __APPLE__
1039
1040PosixSemaphore::PosixSemaphore(uint value) {
1041  int ret = sem_init(&_semaphore, 0, value);
1042
1043  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1044}
1045
1046PosixSemaphore::~PosixSemaphore() {
1047  sem_destroy(&_semaphore);
1048}
1049
1050void PosixSemaphore::signal(uint count) {
1051  for (uint i = 0; i < count; i++) {
1052    int ret = sem_post(&_semaphore);
1053
1054    assert_with_errno(ret == 0, "sem_post failed");
1055  }
1056}
1057
1058void PosixSemaphore::wait() {
1059  int ret;
1060
1061  do {
1062    ret = sem_wait(&_semaphore);
1063  } while (ret != 0 && errno == EINTR);
1064
1065  assert_with_errno(ret == 0, "sem_wait failed");
1066}
1067
1068bool PosixSemaphore::trywait() {
1069  int ret;
1070
1071  do {
1072    ret = sem_trywait(&_semaphore);
1073  } while (ret != 0 && errno == EINTR);
1074
1075  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1076
1077  return ret == 0;
1078}
1079
1080bool PosixSemaphore::timedwait(struct timespec ts) {
1081  while (true) {
1082    int result = sem_timedwait(&_semaphore, &ts);
1083    if (result == 0) {
1084      return true;
1085    } else if (errno == EINTR) {
1086      continue;
1087    } else if (errno == ETIMEDOUT) {
1088      return false;
1089    } else {
1090      assert_with_errno(false, "timedwait failed");
1091      return false;
1092    }
1093  }
1094}
1095
1096#endif // __APPLE__
1097