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