π 2019.12.26 (THU)
WWDC2016 | Session : 412 | Category : Debugging
π Thread Sanitizer and Static Analysis - WWDC 2016 - Videos - Apple Developer
- Find bugs at run time
- Similar to Valgrind
- Low overhead
- Work with Swift 3 and C/C++/Objective-C
- Integrated into Xcode IDE
- Introduced last year
- Finds memory corruption issues
- Effective at finding critical bugs
- Now has full support for Swift
- User of uninitialized mutexes
- Thread leaks (missing
pthread_join
) - Unsafe calls in signal handlers(ex:
malloc
) - Unlock from wrong thread
- Data races
Thread Sanitizer will tell us two race accesses. Read and Write.
Neither of those are a main thread, and the stack traces are the same which means that they are probably executing the same core from multiple threads without using synchronization.
β proper fix here is to dispatch both toe counter increment and the UI update on to the main queue with GCD.
DispatchQueue.main.aync {
activityCount = activityCount + 1
self.updateNetworkActivityUI()
}
This will both take care of the logical problem in our application and also take care of the race because wall the threads will access that count variable from the same thread.
- Edit Scheme - Diagnostics tab
- "Enable Thread Sanitizer" checkbox
- Build and Run
- View all of the generated runtime issue
- Can choose to break on every issue
In order to use Thread Sanitizer, Xcode passes a special flag to both Clang and Swift compilers that instruct them to produce an instrumented binary.
This binary links to a TSan runtime library that is used by the instrumentation to both monitor the execution of the program and detect those threading issues.
- Multiple threads access the same memory without synchronization
- At least one access is a write
- May end up with any value or even memory corruption!
- Use GCD Dispatch racy access to the same serial queue
- Use pthread API, NSLock
pthread_mutex_lock()
to synchronize accesses - New
os_unfair_lock
(use insteadOSSpinLock
) - Atomic operations
- On some architectures (ex. x86) reads and writes are atomic
- But even a "begin" race is undefined behavior in C
- May cause issues with new compilers or architectures
- Does not require running code (unlike sanitizer)
- Great at catching hard to reproduce edge-case bugs
- Supported only for C, C++, and Objective-C
Check for missing localizability
Check for improper instance cleanup
Nullability
- Product > Analyze or Product > Analyze "SingleFile.m"
- View in Issue Navigator
- Explore Issue Path
- New programming model communicate expectation to callers
- Violation can cause crashes or other unexpected behavior
- Swift enforces model in type system with optionals
- Particularly useful in mixed Swift/Objective-C projects
- Logical problem in code
- Incorrect annotations
- Address Sanitizer and Thread Sanitizer
- Clang Static Analyzer
- Use on your code!