Skip to content

Conversation

@frankmorgner
Copy link
Member

#2707 was haunting me for months now and I was finally able to track the problem down to a race condition in sc_lock().

On my way, I learned about valgrind's Helgrind, which may be used like this:

valgrind --tool=helgrind --error-limit=no --free-is-write=yes pkcs11-tool --test-threads ILGISL  --test-threads ILGISL --test-threads ILGISL --test-threads ILGISL

This still shows some problem in pkcs11-tool, which I am ignoring for now.

Unfortunately, running Firefox with helgrind is not possible, at least on my machine, which caused me a lot of headache while finally fixing the real problem. I think it would be very useful if we could extend pkcs11-tool's thread tests with the tests we already have in place by using --test --pin=123456. Currently --test-threads only calls C_Initialize (IL), C_GetInfo (GI) or C_GetSlotList (SL).

Checklist
  • PKCS#11 module is tested

@frankmorgner
Copy link
Member Author

@dengert , could you check whether ignoring the result of card_reader_lock_obtained in sc_lock is OK for you?

card->mutex is used to protect card->lock_count, so let's limit the
scope of the mutex to where the lock_count is used.

First and foremost, this fixes
OpenSC#2707, which is caused by PIV's
failing card_reader_lock_obtained, which would have caused sc_lock to
change lock_count while *not* locking the mutex, which creates a race
condition with other threads using and modifying lock_count.

Secondly, this fixes a possible dead lock when sc_lock is used inside
the card's card->sm_ctx.ops.open, which previously would be called in
sc_lock when the mutex was locked.
@frankmorgner
Copy link
Member Author

I've extended this PR to allow the pkcs11-tool's test suite to be run in multiple threads, e.g. via

pkcs11-tool --use-locking --pin=123456 --test-threads LT  --test-threads LT

@frankmorgner
Copy link
Member Author

with the last couple of changes, no more race conditions were found by helgrind 🥳

@frankmorgner frankmorgner merged commit aa394f2 into OpenSC:master Apr 12, 2023
@xhanulik xhanulik mentioned this pull request Jul 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants