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