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