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