1 /* 2 * Copyright (c) 1999, 2019, 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 "jvm.h" 26 #include "logging/log.hpp" 27 #include "memory/allocation.inline.hpp" 28 #include "os_posix.inline.hpp" 29 #include "utilities/globalDefinitions.hpp" 30 #include "runtime/frame.inline.hpp" 31 #include "runtime/interfaceSupport.inline.hpp" 32 #include "services/memTracker.hpp" 33 #include "utilities/align.hpp" 34 #include "utilities/events.hpp" 35 #include "utilities/formatBuffer.hpp" 36 #include "utilities/macros.hpp" 37 #include "utilities/vmError.hpp" 38 39 #include <dirent.h> 40 #include <dlfcn.h> 41 #include <grp.h> 42 #include <pwd.h> 43 #include <pthread.h> 44 #include <signal.h> 45 #include <sys/mman.h> 46 #include <sys/resource.h> 47 #include <sys/utsname.h> 48 #include <time.h> 49 #include <unistd.h> 50 51 // Todo: provide a os::get_max_process_id() or similar. Number of processes 52 // may have been configured, can be read more accurately from proc fs etc. 53 #ifndef MAX_PID 54 #define MAX_PID INT_MAX 55 #endif 56 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID) 57 58 #define ROOT_UID 0 59 60 #ifndef MAP_ANONYMOUS 61 #define MAP_ANONYMOUS MAP_ANON 62 #endif 63 64 #define check_with_errno(check_type, cond, msg) \ 65 do { \ 66 int err = errno; \ 67 check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err), \ 68 os::errno_name(err)); \ 69 } while (false) 70 71 #define assert_with_errno(cond, msg) check_with_errno(assert, cond, msg) 72 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg) 73 74 // Check core dump limit and report possible place where core can be found 75 void os::check_dump_limit(char* buffer, size_t bufferSize) { 76 if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) { 77 jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line"); 78 VMError::record_coredump_status(buffer, false); 79 return; 80 } 81 82 int n; 83 struct rlimit rlim; 84 bool success; 85 86 char core_path[PATH_MAX]; 87 n = get_core_path(core_path, PATH_MAX); 88 89 if (n <= 0) { 90 jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id()); 91 success = true; 92 #ifdef LINUX 93 } else if (core_path[0] == '"') { // redirect to user process 94 jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path); 95 success = true; 96 #endif 97 } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) { 98 jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path); 99 success = true; 100 } else { 101 switch(rlim.rlim_cur) { 102 case RLIM_INFINITY: 103 jio_snprintf(buffer, bufferSize, "%s", core_path); 104 success = true; 105 break; 106 case 0: 107 jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again"); 108 success = false; 109 break; 110 default: 111 jio_snprintf(buffer, bufferSize, "%s (max size " UINT64_FORMAT " kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, uint64_t(rlim.rlim_cur) / 1024); 112 success = true; 113 break; 114 } 115 } 116 117 VMError::record_coredump_status(buffer, success); 118 } 119 120 int os::get_native_stack(address* stack, int frames, int toSkip) { 121 int frame_idx = 0; 122 int num_of_frames; // number of frames captured 123 frame fr = os::current_frame(); 124 while (fr.pc() && frame_idx < frames) { 125 if (toSkip > 0) { 126 toSkip --; 127 } else { 128 stack[frame_idx ++] = fr.pc(); 129 } 130 if (fr.fp() == NULL || fr.cb() != NULL || 131 fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break; 132 133 if (fr.sender_pc() && !os::is_first_C_frame(&fr)) { 134 fr = os::get_sender_for_C_frame(&fr); 135 } else { 136 break; 137 } 138 } 139 num_of_frames = frame_idx; 140 for (; frame_idx < frames; frame_idx ++) { 141 stack[frame_idx] = NULL; 142 } 143 144 return num_of_frames; 145 } 146 147 148 bool os::unsetenv(const char* name) { 149 assert(name != NULL, "Null pointer"); 150 return (::unsetenv(name) == 0); 151 } 152 153 int os::get_last_error() { 154 return errno; 155 } 156 157 size_t os::lasterror(char *buf, size_t len) { 158 if (errno == 0) return 0; 159 160 const char *s = os::strerror(errno); 161 size_t n = ::strlen(s); 162 if (n >= len) { 163 n = len - 1; 164 } 165 ::strncpy(buf, s, n); 166 buf[n] = '\0'; 167 return n; 168 } 169 170 void os::wait_for_keypress_at_exit(void) { 171 // don't do anything on posix platforms 172 return; 173 } 174 175 int os::create_file_for_heap(const char* dir) { 176 177 const char name_template[] = "/jvmheap.XXXXXX"; 178 179 size_t fullname_len = strlen(dir) + strlen(name_template); 180 char *fullname = (char*)os::malloc(fullname_len + 1, mtInternal); 181 if (fullname == NULL) { 182 vm_exit_during_initialization(err_msg("Malloc failed during creation of backing file for heap (%s)", os::strerror(errno))); 183 return -1; 184 } 185 int n = snprintf(fullname, fullname_len + 1, "%s%s", dir, name_template); 186 assert((size_t)n == fullname_len, "Unexpected number of characters in string"); 187 188 os::native_path(fullname); 189 190 // set the file creation mask. 191 mode_t file_mode = S_IRUSR | S_IWUSR; 192 193 // create a new file. 194 int fd = mkstemp(fullname); 195 196 if (fd < 0) { 197 warning("Could not create file for heap with template %s", fullname); 198 os::free(fullname); 199 return -1; 200 } 201 202 // delete the name from the filesystem. When 'fd' is closed, the file (and space) will be deleted. 203 int ret = unlink(fullname); 204 assert_with_errno(ret == 0, "unlink returned error"); 205 206 os::free(fullname); 207 return fd; 208 } 209 210 static char* reserve_mmapped_memory(size_t bytes, char* requested_addr) { 211 char * addr; 212 int flags = MAP_PRIVATE NOT_AIX( | MAP_NORESERVE ) | MAP_ANONYMOUS; 213 if (requested_addr != NULL) { 214 assert((uintptr_t)requested_addr % os::vm_page_size() == 0, "Requested address should be aligned to OS page size"); 215 flags |= MAP_FIXED; 216 } 217 218 // Map reserved/uncommitted pages PROT_NONE so we fail early if we 219 // touch an uncommitted page. Otherwise, the read/write might 220 // succeed if we have enough swap space to back the physical page. 221 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, 222 flags, -1, 0); 223 224 if (addr != MAP_FAILED) { 225 MemTracker::record_virtual_memory_reserve((address)addr, bytes, CALLER_PC); 226 return addr; 227 } 228 return NULL; 229 } 230 231 static int util_posix_fallocate(int fd, off_t offset, off_t len) { 232 #ifdef __APPLE__ 233 fstore_t store = { F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, len }; 234 // First we try to get a continuous chunk of disk space 235 int ret = fcntl(fd, F_PREALLOCATE, &store); 236 if (ret == -1) { 237 // Maybe we are too fragmented, try to allocate non-continuous range 238 store.fst_flags = F_ALLOCATEALL; 239 ret = fcntl(fd, F_PREALLOCATE, &store); 240 } 241 if(ret != -1) { 242 return ftruncate(fd, len); 243 } 244 return -1; 245 #else 246 return posix_fallocate(fd, offset, len); 247 #endif 248 } 249 250 // Map the given address range to the provided file descriptor. 251 char* os::map_memory_to_file(char* base, size_t size, int fd) { 252 assert(fd != -1, "File descriptor is not valid"); 253 254 // allocate space for the file 255 int ret = util_posix_fallocate(fd, 0, (off_t)size); 256 if (ret != 0) { 257 vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory. error(%d)", ret)); 258 return NULL; 259 } 260 261 int prot = PROT_READ | PROT_WRITE; 262 int flags = MAP_SHARED; 263 if (base != NULL) { 264 flags |= MAP_FIXED; 265 } 266 char* addr = (char*)mmap(base, size, prot, flags, fd, 0); 267 268 if (addr == MAP_FAILED) { 269 warning("Failed mmap to file. (%s)", os::strerror(errno)); 270 return NULL; 271 } 272 if (base != NULL && addr != base) { 273 if (!os::release_memory(addr, size)) { 274 warning("Could not release memory on unsuccessful file mapping"); 275 } 276 return NULL; 277 } 278 return addr; 279 } 280 281 char* os::replace_existing_mapping_with_file_mapping(char* base, size_t size, int fd) { 282 assert(fd != -1, "File descriptor is not valid"); 283 assert(base != NULL, "Base cannot be NULL"); 284 285 return map_memory_to_file(base, size, fd); 286 } 287 288 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED, 289 // so on posix, unmap the section at the start and at the end of the chunk that we mapped 290 // rather than unmapping and remapping the whole chunk to get requested alignment. 291 char* os::reserve_memory_aligned(size_t size, size_t alignment, int file_desc) { 292 assert((alignment & (os::vm_allocation_granularity() - 1)) == 0, 293 "Alignment must be a multiple of allocation granularity (page size)"); 294 assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned"); 295 296 size_t extra_size = size + alignment; 297 assert(extra_size >= size, "overflow, size is too large to allow alignment"); 298 299 char* extra_base; 300 if (file_desc != -1) { 301 // For file mapping, we do not call os:reserve_memory(extra_size, NULL, alignment, file_desc) because 302 // we need to deal with shrinking of the file space later when we release extra memory after alignment. 303 // We also cannot called os:reserve_memory() with file_desc set to -1 because on aix we might get SHM memory. 304 // So here to call a helper function while reserve memory for us. After we have a aligned base, 305 // we will replace anonymous mapping with file mapping. 306 extra_base = reserve_mmapped_memory(extra_size, NULL); 307 if (extra_base != NULL) { 308 MemTracker::record_virtual_memory_reserve((address)extra_base, extra_size, CALLER_PC); 309 } 310 } else { 311 extra_base = os::reserve_memory(extra_size, NULL, alignment); 312 } 313 314 if (extra_base == NULL) { 315 return NULL; 316 } 317 318 // Do manual alignment 319 char* aligned_base = align_up(extra_base, alignment); 320 321 // [ | | ] 322 // ^ extra_base 323 // ^ extra_base + begin_offset == aligned_base 324 // extra_base + begin_offset + size ^ 325 // extra_base + extra_size ^ 326 // |<>| == begin_offset 327 // end_offset == |<>| 328 size_t begin_offset = aligned_base - extra_base; 329 size_t end_offset = (extra_base + extra_size) - (aligned_base + size); 330 331 if (begin_offset > 0) { 332 os::release_memory(extra_base, begin_offset); 333 } 334 335 if (end_offset > 0) { 336 os::release_memory(extra_base + begin_offset + size, end_offset); 337 } 338 339 if (file_desc != -1) { 340 // After we have an aligned address, we can replace anonymous mapping with file mapping 341 if (replace_existing_mapping_with_file_mapping(aligned_base, size, file_desc) == NULL) { 342 vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory")); 343 } 344 MemTracker::record_virtual_memory_commit((address)aligned_base, size, CALLER_PC); 345 } 346 return aligned_base; 347 } 348 349 int os::vsnprintf(char* buf, size_t len, const char* fmt, va_list args) { 350 // All supported POSIX platforms provide C99 semantics. 351 int result = ::vsnprintf(buf, len, fmt, args); 352 // If an encoding error occurred (result < 0) then it's not clear 353 // whether the buffer is NUL terminated, so ensure it is. 354 if ((result < 0) && (len > 0)) { 355 buf[len - 1] = '\0'; 356 } 357 return result; 358 } 359 360 int os::get_fileno(FILE* fp) { 361 return NOT_AIX(::)fileno(fp); 362 } 363 364 struct tm* os::gmtime_pd(const time_t* clock, struct tm* res) { 365 return gmtime_r(clock, res); 366 } 367 368 void os::Posix::print_load_average(outputStream* st) { 369 st->print("load average:"); 370 double loadavg[3]; 371 int res = os::loadavg(loadavg, 3); 372 if (res != -1) { 373 st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); 374 } else { 375 st->print(" Unavailable"); 376 } 377 st->cr(); 378 } 379 380 void os::Posix::print_rlimit_info(outputStream* st) { 381 st->print("rlimit:"); 382 struct rlimit rlim; 383 384 st->print(" STACK "); 385 getrlimit(RLIMIT_STACK, &rlim); 386 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 387 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 388 389 st->print(", CORE "); 390 getrlimit(RLIMIT_CORE, &rlim); 391 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 392 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 393 394 // Isn't there on solaris 395 #if defined(AIX) 396 st->print(", NPROC "); 397 st->print("%d", sysconf(_SC_CHILD_MAX)); 398 #elif !defined(SOLARIS) 399 st->print(", NPROC "); 400 getrlimit(RLIMIT_NPROC, &rlim); 401 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 402 else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur)); 403 #endif 404 405 st->print(", NOFILE "); 406 getrlimit(RLIMIT_NOFILE, &rlim); 407 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 408 else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur)); 409 410 st->print(", AS "); 411 getrlimit(RLIMIT_AS, &rlim); 412 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 413 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 414 415 st->print(", DATA "); 416 getrlimit(RLIMIT_DATA, &rlim); 417 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 418 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 419 420 st->print(", FSIZE "); 421 getrlimit(RLIMIT_FSIZE, &rlim); 422 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 423 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 424 425 st->cr(); 426 } 427 428 void os::Posix::print_uname_info(outputStream* st) { 429 // kernel 430 st->print("uname:"); 431 struct utsname name; 432 uname(&name); 433 st->print("%s ", name.sysname); 434 #ifdef ASSERT 435 st->print("%s ", name.nodename); 436 #endif 437 st->print("%s ", name.release); 438 st->print("%s ", name.version); 439 st->print("%s", name.machine); 440 st->cr(); 441 } 442 443 void os::Posix::print_umask(outputStream* st, mode_t umsk) { 444 st->print((umsk & S_IRUSR) ? "r" : "-"); 445 st->print((umsk & S_IWUSR) ? "w" : "-"); 446 st->print((umsk & S_IXUSR) ? "x" : "-"); 447 st->print((umsk & S_IRGRP) ? "r" : "-"); 448 st->print((umsk & S_IWGRP) ? "w" : "-"); 449 st->print((umsk & S_IXGRP) ? "x" : "-"); 450 st->print((umsk & S_IROTH) ? "r" : "-"); 451 st->print((umsk & S_IWOTH) ? "w" : "-"); 452 st->print((umsk & S_IXOTH) ? "x" : "-"); 453 } 454 455 void os::Posix::print_user_info(outputStream* st) { 456 unsigned id = (unsigned) ::getuid(); 457 st->print("uid : %u ", id); 458 id = (unsigned) ::geteuid(); 459 st->print("euid : %u ", id); 460 id = (unsigned) ::getgid(); 461 st->print("gid : %u ", id); 462 id = (unsigned) ::getegid(); 463 st->print_cr("egid : %u", id); 464 st->cr(); 465 466 mode_t umsk = ::umask(0); 467 ::umask(umsk); 468 st->print("umask: %04o (", (unsigned) umsk); 469 print_umask(st, umsk); 470 st->print_cr(")"); 471 st->cr(); 472 } 473 474 475 bool os::get_host_name(char* buf, size_t buflen) { 476 struct utsname name; 477 uname(&name); 478 jio_snprintf(buf, buflen, "%s", name.nodename); 479 return true; 480 } 481 482 bool os::has_allocatable_memory_limit(julong* limit) { 483 struct rlimit rlim; 484 int getrlimit_res = getrlimit(RLIMIT_AS, &rlim); 485 // if there was an error when calling getrlimit, assume that there is no limitation 486 // on virtual memory. 487 bool result; 488 if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) { 489 result = false; 490 } else { 491 *limit = (julong)rlim.rlim_cur; 492 result = true; 493 } 494 #ifdef _LP64 495 return result; 496 #else 497 // arbitrary virtual space limit for 32 bit Unices found by testing. If 498 // getrlimit above returned a limit, bound it with this limit. Otherwise 499 // directly use it. 500 const julong max_virtual_limit = (julong)3800*M; 501 if (result) { 502 *limit = MIN2(*limit, max_virtual_limit); 503 } else { 504 *limit = max_virtual_limit; 505 } 506 507 // bound by actually allocatable memory. The algorithm uses two bounds, an 508 // upper and a lower limit. The upper limit is the current highest amount of 509 // memory that could not be allocated, the lower limit is the current highest 510 // amount of memory that could be allocated. 511 // The algorithm iteratively refines the result by halving the difference 512 // between these limits, updating either the upper limit (if that value could 513 // not be allocated) or the lower limit (if the that value could be allocated) 514 // until the difference between these limits is "small". 515 516 // the minimum amount of memory we care about allocating. 517 const julong min_allocation_size = M; 518 519 julong upper_limit = *limit; 520 521 // first check a few trivial cases 522 if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) { 523 *limit = upper_limit; 524 } else if (!is_allocatable(min_allocation_size)) { 525 // we found that not even min_allocation_size is allocatable. Return it 526 // anyway. There is no point to search for a better value any more. 527 *limit = min_allocation_size; 528 } else { 529 // perform the binary search. 530 julong lower_limit = min_allocation_size; 531 while ((upper_limit - lower_limit) > min_allocation_size) { 532 julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit; 533 temp_limit = align_down(temp_limit, min_allocation_size); 534 if (is_allocatable(temp_limit)) { 535 lower_limit = temp_limit; 536 } else { 537 upper_limit = temp_limit; 538 } 539 } 540 *limit = lower_limit; 541 } 542 return true; 543 #endif 544 } 545 546 const char* os::get_current_directory(char *buf, size_t buflen) { 547 return getcwd(buf, buflen); 548 } 549 550 FILE* os::open(int fd, const char* mode) { 551 return ::fdopen(fd, mode); 552 } 553 554 ssize_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { 555 return ::pread(fd, buf, nBytes, offset); 556 } 557 558 void os::flockfile(FILE* fp) { 559 ::flockfile(fp); 560 } 561 562 void os::funlockfile(FILE* fp) { 563 ::funlockfile(fp); 564 } 565 566 DIR* os::opendir(const char* dirname) { 567 assert(dirname != NULL, "just checking"); 568 return ::opendir(dirname); 569 } 570 571 struct dirent* os::readdir(DIR* dirp) { 572 assert(dirp != NULL, "just checking"); 573 return ::readdir(dirp); 574 } 575 576 int os::closedir(DIR *dirp) { 577 assert(dirp != NULL, "just checking"); 578 return ::closedir(dirp); 579 } 580 581 // Builds a platform dependent Agent_OnLoad_<lib_name> function name 582 // which is used to find statically linked in agents. 583 // Parameters: 584 // sym_name: Symbol in library we are looking for 585 // lib_name: Name of library to look in, NULL for shared libs. 586 // is_absolute_path == true if lib_name is absolute path to agent 587 // such as "/a/b/libL.so" 588 // == false if only the base name of the library is passed in 589 // such as "L" 590 char* os::build_agent_function_name(const char *sym_name, const char *lib_name, 591 bool is_absolute_path) { 592 char *agent_entry_name; 593 size_t len; 594 size_t name_len; 595 size_t prefix_len = strlen(JNI_LIB_PREFIX); 596 size_t suffix_len = strlen(JNI_LIB_SUFFIX); 597 const char *start; 598 599 if (lib_name != NULL) { 600 name_len = strlen(lib_name); 601 if (is_absolute_path) { 602 // Need to strip path, prefix and suffix 603 if ((start = strrchr(lib_name, *os::file_separator())) != NULL) { 604 lib_name = ++start; 605 } 606 if (strlen(lib_name) <= (prefix_len + suffix_len)) { 607 return NULL; 608 } 609 lib_name += prefix_len; 610 name_len = strlen(lib_name) - suffix_len; 611 } 612 } 613 len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2; 614 agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread); 615 if (agent_entry_name == NULL) { 616 return NULL; 617 } 618 strcpy(agent_entry_name, sym_name); 619 if (lib_name != NULL) { 620 strcat(agent_entry_name, "_"); 621 strncat(agent_entry_name, lib_name, name_len); 622 } 623 return agent_entry_name; 624 } 625 626 627 void os::naked_short_nanosleep(jlong ns) { 628 struct timespec req; 629 assert(ns > -1 && ns < NANOUNITS, "Un-interruptable sleep, short time use only"); 630 req.tv_sec = 0; 631 req.tv_nsec = ns; 632 ::nanosleep(&req, NULL); 633 return; 634 } 635 636 void os::naked_short_sleep(jlong ms) { 637 assert(ms < MILLIUNITS, "Un-interruptable sleep, short time use only"); 638 os::naked_short_nanosleep(ms * (NANOUNITS / MILLIUNITS)); 639 return; 640 } 641 642 static const struct { 643 int sig; const char* name; 644 } 645 g_signal_info[] = 646 { 647 { SIGABRT, "SIGABRT" }, 648 #ifdef SIGAIO 649 { SIGAIO, "SIGAIO" }, 650 #endif 651 { SIGALRM, "SIGALRM" }, 652 #ifdef SIGALRM1 653 { SIGALRM1, "SIGALRM1" }, 654 #endif 655 { SIGBUS, "SIGBUS" }, 656 #ifdef SIGCANCEL 657 { SIGCANCEL, "SIGCANCEL" }, 658 #endif 659 { SIGCHLD, "SIGCHLD" }, 660 #ifdef SIGCLD 661 { SIGCLD, "SIGCLD" }, 662 #endif 663 { SIGCONT, "SIGCONT" }, 664 #ifdef SIGCPUFAIL 665 { SIGCPUFAIL, "SIGCPUFAIL" }, 666 #endif 667 #ifdef SIGDANGER 668 { SIGDANGER, "SIGDANGER" }, 669 #endif 670 #ifdef SIGDIL 671 { SIGDIL, "SIGDIL" }, 672 #endif 673 #ifdef SIGEMT 674 { SIGEMT, "SIGEMT" }, 675 #endif 676 { SIGFPE, "SIGFPE" }, 677 #ifdef SIGFREEZE 678 { SIGFREEZE, "SIGFREEZE" }, 679 #endif 680 #ifdef SIGGFAULT 681 { SIGGFAULT, "SIGGFAULT" }, 682 #endif 683 #ifdef SIGGRANT 684 { SIGGRANT, "SIGGRANT" }, 685 #endif 686 { SIGHUP, "SIGHUP" }, 687 { SIGILL, "SIGILL" }, 688 { SIGINT, "SIGINT" }, 689 #ifdef SIGIO 690 { SIGIO, "SIGIO" }, 691 #endif 692 #ifdef SIGIOINT 693 { SIGIOINT, "SIGIOINT" }, 694 #endif 695 #ifdef SIGIOT 696 // SIGIOT is there for BSD compatibility, but on most Unices just a 697 // synonym for SIGABRT. The result should be "SIGABRT", not 698 // "SIGIOT". 699 #if (SIGIOT != SIGABRT ) 700 { SIGIOT, "SIGIOT" }, 701 #endif 702 #endif 703 #ifdef SIGKAP 704 { SIGKAP, "SIGKAP" }, 705 #endif 706 { SIGKILL, "SIGKILL" }, 707 #ifdef SIGLOST 708 { SIGLOST, "SIGLOST" }, 709 #endif 710 #ifdef SIGLWP 711 { SIGLWP, "SIGLWP" }, 712 #endif 713 #ifdef SIGLWPTIMER 714 { SIGLWPTIMER, "SIGLWPTIMER" }, 715 #endif 716 #ifdef SIGMIGRATE 717 { SIGMIGRATE, "SIGMIGRATE" }, 718 #endif 719 #ifdef SIGMSG 720 { SIGMSG, "SIGMSG" }, 721 #endif 722 { SIGPIPE, "SIGPIPE" }, 723 #ifdef SIGPOLL 724 { SIGPOLL, "SIGPOLL" }, 725 #endif 726 #ifdef SIGPRE 727 { SIGPRE, "SIGPRE" }, 728 #endif 729 { SIGPROF, "SIGPROF" }, 730 #ifdef SIGPTY 731 { SIGPTY, "SIGPTY" }, 732 #endif 733 #ifdef SIGPWR 734 { SIGPWR, "SIGPWR" }, 735 #endif 736 { SIGQUIT, "SIGQUIT" }, 737 #ifdef SIGRECONFIG 738 { SIGRECONFIG, "SIGRECONFIG" }, 739 #endif 740 #ifdef SIGRECOVERY 741 { SIGRECOVERY, "SIGRECOVERY" }, 742 #endif 743 #ifdef SIGRESERVE 744 { SIGRESERVE, "SIGRESERVE" }, 745 #endif 746 #ifdef SIGRETRACT 747 { SIGRETRACT, "SIGRETRACT" }, 748 #endif 749 #ifdef SIGSAK 750 { SIGSAK, "SIGSAK" }, 751 #endif 752 { SIGSEGV, "SIGSEGV" }, 753 #ifdef SIGSOUND 754 { SIGSOUND, "SIGSOUND" }, 755 #endif 756 #ifdef SIGSTKFLT 757 { SIGSTKFLT, "SIGSTKFLT" }, 758 #endif 759 { SIGSTOP, "SIGSTOP" }, 760 { SIGSYS, "SIGSYS" }, 761 #ifdef SIGSYSERROR 762 { SIGSYSERROR, "SIGSYSERROR" }, 763 #endif 764 #ifdef SIGTALRM 765 { SIGTALRM, "SIGTALRM" }, 766 #endif 767 { SIGTERM, "SIGTERM" }, 768 #ifdef SIGTHAW 769 { SIGTHAW, "SIGTHAW" }, 770 #endif 771 { SIGTRAP, "SIGTRAP" }, 772 #ifdef SIGTSTP 773 { SIGTSTP, "SIGTSTP" }, 774 #endif 775 { SIGTTIN, "SIGTTIN" }, 776 { SIGTTOU, "SIGTTOU" }, 777 #ifdef SIGURG 778 { SIGURG, "SIGURG" }, 779 #endif 780 { SIGUSR1, "SIGUSR1" }, 781 { SIGUSR2, "SIGUSR2" }, 782 #ifdef SIGVIRT 783 { SIGVIRT, "SIGVIRT" }, 784 #endif 785 { SIGVTALRM, "SIGVTALRM" }, 786 #ifdef SIGWAITING 787 { SIGWAITING, "SIGWAITING" }, 788 #endif 789 #ifdef SIGWINCH 790 { SIGWINCH, "SIGWINCH" }, 791 #endif 792 #ifdef SIGWINDOW 793 { SIGWINDOW, "SIGWINDOW" }, 794 #endif 795 { SIGXCPU, "SIGXCPU" }, 796 { SIGXFSZ, "SIGXFSZ" }, 797 #ifdef SIGXRES 798 { SIGXRES, "SIGXRES" }, 799 #endif 800 { -1, NULL } 801 }; 802 803 // Returned string is a constant. For unknown signals "UNKNOWN" is returned. 804 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) { 805 806 const char* ret = NULL; 807 808 #ifdef SIGRTMIN 809 if (sig >= SIGRTMIN && sig <= SIGRTMAX) { 810 if (sig == SIGRTMIN) { 811 ret = "SIGRTMIN"; 812 } else if (sig == SIGRTMAX) { 813 ret = "SIGRTMAX"; 814 } else { 815 jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN); 816 return out; 817 } 818 } 819 #endif 820 821 if (sig > 0) { 822 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 823 if (g_signal_info[idx].sig == sig) { 824 ret = g_signal_info[idx].name; 825 break; 826 } 827 } 828 } 829 830 if (!ret) { 831 if (!is_valid_signal(sig)) { 832 ret = "INVALID"; 833 } else { 834 ret = "UNKNOWN"; 835 } 836 } 837 838 if (out && outlen > 0) { 839 strncpy(out, ret, outlen); 840 out[outlen - 1] = '\0'; 841 } 842 return out; 843 } 844 845 int os::Posix::get_signal_number(const char* signal_name) { 846 char tmp[30]; 847 const char* s = signal_name; 848 if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') { 849 jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name); 850 s = tmp; 851 } 852 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 853 if (strcmp(g_signal_info[idx].name, s) == 0) { 854 return g_signal_info[idx].sig; 855 } 856 } 857 return -1; 858 } 859 860 int os::get_signal_number(const char* signal_name) { 861 return os::Posix::get_signal_number(signal_name); 862 } 863 864 // Returns true if signal number is valid. 865 bool os::Posix::is_valid_signal(int sig) { 866 // MacOS not really POSIX compliant: sigaddset does not return 867 // an error for invalid signal numbers. However, MacOS does not 868 // support real time signals and simply seems to have just 33 869 // signals with no holes in the signal range. 870 #ifdef __APPLE__ 871 return sig >= 1 && sig < NSIG; 872 #else 873 // Use sigaddset to check for signal validity. 874 sigset_t set; 875 sigemptyset(&set); 876 if (sigaddset(&set, sig) == -1 && errno == EINVAL) { 877 return false; 878 } 879 return true; 880 #endif 881 } 882 883 bool os::Posix::is_sig_ignored(int sig) { 884 struct sigaction oact; 885 sigaction(sig, (struct sigaction*)NULL, &oact); 886 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 887 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 888 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) { 889 return true; 890 } else { 891 return false; 892 } 893 } 894 895 // Returns: 896 // NULL for an invalid signal number 897 // "SIG<num>" for a valid but unknown signal number 898 // signal name otherwise. 899 const char* os::exception_name(int sig, char* buf, size_t size) { 900 if (!os::Posix::is_valid_signal(sig)) { 901 return NULL; 902 } 903 const char* const name = os::Posix::get_signal_name(sig, buf, size); 904 if (strcmp(name, "UNKNOWN") == 0) { 905 jio_snprintf(buf, size, "SIG%d", sig); 906 } 907 return buf; 908 } 909 910 #define NUM_IMPORTANT_SIGS 32 911 // Returns one-line short description of a signal set in a user provided buffer. 912 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) { 913 assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size"); 914 // Note: for shortness, just print out the first 32. That should 915 // cover most of the useful ones, apart from realtime signals. 916 for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) { 917 const int rc = sigismember(set, sig); 918 if (rc == -1 && errno == EINVAL) { 919 buffer[sig-1] = '?'; 920 } else { 921 buffer[sig-1] = rc == 0 ? '0' : '1'; 922 } 923 } 924 buffer[NUM_IMPORTANT_SIGS] = 0; 925 return buffer; 926 } 927 928 // Prints one-line description of a signal set. 929 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) { 930 char buf[NUM_IMPORTANT_SIGS + 1]; 931 os::Posix::describe_signal_set_short(set, buf, sizeof(buf)); 932 st->print("%s", buf); 933 } 934 935 // Writes one-line description of a combination of sigaction.sa_flags into a user 936 // provided buffer. Returns that buffer. 937 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) { 938 char* p = buffer; 939 size_t remaining = size; 940 bool first = true; 941 int idx = 0; 942 943 assert(buffer, "invalid argument"); 944 945 if (size == 0) { 946 return buffer; 947 } 948 949 strncpy(buffer, "none", size); 950 951 const struct { 952 // NB: i is an unsigned int here because SA_RESETHAND is on some 953 // systems 0x80000000, which is implicitly unsigned. Assignining 954 // it to an int field would be an overflow in unsigned-to-signed 955 // conversion. 956 unsigned int i; 957 const char* s; 958 } flaginfo [] = { 959 { SA_NOCLDSTOP, "SA_NOCLDSTOP" }, 960 { SA_ONSTACK, "SA_ONSTACK" }, 961 { SA_RESETHAND, "SA_RESETHAND" }, 962 { SA_RESTART, "SA_RESTART" }, 963 { SA_SIGINFO, "SA_SIGINFO" }, 964 { SA_NOCLDWAIT, "SA_NOCLDWAIT" }, 965 { SA_NODEFER, "SA_NODEFER" }, 966 #ifdef AIX 967 { SA_ONSTACK, "SA_ONSTACK" }, 968 { SA_OLDSTYLE, "SA_OLDSTYLE" }, 969 #endif 970 { 0, NULL } 971 }; 972 973 for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) { 974 if (flags & flaginfo[idx].i) { 975 if (first) { 976 jio_snprintf(p, remaining, "%s", flaginfo[idx].s); 977 first = false; 978 } else { 979 jio_snprintf(p, remaining, "|%s", flaginfo[idx].s); 980 } 981 const size_t len = strlen(p); 982 p += len; 983 remaining -= len; 984 } 985 } 986 987 buffer[size - 1] = '\0'; 988 989 return buffer; 990 } 991 992 // Prints one-line description of a combination of sigaction.sa_flags. 993 void os::Posix::print_sa_flags(outputStream* st, int flags) { 994 char buffer[0x100]; 995 os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer)); 996 st->print("%s", buffer); 997 } 998 999 // Helper function for os::Posix::print_siginfo_...(): 1000 // return a textual description for signal code. 1001 struct enum_sigcode_desc_t { 1002 const char* s_name; 1003 const char* s_desc; 1004 }; 1005 1006 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) { 1007 1008 const struct { 1009 int sig; int code; const char* s_code; const char* s_desc; 1010 } t1 [] = { 1011 { SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode." }, 1012 { SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand." }, 1013 { SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode." }, 1014 { SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap." }, 1015 { SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode." }, 1016 { SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register." }, 1017 { SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error." }, 1018 { SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error." }, 1019 #if defined(IA64) && defined(LINUX) 1020 { SIGILL, ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" }, 1021 { SIGILL, ILL_BREAK, "ILL_BREAK", "Application Break instruction" }, 1022 #endif 1023 { SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero." }, 1024 { SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow." }, 1025 { SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating-point divide by zero." }, 1026 { SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating-point overflow." }, 1027 { SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating-point underflow." }, 1028 { SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating-point inexact result." }, 1029 { SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating-point operation." }, 1030 { SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range." }, 1031 { SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object." }, 1032 { SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for mapped object." }, 1033 #ifdef AIX 1034 // no explanation found what keyerr would be 1035 { SIGSEGV, SEGV_KEYERR, "SEGV_KEYERR", "key error" }, 1036 #endif 1037 #if defined(IA64) && !defined(AIX) 1038 { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" }, 1039 #endif 1040 #if defined(__sparc) && defined(SOLARIS) 1041 // define Solaris Sparc M7 ADI SEGV signals 1042 #if !defined(SEGV_ACCADI) 1043 #define SEGV_ACCADI 3 1044 #endif 1045 { SIGSEGV, SEGV_ACCADI, "SEGV_ACCADI", "ADI not enabled for mapped object." }, 1046 #if !defined(SEGV_ACCDERR) 1047 #define SEGV_ACCDERR 4 1048 #endif 1049 { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." }, 1050 #if !defined(SEGV_ACCPERR) 1051 #define SEGV_ACCPERR 5 1052 #endif 1053 { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." }, 1054 #endif // defined(__sparc) && defined(SOLARIS) 1055 { SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment." }, 1056 { SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Nonexistent physical address." }, 1057 { SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object-specific hardware error." }, 1058 { SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint." }, 1059 { SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap." }, 1060 { SIGCHLD, CLD_EXITED, "CLD_EXITED", "Child has exited." }, 1061 { SIGCHLD, CLD_KILLED, "CLD_KILLED", "Child has terminated abnormally and did not create a core file." }, 1062 { SIGCHLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally and created a core file." }, 1063 { SIGCHLD, CLD_TRAPPED, "CLD_TRAPPED", "Traced child has trapped." }, 1064 { SIGCHLD, CLD_STOPPED, "CLD_STOPPED", "Child has stopped." }, 1065 { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." }, 1066 #ifdef SIGPOLL 1067 { SIGPOLL, POLL_OUT, "POLL_OUT", "Output buffers available." }, 1068 { SIGPOLL, POLL_MSG, "POLL_MSG", "Input message available." }, 1069 { SIGPOLL, POLL_ERR, "POLL_ERR", "I/O error." }, 1070 { SIGPOLL, POLL_PRI, "POLL_PRI", "High priority input available." }, 1071 { SIGPOLL, POLL_HUP, "POLL_HUP", "Device disconnected. [Option End]" }, 1072 #endif 1073 { -1, -1, NULL, NULL } 1074 }; 1075 1076 // Codes valid in any signal context. 1077 const struct { 1078 int code; const char* s_code; const char* s_desc; 1079 } t2 [] = { 1080 { SI_USER, "SI_USER", "Signal sent by kill()." }, 1081 { SI_QUEUE, "SI_QUEUE", "Signal sent by the sigqueue()." }, 1082 { SI_TIMER, "SI_TIMER", "Signal generated by expiration of a timer set by timer_settime()." }, 1083 { SI_ASYNCIO, "SI_ASYNCIO", "Signal generated by completion of an asynchronous I/O request." }, 1084 { SI_MESGQ, "SI_MESGQ", "Signal generated by arrival of a message on an empty message queue." }, 1085 // Linux specific 1086 #ifdef SI_TKILL 1087 { SI_TKILL, "SI_TKILL", "Signal sent by tkill (pthread_kill)" }, 1088 #endif 1089 #ifdef SI_DETHREAD 1090 { SI_DETHREAD, "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" }, 1091 #endif 1092 #ifdef SI_KERNEL 1093 { SI_KERNEL, "SI_KERNEL", "Signal sent by kernel." }, 1094 #endif 1095 #ifdef SI_SIGIO 1096 { SI_SIGIO, "SI_SIGIO", "Signal sent by queued SIGIO" }, 1097 #endif 1098 1099 #ifdef AIX 1100 { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" }, 1101 { SI_EMPTY, "SI_EMPTY", "siginfo contains no useful information" }, 1102 #endif 1103 1104 #ifdef __sun 1105 { SI_NOINFO, "SI_NOINFO", "No signal information" }, 1106 { SI_RCTL, "SI_RCTL", "kernel generated signal via rctl action" }, 1107 { SI_LWP, "SI_LWP", "Signal sent via lwp_kill" }, 1108 #endif 1109 1110 { -1, NULL, NULL } 1111 }; 1112 1113 const char* s_code = NULL; 1114 const char* s_desc = NULL; 1115 1116 for (int i = 0; t1[i].sig != -1; i ++) { 1117 if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) { 1118 s_code = t1[i].s_code; 1119 s_desc = t1[i].s_desc; 1120 break; 1121 } 1122 } 1123 1124 if (s_code == NULL) { 1125 for (int i = 0; t2[i].s_code != NULL; i ++) { 1126 if (t2[i].code == si->si_code) { 1127 s_code = t2[i].s_code; 1128 s_desc = t2[i].s_desc; 1129 } 1130 } 1131 } 1132 1133 if (s_code == NULL) { 1134 out->s_name = "unknown"; 1135 out->s_desc = "unknown"; 1136 return false; 1137 } 1138 1139 out->s_name = s_code; 1140 out->s_desc = s_desc; 1141 1142 return true; 1143 } 1144 1145 bool os::signal_sent_by_kill(const void* siginfo) { 1146 const siginfo_t* const si = (const siginfo_t*)siginfo; 1147 return si->si_code == SI_USER || si->si_code == SI_QUEUE 1148 #ifdef SI_TKILL 1149 || si->si_code == SI_TKILL 1150 #endif 1151 ; 1152 } 1153 1154 void os::print_siginfo(outputStream* os, const void* si0) { 1155 1156 const siginfo_t* const si = (const siginfo_t*) si0; 1157 1158 char buf[20]; 1159 os->print("siginfo:"); 1160 1161 if (!si) { 1162 os->print(" <null>"); 1163 return; 1164 } 1165 1166 const int sig = si->si_signo; 1167 1168 os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf))); 1169 1170 enum_sigcode_desc_t ed; 1171 get_signal_code_description(si, &ed); 1172 os->print(", si_code: %d (%s)", si->si_code, ed.s_name); 1173 1174 if (si->si_errno) { 1175 os->print(", si_errno: %d", si->si_errno); 1176 } 1177 1178 // Output additional information depending on the signal code. 1179 1180 // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions, 1181 // so it depends on the context which member to use. For synchronous error signals, 1182 // we print si_addr, unless the signal was sent by another process or thread, in 1183 // which case we print out pid or tid of the sender. 1184 if (signal_sent_by_kill(si)) { 1185 const pid_t pid = si->si_pid; 1186 os->print(", si_pid: %ld", (long) pid); 1187 if (IS_VALID_PID(pid)) { 1188 const pid_t me = getpid(); 1189 if (me == pid) { 1190 os->print(" (current process)"); 1191 } 1192 } else { 1193 os->print(" (invalid)"); 1194 } 1195 os->print(", si_uid: %ld", (long) si->si_uid); 1196 if (sig == SIGCHLD) { 1197 os->print(", si_status: %d", si->si_status); 1198 } 1199 } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || 1200 sig == SIGTRAP || sig == SIGFPE) { 1201 os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr)); 1202 #ifdef SIGPOLL 1203 } else if (sig == SIGPOLL) { 1204 os->print(", si_band: %ld", si->si_band); 1205 #endif 1206 } 1207 1208 } 1209 1210 bool os::signal_thread(Thread* thread, int sig, const char* reason) { 1211 OSThread* osthread = thread->osthread(); 1212 if (osthread) { 1213 #if defined (SOLARIS) 1214 // Note: we cannot use pthread_kill on Solaris - not because 1215 // its missing, but because we do not have the pthread_t id. 1216 int status = thr_kill(osthread->thread_id(), sig); 1217 #else 1218 int status = pthread_kill(osthread->pthread_id(), sig); 1219 #endif 1220 if (status == 0) { 1221 Events::log(Thread::current(), "sent signal %d to Thread " INTPTR_FORMAT " because %s.", 1222 sig, p2i(thread), reason); 1223 return true; 1224 } 1225 } 1226 return false; 1227 } 1228 1229 int os::Posix::unblock_thread_signal_mask(const sigset_t *set) { 1230 return pthread_sigmask(SIG_UNBLOCK, set, NULL); 1231 } 1232 1233 address os::Posix::ucontext_get_pc(const ucontext_t* ctx) { 1234 #if defined(AIX) 1235 return Aix::ucontext_get_pc(ctx); 1236 #elif defined(BSD) 1237 return Bsd::ucontext_get_pc(ctx); 1238 #elif defined(LINUX) 1239 return Linux::ucontext_get_pc(ctx); 1240 #elif defined(SOLARIS) 1241 return Solaris::ucontext_get_pc(ctx); 1242 #else 1243 VMError::report_and_die("unimplemented ucontext_get_pc"); 1244 #endif 1245 } 1246 1247 void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) { 1248 #if defined(AIX) 1249 Aix::ucontext_set_pc(ctx, pc); 1250 #elif defined(BSD) 1251 Bsd::ucontext_set_pc(ctx, pc); 1252 #elif defined(LINUX) 1253 Linux::ucontext_set_pc(ctx, pc); 1254 #elif defined(SOLARIS) 1255 Solaris::ucontext_set_pc(ctx, pc); 1256 #else 1257 VMError::report_and_die("unimplemented ucontext_get_pc"); 1258 #endif 1259 } 1260 1261 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) { 1262 size_t stack_size = 0; 1263 size_t guard_size = 0; 1264 int detachstate = 0; 1265 pthread_attr_getstacksize(attr, &stack_size); 1266 pthread_attr_getguardsize(attr, &guard_size); 1267 // Work around linux NPTL implementation error, see also os::create_thread() in os_linux.cpp. 1268 LINUX_ONLY(stack_size -= guard_size); 1269 pthread_attr_getdetachstate(attr, &detachstate); 1270 jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s", 1271 stack_size / 1024, guard_size / 1024, 1272 (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable")); 1273 return buf; 1274 } 1275 1276 char* os::Posix::realpath(const char* filename, char* outbuf, size_t outbuflen) { 1277 1278 if (filename == NULL || outbuf == NULL || outbuflen < 1) { 1279 assert(false, "os::Posix::realpath: invalid arguments."); 1280 errno = EINVAL; 1281 return NULL; 1282 } 1283 1284 char* result = NULL; 1285 1286 // This assumes platform realpath() is implemented according to POSIX.1-2008. 1287 // POSIX.1-2008 allows to specify NULL for the output buffer, in which case 1288 // output buffer is dynamically allocated and must be ::free()'d by the caller. 1289 char* p = ::realpath(filename, NULL); 1290 if (p != NULL) { 1291 if (strlen(p) < outbuflen) { 1292 strcpy(outbuf, p); 1293 result = outbuf; 1294 } else { 1295 errno = ENAMETOOLONG; 1296 } 1297 ::free(p); // *not* os::free 1298 } else { 1299 // Fallback for platforms struggling with modern Posix standards (AIX 5.3, 6.1). If realpath 1300 // returns EINVAL, this may indicate that realpath is not POSIX.1-2008 compatible and 1301 // that it complains about the NULL we handed down as user buffer. 1302 // In this case, use the user provided buffer but at least check whether realpath caused 1303 // a memory overwrite. 1304 if (errno == EINVAL) { 1305 outbuf[outbuflen - 1] = '\0'; 1306 p = ::realpath(filename, outbuf); 1307 if (p != NULL) { 1308 guarantee(outbuf[outbuflen - 1] == '\0', "realpath buffer overwrite detected."); 1309 result = p; 1310 } 1311 } 1312 } 1313 return result; 1314 1315 } 1316 1317 int os::stat(const char *path, struct stat *sbuf) { 1318 return ::stat(path, sbuf); 1319 } 1320 1321 char * os::native_path(char *path) { 1322 return path; 1323 } 1324 1325 bool os::same_files(const char* file1, const char* file2) { 1326 if (strcmp(file1, file2) == 0) { 1327 return true; 1328 } 1329 1330 bool is_same = false; 1331 struct stat st1; 1332 struct stat st2; 1333 1334 if (os::stat(file1, &st1) < 0) { 1335 return false; 1336 } 1337 1338 if (os::stat(file2, &st2) < 0) { 1339 return false; 1340 } 1341 1342 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) { 1343 // same files 1344 is_same = true; 1345 } 1346 return is_same; 1347 } 1348 1349 // Check minimum allowable stack sizes for thread creation and to initialize 1350 // the java system classes, including StackOverflowError - depends on page 1351 // size. 1352 // The space needed for frames during startup is platform dependent. It 1353 // depends on word size, platform calling conventions, C frame layout and 1354 // interpreter/C1/C2 design decisions. Therefore this is given in a 1355 // platform (os/cpu) dependent constant. 1356 // To this, space for guard mechanisms is added, which depends on the 1357 // page size which again depends on the concrete system the VM is running 1358 // on. Space for libc guard pages is not included in this size. 1359 jint os::Posix::set_minimum_stack_sizes() { 1360 size_t os_min_stack_allowed = SOLARIS_ONLY(thr_min_stack()) NOT_SOLARIS(PTHREAD_STACK_MIN); 1361 1362 _java_thread_min_stack_allowed = _java_thread_min_stack_allowed + 1363 JavaThread::stack_guard_zone_size() + 1364 JavaThread::stack_shadow_zone_size(); 1365 1366 _java_thread_min_stack_allowed = align_up(_java_thread_min_stack_allowed, vm_page_size()); 1367 _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, os_min_stack_allowed); 1368 1369 size_t stack_size_in_bytes = ThreadStackSize * K; 1370 if (stack_size_in_bytes != 0 && 1371 stack_size_in_bytes < _java_thread_min_stack_allowed) { 1372 // The '-Xss' and '-XX:ThreadStackSize=N' options both set 1373 // ThreadStackSize so we go with "Java thread stack size" instead 1374 // of "ThreadStackSize" to be more friendly. 1375 tty->print_cr("\nThe Java thread stack size specified is too small. " 1376 "Specify at least " SIZE_FORMAT "k", 1377 _java_thread_min_stack_allowed / K); 1378 return JNI_ERR; 1379 } 1380 1381 // Make the stack size a multiple of the page size so that 1382 // the yellow/red zones can be guarded. 1383 JavaThread::set_stack_size_at_create(align_up(stack_size_in_bytes, vm_page_size())); 1384 1385 // Reminder: a compiler thread is a Java thread. 1386 _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed + 1387 JavaThread::stack_guard_zone_size() + 1388 JavaThread::stack_shadow_zone_size(); 1389 1390 _compiler_thread_min_stack_allowed = align_up(_compiler_thread_min_stack_allowed, vm_page_size()); 1391 _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, os_min_stack_allowed); 1392 1393 stack_size_in_bytes = CompilerThreadStackSize * K; 1394 if (stack_size_in_bytes != 0 && 1395 stack_size_in_bytes < _compiler_thread_min_stack_allowed) { 1396 tty->print_cr("\nThe CompilerThreadStackSize specified is too small. " 1397 "Specify at least " SIZE_FORMAT "k", 1398 _compiler_thread_min_stack_allowed / K); 1399 return JNI_ERR; 1400 } 1401 1402 _vm_internal_thread_min_stack_allowed = align_up(_vm_internal_thread_min_stack_allowed, vm_page_size()); 1403 _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, os_min_stack_allowed); 1404 1405 stack_size_in_bytes = VMThreadStackSize * K; 1406 if (stack_size_in_bytes != 0 && 1407 stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) { 1408 tty->print_cr("\nThe VMThreadStackSize specified is too small. " 1409 "Specify at least " SIZE_FORMAT "k", 1410 _vm_internal_thread_min_stack_allowed / K); 1411 return JNI_ERR; 1412 } 1413 return JNI_OK; 1414 } 1415 1416 // Called when creating the thread. The minimum stack sizes have already been calculated 1417 size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) { 1418 size_t stack_size; 1419 if (req_stack_size == 0) { 1420 stack_size = default_stack_size(thr_type); 1421 } else { 1422 stack_size = req_stack_size; 1423 } 1424 1425 switch (thr_type) { 1426 case os::java_thread: 1427 // Java threads use ThreadStackSize which default value can be 1428 // changed with the flag -Xss 1429 if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) { 1430 // no requested size and we have a more specific default value 1431 stack_size = JavaThread::stack_size_at_create(); 1432 } 1433 stack_size = MAX2(stack_size, 1434 _java_thread_min_stack_allowed); 1435 break; 1436 case os::compiler_thread: 1437 if (req_stack_size == 0 && CompilerThreadStackSize > 0) { 1438 // no requested size and we have a more specific default value 1439 stack_size = (size_t)(CompilerThreadStackSize * K); 1440 } 1441 stack_size = MAX2(stack_size, 1442 _compiler_thread_min_stack_allowed); 1443 break; 1444 case os::vm_thread: 1445 case os::pgc_thread: 1446 case os::cgc_thread: 1447 case os::watcher_thread: 1448 default: // presume the unknown thr_type is a VM internal 1449 if (req_stack_size == 0 && VMThreadStackSize > 0) { 1450 // no requested size and we have a more specific default value 1451 stack_size = (size_t)(VMThreadStackSize * K); 1452 } 1453 1454 stack_size = MAX2(stack_size, 1455 _vm_internal_thread_min_stack_allowed); 1456 break; 1457 } 1458 1459 // pthread_attr_setstacksize() may require that the size be rounded up to the OS page size. 1460 // Be careful not to round up to 0. Align down in that case. 1461 if (stack_size <= SIZE_MAX - vm_page_size()) { 1462 stack_size = align_up(stack_size, vm_page_size()); 1463 } else { 1464 stack_size = align_down(stack_size, vm_page_size()); 1465 } 1466 1467 return stack_size; 1468 } 1469 1470 bool os::Posix::is_root(uid_t uid){ 1471 return ROOT_UID == uid; 1472 } 1473 1474 bool os::Posix::matches_effective_uid_or_root(uid_t uid) { 1475 return is_root(uid) || geteuid() == uid; 1476 } 1477 1478 bool os::Posix::matches_effective_uid_and_gid_or_root(uid_t uid, gid_t gid) { 1479 return is_root(uid) || (geteuid() == uid && getegid() == gid); 1480 } 1481 1482 Thread* os::ThreadCrashProtection::_protected_thread = NULL; 1483 os::ThreadCrashProtection* os::ThreadCrashProtection::_crash_protection = NULL; 1484 volatile intptr_t os::ThreadCrashProtection::_crash_mux = 0; 1485 1486 os::ThreadCrashProtection::ThreadCrashProtection() { 1487 } 1488 1489 /* 1490 * See the caveats for this class in os_posix.hpp 1491 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this 1492 * method and returns false. If none of the signals are raised, returns true. 1493 * The callback is supposed to provide the method that should be protected. 1494 */ 1495 bool os::ThreadCrashProtection::call(os::CrashProtectionCallback& cb) { 1496 sigset_t saved_sig_mask; 1497 1498 Thread::muxAcquire(&_crash_mux, "CrashProtection"); 1499 1500 _protected_thread = Thread::current_or_null(); 1501 assert(_protected_thread != NULL, "Cannot crash protect a NULL thread"); 1502 1503 // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask 1504 // since on at least some systems (OS X) siglongjmp will restore the mask 1505 // for the process, not the thread 1506 pthread_sigmask(0, NULL, &saved_sig_mask); 1507 if (sigsetjmp(_jmpbuf, 0) == 0) { 1508 // make sure we can see in the signal handler that we have crash protection 1509 // installed 1510 _crash_protection = this; 1511 cb.call(); 1512 // and clear the crash protection 1513 _crash_protection = NULL; 1514 _protected_thread = NULL; 1515 Thread::muxRelease(&_crash_mux); 1516 return true; 1517 } 1518 // this happens when we siglongjmp() back 1519 pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL); 1520 _crash_protection = NULL; 1521 _protected_thread = NULL; 1522 Thread::muxRelease(&_crash_mux); 1523 return false; 1524 } 1525 1526 void os::ThreadCrashProtection::restore() { 1527 assert(_crash_protection != NULL, "must have crash protection"); 1528 siglongjmp(_jmpbuf, 1); 1529 } 1530 1531 void os::ThreadCrashProtection::check_crash_protection(int sig, 1532 Thread* thread) { 1533 1534 if (thread != NULL && 1535 thread == _protected_thread && 1536 _crash_protection != NULL) { 1537 1538 if (sig == SIGSEGV || sig == SIGBUS) { 1539 _crash_protection->restore(); 1540 } 1541 } 1542 } 1543 1544 // Shared clock/time and other supporting routines for pthread_mutex/cond 1545 // initialization. This is enabled on Solaris but only some of the clock/time 1546 // functionality is actually used there. 1547 1548 // Shared condattr object for use with relative timed-waits. Will be associated 1549 // with CLOCK_MONOTONIC if available to avoid issues with time-of-day changes, 1550 // but otherwise whatever default is used by the platform - generally the 1551 // time-of-day clock. 1552 static pthread_condattr_t _condAttr[1]; 1553 1554 // Shared mutexattr to explicitly set the type to PTHREAD_MUTEX_NORMAL as not 1555 // all systems (e.g. FreeBSD) map the default to "normal". 1556 static pthread_mutexattr_t _mutexAttr[1]; 1557 1558 // common basic initialization that is always supported 1559 static void pthread_init_common(void) { 1560 int status; 1561 if ((status = pthread_condattr_init(_condAttr)) != 0) { 1562 fatal("pthread_condattr_init: %s", os::strerror(status)); 1563 } 1564 if ((status = pthread_mutexattr_init(_mutexAttr)) != 0) { 1565 fatal("pthread_mutexattr_init: %s", os::strerror(status)); 1566 } 1567 if ((status = pthread_mutexattr_settype(_mutexAttr, PTHREAD_MUTEX_NORMAL)) != 0) { 1568 fatal("pthread_mutexattr_settype: %s", os::strerror(status)); 1569 } 1570 // Solaris has it's own PlatformMutex, distinct from the one for POSIX. 1571 NOT_SOLARIS(os::PlatformMutex::init();) 1572 } 1573 1574 #ifndef SOLARIS 1575 sigset_t sigs; 1576 struct sigaction sigact[NSIG]; 1577 1578 struct sigaction* os::Posix::get_preinstalled_handler(int sig) { 1579 if (sigismember(&sigs, sig)) { 1580 return &sigact[sig]; 1581 } 1582 return NULL; 1583 } 1584 1585 void os::Posix::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 1586 assert(sig > 0 && sig < NSIG, "vm signal out of expected range"); 1587 sigact[sig] = oldAct; 1588 sigaddset(&sigs, sig); 1589 } 1590 #endif 1591 1592 // Not all POSIX types and API's are available on all notionally "posix" 1593 // platforms. If we have build-time support then we will check for actual 1594 // runtime support via dlopen/dlsym lookup. This allows for running on an 1595 // older OS version compared to the build platform. But if there is no 1596 // build time support then there cannot be any runtime support as we do not 1597 // know what the runtime types would be (for example clockid_t might be an 1598 // int or int64_t). 1599 // 1600 #ifdef SUPPORTS_CLOCK_MONOTONIC 1601 1602 // This means we have clockid_t, clock_gettime et al and CLOCK_MONOTONIC 1603 1604 int (*os::Posix::_clock_gettime)(clockid_t, struct timespec *) = NULL; 1605 int (*os::Posix::_clock_getres)(clockid_t, struct timespec *) = NULL; 1606 1607 static int (*_pthread_condattr_setclock)(pthread_condattr_t *, clockid_t) = NULL; 1608 1609 static bool _use_clock_monotonic_condattr = false; 1610 1611 // Determine what POSIX API's are present and do appropriate 1612 // configuration. 1613 void os::Posix::init(void) { 1614 1615 // NOTE: no logging available when this is called. Put logging 1616 // statements in init_2(). 1617 1618 // 1. Check for CLOCK_MONOTONIC support. 1619 1620 void* handle = NULL; 1621 1622 // For linux we need librt, for other OS we can find 1623 // this function in regular libc. 1624 #ifdef NEEDS_LIBRT 1625 // We do dlopen's in this particular order due to bug in linux 1626 // dynamic loader (see 6348968) leading to crash on exit. 1627 handle = dlopen("librt.so.1", RTLD_LAZY); 1628 if (handle == NULL) { 1629 handle = dlopen("librt.so", RTLD_LAZY); 1630 } 1631 #endif 1632 1633 if (handle == NULL) { 1634 handle = RTLD_DEFAULT; 1635 } 1636 1637 int (*clock_getres_func)(clockid_t, struct timespec*) = 1638 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1639 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1640 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1641 if (clock_getres_func != NULL && clock_gettime_func != NULL) { 1642 // We assume that if both clock_gettime and clock_getres support 1643 // CLOCK_MONOTONIC then the OS provides true high-res monotonic clock. 1644 struct timespec res; 1645 struct timespec tp; 1646 if (clock_getres_func(CLOCK_MONOTONIC, &res) == 0 && 1647 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1648 // Yes, monotonic clock is supported. 1649 _clock_gettime = clock_gettime_func; 1650 _clock_getres = clock_getres_func; 1651 } else { 1652 #ifdef NEEDS_LIBRT 1653 // Close librt if there is no monotonic clock. 1654 if (handle != RTLD_DEFAULT) { 1655 dlclose(handle); 1656 } 1657 #endif 1658 } 1659 } 1660 1661 // 2. Check for pthread_condattr_setclock support. 1662 1663 // libpthread is already loaded. 1664 int (*condattr_setclock_func)(pthread_condattr_t*, clockid_t) = 1665 (int (*)(pthread_condattr_t*, clockid_t))dlsym(RTLD_DEFAULT, 1666 "pthread_condattr_setclock"); 1667 if (condattr_setclock_func != NULL) { 1668 _pthread_condattr_setclock = condattr_setclock_func; 1669 } 1670 1671 // Now do general initialization. 1672 1673 pthread_init_common(); 1674 1675 #ifndef SOLARIS 1676 int status; 1677 if (_pthread_condattr_setclock != NULL && _clock_gettime != NULL) { 1678 if ((status = _pthread_condattr_setclock(_condAttr, CLOCK_MONOTONIC)) != 0) { 1679 if (status == EINVAL) { 1680 _use_clock_monotonic_condattr = false; 1681 warning("Unable to use monotonic clock with relative timed-waits" \ 1682 " - changes to the time-of-day clock may have adverse affects"); 1683 } else { 1684 fatal("pthread_condattr_setclock: %s", os::strerror(status)); 1685 } 1686 } else { 1687 _use_clock_monotonic_condattr = true; 1688 } 1689 } 1690 #endif // !SOLARIS 1691 1692 } 1693 1694 void os::Posix::init_2(void) { 1695 #ifndef SOLARIS 1696 log_info(os)("Use of CLOCK_MONOTONIC is%s supported", 1697 (_clock_gettime != NULL ? "" : " not")); 1698 log_info(os)("Use of pthread_condattr_setclock is%s supported", 1699 (_pthread_condattr_setclock != NULL ? "" : " not")); 1700 log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with %s", 1701 _use_clock_monotonic_condattr ? "CLOCK_MONOTONIC" : "the default clock"); 1702 sigemptyset(&sigs); 1703 #endif // !SOLARIS 1704 } 1705 1706 #else // !SUPPORTS_CLOCK_MONOTONIC 1707 1708 void os::Posix::init(void) { 1709 pthread_init_common(); 1710 } 1711 1712 void os::Posix::init_2(void) { 1713 #ifndef SOLARIS 1714 log_info(os)("Use of CLOCK_MONOTONIC is not supported"); 1715 log_info(os)("Use of pthread_condattr_setclock is not supported"); 1716 log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with the default clock"); 1717 sigemptyset(&sigs); 1718 #endif // !SOLARIS 1719 } 1720 1721 #endif // SUPPORTS_CLOCK_MONOTONIC 1722 1723 // Utility to convert the given timeout to an absolute timespec 1724 // (based on the appropriate clock) to use with pthread_cond_timewait, 1725 // and sem_timedwait(). 1726 // The clock queried here must be the clock used to manage the 1727 // timeout of the condition variable or semaphore. 1728 // 1729 // The passed in timeout value is either a relative time in nanoseconds 1730 // or an absolute time in milliseconds. A relative timeout will be 1731 // associated with CLOCK_MONOTONIC if available, unless the real-time clock 1732 // is explicitly requested; otherwise, or if absolute, 1733 // the default time-of-day clock will be used. 1734 1735 // Given time is a 64-bit value and the time_t used in the timespec is 1736 // sometimes a signed-32-bit value we have to watch for overflow if times 1737 // way in the future are given. Further on Solaris versions 1738 // prior to 10 there is a restriction (see cond_timedwait) that the specified 1739 // number of seconds, in abstime, is less than current_time + 100000000. 1740 // As it will be over 20 years before "now + 100000000" will overflow we can 1741 // ignore overflow and just impose a hard-limit on seconds using the value 1742 // of "now + 100000000". This places a limit on the timeout of about 3.17 1743 // years from "now". 1744 // 1745 #define MAX_SECS 100000000 1746 1747 // Calculate a new absolute time that is "timeout" nanoseconds from "now". 1748 // "unit" indicates the unit of "now_part_sec" (may be nanos or micros depending 1749 // on which clock API is being used). 1750 static void calc_rel_time(timespec* abstime, jlong timeout, jlong now_sec, 1751 jlong now_part_sec, jlong unit) { 1752 time_t max_secs = now_sec + MAX_SECS; 1753 1754 jlong seconds = timeout / NANOUNITS; 1755 timeout %= NANOUNITS; // remaining nanos 1756 1757 if (seconds >= MAX_SECS) { 1758 // More seconds than we can add, so pin to max_secs. 1759 abstime->tv_sec = max_secs; 1760 abstime->tv_nsec = 0; 1761 } else { 1762 abstime->tv_sec = now_sec + seconds; 1763 long nanos = (now_part_sec * (NANOUNITS / unit)) + timeout; 1764 if (nanos >= NANOUNITS) { // overflow 1765 abstime->tv_sec += 1; 1766 nanos -= NANOUNITS; 1767 } 1768 abstime->tv_nsec = nanos; 1769 } 1770 } 1771 1772 // Unpack the given deadline in milliseconds since the epoch, into the given timespec. 1773 // The current time in seconds is also passed in to enforce an upper bound as discussed above. 1774 // This is only used with gettimeofday, when clock_gettime is not available. 1775 static void unpack_abs_time(timespec* abstime, jlong deadline, jlong now_sec) { 1776 time_t max_secs = now_sec + MAX_SECS; 1777 1778 jlong seconds = deadline / MILLIUNITS; 1779 jlong millis = deadline % MILLIUNITS; 1780 1781 if (seconds >= max_secs) { 1782 // Absolute seconds exceeds allowed max, so pin to max_secs. 1783 abstime->tv_sec = max_secs; 1784 abstime->tv_nsec = 0; 1785 } else { 1786 abstime->tv_sec = seconds; 1787 abstime->tv_nsec = millis * (NANOUNITS / MILLIUNITS); 1788 } 1789 } 1790 1791 static jlong millis_to_nanos(jlong millis) { 1792 // We have to watch for overflow when converting millis to nanos, 1793 // but if millis is that large then we will end up limiting to 1794 // MAX_SECS anyway, so just do that here. 1795 if (millis / MILLIUNITS > MAX_SECS) { 1796 millis = jlong(MAX_SECS) * MILLIUNITS; 1797 } 1798 return millis * (NANOUNITS / MILLIUNITS); 1799 } 1800 1801 static void to_abstime(timespec* abstime, jlong timeout, 1802 bool isAbsolute, bool isRealtime) { 1803 DEBUG_ONLY(int max_secs = MAX_SECS;) 1804 1805 if (timeout < 0) { 1806 timeout = 0; 1807 } 1808 1809 #ifdef SUPPORTS_CLOCK_MONOTONIC 1810 1811 clockid_t clock = CLOCK_MONOTONIC; 1812 // need to ensure we have a runtime check for clock_gettime support 1813 if (!isAbsolute && os::Posix::supports_monotonic_clock()) { 1814 if (!_use_clock_monotonic_condattr || isRealtime) { 1815 clock = CLOCK_REALTIME; 1816 } 1817 struct timespec now; 1818 int status = os::Posix::clock_gettime(clock, &now); 1819 assert_status(status == 0, status, "clock_gettime"); 1820 calc_rel_time(abstime, timeout, now.tv_sec, now.tv_nsec, NANOUNITS); 1821 DEBUG_ONLY(max_secs += now.tv_sec;) 1822 } else { 1823 1824 #else 1825 1826 { // Match the block scope. 1827 1828 #endif // SUPPORTS_CLOCK_MONOTONIC 1829 1830 // Time-of-day clock is all we can reliably use. 1831 struct timeval now; 1832 int status = gettimeofday(&now, NULL); 1833 assert_status(status == 0, errno, "gettimeofday"); 1834 if (isAbsolute) { 1835 unpack_abs_time(abstime, timeout, now.tv_sec); 1836 } else { 1837 calc_rel_time(abstime, timeout, now.tv_sec, now.tv_usec, MICROUNITS); 1838 } 1839 DEBUG_ONLY(max_secs += now.tv_sec;) 1840 } 1841 1842 assert(abstime->tv_sec >= 0, "tv_sec < 0"); 1843 assert(abstime->tv_sec <= max_secs, "tv_sec > max_secs"); 1844 assert(abstime->tv_nsec >= 0, "tv_nsec < 0"); 1845 assert(abstime->tv_nsec < NANOUNITS, "tv_nsec >= NANOUNITS"); 1846 } 1847 1848 // Create an absolute time 'millis' milliseconds in the future, using the 1849 // real-time (time-of-day) clock. Used by PosixSemaphore. 1850 void os::Posix::to_RTC_abstime(timespec* abstime, int64_t millis) { 1851 to_abstime(abstime, millis_to_nanos(millis), 1852 false /* not absolute */, 1853 true /* use real-time clock */); 1854 } 1855 1856 // Shared pthread_mutex/cond based PlatformEvent implementation. 1857 // Not currently usable by Solaris. 1858 1859 #ifndef SOLARIS 1860 1861 // PlatformEvent 1862 // 1863 // Assumption: 1864 // Only one parker can exist on an event, which is why we allocate 1865 // them per-thread. Multiple unparkers can coexist. 1866 // 1867 // _event serves as a restricted-range semaphore. 1868 // -1 : thread is blocked, i.e. there is a waiter 1869 // 0 : neutral: thread is running or ready, 1870 // could have been signaled after a wait started 1871 // 1 : signaled - thread is running or ready 1872 // 1873 // Having three states allows for some detection of bad usage - see 1874 // comments on unpark(). 1875 1876 os::PlatformEvent::PlatformEvent() { 1877 int status = pthread_cond_init(_cond, _condAttr); 1878 assert_status(status == 0, status, "cond_init"); 1879 status = pthread_mutex_init(_mutex, _mutexAttr); 1880 assert_status(status == 0, status, "mutex_init"); 1881 _event = 0; 1882 _nParked = 0; 1883 } 1884 1885 void os::PlatformEvent::park() { // AKA "down()" 1886 // Transitions for _event: 1887 // -1 => -1 : illegal 1888 // 1 => 0 : pass - return immediately 1889 // 0 => -1 : block; then set _event to 0 before returning 1890 1891 // Invariant: Only the thread associated with the PlatformEvent 1892 // may call park(). 1893 assert(_nParked == 0, "invariant"); 1894 1895 int v; 1896 1897 // atomically decrement _event 1898 for (;;) { 1899 v = _event; 1900 if (Atomic::cmpxchg(v - 1, &_event, v) == v) break; 1901 } 1902 guarantee(v >= 0, "invariant"); 1903 1904 if (v == 0) { // Do this the hard way by blocking ... 1905 int status = pthread_mutex_lock(_mutex); 1906 assert_status(status == 0, status, "mutex_lock"); 1907 guarantee(_nParked == 0, "invariant"); 1908 ++_nParked; 1909 while (_event < 0) { 1910 // OS-level "spurious wakeups" are ignored 1911 status = pthread_cond_wait(_cond, _mutex); 1912 assert_status(status == 0, status, "cond_wait"); 1913 } 1914 --_nParked; 1915 1916 _event = 0; 1917 status = pthread_mutex_unlock(_mutex); 1918 assert_status(status == 0, status, "mutex_unlock"); 1919 // Paranoia to ensure our locked and lock-free paths interact 1920 // correctly with each other. 1921 OrderAccess::fence(); 1922 } 1923 guarantee(_event >= 0, "invariant"); 1924 } 1925 1926 int os::PlatformEvent::park(jlong millis) { 1927 // Transitions for _event: 1928 // -1 => -1 : illegal 1929 // 1 => 0 : pass - return immediately 1930 // 0 => -1 : block; then set _event to 0 before returning 1931 1932 // Invariant: Only the thread associated with the Event/PlatformEvent 1933 // may call park(). 1934 assert(_nParked == 0, "invariant"); 1935 1936 int v; 1937 // atomically decrement _event 1938 for (;;) { 1939 v = _event; 1940 if (Atomic::cmpxchg(v - 1, &_event, v) == v) break; 1941 } 1942 guarantee(v >= 0, "invariant"); 1943 1944 if (v == 0) { // Do this the hard way by blocking ... 1945 struct timespec abst; 1946 to_abstime(&abst, millis_to_nanos(millis), false, false); 1947 1948 int ret = OS_TIMEOUT; 1949 int status = pthread_mutex_lock(_mutex); 1950 assert_status(status == 0, status, "mutex_lock"); 1951 guarantee(_nParked == 0, "invariant"); 1952 ++_nParked; 1953 1954 while (_event < 0) { 1955 status = pthread_cond_timedwait(_cond, _mutex, &abst); 1956 assert_status(status == 0 || status == ETIMEDOUT, 1957 status, "cond_timedwait"); 1958 // OS-level "spurious wakeups" are ignored unless the archaic 1959 // FilterSpuriousWakeups is set false. That flag should be obsoleted. 1960 if (!FilterSpuriousWakeups) break; 1961 if (status == ETIMEDOUT) break; 1962 } 1963 --_nParked; 1964 1965 if (_event >= 0) { 1966 ret = OS_OK; 1967 } 1968 1969 _event = 0; 1970 status = pthread_mutex_unlock(_mutex); 1971 assert_status(status == 0, status, "mutex_unlock"); 1972 // Paranoia to ensure our locked and lock-free paths interact 1973 // correctly with each other. 1974 OrderAccess::fence(); 1975 return ret; 1976 } 1977 return OS_OK; 1978 } 1979 1980 void os::PlatformEvent::unpark() { 1981 // Transitions for _event: 1982 // 0 => 1 : just return 1983 // 1 => 1 : just return 1984 // -1 => either 0 or 1; must signal target thread 1985 // That is, we can safely transition _event from -1 to either 1986 // 0 or 1. 1987 // See also: "Semaphores in Plan 9" by Mullender & Cox 1988 // 1989 // Note: Forcing a transition from "-1" to "1" on an unpark() means 1990 // that it will take two back-to-back park() calls for the owning 1991 // thread to block. This has the benefit of forcing a spurious return 1992 // from the first park() call after an unpark() call which will help 1993 // shake out uses of park() and unpark() without checking state conditions 1994 // properly. This spurious return doesn't manifest itself in any user code 1995 // but only in the correctly written condition checking loops of ObjectMonitor, 1996 // Mutex/Monitor, Thread::muxAcquire and JavaThread::sleep 1997 1998 if (Atomic::xchg(1, &_event) >= 0) return; 1999 2000 int status = pthread_mutex_lock(_mutex); 2001 assert_status(status == 0, status, "mutex_lock"); 2002 int anyWaiters = _nParked; 2003 assert(anyWaiters == 0 || anyWaiters == 1, "invariant"); 2004 status = pthread_mutex_unlock(_mutex); 2005 assert_status(status == 0, status, "mutex_unlock"); 2006 2007 // Note that we signal() *after* dropping the lock for "immortal" Events. 2008 // This is safe and avoids a common class of futile wakeups. In rare 2009 // circumstances this can cause a thread to return prematurely from 2010 // cond_{timed}wait() but the spurious wakeup is benign and the victim 2011 // will simply re-test the condition and re-park itself. 2012 // This provides particular benefit if the underlying platform does not 2013 // provide wait morphing. 2014 2015 if (anyWaiters != 0) { 2016 status = pthread_cond_signal(_cond); 2017 assert_status(status == 0, status, "cond_signal"); 2018 } 2019 } 2020 2021 // JSR166 support 2022 2023 os::PlatformParker::PlatformParker() { 2024 int status; 2025 status = pthread_cond_init(&_cond[REL_INDEX], _condAttr); 2026 assert_status(status == 0, status, "cond_init rel"); 2027 status = pthread_cond_init(&_cond[ABS_INDEX], NULL); 2028 assert_status(status == 0, status, "cond_init abs"); 2029 status = pthread_mutex_init(_mutex, _mutexAttr); 2030 assert_status(status == 0, status, "mutex_init"); 2031 _cur_index = -1; // mark as unused 2032 } 2033 2034 // Parker::park decrements count if > 0, else does a condvar wait. Unpark 2035 // sets count to 1 and signals condvar. Only one thread ever waits 2036 // on the condvar. Contention seen when trying to park implies that someone 2037 // is unparking you, so don't wait. And spurious returns are fine, so there 2038 // is no need to track notifications. 2039 2040 void Parker::park(bool isAbsolute, jlong time) { 2041 2042 // Optional fast-path check: 2043 // Return immediately if a permit is available. 2044 // We depend on Atomic::xchg() having full barrier semantics 2045 // since we are doing a lock-free update to _counter. 2046 if (Atomic::xchg(0, &_counter) > 0) return; 2047 2048 Thread* thread = Thread::current(); 2049 assert(thread->is_Java_thread(), "Must be JavaThread"); 2050 JavaThread *jt = (JavaThread *)thread; 2051 2052 // Optional optimization -- avoid state transitions if there's 2053 // an interrupt pending. 2054 if (jt->is_interrupted(false)) { 2055 return; 2056 } 2057 2058 // Next, demultiplex/decode time arguments 2059 struct timespec absTime; 2060 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 2061 return; 2062 } 2063 if (time > 0) { 2064 to_abstime(&absTime, time, isAbsolute, false); 2065 } 2066 2067 // Enter safepoint region 2068 // Beware of deadlocks such as 6317397. 2069 // The per-thread Parker:: mutex is a classic leaf-lock. 2070 // In particular a thread must never block on the Threads_lock while 2071 // holding the Parker:: mutex. If safepoints are pending both the 2072 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 2073 ThreadBlockInVM tbivm(jt); 2074 2075 // Don't wait if cannot get lock since interference arises from 2076 // unparking. Also re-check interrupt before trying wait. 2077 if (jt->is_interrupted(false) || 2078 pthread_mutex_trylock(_mutex) != 0) { 2079 return; 2080 } 2081 2082 int status; 2083 if (_counter > 0) { // no wait needed 2084 _counter = 0; 2085 status = pthread_mutex_unlock(_mutex); 2086 assert_status(status == 0, status, "invariant"); 2087 // Paranoia to ensure our locked and lock-free paths interact 2088 // correctly with each other and Java-level accesses. 2089 OrderAccess::fence(); 2090 return; 2091 } 2092 2093 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 2094 jt->set_suspend_equivalent(); 2095 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2096 2097 assert(_cur_index == -1, "invariant"); 2098 if (time == 0) { 2099 _cur_index = REL_INDEX; // arbitrary choice when not timed 2100 status = pthread_cond_wait(&_cond[_cur_index], _mutex); 2101 assert_status(status == 0, status, "cond_timedwait"); 2102 } 2103 else { 2104 _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX; 2105 status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime); 2106 assert_status(status == 0 || status == ETIMEDOUT, 2107 status, "cond_timedwait"); 2108 } 2109 _cur_index = -1; 2110 2111 _counter = 0; 2112 status = pthread_mutex_unlock(_mutex); 2113 assert_status(status == 0, status, "invariant"); 2114 // Paranoia to ensure our locked and lock-free paths interact 2115 // correctly with each other and Java-level accesses. 2116 OrderAccess::fence(); 2117 2118 // If externally suspended while waiting, re-suspend 2119 if (jt->handle_special_suspend_equivalent_condition()) { 2120 jt->java_suspend_self(); 2121 } 2122 } 2123 2124 void Parker::unpark() { 2125 int status = pthread_mutex_lock(_mutex); 2126 assert_status(status == 0, status, "invariant"); 2127 const int s = _counter; 2128 _counter = 1; 2129 // must capture correct index before unlocking 2130 int index = _cur_index; 2131 status = pthread_mutex_unlock(_mutex); 2132 assert_status(status == 0, status, "invariant"); 2133 2134 // Note that we signal() *after* dropping the lock for "immortal" Events. 2135 // This is safe and avoids a common class of futile wakeups. In rare 2136 // circumstances this can cause a thread to return prematurely from 2137 // cond_{timed}wait() but the spurious wakeup is benign and the victim 2138 // will simply re-test the condition and re-park itself. 2139 // This provides particular benefit if the underlying platform does not 2140 // provide wait morphing. 2141 2142 if (s < 1 && index != -1) { 2143 // thread is definitely parked 2144 status = pthread_cond_signal(&_cond[index]); 2145 assert_status(status == 0, status, "invariant"); 2146 } 2147 } 2148 2149 // Platform Mutex/Monitor implementation 2150 2151 #if PLATFORM_MONITOR_IMPL_INDIRECT 2152 2153 os::PlatformMutex::Mutex::Mutex() : _next(NULL) { 2154 int status = pthread_mutex_init(&_mutex, _mutexAttr); 2155 assert_status(status == 0, status, "mutex_init"); 2156 } 2157 2158 os::PlatformMutex::Mutex::~Mutex() { 2159 int status = pthread_mutex_destroy(&_mutex); 2160 assert_status(status == 0, status, "mutex_destroy"); 2161 } 2162 2163 pthread_mutex_t os::PlatformMutex::_freelist_lock; 2164 os::PlatformMutex::Mutex* os::PlatformMutex::_mutex_freelist = NULL; 2165 2166 void os::PlatformMutex::init() { 2167 int status = pthread_mutex_init(&_freelist_lock, _mutexAttr); 2168 assert_status(status == 0, status, "freelist lock init"); 2169 } 2170 2171 struct os::PlatformMutex::WithFreeListLocked : public StackObj { 2172 WithFreeListLocked() { 2173 int status = pthread_mutex_lock(&_freelist_lock); 2174 assert_status(status == 0, status, "freelist lock"); 2175 } 2176 2177 ~WithFreeListLocked() { 2178 int status = pthread_mutex_unlock(&_freelist_lock); 2179 assert_status(status == 0, status, "freelist unlock"); 2180 } 2181 }; 2182 2183 os::PlatformMutex::PlatformMutex() { 2184 { 2185 WithFreeListLocked wfl; 2186 _impl = _mutex_freelist; 2187 if (_impl != NULL) { 2188 _mutex_freelist = _impl->_next; 2189 _impl->_next = NULL; 2190 return; 2191 } 2192 } 2193 _impl = new Mutex(); 2194 } 2195 2196 os::PlatformMutex::~PlatformMutex() { 2197 WithFreeListLocked wfl; 2198 assert(_impl->_next == NULL, "invariant"); 2199 _impl->_next = _mutex_freelist; 2200 _mutex_freelist = _impl; 2201 } 2202 2203 os::PlatformMonitor::Cond::Cond() : _next(NULL) { 2204 int status = pthread_cond_init(&_cond, _condAttr); 2205 assert_status(status == 0, status, "cond_init"); 2206 } 2207 2208 os::PlatformMonitor::Cond::~Cond() { 2209 int status = pthread_cond_destroy(&_cond); 2210 assert_status(status == 0, status, "cond_destroy"); 2211 } 2212 2213 os::PlatformMonitor::Cond* os::PlatformMonitor::_cond_freelist = NULL; 2214 2215 os::PlatformMonitor::PlatformMonitor() { 2216 { 2217 WithFreeListLocked wfl; 2218 _impl = _cond_freelist; 2219 if (_impl != NULL) { 2220 _cond_freelist = _impl->_next; 2221 _impl->_next = NULL; 2222 return; 2223 } 2224 } 2225 _impl = new Cond(); 2226 } 2227 2228 os::PlatformMonitor::~PlatformMonitor() { 2229 WithFreeListLocked wfl; 2230 assert(_impl->_next == NULL, "invariant"); 2231 _impl->_next = _cond_freelist; 2232 _cond_freelist = _impl; 2233 } 2234 2235 #else 2236 2237 os::PlatformMutex::PlatformMutex() { 2238 int status = pthread_mutex_init(&_mutex, _mutexAttr); 2239 assert_status(status == 0, status, "mutex_init"); 2240 } 2241 2242 os::PlatformMutex::~PlatformMutex() { 2243 int status = pthread_mutex_destroy(&_mutex); 2244 assert_status(status == 0, status, "mutex_destroy"); 2245 } 2246 2247 os::PlatformMonitor::PlatformMonitor() { 2248 int status = pthread_cond_init(&_cond, _condAttr); 2249 assert_status(status == 0, status, "cond_init"); 2250 } 2251 2252 os::PlatformMonitor::~PlatformMonitor() { 2253 int status = pthread_cond_destroy(&_cond); 2254 assert_status(status == 0, status, "cond_destroy"); 2255 } 2256 2257 #endif // PLATFORM_MONITOR_IMPL_INDIRECT 2258 2259 // Must already be locked 2260 int os::PlatformMonitor::wait(jlong millis) { 2261 assert(millis >= 0, "negative timeout"); 2262 if (millis > 0) { 2263 struct timespec abst; 2264 // We have to watch for overflow when converting millis to nanos, 2265 // but if millis is that large then we will end up limiting to 2266 // MAX_SECS anyway, so just do that here. 2267 if (millis / MILLIUNITS > MAX_SECS) { 2268 millis = jlong(MAX_SECS) * MILLIUNITS; 2269 } 2270 to_abstime(&abst, millis * (NANOUNITS / MILLIUNITS), false, false); 2271 2272 int ret = OS_TIMEOUT; 2273 int status = pthread_cond_timedwait(cond(), mutex(), &abst); 2274 assert_status(status == 0 || status == ETIMEDOUT, 2275 status, "cond_timedwait"); 2276 if (status == 0) { 2277 ret = OS_OK; 2278 } 2279 return ret; 2280 } else { 2281 int status = pthread_cond_wait(cond(), mutex()); 2282 assert_status(status == 0, status, "cond_wait"); 2283 return OS_OK; 2284 } 2285 } 2286 2287 #endif // !SOLARIS