blob: d2261e21768c70c363bd88c3aff1192dbd3806b3 [file] [log] [blame]
/*--------------------------------------------------------------------*/
/*--- Helgrind: a Valgrind tool for detecting errors ---*/
/*--- in threaded programs. hg_main.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Helgrind, a Valgrind tool for detecting errors
in threaded programs.
Copyright (C) 2007-2013 OpenWorks LLP
info@open-works.co.uk
Copyright (C) 2007-2013 Apple, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA.
The GNU General Public License is contained in the file COPYING.
Neither the names of the U.S. Department of Energy nor the
University of California nor the names of its contributors may be
used to endorse or promote products derived from this software
without prior written permission.
*/
#include "pub_tool_basics.h"
#include "pub_tool_gdbserver.h"
#include "pub_tool_libcassert.h"
#include "pub_tool_libcbase.h"
#include "pub_tool_libcprint.h"
#include "pub_tool_threadstate.h"
#include "pub_tool_tooliface.h"
#include "pub_tool_hashtable.h"
#include "pub_tool_replacemalloc.h"
#include "pub_tool_machine.h"
#include "pub_tool_options.h"
#include "pub_tool_xarray.h"
#include "pub_tool_stacktrace.h"
#include "pub_tool_wordfm.h"
#include "pub_tool_debuginfo.h" // VG_(find_seginfo), VG_(seginfo_soname)
#include "pub_tool_redir.h" // sonames for the dynamic linkers
#include "pub_tool_vki.h" // VKI_PAGE_SIZE
#include "pub_tool_libcproc.h" // VG_(atfork)
#include "pub_tool_aspacemgr.h" // VG_(am_is_valid_for_client)
#include "pub_tool_poolalloc.h"
#include "pub_tool_addrinfo.h"
#include "hg_basics.h"
#include "hg_wordset.h"
#include "hg_addrdescr.h"
#include "hg_lock_n_thread.h"
#include "hg_errors.h"
#include "libhb.h"
#include "helgrind.h"
// FIXME: new_mem_w_tid ignores the supplied tid. (wtf?!)
// FIXME: when client destroys a lock or a CV, remove these
// from our mappings, so that the associated SO can be freed up
/*----------------------------------------------------------------*/
/*--- ---*/
/*----------------------------------------------------------------*/
/* Note this needs to be compiled with -fno-strict-aliasing, since it
contains a whole bunch of calls to lookupFM etc which cast between
Word and pointer types. gcc rightly complains this breaks ANSI C
strict aliasing rules, at -O2. No complaints at -O, but -O2 gives
worthwhile performance benefits over -O.
*/
// FIXME what is supposed to happen to locks in memory which
// is relocated as a result of client realloc?
// FIXME put referencing ThreadId into Thread and get
// rid of the slow reverse mapping function.
// FIXME accesses to NoAccess areas: change state to Excl?
// FIXME report errors for accesses of NoAccess memory?
// FIXME pth_cond_wait/timedwait wrappers. Even if these fail,
// the thread still holds the lock.
/* ------------ Debug/trace options ------------ */
// 0 for silent, 1 for some stuff, 2 for lots of stuff
#define SHOW_EVENTS 0
static void all__sanity_check ( const HChar* who ); /* fwds */
#define HG_CLI__DEFAULT_MALLOC_REDZONE_SZB 16 /* let's say */
// 0 for none, 1 for dump at end of run
#define SHOW_DATA_STRUCTURES 0
/* ------------ Misc comments ------------ */
// FIXME: don't hardwire initial entries for root thread.
// Instead, let the pre_thread_ll_create handler do this.
/*----------------------------------------------------------------*/
/*--- Primary data structures ---*/
/*----------------------------------------------------------------*/
/* Admin linked list of Threads */
static Thread* admin_threads = NULL;
Thread* get_admin_threads ( void ) { return admin_threads; }
/* Admin double linked list of Locks */
/* We need a double linked list to properly and efficiently
handle del_LockN. */
static Lock* admin_locks = NULL;
/* Mapping table for core ThreadIds to Thread* */
static Thread** map_threads = NULL; /* Array[VG_N_THREADS] of Thread* */
/* Mapping table for lock guest addresses to Lock* */
static WordFM* map_locks = NULL; /* WordFM LockAddr Lock* */
/* The word-set universes for lock sets. */
static WordSetU* univ_lsets = NULL; /* sets of Lock* */
static WordSetU* univ_laog = NULL; /* sets of Lock*, for LAOG */
static Int next_gc_univ_laog = 1;
/* univ_laog will be garbaged collected when the nr of element in univ_laog is
>= next_gc_univ_laog. */
/* Allow libhb to get at the universe of locksets stored
here. Sigh. */
WordSetU* HG_(get_univ_lsets) ( void ) { return univ_lsets; }
/* Allow libhb to get at the list of locks stored here. Ditto
sigh. */
Lock* HG_(get_admin_locks) ( void ) { return admin_locks; }
/*----------------------------------------------------------------*/
/*--- Simple helpers for the data structures ---*/
/*----------------------------------------------------------------*/
static UWord stats__lockN_acquires = 0;
static UWord stats__lockN_releases = 0;
static
ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr ); /*fwds*/
/* --------- Constructors --------- */
static Thread* mk_Thread ( Thr* hbthr ) {
static Int indx = 1;
Thread* thread = HG_(zalloc)( "hg.mk_Thread.1", sizeof(Thread) );
thread->locksetA = HG_(emptyWS)( univ_lsets );
thread->locksetW = HG_(emptyWS)( univ_lsets );
thread->magic = Thread_MAGIC;
thread->hbthr = hbthr;
thread->coretid = VG_INVALID_THREADID;
thread->created_at = NULL;
thread->announced = False;
thread->errmsg_index = indx++;
thread->admin = admin_threads;
admin_threads = thread;
return thread;
}
// Make a new lock which is unlocked (hence ownerless)
// and insert the new lock in admin_locks double linked list.
static Lock* mk_LockN ( LockKind kind, Addr guestaddr ) {
static ULong unique = 0;
Lock* lock = HG_(zalloc)( "hg.mk_Lock.1", sizeof(Lock) );
/* begin: add to double linked list */
if (admin_locks)
admin_locks->admin_prev = lock;
lock->admin_next = admin_locks;
lock->admin_prev = NULL;
admin_locks = lock;
/* end: add */
lock->unique = unique++;
lock->magic = LockN_MAGIC;
lock->appeared_at = NULL;
lock->acquired_at = NULL;
lock->hbso = libhb_so_alloc();
lock->guestaddr = guestaddr;
lock->kind = kind;
lock->heldW = False;
lock->heldBy = NULL;
tl_assert(HG_(is_sane_LockN)(lock));
return lock;
}
/* Release storage for a Lock. Also release storage in .heldBy, if
any. Removes from admin_locks double linked list. */
static void del_LockN ( Lock* lk )
{
tl_assert(HG_(is_sane_LockN)(lk));
tl_assert(lk->hbso);
libhb_so_dealloc(lk->hbso);
if (lk->heldBy)
VG_(deleteBag)( lk->heldBy );
/* begin: del lock from double linked list */
if (lk == admin_locks) {
tl_assert(lk->admin_prev == NULL);
if (lk->admin_next)
lk->admin_next->admin_prev = NULL;
admin_locks = lk->admin_next;
}
else {
tl_assert(lk->admin_prev != NULL);
lk->admin_prev->admin_next = lk->admin_next;
if (lk->admin_next)
lk->admin_next->admin_prev = lk->admin_prev;
}
/* end: del */
VG_(memset)(lk, 0xAA, sizeof(*lk));
HG_(free)(lk);
}
/* Update 'lk' to reflect that 'thr' now has a write-acquisition of
it. This is done strictly: only combinations resulting from
correct program and libpthread behaviour are allowed. */
static void lockN_acquire_writer ( Lock* lk, Thread* thr )
{
tl_assert(HG_(is_sane_LockN)(lk));
tl_assert(HG_(is_sane_Thread)(thr));
stats__lockN_acquires++;
/* EXPOSITION only */
/* We need to keep recording snapshots of where the lock was
acquired, so as to produce better lock-order error messages. */
if (lk->acquired_at == NULL) {
ThreadId tid;
tl_assert(lk->heldBy == NULL);
tid = map_threads_maybe_reverse_lookup_SLOW(thr);
lk->acquired_at
= VG_(record_ExeContext)(tid, 0/*first_ip_delta*/);
} else {
tl_assert(lk->heldBy != NULL);
}
/* end EXPOSITION only */
switch (lk->kind) {
case LK_nonRec:
case_LK_nonRec:
tl_assert(lk->heldBy == NULL); /* can't w-lock recursively */
tl_assert(!lk->heldW);
lk->heldW = True;
lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNaw.1", HG_(free) );
VG_(addToBag)( lk->heldBy, (UWord)thr );
break;
case LK_mbRec:
if (lk->heldBy == NULL)
goto case_LK_nonRec;
/* 2nd and subsequent locking of a lock by its owner */
tl_assert(lk->heldW);
/* assert: lk is only held by one thread .. */
tl_assert(VG_(sizeUniqueBag(lk->heldBy)) == 1);
/* assert: .. and that thread is 'thr'. */
tl_assert(VG_(elemBag)(lk->heldBy, (UWord)thr)
== VG_(sizeTotalBag)(lk->heldBy));
VG_(addToBag)(lk->heldBy, (UWord)thr);
break;
case LK_rdwr:
tl_assert(lk->heldBy == NULL && !lk->heldW); /* must be unheld */
goto case_LK_nonRec;
default:
tl_assert(0);
}
tl_assert(HG_(is_sane_LockN)(lk));
}
static void lockN_acquire_reader ( Lock* lk, Thread* thr )
{
tl_assert(HG_(is_sane_LockN)(lk));
tl_assert(HG_(is_sane_Thread)(thr));
/* can only add reader to a reader-writer lock. */
tl_assert(lk->kind == LK_rdwr);
/* lk must be free or already r-held. */
tl_assert(lk->heldBy == NULL
|| (lk->heldBy != NULL && !lk->heldW));
stats__lockN_acquires++;
/* EXPOSITION only */
/* We need to keep recording snapshots of where the lock was
acquired, so as to produce better lock-order error messages. */
if (lk->acquired_at == NULL) {
ThreadId tid;
tl_assert(lk->heldBy == NULL);
tid = map_threads_maybe_reverse_lookup_SLOW(thr);
lk->acquired_at
= VG_(record_ExeContext)(tid, 0/*first_ip_delta*/);
} else {
tl_assert(lk->heldBy != NULL);
}
/* end EXPOSITION only */
if (lk->heldBy) {
VG_(addToBag)(lk->heldBy, (UWord)thr);
} else {
lk->heldW = False;
lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNar.1", HG_(free) );
VG_(addToBag)( lk->heldBy, (UWord)thr );
}
tl_assert(!lk->heldW);
tl_assert(HG_(is_sane_LockN)(lk));
}
/* Update 'lk' to reflect a release of it by 'thr'. This is done
strictly: only combinations resulting from correct program and
libpthread behaviour are allowed. */
static void lockN_release ( Lock* lk, Thread* thr )
{
Bool b;
tl_assert(HG_(is_sane_LockN)(lk));
tl_assert(HG_(is_sane_Thread)(thr));
/* lock must be held by someone */
tl_assert(lk->heldBy);
stats__lockN_releases++;
/* Remove it from the holder set */
b = VG_(delFromBag)(lk->heldBy, (UWord)thr);
/* thr must actually have been a holder of lk */
tl_assert(b);
/* normalise */
tl_assert(lk->acquired_at);
if (VG_(isEmptyBag)(lk->heldBy)) {
VG_(deleteBag)(lk->heldBy);
lk->heldBy = NULL;
lk->heldW = False;
lk->acquired_at = NULL;
}
tl_assert(HG_(is_sane_LockN)(lk));
}
static void remove_Lock_from_locksets_of_all_owning_Threads( Lock* lk )
{
Thread* thr;
if (!lk->heldBy) {
tl_assert(!lk->heldW);
return;
}
/* for each thread that holds this lock do ... */
VG_(initIterBag)( lk->heldBy );
while (VG_(nextIterBag)( lk->heldBy, (UWord*)&thr, NULL )) {
tl_assert(HG_(is_sane_Thread)(thr));
tl_assert(HG_(elemWS)( univ_lsets,
thr->locksetA, (UWord)lk ));
thr->locksetA
= HG_(delFromWS)( univ_lsets, thr->locksetA, (UWord)lk );
if (lk->heldW) {
tl_assert(HG_(elemWS)( univ_lsets,
thr->locksetW, (UWord)lk ));
thr->locksetW
= HG_(delFromWS)( univ_lsets, thr->locksetW, (UWord)lk );
}
}
VG_(doneIterBag)( lk->heldBy );
}
/*----------------------------------------------------------------*/
/*--- Print out the primary data structures ---*/
/*----------------------------------------------------------------*/
#define PP_THREADS (1<<1)
#define PP_LOCKS (1<<2)
#define PP_ALL (PP_THREADS | PP_LOCKS)
static const Int sHOW_ADMIN = 0;
static void space ( Int n )
{
Int i;
HChar spaces[128+1];
tl_assert(n >= 0 && n < 128);
if (n == 0)
return;
for (i = 0; i < n; i++)
spaces[i] = ' ';
spaces[i] = 0;
tl_assert(i < 128+1);
VG_(printf)("%s", spaces);
}
static void pp_Thread ( Int d, Thread* t )
{
space(d+0); VG_(printf)("Thread %p {\n", t);
if (sHOW_ADMIN) {
space(d+3); VG_(printf)("admin %p\n", t->admin);
space(d+3); VG_(printf)("magic 0x%x\n", (UInt)t->magic);
}
space(d+3); VG_(printf)("locksetA %d\n", (Int)t->locksetA);
space(d+3); VG_(printf)("locksetW %d\n", (Int)t->locksetW);
space(d+0); VG_(printf)("}\n");
}
static void pp_admin_threads ( Int d )
{
Int i, n;
Thread* t;
for (n = 0, t = admin_threads; t; n++, t = t->admin) {
/* nothing */
}
space(d); VG_(printf)("admin_threads (%d records) {\n", n);
for (i = 0, t = admin_threads; t; i++, t = t->admin) {
if (0) {
space(n);
VG_(printf)("admin_threads record %d of %d:\n", i, n);
}
pp_Thread(d+3, t);
}
space(d); VG_(printf)("}\n");
}
static void pp_map_threads ( Int d )
{
Int i, n = 0;
space(d); VG_(printf)("map_threads ");
for (i = 0; i < VG_N_THREADS; i++) {
if (map_threads[i] != NULL)
n++;
}
VG_(printf)("(%d entries) {\n", n);
for (i = 0; i < VG_N_THREADS; i++) {
if (map_threads[i] == NULL)
continue;
space(d+3);
VG_(printf)("coretid %d -> Thread %p\n", i, map_threads[i]);
}
space(d); VG_(printf)("}\n");
}
static const HChar* show_LockKind ( LockKind lkk ) {
switch (lkk) {
case LK_mbRec: return "mbRec";
case LK_nonRec: return "nonRec";
case LK_rdwr: return "rdwr";
default: tl_assert(0);
}
}
/* Pretty Print lock lk.
if show_lock_addrdescr, describes the (guest) lock address.
(this description will be more complete with --read-var-info=yes).
if show_internal_data, shows also helgrind internal information.
d is the level at which output is indented. */
static void pp_Lock ( Int d, Lock* lk,
Bool show_lock_addrdescr,
Bool show_internal_data)
{
space(d+0);
if (show_internal_data)
VG_(printf)("Lock %p (ga %#lx) {\n", lk, lk->guestaddr);
else
VG_(printf)("Lock ga %#lx {\n", lk->guestaddr);
if (!show_lock_addrdescr
|| !HG_(get_and_pp_addrdescr) ((Addr) lk->guestaddr))
VG_(printf)("\n");
if (sHOW_ADMIN) {
space(d+3); VG_(printf)("admin_n %p\n", lk->admin_next);
space(d+3); VG_(printf)("admin_p %p\n", lk->admin_prev);
space(d+3); VG_(printf)("magic 0x%x\n", (UInt)lk->magic);
}
if (show_internal_data) {
space(d+3); VG_(printf)("unique %llu\n", lk->unique);
}
space(d+3); VG_(printf)("kind %s\n", show_LockKind(lk->kind));
if (show_internal_data) {
space(d+3); VG_(printf)("heldW %s\n", lk->heldW ? "yes" : "no");
}
if (show_internal_data) {
space(d+3); VG_(printf)("heldBy %p", lk->heldBy);
}
if (lk->heldBy) {
Thread* thr;
UWord count;
VG_(printf)(" { ");
VG_(initIterBag)( lk->heldBy );
while (VG_(nextIterBag)( lk->heldBy, (UWord*)&thr, &count )) {
if (show_internal_data)
VG_(printf)("%lu:%p ", count, thr);
else {
VG_(printf)("%c%lu:thread #%d ",
lk->heldW ? 'W' : 'R',
count, thr->errmsg_index);
if (thr->coretid == VG_INVALID_THREADID)
VG_(printf)("tid (exited) ");
else
VG_(printf)("tid %d ", thr->coretid);
}
}
VG_(doneIterBag)( lk->heldBy );
VG_(printf)("}\n");
}
space(d+0); VG_(printf)("}\n");
}
static void pp_admin_locks ( Int d )
{
Int i, n;
Lock* lk;
for (n = 0, lk = admin_locks; lk; n++, lk = lk->admin_next) {
/* nothing */
}
space(d); VG_(printf)("admin_locks (%d records) {\n", n);
for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next) {
if (0) {
space(n);
VG_(printf)("admin_locks record %d of %d:\n", i, n);
}
pp_Lock(d+3, lk,
False /* show_lock_addrdescr */,
True /* show_internal_data */);
}
space(d); VG_(printf)("}\n");
}
static void pp_map_locks ( Int d)
{
void* gla;
Lock* lk;
space(d); VG_(printf)("map_locks (%d entries) {\n",
(Int)VG_(sizeFM)( map_locks ));
VG_(initIterFM)( map_locks );
while (VG_(nextIterFM)( map_locks, (UWord*)&gla,
(UWord*)&lk )) {
space(d+3);
VG_(printf)("guest %p -> Lock %p\n", gla, lk);
}
VG_(doneIterFM)( map_locks );
space(d); VG_(printf)("}\n");
}
static void pp_everything ( Int flags, const HChar* caller )
{
Int d = 0;
VG_(printf)("\n");
VG_(printf)("All_Data_Structures (caller = \"%s\") {\n", caller);
if (flags & PP_THREADS) {
VG_(printf)("\n");
pp_admin_threads(d+3);
VG_(printf)("\n");
pp_map_threads(d+3);
}
if (flags & PP_LOCKS) {
VG_(printf)("\n");
pp_admin_locks(d+3);
VG_(printf)("\n");
pp_map_locks(d+3);
}
VG_(printf)("\n");
VG_(printf)("}\n");
VG_(printf)("\n");
}
#undef SHOW_ADMIN
/*----------------------------------------------------------------*/
/*--- Initialise the primary data structures ---*/
/*----------------------------------------------------------------*/
static void initialise_data_structures ( Thr* hbthr_root )
{
Thread* thr;
WordSetID wsid;
/* Get everything initialised and zeroed. */
tl_assert(admin_threads == NULL);
tl_assert(admin_locks == NULL);
tl_assert(map_threads == NULL);
map_threads = HG_(zalloc)( "hg.ids.1", VG_N_THREADS * sizeof(Thread*) );
tl_assert(map_threads != NULL);
tl_assert(sizeof(Addr) == sizeof(UWord));
tl_assert(map_locks == NULL);
map_locks = VG_(newFM)( HG_(zalloc), "hg.ids.2", HG_(free),
NULL/*unboxed Word cmp*/);
tl_assert(map_locks != NULL);
tl_assert(univ_lsets == NULL);
univ_lsets = HG_(newWordSetU)( HG_(zalloc), "hg.ids.4", HG_(free),
8/*cacheSize*/ );
tl_assert(univ_lsets != NULL);
/* Ensure that univ_lsets is non-empty, with lockset zero being the
empty lockset. hg_errors.c relies on the assumption that
lockset number zero in univ_lsets is always valid. */
wsid = HG_(emptyWS)(univ_lsets);
tl_assert(wsid == 0);
tl_assert(univ_laog == NULL);
if (HG_(clo_track_lockorders)) {
univ_laog = HG_(newWordSetU)( HG_(zalloc), "hg.ids.5 (univ_laog)",
HG_(free), 24/*cacheSize*/ );
tl_assert(univ_laog != NULL);
}
/* Set up entries for the root thread */
// FIXME: this assumes that the first real ThreadId is 1
/* a Thread for the new thread ... */
thr = mk_Thread(hbthr_root);
thr->coretid = 1; /* FIXME: hardwires an assumption about the
identity of the root thread. */
tl_assert( libhb_get_Thr_hgthread(hbthr_root) == NULL );
libhb_set_Thr_hgthread(hbthr_root, thr);
/* and bind it in the thread-map table. */
tl_assert(HG_(is_sane_ThreadId)(thr->coretid));
tl_assert(thr->coretid != VG_INVALID_THREADID);
map_threads[thr->coretid] = thr;
tl_assert(VG_INVALID_THREADID == 0);
all__sanity_check("initialise_data_structures");
}
/*----------------------------------------------------------------*/
/*--- map_threads :: array[core-ThreadId] of Thread* ---*/
/*----------------------------------------------------------------*/
/* Doesn't assert if the relevant map_threads entry is NULL. */
static Thread* map_threads_maybe_lookup ( ThreadId coretid )
{
Thread* thr;
tl_assert( HG_(is_sane_ThreadId)(coretid) );
thr = map_threads[coretid];
return thr;
}
/* Asserts if the relevant map_threads entry is NULL. */
static inline Thread* map_threads_lookup ( ThreadId coretid )
{
Thread* thr;
tl_assert( HG_(is_sane_ThreadId)(coretid) );
thr = map_threads[coretid];
tl_assert(thr);
return thr;
}
/* Do a reverse lookup. Does not assert if 'thr' is not found in
map_threads. */
static ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr )
{
ThreadId tid;
tl_assert(HG_(is_sane_Thread)(thr));
/* Check nobody used the invalid-threadid slot */
tl_assert(VG_INVALID_THREADID >= 0 && VG_INVALID_THREADID < VG_N_THREADS);
tl_assert(map_threads[VG_INVALID_THREADID] == NULL);
tid = thr->coretid;
tl_assert(HG_(is_sane_ThreadId)(tid));
return tid;
}
/* Do a reverse lookup. Warning: POTENTIALLY SLOW. Asserts if 'thr'
is not found in map_threads. */
static ThreadId map_threads_reverse_lookup_SLOW ( Thread* thr )
{
ThreadId tid = map_threads_maybe_reverse_lookup_SLOW( thr );
tl_assert(tid != VG_INVALID_THREADID);
tl_assert(map_threads[tid]);
tl_assert(map_threads[tid]->coretid == tid);
return tid;
}
static void map_threads_delete ( ThreadId coretid )
{
Thread* thr;
tl_assert(coretid != 0);
tl_assert( HG_(is_sane_ThreadId)(coretid) );
thr = map_threads[coretid];
tl_assert(thr);
map_threads[coretid] = NULL;
}
/*----------------------------------------------------------------*/
/*--- map_locks :: WordFM guest-Addr-of-lock Lock* ---*/
/*----------------------------------------------------------------*/
/* Make sure there is a lock table entry for the given (lock) guest
address. If not, create one of the stated 'kind' in unheld state.
In any case, return the address of the existing or new Lock. */
static
Lock* map_locks_lookup_or_create ( LockKind lkk, Addr ga, ThreadId tid )
{
Bool found;
Lock* oldlock = NULL;
tl_assert(HG_(is_sane_ThreadId)(tid));
found = VG_(lookupFM)( map_locks,
NULL, (UWord*)&oldlock, (UWord)ga );
if (!found) {
Lock* lock = mk_LockN(lkk, ga);
lock->appeared_at = VG_(record_ExeContext)( tid, 0 );
tl_assert(HG_(is_sane_LockN)(lock));
VG_(addToFM)( map_locks, (UWord)ga, (UWord)lock );
tl_assert(oldlock == NULL);
return lock;
} else {
tl_assert(oldlock != NULL);
tl_assert(HG_(is_sane_LockN)(oldlock));
tl_assert(oldlock->guestaddr == ga);
return oldlock;
}
}
static Lock* map_locks_maybe_lookup ( Addr ga )
{
Bool found;
Lock* lk = NULL;
found = VG_(lookupFM)( map_locks, NULL, (UWord*)&lk, (UWord)ga );
tl_assert(found ? lk != NULL : lk == NULL);
return lk;
}
static void map_locks_delete ( Addr ga )
{
Addr ga2 = 0;
Lock* lk = NULL;
VG_(delFromFM)( map_locks,
(UWord*)&ga2, (UWord*)&lk, (UWord)ga );
/* delFromFM produces the val which is being deleted, if it is
found. So assert it is non-null; that in effect asserts that we
are deleting a (ga, Lock) pair which actually exists. */
tl_assert(lk != NULL);
tl_assert(ga2 == ga);
}
/*----------------------------------------------------------------*/
/*--- Sanity checking the data structures ---*/
/*----------------------------------------------------------------*/
static UWord stats__sanity_checks = 0;
static void laog__sanity_check ( const HChar* who ); /* fwds */
/* REQUIRED INVARIANTS:
Thread vs Segment/Lock/SecMaps
for each t in Threads {
// Thread.lockset: each element is really a valid Lock
// Thread.lockset: each Lock in set is actually held by that thread
for lk in Thread.lockset
lk == LockedBy(t)
// Thread.csegid is a valid SegmentID
// and the associated Segment has .thr == t
}
all thread Locksets are pairwise empty under intersection
(that is, no lock is claimed to be held by more than one thread)
-- this is guaranteed if all locks in locksets point back to their
owner threads
Lock vs Thread/Segment/SecMaps
for each entry (gla, la) in map_locks
gla == la->guest_addr
for each lk in Locks {
lk->tag is valid
lk->guest_addr does not have shadow state NoAccess
if lk == LockedBy(t), then t->lockset contains lk
if lk == UnlockedBy(segid) then segid is valid SegmentID
and can be mapped to a valid Segment(seg)
and seg->thr->lockset does not contain lk
if lk == UnlockedNew then (no lockset contains lk)
secmaps for lk has .mbHasLocks == True
}
Segment vs Thread/Lock/SecMaps
the Segment graph is a dag (no cycles)
all of the Segment graph must be reachable from the segids
mentioned in the Threads
for seg in Segments {
seg->thr is a sane Thread
}
SecMaps vs Segment/Thread/Lock
for sm in SecMaps {
sm properly aligned
if any shadow word is ShR or ShM then .mbHasShared == True
for each Excl(segid) state
map_segments_lookup maps to a sane Segment(seg)
for each ShM/ShR(tsetid,lsetid) state
each lk in lset is a valid Lock
each thr in tset is a valid thread, which is non-dead
}
*/
/* Return True iff 'thr' holds 'lk' in some mode. */
static Bool thread_is_a_holder_of_Lock ( Thread* thr, Lock* lk )
{
if (lk->heldBy)
return VG_(elemBag)( lk->heldBy, (UWord)thr ) > 0;
else
return False;
}
/* Sanity check Threads, as far as possible */
__attribute__((noinline))
static void threads__sanity_check ( const HChar* who )
{
#define BAD(_str) do { how = (_str); goto bad; } while (0)
const HChar* how = "no error";
Thread* thr;
WordSetID wsA, wsW;
UWord* ls_words;
UWord ls_size, i;
Lock* lk;
for (thr = admin_threads; thr; thr = thr->admin) {
if (!HG_(is_sane_Thread)(thr)) BAD("1");
wsA = thr->locksetA;
wsW = thr->locksetW;
// locks held in W mode are a subset of all locks held
if (!HG_(isSubsetOf)( univ_lsets, wsW, wsA )) BAD("7");
HG_(getPayloadWS)( &ls_words, &ls_size, univ_lsets, wsA );
for (i = 0; i < ls_size; i++) {
lk = (Lock*)ls_words[i];
// Thread.lockset: each element is really a valid Lock
if (!HG_(is_sane_LockN)(lk)) BAD("2");
// Thread.lockset: each Lock in set is actually held by that
// thread
if (!thread_is_a_holder_of_Lock(thr,lk)) BAD("3");
}
}
return;
bad:
VG_(printf)("threads__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how);
tl_assert(0);
#undef BAD
}
/* Sanity check Locks, as far as possible */
__attribute__((noinline))
static void locks__sanity_check ( const HChar* who )
{
#define BAD(_str) do { how = (_str); goto bad; } while (0)
const HChar* how = "no error";
Addr gla;
Lock* lk;
Int i;
// # entries in admin_locks == # entries in map_locks
for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next)
;
if (i != VG_(sizeFM)(map_locks)) BAD("1");
// for each entry (gla, lk) in map_locks
// gla == lk->guest_addr
VG_(initIterFM)( map_locks );
while (VG_(nextIterFM)( map_locks,
(UWord*)&gla, (UWord*)&lk )) {
if (lk->guestaddr != gla) BAD("2");
}
VG_(doneIterFM)( map_locks );
// scan through admin_locks ...
for (lk = admin_locks; lk; lk = lk->admin_next) {
// lock is sane. Quite comprehensive, also checks that
// referenced (holder) threads are sane.
if (!HG_(is_sane_LockN)(lk)) BAD("3");
// map_locks binds guest address back to this lock
if (lk != map_locks_maybe_lookup(lk->guestaddr)) BAD("4");
// look at all threads mentioned as holders of this lock. Ensure
// this lock is mentioned in their locksets.
if (lk->heldBy) {
Thread* thr;
UWord count;
VG_(initIterBag)( lk->heldBy );
while (VG_(nextIterBag)( lk->heldBy,
(UWord*)&thr, &count )) {
// HG_(is_sane_LockN) above ensures these
tl_assert(count >= 1);
tl_assert(HG_(is_sane_Thread)(thr));
if (!HG_(elemWS)(univ_lsets, thr->locksetA, (UWord)lk))
BAD("6");
// also check the w-only lockset
if (lk->heldW
&& !HG_(elemWS)(univ_lsets, thr->locksetW, (UWord)lk))
BAD("7");
if ((!lk->heldW)
&& HG_(elemWS)(univ_lsets, thr->locksetW, (UWord)lk))
BAD("8");
}
VG_(doneIterBag)( lk->heldBy );
} else {
/* lock not held by anybody */
if (lk->heldW) BAD("9"); /* should be False if !heldBy */
// since lk is unheld, then (no lockset contains lk)
// hmm, this is really too expensive to check. Hmm.
}
}
return;
bad:
VG_(printf)("locks__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how);
tl_assert(0);
#undef BAD
}
static void all_except_Locks__sanity_check ( const HChar* who ) {
stats__sanity_checks++;
if (0) VG_(printf)("all_except_Locks__sanity_check(%s)\n", who);
threads__sanity_check(who);
if (HG_(clo_track_lockorders))
laog__sanity_check(who);
}
static void all__sanity_check ( const HChar* who ) {
all_except_Locks__sanity_check(who);
locks__sanity_check(who);
}
/*----------------------------------------------------------------*/
/*--- Shadow value and address range handlers ---*/
/*----------------------------------------------------------------*/
static void laog__pre_thread_acquires_lock ( Thread*, Lock* ); /* fwds */
//static void laog__handle_lock_deletions ( WordSetID ); /* fwds */
static inline Thread* get_current_Thread ( void ); /* fwds */
__attribute__((noinline))
static void laog__handle_one_lock_deletion ( Lock* lk ); /* fwds */
/* Block-copy states (needed for implementing realloc()). */
/* FIXME this copies shadow memory; it doesn't apply the MSM to it.
Is that a problem? (hence 'scopy' rather than 'ccopy') */
static void shadow_mem_scopy_range ( Thread* thr,
Addr src, Addr dst, SizeT len )
{
Thr* hbthr = thr->hbthr;
tl_assert(hbthr);
libhb_copy_shadow_state( hbthr, src, dst, len );
}
static void shadow_mem_cread_range ( Thread* thr, Addr a, SizeT len )
{
Thr* hbthr = thr->hbthr;
tl_assert(hbthr);
LIBHB_CREAD_N(hbthr, a, len);
}
static void shadow_mem_cwrite_range ( Thread* thr, Addr a, SizeT len ) {
Thr* hbthr = thr->hbthr;
tl_assert(hbthr);
LIBHB_CWRITE_N(hbthr, a, len);
}
static void shadow_mem_make_New ( Thread* thr, Addr a, SizeT len )
{
libhb_srange_new( thr->hbthr, a, len );
}
static void shadow_mem_make_NoAccess_NoFX ( Thread* thr, Addr aIN, SizeT len )
{
if (0 && len > 500)
VG_(printf)("make NoAccess_NoFX ( %#lx, %ld )\n", aIN, len );
// has no effect (NoFX)
libhb_srange_noaccess_NoFX( thr->hbthr, aIN, len );
}
static void shadow_mem_make_NoAccess_AHAE ( Thread* thr, Addr aIN, SizeT len )
{
if (0 && len > 500)
VG_(printf)("make NoAccess_AHAE ( %#lx, %ld )\n", aIN, len );
// Actually Has An Effect (AHAE)
libhb_srange_noaccess_AHAE( thr->hbthr, aIN, len );
}
static void shadow_mem_make_Untracked ( Thread* thr, Addr aIN, SizeT len )
{
if (0 && len > 500)
VG_(printf)("make Untracked ( %#lx, %ld )\n", aIN, len );
libhb_srange_untrack( thr->hbthr, aIN, len );
}
/*----------------------------------------------------------------*/
/*--- Event handlers (evh__* functions) ---*/
/*--- plus helpers (evhH__* functions) ---*/
/*----------------------------------------------------------------*/
/*--------- Event handler helpers (evhH__* functions) ---------*/
/* Create a new segment for 'thr', making it depend (.prev) on its
existing segment, bind together the SegmentID and Segment, and
return both of them. Also update 'thr' so it references the new
Segment. */
//zz static
//zz void evhH__start_new_segment_for_thread ( /*OUT*/SegmentID* new_segidP,
//zz /*OUT*/Segment** new_segP,
//zz Thread* thr )
//zz {
//zz Segment* cur_seg;
//zz tl_assert(new_segP);
//zz tl_assert(new_segidP);
//zz tl_assert(HG_(is_sane_Thread)(thr));
//zz cur_seg = map_segments_lookup( thr->csegid );
//zz tl_assert(cur_seg);
//zz tl_assert(cur_seg->thr == thr); /* all sane segs should point back
//zz at their owner thread. */
//zz *new_segP = mk_Segment( thr, cur_seg, NULL/*other*/ );
//zz *new_segidP = alloc_SegmentID();
//zz map_segments_add( *new_segidP, *new_segP );
//zz thr->csegid = *new_segidP;
//zz }
/* The lock at 'lock_ga' has acquired a writer. Make all necessary
updates, and also do all possible error checks. */
static
void evhH__post_thread_w_acquires_lock ( Thread* thr,
LockKind lkk, Addr lock_ga )
{
Lock* lk;
/* Basically what we need to do is call lockN_acquire_writer.
However, that will barf if any 'invalid' lock states would
result. Therefore check before calling. Side effect is that
'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this
routine.
Because this routine is only called after successful lock
acquisition, we should not be asked to move the lock into any
invalid states. Requests to do so are bugs in libpthread, since
that should have rejected any such requests. */
tl_assert(HG_(is_sane_Thread)(thr));
/* Try to find the lock. If we can't, then create a new one with
kind 'lkk'. */
lk = map_locks_lookup_or_create(
lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) );
tl_assert( HG_(is_sane_LockN)(lk) );
/* check libhb level entities exist */
tl_assert(thr->hbthr);
tl_assert(lk->hbso);
if (lk->heldBy == NULL) {
/* the lock isn't held. Simple. */
tl_assert(!lk->heldW);
lockN_acquire_writer( lk, thr );
/* acquire a dependency from the lock's VCs */
libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ );
goto noerror;
}
/* So the lock is already held. If held as a r-lock then
libpthread must be buggy. */
tl_assert(lk->heldBy);
if (!lk->heldW) {
HG_(record_error_Misc)(
thr, "Bug in libpthread: write lock "
"granted on rwlock which is currently rd-held");
goto error;
}
/* So the lock is held in w-mode. If it's held by some other
thread, then libpthread must be buggy. */
tl_assert(VG_(sizeUniqueBag)(lk->heldBy) == 1); /* from precondition */
if (thr != (Thread*)VG_(anyElementOfBag)(lk->heldBy)) {
HG_(record_error_Misc)(
thr, "Bug in libpthread: write lock "
"granted on mutex/rwlock which is currently "
"wr-held by a different thread");
goto error;
}
/* So the lock is already held in w-mode by 'thr'. That means this
is an attempt to lock it recursively, which is only allowable
for LK_mbRec kinded locks. Since this routine is called only
once the lock has been acquired, this must also be a libpthread
bug. */
if (lk->kind != LK_mbRec) {
HG_(record_error_Misc)(
thr, "Bug in libpthread: recursive write lock "
"granted on mutex/wrlock which does not "
"support recursion");
goto error;
}
/* So we are recursively re-locking a lock we already w-hold. */
lockN_acquire_writer( lk, thr );
/* acquire a dependency from the lock's VC. Probably pointless,
but also harmless. */
libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ );
goto noerror;
noerror:
if (HG_(clo_track_lockorders)) {
/* check lock order acquisition graph, and update. This has to
happen before the lock is added to the thread's locksetA/W. */
laog__pre_thread_acquires_lock( thr, lk );
}
/* update the thread's held-locks set */
thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (UWord)lk );
thr->locksetW = HG_(addToWS)( univ_lsets, thr->locksetW, (UWord)lk );
/* fall through */
error:
tl_assert(HG_(is_sane_LockN)(lk));
}
/* The lock at 'lock_ga' has acquired a reader. Make all necessary
updates, and also do all possible error checks. */
static
void evhH__post_thread_r_acquires_lock ( Thread* thr,
LockKind lkk, Addr lock_ga )
{
Lock* lk;
/* Basically what we need to do is call lockN_acquire_reader.
However, that will barf if any 'invalid' lock states would
result. Therefore check before calling. Side effect is that
'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this
routine.
Because this routine is only called after successful lock
acquisition, we should not be asked to move the lock into any
invalid states. Requests to do so are bugs in libpthread, since
that should have rejected any such requests. */
tl_assert(HG_(is_sane_Thread)(thr));
/* Try to find the lock. If we can't, then create a new one with
kind 'lkk'. Only a reader-writer lock can be read-locked,
hence the first assertion. */
tl_assert(lkk == LK_rdwr);
lk = map_locks_lookup_or_create(
lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) );
tl_assert( HG_(is_sane_LockN)(lk) );
/* check libhb level entities exist */
tl_assert(thr->hbthr);
tl_assert(lk->hbso);
if (lk->heldBy == NULL) {
/* the lock isn't held. Simple. */
tl_assert(!lk->heldW);
lockN_acquire_reader( lk, thr );
/* acquire a dependency from the lock's VC */
libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ );
goto noerror;
}
/* So the lock is already held. If held as a w-lock then
libpthread must be buggy. */
tl_assert(lk->heldBy);
if (lk->heldW) {
HG_(record_error_Misc)( thr, "Bug in libpthread: read lock "
"granted on rwlock which is "
"currently wr-held");
goto error;
}
/* Easy enough. In short anybody can get a read-lock on a rwlock
provided it is either unlocked or already in rd-held. */
lockN_acquire_reader( lk, thr );
/* acquire a dependency from the lock's VC. Probably pointless,
but also harmless. */
libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ );
goto noerror;
noerror:
if (HG_(clo_track_lockorders)) {
/* check lock order acquisition graph, and update. This has to
happen before the lock is added to the thread's locksetA/W. */
laog__pre_thread_acquires_lock( thr, lk );
}
/* update the thread's held-locks set */
thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (UWord)lk );
/* but don't update thr->locksetW, since lk is only rd-held */
/* fall through */
error:
tl_assert(HG_(is_sane_LockN)(lk));
}
/* The lock at 'lock_ga' is just about to be unlocked. Make all
necessary updates, and also do all possible error checks. */
static
void evhH__pre_thread_releases_lock ( Thread* thr,
Addr lock_ga, Bool isRDWR )
{
Lock* lock;
Word n;
Bool was_heldW;
/* This routine is called prior to a lock release, before
libpthread has had a chance to validate the call. Hence we need
to detect and reject any attempts to move the lock into an
invalid state. Such attempts are bugs in the client.
isRDWR is True if we know from the wrapper context that lock_ga
should refer to a reader-writer lock, and is False if [ditto]
lock_ga should refer to a standard mutex. */
tl_assert(HG_(is_sane_Thread)(thr));
lock = map_locks_maybe_lookup( lock_ga );
if (!lock) {
/* We know nothing about a lock at 'lock_ga'. Nevertheless
the client is trying to unlock it. So complain, then ignore
the attempt. */
HG_(record_error_UnlockBogus)( thr, lock_ga );
return;
}
tl_assert(lock->guestaddr == lock_ga);
tl_assert(HG_(is_sane_LockN)(lock));
if (isRDWR && lock->kind != LK_rdwr) {
HG_(record_error_Misc)( thr, "pthread_rwlock_unlock with a "
"pthread_mutex_t* argument " );
}
if ((!isRDWR) && lock->kind == LK_rdwr) {
HG_(record_error_Misc)( thr, "pthread_mutex_unlock with a "
"pthread_rwlock_t* argument " );
}
if (!lock->heldBy) {
/* The lock is not held. This indicates a serious bug in the
client. */
tl_assert(!lock->heldW);
HG_(record_error_UnlockUnlocked)( thr, lock );
tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (UWord)lock ));
tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (UWord)lock ));
goto error;
}
/* test just above dominates */
tl_assert(lock->heldBy);
was_heldW = lock->heldW;
/* The lock is held. Is this thread one of the holders? If not,
report a bug in the client. */
n = VG_(elemBag)( lock->heldBy, (UWord)thr );
tl_assert(n >= 0);
if (n == 0) {
/* We are not a current holder of the lock. This is a bug in
the guest, and (per POSIX pthread rules) the unlock
attempt will fail. So just complain and do nothing
else. */
Thread* realOwner = (Thread*)VG_(anyElementOfBag)( lock->heldBy );
tl_assert(HG_(is_sane_Thread)(realOwner));
tl_assert(realOwner != thr);
tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (UWord)lock ));
tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (UWord)lock ));
HG_(record_error_UnlockForeign)( thr, realOwner, lock );
goto error;
}
/* Ok, we hold the lock 'n' times. */
tl_assert(n >= 1);
lockN_release( lock, thr );
n--;
tl_assert(n >= 0);
if (n > 0) {
tl_assert(lock->heldBy);
tl_assert(n == VG_(elemBag)( lock->heldBy, (UWord)thr ));
/* We still hold the lock. So either it's a recursive lock
or a rwlock which is currently r-held. */
tl_assert(lock->kind == LK_mbRec
|| (lock->kind == LK_rdwr && !lock->heldW));
tl_assert(HG_(elemWS)( univ_lsets, thr->locksetA, (UWord)lock ));
if (lock->heldW)
tl_assert(HG_(elemWS)( univ_lsets, thr->locksetW, (UWord)lock ));
else
tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (UWord)lock ));
} else {
/* n is zero. This means we don't hold the lock any more. But
if it's a rwlock held in r-mode, someone else could still
hold it. Just do whatever sanity checks we can. */
if (lock->kind == LK_rdwr && lock->heldBy) {
/* It's a rwlock. We no longer hold it but we used to;
nevertheless it still appears to be held by someone else.
The implication is that, prior to this release, it must
have been shared by us and and whoever else is holding it;
which in turn implies it must be r-held, since a lock
can't be w-held by more than one thread. */
/* The lock is now R-held by somebody else: */
tl_assert(lock->heldW == False);
} else {
/* Normal case. It's either not a rwlock, or it's a rwlock
that we used to hold in w-mode (which is pretty much the
same thing as a non-rwlock.) Since this transaction is
atomic (V does not allow multiple threads to run
simultaneously), it must mean the lock is now not held by
anybody. Hence assert for it. */
/* The lock is now not held by anybody: */
tl_assert(!lock->heldBy);
tl_assert(lock->heldW == False);
}
//if (lock->heldBy) {
// tl_assert(0 == VG_(elemBag)( lock->heldBy, (UWord)thr ));
//}
/* update this thread's lockset accordingly. */
thr->locksetA
= HG_(delFromWS)( univ_lsets, thr->locksetA, (UWord)lock );
thr->locksetW
= HG_(delFromWS)( univ_lsets, thr->locksetW, (UWord)lock );
/* push our VC into the lock */
tl_assert(thr->hbthr);
tl_assert(lock->hbso);
/* If the lock was previously W-held, then we want to do a
strong send, and if previously R-held, then a weak send. */
libhb_so_send( thr->hbthr, lock->hbso, was_heldW );
}
/* fall through */
error:
tl_assert(HG_(is_sane_LockN)(lock));
}
/* ---------------------------------------------------------- */
/* -------- Event handlers proper (evh__* functions) -------- */
/* ---------------------------------------------------------- */
/* What is the Thread* for the currently running thread? This is
absolutely performance critical. We receive notifications from the
core for client code starts/stops, and cache the looked-up result
in 'current_Thread'. Hence, for the vast majority of requests,
finding the current thread reduces to a read of a global variable,
provided get_current_Thread_in_C_C is inlined.
Outside of client code, current_Thread is NULL, and presumably
any uses of it will cause a segfault. Hence:
- for uses definitely within client code, use
get_current_Thread_in_C_C.
- for all other uses, use get_current_Thread.
*/
static Thread *current_Thread = NULL,
*current_Thread_prev = NULL;
static void evh__start_client_code ( ThreadId tid, ULong nDisp ) {
if (0) VG_(printf)("start %d %llu\n", (Int)tid, nDisp);
tl_assert(current_Thread == NULL);
current_Thread = map_threads_lookup( tid );
tl_assert(current_Thread != NULL);
if (current_Thread != current_Thread_prev) {
libhb_Thr_resumes( current_Thread->hbthr );
current_Thread_prev = current_Thread;
}
}
static void evh__stop_client_code ( ThreadId tid, ULong nDisp ) {
if (0) VG_(printf)(" stop %d %llu\n", (Int)tid, nDisp);
tl_assert(current_Thread != NULL);
current_Thread = NULL;
libhb_maybe_GC();
}
static inline Thread* get_current_Thread_in_C_C ( void ) {
return current_Thread;
}
static inline Thread* get_current_Thread ( void ) {
ThreadId coretid;
Thread* thr;
thr = get_current_Thread_in_C_C();
if (LIKELY(thr))
return thr;
/* evidently not in client code. Do it the slow way. */
coretid = VG_(get_running_tid)();
/* FIXME: get rid of the following kludge. It exists because
evh__new_mem is called during initialisation (as notification
of initial memory layout) and VG_(get_running_tid)() returns
VG_INVALID_THREADID at that point. */
if (coretid == VG_INVALID_THREADID)
coretid = 1; /* KLUDGE */
thr = map_threads_lookup( coretid );
return thr;
}
static
void evh__new_mem ( Addr a, SizeT len ) {
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__new_mem(%p, %lu)\n", (void*)a, len );
shadow_mem_make_New( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__new_mem-post");
}
static
void evh__new_mem_stack ( Addr a, SizeT len ) {
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__new_mem_stack(%p, %lu)\n", (void*)a, len );
shadow_mem_make_New( get_current_Thread(),
-VG_STACK_REDZONE_SZB + a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__new_mem_stack-post");
}
static
void evh__new_mem_w_tid ( Addr a, SizeT len, ThreadId tid ) {
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__new_mem_w_tid(%p, %lu)\n", (void*)a, len );
shadow_mem_make_New( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__new_mem_w_tid-post");
}
static
void evh__new_mem_w_perms ( Addr a, SizeT len,
Bool rr, Bool ww, Bool xx, ULong di_handle ) {
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__new_mem_w_perms(%p, %lu, %d,%d,%d)\n",
(void*)a, len, (Int)rr, (Int)ww, (Int)xx );
if (rr || ww || xx)
shadow_mem_make_New( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__new_mem_w_perms-post");
}
static
void evh__set_perms ( Addr a, SizeT len,
Bool rr, Bool ww, Bool xx ) {
// This handles mprotect requests. If the memory is being put
// into no-R no-W state, paint it as NoAccess, for the reasons
// documented at evh__die_mem_munmap().
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__set_perms(%p, %lu, r=%d w=%d x=%d)\n",
(void*)a, len, (Int)rr, (Int)ww, (Int)xx );
/* Hmm. What should we do here, that actually makes any sense?
Let's say: if neither readable nor writable, then declare it
NoAccess, else leave it alone. */
if (!(rr || ww))
shadow_mem_make_NoAccess_AHAE( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__set_perms-post");
}
static
void evh__die_mem ( Addr a, SizeT len ) {
// Urr, libhb ignores this.
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__die_mem(%p, %lu)\n", (void*)a, len );
shadow_mem_make_NoAccess_NoFX( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__die_mem-post");
}
static
void evh__die_mem_munmap ( Addr a, SizeT len ) {
// It's important that libhb doesn't ignore this. If, as is likely,
// the client is subject to address space layout randomization,
// then unmapped areas may never get remapped over, even in long
// runs. If we just ignore them we wind up with large resource
// (VTS) leaks in libhb. So force them to NoAccess, so that all
// VTS references in the affected area are dropped. Marking memory
// as NoAccess is expensive, but we assume that munmap is sufficiently
// rare that the space gains of doing this are worth the costs.
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__die_mem_munmap(%p, %lu)\n", (void*)a, len );
shadow_mem_make_NoAccess_AHAE( get_current_Thread(), a, len );
}
static
void evh__untrack_mem ( Addr a, SizeT len ) {
// Libhb doesn't ignore this.
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__untrack_mem(%p, %lu)\n", (void*)a, len );
shadow_mem_make_Untracked( get_current_Thread(), a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__untrack_mem-post");
}
static
void evh__copy_mem ( Addr src, Addr dst, SizeT len ) {
if (SHOW_EVENTS >= 2)
VG_(printf)("evh__copy_mem(%p, %p, %lu)\n", (void*)src, (void*)dst, len );
shadow_mem_scopy_range( get_current_Thread(), src, dst, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__copy_mem-post");
}
static
void evh__pre_thread_ll_create ( ThreadId parent, ThreadId child )
{
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__pre_thread_ll_create(p=%d, c=%d)\n",
(Int)parent, (Int)child );
if (parent != VG_INVALID_THREADID) {
Thread* thr_p;
Thread* thr_c;
Thr* hbthr_p;
Thr* hbthr_c;
tl_assert(HG_(is_sane_ThreadId)(parent));
tl_assert(HG_(is_sane_ThreadId)(child));
tl_assert(parent != child);
thr_p = map_threads_maybe_lookup( parent );
thr_c = map_threads_maybe_lookup( child );
tl_assert(thr_p != NULL);
tl_assert(thr_c == NULL);
hbthr_p = thr_p->hbthr;
tl_assert(hbthr_p != NULL);
tl_assert( libhb_get_Thr_hgthread(hbthr_p) == thr_p );
hbthr_c = libhb_create ( hbthr_p );
/* Create a new thread record for the child. */
/* a Thread for the new thread ... */
thr_c = mk_Thread( hbthr_c );
tl_assert( libhb_get_Thr_hgthread(hbthr_c) == NULL );
libhb_set_Thr_hgthread(hbthr_c, thr_c);
/* and bind it in the thread-map table */
map_threads[child] = thr_c;
tl_assert(thr_c->coretid == VG_INVALID_THREADID);
thr_c->coretid = child;
/* Record where the parent is so we can later refer to this in
error messages.
On x86/amd64-linux, this entails a nasty glibc specific hack.
The stack snapshot is taken immediately after the parent has
returned from its sys_clone call. Unfortunately there is no
unwind info for the insn following "syscall" - reading the
glibc sources confirms this. So we ask for a snapshot to be
taken as if RIP was 3 bytes earlier, in a place where there
is unwind info. Sigh.
*/
{ Word first_ip_delta = 0;
# if defined(VGP_amd64_linux) || defined(VGP_x86_linux)
first_ip_delta = -3;
# elif defined(VGP_arm64_linux)
first_ip_delta = -1;
# endif
thr_c->created_at = VG_(record_ExeContext)(parent, first_ip_delta);
}
}
if (HG_(clo_sanity_flags) & SCE_THREADS)
all__sanity_check("evh__pre_thread_create-post");
}
static
void evh__pre_thread_ll_exit ( ThreadId quit_tid )
{
Int nHeld;
Thread* thr_q;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__pre_thread_ll_exit(thr=%d)\n",
(Int)quit_tid );
/* quit_tid has disappeared without joining to any other thread.
Therefore there is no synchronisation event associated with its
exit and so we have to pretty much treat it as if it was still
alive but mysteriously making no progress. That is because, if
we don't know when it really exited, then we can never say there
is a point in time when we're sure the thread really has
finished, and so we need to consider the possibility that it
lingers indefinitely and continues to interact with other
threads. */
/* However, it might have rendezvous'd with a thread that called
pthread_join with this one as arg, prior to this point (that's
how NPTL works). In which case there has already been a prior
sync event. So in any case, just let the thread exit. On NPTL,
all thread exits go through here. */
tl_assert(HG_(is_sane_ThreadId)(quit_tid));
thr_q = map_threads_maybe_lookup( quit_tid );
tl_assert(thr_q != NULL);
/* Complain if this thread holds any locks. */
nHeld = HG_(cardinalityWS)( univ_lsets, thr_q->locksetA );
tl_assert(nHeld >= 0);
if (nHeld > 0) {
HChar buf[80];
VG_(sprintf)(buf, "Exiting thread still holds %d lock%s",
nHeld, nHeld > 1 ? "s" : "");
HG_(record_error_Misc)( thr_q, buf );
}
/* Not much to do here:
- tell libhb the thread is gone
- clear the map_threads entry, in order that the Valgrind core
can re-use it. */
/* Cleanup actions (next 5 lines) copied in evh__atfork_child; keep
in sync. */
tl_assert(thr_q->hbthr);
libhb_async_exit(thr_q->hbthr);
tl_assert(thr_q->coretid == quit_tid);
thr_q->coretid = VG_INVALID_THREADID;
map_threads_delete( quit_tid );
if (HG_(clo_sanity_flags) & SCE_THREADS)
all__sanity_check("evh__pre_thread_ll_exit-post");
}
/* This is called immediately after fork, for the child only. 'tid'
is the only surviving thread (as per POSIX rules on fork() in
threaded programs), so we have to clean up map_threads to remove
entries for any other threads. */
static
void evh__atfork_child ( ThreadId tid )
{
UInt i;
Thread* thr;
/* Slot 0 should never be used. */
thr = map_threads_maybe_lookup( 0/*INVALID*/ );
tl_assert(!thr);
/* Clean up all other slots except 'tid'. */
for (i = 1; i < VG_N_THREADS; i++) {
if (i == tid)
continue;
thr = map_threads_maybe_lookup(i);
if (!thr)
continue;
/* Cleanup actions (next 5 lines) copied from end of
evh__pre_thread_ll_exit; keep in sync. */
tl_assert(thr->hbthr);
libhb_async_exit(thr->hbthr);
tl_assert(thr->coretid == i);
thr->coretid = VG_INVALID_THREADID;
map_threads_delete(i);
}
}
/* generate a dependence from the hbthr_q quitter to the hbthr_s stayer. */
static
void generate_quitter_stayer_dependence (Thr* hbthr_q, Thr* hbthr_s)
{
SO* so;
/* Allocate a temporary synchronisation object and use it to send
an imaginary message from the quitter to the stayer, the purpose
being to generate a dependence from the quitter to the
stayer. */
so = libhb_so_alloc();
tl_assert(so);
/* Send last arg of _so_send as False, since the sending thread
doesn't actually exist any more, so we don't want _so_send to
try taking stack snapshots of it. */
libhb_so_send(hbthr_q, so, True/*strong_send*//*?!? wrt comment above*/);
libhb_so_recv(hbthr_s, so, True/*strong_recv*/);
libhb_so_dealloc(so);
/* Tell libhb that the quitter has been reaped. Note that we might
have to be cleverer about this, to exclude 2nd and subsequent
notifications for the same hbthr_q, in the case where the app is
buggy (calls pthread_join twice or more on the same thread) AND
where libpthread is also buggy and doesn't return ESRCH on
subsequent calls. (If libpthread isn't thusly buggy, then the
wrapper for pthread_join in hg_intercepts.c will stop us getting
notified here multiple times for the same joinee.) See also
comments in helgrind/tests/jointwice.c. */
libhb_joinedwith_done(hbthr_q);
}
static
void evh__HG_PTHREAD_JOIN_POST ( ThreadId stay_tid, Thread* quit_thr )
{
Thread* thr_s;
Thread* thr_q;
Thr* hbthr_s;
Thr* hbthr_q;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__post_thread_join(stayer=%d, quitter=%p)\n",
(Int)stay_tid, quit_thr );
tl_assert(HG_(is_sane_ThreadId)(stay_tid));
thr_s = map_threads_maybe_lookup( stay_tid );
thr_q = quit_thr;
tl_assert(thr_s != NULL);
tl_assert(thr_q != NULL);
tl_assert(thr_s != thr_q);
hbthr_s = thr_s->hbthr;
hbthr_q = thr_q->hbthr;
tl_assert(hbthr_s != hbthr_q);
tl_assert( libhb_get_Thr_hgthread(hbthr_s) == thr_s );
tl_assert( libhb_get_Thr_hgthread(hbthr_q) == thr_q );
generate_quitter_stayer_dependence (hbthr_q, hbthr_s);
/* evh__pre_thread_ll_exit issues an error message if the exiting
thread holds any locks. No need to check here. */
/* This holds because, at least when using NPTL as the thread
library, we should be notified the low level thread exit before
we hear of any join event on it. The low level exit
notification feeds through into evh__pre_thread_ll_exit,
which should clear the map_threads entry for it. Hence we
expect there to be no map_threads entry at this point. */
tl_assert( map_threads_maybe_reverse_lookup_SLOW(thr_q)
== VG_INVALID_THREADID);
if (HG_(clo_sanity_flags) & SCE_THREADS)
all__sanity_check("evh__post_thread_join-post");
}
static
void evh__pre_mem_read ( CorePart part, ThreadId tid, const HChar* s,
Addr a, SizeT size) {
if (SHOW_EVENTS >= 2
|| (SHOW_EVENTS >= 1 && size != 1))
VG_(printf)("evh__pre_mem_read(ctid=%d, \"%s\", %p, %lu)\n",
(Int)tid, s, (void*)a, size );
shadow_mem_cread_range( map_threads_lookup(tid), a, size);
if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__pre_mem_read-post");
}
static
void evh__pre_mem_read_asciiz ( CorePart part, ThreadId tid,
const HChar* s, Addr a ) {
Int len;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__pre_mem_asciiz(ctid=%d, \"%s\", %p)\n",
(Int)tid, s, (void*)a );
// Don't segfault if the string starts in an obviously stupid
// place. Actually we should check the whole string, not just
// the start address, but that's too much trouble. At least
// checking the first byte is better than nothing. See #255009.
if (!VG_(am_is_valid_for_client) (a, 1, VKI_PROT_READ))
return;
len = VG_(strlen)( (HChar*) a );
shadow_mem_cread_range( map_threads_lookup(tid), a, len+1 );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__pre_mem_read_asciiz-post");
}
static
void evh__pre_mem_write ( CorePart part, ThreadId tid, const HChar* s,
Addr a, SizeT size ) {
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__pre_mem_write(ctid=%d, \"%s\", %p, %lu)\n",
(Int)tid, s, (void*)a, size );
shadow_mem_cwrite_range( map_threads_lookup(tid), a, size);
if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__pre_mem_write-post");
}
static
void evh__new_mem_heap ( Addr a, SizeT len, Bool is_inited ) {
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__new_mem_heap(%p, %lu, inited=%d)\n",
(void*)a, len, (Int)is_inited );
// FIXME: this is kinda stupid
if (is_inited) {
shadow_mem_make_New(get_current_Thread(), a, len);
} else {
shadow_mem_make_New(get_current_Thread(), a, len);
}
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__pre_mem_read-post");
}
static
void evh__die_mem_heap ( Addr a, SizeT len ) {
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__die_mem_heap(%p, %lu)\n", (void*)a, len );
thr = get_current_Thread();
tl_assert(thr);
if (HG_(clo_free_is_write)) {
/* Treat frees as if the memory was written immediately prior to
the free. This shakes out more races, specifically, cases
where memory is referenced by one thread, and freed by
another, and there's no observable synchronisation event to
guarantee that the reference happens before the free. */
shadow_mem_cwrite_range(thr, a, len);
}
shadow_mem_make_NoAccess_NoFX( thr, a, len );
if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE))
all__sanity_check("evh__pre_mem_read-post");
}
/* --- Event handlers called from generated code --- */
static VG_REGPARM(1)
void evh__mem_help_cread_1(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CREAD_1(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cread_2(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CREAD_2(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cread_4(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CREAD_4(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cread_8(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CREAD_8(hbthr, a);
}
static VG_REGPARM(2)
void evh__mem_help_cread_N(Addr a, SizeT size) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CREAD_N(hbthr, a, size);
}
static VG_REGPARM(1)
void evh__mem_help_cwrite_1(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CWRITE_1(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cwrite_2(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CWRITE_2(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cwrite_4(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CWRITE_4(hbthr, a);
}
static VG_REGPARM(1)
void evh__mem_help_cwrite_8(Addr a) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CWRITE_8(hbthr, a);
}
static VG_REGPARM(2)
void evh__mem_help_cwrite_N(Addr a, SizeT size) {
Thread* thr = get_current_Thread_in_C_C();
Thr* hbthr = thr->hbthr;
LIBHB_CWRITE_N(hbthr, a, size);
}
/* ------------------------------------------------------- */
/* -------------- events to do with mutexes -------------- */
/* ------------------------------------------------------- */
/* EXPOSITION only: by intercepting lock init events we can show the
user where the lock was initialised, rather than only being able to
show where it was first locked. Intercepting lock initialisations
is not necessary for the basic operation of the race checker. */
static
void evh__HG_PTHREAD_MUTEX_INIT_POST( ThreadId tid,
void* mutex, Word mbRec )
{
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_MUTEX_INIT_POST(ctid=%d, mbRec=%ld, %p)\n",
(Int)tid, mbRec, (void*)mutex );
tl_assert(mbRec == 0 || mbRec == 1);
map_locks_lookup_or_create( mbRec ? LK_mbRec : LK_nonRec,
(Addr)mutex, tid );
if (HG_(clo_sanity_flags) & SCE_LOCKS)
all__sanity_check("evh__hg_PTHREAD_MUTEX_INIT_POST");
}
static
void evh__HG_PTHREAD_MUTEX_DESTROY_PRE( ThreadId tid, void* mutex,
Bool mutex_is_init )
{
Thread* thr;
Lock* lk;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_MUTEX_DESTROY_PRE"
"(ctid=%d, %p, isInit=%d)\n",
(Int)tid, (void*)mutex, (Int)mutex_is_init );
thr = map_threads_maybe_lookup( tid );
/* cannot fail - Thread* must already exist */
tl_assert( HG_(is_sane_Thread)(thr) );
lk = map_locks_maybe_lookup( (Addr)mutex );
if (lk == NULL && mutex_is_init) {
/* We're destroying a mutex which we don't have any record of,
and which appears to have the value PTHREAD_MUTEX_INITIALIZER.
Assume it never got used, and so we don't need to do anything
more. */
goto out;
}
if (lk == NULL || (lk->kind != LK_nonRec && lk->kind != LK_mbRec)) {
HG_(record_error_Misc)(
thr, "pthread_mutex_destroy with invalid argument" );
}
if (lk) {
tl_assert( HG_(is_sane_LockN)(lk) );
tl_assert( lk->guestaddr == (Addr)mutex );
if (lk->heldBy) {
/* Basically act like we unlocked the lock */
HG_(record_error_Misc)(
thr, "pthread_mutex_destroy of a locked mutex" );
/* remove lock from locksets of all owning threads */
remove_Lock_from_locksets_of_all_owning_Threads( lk );
VG_(deleteBag)( lk->heldBy );
lk->heldBy = NULL;
lk->heldW = False;
lk->acquired_at = NULL;
}
tl_assert( !lk->heldBy );
tl_assert( HG_(is_sane_LockN)(lk) );
if (HG_(clo_track_lockorders))
laog__handle_one_lock_deletion(lk);
map_locks_delete( lk->guestaddr );
del_LockN( lk );
}
out:
if (HG_(clo_sanity_flags) & SCE_LOCKS)
all__sanity_check("evh__hg_PTHREAD_MUTEX_DESTROY_PRE");
}
static void evh__HG_PTHREAD_MUTEX_LOCK_PRE ( ThreadId tid,
void* mutex, Word isTryLock )
{
/* Just check the mutex is sane; nothing else to do. */
// 'mutex' may be invalid - not checked by wrapper
Thread* thr;
Lock* lk;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_MUTEX_LOCK_PRE(ctid=%d, mutex=%p)\n",
(Int)tid, (void*)mutex );
tl_assert(isTryLock == 0 || isTryLock == 1);
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
lk = map_locks_maybe_lookup( (Addr)mutex );
if (lk && (lk->kind == LK_rdwr)) {
HG_(record_error_Misc)( thr, "pthread_mutex_lock with a "
"pthread_rwlock_t* argument " );
}
if ( lk
&& isTryLock == 0
&& (lk->kind == LK_nonRec || lk->kind == LK_rdwr)
&& lk->heldBy
&& lk->heldW
&& VG_(elemBag)( lk->heldBy, (UWord)thr ) > 0 ) {
/* uh, it's a non-recursive lock and we already w-hold it, and
this is a real lock operation (not a speculative "tryLock"
kind of thing). Duh. Deadlock coming up; but at least
produce an error message. */
const HChar* errstr = "Attempt to re-lock a "
"non-recursive lock I already hold";
const HChar* auxstr = "Lock was previously acquired";
if (lk->acquired_at) {
HG_(record_error_Misc_w_aux)( thr, errstr, auxstr, lk->acquired_at );
} else {
HG_(record_error_Misc)( thr, errstr );
}
}
}
static void evh__HG_PTHREAD_MUTEX_LOCK_POST ( ThreadId tid, void* mutex )
{
// only called if the real library call succeeded - so mutex is sane
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_MUTEX_LOCK_POST(ctid=%d, mutex=%p)\n",
(Int)tid, (void*)mutex );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
evhH__post_thread_w_acquires_lock(
thr,
LK_mbRec, /* if not known, create new lock with this LockKind */
(Addr)mutex
);
}
static void evh__HG_PTHREAD_MUTEX_UNLOCK_PRE ( ThreadId tid, void* mutex )
{
// 'mutex' may be invalid - not checked by wrapper
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_MUTEX_UNLOCK_PRE(ctid=%d, mutex=%p)\n",
(Int)tid, (void*)mutex );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
evhH__pre_thread_releases_lock( thr, (Addr)mutex, False/*!isRDWR*/ );
}
static void evh__HG_PTHREAD_MUTEX_UNLOCK_POST ( ThreadId tid, void* mutex )
{
// only called if the real library call succeeded - so mutex is sane
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_MUTEX_UNLOCK_POST(ctid=%d, mutex=%p)\n",
(Int)tid, (void*)mutex );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
// anything we should do here?
}
/* ------------------------------------------------------- */
/* -------------- events to do with spinlocks ------------ */
/* ------------------------------------------------------- */
/* All a bit of a kludge. Pretend we're really dealing with ordinary
pthread_mutex_t's instead, for the most part. */
static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE( ThreadId tid,
void* slock )
{
Thread* thr;
Lock* lk;
/* In glibc's kludgey world, we're either initialising or unlocking
it. Since this is the pre-routine, if it is locked, unlock it
and take a dependence edge. Otherwise, do nothing. */
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE"
"(ctid=%d, slock=%p)\n",
(Int)tid, (void*)slock );
thr = map_threads_maybe_lookup( tid );
/* cannot fail - Thread* must already exist */;
tl_assert( HG_(is_sane_Thread)(thr) );
lk = map_locks_maybe_lookup( (Addr)slock );
if (lk && lk->heldBy) {
/* it's held. So do the normal pre-unlock actions, as copied
from evh__HG_PTHREAD_MUTEX_UNLOCK_PRE. This stupidly
duplicates the map_locks_maybe_lookup. */
evhH__pre_thread_releases_lock( thr, (Addr)slock,
False/*!isRDWR*/ );
}
}
static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST( ThreadId tid,
void* slock )
{
Lock* lk;
/* More kludgery. If the lock has never been seen before, do
actions as per evh__HG_PTHREAD_MUTEX_INIT_POST. Else do
nothing. */
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_POST"
"(ctid=%d, slock=%p)\n",
(Int)tid, (void*)slock );
lk = map_locks_maybe_lookup( (Addr)slock );
if (!lk) {
map_locks_lookup_or_create( LK_nonRec, (Addr)slock, tid );
}
}
static void evh__HG_PTHREAD_SPIN_LOCK_PRE( ThreadId tid,
void* slock, Word isTryLock )
{
evh__HG_PTHREAD_MUTEX_LOCK_PRE( tid, slock, isTryLock );
}
static void evh__HG_PTHREAD_SPIN_LOCK_POST( ThreadId tid,
void* slock )
{
evh__HG_PTHREAD_MUTEX_LOCK_POST( tid, slock );
}
static void evh__HG_PTHREAD_SPIN_DESTROY_PRE( ThreadId tid,
void* slock )
{
evh__HG_PTHREAD_MUTEX_DESTROY_PRE( tid, slock, 0/*!isInit*/ );
}
/* ----------------------------------------------------- */
/* --------------- events to do with CVs --------------- */
/* ----------------------------------------------------- */
/* A mapping from CV to (the SO associated with it, plus some
auxiliary data for error checking). When the CV is
signalled/broadcasted upon, we do a 'send' into the SO, and when a
wait on it completes, we do a 'recv' from the SO. This is believed
to give the correct happens-before events arising from CV
signallings/broadcasts.
*/
/* .so is the SO for this CV.
.mx_ga is the associated mutex, when .nWaiters > 0
POSIX says effectively that the first pthread_cond_{timed}wait call
causes a dynamic binding between the CV and the mutex, and that
lasts until such time as the waiter count falls to zero. Hence
need to keep track of the number of waiters in order to do
consistency tracking. */
typedef
struct {
SO* so; /* libhb-allocated SO */
void* mx_ga; /* addr of associated mutex, if any */
UWord nWaiters; /* # threads waiting on the CV */
}
CVInfo;
/* pthread_cond_t* -> CVInfo* */
static WordFM* map_cond_to_CVInfo = NULL;
static void map_cond_to_CVInfo_INIT ( void ) {
if (UNLIKELY(map_cond_to_CVInfo == NULL)) {
map_cond_to_CVInfo = VG_(newFM)( HG_(zalloc),
"hg.mctCI.1", HG_(free), NULL );
tl_assert(map_cond_to_CVInfo != NULL);
}
}
static CVInfo* map_cond_to_CVInfo_lookup_or_alloc ( void* cond ) {
UWord key, val;
map_cond_to_CVInfo_INIT();
if (VG_(lookupFM)( map_cond_to_CVInfo, &key, &val, (UWord)cond )) {
tl_assert(key == (UWord)cond);
return (CVInfo*)val;
} else {
SO* so = libhb_so_alloc();
CVInfo* cvi = HG_(zalloc)("hg.mctCloa.1", sizeof(CVInfo));
cvi->so = so;
cvi->mx_ga = 0;
VG_(addToFM)( map_cond_to_CVInfo, (UWord)cond, (UWord)cvi );
return cvi;
}
}
static CVInfo* map_cond_to_CVInfo_lookup_NO_alloc ( void* cond ) {
UWord key, val;
map_cond_to_CVInfo_INIT();
if (VG_(lookupFM)( map_cond_to_CVInfo, &key, &val, (UWord)cond )) {
tl_assert(key == (UWord)cond);
return (CVInfo*)val;
} else {
return NULL;
}
}
static void map_cond_to_CVInfo_delete ( ThreadId tid,
void* cond, Bool cond_is_init ) {
Thread* thr;
UWord keyW, valW;
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
map_cond_to_CVInfo_INIT();
if (VG_(lookupFM)( map_cond_to_CVInfo, &keyW, &valW, (UWord)cond )) {
CVInfo* cvi = (CVInfo*)valW;
tl_assert(keyW == (UWord)cond);
tl_assert(cvi);
tl_assert(cvi->so);
if (cvi->nWaiters > 0) {
HG_(record_error_Misc)(
thr, "pthread_cond_destroy:"
" destruction of condition variable being waited upon");
/* Destroying a cond var being waited upon outcome is EBUSY and
variable is not destroyed. */
return;
}
if (!VG_(delFromFM)( map_cond_to_CVInfo, &keyW, &valW, (UWord)cond ))
tl_assert(0); // cond var found above, and not here ???
libhb_so_dealloc(cvi->so);
cvi->mx_ga = 0;
HG_(free)(cvi);
} else {
/* We have no record of this CV. So complain about it
.. except, don't bother to complain if it has exactly the
value PTHREAD_COND_INITIALIZER, since it might be that the CV
was initialised like that but never used. */
if (!cond_is_init) {
HG_(record_error_Misc)(
thr, "pthread_cond_destroy: destruction of unknown cond var");
}
}
}
static void evh__HG_PTHREAD_COND_SIGNAL_PRE ( ThreadId tid, void* cond )
{
/* 'tid' has signalled on 'cond'. As per the comment above, bind
cond to a SO if it is not already so bound, and 'send' on the
SO. This is later used by other thread(s) which successfully
exit from a pthread_cond_wait on the same cv; then they 'recv'
from the SO, thereby acquiring a dependency on this signalling
event. */
Thread* thr;
CVInfo* cvi;
//Lock* lk;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_COND_SIGNAL_PRE(ctid=%d, cond=%p)\n",
(Int)tid, (void*)cond );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
cvi = map_cond_to_CVInfo_lookup_or_alloc( cond );
tl_assert(cvi);
tl_assert(cvi->so);
// error-if: mutex is bogus
// error-if: mutex is not locked
// Hmm. POSIX doesn't actually say that it's an error to call
// pthread_cond_signal with the associated mutex being unlocked.
// Although it does say that it should be "if consistent scheduling
// is desired." For that reason, print "dubious" if the lock isn't
// held by any thread. Skip the "dubious" if it is held by some
// other thread; that sounds straight-out wrong.
//
// Anybody who writes code that signals on a CV without holding
// the associated MX needs to be shipped off to a lunatic asylum
// ASAP, even though POSIX doesn't actually declare such behaviour
// illegal -- it makes code extremely difficult to understand/
// reason about. In particular it puts the signalling thread in
// a situation where it is racing against the released waiter
// as soon as the signalling is done, and so there needs to be
// some auxiliary synchronisation mechanism in the program that
// makes this safe -- or the race(s) need to be harmless, or
// probably nonexistent.
//
if (1) {
Lock* lk = NULL;
if (cvi->mx_ga != 0) {
lk = map_locks_maybe_lookup( (Addr)cvi->mx_ga );
}
/* note: lk could be NULL. Be careful. */
if (lk) {
if (lk->kind == LK_rdwr) {
HG_(record_error_Misc)(thr,
"pthread_cond_{signal,broadcast}: associated lock is a rwlock");
}
if (lk->heldBy == NULL) {
HG_(record_error_Misc)(thr,
"pthread_cond_{signal,broadcast}: dubious: "
"associated lock is not held by any thread");
}
if (lk->heldBy != NULL && 0 == VG_(elemBag)(lk->heldBy, (UWord)thr)) {
HG_(record_error_Misc)(thr,
"pthread_cond_{signal,broadcast}: "
"associated lock is not held by calling thread");
}
} else {
/* Couldn't even find the damn thing. */
// But actually .. that's not necessarily an error. We don't
// know the (CV,MX) binding until a pthread_cond_wait or bcast
// shows us what it is, and if that may not have happened yet.
// So just keep quiet in this circumstance.
//HG_(record_error_Misc)( thr,
// "pthread_cond_{signal,broadcast}: "
// "no or invalid mutex associated with cond");
}
}
libhb_so_send( thr->hbthr, cvi->so, True/*strong_send*/ );
}
/* returns True if it reckons 'mutex' is valid and held by this
thread, else False */
static Bool evh__HG_PTHREAD_COND_WAIT_PRE ( ThreadId tid,
void* cond, void* mutex )
{
Thread* thr;
Lock* lk;
Bool lk_valid = True;
CVInfo* cvi;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_COND_WAIT_PRE"
"(ctid=%d, cond=%p, mutex=%p)\n",
(Int)tid, (void*)cond, (void*)mutex );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
lk = map_locks_maybe_lookup( (Addr)mutex );
/* Check for stupid mutex arguments. There are various ways to be
a bozo. Only complain once, though, even if more than one thing
is wrong. */
if (lk == NULL) {
lk_valid = False;
HG_(record_error_Misc)(
thr,
"pthread_cond_{timed}wait called with invalid mutex" );
} else {
tl_assert( HG_(is_sane_LockN)(lk) );
if (lk->kind == LK_rdwr) {
lk_valid = False;
HG_(record_error_Misc)(
thr, "pthread_cond_{timed}wait called with mutex "
"of type pthread_rwlock_t*" );
} else
if (lk->heldBy == NULL) {
lk_valid = False;
HG_(record_error_Misc)(
thr, "pthread_cond_{timed}wait called with un-held mutex");
} else
if (lk->heldBy != NULL
&& VG_(elemBag)( lk->heldBy, (UWord)thr ) == 0) {
lk_valid = False;
HG_(record_error_Misc)(
thr, "pthread_cond_{timed}wait called with mutex "
"held by a different thread" );
}
}
// error-if: cond is also associated with a different mutex
cvi = map_cond_to_CVInfo_lookup_or_alloc(cond);
tl_assert(cvi);
tl_assert(cvi->so);
if (cvi->nWaiters == 0) {
/* form initial (CV,MX) binding */
cvi->mx_ga = mutex;
}
else /* check existing (CV,MX) binding */
if (cvi->mx_ga != mutex) {
HG_(record_error_Misc)(
thr, "pthread_cond_{timed}wait: cond is associated "
"with a different mutex");
}
cvi->nWaiters++;
return lk_valid;
}
static void evh__HG_PTHREAD_COND_WAIT_POST ( ThreadId tid,
void* cond, void* mutex,
Bool timeout)
{
/* A pthread_cond_wait(cond, mutex) completed successfully. Find
the SO for this cond, and 'recv' from it so as to acquire a
dependency edge back to the signaller/broadcaster. */
Thread* thr;
CVInfo* cvi;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_COND_WAIT_POST"
"(ctid=%d, cond=%p, mutex=%p)\n, timeout=%d",
(Int)tid, (void*)cond, (void*)mutex, (Int)timeout );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
// error-if: cond is also associated with a different mutex
cvi = map_cond_to_CVInfo_lookup_NO_alloc( cond );
if (!cvi) {
/* This could be either a bug in helgrind or the guest application
that did an error (e.g. cond var was destroyed by another thread.
Let's assume helgrind is perfect ...
Note that this is similar to drd behaviour. */
HG_(record_error_Misc)(thr, "condition variable has been destroyed while"
" being waited upon");
return;
}
tl_assert(cvi);
tl_assert(cvi->so);
tl_assert(cvi->nWaiters > 0);
if (!timeout && !libhb_so_everSent(cvi->so)) {
/* Hmm. How can a wait on 'cond' succeed if nobody signalled
it? If this happened it would surely be a bug in the threads
library. Or one of those fabled "spurious wakeups". */
HG_(record_error_Misc)( thr, "Bug in libpthread: pthread_cond_wait "
"succeeded"
" without prior pthread_cond_post");
}
/* anyway, acquire a dependency on it. */
libhb_so_recv( thr->hbthr, cvi->so, True/*strong_recv*/ );
cvi->nWaiters--;
}
static void evh__HG_PTHREAD_COND_INIT_POST ( ThreadId tid,
void* cond, void* cond_attr )
{
CVInfo* cvi;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_COND_INIT_POST"
"(ctid=%d, cond=%p, cond_attr=%p)\n",
(Int)tid, (void*)cond, (void*) cond_attr );
cvi = map_cond_to_CVInfo_lookup_or_alloc( cond );
tl_assert (cvi);
tl_assert (cvi->so);
}
static void evh__HG_PTHREAD_COND_DESTROY_PRE ( ThreadId tid,
void* cond, Bool cond_is_init )
{
/* Deal with destroy events. The only purpose is to free storage
associated with the CV, so as to avoid any possible resource
leaks. */
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_COND_DESTROY_PRE"
"(ctid=%d, cond=%p, cond_is_init=%d)\n",
(Int)tid, (void*)cond, (Int)cond_is_init );
map_cond_to_CVInfo_delete( tid, cond, cond_is_init );
}
/* ------------------------------------------------------- */
/* -------------- events to do with rwlocks -------------- */
/* ------------------------------------------------------- */
/* EXPOSITION only */
static
void evh__HG_PTHREAD_RWLOCK_INIT_POST( ThreadId tid, void* rwl )
{
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_RWLOCK_INIT_POST(ctid=%d, %p)\n",
(Int)tid, (void*)rwl );
map_locks_lookup_or_create( LK_rdwr, (Addr)rwl, tid );
if (HG_(clo_sanity_flags) & SCE_LOCKS)
all__sanity_check("evh__hg_PTHREAD_RWLOCK_INIT_POST");
}
static
void evh__HG_PTHREAD_RWLOCK_DESTROY_PRE( ThreadId tid, void* rwl )
{
Thread* thr;
Lock* lk;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE(ctid=%d, %p)\n",
(Int)tid, (void*)rwl );
thr = map_threads_maybe_lookup( tid );
/* cannot fail - Thread* must already exist */
tl_assert( HG_(is_sane_Thread)(thr) );
lk = map_locks_maybe_lookup( (Addr)rwl );
if (lk == NULL || lk->kind != LK_rdwr) {
HG_(record_error_Misc)(
thr, "pthread_rwlock_destroy with invalid argument" );
}
if (lk) {
tl_assert( HG_(is_sane_LockN)(lk) );
tl_assert( lk->guestaddr == (Addr)rwl );
if (lk->heldBy) {
/* Basically act like we unlocked the lock */
HG_(record_error_Misc)(
thr, "pthread_rwlock_destroy of a locked mutex" );
/* remove lock from locksets of all owning threads */
remove_Lock_from_locksets_of_all_owning_Threads( lk );
VG_(deleteBag)( lk->heldBy );
lk->heldBy = NULL;
lk->heldW = False;
lk->acquired_at = NULL;
}
tl_assert( !lk->heldBy );
tl_assert( HG_(is_sane_LockN)(lk) );
if (HG_(clo_track_lockorders))
laog__handle_one_lock_deletion(lk);
map_locks_delete( lk->guestaddr );
del_LockN( lk );
}
if (HG_(clo_sanity_flags) & SCE_LOCKS)
all__sanity_check("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE");
}
static
void evh__HG_PTHREAD_RWLOCK_LOCK_PRE ( ThreadId tid,
void* rwl,
Word isW, Word isTryLock )
{
/* Just check the rwl is sane; nothing else to do. */
// 'rwl' may be invalid - not checked by wrapper
Thread* thr;
Lock* lk;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_PRE(ctid=%d, isW=%d, %p)\n",
(Int)tid, (Int)isW, (void*)rwl );
tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */
tl_assert(isTryLock == 0 || isTryLock == 1); /* assured us by wrapper */
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
lk = map_locks_maybe_lookup( (Addr)rwl );
if ( lk
&& (lk->kind == LK_nonRec || lk->kind == LK_mbRec) ) {
/* Wrong kind of lock. Duh. */
HG_(record_error_Misc)(
thr, "pthread_rwlock_{rd,rw}lock with a "
"pthread_mutex_t* argument " );
}
}
static
void evh__HG_PTHREAD_RWLOCK_LOCK_POST ( ThreadId tid, void* rwl, Word isW )
{
// only called if the real library call succeeded - so mutex is sane
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_POST(ctid=%d, isW=%d, %p)\n",
(Int)tid, (Int)isW, (void*)rwl );
tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
(isW ? evhH__post_thread_w_acquires_lock
: evhH__post_thread_r_acquires_lock)(
thr,
LK_rdwr, /* if not known, create new lock with this LockKind */
(Addr)rwl
);
}
static void evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE ( ThreadId tid, void* rwl )
{
// 'rwl' may be invalid - not checked by wrapper
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE(ctid=%d, rwl=%p)\n",
(Int)tid, (void*)rwl );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
evhH__pre_thread_releases_lock( thr, (Addr)rwl, True/*isRDWR*/ );
}
static void evh__HG_PTHREAD_RWLOCK_UNLOCK_POST ( ThreadId tid, void* rwl )
{
// only called if the real library call succeeded - so mutex is sane
Thread* thr;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__hg_PTHREAD_RWLOCK_UNLOCK_POST(ctid=%d, rwl=%p)\n",
(Int)tid, (void*)rwl );
thr = map_threads_maybe_lookup( tid );
tl_assert(thr); /* cannot fail - Thread* must already exist */
// anything we should do here?
}
/* ---------------------------------------------------------- */
/* -------------- events to do with semaphores -------------- */
/* ---------------------------------------------------------- */
/* This is similar to but not identical to the handling for condition
variables. */
/* For each semaphore, we maintain a stack of SOs. When a 'post'
operation is done on a semaphore (unlocking, essentially), a new SO
is created for the posting thread, the posting thread does a strong
send to it (which merely installs the posting thread's VC in the
SO), and the SO is pushed on the semaphore's stack.
Later, when a (probably different) thread completes 'wait' on the
semaphore, we pop a SO off the semaphore's stack (which should be
nonempty), and do a strong recv from it. This mechanism creates
dependencies between posters and waiters of the semaphore.
It may not be necessary to use a stack - perhaps a bag of SOs would
do. But we do need to keep track of how many unused-up posts have
happened for the semaphore.
Imagine T1 and T2 both post once on a semaphore S, and T3 waits
twice on S. T3 cannot complete its waits without both T1 and T2
posting. The above mechanism will ensure that T3 acquires
dependencies on both T1 and T2.
When a semaphore is initialised with value N, we do as if we'd
posted N times on the semaphore: basically create N SOs and do a
strong send to all of then. This allows up to N waits on the
semaphore to acquire a dependency on the initialisation point,
which AFAICS is the correct behaviour.
We don't emit an error for DESTROY_PRE on a semaphore we don't know
about. We should.
*/
/* sem_t* -> XArray* SO* */
static WordFM* map_sem_to_SO_stack = NULL;
static void map_sem_to_SO_stack_INIT ( void ) {
if (map_sem_to_SO_stack == NULL) {
map_sem_to_SO_stack = VG_(newFM)( HG_(zalloc), "hg.mstSs.1",
HG_(free), NULL );
tl_assert(map_sem_to_SO_stack != NULL);
}
}
static void push_SO_for_sem ( void* sem, SO* so ) {
UWord keyW;
XArray* xa;
tl_assert(so);
map_sem_to_SO_stack_INIT();
if (VG_(lookupFM)( map_sem_to_SO_stack,
&keyW, (UWord*)&xa, (UWord)sem )) {
tl_assert(keyW == (UWord)sem);
tl_assert(xa);
VG_(addToXA)( xa, &so );
} else {
xa = VG_(newXA)( HG_(zalloc), "hg.pSfs.1", HG_(free), sizeof(SO*) );
VG_(addToXA)( xa, &so );
VG_(addToFM)( map_sem_to_SO_stack, (UWord)sem, (UWord)xa );
}
}
static SO* mb_pop_SO_for_sem ( void* sem ) {
UWord keyW;
XArray* xa;
SO* so;
map_sem_to_SO_stack_INIT();
if (VG_(lookupFM)( map_sem_to_SO_stack,
&keyW, (UWord*)&xa, (UWord)sem )) {
/* xa is the stack for this semaphore. */
Word sz;
tl_assert(keyW == (UWord)sem);
sz = VG_(sizeXA)( xa );
tl_assert(sz >= 0);
if (sz == 0)
return NULL; /* odd, the stack is empty */
so = *(SO**)VG_(indexXA)( xa, sz-1 );
tl_assert(so);
VG_(dropTailXA)( xa, 1 );
return so;
} else {
/* hmm, that's odd. No stack for this semaphore. */
return NULL;
}
}
static void evh__HG_POSIX_SEM_DESTROY_PRE ( ThreadId tid, void* sem )
{
UWord keyW, valW;
SO* so;
if (SHOW_EVENTS >= 1)
VG_(printf)("evh__HG_POSIX_SEM_DESTROY_PRE(ctid=%d, sem=%p)\n",
(Int)tid, (void*)sem );
map_sem_to_SO_stack_INIT();
/* Empty out the semaphore's SO stack. This way of doing it is
stupid, but at least it's easy. */
while (1) {
so = mb_pop_SO_for_sem( sem );
if (!so) break;
libhb_so_dealloc(so);
}
if (VG_(delFromFM)( map_sem_to_SO_stack, &keyW, &valW, (UWord)sem )) {
XArray* xa = (XArray*)valW;
tl_assert(keyW == (UWord)sem);
tl_assert(xa);
tl_assert(VG_(sizeXA)(xa) == 0); /* preceding loop just emptied it */
VG_(deleteXA)(xa);
}
}