shaka-player-embedded
shaka-player-embedded copied to clipboard
Write clang plugin to audit thread use
Handle multi-threaded use is one of the most complex tasks in C++. For much of our code, we make a lot of assumptions on which thread things happen. This allows us to avoid having locks for each type, but can complicate usage since it is purely by convention.
One way to help would be to add annotations to the code and have a clang plugin analyze the calls to verify things happen on the correct thread. For example, we could annotate a method with THREAD_AFFINITY(MainThread) to indicate that method should only be called from the main thread. Then if you call the method from a different thread it will produce an error. It will detect this only using the annotations, so we'll need to annotate every method and type.
One problem with this is the standard container functions; it may be hard to audit those calls since we can't annotate those functions. For example, detecting a call to a method from std::find is OK so long as the caller of std::find is in the correct thread; but this may be hard to detect. It also may be difficult to detect calls through std::function.
This could also warn about incorrect lock usage. All methods need to be marked with THREAD_AFFINITY or with THREAD_SAFE and use a lock. It will give us an error if a method uses THREAD_SAFE and doesn't use a lock. This ensures people don't misuse locks for getters/setters which do still require locks.
For example:
THREAD_AFFINITY(MainThread) // All member methods implicitly have this affinity.
class HTMLVideoElement : public BackingObject {};
THREAD_SAFE
void ScheduleEvent(...);
THREAD_AFFINITY(Demuxer)
void DoSomething() {
video_->CurrentTime(); // Error: Calling CurrentTime from incorrect thread.
}