os_posix.cpp revision 10272:b0cdcfe42ebf
125603Skjc/* 255205Speter * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. 325603Skjc * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4139823Simp * 525603Skjc * This code is free software; you can redistribute it and/or modify it 625603Skjc * under the terms of the GNU General Public License version 2 only, as 725603Skjc * published by the Free Software Foundation. 825603Skjc * 925603Skjc * This code is distributed in the hope that it will be useful, but WITHOUT 1025603Skjc * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1125603Skjc * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1225603Skjc * version 2 for more details (a copy is included in the LICENSE file that 1325603Skjc * accompanied this code). 1425603Skjc * 1525603Skjc * You should have received a copy of the GNU General Public License version 1625603Skjc * 2 along with this work; if not, write to the Free Software Foundation, 1725603Skjc * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1825603Skjc * 1925603Skjc * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2025603Skjc * or visit www.oracle.com if you need additional information or have any 2125603Skjc * questions. 2225603Skjc * 2325603Skjc */ 2425603Skjc 2525603Skjc#include "utilities/globalDefinitions.hpp" 2625603Skjc#include "prims/jvm.h" 2725603Skjc#include "semaphore_posix.hpp" 2825603Skjc#include "runtime/frame.inline.hpp" 2925603Skjc#include "runtime/interfaceSupport.hpp" 3025603Skjc#include "runtime/os.hpp" 3125603Skjc#include "utilities/vmError.hpp" 3225603Skjc 3325603Skjc#include <signal.h> 3425603Skjc#include <unistd.h> 3525603Skjc#include <sys/resource.h> 3625603Skjc#include <sys/utsname.h> 3725603Skjc#include <pthread.h> 3825603Skjc#include <semaphore.h> 3925603Skjc#include <signal.h> 40114739Sharti 41114739Sharti// Todo: provide a os::get_max_process_id() or similar. Number of processes 42114739Sharti// may have been configured, can be read more accurately from proc fs etc. 43116523Sharti#ifndef MAX_PID 44116523Sharti#define MAX_PID INT_MAX 45116523Sharti#endif 46116523Sharti#define IS_VALID_PID(p) (p > 0 && p < MAX_PID) 47116523Sharti 48116523Sharti// Check core dump limit and report possible place where core can be found 49116441Shartivoid os::check_dump_limit(char* buffer, size_t bufferSize) { 50116441Sharti int n; 51116523Sharti struct rlimit rlim; 52116441Sharti bool success; 53117628Sharti 54117628Sharti char core_path[PATH_MAX]; 55117721Sharti n = get_core_path(core_path, PATH_MAX); 56117721Sharti 57125017Sharti if (n <= 0) { 58114739Sharti jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id()); 59114739Sharti success = true; 60116523Sharti#ifdef LINUX 61116441Sharti } else if (core_path[0] == '"') { // redirect to user process 62116441Sharti jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path); 63116441Sharti success = true; 64116441Sharti#endif 65116441Sharti } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) { 66116441Sharti jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path); 67116441Sharti success = true; 68116441Sharti } else { 69116441Sharti switch(rlim.rlim_cur) { 70117628Sharti case RLIM_INFINITY: 71117628Sharti jio_snprintf(buffer, bufferSize, "%s", core_path); 72117628Sharti success = true; 73117628Sharti break; 74125017Sharti case 0: 75125017Sharti jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again"); 76114739Sharti success = false; 77114739Sharti break; 78114739Sharti default: 79114739Sharti jio_snprintf(buffer, bufferSize, "%s (max size %lu kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, (unsigned long)(rlim.rlim_cur >> 10)); 80114739Sharti success = true; 81114739Sharti break; 82114739Sharti } 83114739Sharti } 84114739Sharti 85114739Sharti VMError::record_coredump_status(buffer, success); 86114739Sharti} 87114739Sharti 88114739Shartiint os::get_native_stack(address* stack, int frames, int toSkip) { 89114739Sharti#ifdef _NMT_NOINLINE_ 90114739Sharti toSkip++; 91114739Sharti#endif 92114739Sharti 93114739Sharti int frame_idx = 0; 94114739Sharti int num_of_frames; // number of frames captured 95114739Sharti frame fr = os::current_frame(); 96114739Sharti while (fr.pc() && frame_idx < frames) { 97114739Sharti if (toSkip > 0) { 98116441Sharti toSkip --; 99116441Sharti } else { 100116441Sharti stack[frame_idx ++] = fr.pc(); 101116441Sharti } 102116441Sharti if (fr.fp() == NULL || fr.cb() != NULL || 103116441Sharti fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break; 104116441Sharti 105116441Sharti if (fr.sender_pc() && !os::is_first_C_frame(&fr)) { 106116441Sharti fr = os::get_sender_for_C_frame(&fr); 107116441Sharti } else { 108116441Sharti break; 109116441Sharti } 110116441Sharti } 111116441Sharti num_of_frames = frame_idx; 112116441Sharti for (; frame_idx < frames; frame_idx ++) { 113116441Sharti stack[frame_idx] = NULL; 114116441Sharti } 115116441Sharti 116116441Sharti return num_of_frames; 117116441Sharti} 118116441Sharti 119116441Sharti 120116441Shartibool os::unsetenv(const char* name) { 121116441Sharti assert(name != NULL, "Null pointer"); 122116441Sharti return (::unsetenv(name) == 0); 123116441Sharti} 124116441Sharti 125116441Shartiint os::get_last_error() { 126116441Sharti return errno; 127116441Sharti} 128116441Sharti 129116441Shartibool os::is_debugger_attached() { 130116441Sharti // not implemented 131116441Sharti return false; 132116441Sharti} 133116441Sharti 134116441Shartivoid os::wait_for_keypress_at_exit(void) { 135116523Sharti // don't do anything on posix platforms 136116523Sharti return; 137116523Sharti} 138116523Sharti 139116523Sharti// Multiple threads can race in this code, and can remap over each other with MAP_FIXED, 140116523Sharti// so on posix, unmap the section at the start and at the end of the chunk that we mapped 141118496Sharti// rather than unmapping and remapping the whole chunk to get requested alignment. 142118496Shartichar* os::reserve_memory_aligned(size_t size, size_t alignment) { 143116441Sharti assert((alignment & (os::vm_allocation_granularity() - 1)) == 0, 144116523Sharti "Alignment must be a multiple of allocation granularity (page size)"); 145116523Sharti assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned"); 146116523Sharti 147116523Sharti size_t extra_size = size + alignment; 148116441Sharti assert(extra_size >= size, "overflow, size is too large to allow alignment"); 149116523Sharti 150116523Sharti char* extra_base = os::reserve_memory(extra_size, NULL, alignment); 151116523Sharti 152116523Sharti if (extra_base == NULL) { 153116441Sharti return NULL; 154116441Sharti } 155116441Sharti 156116441Sharti // Do manual alignment 157116441Sharti char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment); 158116441Sharti 159116441Sharti // [ | | ] 160116441Sharti // ^ extra_base 161116441Sharti // ^ extra_base + begin_offset == aligned_base 162116441Sharti // extra_base + begin_offset + size ^ 163116441Sharti // extra_base + extra_size ^ 164116441Sharti // |<>| == begin_offset 165116441Sharti // end_offset == |<>| 166116441Sharti size_t begin_offset = aligned_base - extra_base; 167116441Sharti size_t end_offset = (extra_base + extra_size) - (aligned_base + size); 168116441Sharti 169116523Sharti if (begin_offset > 0) { 170116523Sharti os::release_memory(extra_base, begin_offset); 171116523Sharti } 172116441Sharti 173117625Sharti if (end_offset > 0) { 174116441Sharti os::release_memory(extra_base + begin_offset + size, end_offset); 175114739Sharti } 176114739Sharti 177114739Sharti return aligned_base; 178114739Sharti} 179147256Sbrooks 180114739Shartiint os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) { 181114739Sharti return vsnprintf(buf, len, fmt, args); 182114739Sharti} 183114739Sharti 184147256Sbrooksvoid os::Posix::print_load_average(outputStream* st) { 185117625Sharti st->print("load average:"); 186114739Sharti double loadavg[3]; 187116480Sharti os::loadavg(loadavg, 3); 188116480Sharti st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); 189116480Sharti st->cr(); 190116480Sharti} 191116480Sharti 192116480Shartivoid os::Posix::print_rlimit_info(outputStream* st) { 193116480Sharti st->print("rlimit:"); 194116480Sharti struct rlimit rlim; 195116480Sharti 196116480Sharti st->print(" STACK "); 197116480Sharti getrlimit(RLIMIT_STACK, &rlim); 198116480Sharti if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 199116480Sharti else st->print("%luk", rlim.rlim_cur >> 10); 200116480Sharti 201116480Sharti st->print(", CORE "); 202116480Sharti getrlimit(RLIMIT_CORE, &rlim); 20325603Skjc if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 204116523Sharti else st->print("%luk", rlim.rlim_cur >> 10); 20525603Skjc 206116523Sharti // Isn't there on solaris 20725603Skjc#if !defined(TARGET_OS_FAMILY_solaris) && !defined(TARGET_OS_FAMILY_aix) 20825603Skjc st->print(", NPROC "); 20925603Skjc getrlimit(RLIMIT_NPROC, &rlim); 21025603Skjc if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 21125603Skjc else st->print("%lu", rlim.rlim_cur); 21225603Skjc#endif 213116523Sharti 21425603Skjc st->print(", NOFILE "); 21525603Skjc getrlimit(RLIMIT_NOFILE, &rlim); 216116523Sharti if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 217116523Sharti else st->print("%lu", rlim.rlim_cur); 218116523Sharti 219116523Sharti st->print(", AS "); 22025603Skjc getrlimit(RLIMIT_AS, &rlim); 22125603Skjc if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 22225603Skjc else st->print("%luk", rlim.rlim_cur >> 10); 22325603Skjc st->cr(); 224117627Sharti} 225118548Sharti 226117627Shartivoid os::Posix::print_uname_info(outputStream* st) { 227117627Sharti // kernel 22825603Skjc st->print("uname:"); 229116523Sharti struct utsname name; 230116523Sharti uname(&name); 23125603Skjc st->print("%s ", name.sysname); 232116523Sharti#ifdef ASSERT 23325603Skjc st->print("%s ", name.nodename); 23425603Skjc#endif 23525603Skjc st->print("%s ", name.release); 236116523Sharti st->print("%s ", name.version); 237116523Sharti st->print("%s", name.machine); 238116523Sharti st->cr(); 23925603Skjc} 240116523Sharti 24137939Skjcbool os::get_host_name(char* buf, size_t buflen) { 24225603Skjc struct utsname name; 24325603Skjc uname(&name); 24425603Skjc jio_snprintf(buf, buflen, "%s", name.nodename); 245116523Sharti return true; 24625603Skjc} 247116523Sharti 248116523Shartibool os::has_allocatable_memory_limit(julong* limit) { 24925603Skjc struct rlimit rlim; 25025603Skjc int getrlimit_res = getrlimit(RLIMIT_AS, &rlim); 25125603Skjc // if there was an error when calling getrlimit, assume that there is no limitation 252116523Sharti // on virtual memory. 253116523Sharti bool result; 254116523Sharti if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) { 255116523Sharti result = false; 256116523Sharti } else { 25725603Skjc *limit = (julong)rlim.rlim_cur; 258118157Sharti result = true; 259118157Sharti } 260118157Sharti#ifdef _LP64 261118157Sharti return result; 262118157Sharti#else 263118157Sharti // arbitrary virtual space limit for 32 bit Unices found by testing. If 264118157Sharti // getrlimit above returned a limit, bound it with this limit. Otherwise 265118157Sharti // directly use it. 266118157Sharti const julong max_virtual_limit = (julong)3800*M; 267118157Sharti if (result) { 268118157Sharti *limit = MIN2(*limit, max_virtual_limit); 269118157Sharti } else { 270118157Sharti *limit = max_virtual_limit; 271118157Sharti } 272118157Sharti 273118157Sharti // bound by actually allocatable memory. The algorithm uses two bounds, an 274118157Sharti // upper and a lower limit. The upper limit is the current highest amount of 275118157Sharti // memory that could not be allocated, the lower limit is the current highest 276118157Sharti // amount of memory that could be allocated. 277118157Sharti // The algorithm iteratively refines the result by halving the difference 278118157Sharti // between these limits, updating either the upper limit (if that value could 279118157Sharti // not be allocated) or the lower limit (if the that value could be allocated) 280118157Sharti // until the difference between these limits is "small". 281118157Sharti 282118157Sharti // the minimum amount of memory we care about allocating. 283118157Sharti const julong min_allocation_size = M; 284118157Sharti 285118157Sharti julong upper_limit = *limit; 286118157Sharti 287118157Sharti // first check a few trivial cases 288118157Sharti if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) { 289118157Sharti *limit = upper_limit; 29025603Skjc } else if (!is_allocatable(min_allocation_size)) { 29192725Salfred // we found that not even min_allocation_size is allocatable. Return it 292114201Sharti // anyway. There is no point to search for a better value any more. 29392725Salfred *limit = min_allocation_size; 294116523Sharti } else { 29592725Salfred // perform the binary search. 296116523Sharti julong lower_limit = min_allocation_size; 297117630Sharti while ((upper_limit - lower_limit) > min_allocation_size) { 298117630Sharti julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit; 299118157Sharti temp_limit = align_size_down_(temp_limit, min_allocation_size); 300118157Sharti if (is_allocatable(temp_limit)) { 301118157Sharti lower_limit = temp_limit; 302118157Sharti } else { 303118157Sharti upper_limit = temp_limit; 304118157Sharti } 305118157Sharti } 306118157Sharti *limit = lower_limit; 307118157Sharti } 308147256Sbrooks return true; 309118157Sharti#endif 310118157Sharti} 311118157Sharti 312118157Sharticonst char* os::get_current_directory(char *buf, size_t buflen) { 313118157Sharti return getcwd(buf, buflen); 314118157Sharti} 315118157Sharti 316118157ShartiFILE* os::open(int fd, const char* mode) { 317147256Sbrooks return ::fdopen(fd, mode); 318118157Sharti} 319118157Sharti 320118157Sharti// Builds a platform dependent Agent_OnLoad_<lib_name> function name 321118157Sharti// which is used to find statically linked in agents. 322118157Sharti// Parameters: 323148887Srwatson// sym_name: Symbol in library we are looking for 324148887Srwatson// lib_name: Name of library to look in, NULL for shared libs. 325118157Sharti// is_absolute_path == true if lib_name is absolute path to agent 326147256Sbrooks// such as "/a/b/libL.so" 327118157Sharti// == false if only the base name of the library is passed in 328118157Sharti// such as "L" 329118157Shartichar* os::build_agent_function_name(const char *sym_name, const char *lib_name, 330118157Sharti bool is_absolute_path) { 331118157Sharti char *agent_entry_name; 332118157Sharti size_t len; 333118157Sharti size_t name_len; 334118157Sharti size_t prefix_len = strlen(JNI_LIB_PREFIX); 335147256Sbrooks size_t suffix_len = strlen(JNI_LIB_SUFFIX); 336118157Sharti const char *start; 33725603Skjc 338 if (lib_name != NULL) { 339 len = name_len = strlen(lib_name); 340 if (is_absolute_path) { 341 // Need to strip path, prefix and suffix 342 if ((start = strrchr(lib_name, *os::file_separator())) != NULL) { 343 lib_name = ++start; 344 } 345 if (len <= (prefix_len + suffix_len)) { 346 return NULL; 347 } 348 lib_name += prefix_len; 349 name_len = strlen(lib_name) - suffix_len; 350 } 351 } 352 len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2; 353 agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread); 354 if (agent_entry_name == NULL) { 355 return NULL; 356 } 357 strcpy(agent_entry_name, sym_name); 358 if (lib_name != NULL) { 359 strcat(agent_entry_name, "_"); 360 strncat(agent_entry_name, lib_name, name_len); 361 } 362 return agent_entry_name; 363} 364 365int os::sleep(Thread* thread, jlong millis, bool interruptible) { 366 assert(thread == Thread::current(), "thread consistency check"); 367 368 ParkEvent * const slp = thread->_SleepEvent ; 369 slp->reset() ; 370 OrderAccess::fence() ; 371 372 if (interruptible) { 373 jlong prevtime = javaTimeNanos(); 374 375 for (;;) { 376 if (os::is_interrupted(thread, true)) { 377 return OS_INTRPT; 378 } 379 380 jlong newtime = javaTimeNanos(); 381 382 if (newtime - prevtime < 0) { 383 // time moving backwards, should only happen if no monotonic clock 384 // not a guarantee() because JVM should not abort on kernel/glibc bugs 385 assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)"); 386 } else { 387 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 388 } 389 390 if (millis <= 0) { 391 return OS_OK; 392 } 393 394 prevtime = newtime; 395 396 { 397 assert(thread->is_Java_thread(), "sanity check"); 398 JavaThread *jt = (JavaThread *) thread; 399 ThreadBlockInVM tbivm(jt); 400 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); 401 402 jt->set_suspend_equivalent(); 403 // cleared by handle_special_suspend_equivalent_condition() or 404 // java_suspend_self() via check_and_wait_while_suspended() 405 406 slp->park(millis); 407 408 // were we externally suspended while we were waiting? 409 jt->check_and_wait_while_suspended(); 410 } 411 } 412 } else { 413 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 414 jlong prevtime = javaTimeNanos(); 415 416 for (;;) { 417 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on 418 // the 1st iteration ... 419 jlong newtime = javaTimeNanos(); 420 421 if (newtime - prevtime < 0) { 422 // time moving backwards, should only happen if no monotonic clock 423 // not a guarantee() because JVM should not abort on kernel/glibc bugs 424 assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)"); 425 } else { 426 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 427 } 428 429 if (millis <= 0) break ; 430 431 prevtime = newtime; 432 slp->park(millis); 433 } 434 return OS_OK ; 435 } 436} 437 438//////////////////////////////////////////////////////////////////////////////// 439// interrupt support 440 441void os::interrupt(Thread* thread) { 442 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 443 "possibility of dangling Thread pointer"); 444 445 OSThread* osthread = thread->osthread(); 446 447 if (!osthread->interrupted()) { 448 osthread->set_interrupted(true); 449 // More than one thread can get here with the same value of osthread, 450 // resulting in multiple notifications. We do, however, want the store 451 // to interrupted() to be visible to other threads before we execute unpark(). 452 OrderAccess::fence(); 453 ParkEvent * const slp = thread->_SleepEvent ; 454 if (slp != NULL) slp->unpark() ; 455 } 456 457 // For JSR166. Unpark even if interrupt status already was set 458 if (thread->is_Java_thread()) 459 ((JavaThread*)thread)->parker()->unpark(); 460 461 ParkEvent * ev = thread->_ParkEvent ; 462 if (ev != NULL) ev->unpark() ; 463 464} 465 466bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 467 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 468 "possibility of dangling Thread pointer"); 469 470 OSThread* osthread = thread->osthread(); 471 472 bool interrupted = osthread->interrupted(); 473 474 // NOTE that since there is no "lock" around the interrupt and 475 // is_interrupted operations, there is the possibility that the 476 // interrupted flag (in osThread) will be "false" but that the 477 // low-level events will be in the signaled state. This is 478 // intentional. The effect of this is that Object.wait() and 479 // LockSupport.park() will appear to have a spurious wakeup, which 480 // is allowed and not harmful, and the possibility is so rare that 481 // it is not worth the added complexity to add yet another lock. 482 // For the sleep event an explicit reset is performed on entry 483 // to os::sleep, so there is no early return. It has also been 484 // recommended not to put the interrupted flag into the "event" 485 // structure because it hides the issue. 486 if (interrupted && clear_interrupted) { 487 osthread->set_interrupted(false); 488 // consider thread->_SleepEvent->reset() ... optional optimization 489 } 490 491 return interrupted; 492} 493 494 495 496static const struct { 497 int sig; const char* name; 498} 499 g_signal_info[] = 500 { 501 { SIGABRT, "SIGABRT" }, 502#ifdef SIGAIO 503 { SIGAIO, "SIGAIO" }, 504#endif 505 { SIGALRM, "SIGALRM" }, 506#ifdef SIGALRM1 507 { SIGALRM1, "SIGALRM1" }, 508#endif 509 { SIGBUS, "SIGBUS" }, 510#ifdef SIGCANCEL 511 { SIGCANCEL, "SIGCANCEL" }, 512#endif 513 { SIGCHLD, "SIGCHLD" }, 514#ifdef SIGCLD 515 { SIGCLD, "SIGCLD" }, 516#endif 517 { SIGCONT, "SIGCONT" }, 518#ifdef SIGCPUFAIL 519 { SIGCPUFAIL, "SIGCPUFAIL" }, 520#endif 521#ifdef SIGDANGER 522 { SIGDANGER, "SIGDANGER" }, 523#endif 524#ifdef SIGDIL 525 { SIGDIL, "SIGDIL" }, 526#endif 527#ifdef SIGEMT 528 { SIGEMT, "SIGEMT" }, 529#endif 530 { SIGFPE, "SIGFPE" }, 531#ifdef SIGFREEZE 532 { SIGFREEZE, "SIGFREEZE" }, 533#endif 534#ifdef SIGGFAULT 535 { SIGGFAULT, "SIGGFAULT" }, 536#endif 537#ifdef SIGGRANT 538 { SIGGRANT, "SIGGRANT" }, 539#endif 540 { SIGHUP, "SIGHUP" }, 541 { SIGILL, "SIGILL" }, 542 { SIGINT, "SIGINT" }, 543#ifdef SIGIO 544 { SIGIO, "SIGIO" }, 545#endif 546#ifdef SIGIOINT 547 { SIGIOINT, "SIGIOINT" }, 548#endif 549#ifdef SIGIOT 550// SIGIOT is there for BSD compatibility, but on most Unices just a 551// synonym for SIGABRT. The result should be "SIGABRT", not 552// "SIGIOT". 553#if (SIGIOT != SIGABRT ) 554 { SIGIOT, "SIGIOT" }, 555#endif 556#endif 557#ifdef SIGKAP 558 { SIGKAP, "SIGKAP" }, 559#endif 560 { SIGKILL, "SIGKILL" }, 561#ifdef SIGLOST 562 { SIGLOST, "SIGLOST" }, 563#endif 564#ifdef SIGLWP 565 { SIGLWP, "SIGLWP" }, 566#endif 567#ifdef SIGLWPTIMER 568 { SIGLWPTIMER, "SIGLWPTIMER" }, 569#endif 570#ifdef SIGMIGRATE 571 { SIGMIGRATE, "SIGMIGRATE" }, 572#endif 573#ifdef SIGMSG 574 { SIGMSG, "SIGMSG" }, 575#endif 576 { SIGPIPE, "SIGPIPE" }, 577#ifdef SIGPOLL 578 { SIGPOLL, "SIGPOLL" }, 579#endif 580#ifdef SIGPRE 581 { SIGPRE, "SIGPRE" }, 582#endif 583 { SIGPROF, "SIGPROF" }, 584#ifdef SIGPTY 585 { SIGPTY, "SIGPTY" }, 586#endif 587#ifdef SIGPWR 588 { SIGPWR, "SIGPWR" }, 589#endif 590 { SIGQUIT, "SIGQUIT" }, 591#ifdef SIGRECONFIG 592 { SIGRECONFIG, "SIGRECONFIG" }, 593#endif 594#ifdef SIGRECOVERY 595 { SIGRECOVERY, "SIGRECOVERY" }, 596#endif 597#ifdef SIGRESERVE 598 { SIGRESERVE, "SIGRESERVE" }, 599#endif 600#ifdef SIGRETRACT 601 { SIGRETRACT, "SIGRETRACT" }, 602#endif 603#ifdef SIGSAK 604 { SIGSAK, "SIGSAK" }, 605#endif 606 { SIGSEGV, "SIGSEGV" }, 607#ifdef SIGSOUND 608 { SIGSOUND, "SIGSOUND" }, 609#endif 610#ifdef SIGSTKFLT 611 { SIGSTKFLT, "SIGSTKFLT" }, 612#endif 613 { SIGSTOP, "SIGSTOP" }, 614 { SIGSYS, "SIGSYS" }, 615#ifdef SIGSYSERROR 616 { SIGSYSERROR, "SIGSYSERROR" }, 617#endif 618#ifdef SIGTALRM 619 { SIGTALRM, "SIGTALRM" }, 620#endif 621 { SIGTERM, "SIGTERM" }, 622#ifdef SIGTHAW 623 { SIGTHAW, "SIGTHAW" }, 624#endif 625 { SIGTRAP, "SIGTRAP" }, 626#ifdef SIGTSTP 627 { SIGTSTP, "SIGTSTP" }, 628#endif 629 { SIGTTIN, "SIGTTIN" }, 630 { SIGTTOU, "SIGTTOU" }, 631#ifdef SIGURG 632 { SIGURG, "SIGURG" }, 633#endif 634 { SIGUSR1, "SIGUSR1" }, 635 { SIGUSR2, "SIGUSR2" }, 636#ifdef SIGVIRT 637 { SIGVIRT, "SIGVIRT" }, 638#endif 639 { SIGVTALRM, "SIGVTALRM" }, 640#ifdef SIGWAITING 641 { SIGWAITING, "SIGWAITING" }, 642#endif 643#ifdef SIGWINCH 644 { SIGWINCH, "SIGWINCH" }, 645#endif 646#ifdef SIGWINDOW 647 { SIGWINDOW, "SIGWINDOW" }, 648#endif 649 { SIGXCPU, "SIGXCPU" }, 650 { SIGXFSZ, "SIGXFSZ" }, 651#ifdef SIGXRES 652 { SIGXRES, "SIGXRES" }, 653#endif 654 { -1, NULL } 655}; 656 657// Returned string is a constant. For unknown signals "UNKNOWN" is returned. 658const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) { 659 660 const char* ret = NULL; 661 662#ifdef SIGRTMIN 663 if (sig >= SIGRTMIN && sig <= SIGRTMAX) { 664 if (sig == SIGRTMIN) { 665 ret = "SIGRTMIN"; 666 } else if (sig == SIGRTMAX) { 667 ret = "SIGRTMAX"; 668 } else { 669 jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN); 670 return out; 671 } 672 } 673#endif 674 675 if (sig > 0) { 676 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 677 if (g_signal_info[idx].sig == sig) { 678 ret = g_signal_info[idx].name; 679 break; 680 } 681 } 682 } 683 684 if (!ret) { 685 if (!is_valid_signal(sig)) { 686 ret = "INVALID"; 687 } else { 688 ret = "UNKNOWN"; 689 } 690 } 691 692 if (out && outlen > 0) { 693 strncpy(out, ret, outlen); 694 out[outlen - 1] = '\0'; 695 } 696 return out; 697} 698 699int os::Posix::get_signal_number(const char* signal_name) { 700 char tmp[30]; 701 const char* s = signal_name; 702 if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') { 703 jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name); 704 s = tmp; 705 } 706 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 707 if (strcmp(g_signal_info[idx].name, s) == 0) { 708 return g_signal_info[idx].sig; 709 } 710 } 711 return -1; 712} 713 714int os::get_signal_number(const char* signal_name) { 715 return os::Posix::get_signal_number(signal_name); 716} 717 718// Returns true if signal number is valid. 719bool os::Posix::is_valid_signal(int sig) { 720 // MacOS not really POSIX compliant: sigaddset does not return 721 // an error for invalid signal numbers. However, MacOS does not 722 // support real time signals and simply seems to have just 33 723 // signals with no holes in the signal range. 724#ifdef __APPLE__ 725 return sig >= 1 && sig < NSIG; 726#else 727 // Use sigaddset to check for signal validity. 728 sigset_t set; 729 if (sigaddset(&set, sig) == -1 && errno == EINVAL) { 730 return false; 731 } 732 return true; 733#endif 734} 735 736// Returns: 737// NULL for an invalid signal number 738// "SIG<num>" for a valid but unknown signal number 739// signal name otherwise. 740const char* os::exception_name(int sig, char* buf, size_t size) { 741 if (!os::Posix::is_valid_signal(sig)) { 742 return NULL; 743 } 744 const char* const name = os::Posix::get_signal_name(sig, buf, size); 745 if (strcmp(name, "UNKNOWN") == 0) { 746 jio_snprintf(buf, size, "SIG%d", sig); 747 } 748 return buf; 749} 750 751#define NUM_IMPORTANT_SIGS 32 752// Returns one-line short description of a signal set in a user provided buffer. 753const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) { 754 assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size"); 755 // Note: for shortness, just print out the first 32. That should 756 // cover most of the useful ones, apart from realtime signals. 757 for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) { 758 const int rc = sigismember(set, sig); 759 if (rc == -1 && errno == EINVAL) { 760 buffer[sig-1] = '?'; 761 } else { 762 buffer[sig-1] = rc == 0 ? '0' : '1'; 763 } 764 } 765 buffer[NUM_IMPORTANT_SIGS] = 0; 766 return buffer; 767} 768 769// Prints one-line description of a signal set. 770void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) { 771 char buf[NUM_IMPORTANT_SIGS + 1]; 772 os::Posix::describe_signal_set_short(set, buf, sizeof(buf)); 773 st->print("%s", buf); 774} 775 776// Writes one-line description of a combination of sigaction.sa_flags into a user 777// provided buffer. Returns that buffer. 778const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) { 779 char* p = buffer; 780 size_t remaining = size; 781 bool first = true; 782 int idx = 0; 783 784 assert(buffer, "invalid argument"); 785 786 if (size == 0) { 787 return buffer; 788 } 789 790 strncpy(buffer, "none", size); 791 792 const struct { 793 // NB: i is an unsigned int here because SA_RESETHAND is on some 794 // systems 0x80000000, which is implicitly unsigned. Assignining 795 // it to an int field would be an overflow in unsigned-to-signed 796 // conversion. 797 unsigned int i; 798 const char* s; 799 } flaginfo [] = { 800 { SA_NOCLDSTOP, "SA_NOCLDSTOP" }, 801 { SA_ONSTACK, "SA_ONSTACK" }, 802 { SA_RESETHAND, "SA_RESETHAND" }, 803 { SA_RESTART, "SA_RESTART" }, 804 { SA_SIGINFO, "SA_SIGINFO" }, 805 { SA_NOCLDWAIT, "SA_NOCLDWAIT" }, 806 { SA_NODEFER, "SA_NODEFER" }, 807#ifdef AIX 808 { SA_ONSTACK, "SA_ONSTACK" }, 809 { SA_OLDSTYLE, "SA_OLDSTYLE" }, 810#endif 811 { 0, NULL } 812 }; 813 814 for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) { 815 if (flags & flaginfo[idx].i) { 816 if (first) { 817 jio_snprintf(p, remaining, "%s", flaginfo[idx].s); 818 first = false; 819 } else { 820 jio_snprintf(p, remaining, "|%s", flaginfo[idx].s); 821 } 822 const size_t len = strlen(p); 823 p += len; 824 remaining -= len; 825 } 826 } 827 828 buffer[size - 1] = '\0'; 829 830 return buffer; 831} 832 833// Prints one-line description of a combination of sigaction.sa_flags. 834void os::Posix::print_sa_flags(outputStream* st, int flags) { 835 char buffer[0x100]; 836 os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer)); 837 st->print("%s", buffer); 838} 839 840// Helper function for os::Posix::print_siginfo_...(): 841// return a textual description for signal code. 842struct enum_sigcode_desc_t { 843 const char* s_name; 844 const char* s_desc; 845}; 846 847static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) { 848 849 const struct { 850 int sig; int code; const char* s_code; const char* s_desc; 851 } t1 [] = { 852 { SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode." }, 853 { SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand." }, 854 { SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode." }, 855 { SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap." }, 856 { SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode." }, 857 { SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register." }, 858 { SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error." }, 859 { SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error." }, 860#if defined(IA64) && defined(LINUX) 861 { SIGILL, ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" }, 862 { SIGILL, ILL_BREAK, "ILL_BREAK", "Application Break instruction" }, 863#endif 864 { SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero." }, 865 { SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow." }, 866 { SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating-point divide by zero." }, 867 { SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating-point overflow." }, 868 { SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating-point underflow." }, 869 { SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating-point inexact result." }, 870 { SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating-point operation." }, 871 { SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range." }, 872 { SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object." }, 873 { SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for mapped object." }, 874#ifdef AIX 875 // no explanation found what keyerr would be 876 { SIGSEGV, SEGV_KEYERR, "SEGV_KEYERR", "key error" }, 877#endif 878#if defined(IA64) && !defined(AIX) 879 { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" }, 880#endif 881#if defined(__sparc) && defined(SOLARIS) 882// define Solaris Sparc M7 ADI SEGV signals 883#if !defined(SEGV_ACCADI) 884#define SEGV_ACCADI 3 885#endif 886 { SIGSEGV, SEGV_ACCADI, "SEGV_ACCADI", "ADI not enabled for mapped object." }, 887#if !defined(SEGV_ACCDERR) 888#define SEGV_ACCDERR 4 889#endif 890 { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." }, 891#if !defined(SEGV_ACCPERR) 892#define SEGV_ACCPERR 5 893#endif 894 { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." }, 895#endif // defined(__sparc) && defined(SOLARIS) 896 { SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment." }, 897 { SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Nonexistent physical address." }, 898 { SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object-specific hardware error." }, 899 { SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint." }, 900 { SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap." }, 901 { SIGCHLD, CLD_EXITED, "CLD_EXITED", "Child has exited." }, 902 { SIGCHLD, CLD_KILLED, "CLD_KILLED", "Child has terminated abnormally and did not create a core file." }, 903 { SIGCHLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally and created a core file." }, 904 { SIGCHLD, CLD_TRAPPED, "CLD_TRAPPED", "Traced child has trapped." }, 905 { SIGCHLD, CLD_STOPPED, "CLD_STOPPED", "Child has stopped." }, 906 { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." }, 907#ifdef SIGPOLL 908 { SIGPOLL, POLL_OUT, "POLL_OUT", "Output buffers available." }, 909 { SIGPOLL, POLL_MSG, "POLL_MSG", "Input message available." }, 910 { SIGPOLL, POLL_ERR, "POLL_ERR", "I/O error." }, 911 { SIGPOLL, POLL_PRI, "POLL_PRI", "High priority input available." }, 912 { SIGPOLL, POLL_HUP, "POLL_HUP", "Device disconnected. [Option End]" }, 913#endif 914 { -1, -1, NULL, NULL } 915 }; 916 917 // Codes valid in any signal context. 918 const struct { 919 int code; const char* s_code; const char* s_desc; 920 } t2 [] = { 921 { SI_USER, "SI_USER", "Signal sent by kill()." }, 922 { SI_QUEUE, "SI_QUEUE", "Signal sent by the sigqueue()." }, 923 { SI_TIMER, "SI_TIMER", "Signal generated by expiration of a timer set by timer_settime()." }, 924 { SI_ASYNCIO, "SI_ASYNCIO", "Signal generated by completion of an asynchronous I/O request." }, 925 { SI_MESGQ, "SI_MESGQ", "Signal generated by arrival of a message on an empty message queue." }, 926 // Linux specific 927#ifdef SI_TKILL 928 { SI_TKILL, "SI_TKILL", "Signal sent by tkill (pthread_kill)" }, 929#endif 930#ifdef SI_DETHREAD 931 { SI_DETHREAD, "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" }, 932#endif 933#ifdef SI_KERNEL 934 { SI_KERNEL, "SI_KERNEL", "Signal sent by kernel." }, 935#endif 936#ifdef SI_SIGIO 937 { SI_SIGIO, "SI_SIGIO", "Signal sent by queued SIGIO" }, 938#endif 939 940#ifdef AIX 941 { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" }, 942 { SI_EMPTY, "SI_EMPTY", "siginfo contains no useful information" }, 943#endif 944 945#ifdef __sun 946 { SI_NOINFO, "SI_NOINFO", "No signal information" }, 947 { SI_RCTL, "SI_RCTL", "kernel generated signal via rctl action" }, 948 { SI_LWP, "SI_LWP", "Signal sent via lwp_kill" }, 949#endif 950 951 { -1, NULL, NULL } 952 }; 953 954 const char* s_code = NULL; 955 const char* s_desc = NULL; 956 957 for (int i = 0; t1[i].sig != -1; i ++) { 958 if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) { 959 s_code = t1[i].s_code; 960 s_desc = t1[i].s_desc; 961 break; 962 } 963 } 964 965 if (s_code == NULL) { 966 for (int i = 0; t2[i].s_code != NULL; i ++) { 967 if (t2[i].code == si->si_code) { 968 s_code = t2[i].s_code; 969 s_desc = t2[i].s_desc; 970 } 971 } 972 } 973 974 if (s_code == NULL) { 975 out->s_name = "unknown"; 976 out->s_desc = "unknown"; 977 return false; 978 } 979 980 out->s_name = s_code; 981 out->s_desc = s_desc; 982 983 return true; 984} 985 986void os::print_siginfo(outputStream* os, const void* si0) { 987 988 const siginfo_t* const si = (const siginfo_t*) si0; 989 990 char buf[20]; 991 os->print("siginfo:"); 992 993 if (!si) { 994 os->print(" <null>"); 995 return; 996 } 997 998 const int sig = si->si_signo; 999 1000 os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf))); 1001 1002 enum_sigcode_desc_t ed; 1003 get_signal_code_description(si, &ed); 1004 os->print(", si_code: %d (%s)", si->si_code, ed.s_name); 1005 1006 if (si->si_errno) { 1007 os->print(", si_errno: %d", si->si_errno); 1008 } 1009 1010 // Output additional information depending on the signal code. 1011 1012 // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions, 1013 // so it depends on the context which member to use. For synchronous error signals, 1014 // we print si_addr, unless the signal was sent by another process or thread, in 1015 // which case we print out pid or tid of the sender. 1016 if (si->si_code == SI_USER || si->si_code == SI_QUEUE) { 1017 const pid_t pid = si->si_pid; 1018 os->print(", si_pid: %ld", (long) pid); 1019 if (IS_VALID_PID(pid)) { 1020 const pid_t me = getpid(); 1021 if (me == pid) { 1022 os->print(" (current process)"); 1023 } 1024 } else { 1025 os->print(" (invalid)"); 1026 } 1027 os->print(", si_uid: %ld", (long) si->si_uid); 1028 if (sig == SIGCHLD) { 1029 os->print(", si_status: %d", si->si_status); 1030 } 1031 } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || 1032 sig == SIGTRAP || sig == SIGFPE) { 1033 os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr)); 1034#ifdef SIGPOLL 1035 } else if (sig == SIGPOLL) { 1036 os->print(", si_band: %ld", si->si_band); 1037#endif 1038 } 1039 1040} 1041 1042int os::Posix::unblock_thread_signal_mask(const sigset_t *set) { 1043 return pthread_sigmask(SIG_UNBLOCK, set, NULL); 1044} 1045 1046address os::Posix::ucontext_get_pc(const ucontext_t* ctx) { 1047#ifdef TARGET_OS_FAMILY_linux 1048 return Linux::ucontext_get_pc(ctx); 1049#elif defined(TARGET_OS_FAMILY_solaris) 1050 return Solaris::ucontext_get_pc(ctx); 1051#elif defined(TARGET_OS_FAMILY_aix) 1052 return Aix::ucontext_get_pc(ctx); 1053#elif defined(TARGET_OS_FAMILY_bsd) 1054 return Bsd::ucontext_get_pc(ctx); 1055#else 1056 VMError::report_and_die("unimplemented ucontext_get_pc"); 1057#endif 1058} 1059 1060void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) { 1061#ifdef TARGET_OS_FAMILY_linux 1062 Linux::ucontext_set_pc(ctx, pc); 1063#elif defined(TARGET_OS_FAMILY_solaris) 1064 Solaris::ucontext_set_pc(ctx, pc); 1065#elif defined(TARGET_OS_FAMILY_aix) 1066 Aix::ucontext_set_pc(ctx, pc); 1067#elif defined(TARGET_OS_FAMILY_bsd) 1068 Bsd::ucontext_set_pc(ctx, pc); 1069#else 1070 VMError::report_and_die("unimplemented ucontext_get_pc"); 1071#endif 1072} 1073 1074 1075os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() { 1076 assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread"); 1077} 1078 1079/* 1080 * See the caveats for this class in os_posix.hpp 1081 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this 1082 * method and returns false. If none of the signals are raised, returns true. 1083 * The callback is supposed to provide the method that should be protected. 1084 */ 1085bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) { 1086 sigset_t saved_sig_mask; 1087 1088 assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread"); 1089 assert(!WatcherThread::watcher_thread()->has_crash_protection(), 1090 "crash_protection already set?"); 1091 1092 // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask 1093 // since on at least some systems (OS X) siglongjmp will restore the mask 1094 // for the process, not the thread 1095 pthread_sigmask(0, NULL, &saved_sig_mask); 1096 if (sigsetjmp(_jmpbuf, 0) == 0) { 1097 // make sure we can see in the signal handler that we have crash protection 1098 // installed 1099 WatcherThread::watcher_thread()->set_crash_protection(this); 1100 cb.call(); 1101 // and clear the crash protection 1102 WatcherThread::watcher_thread()->set_crash_protection(NULL); 1103 return true; 1104 } 1105 // this happens when we siglongjmp() back 1106 pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL); 1107 WatcherThread::watcher_thread()->set_crash_protection(NULL); 1108 return false; 1109} 1110 1111void os::WatcherThreadCrashProtection::restore() { 1112 assert(WatcherThread::watcher_thread()->has_crash_protection(), 1113 "must have crash protection"); 1114 1115 siglongjmp(_jmpbuf, 1); 1116} 1117 1118void os::WatcherThreadCrashProtection::check_crash_protection(int sig, 1119 Thread* thread) { 1120 1121 if (thread != NULL && 1122 thread->is_Watcher_thread() && 1123 WatcherThread::watcher_thread()->has_crash_protection()) { 1124 1125 if (sig == SIGSEGV || sig == SIGBUS) { 1126 WatcherThread::watcher_thread()->crash_protection()->restore(); 1127 } 1128 } 1129} 1130 1131#define check_with_errno(check_type, cond, msg) \ 1132 do { \ 1133 int err = errno; \ 1134 check_type(cond, "%s; error='%s' (errno=%d)", msg, strerror(err), err); \ 1135} while (false) 1136 1137#define assert_with_errno(cond, msg) check_with_errno(assert, cond, msg) 1138#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg) 1139 1140// POSIX unamed semaphores are not supported on OS X. 1141#ifndef __APPLE__ 1142 1143PosixSemaphore::PosixSemaphore(uint value) { 1144 int ret = sem_init(&_semaphore, 0, value); 1145 1146 guarantee_with_errno(ret == 0, "Failed to initialize semaphore"); 1147} 1148 1149PosixSemaphore::~PosixSemaphore() { 1150 sem_destroy(&_semaphore); 1151} 1152 1153void PosixSemaphore::signal(uint count) { 1154 for (uint i = 0; i < count; i++) { 1155 int ret = sem_post(&_semaphore); 1156 1157 assert_with_errno(ret == 0, "sem_post failed"); 1158 } 1159} 1160 1161void PosixSemaphore::wait() { 1162 int ret; 1163 1164 do { 1165 ret = sem_wait(&_semaphore); 1166 } while (ret != 0 && errno == EINTR); 1167 1168 assert_with_errno(ret == 0, "sem_wait failed"); 1169} 1170 1171bool PosixSemaphore::trywait() { 1172 int ret; 1173 1174 do { 1175 ret = sem_trywait(&_semaphore); 1176 } while (ret != 0 && errno == EINTR); 1177 1178 assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed"); 1179 1180 return ret == 0; 1181} 1182 1183bool PosixSemaphore::timedwait(struct timespec ts) { 1184 while (true) { 1185 int result = sem_timedwait(&_semaphore, &ts); 1186 if (result == 0) { 1187 return true; 1188 } else if (errno == EINTR) { 1189 continue; 1190 } else if (errno == ETIMEDOUT) { 1191 return false; 1192 } else { 1193 assert_with_errno(false, "timedwait failed"); 1194 return false; 1195 } 1196 } 1197} 1198 1199#endif // __APPLE__ 1200