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