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