SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
ThreadSanitizer
Data race detection in practice
Konstantin Serebryany <kcc@google.com>
Oct 1, 2010
Data races are scary
A data race occurs when two or more threads concurrently
access a shared memory location and at least one of the
accesses is a write.
void Thread1() {
x[123] = 1;
}
void Thread2() {
x[456] = 2;
}
Data races are scary
A data race occurs when two or more threads concurrently
access a shared memory location and at least one of the
accesses is a write.
std::map<int,int> x;
void Thread1() {
x[123] = 1;
}
void Thread2() {
x[345] = 2;
}
Our goal: find races in Google code
Dynamic race detector
• Intercepts program events at run-time
– Memory access: READ, WRITE
– Synchronization: LOCK, UNLOCK, SIGNAL, WAIT
• Maintains global state
– Locks, other synchronization events, threads
– Memory allocation
• Maintains shadow state for each memory location (byte)
– Remembers previous accesses
– Reports race in appropriate state
• Two major approaches:
– LockSet
– Happens-Before
LockSet
void Thread1() {
mu1.Lock();
mu2.Lock();
*X = 1;
mu2.Unlock();
mu1.Unlock(); ...
void Thread2() {
mu1.Lock();
mu3.Lock();
*X = 2;
mu3.Unlock();
mu1.Unlock(); ...
• LockSet: a set of locks held during a memory access
o Thread1: {mu1, mu2}
o Thread2: {mu1, mu3}
• Common LockSet: intersection of LockSets
o {mu1}
LockSet: false positives
void Thread1() {
x->Update(); // LS={}
mu.Lock();
queue.push(x);
mu.Unlock();
}
void Thread2() {
Obj *y = NULL;
mu.Lock();
y = queue.pop_or_null();
mu.Unlock();
if (y) {
y->UseMe(); // LS={}
}
}
Happens-before
partial order on all events
Segment: a sequence of READ/WRITE events of one thread.
Signal(obj) Wait(obj) is a happens-before arc
Seg1 Seg4 -- segments belong to the same thread.≺
Seg1 ≺ Seg5 -- due to Signal/Wait pair with a macthing object.
Seg1 Seg7 -- happens-before is transitive.≺
Seg3 ⊀ Seg6 -- no ordering constraint.
Pure happens-before: misses races
void Thread1() {
x = 1;
mu.Lock();
do_something1();
mu.Unlock();
}
void Thread2() {
do_something2();
// do_something2()
// may take
// lots of time
mu.Lock();
do_something3();
mu.Unlock();
x = 2;
}
Happens-before vs LockSet
• Pure LockSet
– Many false warnings
– Does not miss races, fast
• Pure happens-before detectors:
– Unlock Lock is a happens-before arc
– No false positives
• unless you use lock-free synchronization
– Less predictable, miss many races (30% - 50%)
• Hybrid (happens-before + LockSet):
– Lock/Unlock don't create happens-before arcs
– Have false positives (easy to annotate)
– More predictable, find more races
Quiz: do we have a race?
static Mutex mu;
static bool flag = flag_init_value;
static int var;
void Thread1() { // Runs in thread1.
var = 1; // << First access.
mu.Lock();
flag = true;
mu.Unlock();
}
void Thread2() { // Runs in thread2.
bool f;
do {
mu.Lock();
f = flag;
mu.Unlock();
} while(!f);
var = 2; // << Second access.
}
Dynamic annotations
void Thread1() {
x->Update(); // LS={}
mu.Lock();
queue.push(x);
ANNOTATE_HAPPENS_BEFORE(x);
mu.Unlock();
}
void Thread2() {
Obj *y = NULL;
mu.Lock();
y = queue.pop_or_null();
ANNOTATE_HAPPENS_AFTER(y);
mu.Unlock();
if (y) {
y->UseMe(); // LS={}
}
}
ThreadSanitizer: Algorithm
• Segment: a sequence of READ/WRITE events of one thread
– All events in a segment have the same LockSet
• Segment Set: a set of segments none of which happen-before
any other
• Shadow state:
– Writer Segment Set: all recent writes
– Reader Segment Set: all recent reads, unordered with or
happened-after writes
• State machine: on each READ/WRITE event
– update the Segment Sets
– check accesses for race
ThreadSanitizer: Algorithm
Example
// Thread1
X = ...;
Sem1.Post();
Sem2.Wait();
L1.Lock();
X = ...;
L1.Unlock();
// Thread2
Sem1.Wait();
... = X;
Sem2.Post();
L1.Lock();
X = ...;
L1.Unlock();
... = X;
Example: shadow state
Pure Happens-before
Writer SS Reader SS
S1 -
S1 S2
S3/L1 -
S4/L1 -
S4/L1 S5
Hybrid
Writer SS Reader SS
S1 -
S1 S2
S3/L1 -
S3/L1, S4/L1 -
S3/L1, S4/L1 S5 {Race!}
Report example
WARNING: Possible data race during write of size 4 at 0x633AA0: {{{
T2 (test-thread-2) (locks held: {L122}):
#0 test301::Thread2() racecheck_unittest.cc:5956
#1 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320
#2 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387
Concurrent write(s) happened at (OR AFTER) these points:
T1 (test-thread-1) (locks held: {L121}):
#0 test301::Thread1() racecheck_unittest.cc:5951
#1 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320
#2 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387
Address 0x633AA0 is 0 bytes inside data symbol "_ZN7test3013varE"
Locks involved in this report (reporting last lock sites): {L121, L122}
L121 (0x633A10)
#0 pthread_mutex_lock ts_valgrind_intercepts.c:602
#1 Mutex::Lock() thread_wrappers_pthread.h:162
#2 MutexLock::MutexLock(Mutex*) thread_wrappers_pthread.h:225
#3 test301::Thread1() racecheck_unittest.cc:5950
#4 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320
#5 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387
L122 (0x633A70)
#0 pthread_mutex_lock ts_valgrind_intercepts.c:602
#1 Mutex::Lock() thread_wrappers_pthread.h:162
#2 MutexLock::MutexLock(Mutex*) thread_wrappers_pthread.h:225
#3 test301::Thread2() racecheck_unittest.cc:5955
#4 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320
#5 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387
Conclusions
• ThreadSanitizer: dynamic detector of data races
• C++, Linux & Mac (Valgrind), Windows (PIN)
• Java (instrumentation with Java ASM, experimental)
• Has two modes of operation:
o conservative (pure happens-before): few false reports,
misses some races
o aggressive (hybrid): more false positives, more real bugs
• Supports "Dynamic Annotations", a data race detector API:
o describe custom (e.g. lock-less) synchronization
o hide benign races
o zero noise level even in the most aggressive mode
• Opensource
Conclusions (cont)
• Overhead is comparable to Valgrind/Memcheck
• Slowdown: 5x-50x
• Memory overhead: 3x-6x
• Detailed output
• Contains all locks involved in a race and all stacks
• Runs regularly on thousands Google tests
• Including Chromium and various server-side apps
• Found thousands of races
• Several 'critical' (aka 'top crashers')
• Dozens of potentially harmful
• Tons of benign or test-only
Quiz: unsafe publication (race)
struct Foo {
int a;
Foo() { a = 42; }
};
static Foo *foo = NULL;
void Thread1() { // Create foo.
foo = new Foo();
}
void Thread2() { // Consume foo.
if (foo) {
assert(foo->a == 42);
}
}
Confirming races
• Important if using aggressive mode.
• Insert sleep (1ms-100ms) around suspected racy accesses.
• Wait for the second racy access to arrive.
• Two tools:
• Manual (user instruments C++ code manually)
• Automatic (Valgrind or PIN instrumentation)
• Can not confirm unsafe publication race.
Atomicity violations (high level races)
// If key exists, return m[key].
// Else set m[key]=val and return val.
// Runs from several threads.
int CheckMapAndInsertIfNeeded(int key, int val) {
Map::iterator it;
{
ReaderLockScoped reader(&mu);
it = m->find(key);
if (it != m->end()) return it->first;
}
// <<<<< Another thread may change the map here.
{
WriterLockScoped writer(&mu);
// Atomicity violation!
ASSERT(m->find(key) == m->end());
(*m)[key] = val;
return val;
}
}
Q&A
http://www.google.com/search?q=ThreadSanitizer

Mais conteúdo relacionado

Mais procurados

Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
RootedCON
 
Django and Python Introduction @ UGent
Django and Python Introduction @ UGentDjango and Python Introduction @ UGent
Django and Python Introduction @ UGent
kevinvw
 
Thread priorities35
Thread priorities35Thread priorities35
Thread priorities35
myrajendra
 

Mais procurados (20)

Workshop@naha_val3
Workshop@naha_val3Workshop@naha_val3
Workshop@naha_val3
 
Kalyna block cipher presentation in English
Kalyna block cipher presentation in EnglishKalyna block cipher presentation in English
Kalyna block cipher presentation in English
 
MODERAN BLOCK CIPHER
MODERAN BLOCK CIPHER MODERAN BLOCK CIPHER
MODERAN BLOCK CIPHER
 
Secured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryptionSecured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryption
 
Crypto talk OpenValue meetup 20-3-18
Crypto talk OpenValue meetup 20-3-18Crypto talk OpenValue meetup 20-3-18
Crypto talk OpenValue meetup 20-3-18
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
Des lecture
Des lectureDes lecture
Des lecture
 
Secure code 3rd_party_libs
Secure code 3rd_party_libsSecure code 3rd_party_libs
Secure code 3rd_party_libs
 
Exploiting Cryptographic Misuse - An Example
Exploiting Cryptographic Misuse - An ExampleExploiting Cryptographic Misuse - An Example
Exploiting Cryptographic Misuse - An Example
 
Installation of ns2
Installation of ns2Installation of ns2
Installation of ns2
 
CNIT 127 14: Protection Mechanisms
CNIT 127 14: Protection MechanismsCNIT 127 14: Protection Mechanisms
CNIT 127 14: Protection Mechanisms
 
MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103MOVED: The challenge of SVE in QEMU - SFO17-103
MOVED: The challenge of SVE in QEMU - SFO17-103
 
Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
Eloi Sanfelix - Hardware security: Side Channel Attacks [RootedCON 2011]
 
Block Cipher vs. Stream Cipher
Block Cipher vs. Stream CipherBlock Cipher vs. Stream Cipher
Block Cipher vs. Stream Cipher
 
We shall play a game....
We shall play a game....We shall play a game....
We shall play a game....
 
Django and Python Introduction @ UGent
Django and Python Introduction @ UGentDjango and Python Introduction @ UGent
Django and Python Introduction @ UGent
 
Thread priorities35
Thread priorities35Thread priorities35
Thread priorities35
 
CNIT 127: 3: Shellcode
CNIT 127: 3: ShellcodeCNIT 127: 3: Shellcode
CNIT 127: 3: Shellcode
 
A tale of two(many) proxies
A tale of two(many) proxiesA tale of two(many) proxies
A tale of two(many) proxies
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 

Destaque

Lean мышление / Специфика Lean Startup
Lean мышление / Специфика Lean StartupLean мышление / Специфика Lean Startup
Lean мышление / Специфика Lean Startup
Media Gorod
 
Дмитрий Репин "Московская школа управления Сколково"
Дмитрий Репин "Московская школа управления Сколково"Дмитрий Репин "Московская школа управления Сколково"
Дмитрий Репин "Московская школа управления Сколково"
Media Gorod
 
Postgre Sql в веб приложениях иван золотухин
Postgre Sql в веб приложениях   иван золотухинPostgre Sql в веб приложениях   иван золотухин
Postgre Sql в веб приложениях иван золотухин
Media Gorod
 
контроль качества по Swebok евгений данилов
контроль качества по Swebok   евгений даниловконтроль качества по Swebok   евгений данилов
контроль качества по Swebok евгений данилов
Media Gorod
 
Web Index Report 2009-02
Web Index Report 2009-02Web Index Report 2009-02
Web Index Report 2009-02
Media Gorod
 
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
Media Gorod
 
введение в Ror олег андреев
введение в Ror   олег андрееввведение в Ror   олег андреев
введение в Ror олег андреев
Media Gorod
 

Destaque (7)

Lean мышление / Специфика Lean Startup
Lean мышление / Специфика Lean StartupLean мышление / Специфика Lean Startup
Lean мышление / Специфика Lean Startup
 
Дмитрий Репин "Московская школа управления Сколково"
Дмитрий Репин "Московская школа управления Сколково"Дмитрий Репин "Московская школа управления Сколково"
Дмитрий Репин "Московская школа управления Сколково"
 
Postgre Sql в веб приложениях иван золотухин
Postgre Sql в веб приложениях   иван золотухинPostgre Sql в веб приложениях   иван золотухин
Postgre Sql в веб приложениях иван золотухин
 
контроль качества по Swebok евгений данилов
контроль качества по Swebok   евгений даниловконтроль качества по Swebok   евгений данилов
контроль качества по Swebok евгений данилов
 
Web Index Report 2009-02
Web Index Report 2009-02Web Index Report 2009-02
Web Index Report 2009-02
 
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
Вячеслав Борилин, SPIRITDSP - Построение системы видеокоммуникаций для большо...
 
введение в Ror олег андреев
введение в Ror   олег андрееввведение в Ror   олег андреев
введение в Ror олег андреев
 

Semelhante a Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла тебя»

AOS Lab 4: If you liked it, then you should have put a “lock” on it
AOS Lab 4: If you liked it, then you should have put a “lock” on itAOS Lab 4: If you liked it, then you should have put a “lock” on it
AOS Lab 4: If you liked it, then you should have put a “lock” on it
Zubair Nabi
 
Drd secr final1_3
Drd secr final1_3Drd secr final1_3
Drd secr final1_3
Devexperts
 

Semelhante a Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла тебя» (20)

Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
 
Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?
 
Backtracking Algorithmic Complexity Attacks Against a NIDS
Backtracking Algorithmic Complexity Attacks Against a NIDSBacktracking Algorithmic Complexity Attacks Against a NIDS
Backtracking Algorithmic Complexity Attacks Against a NIDS
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
 
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
BSides LV 2016 - Beyond the tip of the iceberg - fuzzing binary protocols for...
 
AOS Lab 4: If you liked it, then you should have put a “lock” on it
AOS Lab 4: If you liked it, then you should have put a “lock” on itAOS Lab 4: If you liked it, then you should have put a “lock” on it
AOS Lab 4: If you liked it, then you should have put a “lock” on it
 
NSC #2 - Challenge Solution
NSC #2 - Challenge SolutionNSC #2 - Challenge Solution
NSC #2 - Challenge Solution
 
[Kiwicon 2011] Post Memory Corruption Memory Analysis
[Kiwicon 2011] Post Memory Corruption Memory Analysis[Kiwicon 2011] Post Memory Corruption Memory Analysis
[Kiwicon 2011] Post Memory Corruption Memory Analysis
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
 
Kernel
KernelKernel
Kernel
 
Meltdown and Spectre
Meltdown and SpectreMeltdown and Spectre
Meltdown and Spectre
 
[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis
 
[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit Automation[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit Automation
 
Verilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdfVerilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdf
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
 
verilog ppt .pdf
verilog ppt .pdfverilog ppt .pdf
verilog ppt .pdf
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
 
Drd secr final1_3
Drd secr final1_3Drd secr final1_3
Drd secr final1_3
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
 

Mais de Media Gorod

Iidf market watch_2013
Iidf market watch_2013Iidf market watch_2013
Iidf market watch_2013
Media Gorod
 
E travel 2013 ufs-f
E travel 2013 ufs-fE travel 2013 ufs-f
E travel 2013 ufs-f
Media Gorod
 
Travel shop 2013
Travel shop 2013Travel shop 2013
Travel shop 2013
Media Gorod
 
Kozyakov pay u_e-travel2013
Kozyakov pay u_e-travel2013Kozyakov pay u_e-travel2013
Kozyakov pay u_e-travel2013
Media Gorod
 
13909772985295c7a772abc7.11863824
13909772985295c7a772abc7.1186382413909772985295c7a772abc7.11863824
13909772985295c7a772abc7.11863824
Media Gorod
 
As e-travel 2013
As   e-travel 2013As   e-travel 2013
As e-travel 2013
Media Gorod
 
Ishounkina internet research-projects
Ishounkina internet research-projectsIshounkina internet research-projects
Ishounkina internet research-projects
Media Gorod
 
Orlova pay u group_290813_
Orlova pay u group_290813_Orlova pay u group_290813_
Orlova pay u group_290813_
Media Gorod
 
Ep presentation (infographic 2013)
Ep presentation (infographic 2013)Ep presentation (infographic 2013)
Ep presentation (infographic 2013)
Media Gorod
 
Iway slides e-travel_2013-11_ready
Iway slides e-travel_2013-11_readyIway slides e-travel_2013-11_ready
Iway slides e-travel_2013-11_ready
Media Gorod
 
Data insight e-travel2013
Data insight e-travel2013Data insight e-travel2013
Data insight e-travel2013
Media Gorod
 
Электронное Правительство как Продукт
Электронное Правительство как ПродуктЭлектронное Правительство как Продукт
Электронное Правительство как Продукт
Media Gorod
 
Глобальный взгляд на мобильный мир (Nielsen)
 Глобальный взгляд на мобильный мир (Nielsen) Глобальный взгляд на мобильный мир (Nielsen)
Глобальный взгляд на мобильный мир (Nielsen)
Media Gorod
 
Как россияне используют смартфоны (Nielsen)
 Как россияне используют смартфоны (Nielsen) Как россияне используют смартфоны (Nielsen)
Как россияне используют смартфоны (Nielsen)
Media Gorod
 
Мобильный интернет в России (MailRuGroup)
Мобильный интернет в России (MailRuGroup) Мобильный интернет в России (MailRuGroup)
Мобильный интернет в России (MailRuGroup)
Media Gorod
 
Karlovyvaryparti 130406024405-phpapp02
Karlovyvaryparti 130406024405-phpapp02Karlovyvaryparti 130406024405-phpapp02
Karlovyvaryparti 130406024405-phpapp02
Media Gorod
 

Mais de Media Gorod (20)

Itogi2013
Itogi2013Itogi2013
Itogi2013
 
Moneytree rus 1
Moneytree rus 1Moneytree rus 1
Moneytree rus 1
 
Iidf market watch_2013
Iidf market watch_2013Iidf market watch_2013
Iidf market watch_2013
 
E travel 2013 ufs-f
E travel 2013 ufs-fE travel 2013 ufs-f
E travel 2013 ufs-f
 
Travel shop 2013
Travel shop 2013Travel shop 2013
Travel shop 2013
 
Kozyakov pay u_e-travel2013
Kozyakov pay u_e-travel2013Kozyakov pay u_e-travel2013
Kozyakov pay u_e-travel2013
 
13909772985295c7a772abc7.11863824
13909772985295c7a772abc7.1186382413909772985295c7a772abc7.11863824
13909772985295c7a772abc7.11863824
 
As e-travel 2013
As   e-travel 2013As   e-travel 2013
As e-travel 2013
 
Ishounkina internet research-projects
Ishounkina internet research-projectsIshounkina internet research-projects
Ishounkina internet research-projects
 
E travel13
E travel13E travel13
E travel13
 
Orlova pay u group_290813_
Orlova pay u group_290813_Orlova pay u group_290813_
Orlova pay u group_290813_
 
Ep presentation (infographic 2013)
Ep presentation (infographic 2013)Ep presentation (infographic 2013)
Ep presentation (infographic 2013)
 
Iway slides e-travel_2013-11_ready
Iway slides e-travel_2013-11_readyIway slides e-travel_2013-11_ready
Iway slides e-travel_2013-11_ready
 
Data insight e-travel2013
Data insight e-travel2013Data insight e-travel2013
Data insight e-travel2013
 
Электронное Правительство как Продукт
Электронное Правительство как ПродуктЭлектронное Правительство как Продукт
Электронное Правительство как Продукт
 
Глобальный взгляд на мобильный мир (Nielsen)
 Глобальный взгляд на мобильный мир (Nielsen) Глобальный взгляд на мобильный мир (Nielsen)
Глобальный взгляд на мобильный мир (Nielsen)
 
Как россияне используют смартфоны (Nielsen)
 Как россияне используют смартфоны (Nielsen) Как россияне используют смартфоны (Nielsen)
Как россияне используют смартфоны (Nielsen)
 
Мобильный интернет в России (MailRuGroup)
Мобильный интернет в России (MailRuGroup) Мобильный интернет в России (MailRuGroup)
Мобильный интернет в России (MailRuGroup)
 
Meta Mass Media
Meta Mass MediaMeta Mass Media
Meta Mass Media
 
Karlovyvaryparti 130406024405-phpapp02
Karlovyvaryparti 130406024405-phpapp02Karlovyvaryparti 130406024405-phpapp02
Karlovyvaryparti 130406024405-phpapp02
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла тебя»

  • 1. ThreadSanitizer Data race detection in practice Konstantin Serebryany <kcc@google.com> Oct 1, 2010
  • 2. Data races are scary A data race occurs when two or more threads concurrently access a shared memory location and at least one of the accesses is a write. void Thread1() { x[123] = 1; } void Thread2() { x[456] = 2; }
  • 3. Data races are scary A data race occurs when two or more threads concurrently access a shared memory location and at least one of the accesses is a write. std::map<int,int> x; void Thread1() { x[123] = 1; } void Thread2() { x[345] = 2; } Our goal: find races in Google code
  • 4. Dynamic race detector • Intercepts program events at run-time – Memory access: READ, WRITE – Synchronization: LOCK, UNLOCK, SIGNAL, WAIT • Maintains global state – Locks, other synchronization events, threads – Memory allocation • Maintains shadow state for each memory location (byte) – Remembers previous accesses – Reports race in appropriate state • Two major approaches: – LockSet – Happens-Before
  • 5. LockSet void Thread1() { mu1.Lock(); mu2.Lock(); *X = 1; mu2.Unlock(); mu1.Unlock(); ... void Thread2() { mu1.Lock(); mu3.Lock(); *X = 2; mu3.Unlock(); mu1.Unlock(); ... • LockSet: a set of locks held during a memory access o Thread1: {mu1, mu2} o Thread2: {mu1, mu3} • Common LockSet: intersection of LockSets o {mu1}
  • 6. LockSet: false positives void Thread1() { x->Update(); // LS={} mu.Lock(); queue.push(x); mu.Unlock(); } void Thread2() { Obj *y = NULL; mu.Lock(); y = queue.pop_or_null(); mu.Unlock(); if (y) { y->UseMe(); // LS={} } }
  • 7. Happens-before partial order on all events Segment: a sequence of READ/WRITE events of one thread. Signal(obj) Wait(obj) is a happens-before arc Seg1 Seg4 -- segments belong to the same thread.≺ Seg1 ≺ Seg5 -- due to Signal/Wait pair with a macthing object. Seg1 Seg7 -- happens-before is transitive.≺ Seg3 ⊀ Seg6 -- no ordering constraint.
  • 8. Pure happens-before: misses races void Thread1() { x = 1; mu.Lock(); do_something1(); mu.Unlock(); } void Thread2() { do_something2(); // do_something2() // may take // lots of time mu.Lock(); do_something3(); mu.Unlock(); x = 2; }
  • 9. Happens-before vs LockSet • Pure LockSet – Many false warnings – Does not miss races, fast • Pure happens-before detectors: – Unlock Lock is a happens-before arc – No false positives • unless you use lock-free synchronization – Less predictable, miss many races (30% - 50%) • Hybrid (happens-before + LockSet): – Lock/Unlock don't create happens-before arcs – Have false positives (easy to annotate) – More predictable, find more races
  • 10. Quiz: do we have a race? static Mutex mu; static bool flag = flag_init_value; static int var; void Thread1() { // Runs in thread1. var = 1; // << First access. mu.Lock(); flag = true; mu.Unlock(); } void Thread2() { // Runs in thread2. bool f; do { mu.Lock(); f = flag; mu.Unlock(); } while(!f); var = 2; // << Second access. }
  • 11. Dynamic annotations void Thread1() { x->Update(); // LS={} mu.Lock(); queue.push(x); ANNOTATE_HAPPENS_BEFORE(x); mu.Unlock(); } void Thread2() { Obj *y = NULL; mu.Lock(); y = queue.pop_or_null(); ANNOTATE_HAPPENS_AFTER(y); mu.Unlock(); if (y) { y->UseMe(); // LS={} } }
  • 12. ThreadSanitizer: Algorithm • Segment: a sequence of READ/WRITE events of one thread – All events in a segment have the same LockSet • Segment Set: a set of segments none of which happen-before any other • Shadow state: – Writer Segment Set: all recent writes – Reader Segment Set: all recent reads, unordered with or happened-after writes • State machine: on each READ/WRITE event – update the Segment Sets – check accesses for race
  • 14. Example // Thread1 X = ...; Sem1.Post(); Sem2.Wait(); L1.Lock(); X = ...; L1.Unlock(); // Thread2 Sem1.Wait(); ... = X; Sem2.Post(); L1.Lock(); X = ...; L1.Unlock(); ... = X;
  • 15. Example: shadow state Pure Happens-before Writer SS Reader SS S1 - S1 S2 S3/L1 - S4/L1 - S4/L1 S5 Hybrid Writer SS Reader SS S1 - S1 S2 S3/L1 - S3/L1, S4/L1 - S3/L1, S4/L1 S5 {Race!}
  • 16. Report example WARNING: Possible data race during write of size 4 at 0x633AA0: {{{ T2 (test-thread-2) (locks held: {L122}): #0 test301::Thread2() racecheck_unittest.cc:5956 #1 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320 #2 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387 Concurrent write(s) happened at (OR AFTER) these points: T1 (test-thread-1) (locks held: {L121}): #0 test301::Thread1() racecheck_unittest.cc:5951 #1 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320 #2 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387 Address 0x633AA0 is 0 bytes inside data symbol "_ZN7test3013varE" Locks involved in this report (reporting last lock sites): {L121, L122} L121 (0x633A10) #0 pthread_mutex_lock ts_valgrind_intercepts.c:602 #1 Mutex::Lock() thread_wrappers_pthread.h:162 #2 MutexLock::MutexLock(Mutex*) thread_wrappers_pthread.h:225 #3 test301::Thread1() racecheck_unittest.cc:5950 #4 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320 #5 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387 L122 (0x633A70) #0 pthread_mutex_lock ts_valgrind_intercepts.c:602 #1 Mutex::Lock() thread_wrappers_pthread.h:162 #2 MutexLock::MutexLock(Mutex*) thread_wrappers_pthread.h:225 #3 test301::Thread2() racecheck_unittest.cc:5955 #4 MyThread::ThreadBody(MyThread*) thread_wrappers_pthread.h:320 #5 ThreadSanitizerStartThread ts_valgrind_intercepts.c:387
  • 17. Conclusions • ThreadSanitizer: dynamic detector of data races • C++, Linux & Mac (Valgrind), Windows (PIN) • Java (instrumentation with Java ASM, experimental) • Has two modes of operation: o conservative (pure happens-before): few false reports, misses some races o aggressive (hybrid): more false positives, more real bugs • Supports "Dynamic Annotations", a data race detector API: o describe custom (e.g. lock-less) synchronization o hide benign races o zero noise level even in the most aggressive mode • Opensource
  • 18. Conclusions (cont) • Overhead is comparable to Valgrind/Memcheck • Slowdown: 5x-50x • Memory overhead: 3x-6x • Detailed output • Contains all locks involved in a race and all stacks • Runs regularly on thousands Google tests • Including Chromium and various server-side apps • Found thousands of races • Several 'critical' (aka 'top crashers') • Dozens of potentially harmful • Tons of benign or test-only
  • 19. Quiz: unsafe publication (race) struct Foo { int a; Foo() { a = 42; } }; static Foo *foo = NULL; void Thread1() { // Create foo. foo = new Foo(); } void Thread2() { // Consume foo. if (foo) { assert(foo->a == 42); } }
  • 20. Confirming races • Important if using aggressive mode. • Insert sleep (1ms-100ms) around suspected racy accesses. • Wait for the second racy access to arrive. • Two tools: • Manual (user instruments C++ code manually) • Automatic (Valgrind or PIN instrumentation) • Can not confirm unsafe publication race.
  • 21. Atomicity violations (high level races) // If key exists, return m[key]. // Else set m[key]=val and return val. // Runs from several threads. int CheckMapAndInsertIfNeeded(int key, int val) { Map::iterator it; { ReaderLockScoped reader(&mu); it = m->find(key); if (it != m->end()) return it->first; } // <<<<< Another thread may change the map here. { WriterLockScoped writer(&mu); // Atomicity violation! ASSERT(m->find(key) == m->end()); (*m)[key] = val; return val; } }