SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
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() {             void Thread2() {
      x[123] = 1;                  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() {             void Thread2() {
      x[123] = 1;                  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() {    void Thread2() {
  mu1.Lock();         mu1.Lock();
  mu2.Lock();         mu3.Lock();
  *X = 1;             *X = 2;
  mu2.Unlock();       mu3.Unlock();
  mu1.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() {        void Thread2() {
  x->Update(); // LS={}
  mu.Lock();
  queue.push(x);
  mu.Unlock();            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() {     void Thread2() {
  x = 1;               do_something2();
  mu.Lock();           // do_something2()
  do_something1();     // may take
  mu.Unlock();         // 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() {              void Thread2() {
  x->Update(); // LS={}
  mu.Lock();
  queue.push(x);
  ANNOTATE_HAPPENS_BEFORE(x);
                                Obj *y = NULL;
  mu.Unlock();                  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     // Thread2
X = ...;
Sem1.Post();   Sem1.Wait();
               ... = X;
               Sem2.Post();
Sem2.Wait();
L1.Lock();
X = ...;
L1.Unlock();   L1.Lock();
               X = ...;
               L1.Unlock();
               ... = X;
Example: shadow state
          Hybrid
 Writer SS      Reader SS
    S1               -
    S1              S2
   S3/L1             -
S3/L1, S4/L1         -
S3/L1, S4/L1    S5 {Race!}
    Pure Happens-before
 Writer SS      Reader SS
    S1               -
    S1              S2
   S3/L1             -
   S4/L1             -
   S4/L1            S5
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

Más contenido relacionado

La actualidad más candente

Finding root blocker in oracle database
Finding root blocker in oracle databaseFinding root blocker in oracle database
Finding root blocker in oracle databaseMohsen B
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Siouxnikomatsakis
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matterDawid Weiss
 
Let's play with crypto! v2
Let's play with crypto! v2Let's play with crypto! v2
Let's play with crypto! v2Ange Albertini
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Ciklum Minsk
 
Js set timeout & setinterval
Js set timeout & setintervalJs set timeout & setinterval
Js set timeout & setintervalARIF MAHMUD RANA
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39myrajendra
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra Max Penet
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Let's play with crypto!
Let's play with crypto!Let's play with crypto!
Let's play with crypto!Ange Albertini
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011Patrick Walton
 
Block Cipher vs. Stream Cipher
Block Cipher vs. Stream CipherBlock Cipher vs. Stream Cipher
Block Cipher vs. Stream CipherAmirul Wiramuda
 

La actualidad más candente (20)

Finding root blocker in oracle database
Finding root blocker in oracle databaseFinding root blocker in oracle database
Finding root blocker in oracle database
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
Let's play with crypto! v2
Let's play with crypto! v2Let's play with crypto! v2
Let's play with crypto! v2
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
 
Js set timeout & setinterval
Js set timeout & setintervalJs set timeout & setinterval
Js set timeout & setinterval
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Let's play with crypto!
Let's play with crypto!Let's play with crypto!
Let's play with crypto!
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Block Cipher vs. Stream Cipher
Block Cipher vs. Stream CipherBlock Cipher vs. Stream Cipher
Block Cipher vs. Stream Cipher
 

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

Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...
Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...
Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...Media Gorod
 
Fast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya SerebryanyFast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya Serebryanyyaevents
 
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...Yandex
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreKim Phillips
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelVitaly Nikolenko
 
Where destructors meet threads
Where destructors meet threadsWhere destructors meet threads
Where destructors meet threadsShuo Chen
 
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?greenwop
 
[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 AnalysisMoabi.com
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfsagar414433
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfsagar414433
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
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 NIDSamiable_indian
 
[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 AnalysisMoabi.com
 
[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit Automation[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit AutomationMoabi.com
 
NSC #2 - Challenge Solution
NSC #2 - Challenge SolutionNSC #2 - Challenge Solution
NSC #2 - Challenge SolutionNoSuchCon
 
Drd secr final1_3
Drd secr final1_3Drd secr final1_3
Drd secr final1_3Devexperts
 

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

Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...
Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...
Константин Серебряный, Google, - Как мы охотимся на гонки (data races) или «н...
 
Fast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya SerebryanyFast dynamic analysis, Kostya Serebryany
Fast dynamic analysis, Kostya Serebryany
 
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
Константин Серебряный "Быстрый динамичекский анализ программ на примере поиск...
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Where destructors meet threads
Where destructors meet threadsWhere destructors meet threads
Where destructors meet threads
 
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?
 
[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
 
Cryptography Attacks and Applications
Cryptography Attacks and ApplicationsCryptography Attacks and Applications
Cryptography Attacks and Applications
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
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
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
verilog ppt .pdf
verilog ppt .pdfverilog ppt .pdf
verilog ppt .pdf
 
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
 
[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
 
[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit Automation[HITB Malaysia 2011] Exploit Automation
[HITB Malaysia 2011] Exploit Automation
 
NSC #2 - Challenge Solution
NSC #2 - Challenge SolutionNSC #2 - Challenge Solution
NSC #2 - Challenge Solution
 
Drd secr final1_3
Drd secr final1_3Drd secr final1_3
Drd secr final1_3
 

Más de yaevents

Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...
Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...
Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...yaevents
 
Тема для WordPress в БЭМ. Владимир Гриненко, Яндекс
Тема для WordPress в БЭМ. Владимир Гриненко, ЯндексТема для WordPress в БЭМ. Владимир Гриненко, Яндекс
Тема для WordPress в БЭМ. Владимир Гриненко, Яндексyaevents
 
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...yaevents
 
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндекс
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндексi-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндекс
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндексyaevents
 
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...yaevents
 
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...Модели в профессиональной инженерии и тестировании программ. Александр Петрен...
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...yaevents
 
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...yaevents
 
Мониторинг со всех сторон. Алексей Симаков, Яндекс
Мониторинг со всех сторон. Алексей Симаков, ЯндексМониторинг со всех сторон. Алексей Симаков, Яндекс
Мониторинг со всех сторон. Алексей Симаков, Яндексyaevents
 
Истории про разработку сайтов. Сергей Бережной, Яндекс
Истории про разработку сайтов. Сергей Бережной, ЯндексИстории про разработку сайтов. Сергей Бережной, Яндекс
Истории про разработку сайтов. Сергей Бережной, Яндексyaevents
 
Разработка приложений для Android на С++. Юрий Береза, Shturmann
Разработка приложений для Android на С++. Юрий Береза, ShturmannРазработка приложений для Android на С++. Юрий Береза, Shturmann
Разработка приложений для Android на С++. Юрий Береза, Shturmannyaevents
 
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...yaevents
 
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...yaevents
 
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндекс
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, ЯндексСканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндекс
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндексyaevents
 
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebook
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, FacebookМасштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebook
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebookyaevents
 
Контроль зверей: инструменты для управления и мониторинга распределенных сист...
Контроль зверей: инструменты для управления и мониторинга распределенных сист...Контроль зверей: инструменты для управления и мониторинга распределенных сист...
Контроль зверей: инструменты для управления и мониторинга распределенных сист...yaevents
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Googleyaevents
 
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...yaevents
 
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...yaevents
 
В поисках математики. Михаил Денисенко, Нигма
В поисках математики. Михаил Денисенко, НигмаВ поисках математики. Михаил Денисенко, Нигма
В поисках математики. Михаил Денисенко, Нигмаyaevents
 
Using classifiers to compute similarities between face images. Prof. Lior Wol...
Using classifiers to compute similarities between face images. Prof. Lior Wol...Using classifiers to compute similarities between face images. Prof. Lior Wol...
Using classifiers to compute similarities between face images. Prof. Lior Wol...yaevents
 

Más de yaevents (20)

Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...
Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...
Как научить роботов тестировать веб-интерфейсы. Артем Ерошенко, Илья Кацев, Я...
 
Тема для WordPress в БЭМ. Владимир Гриненко, Яндекс
Тема для WordPress в БЭМ. Владимир Гриненко, ЯндексТема для WordPress в БЭМ. Владимир Гриненко, Яндекс
Тема для WordPress в БЭМ. Владимир Гриненко, Яндекс
 
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...
Построение сложносоставных блоков в шаблонизаторе bemhtml. Сергей Бережной, Я...
 
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндекс
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндексi-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндекс
i-bem.js: JavaScript в БЭМ-терминах. Елена Глухова, Варвара Степанова, Яндекс
 
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...
Дом из готовых кирпичей. Библиотека блоков, тюнинг, инструменты. Елена Глухов...
 
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...Модели в профессиональной инженерии и тестировании программ. Александр Петрен...
Модели в профессиональной инженерии и тестировании программ. Александр Петрен...
 
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...
Администрирование небольших сервисов или один за всех и 100 на одного. Роман ...
 
Мониторинг со всех сторон. Алексей Симаков, Яндекс
Мониторинг со всех сторон. Алексей Симаков, ЯндексМониторинг со всех сторон. Алексей Симаков, Яндекс
Мониторинг со всех сторон. Алексей Симаков, Яндекс
 
Истории про разработку сайтов. Сергей Бережной, Яндекс
Истории про разработку сайтов. Сергей Бережной, ЯндексИстории про разработку сайтов. Сергей Бережной, Яндекс
Истории про разработку сайтов. Сергей Бережной, Яндекс
 
Разработка приложений для Android на С++. Юрий Береза, Shturmann
Разработка приложений для Android на С++. Юрий Береза, ShturmannРазработка приложений для Android на С++. Юрий Береза, Shturmann
Разработка приложений для Android на С++. Юрий Береза, Shturmann
 
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...
Кросс-платформенная разработка под мобильные устройства. Дмитрий Жестилевский...
 
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...
Сложнейшие техники, применяемые буткитами и полиморфными вирусами. Вячеслав З...
 
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндекс
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, ЯндексСканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндекс
Сканирование уязвимостей со вкусом Яндекса. Тарас Иващенко, Яндекс
 
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebook
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, FacebookМасштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebook
Масштабируемость Hadoop в Facebook. Дмитрий Мольков, Facebook
 
Контроль зверей: инструменты для управления и мониторинга распределенных сист...
Контроль зверей: инструменты для управления и мониторинга распределенных сист...Контроль зверей: инструменты для управления и мониторинга распределенных сист...
Контроль зверей: инструменты для управления и мониторинга распределенных сист...
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Google
 
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
 
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...
Зачем обычному программисту знать языки, на которых почти никто не пишет. Але...
 
В поисках математики. Михаил Денисенко, Нигма
В поисках математики. Михаил Денисенко, НигмаВ поисках математики. Михаил Денисенко, Нигма
В поисках математики. Михаил Денисенко, Нигма
 
Using classifiers to compute similarities between face images. Prof. Lior Wol...
Using classifiers to compute similarities between face images. Prof. Lior Wol...Using classifiers to compute similarities between face images. Prof. Lior Wol...
Using classifiers to compute similarities between face images. Prof. Lior Wol...
 

Как мы охотимся на гонки (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() { void Thread2() { x[123] = 1; 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() { void Thread2() { x[123] = 1; 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() { void Thread2() { mu1.Lock(); mu1.Lock(); mu2.Lock(); mu3.Lock(); *X = 1; *X = 2; mu2.Unlock(); mu3.Unlock(); mu1.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() { void Thread2() { x->Update(); // LS={} mu.Lock(); queue.push(x); mu.Unlock(); 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() { void Thread2() { x = 1; do_something2(); mu.Lock(); // do_something2() do_something1(); // may take mu.Unlock(); // 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() { void Thread2() { x->Update(); // LS={} mu.Lock(); queue.push(x); ANNOTATE_HAPPENS_BEFORE(x); Obj *y = NULL; mu.Unlock(); 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 // Thread2 X = ...; Sem1.Post(); Sem1.Wait(); ... = X; Sem2.Post(); Sem2.Wait(); L1.Lock(); X = ...; L1.Unlock(); L1.Lock(); X = ...; L1.Unlock(); ... = X;
  • 15. Example: shadow state Hybrid Writer SS Reader SS S1 - S1 S2 S3/L1 - S3/L1, S4/L1 - S3/L1, S4/L1 S5 {Race!} Pure Happens-before Writer SS Reader SS S1 - S1 S2 S3/L1 - S4/L1 - S4/L1 S5
  • 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; } }