[cairo] Fixing concurrency bugs in cairo's reference counting

Jamey Sharp jamey at minilop.net
Mon Dec 18 12:03:14 PST 2006


On Thu, Dec 14, 2006 at 05:35:01AM -0800, Carl Worth wrote:
> Similarly, we test the value for 0 after decrementing. It's harder to
> guarantee that that's safe, but I think it is.

I'm not sure if this is the same thing Kristian just pointed out, but a
decrement and test implemented like this is not safe:

atomically fetch, decrement, store
fetch
test against 0

If the reference count is 2, then two threads might execute the
decrement before either re-fetches the value. Then both see 0 and the
memory is freed twice. But I wouldn't count on the compiler generating
the right thing given an atomic_decrement function or macro and a
subsequent test.

The Linux kernel function atomic_dec_and_test, in <asm/atomic.h>,
atomically decrements, but leaves the new value in a register, so it
needn't re-fetch. (Actually, on x86, it only leaves the zero-flag set.)
glibc has an equivalent, though I think it isn't installed for
applications to use...

> The thing to look out for is a race condition between acquiring a
> pointer to an object and incrementing the reference count. If another
> thread can decrement the reference counter to 0 during that window we
> lose. (And note that Monty's mutex locks wouldn't even help here.)

I had to read this a few times to understand the issue and figure out
that it wasn't related to the previous sentence. I guess the only option
is to ensure that the source of the pointer continues to hold a
reference until you can get your own. That should be pretty easy to
ensure statically, at least with the help of a mutex here and there.

--Jamey
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://lists.freedesktop.org/archives/cairo/attachments/20061218/d299bab5/attachment.pgp


More information about the cairo mailing list