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