SlideShare a Scribd company logo
UNDEFINED BEHAVIORUNDEFINED BEHAVIOR
SŁAWOMIR ZBOROWSKISŁAWOMIR ZBOROWSKI
CODE::DIVE V3.0 (2016), WROCŁAW, PLCODE::DIVE V3.0 (2016), WROCŁAW, PL
http://www.krschannel.com/blackhole.jpg
1 of 74
SŁAWEK ZBOROWSKISŁAWEK ZBOROWSKI
WROCŁAW, POLANDWROCŁAW, POLAND
C++ Engineer @
Opinions expressed are solely my own and do not express the
views or opinions of my employer.
2 of 74
TARGET AUDIENCETARGET AUDIENCE
3 of 74
OUTLINEOUTLINE
low level = danger
perils of undefined behavior
undefined behavior
what, where & why?
UB in C/C++
list, examples
ub sanitizer
motivation, usage, ubsan in action
4 of 74
OUTLINEOUTLINE
low level = danger
perils of undefined behavior
undefined behavior
what, where & why?
UB in C/C++
list, examples
ub sanitizer
motivation, usage, ubsan in action
5 of 74
UNRTF STORYUNRTF STORY
6 of 74
UNRTF STORYUNRTF STORY
https://www.reqview.com/img/doc/DOORSUserNeedsStandardView.png
7 of 74
UNRTF STORYUNRTF STORY
8 of 74
UNRTF STORYUNRTF STORY
9 of 74
UNRTF STORYUNRTF STORY
happyworker.com/sites/default/files/styles/940x450/public/slideshow/mozilla-firefox-plush-front.jpg
10 of 74
UNRTF STORYUNRTF STORY
happyworker.com/sites/default/files/styles/940x450/public/slideshow/mozilla-firefox-plush-front.jpg
11 of 74
UNRTF STORYUNRTF STORY
happyworker.com/sites/default/files/styles/940x450/public/slideshow/mozilla-firefox-plush-front.jpg
12 of 74
UNRTF STORYUNRTF STORY
1 from subprocess import Popen, PIPE
2
3 # ...
4
5 p = Popen(["unrtf"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
6
7 r = p.communicate(input_data)
13 of 74
UNRTF STORYUNRTF STORY
1 from subprocess import Popen, PIPE
2
3 # ...
4
5 p = Popen(["unrtf"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
6
7 r = p.communicate(input_data)
http://ci.memecdn.com/53/5397053.jpg
14 of 74
UNRTF STORYUNRTF STORY
http://devopsreactions.tumblr.com/post/140680248273/the-effect-of-gil-on-multithreaded-python-
programs
15 of 74
C++C++
10X FASTER10X FASTER
16 of 74
UNRTF STORYUNRTF STORY
17 of 74
UNRTF STORYUNRTF STORY
18 of 74
UNRTF STORYUNRTF STORY
19 of 74
UNRTF STORYUNRTF STORY
global-buffer-overflow @ font entry table
20 of 74
LESSONS LEARNEDLESSONS LEARNED
http://icons.iconarchive.com
/icons/untergunter/leaf-mimes/256/text-x-python-icon.png
21 of 74
LESSONS LEARNEDLESSONS LEARNED
http://icons.iconarchive.com
/icons/untergunter/leaf-mimes/256/text-x-python-icon.png
22 of 74
OUTLINEOUTLINE
low level = danger
perils of undefined behavior
undefined behavior
what, where & why?
UB in C/C++
list, examples
ub sanitizer
motivation, usage, ubsan in action
23 of 74
THE DEFINITONTHE DEFINITON
24 of 74
BUT WHAT DOES IT MEAN?BUT WHAT DOES IT MEAN?
actually anything
and this is the most frightening thing…
25 of 74
UB CAN EXHIBITUB CAN EXHIBIT
- SIMPLY NOTHING- SIMPLY NOTHING
you don't want this
26 of 74
UB CAN EXHIBITUB CAN EXHIBIT
- WEIRD BEHAVIOR- WEIRD BEHAVIOR
a little bit better, but still not preferred
27 of 74
UB CAN EXHIBITUB CAN EXHIBIT
- A CRASH- A CRASH
https://i.imgur.com/YxjYp.jpg
this is what you want
28 of 74
UB OUTSIDE C/C++UB OUTSIDE C/C++
C++ is not the only one:
Fortran
…
Go
Rust (Unsafe Rust)
29 of 74
http://math-fail.com/images-old/divide-by-zero6.jpg
30 of 74
2 = 12 = 1
a = b
a2 = ab
a2 – b2 = ab – b2
(a – b)(a + b) = b(a – b)
a + b = b
b + b = b
2 = 1
division by zero
invalidates all
subsequent operations
in C++ it is even worse!
31 of 74
PATTERN?PATTERN?
compiled
weakly-typed
interpreted
strongly-typed
32 of 74
PATTERN?PATTERN?
perils
of
UB
compiled
weakly-typed
interpreted
strongly-typed
33 of 74
PATTERN?PATTERN?
perils
of
UB
compiled
weakly-typed
interpreted
strongly-typed
34 of 74
PATTERN?PATTERN?
perils
of
UB
compiled
weakly-typed
interpreted
strongly-typed
35 of 74
WHY NOT AVOID UB AT ALL?WHY NOT AVOID UB AT ALL?
36 of 74
37 of 74
Is bounds checking in C or C++ expensive?
38 of 74
39 of 74
40 of 74
OUTLINEOUTLINE
low level = danger
perils of undefined behavior
undefined behavior
what, where & why?
UB in C/C++
list, examples
ub sanitizer
motivation, usage, ubsan in action
41 of 74
, ACCU 2016
the more complicated the
code, the higher chance it
contains UB
J. Daniel Garcia
42 of 74
arr[i] = i++; // you think it's safe?
43 of 74
44 of 74
UB IN C/C++UB IN C/C++
"is undefined" - 130 occurences in the standard
report more than 190 UBs
available online, so created
some sources
dra� sources "ub extractor"
45 of 74
UB EXTRACTORUB EXTRACTOR
46 of 74
ARRAY BOUNDARIESARRAY BOUNDARIES
47 of 74
MODIFYING CONSTSMODIFYING CONSTS
1 char * PREFERRED_PROTOCOL_VERSION = "2.0";
2
3 void foo(Environment const& environment) {
4 if (environment.get("PROTO_V1")) {
5 PREFERRED_PROTOCOL_VERSION[0] = '1'; // KABOOM
6 }
7 }
§7.1.7.1[dcl.type.cv]/4
48 of 74
UNDEF MATH OPSUNDEF MATH OPS
1 int ret = 0;
2 for (int i = 100; i > 0; --i) {
3 ret += i;
4 }
5 return ret;
movl $5050, %eax
1 float ret = 1;
2 for (int i = 10; i > 1; --i) {
3 ret /= i;
4 }
5 return static_cast<int>(ret * 1e7);
movl $2, %eax
49 of 74
UNDEFINED MATH OPSUNDEFINED MATH OPS
1 void foo(int x, int y) {
2 for (int i = 0; i < 100; ++i) {
3 globalVar += i * (y / (x - 2));
4 }
5 }
50 of 74
UNDEFINED MATH OPSUNDEFINED MATH OPS
1 void foo(int x, int y) {
2 int _X = y / (x - 2);
3 for (int i = 0; i < 100; ++i) {
4 globalVar += i * _X;
5 }
6 }
TRAVELLING BUG PROBLEMTRAVELLING BUG PROBLEM
51 of 74
INT OVERFLOWINT OVERFLOW
example taken from http://www.airs.com/blog/archives/120
1 int foo(int i) {
2 int k = 0;
3 for (int j = i; j < i + 10; ++j, ++k);
4 return k;
5 }
foo(30);
§5[expr]/4
foo(INT_MAX-1); // Oops!
52 of 74
taken from
LEFT SHIFTLEFT SHIFT
Chromium bug #3905
1 void
2 RelocIterator::AdvanceReadPosition() {
3 int x = 0;
4 for (int i = 0; i < kIntSize; i++) {
5 x |= static_cast<int>(*--pos_) << i * kBitsPerByte;
6 }
7 last_position_ += x;
8 rinfo_.data_ = last_position_;
9 }
§5.8[expr.shi�]/2
53 of 74
FLOATING POINT → INTFLOATING POINT → INT
1 void bar(int value);
2
3 void foo(float user_data) {
4 bar(user_data);
5 }
(approx) int range (x86-64): ±231 ±2.15·109
float range (iee754): ±3.4·1038
Oops!
§4.10[conv.fpint]/1
54 of 74
INT → ENUMINT → ENUM
1 enum class Color {
2 Red,
3 Blue,
4 // ...
5 Green,
6
7 Invalid
8 };
9
10 void foo(int user_data) {
11 if (static_cast<Color>(user_data) > Color::Invalid) {
12 // ...
13 }
14 // ...
15 }
55 of 74
BOOL ∉ {TRUE,FALSE}BOOL ∉ {TRUE,FALSE}
§3.9.1[basic.fundamental]/6
56 of 74
DANGEROUS CONSTRUCTORSDANGEROUS CONSTRUCTORS
1 struct Screen : ScreenBase {
2 ScreenResolution getResolution(VideoMode const&) override {
3 return {};
4 }
5
6 explicit Screen(VideoMode const& vm)
7 : ScreenBase(getResolution(vm)) {
8 }
9 };
57 of 74
DANGEROUS DESTRUCTORSDANGEROUS DESTRUCTORS
1 struct A;
2 void foo(A * a) {
3 delete a;
4 }
§5.3.5[expr.delete]/5
BTW — compilers are more verbose nowadays
58 of 74
DANGEROUS DESTRUCTORSDANGEROUS DESTRUCTORS
1 struct A {};
2 struct B : public A { std::string foo = "foo"; };
3
4 void foo() {
5 A * b = new B;
6 delete b;
7 }
§5.3.5[expr.delete]/3
59 of 74
BESIDES UBBESIDES UB
conditionally-supported behavior
unspecified behavior
implementation-defined behavior
locale-specific behavior
https://www.flickr.com/photos/andrew_jian/475479747
60 of 74
OUTLINEOUTLINE
low level = danger
perils of undefined behavior
undefined behavior
what, where & why?
UB in C/C++
list, examples
ub sanitizer
motivation, usage, ubsan in action
61 of 74
UBSANUBSAN
Undefined Behavior Sanitizer
compiler-generated instrumentalization for detecting UB
at runtime
sibling of ASan, TSan, etc.
62 of 74
WHY COMPILER-GENERATED?WHY COMPILER-GENERATED?
static analysis — no way
valgrind-like — too slow
separate tool — support for multiple targets needed
63 of 74
USING UBSANUSING UBSAN
just add -fsanitize=undefined compiler flag
can specify what happens upon UB
print & continue print & exit trap
div by zero x
int overflow x
array bounds x
…
64 of 74
ACHTUNG!ACHTUNG!
not all HW architectures / OSes are supported out-of-
the-box!
it doesn't find everything
65 of 74
HUNTING FOR UBHUNTING FOR UB
vs
no UB spotted
66 of 74
HUNTING FOR UBHUNTING FOR UB
vs
67 of 74
HUNTING FOR UBHUNTING FOR UB
https://static.ylilauta.org/files/ke/orig/99tjgpx9/knallil%C3%B6tk%C3%B6tin.jpg
68 of 74
HUNTING FOR UBHUNTING FOR UB
69 of 74
HUNTING FOR UBHUNTING FOR UB
vs
zero UBs
70 of 74
GOING FURTHER?GOING FURTHER?
American Fuzzy Lop (or other)
LFS
VM/QEMU
71 of 74
DISCLAIMERSDISCLAIMERS
ISO C++ standard used: N4606 (2016-07-12)
Compiler used for hunting: Clang 4.0
no animals were harmed in the making of this presentation
72 of 74
WRAP UPWRAP UP
UB is dangerous
UB exists because of high performance needs
UB can be fought with UB sanitizer
73 of 74
THANKSTHANKS
http://img.mota.ru/upload/wallpapers/2013/03/08/14/03/35089/0xKNOZ92Hj-2560x1600.jpg
74 of 74

More Related Content

Viewers also liked (12)

PPTX
Is cloud computing right for your business
Tyrone Systems
 
PDF
Gudi Padwa 2017
Swati1223
 
PPTX
Higiene y seguridad indusrtial
daniel acosta cubides
 
PPTX
popular games in india
SHANTY E V E V
 
PPTX
Task 2
georgia lonie
 
PDF
Apresentação Konnecta TI Consultoria
Gilberto Nunes
 
PPTX
3Com 3C10318
savomir
 
PPTX
Búsqueda en scopus y cinahl
Inmaculada Martín Varo
 
PPTX
3Com 68GFM
savomir
 
PPTX
Power point
Skudnyakov
 
PDF
La grande consultation des entrepreneurs / Vague mars 2017
contactOpinionWay
 
Is cloud computing right for your business
Tyrone Systems
 
Gudi Padwa 2017
Swati1223
 
Higiene y seguridad indusrtial
daniel acosta cubides
 
popular games in india
SHANTY E V E V
 
Apresentação Konnecta TI Consultoria
Gilberto Nunes
 
3Com 3C10318
savomir
 
Búsqueda en scopus y cinahl
Inmaculada Martín Varo
 
3Com 68GFM
savomir
 
Power point
Skudnyakov
 
La grande consultation des entrepreneurs / Vague mars 2017
contactOpinionWay
 

Similar to C++ Undefined Behavior (Code::Dive 2016) (20)

PDF
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
PPTX
COSCUP: Introduction to Julia
岳華 杜
 
PPTX
20170415 當julia遇上資料科學
岳華 杜
 
PPTX
20171127 當julia遇上資料科學
岳華 杜
 
PPT
Verilog hdl
Muhammad Uzair Rasheed
 
PDF
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Chris Ohk
 
PPT
Spock Framework
Леонид Ставила
 
PPTX
How to add an optimization for C# to RyuJIT
Egor Bogatov
 
PDF
Message in a bottle
Konstantin Haase
 
PPTX
Undefined Behaviour and Poison Values in LLVM
radcircles1059
 
PDF
Java Bytecodes by Example
Ganesh Samarthyam
 
PPTX
Introduction to julia
岳華 杜
 
PDF
Part II: LLVM Intermediate Representation
Wei-Ren Chen
 
PDF
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Gavin Guo
 
PDF
Automated reduction of attack surface using call graph enumeration
Ruo Ando
 
PDF
clegoues-pwlconf-sept16-asPDF.pdf
aoecmtin
 
PDF
Catch a spider monkey
ChengHui Weng
 
PDF
Exceptions and Exception Handling in C++
IRJET Journal
 
PDF
Davide Berardi - Linux hardening and security measures against Memory corruption
linuxlab_conf
 
PDF
Static Optimization of PHP bytecode (PHPSC 2017)
Nikita Popov
 
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
COSCUP: Introduction to Julia
岳華 杜
 
20170415 當julia遇上資料科學
岳華 杜
 
20171127 當julia遇上資料科學
岳華 杜
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Chris Ohk
 
How to add an optimization for C# to RyuJIT
Egor Bogatov
 
Message in a bottle
Konstantin Haase
 
Undefined Behaviour and Poison Values in LLVM
radcircles1059
 
Java Bytecodes by Example
Ganesh Samarthyam
 
Introduction to julia
岳華 杜
 
Part II: LLVM Intermediate Representation
Wei-Ren Chen
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Gavin Guo
 
Automated reduction of attack surface using call graph enumeration
Ruo Ando
 
clegoues-pwlconf-sept16-asPDF.pdf
aoecmtin
 
Catch a spider monkey
ChengHui Weng
 
Exceptions and Exception Handling in C++
IRJET Journal
 
Davide Berardi - Linux hardening and security measures against Memory corruption
linuxlab_conf
 
Static Optimization of PHP bytecode (PHPSC 2017)
Nikita Popov
 
Ad

More from Sławomir Zborowski (7)

PDF
What every C++ programmer should know about modern compilers (w/ comments, AC...
Sławomir Zborowski
 
PDF
What every C++ programmer should know about modern compilers (w/o comments, A...
Sławomir Zborowski
 
PDF
Algorithms for Cloud Computing
Sławomir Zborowski
 
PDF
More functional C++14
Sławomir Zborowski
 
PDF
Boost.Python - domesticating the snake
Sławomir Zborowski
 
PDF
Boost Multi Index
Sławomir Zborowski
 
PDF
How it's made: C++ compilers (GCC)
Sławomir Zborowski
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
Sławomir Zborowski
 
What every C++ programmer should know about modern compilers (w/o comments, A...
Sławomir Zborowski
 
Algorithms for Cloud Computing
Sławomir Zborowski
 
More functional C++14
Sławomir Zborowski
 
Boost.Python - domesticating the snake
Sławomir Zborowski
 
Boost Multi Index
Sławomir Zborowski
 
How it's made: C++ compilers (GCC)
Sławomir Zborowski
 
Ad

Recently uploaded (20)

PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
PPTX
site survey architecture student B.arch.
sri02032006
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PDF
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PDF
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
PPTX
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
EC3551-Transmission lines Demo class .pptx
Mahalakshmiprasannag
 
PPTX
Innowell Capability B0425 - Commercial Buildings.pptx
regobertroza
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
monopile foundation seminar topic for civil engineering students
Ahina5
 
PPTX
REINFORCEMENT AS CONSTRUCTION MATERIALS.pptx
mohaiminulhaquesami
 
PDF
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
site survey architecture student B.arch.
sri02032006
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
EC3551-Transmission lines Demo class .pptx
Mahalakshmiprasannag
 
Innowell Capability B0425 - Commercial Buildings.pptx
regobertroza
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
monopile foundation seminar topic for civil engineering students
Ahina5
 
REINFORCEMENT AS CONSTRUCTION MATERIALS.pptx
mohaiminulhaquesami
 
A presentation on the Urban Heat Island Effect
studyfor7hrs
 

C++ Undefined Behavior (Code::Dive 2016)