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