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