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