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