Reverse Engineering for Beginners
Dennis Yurichev
Reverse Engineering for Beginners
Dennis Yurichev
<dennis(a)yurichev.com>
cbnd
©2013-2015, Dennis Yurichev.
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported
License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-nd/3.0/.
Text version (April 14, 2015).
There is probably a newer version of this text, and Russian language version also accessible at
beginners.re. E-book reader version is also available on the page.
There are also shortened LITE-version (introductory), intended to those who wants very quick
introduction to reverse engineering basics: beginners.re
You may also subscribe to my twitter, to get information about updates of this text, etc: @yurichev
1
or to subscribe to mailing list
2
.
The cover was made by Andy Nechaevsky: facebook.
1twitter
2yurichev.com
ii
Please take a short survey!
Feedback is extremely important to the author!
http://beginners.re/survey.html.
i
SHORT CONTENTS SHORT CONTENTS
Short contents
I Code patterns 1
II Important fundamentals 450
III Slightly more advanced examples 458
IV Java 603
V Finding important/interesting stuff in the code 639
VI OS-specific 662
VII Tools 716
VIII More examples 722
IX Examples of reversing proprietary file formats 834
X Other things 865
XI Books/blogs worth reading 883
XII Exercises 887
Afterword 923
Appendix 925
Acronyms used 964
ii
CONTENTS CONTENTS
Contents
0.0.1 Donate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
I Code patterns 1
1 A short introduction to the CPU 3
1.1 A couple of words about different ISA3
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Simplest possible function 4
2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3.1 Note about MIPS instruction/register names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Hello, world! 6
3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.1.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.1.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.3 GCC: AT&T syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.1 MSVC—x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.2 GCC—x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 GCC—one more thing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4.1 Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4.2 Non-optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4.3 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4.4 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.4.5 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.5.1 Word about “global pointer” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.5.2 Optimizing GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.5.3 Non-optimizing GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.5.4 Role of the stack frame in this example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5.5 Optimizing GCC: load it into GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4 Function prologue and epilogue 21
4.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5 Stack 22
5.1 Why does the stack grow backwards? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.2 What is the stack used for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.2.1 Save the function’s return address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.2.2 Passing function arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.2.3 Local variable storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.2.4 x86: alloca() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.2.5 (Windows) SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.2.6 Buffer overflow protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.3 Typical stack layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3Instruction Set Architecture
iii
CONTENTS
5.4 Noise in stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.5.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6 printf() with several arguments 33
6.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.1.1 x86: 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.1.2 x64: 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2.1 ARM: 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2.2 ARM: 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
6.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.3.1 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.3.2 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
6.5 By the way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
7 scanf() 56
7.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.1.1 About pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.1.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.1.3 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
7.1.4 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
7.1.5 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7.1.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
7.2 Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.2.1 MSVC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.2.2 MSVC: x86 + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.2.3 GCC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.2.4 MSVC: x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.2.5 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2.6 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.2.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.3 scanf() result checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.3.1 MSVC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.3.2 MSVC: x86: IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.3.3 MSVC: x86 + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.3.4 MSVC: x86 + Hiew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.3.5 MSVC: x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.3.6 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.3.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.3.8 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8 Accessing passed arguments 86
8.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.1.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.1.2 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.1.3 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.2.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.2.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.2.3 GCC: uint64_t instead of int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.3 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
8.3.1 Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
8.3.2 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
8.3.3 Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.3.4 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
9 More about results returning 95
9.1 Attempt to use the result of a function returning void . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
9.2 What if we do not use the function result? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.3 Returning a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
iv
CONTENTS
10 Pointers 98
10.1 Global variables example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10.2 Local variables example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
10.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
11 GOTO 108
11.1 Dead code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
11.2 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
12 Conditional jumps 111
12.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
12.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
12.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
12.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
12.2 Calculating absolute value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.2.1 Optimizing MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
12.2.2 Optimizing Keil 6/2013: thumb mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.2.3 Optimizing Keil 6/2013: ARM mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.2.4 Non-optimizing GCC 4.9 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.2.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.2.6 Branchless version? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.3 Conditional operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
12.3.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
12.3.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
12.3.5 Let’s rewrite it in an if/else way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.3.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.3.7 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.4 Getting minimal and maximal values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.4.1 32-bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
12.4.2 64-bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
12.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
12.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.4 Branchless . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
13 switch()/case/default 139
13.1 Small number of cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
13.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
13.1.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.1.5 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
13.1.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
13.1.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.2 A lot of cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
13.2.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
13.2.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.2.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
13.3 When there are several case statements in one block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
13.3.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
13.3.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
13.3.3 ARM64: Optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
13.4 Fall-through . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
13.4.1 MSVC x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
13.4.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
13.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
13.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
v
CONTENTS
14 Loops 169
14.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
14.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
14.1.2 x86: OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.1.3 x86: tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
14.1.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
14.1.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
14.1.6 One more thing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
14.2 Memory blocks copying routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
14.2.1 Straight-forward implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
14.2.2 ARM in ARM mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
14.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.2.4 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.4.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.4.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.4.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
14.4.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
15 Simple C-strings processing 188
15.1 strlen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
15.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
15.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
15.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
15.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
15.2.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
16 Replacing arithmetic instructions to other ones 201
16.1 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16.1.1 Multiplication using addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16.1.2 Multiplication using shifting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
16.1.3 Multiplication using shifting/subtracting/adding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
16.2 Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
16.2.1 Division using shifts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
16.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
16.3.1 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
17 Floating-point unit 208
17.1 IEEE 754 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
17.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
17.3 ARM, MIPS, x86/x64 SIMD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
17.4 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
17.5 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
17.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
17.5.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
17.5.4 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
17.5.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
17.6 Passing floating point numbers via arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
17.6.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
17.6.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
17.7 Comparison example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
17.7.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
17.7.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
17.7.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
17.7.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
17.8 Stack, calculators and reverse Polish notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
17.9 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
17.10Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
17.10.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
vi
CONTENTS
17.10.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
18 Arrays 257
18.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
18.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
18.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
18.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
18.2 Buffer overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
18.2.1 Reading outside array bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
18.2.2 Writing beyond array bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
18.3 Buffer overflow protection methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
18.3.1 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
18.4 One more word about arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
18.5 Array of pointers to strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
18.5.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
18.5.2 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
18.5.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
18.5.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
18.5.5 Array overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
18.6 Multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
18.6.1 Two-dimensional array example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
18.6.2 Access two-dimensional array as one-dimensional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
18.6.3 Three-dimensional array example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
18.6.4 More examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
18.7 Pack of strings as a two-dimensional array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
18.7.1 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
18.7.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
18.7.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
18.7.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
18.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
18.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
18.9.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
18.9.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
18.9.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
18.9.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
18.9.5 Exercise #5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
19 Manipulating specific bit(s) 305
19.1 Specific bit checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
19.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
19.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
19.2 Specific bit setting/clearing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
19.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
19.2.3 ARM + Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
19.2.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
19.2.5 ARM: more about the BIC instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
19.2.6 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
19.2.8 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
19.3 Shifts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
19.4 Specific bit setting/clearing: FPU4
example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
19.4.1 A word about the XOR operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
19.4.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
19.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
19.4.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
19.5 Counting bits set to 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
19.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
19.5.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
19.5.5 ARM64 + Optimizing GCC 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
19.5.6 ARM64 + Non-optimizing GCC 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
4Floating-point unit
vii
CONTENTS
19.5.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
19.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
19.6.1 Check for specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
19.6.2 Check for specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
19.6.3 Set specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
19.6.4 Set specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
19.6.5 Clear specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
19.6.6 Clear specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
19.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
19.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
19.7.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
19.7.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
19.7.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
20 Linear congruential generator as pseudorandom number generator 344
20.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
20.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
20.3 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
20.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
20.4.1 MIPS relocations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
20.5 Thread-safe version of the example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
21 Structures 349
21.1 MSVC: SYSTEMTIME example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
21.1.1 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
21.1.2 Replacing the structure with array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
21.2 Let’s allocate space for a structure using malloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
21.3 UNIX: struct tm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
21.3.1 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
21.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
21.3.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
21.3.4 Structure as a set of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
21.3.5 Structure as an array of 32-bit words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
21.3.6 Structure as an array of bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
21.4 Fields packing in structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
21.4.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
21.4.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
21.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
21.4.4 One more word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
21.5 Nested structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
21.5.1 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
21.6 Bit fields in a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
21.6.1 CPUID example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
21.6.2 Working with the float type as with a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
21.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
21.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
21.7.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
22 Unions 384
22.1 Pseudo-random number generator example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
22.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
22.1.2 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
22.1.3 ARM (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
22.2 Calculating machine epsilon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
22.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
22.2.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
22.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
22.2.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
viii
CONTENTS
23 Pointers to functions 391
23.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
23.1.1 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
23.1.2 MSVC + tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
23.1.3 MSVC + tracer (code coverage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
23.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
23.2.1 GCC + GDB (with source code) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
23.2.2 GCC + GDB (no source code) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
24 64-bit values in 32-bit environment 403
24.1 Returning of 64-bit value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
24.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
24.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
24.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
24.2 Arguments passing, addition, subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
24.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
24.2.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
24.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
24.3 Multiplication, division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
24.3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
24.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
24.3.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
24.4 Shifting right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
24.4.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
24.4.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
24.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
24.5 Converting 32-bit value into 64-bit one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
24.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
24.5.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
24.5.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
25 SIMD 413
25.1 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
25.1.1 Addition example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
25.1.2 Memory copy example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
25.2 SIMD strlen() implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
26 64 bits 426
26.1 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
26.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
26.3 Float point numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
27 Working with floating point numbers using SIMD 434
27.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
27.1.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
27.1.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
27.2 Passing floating point number via arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
27.3 Comparison example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
27.3.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
27.3.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
27.4 Calculating machine epsilon: x64 and SIMD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
27.5 Pseudo-random number generator example revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
27.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
28 More about ARM 445
28.1 Number sign (#) before number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
28.2 Addressing modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
28.3 Loading a constant into a register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
28.3.1 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
28.3.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
28.4 Relocs in ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
29 More about MIPS 449
29.1 Loading constants into register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
29.2 Further reading about MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
ix
CONTENTS
II Important fundamentals 450
30 Signed number representations 451
31 Endianness 453
31.1 Big-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
31.2 Little-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
31.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
31.4 Bi-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
31.5 Converting data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
32 Memory 455
33 CPU 456
33.1 Branch predictors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
33.2 Data dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
34 Hash functions 457
34.1 How one-way function works? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
III Slightly more advanced examples 458
35 Temperature converting 459
35.1 Integer values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
35.1.1 Optimizing MSVC 2012 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
35.1.2 Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
35.2 Floating-point values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
36 Fibonacci numbers 464
36.1 Example #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
36.2 Example #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
36.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
37 CRC32 calculation example 471
38 Network address calculation example 474
38.1 calc_network_address() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
38.2 form_IP() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
38.3 print_as_IP() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
38.4 form_netmask() and set_bit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
38.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
39 Loops: several iterators 480
39.1 Three iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
39.2 Two iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
39.3 Intel C++ 2011 case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
40 Duff’s device 485
41 Division by 9 488
41.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
41.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
41.2.1 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
41.2.2 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
41.2.3 Non-optimizing Xcode 4.6.3 (LLVM) and Keil 6/2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
41.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
41.4 How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
41.5 Getting the divisor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
41.5.1 Variant #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
41.5.2 Variant #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
41.6 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
x
CONTENTS
42 String to number conversion (atoi()) 494
42.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
42.1.1 Optimizing MSVC 2013 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
42.1.2 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
42.1.3 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
42.1.4 Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
42.1.5 Optimizing GCC 4.9.1 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
42.2 A slightly advanced example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
42.2.1 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
42.2.2 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
43 Inline functions 500
43.1 Strings and memory functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
43.1.1 strcmp() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
43.1.2 strlen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
43.1.3 strcpy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
43.1.4 memset() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
43.1.5 memcpy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
43.1.6 memcmp() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
43.1.7 IDA script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
44 C99 restrict 509
45 Branchless abs() function 512
45.1 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
45.2 Optimizing GCC 4.9 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
46 Variadic functions 514
46.1 Computing arithmetic mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
46.1.1 cdecl calling conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
46.1.2 Register-based calling conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
46.2 vprintf() function case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
47 Strings trimming 519
47.1 x64: Optimizing MSVC 2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
47.2 x64: Non-optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
47.3 x64: Optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
47.4 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
47.5 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
47.6 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
47.7 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
47.8 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
48 toupper() function 528
48.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
48.1.1 Two comparison operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
48.1.2 One comparison operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
48.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
48.2.1 GCC for ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
48.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
49 Incorrectly disassembled code 532
49.1 Disassembling from an incorrect start (x86) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
49.2 How does random noise looks disassembled? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
50 Obfuscation 537
50.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
50.2 Executable code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
50.2.1 Inserting garbage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
50.2.2 Replacing instructions with bloated equivalents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
50.2.3 Always executed/never executed code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
50.2.4 Making a lot of mess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
50.2.5 Using indirect pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
50.3 Virtual machine / pseudo-code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
50.4 Other things to mention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
xi
CONTENTS
50.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
50.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
51 C++ 540
51.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
51.1.1 A simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
51.1.2 Class inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
51.1.3 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
51.1.4 Multiple inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
51.1.5 Virtual methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
51.2 ostream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
51.3 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
51.4 STL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
51.4.1 std::string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
51.4.2 std::list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
51.4.3 std::vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
51.4.4 std::map and std::set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
52 Negative array indices 589
53 Windows 16-bit 592
53.1 Example#1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
53.2 Example #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
53.3 Example #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
53.4 Example #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
53.5 Example #5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
53.6 Example #6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
53.6.1 Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
IV Java 603
54 Java 604
54.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
54.2 Returning a value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
54.3 Simple calculating functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
54.4 JVM5
memory model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
54.5 Simple function calling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
54.6 Calling beep() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
54.7 Linear congruential PRNG6
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
54.8 Conditional jumps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
54.9 Passing arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
54.10Bitfields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
54.11Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
54.12switch() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
54.13Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
54.13.1Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
54.13.2Summing elements of array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
54.13.3main() function sole argument is array too . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
54.13.4Pre-initialized array of strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
54.13.5Variadic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
54.13.6Two-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
54.13.7Three-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
54.13.8Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
54.14Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
54.14.1First example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
54.14.2Second example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
54.15Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
54.16Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
54.17Simple patching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
54.17.1 First example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
54.17.2 Second example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
54.18Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
5Java virtual machine
6Pseudorandom number generator
xii
CONTENTS
V Finding important/interesting stuff in the code 639
55 Identification of executable files 641
55.1 Microsoft Visual C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.1.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.2.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.2.2 Cygwin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.2.3 MinGW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.3 Intel FORTRAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
55.4 Watcom, OpenWatcom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
55.4.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
55.5 Borland . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
55.5.1 Delphi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
55.6 Other known DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
56 Communication with the outer world (win32) 644
56.1 Often used functions in the Windows API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
56.2 tracer: Intercepting all functions in specific module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
57 Strings 646
57.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
57.1.1 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
57.1.2 Borland Delphi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
57.1.3 Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
57.1.4 Base64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
57.2 Error/debug messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
57.3 Suspicious magic strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
58 Calls to assert() 651
59 Constants 652
59.1 Magic numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
59.1.1 DHCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
59.2 Searching for constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
60 Finding the right instructions 654
61 Suspicious code patterns 656
61.1 XOR instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
61.2 Hand-written assembly code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
62 Using magic numbers while tracing 658
63 Other things 659
63.1 General idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
63.2 C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
63.3 Some binary file patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
63.4 Memory “snapshots” comparing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
63.4.1 Windows registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
63.4.2 Blink-comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
VI OS-specific 662
64 Arguments passing methods (calling conventions) 663
64.1 cdecl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
64.2 stdcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
64.2.1 Functions with variable number of arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
64.3 fastcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
64.3.1 GCC regparm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
64.3.2 Watcom/OpenWatcom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
64.4 thiscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
64.5 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
64.5.1 Windows x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
64.5.2 Linux x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
xiii
CONTENTS
64.6 Return values of float and double type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
64.7 Modifying arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
64.8 Taking a pointer to function argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
65 Thread Local Storage 671
65.1 Linear congruential generator revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
65.1.1 Win32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
65.1.2 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
66 System calls (syscall-s) 676
66.1 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
66.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
67 Linux 678
67.1 Position-independent code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
67.1.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
67.2 LD_PRELOAD hack in Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
68 Windows NT 683
68.1 CRT (win32) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
68.2 Win32 PE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
68.2.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
68.2.2 Base address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
68.2.3 Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
68.2.4 OS version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
68.2.5 Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
68.2.6 Relocations (relocs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
68.2.7 Exports and imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
68.2.8 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
68.2.9 .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
68.2.10TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
68.2.11Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
68.2.12Further reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
68.3 Windows SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
68.3.1 Let’s forget about MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
68.3.2 Now let’s get back to MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
68.3.3 Windows x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
68.3.4 Read more about SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
68.4 Windows NT: Critical section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
VII Tools 716
69 Disassembler 717
69.1 IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
70 Debugger 718
70.1 tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
70.2 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
70.3 GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
71 System calls tracing 719
71.0.1 strace / dtruss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
72 Decompilers 720
73 Other tools 721
VIII More examples 722
74 Task manager practical joke (Windows Vista) 723
74.1 Using LEA to load values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
75 Color Lines game practical joke 727
xiv
CONTENTS
76 Minesweeper (Windows XP) 731
76.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
77 Hand decompiling + Z3 SMT solver 736
77.1 Hand decompiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
77.2 Now let’s use the Z3 SMT solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
78 Dongles 744
78.1 Example #1: MacOS Classic and PowerPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
78.2 Example #2: SCO OpenServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
78.2.1 Decrypting error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
78.3 Example #3: MS-DOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
79 “QR9”: Rubik’s cube inspired amateur crypto-algorithm 765
80 SAP 792
80.1 About SAP client network traffic compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
80.2 SAP 6.0 password checking functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
81 Oracle RDBMS 806
81.1 V$VERSION table in the Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
81.2 X$KSMLRU table in Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
81.3 V$TIMER table in Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
82 Handwritten assembly code 819
82.1 EICAR test file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
83 Demos 821
83.1 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
83.1.1 Trixter’s 42 byte version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
83.1.2 My attempt to reduce Trixter’s version: 27 bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
83.1.3 Taking random memory garbage as a source of randomness . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
83.1.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
83.2 Mandelbrot set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
83.2.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
83.2.2 Let’s get back to the demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830
83.2.3 My “fixed” version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
IX Examples of reversing proprietary file formats 834
84 Primitive XOR-encryption 835
84.1 Norton Guide: simplest possible 1-byte XOR encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
84.1.1 Entropy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
84.2 Simplest possible 4-byte XOR encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
84.2.1 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842
85 Millenium game save file 843
86 Oracle RDBMS: .SYM-files 850
87 Oracle RDBMS: .MSB-files 859
87.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
X Other things 865
88 npad 866
89 Executable files patching 868
89.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
89.2 x86 code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
90 Compiler intrinsic 869
91 Compiler’s anomalies 870
xv
CONTENTS
92 OpenMP 871
92.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 872
92.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
93 Itanium 877
94 8086 memory model 880
95 Basic blocks reordering 881
95.1 Profile-guided optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
XI Books/blogs worth reading 883
96 Books 884
96.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
96.2 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
96.3 x86 / x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
96.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
96.5 Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
97 Blogs 885
97.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
98 Other 886
XII Exercises 887
99 Level 1 889
99.1 Exercise 1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889
100Level 2 890
100.1Exercise 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
100.1.1Optimizing MSVC 2010 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
100.1.2Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
100.2Exercise 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
100.2.1Optimizing MSVC 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
100.2.2GCC 4.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892
100.2.3Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893
100.2.4Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
100.2.5Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
100.2.6Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
100.3Exercise 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
100.3.1Optimizing MSVC 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
100.3.2Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
100.3.3Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
100.3.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898
100.3.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
100.4Exercise 2.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
100.4.1Optimizing MSVC 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
100.4.2Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
100.4.3Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
100.4.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
100.4.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
100.5Exercise 2.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
100.5.1MSVC 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901
100.5.2Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901
100.5.3GCC 4.6.3 for Raspberry Pi (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902
100.5.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
100.5.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
100.6Exercise 2.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
100.6.1Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
100.6.2Optimizing GCC 4.4.6 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907
100.6.3Optimizing GCC 4.8.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
100.6.4Keil (ARM mode): Cortex-R4F CPU as target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909
xvi
CONTENTS
100.6.5Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
100.6.6Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
100.7Exercise 2.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912
100.7.1 Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912
100.7.2 Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
100.7.3 Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
100.7.4 Non-optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
100.7.5 Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
100.7.6 Non-optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916
100.8Exercise 2.17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
100.9Exercise 2.18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
100.10Exercise 2.19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
100.11Exercise 2.20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
101Level 3 919
101.1Exercise 3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
101.2Exercise 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
101.3Exercise 3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
101.4Exercise 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
101.5Exercise 3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
101.6Exercise 3.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
102crackme / keygenme 921
Afterword 923
103Questions? 923
Appendix 925
A x86 925
A.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
A.2 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
A.2.1 RAX/EAX/AX/AL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
A.2.2 RBX/EBX/BX/BL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
A.2.3 RCX/ECX/CX/CL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.4 RDX/EDX/DX/DL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.5 RSI/ESI/SI/SIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.6 RDI/EDI/DI/DIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.7 R8/R8D/R8W/R8L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.8 R9/R9D/R9W/R9L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.9 R10/R10D/R10W/R10L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
A.2.10 R11/R11D/R11W/R11L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.11 R12/R12D/R12W/R12L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.12 R13/R13D/R13W/R13L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.13 R14/R14D/R14W/R14L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.14 R15/R15D/R15W/R15L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.15 RSP/ESP/SP/SPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.16 RBP/EBP/BP/BPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
A.2.17 RIP/EIP/IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
A.2.18 CS/DS/ES/SS/FS/GS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
A.2.19 Flags register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
A.3 FPU registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
A.3.1 Control Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
A.3.2 Status Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
A.3.3 Tag Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.4 SIMD registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.4.1 MMX registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.4.2 SSE and AVX registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.5 Debugging registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.5.1 DR6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
A.5.2 DR7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
A.6 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
xvii
CONTENTS
A.6.1 Prefixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
A.6.2 Most frequently used instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932
A.6.3 Less frequently used instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936
A.6.4 FPU instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940
A.6.5 Instructions having printable ASCII opcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941
B ARM 944
B.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
B.2 Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
B.3 32-bit ARM (AArch32) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
B.3.1 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944
B.3.2 Current Program Status Register (CPSR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945
B.3.3 VFP (floating point) and NEON registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945
B.4 64-bit ARM (AArch64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945
B.4.1 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945
B.5 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
B.5.1 Conditional codes table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
C MIPS 947
C.1 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
C.1.1 General purpose registers GPR7
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
C.1.2 Floating-point registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
C.2 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
C.2.1 Jump instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948
D Some GCC library functions 949
E Some MSVC library functions 950
F Cheatsheets 951
F.1 IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951
F.2 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951
F.3 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
F.4 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
F.5 GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
G Exercise solutions 954
G.1 Per chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.1 “Stack” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.2 “switch()/case/default” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.3 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.4 “Loops” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.5 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
G.1.6 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
G.1.7 “Simple C-strings processing” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
G.1.8 “Replacing arithmetic instructions to other ones” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
G.1.9 “Floating-point unit” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
G.1.10 “Arrays” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
G.1.11 “Manipulating specific bit(s)” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956
G.1.12 “Structures” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
G.1.13 “Obfuscation” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.1.14 “Division by 9” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.2 Level 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.2.1 Exercise 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.2.2 Exercise 1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.3 Level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.3.1 Exercise 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.3.2 Exercise 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
G.3.3 Exercise 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
G.3.4 Exercise 2.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
G.3.5 Exercise 2.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
G.3.6 Exercise 2.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
G.3.7 Exercise 2.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
G.3.8 Exercise 2.17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
7General Purpose Registers
xviii
CONTENTS
G.3.9 Exercise 2.18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.3.10 Exercise 2.19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.3.11 Exercise 2.20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4 Level 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.1 Exercise 3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.2 Exercise 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.3 Exercise 3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.4 Exercise 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.5 Exercise 3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.4.6 Exercise 3.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
G.5 Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
G.5.1 “Minesweeper (Windows XP)” example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
Acronyms used 964
Glossary 968
Index 970
xix
CONTENTS
Preface
There are several popular meanings of the term “reverse engineering”: 1) reverse engineering of software: researching
compiled programs; 2) 3D model scanning and reworking in order to make a copy of it; 3) recreating DBMS8
structure. This
book is related to the first meaning.
Topics discussed
x86/x64, ARM/ARM64, MIPS, Java/JVM.
Topics touched
Oracle RDBMS ( 81 on page 806), Itanium ( 93 on page 877), copy-protection dongles ( 78 on page 744), LD_PRELOAD ( 67.2
on page 680), stack overflow, ELF9
, win32 PE file format ( 68.2 on page 686), x86-64 ( 26.1 on page 426), critical sections
( 68.4 on page 714), syscalls ( 66 on page 676), TLS10
, position-independent code (PIC11
) ( 67.1 on page 678), profile-guided
optimization ( 95.1 on page 881), C++ STL ( 51.4 on page 556), OpenMP ( 92 on page 871), SEH ( 68.3 on page 692).
About the author
Dennis Yurichev is an experienced reverse engineer and programmer. He can be
contacted by email: dennis(a)yurichev.com, or Skype: dennis.yurichev.
Thanks
For patiently answering all my questions: Andrey “herm1t” Baranovich, Slava ”Avid” Kazakov.
For sending me notes about mistakes and inaccuracies: Stanislav ”Beaver” Bobrytskyy, Alexander Lysenko, Shell Rocket,
Zhu Ruijin, Changmin Heo.
For helping me in other ways: Andrew Zubinski, Arnaud Patard (rtp on #debian-arm IRC).
For translating to Chinese simplified: Xian Chi.
For translating to Korean: Byungho Min.
For proofreading: Alexander ”Lstar” Chernenkiy, Vladimir Botov, Andrei Brazhuk, Mark “Logxen” Cooper, Yuan Jochen Kang,
Mal Malakov.
Vasil Kolev did a great amount of work in proofreading and correcting many mistakes.
For illustrations and cover art: Andy Nechaevsky.
Thanks also to all the folks on github.com who have contributed notes and corrections.
Many LATEX packages were used: I would like to thank the authors as well.
0.0.1 Donate
As it turns out, (technical) writing takes a lot of effort and work.
This book is free, available freely and available in source code form 12
(LaTeX), and it will stay so forever.
It is also ad-free.
My current plan for this book is to add lots of information about: PLANS13
.
If you want me to continue writing on all these topics, you may consider donating.
Ways to donate are available on the page: beginners.re.
Every donor’s name will be included in the book! Donors also have a right to ask me to rearrange items in my writing
plan.
8Database management systems
9Executable file format widely used in *NIX system including Linux
10Thread Local Storage
11Position Independent Code: 67.1 on page 678
12GitHub
13GitHub
xx
CONTENTS
Donors
23 * anonymous, 2 * Oleg Vygovsky (50+100 UAH), Daniel Bilar ($50), James Truscott ($4.5), Luis Rocha ($63), Joris van de
Vis ($127), Richard S Shultz ($20), Jang Minchang ($20), Shade Atlas (5 AUD), Yao Xiao ($10), Pawel Szczur (40 CHF), Justin
Simms ($20), Shawn the R0ck ($27), Ki Chan Ahn ($50), Triop AB (100 SEK), Ange Albertini (10+50 EUR), Sergey Lukianov
(300 RUR), Ludvig Gislason (200 SEK), Gérard Labadie (40 EUR), Sergey Volchkov (10 AUD), Vankayala Vigneswararao ($50),
Philippe Teuwen ($4), Martin Haeberli ($10), Victor Cazacov (5 EUR), Tobias Sturzenegger (10 CHF), Sonny Thai ($15), Bayna
AlZaabi ($75), Redfive B.V. (25 EUR), Joona Oskari Heikkilä (5 EUR), Marshall Bishop ($50), Nicolas Werner (12 EUR), Jeremy
Brown ($100), Alexandre Borges ($25), Vladimir Dikovski (50 EUR), Jiarui Hong (100.00 SEK), Jim_Di (500 RUR), Tan Vincent
($30), Sri Harsha Kandrakota (10 AUD), Pillay Harish (10 SGD), Timur Valiev (230 RUR), Carlos Garcia Prado (10 EUR), Salikov
Alexander (500 RUR), Oliver Whitehouse (30 GBP), Katy Moe ($14), Maxim Dyakonov ($3).
mini-FAQ
Q: Why one should learn assembly language these days?
A: Unless you are OS developer, you probably don’t need to write in assembly: modern compilers perform optimizations
much better than humans do. 14
. Also, modern CPU15
s are very complex devices and assembly knowledge would not help
you understand its internals. That said, there are at least two areas where a good understanding of assembly may help:
first, security/malware research. Second, gaining a better understanding of your compiled code while debugging. Therefore,
this book is intended for those who want to understand assembly language rather than to write in it, which is why there are
many examples of compiler output.
Q: I clicked on hyperlink inside of PDF-document, how to get back?
A: (Adobe Acrobat Reader) Alt + LeftArrow
Q: Your book is so huge! Is there anything shorter?
A: There is shortened lite version: http://beginners.re/#lite.
Q: May I print this book? Use it for teaching?
A: Of course, that’s why book is licensed under Creative Commons terms. Someone may also want to build their own version
of book, read here about it.
Q: I want to translate your book to some other language.
A: Read my note to translators.
Q: How would one find a reverse engineering job?
A: There are hiring threads that appear from time to time on reddit devoted to RE16
(2013 Q3, 2014). Try looking there. A
somewhat related hiring thread can be found in the “netsec” subreddit: 2014 Q2.
Q: I have a question...
A: Write me it by email (dennis(a)yurichev.com) or ask your question at my forum: forum.yurichev.com.
Praise for Reverse Engineering for Beginners
• “It’s very well done .. and for free .. amazing.”17
Daniel Bilar, Siege Technologies, LLC.
• “...excellent and free”18
Pete Finnigan, Oracle RDBMS security guru.
• “... book is interesting, great job!” Michael Sikorski, author of Practical Malware Analysis: The Hands-On Guide to
Dissecting Malicious Software.
• “... my compliments for the very nice tutorial!” Herbert Bos, full professor at the Vrije Universiteit Amsterdam, co-author
of Modern Operating Systems (4th Edition).
• “... It is amazing and unbelievable.” Luis Rocha, CISSP / ISSAP, Technical Manager, Network & Information Security at
Verizon Business.
• “Thanks for the great work and your book.” Joris van de Vis, SAP Netweaver & Security specialist.
• “... reasonable intro to some of the techniques.”19
(Mike Stay, teacher at the Federal Law Enforcement Training Center,
Georgia, US.)
14A very good text about this topic: [Fog13b]
15Central processing unit
16reddit
17twitter
18twitter
19reddit
xxi
CONTENTS
• “I love this book! I have several students reading it at the moment, plan to use it in graduate course.”20
(Sergey Bratus,
Research Assistant Professor at the Computer Science Department at Dartmouth College)
• “Dennis @Yurichev has published an impressive (and free!) book on reverse engineering”21
Tanel Poder, Oracle RDBMS
performance tuning expert.
About Korean translation
In January 2015, Acorn publishing company (www.acornpub.co.kr) in South Korea did huge amount of work in translating and
publishing my book (state which is it in August 2014) in Korean language.
Now it’s available at their website.
Translator is Byungho Min (twitter/tais9).
Cover pictures was done by my artist friend Andy Nechaevsky : facebook/andydinka.
They are also the Korean translation copyright holder.
So if you want to have a real book on your shelf in Korean language and/or want to support my work, now you may buy
it.
20twitter
21twitter
xxii
Part I
Code patterns
1
When I first started learning C and then C++, I used to write small pieces of code, compile them, and look at the assembly
language output. This was much easy for me to understand 22
. I did it so many times that the relation between the C/C++
code and what the compiler produced was imprinted deeply in my mind. That is why when I look at assembly code I could
instantly grasp what the original C code in general does and looks like. Perhaps this technique could be helpful for someone
else and so I’m going to describe some examples here.
Sometimes I use ancient compilers, in order to get the shortest (or simplest) possible code snippet.
Exercises
When I studied assembly language, I also often compiled small C-functions and then rewrote them gradually to assembly,
trying to make their code as short as possible. This probably is not worth doing today in real-world scenarios (because it’s
hard to compete with modern compilers on efficiency), but it’s a very good method to learn assembly better. Therefore, you
can take any assembly code from this book and try to make it shorter. However, please also do not forget about testing your
results!
Difference between non-optimized (debug) and optimized (release) versions
A non-optimizing compiler works faster and produces more understandable (verbose, though) code.
An optimizing (release) compiler works slower and tries to produce faster (but not necessarily smaller) code.
One important feature of the debugging code is that there might be debugging information showing connections between
each line in source code and machine code addresses. Optimizing compilers tend to produce such output where whole source
code lines may be optimized away and not present in the resulting machine code.
Reverse engineer practitioner usually encounters either version because some developers turn on compiler’s optimization
switches and others do not.
That’s why I try to give examples of both versions of code.
22Frankly speaking, I still do so when I can’t understand what some code does.
2
CHAPTER 1. A SHORT INTRODUCTION TO THE CPU
Chapter 1
A short introduction to the CPU
The CPU is the unit, which executes all of the programs.
Short glossary:
Instruction : a primitive CPU command. Simplest examples: moving data between registers, working with memory, arith-
metic primitives. As a rule, each CPU has its own instruction set architecture (ISA).
Machine code : code for the CPU. Each instruction is usually encoded by several bytes.
Assembly language : mnemonic code and some extensions like macros which are intended to make a programmer’s life
easier.
CPU register : Each CPU has a fixed set of general purpose registers (GPR). ≈ 8 in x86, ≈ 16 in x86-64, ≈ 16 in ARM. The
easiest way to understand a register is to think of it as an untyped temporary variable. Imagine you are working with
a high-level PL1
and you have only 8 32-bit (or 64-bit) variables. Many things can be done using only these!
What is the difference between machine code and a PL? It is much easier for humans to use a high-level PL like C/C++,
Java, Python, etc., but it is easier for a CPU to use a much lower level of abstraction. Perhaps, it would be possible to invent a
CPU which can execute high-level PL code, but it would be much more complex. On the contrary, it is very inconvenient for
humans to use assembly language due to it being low-level. Besides, it is very hard to do it without making a huge amount
of annoying mistakes. The program, which converts high-level PL code into assembly, is called a compiler.
1.1 A couple of words about different ISA
x86 was always an ISA with variable-length opcodes, so when the 64-bit era came, the x64 extensions did not affect the ISA
very much. x86 has a lot of instructions that appeared in 16-bit 8086 CPU and are still present in latest CPUs.
ARM is a RISC2
CPU designed with constant opcode length in mind, which had some advantages in the past. At
the very beginning, ARM had all instructions encoded in 4 bytes 3
. This is now referred as “ARM mode”.
Then they thought it wasn’t very frugal. In fact, most used CPU instructions4
in real world applications can be encoded
using less information. So they added another ISA called Thumb, where each instruction was encoded in just 2 bytes. This
is now referred as “Thumb mode”. However, not all ARM instructions can be encoded in just 2 bytes, so Thumb instruction
set is somewhat limited. Code compiled for ARM mode and Thumb mode may coexist in one program, of course.
Then ARM creators thought Thumb could be extended: Thumb-2 appeared (in ARMv7). Thumb-2 is still 2-byte instruc-
tions, but some new instructions have a size of 4 bytes. There is a common misconception that Thumb-2 is a mix of ARM and
Thumb. This is incorrect. Rather, Thumb-2 was extended to fully support all processor features so it could compete with ARM
mode. On instruction set richness, Thumb-2 now competes with the original ARM mode. The majority of iPod/iPhone/iPad
applications are compiled for the Thumb-2 instruction set because Xcode does this by default.
Later the 64-bit ARM came out. This ISA has 4-byte opcodes again, without any additional Thumb mode. But the 64-
bit requirements affected ISA, so, summarizing, we now have 3 ARM instruction sets: ARM mode, Thumb mode (including
Thumb-2) and ARM64. These ISAs intersect partially, but I would rather say they are different ISAs than variations of the
same one. Therefore, I try to add fragments of code in all 3 ARM ISAs in this book.
There are many other RISC ISAs with fixed length 32-bit opcodes, for example MIPS, PowerPC and Alpha AXP.
1Programming language
2Reduced instruction set computing
3By the way, fixed-length instructions are handy in a way that one can calculate the next (or previous) instruction’s address without effort. This feature
will be discussed in switch() ( 13.2.2 on page 158) section.
4These are MOV/PUSH/CALL/Jcc
3
CHAPTER 2. SIMPLEST POSSIBLE FUNCTION
Chapter 2
Simplest possible function
Probably the simplest possible function is that one which just returns some constant value.
Here it is:
int f()
{
return 123;
};
2.1 x86
And that’s what the optimizing GCC compiler produces:
Listing 2.1: Optimizing GCC
f:
mov eax, 123
ret
MSVC’s result is exactly the same.
There are just two instructions: the first places the value 123 into the EAX register, which is used by convention for
storing the return value and the second one is RET, which returns execution to the caller. The caller will take the result
from the EAX register.
2.2 ARM
What about ARM?
Listing 2.2: Optimizing Keil 6/2013 (ARM mode)
f PROC
MOV r0,#0x7b ; 123
BX lr
ENDP
ARM uses register R0 for returning results, so 123 is stored into R0 here.
The return address (RA1
) is not saved on the local stack in ARM, but rather in the LR2
register. So the BX LR instruction
is jumping to that address, effectively, returning execution to the caller.
It has to be noted that MOV is a confusing name for the instruction in both x86 and ARM ISAs. In fact, data is not moved,
it’s rather copied.
2.3 MIPS
There are two ways of registers naming that are used in the MIPS world. By number (from $0 to $31) or by pseudoname
($V0, $A0, etc). Assembly listing generated by GCC shows registers by number:
Listing 2.3: Optimizing GCC 4.4.5 (assembly output)
j $31
li $2,123 # 0x7b
1Return Address
2Link Register
4
CHAPTER 2. SIMPLEST POSSIBLE FUNCTION 2.3. MIPS
…while IDA3
— by pseudoname:
Listing 2.4: Optimizing GCC 4.4.5 (IDA)
jr $ra
li $v0, 0x7B
So the $2 (or $V0) register is used to store the function result. LI is “Load Immediate”.
The other instruction is jump instruction (J or JR) which returns execution flow to the caller, jumping to the address in
$31 (or $RA) register. This is the register analogous to LR in ARM.
But why the load instruction (LI) and the jump instruction (J or JR) are swapped? This is merely RISC feature called “branch
delay slot”. We don’t need to get into details here. We just need to remember that: in MIPS, the instruction following jump
or branch instruction is executed before the jump/brunch instruction itslef. Hence, branch instruction always swap place
with the instruction, which must be executed beforehand.
2.3.1 Note about MIPS instruction/register names
Register names and instruction names in MIPS world are traditionally written in lowercase. But I’ve decided to stick to
uppercase, because the instruction and register names of other ISAs are all written in uppercase in this book.
3Interactive Disassembler and debugger developed by Hex-Rays
5
CHAPTER 3. HELLO, WORLD!
Chapter 3
Hello, world!
Let’s continue with the famous example from the “The C programming Language”[Ker88] book:
#include <stdio.h>
int main()
{
printf("hello, worldn");
return 0;
}
3.1 x86
3.1.1 MSVC
Let’s compile it in MSVC 2010:
cl 1.cpp /Fa1.asm
(/Fa option instructs the compiler to generate assembly listing file)
Listing 3.1: MSVC 2010
CONST SEGMENT
$SG3830 DB 'hello, world', 0AH, 00H
CONST ENDS
PUBLIC _main
EXTRN _printf:PROC
; Function compile flags: /Odtp
_TEXT SEGMENT
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG3830
call _printf
add esp, 4
xor eax, eax
pop ebp
ret 0
_main ENDP
_TEXT ENDS
MSVC produces assembly listings in Intel-syntax. The difference between Intel-syntax and AT&T-syntax will be discussed
in 3.1.3 on the next page.
The compiler generated 1.obj file, which is to be linked into 1.exe.
In our case, the file contains two segments: CONST (for data constants) and _TEXT (for code).
The string ``hello, world'' in C/C++ has type const char[] [Str13, p176, 7.3.2], however it does not have its
own name.
The compiler needs to deal with the string somehow so it defines the internal name $SG3830 for it.
That is why the example may be rewritten as follows:
#include <stdio.h>
const char $SG3830[]="hello, worldn";
6
CHAPTER 3. HELLO, WORLD! 3.1. X86
int main()
{
printf($SG3830);
return 0;
}
Let’s go back to the assembly listing. As we can see, the string is terminated by a zero byte, which is standard for C/C++
strings. More about C strings: 57.1.1 on page 646.
In the code segment, _TEXT, there is only one function so far: main().
The function main() starts with prologue code and ends with epilogue code (like almost any function) 1
.
After the function prologue we see the call to the printf() function: CALL _printf.
Before the call the string address (or a pointer to it) containing our greeting is placed on the stack with the help of the
PUSH instruction.
When the printf() function returns the control to the main() function, the string address (or a pointer to it) is still
on the stack.
Since we do not need it anymore, the stack pointer (the ESP register) needs to be corrected.
ADD ESP, 4 means add 4 to the ESP register value.
Why 4? Since this is 32-bit program, we need exactly 4 bytes for address passing through the stack. If it was x64 code
we would need 8 bytes.
``ADD ESP, 4'' is effectively equivalent to ``POP register'' but without using any register2
.
Some compilers (like the Intel C++ Compiler) in the same situation may emit POP ECX instead of ADD (e.g., such a pattern
can be observed in the Oracle RDBMS code as it is compiled with the Intel C++ compiler). This instruction has almost the
same effect but the ECX register contents will be overwritten. The Intel C++ compiler probably uses POP ECX since this
instruction’s opcode is shorter than ADD ESP, x (1 byte against 3).
Here is an example:
Listing 3.2: Oracle RDBMS 10.2 Linux (app.o file)
.text:0800029A push ebx
.text:0800029B call qksfroChild
.text:080002A0 pop ecx
Read more about the stack in section ( 5 on page 22).
After calling printf(), the original C/C++ code contains the statement return 0 —return 0 as the result of the main()
function.
In the generated code this is implemented by the instruction XOR EAX, EAX
XOR is in fact just “eXclusive OR” 3
but the compilers often use it instead of MOV EAX, 0 —again because it is a slightly
shorter opcode (2 bytes against 5).
Some compilers emit SUB EAX, EAX, which means SUBtract the value in the EAX from the value in EAX, which in any
case resulting in zero.
The last instruction RET returns the control to the caller. Usually, this is C/C++ CRT4
code, which in its turn returns the
control to the OS5
.
3.1.2 GCC
Now let’s try to compile the same C/C++ code in the GCC 4.4.1 compiler in Linux: gcc 1.c -o 1
Next, with the assistance of the IDA disassembler, let’s see how the main() function was created.
(IDA, like MSVC, uses Intel-syntax) 6
.
Listing 3.3: code in IDA
main proc near
var_10 = dword ptr -10h
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
mov eax, offset aHelloWorld ; "hello, worldn"
mov [esp+10h+var_10], eax
1You can read more about it in section about function prolog and epilog ( 4 on page 21).
2CPU flags, however, are modified
3wikipedia
4C runtime library : 68.1 on page 683
5Operating System
6N.B. We could also have GCC produce assembly listings in Intel-syntax by applying the options -S -masm=intel.
7
CHAPTER 3. HELLO, WORLD! 3.1. X86
call _printf
mov eax, 0
leave
retn
main endp
The result is almost the same. The address of the “hello, world” string (stored in the data segment) is loaded in the EAX
register first and then it is saved onto the stack. In addition, the function prologue contains AND ESP, 0FFFFFFF0h —this
instruction aligns the ESP register value on a 16-byte boundary. This results in all values in the stack being aligned the
same way (The CPU performs better if the values it is dealing with are located in memory at addresses aligned on a 4- or
16-byte boundary)7
.
SUB ESP, 10h allocates 16 bytes on the stack. Although, as we can see hereafter, only 4 are necessary here.
This is because the size of the allocated stack is also aligned on a 16-byte boundary.
The string address (or a pointer to the string) is then stored directly onto the stack without using the PUSH instruction.
var_10 —is a local variable and is also an argument for printf(). Read about it below.
Then the printf() function is called.
Unlike MSVC, when GCC is compiling without optimization turned on, it emits MOV EAX, 0 instead of a shorter opcode.
The last instruction, LEAVE —is the equivalent of the MOV ESP, EBP and POP EBP instruction pair —in other words,
this instruction sets the stack pointer (ESP) back and restores the EBP register to its initial state.
This is necessary since we modified these register values (ESP and EBP) at the beginning of the function (executing MOV
EBP, ESP / AND ESP, ...).
3.1.3 GCC: AT&T syntax
Let’s see how this can be represented in assembly language AT&T syntax. This syntax is much more popular in the UNIX-
world.
Listing 3.4: let’s compile in GCC 4.7.3
gcc -S 1_1.c
We get this:
Listing 3.5: GCC 4.7.3
.file "1_1.c"
.section .rodata
.LC0:
.string "hello, worldn"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $16, %esp
movl $.LC0, (%esp)
call printf
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3"
.section .note.GNU-stack,"",@progbits
The listing contains many macros (beginning with dot). These are not interesting for us at the moment. For now, for
the sake of simplification, we can ignore them (except the .string macro which encodes a null-terminated character sequence
just like a C-string). Then we’ll see this
7Wikipedia: Data structure alignment
8
CHAPTER 3. HELLO, WORLD! 3.2. X86-64
8
:
Listing 3.6: GCC 4.7.3
.LC0:
.string "hello, worldn"
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl $.LC0, (%esp)
call printf
movl $0, %eax
leave
ret
Some of the major differences between Intel and AT&T syntax are:
• Source and destination operands are written in opposite order.
In Intel-syntax: <instruction> <destination operand> <source operand>.
In AT&T syntax: <instruction> <source operand> <destination operand>.
Here is a way to easy memorise the difference: when you deal with Intel-syntax, you can imagine that there is an
equality sign (=) between operands and when you deal with AT&T-syntax imagine there is a right arrow (→) 9
.
• AT&T: Before register names, a percent sign must be written (%) and before numbers a dollar sign ($). Parentheses
are used instead of brackets.
• AT&T: Suffix is added to instructions to define the operand size:
– q — quad (64 bits)
– l — long (32 bits)
– w — word (16 bits)
– b — byte (8 bits)
Let’s go back to the compiled result: it is identical to what we saw in IDA. With one subtle difference: 0FFFFFFF0h is
presented as $-16. It is the same thing: 16 in the decimal system is 0x10 in hexadecimal. -0x10 is equal to 0xFFFFFFF0
(for a 32-bit data type).
One more thing: the return value is to be set to 0 by using usual MOV, not XOR. MOV just loads value to a register. Its
name is misnomer (data is not moved but rather copied). In other architectures, this instruction is named “LOAD” and/or
“STORE” or something similar.
3.2 x86-64
3.2.1 MSVC—x86-64
Let’s also try 64-bit MSVC:
Listing 3.7: MSVC 2012 x64
$SG2989 DB 'hello, world', 0AH, 00H
main PROC
sub rsp, 40
lea rcx, OFFSET FLAT:$SG2989
call printf
xor eax, eax
add rsp, 40
ret 0
main ENDP
8This GCC option can be used to eliminate “unnecessary” macros: -fno-asynchronous-unwind-tables
9 By the way, in some C standard functions (e.g., memcpy(), strcpy()) the arguments are listed in the same way as in Intel-syntax: pointer to the destination
memory block at the beginning and then pointer to the source memory block.
9
CHAPTER 3. HELLO, WORLD! 3.2. X86-64
In x86-64, all registers were extended to 64-bit and now their names have an R- prefix. In order to use the stack less
often (in other words, to access external memory/cache less often), there exists a popular way to pass function arguments
via registers (fastcall : 64.3 on page 664 ). I.e., a part of the function arguments are passed in registers, the rest—via the
stack. In Win64, 4 function arguments are passed in RCX, RDX, R8, R9 registers. That is what we see here: a pointer to the
string for printf() is now passed not in stack, but in the RCX register.
The pointers are 64-bit now, so they are passed in the 64-bit registers (which have the R- prefix). However, for backward
compatibility, it is still possible to access the 32-bit parts, using the E- prefix.
This is how RAX/EAX/AX/AL looks like in 64-bit x86-compatible CPUs:
7th (byte number)
6th 5th 4th 3rd 2nd 1st 0th
RAXx64
EAX
AX
AH AL
The main() function returns an int-typed value, which is, in the C/C++, for better backward compatibility and portability,
still 32-bit, so that is why the EAX register is cleared at the function end (i.e., 32-bit part of register) instead of RAX.
There are also 40 bytes allocated in the local stack. This is called “shadow space”, about which we are going to talk
later: 8.2.1 on page 89.
3.2.2 GCC—x86-64
Let’s also try GCC in 64-bit Linux:
Listing 3.8: GCC 4.4.6 x64
.string "hello, worldn"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC0 ; "hello, worldn"
xor eax, eax ; number of vector registers passed
call printf
xor eax, eax
add rsp, 8
ret
A method to pass function arguments in registers is also used in Linux, *BSD and Mac OS X [Mit13]. The first 6 arguments
are passed in the RDI, RSI, RDX, RCX, R8, R9 registers, and the rest—via the stack.
So the pointer to the string is passed in EDI (32-bit part of register). But why not use the 64-bit part, RDI?
It is important to keep in mind that all MOV instructions in 64-bit mode that write something into the lower 32-bit register
part, also clear the higher 32-bits[Int13]. I.e., the MOV EAX, 011223344h writes a value into RAX correctly, since the
higher bits will be cleared.
If we open the compiled object file (.o), we can also see all instruction’s opcodes 10
:
Listing 3.9: GCC 4.4.6 x64
.text:00000000004004D0 main proc near
.text:00000000004004D0 48 83 EC 08 sub rsp, 8
.text:00000000004004D4 BF E8 05 40 00 mov edi, offset format ; "hello, worldn"
.text:00000000004004D9 31 C0 xor eax, eax
.text:00000000004004DB E8 D8 FE FF FF call _printf
.text:00000000004004E0 31 C0 xor eax, eax
.text:00000000004004E2 48 83 C4 08 add rsp, 8
.text:00000000004004E6 C3 retn
.text:00000000004004E6 main endp
As we can see, the instruction that writes into EDI at 0x4004D4 occupies 5 bytes. The same instruction writing a
64-bit value into RDI occupies 7 bytes. Apparently, GCC is trying to save some space. Besides, it can be sure that the data
segment containing the string will not be allocated at the addresses higher than 4GiB.
We also see that the EAX register was cleared before the printf() function call. This is done because the number of
used vector registers is passed in EAX by standard: “with variable arguments passes information about the number of vector
registers used”[Mit13].
10This must be enabled in Options → Disassembly → Number of opcode bytes
10
CHAPTER 3. HELLO, WORLD! 3.3. GCC—ONE MORE THING
3.3 GCC—one more thing
The fact that an anonymous C-string has const type ( 3.1.1 on page 6), and the fact that C-strings allocated in constants
segment are guaranteed to be immutable, has an interesting consequence: the compiler may use a specific part of string.
Let’s try this example:
#include <stdio.h>
int f1()
{
printf ("worldn");
}
int f2()
{
printf ("hello worldn");
}
int main()
{
f1();
f2();
}
Common C/C++-compilers (including MSVC) allocates two strings, but let’s see what GCC 4.8.1 does:
Listing 3.10: GCC 4.8.1 + IDA listing
f1 proc near
s = dword ptr -1Ch
sub esp, 1Ch
mov [esp+1Ch+s], offset s ; "worldn"
call _puts
add esp, 1Ch
retn
f1 endp
f2 proc near
s = dword ptr -1Ch
sub esp, 1Ch
mov [esp+1Ch+s], offset aHello ; "hello "
call _puts
add esp, 1Ch
retn
f2 endp
aHello db 'hello '
s db 'world',0xa,0
Indeed: when we print the “hello world” string, these two words are positioned in memory adjacently and puts() called
from f2() function is not aware this string is divided. It’s not divided in fact, it’s divided only “virtually”, in this listing.
When puts() is called from f1(), it uses “world” string plus zero byte. puts() is not aware there is something before
this string!
This clever trick is often used by at least GCC and can save some memory.
3.4 ARM
For my experiments with ARM processors, I used several compilers:
• Popular in the embedded area Keil Release 6/2013.
• Apple Xcode 4.6.3 IDE (with LLVM-GCC 4.2 compiler 11
).
• GCC 4.9 (Linaro) (for ARM64), available as win32-executables at http://go.yurichev.com/17325.
11It is indeed so: Apple Xcode 4.6.3 uses open-source GCC as front-end compiler and LLVM code generator
11
CHAPTER 3. HELLO, WORLD! 3.4. ARM
32-bit ARM code is used in all cases in this book, if not mentioned otherwise. When we talk about 64-bit ARM here, it
is called ARM64 here.
3.4.1 Non-optimizing Keil 6/2013 (ARM mode)
Let’s start by compiling our example in Keil:
armcc.exe --arm --c90 -O0 1.c
The armcc compiler produces assembly listings in Intel-syntax but it has high-level ARM-processor related macros12
, but
it is more important for us to see the instructions “as is” so let’s see the compiled result in IDA.
Listing 3.11: Non-optimizing Keil 6/2013 (ARM mode) IDA
.text:00000000 main
.text:00000000 10 40 2D E9 STMFD SP!, {R4,LR}
.text:00000004 1E 0E 8F E2 ADR R0, aHelloWorld ; "hello, world"
.text:00000008 15 19 00 EB BL __2printf
.text:0000000C 00 00 A0 E3 MOV R0, #0
.text:00000010 10 80 BD E8 LDMFD SP!, {R4,PC}
.text:000001EC 68 65 6C 6C+aHelloWorld DCB "hello, world",0 ; DATA XREF: main+4
In the example, we can easily see each instruction has a size of 4 bytes. Indeed, we compiled our code for ARM mode,
not for thumb.
The very first instruction, ``STMFD SP!, {R4,LR}''13
, works as an x86 PUSH instruction, writing the values of two
registers (R4 and LR) into the stack. Indeed, in the output listing from the armcc compiler, for the sake of simplification,
actually shows the ``PUSH {r4,lr}'' instruction. But that is not quite precise. The PUSH instruction is only available
in thumb mode. So, to make things less confusing, we’re doing this in IDA.
This instruction decrements first the SP15
so it points to the place in the stack that is free for new entries, then it saves
the values of the R4 and LR registers at the address stored in the modified SP.
This instruction (like the PUSH instruction in thumb mode) is able to save several register values at once which can be
very useful. By the way, this has no equivalent in x86. It can also be noted that the STMFD instruction is a generalization of
the PUSH instruction (extending its features), since it can work with any register, not just with SP. In other words, STMFD
may be used for storing pack of registers at the specified memory address.
The ``ADR R0, aHelloWorld'' instruction adds or subtracts the value in the PC16
register to the offset where the
“hello, world” string is located. How is the PC register used here, one might ask? This is so-called “position-independent
code”. 17
Such code can be be executed at a non-fixed address in memory. In other words, this is PC-relative addressing.
The ADR instruction takes into account the difference between the address of this instruction and the address where the
string is located. This difference (offset) is always to be the same, no matter at what address our code is loaded by the OS.
That’s why all we need is to add the address of the current instruction (from PC) in order to get the absolute memory address
of our C-string.
``BL __2printf''18
instruction calls the printf() function. Here’s how this instruction works:
• store the address following the BL instruction (0xC) into the LR;
• then pass the control to the printf() by writing its address into the PC register.
When printf() finishes its execution it must have information about where it needs to return the control to. That’s
why each function passes control to the address stored in the LR register.
That is a difference between “pure” RISC-processors like ARM and CISC19
-processors like x86, where the return address
is usually stored on the stack20
.
By the way, an absolute 32-bit address or offset cannot be encoded in the 32-bit BL instruction because it only has space
for 24 bits. As we may remember, all ARM-mode instructions have a size of 4 bytes (32 bits). Hence, they can only be located
on 4-byte boundary addresses. This implies that the last 2 bits of the instruction address (which are always zero bits) may
be omitted. In summary, we have 26 bits for offset encoding. This is enough to encode current_PC ± ≈ 32M.
Next, the ``MOV R0, #0''21
instruction just writes 0 into the R0 register. That’s because our C-function returns 0 and
the return value is to be placed in the R0 register.
12e.g. ARM mode lacks PUSH/POP instructions
13STMFD14
15stack pointer. SP/ESP/RSP in x86/x64. SP in ARM.
16Program Counter. IP/EIP/RIP in x86/64. PC in ARM.
17Read more about it in relevant section ( 67.1 on page 678)
18Branch with Link
19Complex instruction set computing
20Read more about this in next section ( 5 on page 22)
21MOVe
12
CHAPTER 3. HELLO, WORLD! 3.4. ARM
The last instruction ``LDMFD SP!, R4,PC''22
is an inverse instruction of STMFD. It loads values from the stack (or
any other memory place) in order to save them into R4 and PC, and increments the stack pointer SP. It works like POP here.
N.B. The very first instruction STMFD saved the R4 and LR registers pair on the stack, but R4 and PC are restored during the
LDMFD execution.
As I mentioned before, the address of the place where each function must return control to is usually saved in the LR
register. The very first instruction saves its value in the stack because the same register will be used by our main() function
when calling printf(). In the function’s end, this value can be written directly to the PC register, thus passing control to
where our function was called. Since main() is usually the primary function in C/C++, the control will be returned to the
OS loader or to a point in a CRT, or something like that.
DCB is an assembly language directive defining an array of bytes or ASCII strings, akin to the DB directive in x86-assembly
language.
3.4.2 Non-optimizing Keil 6/2013 (thumb mode)
Let’s compile the same example using Keil in thumb mode:
armcc.exe --thumb --c90 -O0 1.c
We are getting (in IDA):
Listing 3.12: Non-optimizing Keil 6/2013 (thumb mode) + IDA
.text:00000000 main
.text:00000000 10 B5 PUSH {R4,LR}
.text:00000002 C0 A0 ADR R0, aHelloWorld ; "hello, world"
.text:00000004 06 F0 2E F9 BL __2printf
.text:00000008 00 20 MOVS R0, #0
.text:0000000A 10 BD POP {R4,PC}
.text:00000304 68 65 6C 6C+aHelloWorld DCB "hello, world",0 ; DATA XREF: main+2
We can easily spot the 2-byte (16-bit) opcodes. This is, as I mentioned, thumb. The BL instruction, however, consists of
two 16-bit instructions. This is because it is impossible to load an offset for the printf() function into PC while using
the small space in one 16-bit opcode. Therefore, the first 16-bit instruction loads the higher 10 bits of the offset and the
second instruction loads the lower 11 bits of the offset. As I mentioned, all instructions in thumb mode have a size of 2
bytes (or 16 bits). This implies it is impossible for a thumb-instruction to be at an odd address whatsoever. Given the
above, the last address bit may be omitted while encoding instructions. In summary, BL thumb-instruction can encode the
address current_PC ± ≈ 2M.
As for the other instructions in the function: PUSH and POP work here just like the described STMFD/LDMFD only the SP
register is not mentioned explicitly here. ADR works just like in the previous example. MOVS writes 0 into the R0 register in
order to return zero.
3.4.3 Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Xcode 4.6.3 without optimization turned on produces a lot of redundant code so we’ll study optimized output, where the
instruction count is as small as possible, setting the compiler switch -O3.
Listing 3.13: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
__text:000028C4 _hello_world
__text:000028C4 80 40 2D E9 STMFD SP!, {R7,LR}
__text:000028C8 86 06 01 E3 MOV R0, #0x1686
__text:000028CC 0D 70 A0 E1 MOV R7, SP
__text:000028D0 00 00 40 E3 MOVT R0, #0
__text:000028D4 00 00 8F E0 ADD R0, PC, R0
__text:000028D8 C3 05 00 EB BL _puts
__text:000028DC 00 00 A0 E3 MOV R0, #0
__text:000028E0 80 80 BD E8 LDMFD SP!, {R7,PC}
__cstring:00003F62 48 65 6C 6C+aHelloWorld_0 DCB "Hello world!",0
The instructions STMFD and LDMFD are already familiar to us.
The MOV instruction just writes the number 0x1686 into the R0 register. This is the offset pointing to the “Hello world!”
string.
The R7 register (as it is standardized in [App10]) is a frame pointer. More on that below.
The MOVT R0, #0 (MOVe Top) instruction writes 0 into higher 16 bits of the register. The issue here is that the generic
MOV instruction in ARM mode may write only the lower 16 bits of the register. Remember, all instruction opcodes in ARM
22LDMFD23
13
CHAPTER 3. HELLO, WORLD! 3.4. ARM
mode are limited in size to 32 bits. Of course, this limitation is not related to moving data between registers. That’s why
an additional instruction MOVT exists for writing into the higher bits (from 16 to 31 inclusive). Its usage here, however, is
redundant because the ``MOV R0, #0x1686'' instruction above cleared the higher part of the register. This is probably
a shortcoming of the compiler.
The ``ADD R0, PC, R0'' instruction adds the value in the PC to the value in the R0, to calculate absolute address
of the “Hello world!” string. As we already know, it is “position-independent code” so this correction is essential here.
The BL instruction calls the puts() function instead of printf().
GCC replaced the first printf() call with puts(). Indeed: printf() with a sole argument is almost analogous to
puts().
Almost, because the two functions are producing the same result only in case the string does not contain printf format
identifiers starting with %. In case it does, the effect of these two functions would be different 24
.
Why did the compiler replace the printf() with puts()? Probably because puts() is faster 25
.
puts() works faster because it just passes characters to stdout without comparing every one of them with the % symbol.
Next, we see the familiar ``MOV R0, #0'' instruction intended to set the R0 register to 0.
3.4.4 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
By default Xcode 4.6.3 generates code for thumb-2 in this manner:
Listing 3.14: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
__text:00002B6C _hello_world
__text:00002B6C 80 B5 PUSH {R7,LR}
__text:00002B6E 41 F2 D8 30 MOVW R0, #0x13D8
__text:00002B72 6F 46 MOV R7, SP
__text:00002B74 C0 F2 00 00 MOVT.W R0, #0
__text:00002B78 78 44 ADD R0, PC
__text:00002B7A 01 F0 38 EA BLX _puts
__text:00002B7E 00 20 MOVS R0, #0
__text:00002B80 80 BD POP {R7,PC}
...
__cstring:00003E70 48 65 6C 6C 6F 20+aHelloWorld DCB "Hello world!",0xA,0
The BL and BLX instructions in thumb mode, as we recall, are encoded as a pair of 16-bit instructions. In thumb-2 these
surrogate opcodes are extended in such a way so that new instructions may be encoded here as 32-bit instructions. That is
obvious considering that the opcodes of the thumb-2 instructions always begin with 0xFx or 0xEx. But in the IDA listing
the opcode bytes are swapped because for ARM processor the instructions are encoded as follows: last byte comes first and
after that comes the first one (for thumb and thumb-2 modes) or for instructions in ARM mode the fourth byte comes first,
then the third, then the second and finally the first (due to different endianness). So as we can see, the MOVW, MOVT.W and
BLX instructions begin with 0xFx.
One of the thumb-2 instructions is ``MOVW R0, #0x13D8'' —it stores a 16-bit value into the lower part of the R0
register, clearing the higher bits.
Also, ``MOVT.W R0, #0'' works just like MOVT from the previous example only it works in thumb-2.
Among the other differences, the BLX instruction is used in this case instead of the BL. The difference is that, be-
sides saving the RA in the LR register and passing control to the puts() function, the processor is also switching from
thumb/thumb-2 mode to ARM mode (or back). This instruction is placed here since the instruction to which control is
passed looks like (it is encoded in ARM mode):
__symbolstub1:00003FEC _puts ; CODE XREF: _hello_world+E
__symbolstub1:00003FEC 44 F0 9F E5 LDR PC, =__imp__puts
This is essentially jump to place where puts() address is written in imports’ section.
So, the observant reader may ask: why not call puts() right at the point in the code where it is needed?
Because it is not very space-efficient.
Almost any program uses external dynamic libraries (like DLL in Windows, .so in *NIX or .dylib in Mac OS X). The dynamic
libraries contain frequently used library functions, including the standard C-function puts().
In an executable binary file (Windows PE .exe, ELF or Mach-O) an import section is present. This is a list of symbols
(functions or global variables) imported from external modules along with the names of the modules themselves.
The OS loader loads all modules it needs and, while enumerating import symbols in the primary module, determines the
correct addresses of each symbol.
In our case, __imp__puts is a 32-bit variable used by the OS loader to store the correct address of the function in an
external library. Then the LDR instruction just reads the 32-bit value from this variable and writes it into the PC register,
passing control to it.
24It has also to be noted the puts() does not require a ’n’ new line symbol at the end of a string, so we do not see it here.
25http://go.yurichev.com/17063
14
CHAPTER 3. HELLO, WORLD! 3.4. ARM
So, in order to reduce the time the OS loader needs for completing this procedure, it is good idea if it writes the address
of each symbol only once, to a dedicated place.
Besides, as we have already figured out, it is impossible to load a 32-bit value into a register while using only one
instruction without a memory access. Therefore, the optimal solution is to allocate a separate function working in ARM
mode with sole goal to pass control to the dynamic library and then to jump to this short one-instruction function (the
so-called thunk function) from the thumb-code.
By the way, in the previous example (compiled for ARM mode) the control is passed by the BL to the same thunk function.
The processor mode, however, is not being switched (hence the absence of an “X” in the instruction mnemonic).
3.4.5 ARM64
GCC
Let’s compile the example using GCC 4.8.1 in ARM64:
Listing 3.15: Non-optimizing GCC 4.8.1 + objdump
1 0000000000400590 <main>:
2 400590: a9bf7bfd stp x29, x30, [sp,#-16]!
3 400594: 910003fd mov x29, sp
4 400598: 90000000 adrp x0, 400000 <_init-0x3b8>
5 40059c: 91192000 add x0, x0, #0x648
6 4005a0: 97ffffa0 bl 400420 <puts@plt>
7 4005a4: 52800000 mov w0, #0x0 // #0
8 4005a8: a8c17bfd ldp x29, x30, [sp],#16
9 4005ac: d65f03c0 ret
10
11 ...
12
13 Contents of section .rodata:
14 400640 01000200 00000000 48656c6c 6f210a00 ........Hello!..
There are no thumb and thumb-2 modes in ARM64, only ARM, so there are 32-bit instructions only. Registers count is
doubled: B.4.1 on page 945. 64-bit registers has X- prefixes, while its 32-bit parts—W-.
The STP instruction (Store Pair) saves two registers in the stack simultaneously: X29 in X30. Of course, this instruction
is able to save this pair at a random place of memory, but the SP register is specified here, so the pair is saved in the stack.
ARM64 registers are 64-bit ones, each has a size of 8 bytes, so one needs 16 bytes for saving two registers.
Exclamation mark after operand mean that 16 is to be subtracted from SP first, and only then values from registers pair
are to be written into the stack. This is also called pre-index. About the difference between post-index and pre-index, read
here: 28.2 on page 445.
Hence, in the terms of more familiar x86, the first instruction is just an analogue to pair of PUSH X29 and PUSH X30.
X29 is used as FP26
in ARM64, and X30 as LR, so that’s why they are saved in the function prologue and restored in the
function epilogue.
The second instruction copies SP in X29 (or FP). This is done to set up the function stack frame.
ADRP and ADD instructions are used to fill the string “Hello!” address into the X0 register, because the first function
argument is passed in this register. There are no instructions, whatsoever, in ARM that can store a large number into a
register (because the instruction length is limited to 4 bytes, read more about it here: 28.3.1 on page 445). So several
instructions must be utilised. The first instruction (ADRP) writes address of 4Kb page where the string is located into X0,
and the the second one (ADD) just adds reminder to the address. More about that in: 28.4 on page 447.
0x400000 + 0x648 = 0x400648, and we see our “Hello!” C-string in the .rodata data segment at this address.
puts() is called afterwards using BL instruction. This was already discussed: 3.4.3 on page 14.
MOV instruction writes 0 into W0. W0 is low 32 bits of 64-bit X0 register:
High 32-bit part low 32-bit part
X0
W0
The function result is returned via X0 and main() returns 0, so that’s how the return result is prepared. But why using
the 32-bit part? Because int data type in ARM64, just like in x86-64, is still 32-bit, for better compatibility. So if a function
returns 32-bit int, only the low 32 bits of X0 register has to be filled.
In order to verify this, I changed my example slightly and recompiled it. Now main() returns 64-bit value:
Listing 3.16: main() returning a value of uint64_t type
#include <stdio.h>
#include <stdint.h>
26Frame Pointer
15
CHAPTER 3. HELLO, WORLD! 3.5. MIPS
uint64_t main()
{
printf ("Hello!n");
return 0;
}
The result is the same, but that’s how MOV at that line looks like now:
Listing 3.17: Non-optimizing GCC 4.8.1 + objdump
4005a4: d2800000 mov x0, #0x0 // #0
LDP (Load Pair) then restores X29 and X30 registers. There is no exclamation mark after the instruction: this implies
that the value is first loaded from the stack, only then SP it is increased by 16. This is called post-index.
New instruction appeared in ARM64: RET. It works just as BX LR, only a special hint bit is added, informing the CPU that
this is a return from a function, not just another jump instruction, so it can execute it more optimally.
Due to the simplicity of the function, optimizing GCC generates the very same code.
3.5 MIPS
3.5.1 Word about “global pointer”
One important MIPS concept is “global pointer”. As we may already know, each MIPS instruction has size of 32 bits, so it’s
impossible to embed 32-bit address into one instruction: a pair has to be used for this (like GCC did in our example for the
text string address loading).
It’s possible, however, to load data from the address in range of register − 32768...register + 32767 using one single
instruction (because 16 bits of signed offset could be encoded in single instruction). So we can allocate some register
for this purpose and also allocate 64KiB area of most used data. This allocated register is called “global pointer” and it
points to the middle of the 64KiB area. This area usually contains global variables and addresses of imported functions
like printf(), because GCC developers decided that getting address of some function must be as fast as single instruction
execution instead of two. In an ELF file this 64KiB area is located partly in .sbss (“small BSS27
”, for not initialized data) and
.sdata (“small data”, for initialized data) sections.
This implies that the programmer may choose what data he/she wants to be accessed fast and place it into .sdata/.sbss.
Some old-school programmers may recall the MS-DOS memory model 94 on page 880 or the MS-DOS memory managers
like XMS/EMS where all memory was divided in 64KiB blocks.
This concept is not unique to MIPS. At least PowerPC uses this technique as well.
3.5.2 Optimizing GCC
Listing 3.18: Optimizing GCC 4.4.5 (assembly output)
1 $LC0:
2 ; 000 is zero byte in octal base:
3 .ascii "Hello, world!012000"
4 main:
5 ; function prologue.
6 ; set GP:
7 lui $28,%hi(__gnu_local_gp)
8 addiu $sp,$sp,-32
9 addiu $28,$28,%lo(__gnu_local_gp)
10 ; save RA to the local stack:
11 sw $31,28($sp)
12 ; load address of puts() function from GP to $25:
13 lw $25,%call16(puts)($28)
14 ; load address of the text string to $4 ($a0):
15 lui $4,%hi($LC0)
16 ; jump to puts(), saving return address in link register:
17 jalr $25
18 addiu $4,$4,%lo($LC0) ; branch delay slot
19 ; restore RA:
20 lw $31,28($sp)
21 ; copy 0 from $zero to $v0:
22 move $2,$0
23 ; return by jumping to address in RA:
24 j $31
25 ; function epilogue:
27Block Started by Symbol
16
CHAPTER 3. HELLO, WORLD! 3.5. MIPS
26 addiu $sp,$sp,32 ; branch delay slot
The $GP register is set in the function prologue to point the middle of this area. The RA register is also saved in the
local stack. puts() is also used here instead of printf(). The address of the puts() function is loaded into $25 using
LW the instruction (“Load Word”). Then the address of the text string is loaded to $4 using LUI (“Load Upper Immediate”)
and ADDIU (“Add Immediate Unsigned Word”) instruction pair. LUI sets the high 16 bits of the register (hence “upper” word
in instruction name) and ADDIU adds the lower 16 bits of the address. ADDIU follows JALR (remember branch delay slots?).
The register $4 is also called $A0, which is used for passing the first function argument 28
.
JALR (“Jump and Link Register”) jumps to the address stored in the $25 register (address of puts()) while saving the
address of the next instruction (LW) in RA. This is very similar to ARM. Oh, and one important thing is that the address saved
in RA is not the address of the next instruction (because it’s in a delay slot and is executed before the jump instruction), but
the address of the instruction after the next one (after the delay slot). Hence, PC + 8 is written to RA during the execution
of JALR, in our case, this is the address of the LW instruction next to ADDIU.
LW (“Load Word”) at line 19 restores RA from the local stack (this instruction is rather part of function epilogue).
MOVE at line 22 copies the value from $0 ($ZERO) register to $2 ($V0). MIPS has a constant register, which always
holds zero. Apparently, the MIPS developers came with the idea that zero is in fact the busiest constant in the computer
programming, so let’s just use $0 register every time zero is needed. Another interesting fact is that MIPS lacks instruction
which transfers data between registers. In fact, MOVE DST, SRC is ADD DST, SRC, $ZERO (DST = SRC + 0), which
does the same. Apparently, MIPS developers wanted to have compact opcode table. This does not mean an actual addition
happens at each MOVE instruction. Most likely, the CPU optimizes these pseudoinstructions and ALU29
is never used.
J at line 24 jumps to the address in RA, which is effectively performing return from the function. ADDIU after J is in fact
executed before J (remember branch delay slots?) and is part of function epilogue.
Here is also a listing generated by IDA. Each register here has its own pseudoname:
Listing 3.19: Optimizing GCC 4.4.5 (IDA)
1 .text:00000000 main:
2 .text:00000000
3 .text:00000000 var_10 = -0x10
4 .text:00000000 var_4 = -4
5 .text:00000000
6 ; function prologue.
7 ; set GP:
8 .text:00000000 lui $gp, (__gnu_local_gp >> 16)
9 .text:00000004 addiu $sp, -0x20
10 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF)
11 ; save RA to the local stack:
12 .text:0000000C sw $ra, 0x20+var_4($sp)
13 ; save GP to the local stack:
14 ; by some reason, this instruction is missing in GCC assembly output:
15 .text:00000010 sw $gp, 0x20+var_10($sp)
16 ; load address of puts() function from GP to $t9:
17 .text:00000014 lw $t9, (puts & 0xFFFF)($gp)
18 ; form address of the text string in $a0:
19 .text:00000018 lui $a0, ($LC0 >> 16) # "Hello, world!"
20 ; jump to puts(), saving return address in link register:
21 .text:0000001C jalr $t9
22 .text:00000020 la $a0, ($LC0 & 0xFFFF) # "Hello, world!"
23 ; restore RA:
24 .text:00000024 lw $ra, 0x20+var_4($sp)
25 ; copy 0 from $zero to $v0:
26 .text:00000028 move $v0, $zero
27 ; return by jumping to address in RA:
28 .text:0000002C jr $ra
29 ; function epilogue:
30 .text:00000030 addiu $sp, 0x20
The instruction at line 15 saves GP value into the local stack, and this instruction is missing mysteriously from the GCC
output listing, maybe by a GCC error30
. The GP value has to be saved indeed, because each function can use its own 64KiB
data window.
The register containing the puts() address is called $T9, because registers prefixed with T- are called “temporaries”
and their contents may not be preserved.
3.5.3 Non-optimizing GCC
28The MIPS registers table is available in appendix C.1 on page 947
29Arithmetic logic unit
30Apparently, functions generating listings are not so critical to GCC users, so some unfixed errors may still exist.
17
CHAPTER 3. HELLO, WORLD! 3.5. MIPS
Listing 3.20: Non-optimizing GCC 4.4.5 (assembly output)
1 $LC0:
2 .ascii "Hello, world!012000"
3 main:
4 ; function prologue.
5 ; save GP and FP in the stack:
6 addiu $sp,$sp,-32
7 sw $31,28($sp)
8 sw $fp,24($sp)
9 ; set FP (stack frame pointer):
10 move $fp,$sp
11 ; set GP:
12 lui $28,%hi(__gnu_local_gp)
13 addiu $28,$28,%lo(__gnu_local_gp)
14 ; load address of the text string:
15 lui $2,%hi($LC0)
16 addiu $4,$2,%lo($LC0)
17 ; load address of puts() address using GP:
18 lw $2,%call16(puts)($28)
19 nop
20 ; call to puts():
21 move $25,$2
22 jalr $25
23 nop ; branch delay slot
24
25 ; restore GP from local stack:
26 lw $28,16($fp)
27 ; set register $2 ($V0) to zero:
28 move $2,$0
29 ; function epilogue.
30 ; restore SP:
31 move $sp,$fp
32 ; restore RA:
33 lw $31,28($sp)
34 ; restore FP:
35 lw $fp,24($sp)
36 addiu $sp,$sp,32
37 ; jump to RA:
38 j $31
39 nop ; branch delay slot
Non-optimizing GCC is more verbose. We see here that register FP is used as a pointer to the stack frame. We also see
3 NOP31
s. The second and third of which follow the branch instructions.
I guess (not sure, though) that the GCC compiler always adds NOPs (because of branch delay slots) after branch instructions
and then, if optimization is turned on, maybe eliminates them. So in this case they are left here.
Here is also IDA listing:
Listing 3.21: Non-optimizing GCC 4.4.5 (IDA)
1 .text:00000000 main:
2 .text:00000000
3 .text:00000000 var_10 = -0x10
4 .text:00000000 var_8 = -8
5 .text:00000000 var_4 = -4
6 .text:00000000
7 ; function prologue.
8 ; save GP and FP in the stack:
9 .text:00000000 addiu $sp, -0x20
10 .text:00000004 sw $ra, 0x20+var_4($sp)
11 .text:00000008 sw $fp, 0x20+var_8($sp)
12 ; set FP (stack frame pointer):
13 .text:0000000C move $fp, $sp
14 ; set GP:
15 .text:00000010 la $gp, __gnu_local_gp
16 .text:00000018 sw $gp, 0x20+var_10($sp)
17 ; load address of the text string:
18 .text:0000001C lui $v0, (aHelloWorld >> 16) # "Hello, world!"
19 .text:00000020 addiu $a0, $v0, (aHelloWorld & 0xFFFF) # "Hello, world!"
20 ; load address of puts() address using GP:
31No OPeration
18
CHAPTER 3. HELLO, WORLD! 3.5. MIPS
21 .text:00000024 lw $v0, (puts & 0xFFFF)($gp)
22 .text:00000028 or $at, $zero ; NOP
23 ; call to puts():
24 .text:0000002C move $t9, $v0
25 .text:00000030 jalr $t9
26 .text:00000034 or $at, $zero ; NOP
27 ; restore GP from local stack:
28 .text:00000038 lw $gp, 0x20+var_10($fp)
29 ; set register $2 ($V0) to zero:
30 .text:0000003C move $v0, $zero
31 ; function epilogue.
32 ; restore SP:
33 .text:00000040 move $sp, $fp
34 ; restore RA:
35 .text:00000044 lw $ra, 0x20+var_4($sp)
36 ; restore FP:
37 .text:00000048 lw $fp, 0x20+var_8($sp)
38 .text:0000004C addiu $sp, 0x20
39 ; jump to RA:
40 .text:00000050 jr $ra
41 .text:00000054 or $at, $zero ; NOP
Interestingly, IDA recognized LUI/ADDIU instructions pair and coalesces them into one LA (“Load Address”) pseudoin-
struction at line 15. We may also see that this pseudoinstruction has size of 8 bytes! This is a pseudoinstruction (or macro)
because it’s not a real MIPS instruction, but rather handy name for an instruction pair.
Another thing is that IDA doesn’t recognize NOP instructions, so here they are at lines 22, 26 and 41. It is OR $AT,
$ZERO. Essentially, this instruction applies OR operation to contents of $AT register with zero, which is, of course, idle
instruction. MIPS, like many other ISAs, doesn’t have a separate NOP instruction.
3.5.4 Role of the stack frame in this example
The address of the text string is passed in register. Why setup local stack anyway? The reason for this lies in the fact
that registers RA and GP’s values has to be saved somewhere (because printf() is called), and the local stack is used for
this purpose. If this was a leaf function, it would have been possible to get rid of the function prologue and epilogue, for
example: 2.3 on page 4.
3.5.5 Optimizing GCC: load it into GDB
Listing 3.22: sample GDB session
root@debian-mips:~# gcc hw.c -O3 -o hw
root@debian-mips:~# gdb hw
GNU gdb (GDB) 7.0.1-debian
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "mips-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/hw...(no debugging symbols found)...done.
(gdb) b main
Breakpoint 1 at 0x400654
(gdb) run
Starting program: /root/hw
Breakpoint 1, 0x00400654 in main ()
(gdb) set step-mode on
(gdb) disas
Dump of assembler code for function main:
0x00400640 <main+0>: lui gp,0x42
0x00400644 <main+4>: addiu sp,sp,-32
0x00400648 <main+8>: addiu gp,gp,-30624
0x0040064c <main+12>: sw ra,28(sp)
0x00400650 <main+16>: sw gp,16(sp)
0x00400654 <main+20>: lw t9,-32716(gp)
0x00400658 <main+24>: lui a0,0x40
19
CHAPTER 3. HELLO, WORLD! 3.6. CONCLUSION
0x0040065c <main+28>: jalr t9
0x00400660 <main+32>: addiu a0,a0,2080
0x00400664 <main+36>: lw ra,28(sp)
0x00400668 <main+40>: move v0,zero
0x0040066c <main+44>: jr ra
0x00400670 <main+48>: addiu sp,sp,32
End of assembler dump.
(gdb) s
0x00400658 in main ()
(gdb) s
0x0040065c in main ()
(gdb) s
0x2ab2de60 in printf () from /lib/libc.so.6
(gdb) x/s $a0
0x400820: "hello, world"
(gdb)
3.6 Conclusion
The main difference between x86/ARM and x64/ARM64 code is that pointer to the string is now 64-bit. Indeed, modern
CPUs are 64-bit now because memory is cheaper nowadays. We can add much more memory to our computers and 32-bit
pointers are not enough to address it. So all pointers are 64-bit now.
3.7 Exercises
3.7.1 Exercise #1
main:
push 0xFFFFFFFF
call MessageBeep
xor eax,eax
retn
What does this win32-function do?
20
CHAPTER 4. FUNCTION PROLOGUE AND EPILOGUE
Chapter 4
Function prologue and epilogue
A function prologue is a sequence of instructions at the start of a function. It often looks something like the following code
fragment:
push ebp
mov ebp, esp
sub esp, X
What these instruction do: save the value in the EBP register, sets the value of the EBP register to the value of the ESP
and then allocate space on the stack for local variables.
The value in the EBP stays the same over the period of the function execution and is to be used for local variables and
arguments access. For the same purpose one can use ESP, but since it changes over time this approach is not too convenient.
The function epilogue frees allocated space in the stack, returns the value in the EBP register back to its initial state and
returns the control flow to the callee:
mov esp, ebp
pop ebp
ret 0
Function prologues and epilogues are usually detected in disassemblers for function delimitation.
4.1 Recursion
Epilogues and prologues can negatively affect the recursion performance.
More about recursion in this book: 36.3 on page 470.
21
CHAPTER 5. STACK
Chapter 5
Stack
The stack is one of the most fundamental data structures in computer science 1
.
Technically, it is just a block of memory in process memory along with the ESP or RSP register in x86 or x64, or the SP
register in ARM, as a pointer within that block.
The most frequently used stack access instructions are PUSH and POP (in both x86 and ARM thumb-mode). PUSH subtracts
from ESP/RSP/SP 4 in 32-bit mode (or 8 in 64-bit mode) and then writes the contents of its sole operand to the memory
address pointed by ESP/RSP/SP.
POP is the reverse operation: retrieve the data from memory pointed by SP, loads it into the instruction operand (often
a register) and then add 4 (or 8) to the stack pointer.
After stack allocation, the stack pointer points at the bottom of the stack. PUSH decreases the stack pointer and POP
increases it. The bottom of the stack is actually at the beginning of the memory allocated for the stack block. It seems
strange, but that’s the way it is.
ARM supports both descending and ascending stacks.
For example the STMFD/LDMFD, STMED2
/LDMED3
instructions are intended to deal with a descending stack (grows
downwards, starting with a high address and progressing to a lower one). The STMFA4
/LDMFA5
, STMEA6
/LDMEA7
instruc-
tions are intended to deal with an ascending stack (grows upwards, starting from a low address and progressing to a higher
one).
5.1 Why does the stack grow backwards?
Intuitively, we might think that the stack grow upwards, i.e. towards higher addresses, like any other data structure.
The reason that the stack grows backward is probably historical. When the computers were big and occupied a whole
room, it was easy to divide memory into two parts, one for the heap and one for the stack. Of course, it was unknown how
big the heap and the stack would be during program execution, so this solution was the simplest possible.
...Heap . Stack...
Start of heap
.
Start of stack
In [RT74] we can read:
The user-core part of an image is divided into three logical segments. The program text segment begins
at location 0 in the virtual address space. During execution, this segment is write-protected and a single
copy of it is shared among all processes executing the same program. At the first 8K byte boundary above
the program text segment in the virtual address space begins a nonshared, writable data segment, the size
of which may be extended by a system call. Starting at the highest address in the virtual address space is a
stack segment, which automatically grows downward as the hardware’s stack pointer fluctuates.
1wikipedia
2Store Multiple Empty Descending (ARM instruction)
3Load Multiple Empty Descending (ARM instruction)
4Store Multiple Full Ascending (ARM instruction)
5Load Multiple Full Ascending (ARM instruction)
6Store Multiple Empty Ascending (ARM instruction)
7Load Multiple Empty Ascending (ARM instruction)
22
CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR?
This reminds us how some students write two lecture notes using only one notebook: notes for the first lecture are
written as usual, and notes for the second one are written from the end of notebook, by flipping it. Notes may meet each
other somewhere in between, in case of lack of free space.
5.2 What is the stack used for?
5.2.1 Save the function’s return address
x86
When calling another function with a CALL instruction the address of the point exactly after the CALL instruction is saved
to the stack and then an unconditional jump to the address in the CALL operand is executed.
The CALL instruction is equivalent to a PUSH address_after_call / JMP operand instruction pair.
RET fetches a value from the stack and jumps to it —that is equivalent to a POP tmp / JMP tmp instruction pair.
Overflowing the stack is straightforward. Just run eternal recursion:
void f()
{
f();
};
MSVC 2008 reports the problem:
c:tmp6>cl ss.cpp /Fass.asm
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
ss.cpp
c:tmp6ss.cpp(4) : warning C4717: 'f' : recursive on all control paths, function will cause ⤦
runtime stack overflow
…but generates the right code anyway:
?f@@YAXXZ PROC ; f
; File c:tmp6ss.cpp
; Line 2
push ebp
mov ebp, esp
; Line 3
call ?f@@YAXXZ ; f
; Line 4
pop ebp
ret 0
?f@@YAXXZ ENDP ; f
… Also if we turn on the compiler optimization (/Ox option) the optimized code will not overflow the stack and will work
correctly8
instead:
?f@@YAXXZ PROC ; f
; File c:tmp6ss.cpp
; Line 2
$LL3@f:
; Line 3
jmp SHORT $LL3@f
?f@@YAXXZ ENDP ; f
GCC 4.4.1 generates similar code in both cases without, however, issuing any warning about the problem.
ARM
ARM programs also use the stack for saving return addresses, but differently. As mentioned in “Hello, world!” ( 3.4 on
page 11), the RA is saved to the LR (link register). If one needs, however, to call another function and use the LR register one
more time its value has to be saved. Usually it is saved in the function prologue. Often, we see instructions like ``PUSH
R4-R7,LR'' along with this instruction in epilogue ``POP R4-R7,PC'' —thus register values to be used in the function
are saved in the stack, including LR.
Nevertheless, if a function never calls any other function, in ARM terminology it is called a leaf function9
. As a conse-
quence, leaf functions do not save the LR register (because they don’t modify it). If such function is small and uses a small
8irony here
9http://go.yurichev.com/17064
23
CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR?
number of registers, it may not use the stack at all. Thus, it is possible to call leaf functions without using the stack which
can be faster than on older x86 because external RAM is not used for the stack 10
. This can be also useful for situations
when memory for the stack is not yet allocated or not available.
Some examples of leaf functions are: listing. 8.3.2 on page 91, 8.3.3 on page 92, 19.17 on page 315, 19.33 on page 332, 19.5.4
on page 333, 15.4 on page 196, 15.2 on page 195, 17.3 on page 216.
5.2.2 Passing function arguments
The most popular way to pass parameters in x86 is called “cdecl”:
push arg3
push arg2
push arg1
call f
add esp, 4*3
Callee functions get their arguments via the stack pointer.
Therefore, this is how the argument values are located in the stack before the execution of the f() function’s very first
instruction:
ESP return address
ESP+4 argument#1, marked in IDA as arg_0
ESP+8 argument#2, marked in IDA as arg_4
ESP+0xC argument#3, marked in IDA as arg_8
… …
For more information on other calling conventions see also section ( 64 on page 663). It is worth noting that nothing
obliges programmers to pass arguments through the stack. It is not a requirement. One could implement any other method
without using the stack at all.
For example, it is possible to allocate a space for arguments in the heap, fill it and pass it to a function via a pointer to
this block in the EAX register. This will work 11
. However, it is a convenient custom in x86 and ARM to use the stack for
this purpose.
By the way, the callee function does not have any information about how many arguments were passed. C functions
with a variable number of arguments (like printf()) determine their number using format string specifiers (which begin
with the % symbol). If we write something like
printf("%d %d %d", 1234);
printf() will print 1234, and then two random numbers, which were laying next to it in the stack.
That’s why it is not very important how we declare the main() function: as main(), main(int argc, char *argv[])
or main(int argc, char *argv[], char *envp[]).
In fact, the CRT-code is calling main() roughly as:
push envp
push argv
push argc
call main
...
If you declare main() as main() without arguments, they are, nevertheless, still present in the stack, but are not used.
If you declare main() as main(int argc, char *argv[]), you will be able to use first two arguments, and the third
will remain “invisible” for your function. Even more, it is possible to declare main(int argc), and it will work.
5.2.3 Local variable storage
A function could allocate space in the stack for its local variables just by shifting the stack pointer towards the stack bottom.
Hence, it’s very fast, no matter how many local variables are defined.
It is also not a requirement to store local variables in the stack. You could store local variables wherever you like, but
traditionally this is how it’s done.
10Some time ago, on PDP-11 and VAX, the CALL instruction (calling other functions) was expensive; up to 50% of execution time might be spent on it, so
it was considered that having a big number of small functions is an anti-pattern[Ray03, Chapter 4, Part II].
11For example, in the “The Art of Computer Programming” book by Donald Knuth, in section 1.4.1 dedicated to subroutines[Knu98, section 1.4.1], we
could read that one way to supply arguments to a subroutine is simply to list them after the JMP instruction passing control to subroutine. Knuth explains
that this method was particularly convenient on IBM System/360.
24
CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR?
5.2.4 x86: alloca() function
It is worth noting the alloca() function.12
.
This function works like malloc(), but allocates memory directly on the stack.
The allocated memory chunk does not need to be freed via a free() function call, since the function epilogue ( 4 on
page 21) returns ESP back to its initial state and the allocated memory is just dropped.
It is worth noting how alloca() is implemented.
In simple terms, this function just shifts ESP downwards toward the stack bottom by the number of bytes you need and
sets ESP as a pointer to the allocated block. Let’s try:
#ifdef __GNUC__
#include <alloca.h> // GCC
#else
#include <malloc.h> // MSVC
#endif
#include <stdio.h>
void f()
{
char *buf=(char*)alloca (600);
#ifdef __GNUC__
snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // GCC
#else
_snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // MSVC
#endif
puts (buf);
};
(_snprintf() function works just like printf(), but instead of dumping the result into stdout (e.g., to terminal or
console), it writes it to the buf buffer. puts() copies buf contents to stdout. Of course, these two function calls might be
replaced by one printf() call, but I would like to illustrate small buffer usage.)
MSVC
Let’s compile (MSVC 2010):
Listing 5.1: MSVC 2010
...
mov eax, 600 ; 00000258H
call __alloca_probe_16
mov esi, esp
push 3
push 2
push 1
push OFFSET $SG2672
push 600 ; 00000258H
push esi
call __snprintf
push esi
call _puts
add esp, 28 ; 0000001cH
...
The sole alloca() argument is passed via EAX (instead of pushing it into the stack) 13
. After the alloca() call, ESP
points to the block of 600 bytes and we can use it as memory for the buf array.
GCC + Intel syntax
GCC 4.4.1 does the same without calling external functions:
12In MSVC, the function implementation can be found in alloca16.asm and chkstk.asm in C:Program Files (x86)Microsoft Visual
Studio 10.0VCcrtsrcintel
13It is because alloca() is rather a compiler intrinsic ( 90 on page 869) than a normal function.
One of the reasons we need a separate function instead of just a couple of instructions in the code, is because the MSVC14 alloca() implementation also
has code which reads from the memory just allocated, in order to let the OS map physical memory to this VM15 region.
25
CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR?
Listing 5.2: GCC 4.7.3
.LC0:
.string "hi! %d, %d, %dn"
f:
push ebp
mov ebp, esp
push ebx
sub esp, 660
lea ebx, [esp+39]
and ebx, -16 ; align pointer by 16-bit border
mov DWORD PTR [esp], ebx ; s
mov DWORD PTR [esp+20], 3
mov DWORD PTR [esp+16], 2
mov DWORD PTR [esp+12], 1
mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %dn"
mov DWORD PTR [esp+4], 600 ; maxlen
call _snprintf
mov DWORD PTR [esp], ebx ; s
call puts
mov ebx, DWORD PTR [ebp-4]
leave
ret
GCC + AT&T syntax
Let’s see the same code, but in AT&T syntax:
Listing 5.3: GCC 4.7.3
.LC0:
.string "hi! %d, %d, %dn"
f:
pushl %ebp
movl %esp, %ebp
pushl %ebx
subl $660, %esp
leal 39(%esp), %ebx
andl $-16, %ebx
movl %ebx, (%esp)
movl $3, 20(%esp)
movl $2, 16(%esp)
movl $1, 12(%esp)
movl $.LC0, 8(%esp)
movl $600, 4(%esp)
call _snprintf
movl %ebx, (%esp)
call puts
movl -4(%ebp), %ebx
leave
ret
The code is the same as in the previous listing.
By the way, movl $3, 20(%esp) corresponds to mov DWORD PTR [esp+20], 3 in Intel-syntax. In AT&T syntax
when addressing memory using register+offset format, it is notated as offset(%register).
5.2.5 (Windows) SEH
SEH16
records are also stored on the stack (if they present)..
Read more about it: ( 68.3 on page 692).
5.2.6 Buffer overflow protection
More about it here ( 18.2 on page 264).
16Structured Exception Handling : 68.3 on page 692
26
CHAPTER 5. STACK 5.3. TYPICAL STACK LAYOUT
5.3 Typical stack layout
A typical stack layout in a 32-bit environment at the start of a function, before the first instruction execution looks like this:
… …
ESP-0xC local variable #2, marked in IDA as var_8
ESP-8 local variable #1, marked in IDA as var_4
ESP-4 saved value of EBP
ESP return address
ESP+4 argument#1, marked in IDA as arg_0
ESP+8 argument#2, marked in IDA as arg_4
ESP+0xC argument#3, marked in IDA as arg_8
… …
5.4 Noise in stack
Often in this book I write about “noise” or “garbage” values in stack or memory. Where do they come from? These are what
was left in there after other functions’ executions. Short example:
#include <stdio.h>
void f1()
{
int a=1, b=2, c=3;
};
void f2()
{
int a, b, c;
printf ("%d, %d, %dn", a, b, c);
};
int main()
{
f1();
f2();
};
Compiling…
Listing 5.4: Non-optimizing MSVC 2010
$SG2752 DB '%d, %d, %d', 0aH, 00H
_c$ = -12 ; size = 4
_b$ = -8 ; size = 4
_a$ = -4 ; size = 4
_f1 PROC
push ebp
mov ebp, esp
sub esp, 12
mov DWORD PTR _a$[ebp], 1
mov DWORD PTR _b$[ebp], 2
mov DWORD PTR _c$[ebp], 3
mov esp, ebp
pop ebp
ret 0
_f1 ENDP
_c$ = -12 ; size = 4
_b$ = -8 ; size = 4
_a$ = -4 ; size = 4
_f2 PROC
push ebp
mov ebp, esp
sub esp, 12
mov eax, DWORD PTR _c$[ebp]
push eax
mov ecx, DWORD PTR _b$[ebp]
27
CHAPTER 5. STACK 5.4. NOISE IN STACK
push ecx
mov edx, DWORD PTR _a$[ebp]
push edx
push OFFSET $SG2752 ; '%d, %d, %d'
call DWORD PTR __imp__printf
add esp, 16
mov esp, ebp
pop ebp
ret 0
_f2 ENDP
_main PROC
push ebp
mov ebp, esp
call _f1
call _f2
xor eax, eax
pop ebp
ret 0
_main ENDP
The compiler will grumble a little bit…
c:Polygonc>cl st.c /Fast.asm /MD
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
st.c
c:polygoncst.c(11) : warning C4700: uninitialized local variable 'c' used
c:polygoncst.c(11) : warning C4700: uninitialized local variable 'b' used
c:polygoncst.c(11) : warning C4700: uninitialized local variable 'a' used
Microsoft (R) Incremental Linker Version 10.00.40219.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:st.exe
st.obj
But when I run the compiled program…
c:Polygonc>st
1, 2, 3
Oh, what a weird thing! We did not set any variables in f2(). These are “ghosts” values, which are still in the stack.
28
CHAPTER 5. STACK 5.4. NOISE IN STACK
Let’s load the example into OllyDbg:
Figure 5.1: OllyDbg: f1()
When f1() assigns the variables a, b and c , their values are stored at the address 0x14F860 and so on.
29
CHAPTER 5. STACK 5.5. EXERCISES
And when f2() executes:
Figure 5.2: OllyDbg: f2()
... a, b and c of f2() are located at the same addresses! No one has overwritten the values yet, so at that point they
are still untouched.
So, for this weird situation, several functions has to be called one after another and SP has to be the same at each function
entry (i.e., they has same number of arguments). Then the local variables will be located at the same positions in the stack.
Summarizing, all values in the stack (and memory cells in general) have values left there from previous function execu-
tions. They are not random in the strict sense, but rather have unpredictable values.
Is there other option? It probably would be possible to clear portions of the stack before each function execution, but
that’s too much extra (and unnecessary) work.
5.5 Exercises
5.5.1 Exercise #1
If we compile this piece of code in MSVC and run it, three numbers are printed. Where do they come from? Where they come
from if you compile it in MSVC with optimization (/Ox)? Why is the situation completely different if we compile with GCC?
#include <stdio.h>
int main()
{
printf ("%d, %d, %dn");
return 0;
};
Answer: G.1.1 on page 954.
5.5.2 Exercise #2
What does this code do?
Listing 5.5: Optimizing MSVC 2010
$SG3103 DB '%d', 0aH, 00H
_main PROC
push 0
call DWORD PTR __imp___time64
push edx
push eax
30
CHAPTER 5. STACK 5.5. EXERCISES
push OFFSET $SG3103 ; '%d'
call DWORD PTR __imp__printf
add esp, 16
xor eax, eax
ret 0
_main ENDP
Listing 5.6: Optimizing Keil 6/2013 (ARM mode)
main PROC
PUSH {r4,lr}
MOV r0,#0
BL time
MOV r1,r0
ADR r0,|L0.32|
BL __2printf
MOV r0,#0
POP {r4,pc}
ENDP
|L0.32|
DCB "%dn",0
Listing 5.7: Optimizing Keil 6/2013 (thumb mode)
main PROC
PUSH {r4,lr}
MOVS r0,#0
BL time
MOVS r1,r0
ADR r0,|L0.20|
BL __2printf
MOVS r0,#0
POP {r4,pc}
ENDP
|L0.20|
DCB "%dn",0
Listing 5.8: Optimizing GCC 4.9 (ARM64)
main:
stp x29, x30, [sp, -16]!
mov x0, 0
add x29, sp, 0
bl time
mov x1, x0
ldp x29, x30, [sp], 16
adrp x0, .LC0
add x0, x0, :lo12:.LC0
b printf
.LC0:
.string "%dn"
Listing 5.9: Optimizing GCC 4.4.5 (MIPS) (IDA)
main:
var_10 = -0x10
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
lw $t9, (time & 0xFFFF)($gp)
or $at, $zero
jalr $t9
move $a0, $zero
31
CHAPTER 5. STACK 5.5. EXERCISES
lw $gp, 0x20+var_10($sp)
lui $a0, ($LC0 >> 16) # "%dn"
lw $t9, (printf & 0xFFFF)($gp)
lw $ra, 0x20+var_4($sp)
la $a0, ($LC0 & 0xFFFF) # "%dn"
move $a1, $v0
jr $t9
addiu $sp, 0x20
$LC0: .ascii "%dn"<0> # DATA XREF: main+28
Answer: G.1.1 on page 954.
32
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS
Chapter 6
printf() with several arguments
Now let’s extend the Hello, world! ( 3 on page 6) example, replacing printf() in the main() function body with this:
#include <stdio.h>
int main()
{
printf("a=%d; b=%d; c=%d", 1, 2, 3);
return 0;
};
6.1 x86
6.1.1 x86: 3 arguments
MSVC
When we compile it with MSVC 2010 Express we get:
$SG3830 DB 'a=%d; b=%d; c=%d', 00H
...
push 3
push 2
push 1
push OFFSET $SG3830
call _printf
add esp, 16 ; 00000010H
Almost the same, but now we can see the printf() arguments are pushed onto the stack in reverse order. The first
argument is pushed last.
By the way, variables of int type in 32-bit environment have 32-bit width, that is 4 bytes.
So, we have 4 arguments here. 4 ∗ 4 = 16 —they occupy exactly 16 bytes in the stack: a 32-bit pointer to a string and 3
numbers of type int.
When the stack pointer (ESP register) has changed back by the ADD ESP, X instruction after a function call, often, the
number of function arguments could be deduced by simply dividing X by 4.
Of course, this is specific to the cdecl calling convention, and only for 32-bit environment.
See also the calling conventions section ( 64 on page 663).
In certain cases where several functions return right after one another, the compiler could merge multiple ``ADD ESP,
X'' instructions into one, after the last call:
push a1
push a2
call ...
...
push a1
call ...
...
push a1
push a2
push a3
call ...
33
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
add esp, 24
34
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
MSVC and OllyDbg
Now let’s try to load this example in OllyDbg. It is one of the most popular user-land win32 debuggers. We can compile our
example in MSVC 2012 with /MD option, which means to link with MSVCR*.DLL, so we can see the imported functions
clearly in the debugger.
Then load the executable in OllyDbg. The very first breakpoint is in ntdll.dll, press F9 (run). The second breakpoint
is in CRT-code. Now we have to find the main() function.
Find this code by scrolling the code to the very top (MSVC allocates the main() function at the very beginning of the
code section):
Figure 6.1: OllyDbg: the very start of the main() function
Click on the PUSH EBP instruction, press F2 (set breakpoint) and press F9 (run). We need to perform these actions in
order to skip CRT-code, because we aren’t really interested in it yet.
35
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
Press F8 (step over) 6 times, i.e., skip 6 instructions:
Figure 6.2: OllyDbg: before printf() execution
Now the PC points to the CALL printf instruction. OllyDbg, like other debuggers, highlights the value of the registers
which were changed. So each time you press F8, EIP changes and its value is displayed in red. ESP changes as well, because
the arguments values are pushed into the stack.
Where are the values in the stack? Take a look at the right/bottom debugger window:
Figure 6.3: OllyDbg: stack after the argument values have been pushed (The red rectangular border was added by me in a
graphics editor)
We can see 3 columns there: address in the stack, value in the stack and some additional OllyDbg comments. OllyDbg
understands printf()-like strings, so it reports the string here and the 3 values attached to it.
It is possible to right-click on the format string, click on “Follow in dump”, and the format string will appear in the
debugger left-bottom window, which always displays some part of the memory. These memory values can be edited. It is
possible to change the format string, in which case the result of our example would be different. It is not very useful in this
particular case, but it could be good as an exercise so you start building a feel of how everything works here.
36
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
Press F8 (step over).
We see the following output in the console:
Figure 6.4: printf() function executed
Let’s see how the registers and stack state have changed:
Figure 6.5: OllyDbg: after printf() execution
Register EAX now contains 0xD (13). That is correct, since printf() returns the number of characters printed. The EIP
value has changed: indeed, now it contains the address of the instruction coming after CALL printf. ECX and EDX values
have changed as well. Apparently, the printf() function’s hidden machinery used them for its own needs.
A very important fact is that neither the ESP value, nor the stack state have been changed! We clearly see that the
format string and corresponding 3 values are still there. This is indeed the cdecl calling convention behaviour: callee does
not return ESP back to its previous value. The caller is responsible to do so.
37
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
Press F8 again to execute ADD ESP, 10 instruction:
Figure 6.6: OllyDbg: after ADD ESP, 10 instruction execution
ESP has changed, but the values are still in the stack! Yes, of course; no one needs to set these values to zeroes or
something like that because everything above the stack pointer (SP) is noise or garbage, and has no meaning at all. It would
be time consuming to clear the unused stack entries anyway, and no one really needs to.
GCC
Now let’s compile the same program in Linux using GCC 4.4.1 and take a look at what we have got in IDA:
main proc near
var_10 = dword ptr -10h
var_C = dword ptr -0Ch
var_8 = dword ptr -8
var_4 = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
mov eax, offset aADBDCD ; "a=%d; b=%d; c=%d"
mov [esp+10h+var_4], 3
mov [esp+10h+var_8], 2
mov [esp+10h+var_C], 1
mov [esp+10h+var_10], eax
call _printf
mov eax, 0
leave
retn
main endp
Its noticeable that the difference between the MSVC code and the GCC code is only in the way the arguments are stored
on the stack. Here the GCC is working directly with the stack without the use of PUSH/POP.
GCC and GDB
Let’s try this example also in GDB1
in Linux.
-g option instructs the compiler to include debug information in the executable file.
$ gcc 1.c -g -o 1
$ gdb 1
GNU gdb (GDB) 7.6.1-ubuntu
1GNU debugger
38
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dennis/polygon/1...done.
Listing 6.1: let’s set breakpoint on printf()
(gdb) b printf
Breakpoint 1 at 0x80482f0
Run. We don’t have the printf() function source code here, so GDB can’t show it, but may do so.
(gdb) run
Starting program: /home/dennis/polygon/1
Breakpoint 1, __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29
29 printf.c: No such file or directory.
Print 10 stack elements. The most left column contains addresses on the stack.
(gdb) x/10w $esp
0xbffff11c: 0x0804844a 0x080484f0 0x00000001 0x00000002
0xbffff12c: 0x00000003 0x08048460 0x00000000 0x00000000
0xbffff13c: 0xb7e29905 0x00000001
The very first element is the RA (0x0804844a). We can verify this by disassembling the memory at this address:
(gdb) x/5i 0x0804844a
0x804844a <main+45>: mov $0x0,%eax
0x804844f <main+50>: leave
0x8048450 <main+51>: ret
0x8048451: xchg %ax,%ax
0x8048453: xchg %ax,%ax
The two XCHG instructions are probably random garbage, which we can ignore for now.
The second element (0x080484f0) is the format string address:
(gdb) x/s 0x080484f0
0x80484f0: "a=%d; b=%d; c=%d"
Next 3 elements (1, 2, 3) are the printf() arguments. The rest of the elements could be just “garbage” on the stack,
but could also be values from other functions, their local variables, etc. We can ignore them for now.
Run “finish”. The command instructs GDB to “execute all instructions until the end of the function”. In this case: execute
till the end of printf().
(gdb) finish
Run till exit from #0 __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29
main () at 1.c:6
6 return 0;
Value returned is $2 = 13
GDB shows what printf() returned in EAX (13). This is the number of characters printed out, just like in the OllyDbg
example.
We also see “return 0;” and the information that this expression is in the 1.c file at the line 6. Indeed, the 1.c file is
located in the current directory, and GDB finds the string there. How does GDB know which C-code line is being currently
executed? This is due to the fact that the compiler, while generating debugging information, also saves a table of relations
between source code line numbers and instruction addresses. GDB is a source-level debugger, after all.
Let’s examine the registers. 13 in EAX:
(gdb) info registers
eax 0xd 13
ecx 0x0 0
edx 0x0 0
ebx 0xb7fc0000 -1208221696
esp 0xbffff120 0xbffff120
ebp 0xbffff138 0xbffff138
esi 0x0 0
39
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
edi 0x0 0
eip 0x804844a 0x804844a <main+45>
...
Let’s disassemble the current instructions. The arrow points to the instruction to be executed next.
(gdb) disas
Dump of assembler code for function main:
0x0804841d <+0>: push %ebp
0x0804841e <+1>: mov %esp,%ebp
0x08048420 <+3>: and $0xfffffff0,%esp
0x08048423 <+6>: sub $0x10,%esp
0x08048426 <+9>: movl $0x3,0xc(%esp)
0x0804842e <+17>: movl $0x2,0x8(%esp)
0x08048436 <+25>: movl $0x1,0x4(%esp)
0x0804843e <+33>: movl $0x80484f0,(%esp)
0x08048445 <+40>: call 0x80482f0 <printf@plt>
=> 0x0804844a <+45>: mov $0x0,%eax
0x0804844f <+50>: leave
0x08048450 <+51>: ret
End of assembler dump.
GDB uses AT&T syntax by default. It is possible to switch to Intel syntax:
(gdb) set disassembly-flavor intel
(gdb) disas
Dump of assembler code for function main:
0x0804841d <+0>: push ebp
0x0804841e <+1>: mov ebp,esp
0x08048420 <+3>: and esp,0xfffffff0
0x08048423 <+6>: sub esp,0x10
0x08048426 <+9>: mov DWORD PTR [esp+0xc],0x3
0x0804842e <+17>: mov DWORD PTR [esp+0x8],0x2
0x08048436 <+25>: mov DWORD PTR [esp+0x4],0x1
0x0804843e <+33>: mov DWORD PTR [esp],0x80484f0
0x08048445 <+40>: call 0x80482f0 <printf@plt>
=> 0x0804844a <+45>: mov eax,0x0
0x0804844f <+50>: leave
0x08048450 <+51>: ret
End of assembler dump.
Execute next instruction. GDB shows ending bracket, meaning, this ends the block.
(gdb) step
7 };
Let’s examine the registers after the MOV EAX, 0 instruction execution. Indeed EAX is zero at that point.
(gdb) info registers
eax 0x0 0
ecx 0x0 0
edx 0x0 0
ebx 0xb7fc0000 -1208221696
esp 0xbffff120 0xbffff120
ebp 0xbffff138 0xbffff138
esi 0x0 0
edi 0x0 0
eip 0x804844f 0x804844f <main+50>
...
6.1.2 x64: 8 arguments
To see how other arguments are passed via the stack, let’s change our example again by increasing the number of arguments
to 9 (printf() format string + 8 int variables):
#include <stdio.h>
int main()
{
printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8);
return 0;
};
40
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
MSVC
As it was mentioned earlier, the first 4 arguments has to be passed through the RCX, RDX, R8, R9 registers in Win64, while
all the rest—via the stack. That is exactly what we see here. However, the MOV instruction, instead of PUSH, is used for
preparing the stack, so the values are stored to the stack in a straightforward manner.
Listing 6.2: MSVC 2012 x64
$SG2923 DB 'a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d', 0aH, 00H
main PROC
sub rsp, 88
mov DWORD PTR [rsp+64], 8
mov DWORD PTR [rsp+56], 7
mov DWORD PTR [rsp+48], 6
mov DWORD PTR [rsp+40], 5
mov DWORD PTR [rsp+32], 4
mov r9d, 3
mov r8d, 2
mov edx, 1
lea rcx, OFFSET FLAT:$SG2923
call printf
; return 0
xor eax, eax
add rsp, 88
ret 0
main ENDP
_TEXT ENDS
END
The observant reader may ask why are 8 bytes allocated for int values, when 4 is enough? Yes, one has to remember: 8
bytes are allocated for any data type shorter than 64 bits. This is established for the convenience’s sake: it makes it easy to
calculate the address of arbitrary argument. Besides, they are all located at aligned memory addresses. It is the same in
the 32-bit environments: 4 bytes are reserved for all data types.
GCC
The picture is similar for x86-64 *NIX OS-es, except that the first 6 arguments are passed through the RDI, RSI, RDX, RCX,
R8, R9 registers. All the rest—via the stack. GCC generates the code storing the string pointer into EDI instead of RDI—we
noted that previously: 3.2.2 on page 10.
We also noted earlier that the EAX register has been cleared before a printf() call: 3.2.2 on page 10.
Listing 6.3: Optimizing GCC 4.4.6 x64
.LC0:
.string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn"
main:
sub rsp, 40
mov r9d, 5
mov r8d, 4
mov ecx, 3
mov edx, 2
mov esi, 1
mov edi, OFFSET FLAT:.LC0
xor eax, eax ; number of vector registers passed
mov DWORD PTR [rsp+16], 8
mov DWORD PTR [rsp+8], 7
mov DWORD PTR [rsp], 6
call printf
; return 0
xor eax, eax
add rsp, 40
ret
41
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86
GCC + GDB
Let’s try this example in GDB.
$ gcc -g 2.c -o 2
$ gdb 2
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dennis/polygon/2...done.
Listing 6.4: let’s set the breakpoint to printf(), and run
(gdb) b printf
Breakpoint 1 at 0x400410
(gdb) run
Starting program: /home/dennis/polygon/2
Breakpoint 1, __printf (format=0x400628 "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn") at ⤦
printf.c:29
29 printf.c: No such file or directory.
Registers RSI/RDX/RCX/R8/R9 have the expected values. RIP has the address of the very first instruction of the
printf() function.
(gdb) info registers
rax 0x0 0
rbx 0x0 0
rcx 0x3 3
rdx 0x2 2
rsi 0x1 1
rdi 0x400628 4195880
rbp 0x7fffffffdf60 0x7fffffffdf60
rsp 0x7fffffffdf38 0x7fffffffdf38
r8 0x4 4
r9 0x5 5
r10 0x7fffffffdce0 140737488346336
r11 0x7ffff7a65f60 140737348263776
r12 0x400440 4195392
r13 0x7fffffffe040 140737488347200
r14 0x0 0
r15 0x0 0
rip 0x7ffff7a65f60 0x7ffff7a65f60 <__printf>
...
Listing 6.5: let’s inspect the format string
(gdb) x/s $rdi
0x400628: "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn"
Let’s dump the stack with the x/g command this time—g stands for giant words, i.e., 64-bit words.
(gdb) x/10g $rsp
0x7fffffffdf38: 0x0000000000400576 0x0000000000000006
0x7fffffffdf48: 0x0000000000000007 0x00007fff00000008
0x7fffffffdf58: 0x0000000000000000 0x0000000000000000
0x7fffffffdf68: 0x00007ffff7a33de5 0x0000000000000000
0x7fffffffdf78: 0x00007fffffffe048 0x0000000100000000
The very first stack element, just like in the previous case, is the RA. 3 values are also passed through the stack: 6, 7,
8. We also see that 8 is passed with the high 32-bits not cleared: 0x00007fff00000008. That’s OK, because the values
have int type, which is 32-bit. So, the high register or stack element part may contain “random garbage”.
If you take a look at where the control will return after the printf() execution, GDB will show the entire main()
function:
42
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM
(gdb) set disassembly-flavor intel
(gdb) disas 0x0000000000400576
Dump of assembler code for function main:
0x000000000040052d <+0>: push rbp
0x000000000040052e <+1>: mov rbp,rsp
0x0000000000400531 <+4>: sub rsp,0x20
0x0000000000400535 <+8>: mov DWORD PTR [rsp+0x10],0x8
0x000000000040053d <+16>: mov DWORD PTR [rsp+0x8],0x7
0x0000000000400545 <+24>: mov DWORD PTR [rsp],0x6
0x000000000040054c <+31>: mov r9d,0x5
0x0000000000400552 <+37>: mov r8d,0x4
0x0000000000400558 <+43>: mov ecx,0x3
0x000000000040055d <+48>: mov edx,0x2
0x0000000000400562 <+53>: mov esi,0x1
0x0000000000400567 <+58>: mov edi,0x400628
0x000000000040056c <+63>: mov eax,0x0
0x0000000000400571 <+68>: call 0x400410 <printf@plt>
0x0000000000400576 <+73>: mov eax,0x0
0x000000000040057b <+78>: leave
0x000000000040057c <+79>: ret
End of assembler dump.
Let’s finish executing printf(), execute the instruction zeroing EAX, and note that the EAX register has a value of
exactly zero. RIP now points to the LEAVE instruction, i.e., the penultimate one in the main() function.
(gdb) finish
Run till exit from #0 __printf (format=0x400628 "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%⤦
dn") at printf.c:29
a=1; b=2; c=3; d=4; e=5; f=6; g=7; h=8
main () at 2.c:6
6 return 0;
Value returned is $1 = 39
(gdb) next
7 };
(gdb) info registers
rax 0x0 0
rbx 0x0 0
rcx 0x26 38
rdx 0x7ffff7dd59f0 140737351866864
rsi 0x7fffffd9 2147483609
rdi 0x0 0
rbp 0x7fffffffdf60 0x7fffffffdf60
rsp 0x7fffffffdf40 0x7fffffffdf40
r8 0x7ffff7dd26a0 140737351853728
r9 0x7ffff7a60134 140737348239668
r10 0x7fffffffd5b0 140737488344496
r11 0x7ffff7a95900 140737348458752
r12 0x400440 4195392
r13 0x7fffffffe040 140737488347200
r14 0x0 0
r15 0x0 0
rip 0x40057b 0x40057b <main+78>
...
6.2 ARM
6.2.1 ARM: 3 arguments
ARM’s traditional scheme for passing arguments (calling convention) behaves as follows: the first 4 arguments are passed
through the R0-R3 registers; the remaining arguments via the stack. This resembles the arguments passing scheme in
fastcall ( 64.3 on page 664) or win64 ( 64.5.1 on page 665).
32-bit ARM
Non-optimizing Keil 6/2013 (ARM mode)
43
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM
Listing 6.6: Non-optimizing Keil 6/2013 (ARM mode)
.text:00000000 main
.text:00000000 10 40 2D E9 STMFD SP!, {R4,LR}
.text:00000004 03 30 A0 E3 MOV R3, #3
.text:00000008 02 20 A0 E3 MOV R2, #2
.text:0000000C 01 10 A0 E3 MOV R1, #1
.text:00000010 08 00 8F E2 ADR R0, aADBDCD ; "a=%d; b=%d; c=%d"
.text:00000014 06 00 00 EB BL __2printf
.text:00000018 00 00 A0 E3 MOV R0, #0 ; return 0
.text:0000001C 10 80 BD E8 LDMFD SP!, {R4,PC}
So, the first 4 arguments are passed via the R0-R3 registers in this order: a pointer to the printf() format string in
R0, then 1 in R1, 2 in R2 and 3 in R3.
The instruction at 0x18 writes 0 to R0 —this is return 0 C-statement.
There is nothing unusual so far.
Optimizing Keil 6/2013 generates the same code.
Optimizing Keil 6/2013 (thumb mode)
Listing 6.7: Optimizing Keil 6/2013 (thumb mode)
.text:00000000 main
.text:00000000 10 B5 PUSH {R4,LR}
.text:00000002 03 23 MOVS R3, #3
.text:00000004 02 22 MOVS R2, #2
.text:00000006 01 21 MOVS R1, #1
.text:00000008 02 A0 ADR R0, aADBDCD ; "a=%d; b=%d; c=%d"
.text:0000000A 00 F0 0D F8 BL __2printf
.text:0000000E 00 20 MOVS R0, #0
.text:00000010 10 BD POP {R4,PC}
There is no significant difference from the non-optimized code for ARM mode.
Optimizing Keil 6/2013 (ARM mode) + let’s remove return
Let’s rework example slightly by removing return 0:
#include <stdio.h>
void main()
{
printf("a=%d; b=%d; c=%d", 1, 2, 3);
};
The result is somewhat unusual:
Listing 6.8: Optimizing Keil 6/2013 (ARM mode)
.text:00000014 main
.text:00000014 03 30 A0 E3 MOV R3, #3
.text:00000018 02 20 A0 E3 MOV R2, #2
.text:0000001C 01 10 A0 E3 MOV R1, #1
.text:00000020 1E 0E 8F E2 ADR R0, aADBDCD ; "a=%d; b=%d; c=%dn"
.text:00000024 CB 18 00 EA B __2printf
This is the optimized (-O3) version for ARM mode and this time we see B as the last instruction instead of the familiar
BL. Another difference between this optimized version and the previous one (compiled without optimization) is the lack
of function prologue and epilogue (instructions preserving the R0 and LR registers values). The B instruction just jumps to
another address, without any manipulation of the LR register, similar to JMP in x86. Why does it work? Because this code
is, in fact, effectively equivalent to the previous. There are two main reasons: 1) neither the stack nor SP (the stack pointer)
is modified; 2) the call to printf() is the last instruction, so there is nothing going on afterwards. On completion, the
printf() function simply returns the control to the address stored in LR. Since the LR currently stores the address of
the point from where our function was called then the control from printf() will be returned to that point. Therefore
we do not need to save LR because we do not need to modify LR. And we do not need to modify LR because there are no
other function calls except printf(). Furthermore, after this call we do not to do anything else! That is the reason such
optimization is possible.
This optimization is often used in functions where the last statement is a call to another function.
A similar example is presented here: 13.1.1 on page 141.
44
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM
ARM64
Non-optimizing GCC (Linaro) 4.9
Listing 6.9: Non-optimizing GCC (Linaro) 4.9
.LC1:
.string "a=%d; b=%d; c=%d"
f2:
; save FP and LR in stack frame:
stp x29, x30, [sp, -16]!
; set stack frame (FP=SP):
add x29, sp, 0
adrp x0, .LC1
add x0, x0, :lo12:.LC1
mov w1, 1
mov w2, 2
mov w3, 3
bl printf
mov w0, 0
; restore FP and LR
ldp x29, x30, [sp], 16
ret
The first instruction STP (Store Pair) saves FP (X29) and LR (X30) in the stack. The second ADD X29, SP, 0 instruction
forms the stack frame. It is just writing the value of SP into X29.
Next, we see the familiar ADRP/ADD instruction pair, which forms a pointer to the string.
%d in printf() string format is a 32-bit int, so the 1, 2 and 3 are loaded into 32-bit register parts.
Optimizing GCC (Linaro) 4.9 generates the same code.
6.2.2 ARM: 8 arguments
Let’s use again the example with 9 arguments from the previous section: 6.1.2 on page 40.
#include <stdio.h>
int main()
{
printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8);
return 0;
};
Optimizing Keil 6/2013: ARM mode
.text:00000028 main
.text:00000028
.text:00000028 var_18 = -0x18
.text:00000028 var_14 = -0x14
.text:00000028 var_4 = -4
.text:00000028
.text:00000028 04 E0 2D E5 STR LR, [SP,#var_4]!
.text:0000002C 14 D0 4D E2 SUB SP, SP, #0x14
.text:00000030 08 30 A0 E3 MOV R3, #8
.text:00000034 07 20 A0 E3 MOV R2, #7
.text:00000038 06 10 A0 E3 MOV R1, #6
.text:0000003C 05 00 A0 E3 MOV R0, #5
.text:00000040 04 C0 8D E2 ADD R12, SP, #0x18+var_14
.text:00000044 0F 00 8C E8 STMIA R12, {R0-R3}
.text:00000048 04 00 A0 E3 MOV R0, #4
.text:0000004C 00 00 8D E5 STR R0, [SP,#0x18+var_18]
.text:00000050 03 30 A0 E3 MOV R3, #3
.text:00000054 02 20 A0 E3 MOV R2, #2
.text:00000058 01 10 A0 E3 MOV R1, #1
.text:0000005C 6E 0F 8F E2 ADR R0, aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g⤦
=%"...
.text:00000060 BC 18 00 EB BL __2printf
.text:00000064 14 D0 8D E2 ADD SP, SP, #0x14
.text:00000068 04 F0 9D E4 LDR PC, [SP+4+var_4],#4
45
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM
This code can be divided into several parts:
• Function prologue:
The very first ``STR LR, [SP,#var_4]!'' instruction saves LR on the stack, because we are going to use
this register for the printf() call. Exclamation mark at the end indicates pre-index. This implies that SP is to be
decreased by 4 first, and then LR will be saved at the address stored in SP. This is similar to PUSH in x86. Read more
about it at: 28.2 on page 445.
The second ``SUB SP, SP, #0x14'' instruction decreases SP (the stack pointer) in order to allocate 0x14 (20)
bytes on the stack. Indeed, we need to pass 5 32-bit values via the stack to the printf() function, and each one
occupies 4 bytes, which is exactly 5 ∗ 4 = 20. The other 4 32-bit values are to be passed through registers.
• Passing 5, 6, 7 and 8 via the stack: they are stored in the R0, R1, R2 and R3 registers respectively. Then, the ``ADD
R12, SP, #0x18+var_14'' instruction writes the stack address where these 4 variables are to be stored, into the
R12 register. var_14 is an assembly macro, equal to −0x14, created by IDA to conveniently display the code accessing
the stack. The var_? macros generated by IDA reflect local variables in the stack. So, SP + 4 is to be stored into the
R12 register. The next ``STMIA R12, R0-R3'' instruction writes registers R0-R3 contents to the memory pointed
by R12. STMIA abbreviates Store Multiple Increment After. “Increment After” implies that R12 is to be increased by 4
after each register value is written.
• Passing 4 via the stack: 4 is stored in R0 and then this value, with the help of the ``STR R0, [SP,#0x18+var_18]''
instruction is saved on the stack. var_18 is −0x18, so the offset is to be 0, thus the value from the R0 register (4) is to
be written to the address written in SP.
• Passing 1, 2 and 3 via registers:
The values of the first 3 numbers (a, b, c) (1, 2, 3 respectively) are passed through the R1, R2 and R3 registers right
before the printf() call, and the other 5 values are passed via the stack:
• printf() call.
• Function epilogue:
The ``ADD SP, SP, #0x14'' instruction restores the SP pointer back to its former value, thus cleaning the stack.
Of course, what was stored on the stack will stay there, but it will all be rewritten during the execution of subsequent
functions.
The ``LDR PC, [SP+4+var_4],#4'' instruction loads the saved LR value from the stack into the PC register,
thus causing the function to exit. There is no exclamation mark—indeed, PC is loaded first from the address stored in
SP (4 + var_4 = 4 + (−4) = 0, so this instruction is analogous to LDR PC, [SP],#4), and then SP is increased by 4.
This is referred as post-index2
. Why does IDA display the instruction like that? Because it wants to illustrate the stack
layout and the fact that var_4 is allocated for saving the LR value in the local stack. This instruction is somewhat
similar to POP PC in x863
.
Optimizing Keil 6/2013: thumb mode
.text:0000001C printf_main2
.text:0000001C
.text:0000001C var_18 = -0x18
.text:0000001C var_14 = -0x14
.text:0000001C var_8 = -8
.text:0000001C
.text:0000001C 00 B5 PUSH {LR}
.text:0000001E 08 23 MOVS R3, #8
.text:00000020 85 B0 SUB SP, SP, #0x14
.text:00000022 04 93 STR R3, [SP,#0x18+var_8]
.text:00000024 07 22 MOVS R2, #7
.text:00000026 06 21 MOVS R1, #6
.text:00000028 05 20 MOVS R0, #5
.text:0000002A 01 AB ADD R3, SP, #0x18+var_14
.text:0000002C 07 C3 STMIA R3!, {R0-R2}
.text:0000002E 04 20 MOVS R0, #4
.text:00000030 00 90 STR R0, [SP,#0x18+var_18]
.text:00000032 03 23 MOVS R3, #3
.text:00000034 02 22 MOVS R2, #2
.text:00000036 01 21 MOVS R1, #1
.text:00000038 A0 A0 ADR R0, aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; ⤦
g=%"...
2Read more about it: 28.2 on page 445.
3It is impossible to set IP/EIP/RIP value using POP in x86, but anyway, you get the idea, I hope.
46
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM
.text:0000003A 06 F0 D9 F8 BL __2printf
.text:0000003E
.text:0000003E loc_3E ; CODE XREF: example13_f+16
.text:0000003E 05 B0 ADD SP, SP, #0x14
.text:00000040 00 BD POP {PC}
The output is almost like in the previous example. However, this is thumb code and the values are packed into stack
differently: 8 goes first, then 5, 6, 7, and 4 goes third.
Optimizing Xcode 4.6.3 (LLVM): ARM mode
__text:0000290C _printf_main2
__text:0000290C
__text:0000290C var_1C = -0x1C
__text:0000290C var_C = -0xC
__text:0000290C
__text:0000290C 80 40 2D E9 STMFD SP!, {R7,LR}
__text:00002910 0D 70 A0 E1 MOV R7, SP
__text:00002914 14 D0 4D E2 SUB SP, SP, #0x14
__text:00002918 70 05 01 E3 MOV R0, #0x1570
__text:0000291C 07 C0 A0 E3 MOV R12, #7
__text:00002920 00 00 40 E3 MOVT R0, #0
__text:00002924 04 20 A0 E3 MOV R2, #4
__text:00002928 00 00 8F E0 ADD R0, PC, R0
__text:0000292C 06 30 A0 E3 MOV R3, #6
__text:00002930 05 10 A0 E3 MOV R1, #5
__text:00002934 00 20 8D E5 STR R2, [SP,#0x1C+var_1C]
__text:00002938 0A 10 8D E9 STMFA SP, {R1,R3,R12}
__text:0000293C 08 90 A0 E3 MOV R9, #8
__text:00002940 01 10 A0 E3 MOV R1, #1
__text:00002944 02 20 A0 E3 MOV R2, #2
__text:00002948 03 30 A0 E3 MOV R3, #3
__text:0000294C 10 90 8D E5 STR R9, [SP,#0x1C+var_C]
__text:00002950 A4 05 00 EB BL _printf
__text:00002954 07 D0 A0 E1 MOV SP, R7
__text:00002958 80 80 BD E8 LDMFD SP!, {R7,PC}
Almost the same as what we have already seen, with the exception of STMFA (Store Multiple Full Ascending) instruction,
which is a synonym of STMIB (Store Multiple Increment Before) instruction. This instruction increases the value in the
SP register and only then writes the next register value into the memory, rather than performing those two actions in the
opposite order.
Another thing that catches the eye is that the instructions are arranged seemingly random. For example, the value in the
R0 register is manipulated in three places, at addresses 0x2918, 0x2920 and 0x2928, when it would be possible to do it in
one point. However, the optimizing compiler may have its own reasons on how to order the instructions so to achieve higher
efficiency during the execution. Usually, the processor attempts to simultaneously execute instructions located side-by-side.
For example, instructions like ``MOVT R0, #0'' and ``ADD R0, PC, R0'' cannot be executed simultaneously since
they both modify the R0 register. On the other hand, ``MOVT R0, #0'' and ``MOV R2, #4'' instructions can be
executed simultaneously since the effects of their execution are not conflicting with each other. Presumably, the compiler
tries to generate code in such a manner (wherever it is possible).
Optimizing Xcode 4.6.3 (LLVM): thumb-2 mode
__text:00002BA0 _printf_main2
__text:00002BA0
__text:00002BA0 var_1C = -0x1C
__text:00002BA0 var_18 = -0x18
__text:00002BA0 var_C = -0xC
__text:00002BA0
__text:00002BA0 80 B5 PUSH {R7,LR}
__text:00002BA2 6F 46 MOV R7, SP
__text:00002BA4 85 B0 SUB SP, SP, #0x14
__text:00002BA6 41 F2 D8 20 MOVW R0, #0x12D8
__text:00002BAA 4F F0 07 0C MOV.W R12, #7
__text:00002BAE C0 F2 00 00 MOVT.W R0, #0
__text:00002BB2 04 22 MOVS R2, #4
__text:00002BB4 78 44 ADD R0, PC ; char *
__text:00002BB6 06 23 MOVS R3, #6
47
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
__text:00002BB8 05 21 MOVS R1, #5
__text:00002BBA 0D F1 04 0E ADD.W LR, SP, #0x1C+var_18
__text:00002BBE 00 92 STR R2, [SP,#0x1C+var_1C]
__text:00002BC0 4F F0 08 09 MOV.W R9, #8
__text:00002BC4 8E E8 0A 10 STMIA.W LR, {R1,R3,R12}
__text:00002BC8 01 21 MOVS R1, #1
__text:00002BCA 02 22 MOVS R2, #2
__text:00002BCC 03 23 MOVS R3, #3
__text:00002BCE CD F8 10 90 STR.W R9, [SP,#0x1C+var_C]
__text:00002BD2 01 F0 0A EA BLX _printf
__text:00002BD6 05 B0 ADD SP, SP, #0x14
__text:00002BD8 80 BD POP {R7,PC}
The output is almost the same as in the previous example, with the exception that thumb-instructions are used instead.
ARM64
Non-optimizing GCC (Linaro) 4.9
Listing 6.10: Non-optimizing GCC (Linaro) 4.9
.LC2:
.string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn"
f3:
; grab more space in stack:
sub sp, sp, #32
; save FP and LR in stack frame:
stp x29, x30, [sp,16]
; set stack frame (FP=SP):
add x29, sp, 16
adrp x0, .LC2 ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn"
add x0, x0, :lo12:.LC2
mov w1, 8 ; 9th argument
str w1, [sp] ; store 9th argument in the stack
mov w1, 1
mov w2, 2
mov w3, 3
mov w4, 4
mov w5, 5
mov w6, 6
mov w7, 7
bl printf
sub sp, x29, #16
; restore FP and LR
ldp x29, x30, [sp,16]
add sp, sp, 32
ret
The first 8 arguments are passed in X- or W-registers: [ARM13c]. A string pointer requires a 64-bit register, so it’s passed
in X0. All other values have a int 32-bit type, so they are stored in the 32-bit part of the registers (W-). The 9th argument (8)
is passed via the stack. Indeed: it’s not possible to pass large number of arguments through registers, because the number
of registers is limited.
Optimizing GCC (Linaro) 4.9 generates the same code.
6.3 MIPS
6.3.1 3 arguments
Optimizing GCC 4.4.5
The main difference with the “Hello, world!” example is that in this case printf() is called instead of puts() and 3 more
arguments are passed through the registers $5 …$7 (or $A0 …$A2).
That is why these registers are prefixed with A-, which implies they are used for function arguments passing.
Listing 6.11: Optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "a=%d; b=%d; c=%d000"
main:
48
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
; function prologue:
lui $28,%hi(__gnu_local_gp)
addiu $sp,$sp,-32
addiu $28,$28,%lo(__gnu_local_gp)
sw $31,28($sp)
; load address of printf():
lw $25,%call16(printf)($28)
; load address of the text string and set 1st argument of printf():
lui $4,%hi($LC0)
addiu $4,$4,%lo($LC0)
; set 2nd argument of printf():
li $5,1 # 0x1
; set 3rd argument of printf():
li $6,2 # 0x2
; call printf():
jalr $25
; set 4th argument of printf() (branch delay slot):
li $7,3 # 0x3
; function epilogue:
lw $31,28($sp)
; set return value to 0:
move $2,$0
; return
j $31
addiu $sp,$sp,32 ; branch delay slot
Listing 6.12: Optimizing GCC 4.4.5 (IDA)
.text:00000000 main:
.text:00000000
.text:00000000 var_10 = -0x10
.text:00000000 var_4 = -4
.text:00000000
; function prologue:
.text:00000000 lui $gp, (__gnu_local_gp >> 16)
.text:00000004 addiu $sp, -0x20
.text:00000008 la $gp, (__gnu_local_gp & 0xFFFF)
.text:0000000C sw $ra, 0x20+var_4($sp)
.text:00000010 sw $gp, 0x20+var_10($sp)
; load address of printf():
.text:00000014 lw $t9, (printf & 0xFFFF)($gp)
; load address of the text string and set 1st argument of printf():
.text:00000018 la $a0, $LC0 # "a=%d; b=%d; c=%d"
; set 2nd argument of printf():
.text:00000020 li $a1, 1
; set 3rd argument of printf():
.text:00000024 li $a2, 2
; call printf():
.text:00000028 jalr $t9
; set 4th argument of printf() (branch delay slot):
.text:0000002C li $a3, 3
; function epilogue:
.text:00000030 lw $ra, 0x20+var_4($sp)
; set return value to 0:
.text:00000034 move $v0, $zero
; return
.text:00000038 jr $ra
.text:0000003C addiu $sp, 0x20 ; branch delay slot
Non-optimizing GCC 4.4.5
Non-optimizing GCC is more verbose:
Listing 6.13: Non-optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "a=%d; b=%d; c=%d000"
main:
; function prologue:
49
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
addiu $sp,$sp,-32
sw $31,28($sp)
sw $fp,24($sp)
move $fp,$sp
lui $28,%hi(__gnu_local_gp)
addiu $28,$28,%lo(__gnu_local_gp)
; load address of the text string:
lui $2,%hi($LC0)
addiu $2,$2,%lo($LC0)
; set 1st argument of printf():
move $4,$2
; set 2nd argument of printf():
li $5,1 # 0x1
; set 3rd argument of printf():
li $6,2 # 0x2
; set 4th argument of printf():
li $7,3 # 0x3
; get address of printf():
lw $2,%call16(printf)($28)
nop
; call printf():
move $25,$2
jalr $25
nop
; function epilogue:
lw $28,16($fp)
; set return value to 0:
move $2,$0
move $sp,$fp
lw $31,28($sp)
lw $fp,24($sp)
addiu $sp,$sp,32
; return
j $31
nop
Listing 6.14: Non-optimizing GCC 4.4.5 (IDA)
.text:00000000 main:
.text:00000000
.text:00000000 var_10 = -0x10
.text:00000000 var_8 = -8
.text:00000000 var_4 = -4
.text:00000000
; function prologue:
.text:00000000 addiu $sp, -0x20
.text:00000004 sw $ra, 0x20+var_4($sp)
.text:00000008 sw $fp, 0x20+var_8($sp)
.text:0000000C move $fp, $sp
.text:00000010 la $gp, __gnu_local_gp
.text:00000018 sw $gp, 0x20+var_10($sp)
; load address of the text string:
.text:0000001C la $v0, aADBDCD # "a=%d; b=%d; c=%d"
; set 1st argument of printf():
.text:00000024 move $a0, $v0
; set 2nd argument of printf():
.text:00000028 li $a1, 1
; set 3rd argument of printf():
.text:0000002C li $a2, 2
; set 4th argument of printf():
.text:00000030 li $a3, 3
; get address of printf():
.text:00000034 lw $v0, (printf & 0xFFFF)($gp)
.text:00000038 or $at, $zero
; call printf():
.text:0000003C move $t9, $v0
.text:00000040 jalr $t9
.text:00000044 or $at, $zero ; NOP
; function epilogue:
50
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
.text:00000048 lw $gp, 0x20+var_10($fp)
; set return value to 0:
.text:0000004C move $v0, $zero
.text:00000050 move $sp, $fp
.text:00000054 lw $ra, 0x20+var_4($sp)
.text:00000058 lw $fp, 0x20+var_8($sp)
.text:0000005C addiu $sp, 0x20
; return
.text:00000060 jr $ra
.text:00000064 or $at, $zero ; NOP
6.3.2 8 arguments
Let’s use again the example with 9 arguments from the previous section: 6.1.2 on page 40.
#include <stdio.h>
int main()
{
printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8);
return 0;
};
Optimizing GCC 4.4.5
Only the first 4 arguments are passed in the $A0 …$A3 registers, the rest are passed via the stack. This is the O32 calling
convention (which is the most common one in the MIPS world). Other calling conventions (like N32) may use the registers
for different purposes.
SW abbreviates “Store Word” (from register to memory). MIPS lacks instructions for storing a value into memory, so an
instruction pair has to be used instead (LI/SW).
Listing 6.15: Optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d012000"
main:
; function prologue:
lui $28,%hi(__gnu_local_gp)
addiu $sp,$sp,-56
addiu $28,$28,%lo(__gnu_local_gp)
sw $31,52($sp)
; pass 5th argument in stack:
li $2,4 # 0x4
sw $2,16($sp)
; pass 6th argument in stack:
li $2,5 # 0x5
sw $2,20($sp)
; pass 7th argument in stack:
li $2,6 # 0x6
sw $2,24($sp)
; pass 8th argument in stack:
li $2,7 # 0x7
lw $25,%call16(printf)($28)
sw $2,28($sp)
; pass 1st argument in $a0:
lui $4,%hi($LC0)
; pass 9th argument in stack:
li $2,8 # 0x8
sw $2,32($sp)
addiu $4,$4,%lo($LC0)
; pass 2nd argument in $a1:
li $5,1 # 0x1
; pass 3rd argument in $a2:
li $6,2 # 0x2
; call printf():
jalr $25
; pass 4th argument in $a3 (branch delay slot):
li $7,3 # 0x3
51
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
; function epilogue:
lw $31,52($sp)
; set return value to 0:
move $2,$0
; return
j $31
addiu $sp,$sp,56 ; branch delay slot
Listing 6.16: Optimizing GCC 4.4.5 (IDA)
.text:00000000 main:
.text:00000000
.text:00000000 var_28 = -0x28
.text:00000000 var_24 = -0x24
.text:00000000 var_20 = -0x20
.text:00000000 var_1C = -0x1C
.text:00000000 var_18 = -0x18
.text:00000000 var_10 = -0x10
.text:00000000 var_4 = -4
.text:00000000
; function prologue:
.text:00000000 lui $gp, (__gnu_local_gp >> 16)
.text:00000004 addiu $sp, -0x38
.text:00000008 la $gp, (__gnu_local_gp & 0xFFFF)
.text:0000000C sw $ra, 0x38+var_4($sp)
.text:00000010 sw $gp, 0x38+var_10($sp)
; pass 5th argument in stack:
.text:00000014 li $v0, 4
.text:00000018 sw $v0, 0x38+var_28($sp)
; pass 6th argument in stack:
.text:0000001C li $v0, 5
.text:00000020 sw $v0, 0x38+var_24($sp)
; pass 7th argument in stack:
.text:00000024 li $v0, 6
.text:00000028 sw $v0, 0x38+var_20($sp)
; pass 8th argument in stack:
.text:0000002C li $v0, 7
.text:00000030 lw $t9, (printf & 0xFFFF)($gp)
.text:00000034 sw $v0, 0x38+var_1C($sp)
; prepare 1st argument in $a0:
.text:00000038 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d⤦
; g=%"...
; pass 9th argument in stack:
.text:0000003C li $v0, 8
.text:00000040 sw $v0, 0x38+var_18($sp)
; pass 1st argument in $a1:
.text:00000044 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%d; e=%d; f⤦
=%d; g=%"...
; pass 2nd argument in $a1:
.text:00000048 li $a1, 1
; pass 3rd argument in $a2:
.text:0000004C li $a2, 2
; call printf():
.text:00000050 jalr $t9
; pass 4th argument in $a3 (branch delay slot):
.text:00000054 li $a3, 3
; function epilogue:
.text:00000058 lw $ra, 0x38+var_4($sp)
; set return value to 0:
.text:0000005C move $v0, $zero
; return
.text:00000060 jr $ra
.text:00000064 addiu $sp, 0x38 ; branch delay slot
Non-optimizing GCC 4.4.5
Non-optimizing GCC is more verbose:
52
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS
Listing 6.17: Non-optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d012000"
main:
; function prologue:
addiu $sp,$sp,-56
sw $31,52($sp)
sw $fp,48($sp)
move $fp,$sp
lui $28,%hi(__gnu_local_gp)
addiu $28,$28,%lo(__gnu_local_gp)
lui $2,%hi($LC0)
addiu $2,$2,%lo($LC0)
; pass 5th argument in stack:
li $3,4 # 0x4
sw $3,16($sp)
; pass 6th argument in stack:
li $3,5 # 0x5
sw $3,20($sp)
; pass 7th argument in stack:
li $3,6 # 0x6
sw $3,24($sp)
; pass 8th argument in stack:
li $3,7 # 0x7
sw $3,28($sp)
; pass 9th argument in stack:
li $3,8 # 0x8
sw $3,32($sp)
; pass 1st argument in $a0:
move $4,$2
; pass 2nd argument in $a1:
li $5,1 # 0x1
; pass 3rd argument in $a2:
li $6,2 # 0x2
; pass 4th argument in $a3:
li $7,3 # 0x3
; call printf():
lw $2,%call16(printf)($28)
nop
move $25,$2
jalr $25
nop
; function epilogue:
lw $28,40($fp)
; set return value to 0:
move $2,$0
move $sp,$fp
lw $31,52($sp)
lw $fp,48($sp)
addiu $sp,$sp,56
; return
j $31
nop
Listing 6.18: Non-optimizing GCC 4.4.5 (IDA)
.text:00000000 main:
.text:00000000
.text:00000000 var_28 = -0x28
.text:00000000 var_24 = -0x24
.text:00000000 var_20 = -0x20
.text:00000000 var_1C = -0x1C
.text:00000000 var_18 = -0x18
.text:00000000 var_10 = -0x10
.text:00000000 var_8 = -8
.text:00000000 var_4 = -4
.text:00000000
; function prologue:
.text:00000000 addiu $sp, -0x38
.text:00000004 sw $ra, 0x38+var_4($sp)
53
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.4. CONCLUSION
.text:00000008 sw $fp, 0x38+var_8($sp)
.text:0000000C move $fp, $sp
.text:00000010 la $gp, __gnu_local_gp
.text:00000018 sw $gp, 0x38+var_10($sp)
.text:0000001C la $v0, aADBDCDDDEDFDGD # "a=%d; b=%d; c=%d; d=%d; e=%d; f⤦
=%d; g=%"...
; pass 5th argument in stack:
.text:00000024 li $v1, 4
.text:00000028 sw $v1, 0x38+var_28($sp)
; pass 6th argument in stack:
.text:0000002C li $v1, 5
.text:00000030 sw $v1, 0x38+var_24($sp)
; pass 7th argument in stack:
.text:00000034 li $v1, 6
.text:00000038 sw $v1, 0x38+var_20($sp)
; pass 8th argument in stack:
.text:0000003C li $v1, 7
.text:00000040 sw $v1, 0x38+var_1C($sp)
; pass 9th argument in stack:
.text:00000044 li $v1, 8
.text:00000048 sw $v1, 0x38+var_18($sp)
; pass 1st argument in $a0:
.text:0000004C move $a0, $v0
; pass 2nd argument in $a1:
.text:00000050 li $a1, 1
; pass 3rd argument in $a2:
.text:00000054 li $a2, 2
; pass 4th argument in $a3:
.text:00000058 li $a3, 3
; call printf():
.text:0000005C lw $v0, (printf & 0xFFFF)($gp)
.text:00000060 or $at, $zero
.text:00000064 move $t9, $v0
.text:00000068 jalr $t9
.text:0000006C or $at, $zero ; NOP
; function epilogue:
.text:00000070 lw $gp, 0x38+var_10($fp)
; set return value to 0:
.text:00000074 move $v0, $zero
.text:00000078 move $sp, $fp
.text:0000007C lw $ra, 0x38+var_4($sp)
.text:00000080 lw $fp, 0x38+var_8($sp)
.text:00000084 addiu $sp, 0x38
; return
.text:00000088 jr $ra
.text:0000008C or $at, $zero ; NOP
6.4 Conclusion
Here is a rough skeleton of the function call:
Listing 6.19: x86
...
PUSH 3rd argument
PUSH 2nd argument
PUSH 1st argument
CALL function
; modify stack pointer (if needed)
Listing 6.20: x64 (MSVC)
MOV RCX, 1st argument
MOV RDX, 2nd argument
MOV R8, 3rd argument
MOV R9, 4th argument
...
PUSH 5th, 6th argument, etc (if needed)
CALL function
54
CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.5. BY THE WAY
; modify stack pointer (if needed)
Listing 6.21: x64 (GCC)
MOV RDI, 1st argument
MOV RSI, 2nd argument
MOV RDX, 3rd argument
MOV RCX, 4th argument
MOV R8, 5th argument
MOV R9, 6th argument
...
PUSH 7th, 8th argument, etc (if needed)
CALL function
; modify stack pointer (if needed)
Listing 6.22: ARM
MOV R0, 1st argument
MOV R1, 2nd argument
MOV R2, 3rd argument
MOV R3, 4th argument
; pass 5th, 6th argument, etc, in stack (if needed)
BL function
; modify stack pointer (if needed)
Listing 6.23: ARM64
MOV X0, 1st argument
MOV X1, 2nd argument
MOV X2, 3rd argument
MOV X3, 4th argument
MOV X4, 5th argument
MOV X5, 6th argument
MOV X6, 7th argument
MOV X7, 8th argument
; pass 9th, 10th argument, etc, in stack (if needed)
BL CALL function
; modify stack pointer (if needed)
Listing 6.24: MIPS (O32 calling convention)
LI $4, 1st argument ; AKA $A0
LI $5, 2nd argument ; AKA $A1
LI $6, 3rd argument ; AKA $A2
LI $7, 4th argument ; AKA $A3
; pass 5th, 6th argument, etc, in stack (if needed)
LW temp_reg, address of function
JALR temp_reg
6.5 By the way
By the way, this difference between the arguments passing in x86, x64, fastcall, ARM and MIPS is a good illustration of the
fact that the CPU is oblivious to how the arguments are passed to functions. It is also possible to create a hypothetical
compiler able to pass arguments via a special structure without using stack at all.
MIPS $A0 …$A3 registers are labelled this way only for convenience (that is in the O32 calling convention). Programmers
may use any other register (well, maybe except $ZERO) to pass data or use any other calling convention.
The CPU is not aware of calling conventions whatsoever.
We may also recall how newcoming assembly language programmers passing arguments into other functions: usually
via registers, without any explicit order, or even via global variables. Of course, it works fine.
55
CHAPTER 7. SCANF()
Chapter 7
scanf()
Now let’s use scanf().
7.1 Simple example
#include <stdio.h>
int main()
{
int x;
printf ("Enter X:n");
scanf ("%d", &x);
printf ("You entered %d...n", x);
return 0;
};
OK, I agree, it is not clever to use scanf() for user interactions nowadays. I wanted, however, to illustrate passing a
pointer to a variable of type int.
7.1.1 About pointers
Pointers are one of the fundamental concepts in computer science. Often, passing a large array, structure or object as an
argument to another function is too expensive, while passing their address is much cheaper. In addition if the callee function
needs to modify something in the large array or structure received as a parameter and return back the entire structure then
the situation is close to absurd. So the simplest thing to do is to pass the address of the array or structure to the callee
function, and let it change what needs to be changed.
A pointer in C/C++ is simply an address of some memory location.
In x86, the address is represented as a 32-bit number (i.e., it is occupying 4 bytes), while in x86–64 it is a 64-bit num-
ber(occupying 8 bytes). By the way, that is the reason behind some people’s indignation related to switching to x86-64 —all
pointers in the x64-architecture require twice as much space.
It is possible to work with untyped pointers only, given some effort; e.g. the standard C function memcpy(), that copies
a block from one memory location to another, takes 2 pointers of type void* as arguments, since it is impossible to predict
the type of the data you would like to copy. Data types are not important, only the block size matters.
Pointers are also widely used when a function needs to return more than one value (we are going to get back to this
later ( 10 on page 98) ). scanf() is such a case. Besides the fact that the function needs to indicate how many values were
successfully read, it also needs to return all these values.
In C/C++ the pointer type is only needed for compile-time type checking. Internally, in the compiled code there is no
information about pointer types at all.
7.1.2 x86
MSVC
Here is what we get after compiling with MSVC 2010:
CONST SEGMENT
$SG3831 DB 'Enter X:', 0aH, 00H
$SG3832 DB '%d', 00H
56
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
$SG3833 DB 'You entered %d...', 0aH, 00H
CONST ENDS
PUBLIC _main
EXTRN _scanf:PROC
EXTRN _printf:PROC
; Function compile flags: /Odtp
_TEXT SEGMENT
_x$ = -4 ; size = 4
_main PROC
push ebp
mov ebp, esp
push ecx
push OFFSET $SG3831 ; 'Enter X:'
call _printf
add esp, 4
lea eax, DWORD PTR _x$[ebp]
push eax
push OFFSET $SG3832 ; '%d'
call _scanf
add esp, 8
mov ecx, DWORD PTR _x$[ebp]
push ecx
push OFFSET $SG3833 ; 'You entered %d...'
call _printf
add esp, 8
; return 0
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
_TEXT ENDS
x is a local variable.
According to the C/C++ standard it must be visible only in this function and not from any other external scope. Tradition-
ally, local variables are stored on the stack. There are probably other ways to allocate them, but in x86 that is the way it
is.
The goal of the instruction following the function prologue, PUSH ECX, is not to save the ECX state (notice the absence
of corresponding POP ECX at the function’s end).
In fact it allocates 4 bytes on the stack for storing the x variable.
x is to be accessed with the assistance of the _x$ macro (it equals to -4) and the EBP register pointing to the current
frame.
Over the span of the function’s execution, EBP is pointing to the current stack frame making it possible to access local
variables and function arguments via EBP+offset.
It is also possible to use ESP for the same purpose, although that is not very convenient since it changes frequently. The
value of the EBP could be perceived as a frozen state of the value in ESP at the start of the function’s execution.
Here is a typical stack frame layout in 32-bit environment:
… …
EBP-8 local variable #2, marked in IDA as var_8
EBP-4 local variable #1, marked in IDA as var_4
EBP saved value of EBP
EBP+4 return address
EBP+8 argument#1, marked in IDA as arg_0
EBP+0xC argument#2, marked in IDA as arg_4
EBP+0x10 argument#3, marked in IDA as arg_8
… …
The scanf() function in our example has two arguments.
The first one is a pointer to the string containing ``%d'' and the second is the address of the x variable.
First, the x variable’s address is loaded into the EAX register by the lea eax, DWORD PTR _x$[ebp] instruction
LEA stands for load effective address, and is often used for forming an address ( A.6.2 on page 933).
We could say that in this case LEA simply stores the sum of the EBP register value and the _x$ macro in the EAX register.
This is the same as lea eax, [ebp-4].
So, 4 is being subtracted from the EBP register value and the result is loaded in the EAX register. Next the EAX register
value is pushed into the stack and scanf() is being called.
57
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
printf() is being called after that with its first argument - a pointer to the string: ``You entered %d...n''.
The second argument is prepared with: mov ecx, [ebp-4]. The instruction stores the x variable value and not its
address, in the ECX register.
Next the value in the ECX is stored on the stack and the last printf() is being called.
58
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
7.1.3 MSVC + OllyDbg
Let’s try this example in OllyDbg. Let’s load it and keep pressing F8 (step over) until we reach our executable file instead of
ntdll.dll. Scroll up until main() appears. Click on the first instruction (PUSH EBP), press F2 (set a breakpoint), then
F9 (Run). The breakpoint will be triggered when main() begins.
Let’s trace to the point where the address of the variable x is calculated:
Figure 7.1: OllyDbg: The address of the local variable is calculated
Right-click the EAX in the registers window and then select “Follow in stack”. This address will appear in the stack
window. The red arrow, I have added, points to the variable in the local stack. At that moment this location contains some
garbage (0x6E494714). Now with the help of PUSH instruction the address of this stack element is going to be stored
to the same stack on the next position. Let’s trace with F8 until the scanf() execution completes. During the scanf()
execution, we input, for example, 123, in the console window:
Figure 7.2: User input in the console window
59
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
scanf() completed its execution already:
Figure 7.3: OllyDbg: scanf() executed
scanf() returns 1 in EAX, which implies that it has read successfully one value. If we look again at the stack element
corresponding to the local variable it now contains 0x7B (123).
60
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
Further, this value is copied from the stack to the ECX register and passed to printf():
Figure 7.4: OllyDbg: preparing the value for passing to printf()
GCC
Let’s try to compile this code in GCC 4.4.1 under Linux:
main proc near
var_20 = dword ptr -20h
var_1C = dword ptr -1Ch
var_4 = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 20h
mov [esp+20h+var_20], offset aEnterX ; "Enter X:"
call _puts
mov eax, offset aD ; "%d"
lea edx, [esp+20h+var_4]
mov [esp+20h+var_1C], edx
mov [esp+20h+var_20], eax
call ___isoc99_scanf
mov edx, [esp+20h+var_4]
mov eax, offset aYouEnteredD___ ; "You entered %d...n"
mov [esp+20h+var_1C], edx
mov [esp+20h+var_20], eax
call _printf
mov eax, 0
leave
retn
main endp
GCC replaced the printf() call with call to puts(). The reason for this was explained in ( 3.4.3 on page 14).
As in the MSVC example —the arguments are placed on the stack using the MOV instruction.
By the way
By the way, this simple example is a demonstration of the fact that compiler translates list of expressions in C/C++-block into
sequential list of instructions. There are nothing between expressions in C/C++, and so in resulting machine code, there are
nothing between, control flow slips from one expression to another.
7.1.4 x64
The picture here is similar with the difference that the registers, rather than the stack, are used for arguments passing.
61
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
MSVC
Listing 7.1: MSVC 2012 x64
_DATA SEGMENT
$SG1289 DB 'Enter X:', 0aH, 00H
$SG1291 DB '%d', 00H
$SG1292 DB 'You entered %d...', 0aH, 00H
_DATA ENDS
_TEXT SEGMENT
x$ = 32
main PROC
$LN3:
sub rsp, 56
lea rcx, OFFSET FLAT:$SG1289 ; 'Enter X:'
call printf
lea rdx, QWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG1291 ; '%d'
call scanf
mov edx, DWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG1292 ; 'You entered %d...'
call printf
; return 0
xor eax, eax
add rsp, 56
ret 0
main ENDP
_TEXT ENDS
GCC
Listing 7.2: Optimizing GCC 4.4.6 x64
.LC0:
.string "Enter X:"
.LC1:
.string "%d"
.LC2:
.string "You entered %d...n"
main:
sub rsp, 24
mov edi, OFFSET FLAT:.LC0 ; "Enter X:"
call puts
lea rsi, [rsp+12]
mov edi, OFFSET FLAT:.LC1 ; "%d"
xor eax, eax
call __isoc99_scanf
mov esi, DWORD PTR [rsp+12]
mov edi, OFFSET FLAT:.LC2 ; "You entered %d...n"
xor eax, eax
call printf
; return 0
xor eax, eax
add rsp, 24
ret
7.1.5 ARM
Optimizing Keil 6/2013 (thumb mode)
.text:00000042 scanf_main
.text:00000042
.text:00000042 var_8 = -8
62
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
.text:00000042
.text:00000042 08 B5 PUSH {R3,LR}
.text:00000044 A9 A0 ADR R0, aEnterX ; "Enter X:n"
.text:00000046 06 F0 D3 F8 BL __2printf
.text:0000004A 69 46 MOV R1, SP
.text:0000004C AA A0 ADR R0, aD ; "%d"
.text:0000004E 06 F0 CD F8 BL __0scanf
.text:00000052 00 99 LDR R1, [SP,#8+var_8]
.text:00000054 A9 A0 ADR R0, aYouEnteredD___ ; "You entered %d...n"
.text:00000056 06 F0 CB F8 BL __2printf
.text:0000005A 00 20 MOVS R0, #0
.text:0000005C 08 BD POP {R3,PC}
In order for scanf() to be able to read item it needs a parameter—pointer to an int. int is 32-bit, so we need 4 bytes to
store it somewhere in memory, and it fits exactly in a 32-bit register. A place for the local variable x is allocated in the stack
and IDA has named it var_8. It is not necessary, however, to allocate a such since SP (stack pointer) is already pointing to that
space and it can be used directly. So, SP’s value is copied to the R1 register and, together with the format-string, passed to
scanf(). Later, with the help of the LDR instruction, this value is moved from the stack to the R1 register in order to be
passed to printf().
ARM64
Listing 7.3: Non-optimizing GCC 4.9.1 ARM64
1 .LC0:
2 .string "Enter X:"
3 .LC1:
4 .string "%d"
5 .LC2:
6 .string "You entered %d...n"
7 f4:
8 ; save FP and LR in stack frame:
9 stp x29, x30, [sp, -32]!
10 ; set stack frame (FP=SP)
11 add x29, sp, 0
12 ; load pointer to the "Enter X:" string:
13 adrp x0, .LC0
14 add x0, x0, :lo12:.LC0
15 ; X0=pointer to the "Enter X:" string
16 ; print it:
17 bl puts
18 ; load pointer to the "%d" string:
19 adrp x0, .LC1
20 add x0, x0, :lo12:.LC1
21 ; find a space in stack frame for "x" variable (X1=FP+28):
22 add x1, x29, 28
23 ; X1=address of "x" variable
24 ; pass the address to scanf() and call it:
25 bl __isoc99_scanf
26 ; load 32-bit value from the variable in stack frame:
27 ldr w1, [x29,28]
28 ; W1=x
29 ; load pointer to the "You entered %d...n" string
30 ; printf() will take text string from X0 and "x" variable from X1 (or W1)
31 adrp x0, .LC2
32 add x0, x0, :lo12:.LC2
33 bl printf
34 ; return 0
35 mov w0, 0
36 ; restore FP and LR:
37 ldp x29, x30, [sp], 32
38 ret
The most interesting part is finding space for the x variable in the stack frame (line 22). The address is passed to
scanf(), which just stores the user input value in the memory at that address. This is 32-bit value of type int. The value
is fetched at line 27 and then passed to printf().
63
CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE
7.1.6 MIPS
A place in the local stack is allocated for the x variable, and it is to be referred as $sp+24. Its address is passed to scanf(),
and the user input values is loaded using the LW (“Load Word”) instruction and then passed to printf().
Listing 7.4: Optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "Enter X:000"
$LC1:
.ascii "%d000"
$LC2:
.ascii "You entered %d...012000"
main:
; function prologue:
lui $28,%hi(__gnu_local_gp)
addiu $sp,$sp,-40
addiu $28,$28,%lo(__gnu_local_gp)
sw $31,36($sp)
; call puts():
lw $25,%call16(puts)($28)
lui $4,%hi($LC0)
jalr $25
addiu $4,$4,%lo($LC0) ; branch delay slot
; call scanf():
lw $28,16($sp)
lui $4,%hi($LC1)
lw $25,%call16(__isoc99_scanf)($28)
; set 2nd argument of scanf(), $a1=$sp+24:
addiu $5,$sp,24
jalr $25
addiu $4,$4,%lo($LC1) ; branch delay slot
; call printf():
lw $28,16($sp)
; set 2nd argument of printf(),
; load word at address $sp+24:
lw $5,24($sp)
lw $25,%call16(printf)($28)
lui $4,%hi($LC2)
jalr $25
addiu $4,$4,%lo($LC2) ; branch delay slot
; function epilogue:
lw $31,36($sp)
; set return value to 0:
move $2,$0
; return:
j $31
addiu $sp,$sp,40 ; branch delay slot
IDA displays the stack layout as follows:
Listing 7.5: Optimizing GCC 4.4.5 (IDA)
.text:00000000 main:
.text:00000000
.text:00000000 var_18 = -0x18
.text:00000000 var_10 = -0x10
.text:00000000 var_4 = -4
.text:00000000
; function prologue:
.text:00000000 lui $gp, (__gnu_local_gp >> 16)
.text:00000004 addiu $sp, -0x28
.text:00000008 la $gp, (__gnu_local_gp & 0xFFFF)
.text:0000000C sw $ra, 0x28+var_4($sp)
.text:00000010 sw $gp, 0x28+var_18($sp)
; call puts():
.text:00000014 lw $t9, (puts & 0xFFFF)($gp)
.text:00000018 lui $a0, ($LC0 >> 16) # "Enter X:"
.text:0000001C jalr $t9
.text:00000020 la $a0, ($LC0 & 0xFFFF) # "Enter X:" ; branch delay slot
64
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
; call scanf():
.text:00000024 lw $gp, 0x28+var_18($sp)
.text:00000028 lui $a0, ($LC1 >> 16) # "%d"
.text:0000002C lw $t9, (__isoc99_scanf & 0xFFFF)($gp)
; set 2nd argument of scanf(), $a1=$sp+24:
.text:00000030 addiu $a1, $sp, 0x28+var_10
.text:00000034 jalr $t9 ; branch delay slot
.text:00000038 la $a0, ($LC1 & 0xFFFF) # "%d"
; call printf():
.text:0000003C lw $gp, 0x28+var_18($sp)
; set 2nd argument of printf(),
; load word at address $sp+24:
.text:00000040 lw $a1, 0x28+var_10($sp)
.text:00000044 lw $t9, (printf & 0xFFFF)($gp)
.text:00000048 lui $a0, ($LC2 >> 16) # "You entered %d...n"
.text:0000004C jalr $t9
.text:00000050 la $a0, ($LC2 & 0xFFFF) # "You entered %d...n" ; branch ⤦
delay slot
; function epilogue:
.text:00000054 lw $ra, 0x28+var_4($sp)
; set return value to 0:
.text:00000058 move $v0, $zero
; return:
.text:0000005C jr $ra
.text:00000060 addiu $sp, 0x28 ; branch delay slot
7.2 Global variables
What if the x variable from the previous example was not local but a global one? Then it would have been accessible from
any point, not only from the function body. Global variables are considered anti-pattern, but for the sake of the experiment,
we could do this.
#include <stdio.h>
// now x is global variable
int x;
int main()
{
printf ("Enter X:n");
scanf ("%d", &x);
printf ("You entered %d...n", x);
return 0;
};
7.2.1 MSVC: x86
_DATA SEGMENT
COMM _x:DWORD
$SG2456 DB 'Enter X:', 0aH, 00H
$SG2457 DB '%d', 00H
$SG2458 DB 'You entered %d...', 0aH, 00H
_DATA ENDS
PUBLIC _main
EXTRN _scanf:PROC
EXTRN _printf:PROC
; Function compile flags: /Odtp
_TEXT SEGMENT
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG2456
call _printf
65
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
add esp, 4
push OFFSET _x
push OFFSET $SG2457
call _scanf
add esp, 8
mov eax, DWORD PTR _x
push eax
push OFFSET $SG2458
call _printf
add esp, 8
xor eax, eax
pop ebp
ret 0
_main ENDP
_TEXT ENDS
In this case the x variable is defined in the _DATA segment and no memory is allocated in the local stack. It is accessed
directly, not through the stack. Uninitialized global variables take no space in the executable file (indeed, why one needs to
allocate space for variables initially set to zero?), but when someone accesses their address, the OS will allocate a block of
zeroes there1
.
Now let’s explicitly assign a value to the variable:
int x=10; // default value
We got:
_DATA SEGMENT
_x DD 0aH
...
Here we see a value 0xA of DWORD type (DD stands for DWORD = 32 bit) for this variable.
If you open the compiled .exe in IDA, you can see the x variable placed at the beginning of the _DATA segment, and after
it you can see text strings.
If you open the compiled .exe from the previous example in IDA, where the value of x was not set, you would see
something like this:
.data:0040FA80 _x dd ? ; DATA XREF: _main+10
.data:0040FA80 ; _main+22
.data:0040FA84 dword_40FA84 dd ? ; DATA XREF: _memset+1E
.data:0040FA84 ; unknown_libname_1+28
.data:0040FA88 dword_40FA88 dd ? ; DATA XREF: ___sbh_find_block+5
.data:0040FA88 ; ___sbh_free_block+2BC
.data:0040FA8C ; LPVOID lpMem
.data:0040FA8C lpMem dd ? ; DATA XREF: ___sbh_find_block+B
.data:0040FA8C ; ___sbh_free_block+2CA
.data:0040FA90 dword_40FA90 dd ? ; DATA XREF: _V6_HeapAlloc+13
.data:0040FA90 ; __calloc_impl+72
.data:0040FA94 dword_40FA94 dd ? ; DATA XREF: ___sbh_free_block+2FE
_x is marked with ? with the rest of the variables that do not need to be initialized. This implies that after loading the
.exe to the memory, a space for all these variables is to be allocated and filled with zeroes [ISO07, 6.7.8p10]. But in the .exe
file these uninitialized variables do not occupy anything. This is convenient for example when using large arrays.
1That is how a VM behaves
66
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
7.2.2 MSVC: x86 + OllyDbg
Things are even simpler here:
Figure 7.5: OllyDbg: after scanf() execution
The variable is located in the data segment. After the PUSH instruction (pushing the address of x) gets executed, the
address appears in the stack window. Right-click on that row and select “Follow in dump”. The variable will appear in the
memory window on the left.
After we have entered 123 in the console, 0x7B appears in the memory window (see the highlighted screenshot regions).
But why is the first byte 7B? Thinking logically, 00 00 00 7B should be there. The cause for this is referred as
endianness, and x86 uses little-endian. This implies that the lowest byte is written first, and the highest written last. Read
more about it at: 31 on page 453.
Back to the example, the 32-bit value is loaded from this memory address into EAX and passed to printf().
The memory address of x is 0x00C53394.
67
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
In OllyDbg we can review the process memory map (Alt-M) and we can see that this address is inside the .data PE-
segment of our program:
Figure 7.6: OllyDbg: process memory map
7.2.3 GCC: x86
The picture in Linux is near the same, with the difference that the uninitialized variables are located in the _bss segment.
In ELF file this segment has the following attributes:
; Segment type: Uninitialized
; Segment permissions: Read/Write
If you, however, initialise the variable with some value e.g. 10, it is to be placed in the _data segment, which has the
following attributes:
; Segment type: Pure data
; Segment permissions: Read/Write
7.2.4 MSVC: x64
Listing 7.6: MSVC 2012 x64
_DATA SEGMENT
COMM x:DWORD
$SG2924 DB 'Enter X:', 0aH, 00H
$SG2925 DB '%d', 00H
$SG2926 DB 'You entered %d...', 0aH, 00H
_DATA ENDS
_TEXT SEGMENT
main PROC
$LN3:
sub rsp, 40
lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X:'
call printf
lea rdx, OFFSET FLAT:x
68
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
lea rcx, OFFSET FLAT:$SG2925 ; '%d'
call scanf
mov edx, DWORD PTR x
lea rcx, OFFSET FLAT:$SG2926 ; 'You entered %d...'
call printf
; return 0
xor eax, eax
add rsp, 40
ret 0
main ENDP
_TEXT ENDS
The code is almost the same as in x86. Please note that the address of the x variable is passed to scanf() using a
LEA instruction, while the variable’s value is passed to the second printf() using a MOV instruction. ``DWORD PTR''
is a part of the assembly language (no relation to the machine code), indicating that the variable data size is 32-bit and the
MOV instruction has to be encoded accordingly.
7.2.5 ARM: Optimizing Keil 6/2013 (thumb mode)
.text:00000000 ; Segment type: Pure code
.text:00000000 AREA .text, CODE
...
.text:00000000 main
.text:00000000 PUSH {R4,LR}
.text:00000002 ADR R0, aEnterX ; "Enter X:n"
.text:00000004 BL __2printf
.text:00000008 LDR R1, =x
.text:0000000A ADR R0, aD ; "%d"
.text:0000000C BL __0scanf
.text:00000010 LDR R0, =x
.text:00000012 LDR R1, [R0]
.text:00000014 ADR R0, aYouEnteredD___ ; "You entered %d...n"
.text:00000016 BL __2printf
.text:0000001A MOVS R0, #0
.text:0000001C POP {R4,PC}
...
.text:00000020 aEnterX DCB "Enter X:",0xA,0 ; DATA XREF: main+2
.text:0000002A DCB 0
.text:0000002B DCB 0
.text:0000002C off_2C DCD x ; DATA XREF: main+8
.text:0000002C ; main+10
.text:00000030 aD DCB "%d",0 ; DATA XREF: main+A
.text:00000033 DCB 0
.text:00000034 aYouEnteredD___ DCB "You entered %d...",0xA,0 ; DATA XREF: main+14
.text:00000047 DCB 0
.text:00000047 ; .text ends
.text:00000047
...
.data:00000048 ; Segment type: Pure data
.data:00000048 AREA .data, DATA
.data:00000048 ; ORG 0x48
.data:00000048 EXPORT x
.data:00000048 x DCD 0xA ; DATA XREF: main+8
.data:00000048 ; main+10
.data:00000048 ; .data ends
So, the x variable is now global and for this reason located in another segment, namely the data segment (.data). One
could ask, why are the text strings located in the code segment (.text) and x is located right here? Because it is a variable
and by definition its value could change. Moreover it could possibly change often. The code segment might sometimes
be located in a ROM2
chip (remember, we now deal with embedded microelectronics, and memory scarcity is common here),
and changeable variables —in RAM3
. It is not very economical to store constant variables in RAM when you have ROM.
Furthermore, constant variables in RAM must be initialized, because after powering on, the RAM, obviously, contains random
information.
2Read-only memory
3Random-access memory
69
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
Moving forward, we see a pointer to the x (off_2C) variable in the code segment, and that all operations with the
variable occur via this pointer. That is because the x variable could be located somewhere far from this particular code
fragment, so its address must be saved somewhere in close proximity to the code. The LDR instruction in thumb mode can
only address variables in a range of 1020 bytes from its location, and in in ARM-mode —variables in range of ±4095 bytes.
And so the address of the x variable must be located somewhere in close proximity, because there is no guarantee that the
linker would be able to accommodate the variable somewhere nearby the code, it may well be even in an external memory
chip!
One more thing: if a variable is declared as const, the Keil compiler allocates it in the .constdata segment. Perhaps,
thereafter, the linker could place this segment in ROM too, along with the code segment.
7.2.6 ARM64
Listing 7.7: Non-optimizing GCC 4.9.1 ARM64
1 .comm x,4,4
2 .LC0:
3 .string "Enter X:"
4 .LC1:
5 .string "%d"
6 .LC2:
7 .string "You entered %d...n"
8 f5:
9 ; save FP and LR in stack frame:
10 stp x29, x30, [sp, -16]!
11 ; set stack frame (FP=SP)
12 add x29, sp, 0
13 ; load pointer to the "Enter X:" string:
14 adrp x0, .LC0
15 add x0, x0, :lo12:.LC0
16 bl puts
17 ; load pointer to the "%d" string:
18 adrp x0, .LC1
19 add x0, x0, :lo12:.LC1
20 ; form address of x global variable:
21 adrp x1, x
22 add x1, x1, :lo12:x
23 bl __isoc99_scanf
24 ; form address of x global variable again:
25 adrp x0, x
26 add x0, x0, :lo12:x
27 ; load value from memory at this address:
28 ldr w1, [x0]
29 ; load pointer to the "You entered %d...n" string:
30 adrp x0, .LC2
31 add x0, x0, :lo12:.LC2
32 bl printf
33 ; return 0
34 mov w0, 0
35 ; restore FP and LR:
36 ldp x29, x30, [sp], 16
37 ret
In this case the x variable is declared as global and its address is calculated using the ADRP/ADD instruction pair (lines
21 and 25).
7.2.7 MIPS
Uninitialized global variable
So now the x variable is global. I have compiled to executable file rather than object file and I have loaded it into IDA. IDA
displays the x variable in the .sbss ELF section (remember the “Global Pointer”? 3.5.1 on page 16), since the variable is not
initialized at the start.
Listing 7.8: Optimizing GCC 4.4.5 (IDA)
.text:004006C0 main:
.text:004006C0
.text:004006C0 var_10 = -0x10
.text:004006C0 var_4 = -4
70
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
.text:004006C0
; function prologue:
.text:004006C0 lui $gp, 0x42
.text:004006C4 addiu $sp, -0x20
.text:004006C8 li $gp, 0x418940
.text:004006CC sw $ra, 0x20+var_4($sp)
.text:004006D0 sw $gp, 0x20+var_10($sp)
; call puts():
.text:004006D4 la $t9, puts
.text:004006D8 lui $a0, 0x40
.text:004006DC jalr $t9 ; puts
.text:004006E0 la $a0, aEnterX # "Enter X:" ; branch delay slot
; call scanf():
.text:004006E4 lw $gp, 0x20+var_10($sp)
.text:004006E8 lui $a0, 0x40
.text:004006EC la $t9, __isoc99_scanf
; prepare address of x:
.text:004006F0 la $a1, x
.text:004006F4 jalr $t9 ; __isoc99_scanf
.text:004006F8 la $a0, aD # "%d" ; branch delay slot
; call printf():
.text:004006FC lw $gp, 0x20+var_10($sp)
.text:00400700 lui $a0, 0x40
; get address of x:
.text:00400704 la $v0, x
.text:00400708 la $t9, printf
; load value from "x" variable and pass it to printf() in $a1:
.text:0040070C lw $a1, (x - 0x41099C)($v0)
.text:00400710 jalr $t9 ; printf
.text:00400714 la $a0, aYouEnteredD___ # "You entered %d...n" ; branch ⤦
delay slot
; function epilogue:
.text:00400718 lw $ra, 0x20+var_4($sp)
.text:0040071C move $v0, $zero
.text:00400720 jr $ra
.text:00400724 addiu $sp, 0x20 ; branch delay slot
...
.sbss:0041099C # Segment type: Uninitialized
.sbss:0041099C .sbss
.sbss:0041099C .globl x
.sbss:0041099C x: .space 4
.sbss:0041099C
IDA reduces the amount of information, so I also made a listing using objdump and commented it:
Listing 7.9: Optimizing GCC 4.4.5 (objdump)
1 004006c0 <main>:
2 ; function prologue:
3 4006c0: 3c1c0042 lui gp,0x42
4 4006c4: 27bdffe0 addiu sp,sp,-32
5 4006c8: 279c8940 addiu gp,gp,-30400
6 4006cc: afbf001c sw ra,28(sp)
7 4006d0: afbc0010 sw gp,16(sp)
8 ; call puts():
9 4006d4: 8f998034 lw t9,-32716(gp)
10 4006d8: 3c040040 lui a0,0x40
11 4006dc: 0320f809 jalr t9
12 4006e0: 248408f0 addiu a0,a0,2288 ; branch delay slot
13 ; call scanf():
14 4006e4: 8fbc0010 lw gp,16(sp)
15 4006e8: 3c040040 lui a0,0x40
16 4006ec: 8f998038 lw t9,-32712(gp)
17 ; prepare address of x:
18 4006f0: 8f858044 lw a1,-32700(gp)
19 4006f4: 0320f809 jalr t9
20 4006f8: 248408fc addiu a0,a0,2300 ; branch delay slot
21 ; call printf():
22 4006fc: 8fbc0010 lw gp,16(sp)
71
CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES
23 400700: 3c040040 lui a0,0x40
24 ; get address of x:
25 400704: 8f828044 lw v0,-32700(gp)
26 400708: 8f99803c lw t9,-32708(gp)
27 ; load value from "x" variable and pass it to printf() in $a1:
28 40070c: 8c450000 lw a1,0(v0)
29 400710: 0320f809 jalr t9
30 400714: 24840900 addiu a0,a0,2304 ; branch delay slot
31 ; function epilogue:
32 400718: 8fbf001c lw ra,28(sp)
33 40071c: 00001021 move v0,zero
34 400720: 03e00008 jr ra
35 400724: 27bd0020 addiu sp,sp,32 ; branch delay slot
36 ; pack of NOPs used for aligning next function start on 16-byte boundary:
37 400728: 00200825 move at,at
38 40072c: 00200825 move at,at
Now we see the x variable address is read from a 64KiB data buffer using GP and adding negative offset to it (line
18). More than that, the addresses of the three external functions which are used in our example (puts(), scanf(),
printf()), are also read from the 64KiB global data buffer using GP (lines 9, 16 and 26). GP points to the middle of
the buffer, and such offset suggests that all three function’s addresses, and also the address of the x variable, are all stored
somewhere at the beginning of that buffer. That make sense, because our example is tiny.
Another thing worth mentioning is that the function ends with two NOPs (MOVE $AT,$AT — an idle instruction), in
order to align next function’s start on 16-byte boundary.
Initialized global variable
Let’s alter our example by giving the x variable a default value:
int x=10; // default value
Now IDA shows that the x variable is residing in the .data section:
Listing 7.10: Optimizing GCC 4.4.5 (IDA)
.text:004006A0 main:
.text:004006A0
.text:004006A0 var_10 = -0x10
.text:004006A0 var_8 = -8
.text:004006A0 var_4 = -4
.text:004006A0
.text:004006A0 lui $gp, 0x42
.text:004006A4 addiu $sp, -0x20
.text:004006A8 li $gp, 0x418930
.text:004006AC sw $ra, 0x20+var_4($sp)
.text:004006B0 sw $s0, 0x20+var_8($sp)
.text:004006B4 sw $gp, 0x20+var_10($sp)
.text:004006B8 la $t9, puts
.text:004006BC lui $a0, 0x40
.text:004006C0 jalr $t9 ; puts
.text:004006C4 la $a0, aEnterX # "Enter X:"
.text:004006C8 lw $gp, 0x20+var_10($sp)
; prepare high part of x address:
.text:004006CC lui $s0, 0x41
.text:004006D0 la $t9, __isoc99_scanf
.text:004006D4 lui $a0, 0x40
; add low part of x address:
.text:004006D8 addiu $a1, $s0, (x - 0x410000)
; now address of x is in $a1.
.text:004006DC jalr $t9 ; __isoc99_scanf
.text:004006E0 la $a0, aD # "%d"
.text:004006E4 lw $gp, 0x20+var_10($sp)
; get a word from memory:
.text:004006E8 lw $a1, x
; value of x is now in $a1.
.text:004006EC la $t9, printf
.text:004006F0 lui $a0, 0x40
.text:004006F4 jalr $t9 ; printf
.text:004006F8 la $a0, aYouEnteredD___ # "You entered %d...n"
.text:004006FC lw $ra, 0x20+var_4($sp)
.text:00400700 move $v0, $zero
72
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
.text:00400704 lw $s0, 0x20+var_8($sp)
.text:00400708 jr $ra
.text:0040070C addiu $sp, 0x20
...
.data:00410920 .globl x
.data:00410920 x: .word 0xA
Why not .sdata? I do not know, its possible that this depends on some GCC option. Nevertheless, now x is in .data, which
is a general memory area, and we can take a look how to work with variables there.
The variable’s address must be formed using a pair of instructions. In our case those are LUI (“Load Upper Immediate”)
and ADDIU (“Add Immediate Unsigned Word”).
Here is also the objdump listing for close inspection:
Listing 7.11: Optimizing GCC 4.4.5 (objdump)
004006a0 <main>:
4006a0: 3c1c0042 lui gp,0x42
4006a4: 27bdffe0 addiu sp,sp,-32
4006a8: 279c8930 addiu gp,gp,-30416
4006ac: afbf001c sw ra,28(sp)
4006b0: afb00018 sw s0,24(sp)
4006b4: afbc0010 sw gp,16(sp)
4006b8: 8f998034 lw t9,-32716(gp)
4006bc: 3c040040 lui a0,0x40
4006c0: 0320f809 jalr t9
4006c4: 248408d0 addiu a0,a0,2256
4006c8: 8fbc0010 lw gp,16(sp)
; prepare high part of x address:
4006cc: 3c100041 lui s0,0x41
4006d0: 8f998038 lw t9,-32712(gp)
4006d4: 3c040040 lui a0,0x40
; add low part of x address:
4006d8: 26050920 addiu a1,s0,2336
; now address of x is in $a1.
4006dc: 0320f809 jalr t9
4006e0: 248408dc addiu a0,a0,2268
4006e4: 8fbc0010 lw gp,16(sp)
; high part of x address is still in $s0.
; add low part to it and load a word from memory:
4006e8: 8e050920 lw a1,2336(s0)
; value of x is now in $a1.
4006ec: 8f99803c lw t9,-32708(gp)
4006f0: 3c040040 lui a0,0x40
4006f4: 0320f809 jalr t9
4006f8: 248408e0 addiu a0,a0,2272
4006fc: 8fbf001c lw ra,28(sp)
400700: 00001021 move v0,zero
400704: 8fb00018 lw s0,24(sp)
400708: 03e00008 jr ra
40070c: 27bd0020 addiu sp,sp,32
We see that the address is formed using LUI and ADDIU, but the high part of address is still in the $S0 register, and it is
possible to encode the offset in a LW (“Load Word”) instruction, so one single LW is enough to load a value from the variable
and pass it to printf().
Registers holding temporary data are prefixed with T-, but here we also see some prefixed with S-, the contents of which
is need to be preserved before use in other functions (i.e., “saved”). That is why the value of $S0 was set at address 0x4006cc
and was used again at address 0x4006e8, after the scanf() call. The scanf() function does not change its value.
7.3 scanf() result checking
As I noted before, it is slightly old-fashioned to use scanf() today. But if we have to, we need to at least check if scanf()
finishes correctly without an error.
#include <stdio.h>
int main()
{
73
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
int x;
printf ("Enter X:n");
if (scanf ("%d", &x)==1)
printf ("You entered %d...n", x);
else
printf ("What you entered? Huh?n");
return 0;
};
By standard, the scanf()4
function returns the number of fields it has successfully read.
In our case, if everything goes fine and the user enters a number scanf() returns 1, or in case of error (or EOF5
) - 0.
I have added some C code to check the scanf() return value and print error message in case of an error.
This works as expected:
C:...>ex3.exe
Enter X:
123
You entered 123...
C:...>ex3.exe
Enter X:
ouch
What you entered? Huh?
7.3.1 MSVC: x86
Here is what we get in the assembly output (MSVC 2010):
lea eax, DWORD PTR _x$[ebp]
push eax
push OFFSET $SG3833 ; '%d', 00H
call _scanf
add esp, 8
cmp eax, 1
jne SHORT $LN2@main
mov ecx, DWORD PTR _x$[ebp]
push ecx
push OFFSET $SG3834 ; 'You entered %d...', 0aH, 00H
call _printf
add esp, 8
jmp SHORT $LN1@main
$LN2@main:
push OFFSET $SG3836 ; 'What you entered? Huh?', 0aH, 00H
call _printf
add esp, 4
$LN1@main:
xor eax, eax
The Caller function (main()) needs the callee function (scanf()) result, so the callee returns it in the EAX register.
We check it with the help of the instruction CMP EAX, 1 (CoMPare). In other words, we compare the value in the EAX
register with 1.
A JNE conditional jump follows the CMP instruction. JNE stands for Jump if Not Equal.
So, if the value in the EAX register is not equal to 1, the CPU will pass the execution to the address mentioned in the
JNE operand, in our case $LN2@main. Passing the control to this address results in the CPU executing printf() with
the argument ``What you entered? Huh?''. But if everything is fine, the conditional jump is not be be taken, and
another printf() call is to be executed, with two arguments: 'You entered %d...' and the value of x.
Since in this case the second printf() has not to be executed, there is a JMP preceding it (unconditional jump). It passes
the control to the point after the second printf() and just before the XOR EAX, EAX instruction, which implements
return 0.
So, it could be said that comparing a value with another is usually implemented by CMP/Jcc instruction pair, where cc is
condition code. CMP compares two values and sets processor flags6
. Jcc checks those flags and decides to either pass the
control to the specified address or not.
4scanf, wscanf: MSDN
5End of file
6x86 flags, see also: wikipedia.
74
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
This could sound paradoxical, but the CMP instruction is in fact SUB (subtract). All arithmetic instructions set processor
flags, not just CMP. If we compare 1 and 1, 1 − 1 is 0 so the ZF flag would be set (meaning that the last result was 0). In no
other circumstances ZF can be set, except when the operands are equal. JNE checks only the ZF flag and jumps only if it
is not set. JNE is in fact a synonym for JNZ (Jump if Not Zero). Assembler translates both JNE and JNZ instructions into the
same opcode. So, the CMP instruction can be replaced with a SUB instruction and almost everything will be fine, with the
difference that SUB alters the value of the first operand. CMP is SUB without saving the result.
7.3.2 MSVC: x86: IDA
It is time to run IDA and try to do something in it. By the way, for beginners it is good idea to use /MD option in MSVC,
which means that all these standard functions are not be linked with the executable file, but are to be imported from the
MSVCR*.DLL file instead. Thus it will be easier to see which standard function are used and where.
While analysing code in IDA, it is very helpful to leave notes for oneself (and others). In instance, analysing this example,
we see that JNZ is to be triggered in case of an error. So it is possible to move the cursor to the label, press “n” and rename
it to “error”. Create another label—into “exit”. Here is my result:
.text:00401000 _main proc near
.text:00401000
.text:00401000 var_4 = dword ptr -4
.text:00401000 argc = dword ptr 8
.text:00401000 argv = dword ptr 0Ch
.text:00401000 envp = dword ptr 10h
.text:00401000
.text:00401000 push ebp
.text:00401001 mov ebp, esp
.text:00401003 push ecx
.text:00401004 push offset Format ; "Enter X:n"
.text:00401009 call ds:printf
.text:0040100F add esp, 4
.text:00401012 lea eax, [ebp+var_4]
.text:00401015 push eax
.text:00401016 push offset aD ; "%d"
.text:0040101B call ds:scanf
.text:00401021 add esp, 8
.text:00401024 cmp eax, 1
.text:00401027 jnz short error
.text:00401029 mov ecx, [ebp+var_4]
.text:0040102C push ecx
.text:0040102D push offset aYou ; "You entered %d...n"
.text:00401032 call ds:printf
.text:00401038 add esp, 8
.text:0040103B jmp short exit
.text:0040103D
.text:0040103D error: ; CODE XREF: _main+27
.text:0040103D push offset aWhat ; "What you entered? Huh?n"
.text:00401042 call ds:printf
.text:00401048 add esp, 4
.text:0040104B
.text:0040104B exit: ; CODE XREF: _main+3B
.text:0040104B xor eax, eax
.text:0040104D mov esp, ebp
.text:0040104F pop ebp
.text:00401050 retn
.text:00401050 _main endp
Now it is slightly easier to understand the code. However, it is not a good idea to comment on every instruction.
You could also hide(collapse) parts of a function in IDA. To do that mark the block, then press “–” on the numerical pad
and enter the text to be displayed instead.
I have hidden two blocks and given them names:
.text:00401000 _text segment para public 'CODE' use32
.text:00401000 assume cs:_text
.text:00401000 ;org 401000h
.text:00401000 ; ask for X
.text:00401012 ; get X
.text:00401024 cmp eax, 1
.text:00401027 jnz short error
.text:00401029 ; print result
.text:0040103B jmp short exit
75
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
.text:0040103D
.text:0040103D error: ; CODE XREF: _main+27
.text:0040103D push offset aWhat ; "What you entered? Huh?n"
.text:00401042 call ds:printf
.text:00401048 add esp, 4
.text:0040104B
.text:0040104B exit: ; CODE XREF: _main+3B
.text:0040104B xor eax, eax
.text:0040104D mov esp, ebp
.text:0040104F pop ebp
.text:00401050 retn
.text:00401050 _main endp
To expand previously collapsed parts of the code, use “+” on the numerical pad.
76
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
By pressing “space”, we can see how IDA represents a function as a graph:
Figure 7.7: Graph mode in IDA
There are two arrows after each conditional jump: green and red. The green arrow points to the block which executes
if the jump is triggered, and red if otherwise.
77
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
It is possible to fold nodes in this mode and give them names as well (“group nodes”). I did it for 3 blocks:
Figure 7.8: Graph mode in IDA with 3 nodes folded
That is very useful. It could be said that a very important part of the reverse engineer’s job is to reduce the information
he/she deals with.
78
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
7.3.3 MSVC: x86 + OllyDbg
Let’s try to hack our program in OllyDbg, forcing it to think scanf() always works without error.
When an address of a local variable is passed into scanf(), the variable initially contains some random garbage, in this
case 0x6E494714:
Figure 7.9: OllyDbg: passing variable address into scanf()
79
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
While scanf() executes, in the console I enter something that is definitely not a number, like “asdasd”. scanf()
finishes with 0 in EAX, which indicates that an error has occurred:
Figure 7.10: OllyDbg: scanf() returning error
We can also check the local variable in the stack and note that it has not changed. Indeed, what would scanf() write
there? It simply did nothing except returning zero.
Let’s try to “hack” our program. Right-click on EAX, Among the options there is “Set to 1”. This is what we need.
We now have 1 in EAX, so the following check is to be executed as intended, and printf() will print the value of the
variable in the stack.
When we run the program (F9) we can see the following in the console window:
Figure 7.11: console window
Indeed, 1850296084 is a decimal representation of the number in the stack (0x6E494714)!
80
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
7.3.4 MSVC: x86 + Hiew
This can also be used as a simple example of executable file patching. We may try to patch the executable so the program
would always print the input, no matter what we enter.
Assuming that the executable is compiled against external MSVCR*.DLL (i.e., with /MD option)7
, we see the main()
function at the beginning of the .text section. Let’s open the executable in Hiew and find the beginning of the .text
section (Enter, F8, F6, Enter, Enter).
We can see this:
Figure 7.12: Hiew: main() function
Hiew finds ASCIIZ8
strings and displays them, as it does with the imported functions’ names.
7that’s what also called “dynamic linking”
8ASCII Zero (null-terminated ASCII string)
81
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
Move the cursor to address .00401027 (where the JNZ instruction, we have to bypass, is located), press F3, and then
type “9090”(, meaning two NOPs):
Figure 7.13: Hiew: replacing JNZ with two NOPs
Then press F9 (update). Now the executable is saved to the disk. It will behave as we wanted.
Two NOPs are probably not the most æsthetic approach. Another way to patch this instruction is to write just 0 to the
second opcode byte (jump offset), so that JNZ will always jump to the next instruction.
We could also do the opposite: replace first byte with EB while not touching the second byte (jump offset). We would get
an unconditional jump that is always triggered. In this case the error message would be printed every time, no matter the
input.
7.3.5 MSVC: x64
Since we work here with int-typed variables, which are still 32-bit in x86-64, we see how the 32-bit part of the registers
(prefixed with E-) are used here as well. While working with pointers, however, 64-bit register parts are used, prefixed with
R-.
Listing 7.12: MSVC 2012 x64
_DATA SEGMENT
$SG2924 DB 'Enter X:', 0aH, 00H
$SG2926 DB '%d', 00H
$SG2927 DB 'You entered %d...', 0aH, 00H
$SG2929 DB 'What you entered? Huh?', 0aH, 00H
_DATA ENDS
_TEXT SEGMENT
x$ = 32
main PROC
$LN5:
sub rsp, 56
lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X:'
82
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
call printf
lea rdx, QWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG2926 ; '%d'
call scanf
cmp eax, 1
jne SHORT $LN2@main
mov edx, DWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG2927 ; 'You entered %d...'
call printf
jmp SHORT $LN1@main
$LN2@main:
lea rcx, OFFSET FLAT:$SG2929 ; 'What you entered? Huh?'
call printf
$LN1@main:
; return 0
xor eax, eax
add rsp, 56
ret 0
main ENDP
_TEXT ENDS
END
7.3.6 ARM
ARM: Optimizing Keil 6/2013 (thumb mode)
Listing 7.13: Optimizing Keil 6/2013 (thumb mode)
var_8 = -8
PUSH {R3,LR}
ADR R0, aEnterX ; "Enter X:n"
BL __2printf
MOV R1, SP
ADR R0, aD ; "%d"
BL __0scanf
CMP R0, #1
BEQ loc_1E
ADR R0, aWhatYouEntered ; "What you entered? Huh?n"
BL __2printf
loc_1A ; CODE XREF: main+26
MOVS R0, #0
POP {R3,PC}
loc_1E ; CODE XREF: main+12
LDR R1, [SP,#8+var_8]
ADR R0, aYouEnteredD___ ; "You entered %d...n"
BL __2printf
B loc_1A
The new instructions here are CMP and BEQ9
.
CMP is analogous to the x86 instruction with the same name, it subtracts one of the arguments from the other and
updates the conditional flags if needed.
BEQ jumps to another address if the operands were equal to each other, or, if the result of the last computation was 0,
or if the Z flag is 1. It behaves as JZ in x86.
Everything else is simple: the execution flow forks in two branches, then the branches converge at the point where 0 is
written into the R0 as a function return value, and then the function ends.
ARM64
Listing 7.14: Non-optimizing GCC 4.9.1 ARM64
1 .LC0:
2 .string "Enter X:"
3 .LC1:
9(PowerPC, ARM) Branch if Equal
83
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
4 .string "%d"
5 .LC2:
6 .string "You entered %d...n"
7 .LC3:
8 .string "What you entered? Huh?"
9 f6:
10 ; save FP and LR in stack frame:
11 stp x29, x30, [sp, -32]!
12 ; set stack frame (FP=SP)
13 add x29, sp, 0
14 ; load pointer to the "Enter X:" string:
15 adrp x0, .LC0
16 add x0, x0, :lo12:.LC0
17 bl puts
18 ; load pointer to the "%d" string:
19 adrp x0, .LC1
20 add x0, x0, :lo12:.LC1
21 ; calculate address of x variable in the local stack
22 add x1, x29, 28
23 bl __isoc99_scanf
24 ; scanf() returned result in W0.
25 ; check it:
26 cmp w0, 1
27 ; BNE is Branch if Not Equal
28 ; so if W0<>0, jump to L2 will be occurred
29 bne .L2
30 ; at this moment W0=1, meaning no error
31 ; load x value from the local stack
32 ldr w1, [x29,28]
33 ; load pointer to the "You entered %d...n" string:
34 adrp x0, .LC2
35 add x0, x0, :lo12:.LC2
36 bl printf
37 ; skip the code, which print the "What you entered? Huh?" string:
38 b .L3
39 .L2:
40 ; load pointer to the "What you entered? Huh?" string:
41 adrp x0, .LC3
42 add x0, x0, :lo12:.LC3
43 bl puts
44 .L3:
45 ; return 0
46 mov w0, 0
47 ; restore FP and LR:
48 ldp x29, x30, [sp], 32
49 ret
Code flow in this case forks with the use of CMP/BNE (Branch if Not Equal) instructions pair.
7.3.7 MIPS
Listing 7.15: Optimizing GCC 4.4.5 (IDA)
.text:004006A0 main:
.text:004006A0
.text:004006A0 var_18 = -0x18
.text:004006A0 var_10 = -0x10
.text:004006A0 var_4 = -4
.text:004006A0
.text:004006A0 lui $gp, 0x42
.text:004006A4 addiu $sp, -0x28
.text:004006A8 li $gp, 0x418960
.text:004006AC sw $ra, 0x28+var_4($sp)
.text:004006B0 sw $gp, 0x28+var_18($sp)
.text:004006B4 la $t9, puts
.text:004006B8 lui $a0, 0x40
.text:004006BC jalr $t9 ; puts
.text:004006C0 la $a0, aEnterX # "Enter X:"
.text:004006C4 lw $gp, 0x28+var_18($sp)
.text:004006C8 lui $a0, 0x40
84
CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING
.text:004006CC la $t9, __isoc99_scanf
.text:004006D0 la $a0, aD # "%d"
.text:004006D4 jalr $t9 ; __isoc99_scanf
.text:004006D8 addiu $a1, $sp, 0x28+var_10 # branch delay slot
.text:004006DC li $v1, 1
.text:004006E0 lw $gp, 0x28+var_18($sp)
.text:004006E4 beq $v0, $v1, loc_40070C
.text:004006E8 or $at, $zero # branch delay slot, NOP
.text:004006EC la $t9, puts
.text:004006F0 lui $a0, 0x40
.text:004006F4 jalr $t9 ; puts
.text:004006F8 la $a0, aWhatYouEntered # "What you entered? Huh?"
.text:004006FC lw $ra, 0x28+var_4($sp)
.text:00400700 move $v0, $zero
.text:00400704 jr $ra
.text:00400708 addiu $sp, 0x28
.text:0040070C loc_40070C:
.text:0040070C la $t9, printf
.text:00400710 lw $a1, 0x28+var_10($sp)
.text:00400714 lui $a0, 0x40
.text:00400718 jalr $t9 ; printf
.text:0040071C la $a0, aYouEnteredD___ # "You entered %d...n"
.text:00400720 lw $ra, 0x28+var_4($sp)
.text:00400724 move $v0, $zero
.text:00400728 jr $ra
.text:0040072C addiu $sp, 0x28
scanf() returns the result of its work in register $V0. It is checked at address 0x004006E4 by comparing the values in
$V0 with $V1 (1 was stored in $V1 earlier, at 0x004006DC). BEQ stands for “Branch Equal”. If the two values are equal (i.e.,
success), the execution jumps to address 0x0040070C.
7.3.8 Exercise
As we can see, the JNE/JNZ instruction can be easily replaced by the JE/JZ and vice versa (or BNE by BEQ and vice versa). But
then the basic blocks must also be swapped. Try to do this in some of the examples.
85
CHAPTER 8. ACCESSING PASSED ARGUMENTS
Chapter 8
Accessing passed arguments
Now we figured out that the caller function is passing arguments to the callee via the stack. But how does the callee access
them?
Listing 8.1: simple example
#include <stdio.h>
int f (int a, int b, int c)
{
return a*b+c;
};
int main()
{
printf ("%dn", f(1, 2, 3));
return 0;
};
8.1 x86
8.1.1 MSVC
Here is what we get after compilation (MSVC 2010 Express):
Listing 8.2: MSVC 2010 Express
_TEXT SEGMENT
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_c$ = 16 ; size = 4
_f PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
imul eax, DWORD PTR _b$[ebp]
add eax, DWORD PTR _c$[ebp]
pop ebp
ret 0
_f ENDP
_main PROC
push ebp
mov ebp, esp
push 3 ; 3rd argument
push 2 ; 2nd argument
push 1 ; 1st argument
call _f
add esp, 12
push eax
push OFFSET $SG2463 ; '%d', 0aH, 00H
call _printf
add esp, 8
; return 0
86
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.1. X86
xor eax, eax
pop ebp
ret 0
_main ENDP
What we see is that the main() function pushes 3 numbers onto the stack and calls f(int,int,int). Argument
access inside f() is organized with the help of macros like: _a$ = 8, in the same way as local variables, but with positive
offsets (addressed with plus). So, we are addressing the outer side of the stack frame by adding the _a$ macro to the value
in the EBP register.
Then the value of a is stored into EAX. After IMUL instruction execution, the value in EAX is a product of the value in
EAX and the content of _b. After that, ADD adds the value in _c to EAX. The value in EAX does not need to be moved: it
is already where it must be. On returning to caller, it takes the EAX value and use it as an argument to printf().
8.1.2 MSVC + OllyDbg
Let’s illustrate this in OllyDbg. When we trace to the first instruction in f() that uses one of the arguments (first one), we
see that EBP is pointing to the stack frame, which I marked with a red rectangle. The first element of the stack frame is the
saved value of EBP, the second one is RA, the third is the first function argument, then the second and third ones. To access
the first function argument, one needs to add exactly 8 (2 32-bit words) to EBP.
OllyDbg is aware about this, so it has added comments to the stack elements like “RETURN from” and “Arg1 = …”, etc.
N.B.: Function arguments are not members of the function’s stack frame, they are rather members of the stack frame of
the caller function. Hence, OllyDbg marked “Arg” elements as members of another stack frame.
Figure 8.1: OllyDbg: inside of f() function
8.1.3 GCC
Let’s compile the same in GCC 4.4.1 and see the results in IDA:
Listing 8.3: GCC 4.4.1
public f
f proc near
arg_0 = dword ptr 8
arg_4 = dword ptr 0Ch
arg_8 = dword ptr 10h
push ebp
mov ebp, esp
mov eax, [ebp+arg_0] ; 1st argument
imul eax, [ebp+arg_4] ; 2nd argument
add eax, [ebp+arg_8] ; 3rd argument
pop ebp
retn
f endp
87
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64
public main
main proc near
var_10 = dword ptr -10h
var_C = dword ptr -0Ch
var_8 = dword ptr -8
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
mov [esp+10h+var_8], 3 ; 3rd argument
mov [esp+10h+var_C], 2 ; 2nd argument
mov [esp+10h+var_10], 1 ; 1st argument
call f
mov edx, offset aD ; "%dn"
mov [esp+10h+var_C], eax
mov [esp+10h+var_10], edx
call _printf
mov eax, 0
leave
retn
main endp
The result is almost the same with some minor differences discussed earlier.
The stack pointer is not set back after the two function calls(f and printf), because the penultimate LEAVE ( A.6.2 on
page 933) instruction takes care of this at the end.
8.2 x64
The story is a bit different in x86-64, function arguments (first 4 or first 6 of them) are passed in registers i.e. the callee reads
them from there instead of reading them from the stack.
8.2.1 MSVC
Optimizing MSVC:
Listing 8.4: Optimizing MSVC 2012 x64
$SG2997 DB '%d', 0aH, 00H
main PROC
sub rsp, 40
mov edx, 2
lea r8d, QWORD PTR [rdx+1] ; R8D=3
lea ecx, QWORD PTR [rdx-1] ; ECX=1
call f
lea rcx, OFFSET FLAT:$SG2997 ; '%d'
mov edx, eax
call printf
xor eax, eax
add rsp, 40
ret 0
main ENDP
f PROC
; ECX - 1st argument
; EDX - 2nd argument
; R8D - 3rd argument
imul ecx, edx
lea eax, DWORD PTR [r8+rcx]
ret 0
f ENDP
As we can see, the compact function f() takes all its arguments from the registers. The LEA instruction here is used
for addition, apparently the compiler considered it faster than ADD. LEA is also used in the main() function to prepare the
first and third f() arguments. The compiler must have decided that this would work faster than the usual way of loading
values into a register — using MOV instruction.
Let’s take a look at the non-optimizing MSVC output:
88
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64
Listing 8.5: MSVC 2012 x64
f proc near
; shadow space:
arg_0 = dword ptr 8
arg_8 = dword ptr 10h
arg_10 = dword ptr 18h
; ECX - 1st argument
; EDX - 2nd argument
; R8D - 3rd argument
mov [rsp+arg_10], r8d
mov [rsp+arg_8], edx
mov [rsp+arg_0], ecx
mov eax, [rsp+arg_0]
imul eax, [rsp+arg_8]
add eax, [rsp+arg_10]
retn
f endp
main proc near
sub rsp, 28h
mov r8d, 3 ; 3rd argument
mov edx, 2 ; 2nd argument
mov ecx, 1 ; 1st argument
call f
mov edx, eax
lea rcx, $SG2931 ; "%dn"
call printf
; return 0
xor eax, eax
add rsp, 28h
retn
main endp
It looks somewhat puzzling because all 3 arguments from the registers are saved to the stack for some reason. This
is called “shadow space” 1
: every Win64 may (but is not required to) save all 4 register values there. This is done for two
reasons: 1) it is too lavish to allocate a whole register (or even 4 registers) for an input argument, so it will be accessed via
stack; 2) the debugger is always aware where to find the function arguments at a break 2
.
So, some large functions can save their input arguments in the “shadows space” if they need to use them during execution,
but some small functions (like ours) may not do this.
It is a caller responsibility to allocate “shadow space” in the stack.
8.2.2 GCC
Optimizing GCC generates more or less understandable code:
Listing 8.6: Optimizing GCC 4.4.6 x64
f:
; EDI - 1st argument
; ESI - 2nd argument
; EDX - 3rd argument
imul esi, edi
lea eax, [rdx+rsi]
ret
main:
sub rsp, 8
mov edx, 3
mov esi, 2
mov edi, 1
call f
mov edi, OFFSET FLAT:.LC0 ; "%dn"
mov esi, eax
xor eax, eax ; number of vector registers passed
1MSDN
2MSDN
89
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64
call printf
xor eax, eax
add rsp, 8
ret
Non-optimizing GCC:
Listing 8.7: GCC 4.4.6 x64
f:
; EDI - 1st argument
; ESI - 2nd argument
; EDX - 3rd argument
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov DWORD PTR [rbp-12], edx
mov eax, DWORD PTR [rbp-4]
imul eax, DWORD PTR [rbp-8]
add eax, DWORD PTR [rbp-12]
leave
ret
main:
push rbp
mov rbp, rsp
mov edx, 3
mov esi, 2
mov edi, 1
call f
mov edx, eax
mov eax, OFFSET FLAT:.LC0 ; "%dn"
mov esi, edx
mov rdi, rax
mov eax, 0 ; number of vector registers passed
call printf
mov eax, 0
leave
ret
There are no “shadow space” requirements in System V *NIX[Mit13], but the callee may need to save its arguments
somewhere in case of registers shortage.
8.2.3 GCC: uint64_t instead of int
Our example works with 32-bit int, that is why 32-bit register parts are used (prefixed by E-).
It can be altered slightly in order to use 64-bit values:
#include <stdio.h>
#include <stdint.h>
uint64_t f (uint64_t a, uint64_t b, uint64_t c)
{
return a*b+c;
};
int main()
{
printf ("%lldn", f(0x1122334455667788,
0x1111111122222222,
0x3333333344444444));
return 0;
};
Listing 8.8: Optimizing GCC 4.4.6 x64
f proc near
imul rsi, rdi
lea rax, [rdx+rsi]
retn
f endp
90
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.3. ARM
main proc near
sub rsp, 8
mov rdx, 3333333344444444h ; 3rd argument
mov rsi, 1111111122222222h ; 2nd argument
mov rdi, 1122334455667788h ; 1st argument
call f
mov edi, offset format ; "%lldn"
mov rsi, rax
xor eax, eax ; number of vector registers passed
call _printf
xor eax, eax
add rsp, 8
retn
main endp
The code is the same, but this time the full size registers (prefixed by R-) are used.
8.3 ARM
8.3.1 Non-optimizing Keil 6/2013 (ARM mode)
.text:000000A4 00 30 A0 E1 MOV R3, R0
.text:000000A8 93 21 20 E0 MLA R0, R3, R1, R2
.text:000000AC 1E FF 2F E1 BX LR
...
.text:000000B0 main
.text:000000B0 10 40 2D E9 STMFD SP!, {R4,LR}
.text:000000B4 03 20 A0 E3 MOV R2, #3
.text:000000B8 02 10 A0 E3 MOV R1, #2
.text:000000BC 01 00 A0 E3 MOV R0, #1
.text:000000C0 F7 FF FF EB BL f
.text:000000C4 00 40 A0 E1 MOV R4, R0
.text:000000C8 04 10 A0 E1 MOV R1, R4
.text:000000CC 5A 0F 8F E2 ADR R0, aD_0 ; "%dn"
.text:000000D0 E3 18 00 EB BL __2printf
.text:000000D4 00 00 A0 E3 MOV R0, #0
.text:000000D8 10 80 BD E8 LDMFD SP!, {R4,PC}
The main() function simply calls two other functions, with three values passed to the first one —(f()).
As I mentioned before, in ARM the first 4 values are usually passed in the first 4 registers (R0-R3).
The f() function, as it seems, uses the first 3 registers (R0-R2) as arguments.
The MLA (Multiply Accumulate) instruction multiplies its first two operands (R3 and R1), adds the third operand (R2) to
the product and stores the result into the zeroth register (R0), via which, by standard, functions return values.
Multiplication and addition at once3
(Fused multiply–add) is a very useful operation. By the way, there was no such
instruction in x86 before FMA-instructions appeared in SIMD 4
.
The very first MOV R3, R0, instruction is, apparently, redundant (a single MLA instruction could be used here instead),
the compiler has not optimized it, since this is non-optimizing compilation.
The BX instruction returns the control to the address stored in the LR register and, if necessary, switches the processor
mode from thumb to ARM or vice versa. This can be necessary since, as we can see, function f() is not aware from what
kind of code it may be called, ARM or thumb. Thus, if it gets called from thumb code, BX is not only returns control to the
calling function, but also switches the processor mode to thumb. Or not switch, if the function was called from ARM code
[ARM12, A2.3.2].
8.3.2 Optimizing Keil 6/2013 (ARM mode)
.text:00000098 f
.text:00000098 91 20 20 E0 MLA R0, R1, R0, R2
.text:0000009C 1E FF 2F E1 BX LR
And here is the f() function compiled by the Keil compiler in full optimization mode (-O3). The MOV instruction was
optimized out (or reduced) and now MLA uses all input registers and also places the result right into R0, exactly where the
calling function will read and use it.
3wikipedia: Multiply–accumulate operation
4wikipedia
91
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.3. ARM
8.3.3 Optimizing Keil 6/2013 (thumb mode)
.text:0000005E 48 43 MULS R0, R1
.text:00000060 80 18 ADDS R0, R0, R2
.text:00000062 70 47 BX LR
The MLA instruction is not available in thumb mode, so the compiler generates the code doing these two operations
(multiplication and addition) separately. First the MULS instruction multiplies R0 by R1, leaving the result in register R1.
The second instruction (ADDS) adds the result and R2 leaving the result in register R0.
8.3.4 ARM64
Optimizing GCC (Linaro) 4.9
Everything here is simple. MADD is just an instruction doing fused multiply/add (similar to the MLA we already saw). All 3
arguments are passed in the 32-bit parts of X-registers. Indeed, the argument types are 32-bit int’s. The result is returned
in W0.
Listing 8.9: Optimizing GCC (Linaro) 4.9
f:
madd w0, w0, w1, w2
ret
main:
; save FP and LR to stack frame:
stp x29, x30, [sp, -16]!
mov w2, 3
mov w1, 2
add x29, sp, 0
mov w0, 1
bl f
mov w1, w0
adrp x0, .LC7
add x0, x0, :lo12:.LC7
bl printf
; return 0
mov w0, 0
; restore FP and LR
ldp x29, x30, [sp], 16
ret
.LC7:
.string "%dn"
I also extended all data types to 64-bit uint64_t and tested:
#include <stdio.h>
#include <stdint.h>
uint64_t f (uint64_t a, uint64_t b, uint64_t c)
{
return a*b+c;
};
int main()
{
printf ("%lldn", f(0x1122334455667788,
0x1111111122222222,
0x3333333344444444));
return 0;
};
f:
madd x0, x0, x1, x2
ret
main:
mov x1, 13396
adrp x0, .LC8
stp x29, x30, [sp, -16]!
92
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.4. MIPS
movk x1, 0x27d0, lsl 16
add x0, x0, :lo12:.LC8
movk x1, 0x122, lsl 32
add x29, sp, 0
movk x1, 0x58be, lsl 48
bl printf
mov w0, 0
ldp x29, x30, [sp], 16
ret
.LC8:
.string "%lldn"
The f() function is the same, only the whole 64-bit X-registers are now used. Long 64-bit values are loaded into the
registers by parts, I have described it also here: 28.3.1 on page 445.
Non-optimizing GCC (Linaro) 4.9
The non-optimizing compiler is more redundant:
f:
sub sp, sp, #16
str w0, [sp,12]
str w1, [sp,8]
str w2, [sp,4]
ldr w1, [sp,12]
ldr w0, [sp,8]
mul w1, w1, w0
ldr w0, [sp,4]
add w0, w1, w0
add sp, sp, 16
ret
The code saves its input arguments in the local stack, in case someone (or something) in this function needs using the
W0...W2 registers. This prevents overwriting the original function arguments, which may be needed again in the future.
This is called Register Save Area. [ARM13c] The callee, however, is not obliged to save them. This is somewhat similar to
“Shadow Space”: 8.2.1 on page 89.
Why did the optimizing GCC 4.9 drop this argument saving code? Because it did some additional optimizing work and
concluded that the function arguments will not be needed in the future and also that the registers W0...W2 will not be
used.
We also see a MUL/ADD instruction pair instead of single a MADD.
8.4 MIPS
Listing 8.10: Optimizing GCC 4.4.5
.text:00000000 f:
; $a0=a
; $a1=b
; $a2=c
.text:00000000 mult $a1, $a0
.text:00000004 mflo $v0
.text:00000008 jr $ra
.text:0000000C addu $v0, $a2, $v0 ; branch delay slot
; result in $v0 upon return
.text:00000010 main:
.text:00000010
.text:00000010 var_10 = -0x10
.text:00000010 var_4 = -4
.text:00000010
.text:00000010 lui $gp, (__gnu_local_gp >> 16)
.text:00000014 addiu $sp, -0x20
.text:00000018 la $gp, (__gnu_local_gp & 0xFFFF)
.text:0000001C sw $ra, 0x20+var_4($sp)
.text:00000020 sw $gp, 0x20+var_10($sp)
; set c:
.text:00000024 li $a2, 3
93
CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.4. MIPS
; set a:
.text:00000028 li $a0, 1
.text:0000002C jal f
; set b:
.text:00000030 li $a1, 2 ; branch delay slot
; result in $v0 now
.text:00000034 lw $gp, 0x20+var_10($sp)
.text:00000038 lui $a0, ($LC0 >> 16)
.text:0000003C lw $t9, (printf & 0xFFFF)($gp)
.text:00000040 la $a0, ($LC0 & 0xFFFF)
.text:00000044 jalr $t9
; take result of f() function and pass it as a second argument to printf():
.text:00000048 move $a1, $v0 ; branch delay slot
.text:0000004C lw $ra, 0x20+var_4($sp)
.text:00000050 move $v0, $zero
.text:00000054 jr $ra
.text:00000058 addiu $sp, 0x20 ; branch delay slot
The first four function arguments are passed in four registers prefixed by A-.
There are two special registers in MIPS: HI and LO which are filled with the 64-bit result of the multiplication during the
execution of the MULT instruction. These registers are accessible only by using the MFLO and MFHI instructions. MFLO
here takes the low-part of the multiplication result and stores it into $V0.
So the high 32-bit part of the multiplication result is dropped (the HI register content is not used). Indeed: we work
with 32-bit int data types here.
Finally, ADDU (“Add Unsigned”) adds the value of the third argument to the result.
There are two different addition instructions in MIPS: ADD and ADDU. The difference between them is not related to
signedness, but to exceptions. ADD can raise an exception on overflow, which is sometimes useful5
and supported in Ada PL,
for instance. ADDU does not raise exceptions on overflow. Since C/C++ does not support this, in our example we see ADDU
instead of ADD.
The 32-bit result is left in $V0.
There is a new instruction for us in main(): JAL (“Jump and Link”). The difference between JAL and JALR is that a
relative offset is encoded in the first instruction, while JALR jumps to the absolute address stored in a register (“Jump and
Link Register”). Both f() and main() functions are located in the same object file, so the relative address of f() is known
and fixed.
5http://go.yurichev.com/17326
94
CHAPTER 9. MORE ABOUT RESULTS RETURNING
Chapter 9
More about results returning
In x86, the result of function execution is usually returned 1
in the EAX register. If it is byte type or a character (char), then
the lowest part of register EAX (AL) is used. If a function returns a float number, the FPU register ST(0) is used instead. In
ARM, the result is usually returned in the R0 register.
9.1 Attempt to use the result of a function returning void
So, what if the main() function return value was declared of type void and not int?
The so-called startup-code is calling main() roughly as follows:
push envp
push argv
push argc
call main
push eax
call exit
In other words:
exit(main(argc,argv,envp));
If you declare main() as void, nothing is to be returned explicitly (using the return statement), then something random,
that was stored in the EAX register at the end of main() becomes the sole argument of the exit() function. Most likely,
there will be a random value, left from your function execution, so the exit code of program is pseudorandom.
I can illustrate this fact. Please note that here the main() function has a void return type:
#include <stdio.h>
void main()
{
printf ("Hello, world!n");
};
Let’s compile it in Linux.
GCC 4.8.1 replaced printf() with puts() (we have seen this before: 3.4.3 on page 14) , but that’s OK, since puts()
returns the number of characters printed out, just like printf(). Please notice that EAX is not zeroed before main()’s
end. This implies that the value of EAX at the end of main() contains what puts() has left there.
Listing 9.1: GCC 4.8.1
.LC0:
.string "Hello, world!"
main:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov DWORD PTR [esp], OFFSET FLAT:.LC0
call puts
leave
ret
1See also: MSDN: Return Values (C++): MSDN
95
CHAPTER 9. MORE ABOUT RESULTS RETURNING 9.2. WHAT IF WE DO NOT USE THE FUNCTION RESULT?
Let’ s write a bash script that shows the exit status:
Listing 9.2: tst.sh
#!/bin/sh
./hello_world
echo $?
And run it:
$ tst.sh
Hello, world!
14
14 is the number of characters printed.
9.2 What if we do not use the function result?
printf() returns the count of characters successfully output, but the result of this function is rarely used in practice. It is
also possible to call a function whose essence is in returning a value, and not use it:
int f()
{
// skip first 3 random values
rand();
rand();
rand();
// and use 4th
return rand();
};
The result of the rand() function is left in EAX, in all four cases. But in the first 3 cases, the value in EAX is just thrown
away.
9.3 Returning a structure
Let’s go back to the fact that the return value is left in the EAX register. That is why old C compilers cannot create functions
capable of returning something that does not fit in one register (usually int), but if one needs it, one have to return information
via pointers passed as function’s arguments. So, usually, if a function needs to return several values, it returns only one,
and all the rest—via pointers. Now it has become possible to return, let’s say, an entire structure, but that is still not very
popular. If a function has to return a large structure, the caller must allocate it and pass a pointer to it via the first argument,
transparently for the programmer. That is almost the same as to pass a pointer in the first argument manually, but the
compiler hides it.
Small example:
struct s
{
int a;
int b;
int c;
};
struct s get_some_values (int a)
{
struct s rt;
rt.a=a+1;
rt.b=a+2;
rt.c=a+3;
return rt;
};
…what we got (MSVC 2010 /Ox):
$T3853 = 8 ; size = 4
_a$ = 12 ; size = 4
?get_some_values@@YA?AUs@@H@Z PROC ; get_some_values
mov ecx, DWORD PTR _a$[esp-4]
96
CHAPTER 9. MORE ABOUT RESULTS RETURNING 9.3. RETURNING A STRUCTURE
mov eax, DWORD PTR $T3853[esp-4]
lea edx, DWORD PTR [ecx+1]
mov DWORD PTR [eax], edx
lea edx, DWORD PTR [ecx+2]
add ecx, 3
mov DWORD PTR [eax+4], edx
mov DWORD PTR [eax+8], ecx
ret 0
?get_some_values@@YA?AUs@@H@Z ENDP ; get_some_values
The macro name for internal passing of pointer to a structure her is $T3853.
This example can be rewritten using the C99 language extensions:
struct s
{
int a;
int b;
int c;
};
struct s get_some_values (int a)
{
return (struct s){.a=a+1, .b=a+2, .c=a+3};
};
Listing 9.3: GCC 4.8.1
_get_some_values proc near
ptr_to_struct = dword ptr 4
a = dword ptr 8
mov edx, [esp+a]
mov eax, [esp+ptr_to_struct]
lea ecx, [edx+1]
mov [eax], ecx
lea ecx, [edx+2]
add edx, 3
mov [eax+4], ecx
mov [eax+8], edx
retn
_get_some_values endp
As we see, the function is just filling the structure’s fields allocated by the caller function, as if a pointer to the structure
was passed. So there are no performance drawbacks.
97
CHAPTER 10. POINTERS
Chapter 10
Pointers
Pointers are often used to return values from functions (recall scanf() case ( 7 on page 56)). For example, when a function
needs to return two values.
10.1 Global variables example
#include <stdio.h>
void f1 (int x, int y, int *sum, int *product)
{
*sum=x+y;
*product=x*y;
};
int sum, product;
void main()
{
f1(123, 456, &sum, &product);
printf ("sum=%d, product=%dn", sum, product);
};
This compiles to:
Listing 10.1: Optimizing MSVC 2010 (/Ob0)
COMM _product:DWORD
COMM _sum:DWORD
$SG2803 DB 'sum=%d, product=%d', 0aH, 00H
_x$ = 8 ; size = 4
_y$ = 12 ; size = 4
_sum$ = 16 ; size = 4
_product$ = 20 ; size = 4
_f1 PROC
mov ecx, DWORD PTR _y$[esp-4]
mov eax, DWORD PTR _x$[esp-4]
lea edx, DWORD PTR [eax+ecx]
imul eax, ecx
mov ecx, DWORD PTR _product$[esp-4]
push esi
mov esi, DWORD PTR _sum$[esp]
mov DWORD PTR [esi], edx
mov DWORD PTR [ecx], eax
pop esi
ret 0
_f1 ENDP
_main PROC
push OFFSET _product
push OFFSET _sum
push 456 ; 000001c8H
push 123 ; 0000007bH
call _f1
98
CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE
mov eax, DWORD PTR _product
mov ecx, DWORD PTR _sum
push eax
push ecx
push OFFSET $SG2803
call DWORD PTR __imp__printf
add esp, 28 ; 0000001cH
xor eax, eax
ret 0
_main ENDP
99
CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE
Let’s see this in OllyDbg:
Figure 10.1: OllyDbg: global variables addresses are passed to f1()
First, global variables’ addresses are passed to f1(). We can click “Follow in dump” on the stack element, and we can
see the place in the data segment allocated for the two variables.
100
CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE
These variables are zeroed, because non-initialized data (from BSS) is cleared before the execution begins: [ISO07,
6.7.8p10]. They reside in the data segment, we can verify this by pressing Alt-M and reviewing the memory map:
Figure 10.2: OllyDbg: memory map
101
CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE
Let’s trace (F7) to the start of f1():
Figure 10.3: OllyDbg: f1() starts
Two values are visible in the stack 456 (0x1C8) and 123 (0x7B), and also the addresses of the two global variables.
102
CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE
Let’s trace until the end of f1(). In the left bottom window we see how the results of the calculation appear in the
global variables:
Figure 10.4: OllyDbg: f1() execution completed
103
CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE
Now the global variables’ values are loaded into registers ready for passing to printf() (via the stack):
Figure 10.5: OllyDbg: global variables’ addresses are passed into printf()
10.2 Local variables example
Let’s rework our example slightly:
Listing 10.2: now the sum and product variables are local
void main()
{
int sum, product; // now variables are local in this function
f1(123, 456, &sum, &product);
printf ("sum=%d, product=%dn", sum, product);
};
f1() code will not change. Only the code of main() will do:
Listing 10.3: Optimizing MSVC 2010 (/Ob0)
_product$ = -8 ; size = 4
_sum$ = -4 ; size = 4
_main PROC
; Line 10
sub esp, 8
; Line 13
lea eax, DWORD PTR _product$[esp+8]
push eax
lea ecx, DWORD PTR _sum$[esp+12]
push ecx
push 456 ; 000001c8H
push 123 ; 0000007bH
call _f1
; Line 14
mov edx, DWORD PTR _product$[esp+24]
mov eax, DWORD PTR _sum$[esp+24]
push edx
push eax
push OFFSET $SG2803
call DWORD PTR __imp__printf
; Line 15
xor eax, eax
add esp, 36 ; 00000024H
ret 0
104
CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE
Let’s look again with OllyDbg. The addresses of the local variables in the stack are 0x2EF854 and 0x2EF858. We see
how these are pushed into the stack:
Figure 10.6: OllyDbg: local variables’ addresses are pushed into the stack
105
CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE
f1() starts. So far there is only random garbage in the stack at 0x2EF854 and 0x2EF858:
Figure 10.7: OllyDbg: f1() starting
106
CHAPTER 10. POINTERS 10.3. CONCLUSION
f1() completes:
Figure 10.8: OllyDbg: f1() completes execution
We now find 0xDB18 and 0x243 at addresses 0x2EF854 and 0x2EF858. These values are the f1() results.
10.3 Conclusion
f1() could return pointers to any place in memory, located anywhere. This is in essence the usefulness of the pointers.
By the way, C++ references work exactly the same way. Read more about them: ( 51.3 on page 556).
107
CHAPTER 11. GOTO
Chapter 11
GOTO
The GOTO operator is considered harmful [Dij68], but nevertheless, it can be used reasonably [Knu74], [Yur13, p. 1.3.2].
Here is a very simple example:
#include <stdio.h>
int main()
{
printf ("beginn");
goto exit;
printf ("skip me!n");
exit:
printf ("endn");
};
Here is what we’ve get in MSVC 2012:
Listing 11.1: MSVC 2012
$SG2934 DB 'begin', 0aH, 00H
$SG2936 DB 'skip me!', 0aH, 00H
$SG2937 DB 'end', 0aH, 00H
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG2934 ; 'begin'
call _printf
add esp, 4
jmp SHORT $exit$3
push OFFSET $SG2936 ; 'skip me!'
call _printf
add esp, 4
$exit$3:
push OFFSET $SG2937 ; 'end'
call _printf
add esp, 4
xor eax, eax
pop ebp
ret 0
_main ENDP
The goto statement is just replaced by a JMP instruction, which has the same effect: unconditional jump to another place.
The second printf() call can be executed only with human intervention, by using a debugger or patching.
108
CHAPTER 11. GOTO
This also could be a simple patching exercise. Let’s open the resulting executable in Hiew:
Figure 11.1: Hiew
109
CHAPTER 11. GOTO 11.1. DEAD CODE
Place the cursor to address JMP (0x410), press F3 (edit), press zero twice, so the opcode becomes EB 00:
Figure 11.2: Hiew
The second byte of the JMP opcode is relative offset of jump, 0 implies the point right after the current instruction. So
now JMP not skipping the second printf() call.
Now press F9 (save) and exit. Now we run the executable and we see this:
Figure 11.3: Result
The same effect can be achieved by replacing the JMP instruction with 2 NOP instructions. NOP has an opcode of 0x90
and length of 1 byte, so we need 2 instructions as replacement.
11.1 Dead code
The second printf() call is also called “dead code” in compiler terms. This mean, the code will never be executed. So
when you compile this example with optimizations, the compiler removes “dead code”, leaving no trace of it:
Listing 11.2: Optimizing MSVC 2012
$SG2981 DB 'begin', 0aH, 00H
$SG2983 DB 'skip me!', 0aH, 00H
$SG2984 DB 'end', 0aH, 00H
_main PROC
push OFFSET $SG2981 ; 'begin'
call _printf
push OFFSET $SG2984 ; 'end'
$exit$4:
call _printf
add esp, 8
xor eax, eax
ret 0
_main ENDP
However, the compiler forgot to remove the “skip me!” string.
11.2 Exercise
Try to achieve the same result using your favorite compiler and debugger.
110
CHAPTER 12. CONDITIONAL JUMPS
Chapter 12
Conditional jumps
12.1 Simple example
#include <stdio.h>
void f_signed (int a, int b)
{
if (a>b)
printf ("a>bn");
if (a==b)
printf ("a==bn");
if (a<b)
printf ("a<bn");
};
void f_unsigned (unsigned int a, unsigned int b)
{
if (a>b)
printf ("a>bn");
if (a==b)
printf ("a==bn");
if (a<b)
printf ("a<bn");
};
int main()
{
f_signed(1, 2);
f_unsigned(1, 2);
return 0;
};
12.1.1 x86
x86 + MSVC
What we have in the f_signed() function:
Listing 12.1: Non-optimizing MSVC 2010
_a$ = 8
_b$ = 12
_f_signed PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
cmp eax, DWORD PTR _b$[ebp]
jle SHORT $LN3@f_signed
push OFFSET $SG737 ; 'a>b'
call _printf
add esp, 4
$LN3@f_signed:
mov ecx, DWORD PTR _a$[ebp]
111
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
cmp ecx, DWORD PTR _b$[ebp]
jne SHORT $LN2@f_signed
push OFFSET $SG739 ; 'a==b'
call _printf
add esp, 4
$LN2@f_signed:
mov edx, DWORD PTR _a$[ebp]
cmp edx, DWORD PTR _b$[ebp]
jge SHORT $LN4@f_signed
push OFFSET $SG741 ; 'a<b'
call _printf
add esp, 4
$LN4@f_signed:
pop ebp
ret 0
_f_signed ENDP
The first instruction, JLE, stands for Jump if Less or Equal. In other words, if the second operand is larger than first or
equal, control is to be passed to address or label mentioned in instruction. If this condition does not trigger (second operand
smaller than first), the control flow is not to be altered and the first printf() is to be called. The second check is JNE: Jump
if Not Equal. Control flow will not change if the operands are equal. The third check is JGE: Jump if Greater or Equal—jump if
the first operand is larger than the second or if they are equal. So, if all three conditional jumps are triggered, no printf()
to be called whatsoever. But it is impossible without special intervention.
The f_unsigned() function is the same, with the exception that the JBE and JAE instructions are used here instead
of JLE and JGE, see below:
Now let’s take a look at the f_unsigned() function
Listing 12.2: GCC
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_f_unsigned PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
cmp eax, DWORD PTR _b$[ebp]
jbe SHORT $LN3@f_unsigned
push OFFSET $SG2761 ; 'a>b'
call _printf
add esp, 4
$LN3@f_unsigned:
mov ecx, DWORD PTR _a$[ebp]
cmp ecx, DWORD PTR _b$[ebp]
jne SHORT $LN2@f_unsigned
push OFFSET $SG2763 ; 'a==b'
call _printf
add esp, 4
$LN2@f_unsigned:
mov edx, DWORD PTR _a$[ebp]
cmp edx, DWORD PTR _b$[ebp]
jae SHORT $LN4@f_unsigned
push OFFSET $SG2765 ; 'a<b'
call _printf
add esp, 4
$LN4@f_unsigned:
pop ebp
ret 0
_f_unsigned ENDP
Almost the same, with these different instructions: JBE—Jump if Below or Equal and JAE—Jump if Above or Equal. The
difference in these instructions (JA/JAE/JBE/JBE) JG/JGE/JL/JLE is that they work with unsigned numbers.
See also the section about signed number representations ( 30 on page 451). So, where we see JG/JL instead of JA/JBE
or vice-versa, we can almost be sure that the variables are signed or unsigned, respectively.
Here is also the main() function, where there is nothing much new to us:
Listing 12.3: main()
_main PROC
push ebp
mov ebp, esp
push 2
112
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
push 1
call _f_signed
add esp, 8
push 2
push 1
call _f_unsigned
add esp, 8
xor eax, eax
pop ebp
ret 0
_main ENDP
113
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
x86 + MSVC + OllyDbg
We can see how flags are set by running this example in OllyDbg. Let’s begin with f_unsigned() , which works with
unsigned numbers. CMP is executed thrice here, but for the same arguments, so the flags are the same each time.
Result of the first comparison:
Figure 12.1: OllyDbg: f_unsigned(): first conditional jump
So, the flags are: C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0. They are named with one character for brevity in OllyDbg.
OllyDbg gives a hint that the (JBE) jump is to be triggered now. Indeed, if we take a look into [Int13], we can read there
that JBE is triggering if CF=1 or ZF=1. The condition is true here, so the jump is triggered.
114
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
The next conditional jump:
Figure 12.2: OllyDbg: f_unsigned(): second conditional jump
OllyDbg gives a hint that JNZ is to be triggered now. Indeed, JNZ triggering if ZF=0 (zero flag).
115
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
The third conditional jump, JNB:
Figure 12.3: OllyDbg: f_unsigned(): third conditional jump
In [Int13] we can see that JNB triggers if CF=0 (carry flag). It’s not true in our case, so the third printf() executes.
116
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
Now we can try in OllyDbg the f_signed() function, which works with signed values.
Flags are set in the same way: C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0.
The first conditional jump JLE is to be triggered:
Figure 12.4: OllyDbg: f_unsigned(): first conditional jump
In [Int13] we find that this instruction is triggered if ZF=1 or SF≠OF. SF≠OF in our case, so the jump triggers.
117
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
The second JNZ conditional jump triggering: if ZF=0 (zero flag):
Figure 12.5: OllyDbg: f_unsigned(): second conditional jump
118
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
The third conditional jump JGE will not trigger because it will only if SF=OF, and that is not true in our case:
Figure 12.6: OllyDbg: f_unsigned(): third conditional jump
119
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
x86 + MSVC + Hiew
We can try to patch the executable file in a way that the f_unsigned() function will always print “a==b”, for any input
values.
Here is how it looks in Hiew:
Figure 12.7: Hiew: f_unsigned() function
Essentially, we’ve got three tasks:
• force the first jump to always trigger;
• force the second jump to never trigger;
• force the third jump to always trigger.
Thus we can point the code flow to the second printf(), and it always print “a==b”.
Three instructions (or bytes) has to be patched:
• The first jump will now be JMP, but the jump offset is still the same.
• The second jump may be triggered sometimes, but in any case it will jump to the next instruction, because, we set the
jump offset to 0. Jump offset is just gets added to the address for the next instruction in these instructions. So if the
offset is 0, the jump slips to the next instruction.
• The third jump we convert into JMP just as the first one, so it is always triggering.
120
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
That’s what we do:
Figure 12.8: Hiew: let’s modify the f_unsigned() function
If we forget about any of these jumps, then several printf() calls may execute, but we want just one.
Non-optimizing GCC
Non-optimizing GCC 4.4.1 produces almost the same code, but with puts() ( 3.4.3 on page 14) instead of printf().
Optimizing GCC
An observant reader may ask, why execute CMP several times, if the flags are same after each execution? Perhaps optimizing
MSVC can’t do this, but optimizing GCC 4.8.1 can go deeper:
Listing 12.4: GCC 4.8.1 f_signed()
f_signed:
mov eax, DWORD PTR [esp+8]
cmp DWORD PTR [esp+4], eax
jg .L6
je .L7
jge .L1
mov DWORD PTR [esp+4], OFFSET FLAT:.LC2 ; "a<b"
jmp puts
.L6:
mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 ; "a>b"
jmp puts
.L1:
rep ret
.L7:
mov DWORD PTR [esp+4], OFFSET FLAT:.LC1 ; "a==b"
jmp puts
121
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
We also see JMP puts here instead of CALL puts / RETN. This kind of trick will have explained later: 13.1.1 on
page 140.
This type of x86 code is somewhat rare. MSVC 2012, as it seems, can’t generate such code. On the other hand, assembly
language programmers are fully aware of the fact that Jcc instructions can be stacked. So if you see it somewhere, there
is a good probability that the code was hand-written.
The f_unsigned() function is not that æsthetically short:
Listing 12.5: GCC 4.8.1 f_unsigned()
f_unsigned:
push esi
push ebx
sub esp, 20
mov esi, DWORD PTR [esp+32]
mov ebx, DWORD PTR [esp+36]
cmp esi, ebx
ja .L13
cmp esi, ebx ; this instruction could be removed
je .L14
.L10:
jb .L15
add esp, 20
pop ebx
pop esi
ret
.L15:
mov DWORD PTR [esp+32], OFFSET FLAT:.LC2 ; "a<b"
add esp, 20
pop ebx
pop esi
jmp puts
.L13:
mov DWORD PTR [esp], OFFSET FLAT:.LC0 ; "a>b"
call puts
cmp esi, ebx
jne .L10
.L14:
mov DWORD PTR [esp+32], OFFSET FLAT:.LC1 ; "a==b"
add esp, 20
pop ebx
pop esi
jmp puts
But nevertheless, there are two CMP instructions instead of three. So optimization algorithms of GCC 4.8.1 are probably
not perfect yet.
12.1.2 ARM
32-bit ARM
Optimizing Keil 6/2013 (ARM mode)
Listing 12.6: Optimizing Keil 6/2013 (ARM mode)
.text:000000B8 EXPORT f_signed
.text:000000B8 f_signed ; CODE XREF: main+C
.text:000000B8 70 40 2D E9 STMFD SP!, {R4-R6,LR}
.text:000000BC 01 40 A0 E1 MOV R4, R1
.text:000000C0 04 00 50 E1 CMP R0, R4
.text:000000C4 00 50 A0 E1 MOV R5, R0
.text:000000C8 1A 0E 8F C2 ADRGT R0, aAB ; "a>bn"
.text:000000CC A1 18 00 CB BLGT __2printf
.text:000000D0 04 00 55 E1 CMP R5, R4
.text:000000D4 67 0F 8F 02 ADREQ R0, aAB_0 ; "a==bn"
.text:000000D8 9E 18 00 0B BLEQ __2printf
.text:000000DC 04 00 55 E1 CMP R5, R4
.text:000000E0 70 80 BD A8 LDMGEFD SP!, {R4-R6,PC}
.text:000000E4 70 40 BD E8 LDMFD SP!, {R4-R6,LR}
.text:000000E8 19 0E 8F E2 ADR R0, aAB_1 ; "a<bn"
.text:000000EC 99 18 00 EA B __2printf
122
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
.text:000000EC ; End of function f_signed
A lot of instructions in ARM mode can be executed only when specific flags are set. E.g. this is often used when
comparing numbers.
For instance, the ADD instruction is in fact ADDAL internally, where AL stands for Always, i.e., execute always. The
predicates are encoded in 4 high bits of the 32-bit ARM instructions (condition field). The B instruction for unconditional
jumping is in fact conditional and encoded just like any other conditional jump, but has AL in the condition field, and it
implies execute ALways, ignoring flags.
The ADRGT instructions works just like ADR but executes only in the case when the previous CMP instruction found one
number greater than another, while comparing the two. (Greater Than).
The next BLGT instruction behaves exactly as BL and is triggered only if the result of the comparison was the same
(Greater Than). ADRGT writes a pointer to the string ``a>bn'' into R0 and BLGT calls printf(). Consequently, these
instructions with suffix -GT are executes only in the case when the value in R0 (a is there) is bigger than the value in R4 (b
is there).
Then we see the ADREQ and BLEQ instructions. They behave just like ADR and BL, but are to be executed only if operands
were equal to each other during the last comparison. Another CMP is located before them (because the printf() call may
tamper the flag state).
Then we see LDMGEFD, this instruction works just like LDMFD1
, but is triggered only when one value was greater or equal
to the other (Greater or Equal).
The sense of ``LDMGEFD SP!, {R4-R6,PC}'' instruction is that is like a function epilogue, but it is triggered
only if a >= b, only then the function execution finishes. But if it is not true, i.e., a < b, then the control flow continues to
the next ``LDMFD SP!, {R4-R6,LR}'' instruction, which is one more function epilogue. This instruction restores the
state of registers R4-R6, but also LR instead of PC, thus, it does not returns from the function. The last two instructions
call printf() with the string «a<bn» as a sole argument. We already examined an unconditional jump to the printf()
function instead of function return, in «printf() with several arguments» section, here ( 6.2.1 on page 44).
f_unsigned is likewise, but the ADRHI, BLHI, and LDMCSFD instructions are used there, these predicates (HI = Unsigned
higher, CS = Carry Set (greater than or equal)) are analogous to those examined before, but for unsigned values.
There is not much new in the main() function for us:
Listing 12.7: main()
.text:00000128 EXPORT main
.text:00000128 main
.text:00000128 10 40 2D E9 STMFD SP!, {R4,LR}
.text:0000012C 02 10 A0 E3 MOV R1, #2
.text:00000130 01 00 A0 E3 MOV R0, #1
.text:00000134 DF FF FF EB BL f_signed
.text:00000138 02 10 A0 E3 MOV R1, #2
.text:0000013C 01 00 A0 E3 MOV R0, #1
.text:00000140 EA FF FF EB BL f_unsigned
.text:00000144 00 00 A0 E3 MOV R0, #0
.text:00000148 10 80 BD E8 LDMFD SP!, {R4,PC}
.text:00000148 ; End of function main
That’s how you can get rid of conditional jumps in ARM mode.
Why it is so good? Read here: 33.1 on page 456.
There is no such feature in x86, except the CMOVcc instruction, it is the same as MOV, but triggered only when specific
flags are set, usually set by CMP.
Optimizing Keil 6/2013 (thumb mode)
Listing 12.8: Optimizing Keil 6/2013 (thumb mode)
.text:00000072 f_signed ; CODE XREF: main+6
.text:00000072 70 B5 PUSH {R4-R6,LR}
.text:00000074 0C 00 MOVS R4, R1
.text:00000076 05 00 MOVS R5, R0
.text:00000078 A0 42 CMP R0, R4
.text:0000007A 02 DD BLE loc_82
.text:0000007C A4 A0 ADR R0, aAB ; "a>bn"
.text:0000007E 06 F0 B7 F8 BL __2printf
.text:00000082
.text:00000082 loc_82 ; CODE XREF: f_signed+8
.text:00000082 A5 42 CMP R5, R4
.text:00000084 02 D1 BNE loc_8C
.text:00000086 A4 A0 ADR R0, aAB_0 ; "a==bn"
1LDMFD
123
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
.text:00000088 06 F0 B2 F8 BL __2printf
.text:0000008C
.text:0000008C loc_8C ; CODE XREF: f_signed+12
.text:0000008C A5 42 CMP R5, R4
.text:0000008E 02 DA BGE locret_96
.text:00000090 A3 A0 ADR R0, aAB_1 ; "a<bn"
.text:00000092 06 F0 AD F8 BL __2printf
.text:00000096
.text:00000096 locret_96 ; CODE XREF: f_signed+1C
.text:00000096 70 BD POP {R4-R6,PC}
.text:00000096 ; End of function f_signed
Only B instructions in thumb mode may be supplemented by condition codes, so the thumb code looks more ordinary.
BLE is a normal conditional jump Less than or Equal, BNE—Not Equal, BGE—Greater than or Equal.
f_unsigned is likewise, but other instructions are used while dealing with unsigned values: BLS (Unsigned lower or
same) and BCS (Carry Set (Greater than or equal)).
ARM64: Optimizing GCC (Linaro) 4.9
Listing 12.9: f_signed()
f_signed:
; W0=a, W1=b
cmp w0, w1
bgt .L19 ; Branch if Greater Than (a>b)
beq .L20 ; Branch if Equal (a==b)
bge .L15 ; Branch if Greater than or Equal (a>=b) (impossible here)
; a<b
adrp x0, .LC11 ; "a<b"
add x0, x0, :lo12:.LC11
b puts
.L19:
adrp x0, .LC9 ; "a>b"
add x0, x0, :lo12:.LC9
b puts
.L15: ; impossible here
ret
.L20:
adrp x0, .LC10 ; "a==b"
add x0, x0, :lo12:.LC10
b puts
Listing 12.10: f_unsigned()
f_unsigned:
stp x29, x30, [sp, -48]!
; W0=a, W1=b
cmp w0, w1
add x29, sp, 0
str x19, [sp,16]
mov w19, w0
bhi .L25 ; Branch if HIgher (a>b)
cmp w19, w1
beq .L26 ; Branch if Equal (a==b)
.L23:
bcc .L27 ; Branch if Carry Clear (if less than) (a<b)
; function epilogue, impossible to be here
ldr x19, [sp,16]
ldp x29, x30, [sp], 48
ret
.L27:
ldr x19, [sp,16]
adrp x0, .LC11 ; "a<b"
ldp x29, x30, [sp], 48
add x0, x0, :lo12:.LC11
b puts
.L25:
adrp x0, .LC9 ; "a>b"
str x1, [x29,40]
124
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
add x0, x0, :lo12:.LC9
bl puts
ldr x1, [x29,40]
cmp w19, w1
bne .L23 ; Branch if Not Equal
.L26:
ldr x19, [sp,16]
adrp x0, .LC10 ; "a==b"
ldp x29, x30, [sp], 48
add x0, x0, :lo12:.LC10
b puts
I have added the comments. What is also striking is that compiler is not aware that some conditions are not possible at
all, so there is dead code at some places, which will never be executed.
Exercise
Try to optimize these functions manually for size, removing redundant instructions, without adding new ones.
12.1.3 MIPS
One distinctive MIPS feature is the absence of flags. Apparently, it was done to simplify the analysis of data dependencies.
There are instructions similar to SETcc in x86: SLT (“Set on Less Than”: signed version) and SLTU (unsigned version).
These instructions sets destination register value to 1 if the condition is true or to 0 if otherwise.
The destination register is then checked using BEQ (“Branch on Equal”) or BNE (“Branch on Not Equal”) and a jump may
occur.
So, this instruction pair has to be used in MIPS for comparison and branch.
Let’s first start with the signed version of our function:
Listing 12.11: Non-optimizing GCC 4.4.5 (IDA)
.text:00000000 f_signed: # CODE XREF: main+18
.text:00000000
.text:00000000 var_10 = -0x10
.text:00000000 var_8 = -8
.text:00000000 var_4 = -4
.text:00000000 arg_0 = 0
.text:00000000 arg_4 = 4
.text:00000000
.text:00000000 addiu $sp, -0x20
.text:00000004 sw $ra, 0x20+var_4($sp)
.text:00000008 sw $fp, 0x20+var_8($sp)
.text:0000000C move $fp, $sp
.text:00000010 la $gp, __gnu_local_gp
.text:00000018 sw $gp, 0x20+var_10($sp)
; store input values into local stack:
.text:0000001C sw $a0, 0x20+arg_0($fp)
.text:00000020 sw $a1, 0x20+arg_4($fp)
; reload them.
.text:00000024 lw $v1, 0x20+arg_0($fp)
.text:00000028 lw $v0, 0x20+arg_4($fp)
; $v0=b
; $v1=a
.text:0000002C or $at, $zero ; NOP
; this is pseudoinstruction. in fact, "slt $v0,$v0,$v1" is there.
; so $v0 will be set to 1 if $v0<$v1 (b<a) or to 0 if otherwise:
.text:00000030 slt $v0, $v1
; jump to loc_5c, if condition is not true.
; this is pseudoinstruction. in fact, "beq $v0,$zero,loc_5c" is there:
.text:00000034 beqz $v0, loc_5C
; print "a>b" and finish
.text:00000038 or $at, $zero ; branch delay slot, NOP
.text:0000003C lui $v0, (unk_230 >> 16) # "a>b"
.text:00000040 addiu $a0, $v0, (unk_230 & 0xFFFF) # "a>b"
.text:00000044 lw $v0, (puts & 0xFFFF)($gp)
.text:00000048 or $at, $zero ; NOP
.text:0000004C move $t9, $v0
.text:00000050 jalr $t9
.text:00000054 or $at, $zero ; branch delay slot, NOP
125
CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE
.text:00000058 lw $gp, 0x20+var_10($fp)
.text:0000005C
.text:0000005C loc_5C: # CODE XREF: f_signed+34
.text:0000005C lw $v1, 0x20+arg_0($fp)
.text:00000060 lw $v0, 0x20+arg_4($fp)
.text:00000064 or $at, $zero ; NOP
; check if a==b, jump to loc_90 if its not true':
.text:00000068 bne $v1, $v0, loc_90
.text:0000006C or $at, $zero ; branch delay slot, NOP
; condition is true, so print "a==b" and finish:
.text:00000070 lui $v0, (aAB >> 16) # "a==b"
.text:00000074 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b"
.text:00000078 lw $v0, (puts & 0xFFFF)($gp)
.text:0000007C or $at, $zero ; NOP
.text:00000080 move $t9, $v0
.text:00000084 jalr $t9
.text:00000088 or $at, $zero ; branch delay slot, NOP
.text:0000008C lw $gp, 0x20+var_10($fp)
.text:00000090
.text:00000090 loc_90: # CODE XREF: f_signed+68
.text:00000090 lw $v1, 0x20+arg_0($fp)
.text:00000094 lw $v0, 0x20+arg_4($fp)
.text:00000098 or $at, $zero ; NOP
; check if $v1<$v0 (a<b), set $v0 to 1 if condition is true:
.text:0000009C slt $v0, $v1, $v0
; if condition is not true (i.e., $v0==0), jump to loc_c8:
.text:000000A0 beqz $v0, loc_C8
.text:000000A4 or $at, $zero ; branch delay slot, NOP
; condition is true, print "a<b" and finish
.text:000000A8 lui $v0, (aAB_0 >> 16) # "a<b"
.text:000000AC addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b"
.text:000000B0 lw $v0, (puts & 0xFFFF)($gp)
.text:000000B4 or $at, $zero ; NOP
.text:000000B8 move $t9, $v0
.text:000000BC jalr $t9
.text:000000C0 or $at, $zero ; branch delay slot, NOP
.text:000000C4 lw $gp, 0x20+var_10($fp)
.text:000000C8
; all 3 conditions were false, so just finish:
.text:000000C8 loc_C8: # CODE XREF: f_signed+A0
.text:000000C8 move $sp, $fp
.text:000000CC lw $ra, 0x20+var_4($sp)
.text:000000D0 lw $fp, 0x20+var_8($sp)
.text:000000D4 addiu $sp, 0x20
.text:000000D8 jr $ra
.text:000000DC or $at, $zero ; branch delay slot, NOP
.text:000000DC # End of function f_signed
“SLT REG0, REG0, REG1” is reduced by IDA to its shorter form: “SLT REG0, REG1”. We also see there BEQZ pseudoinstruction
(“Branch if Equal to Zero”), which are in fact “BEQ REG, $ZERO, LABEL”.
The unsigned version is just the same, but SLTU (unsigned version, hence “U” in name) is used instead of SLT:
Listing 12.12: Non-optimizing GCC 4.4.5 (IDA)
.text:000000E0 f_unsigned: # CODE XREF: main+28
.text:000000E0
.text:000000E0 var_10 = -0x10
.text:000000E0 var_8 = -8
.text:000000E0 var_4 = -4
.text:000000E0 arg_0 = 0
.text:000000E0 arg_4 = 4
.text:000000E0
.text:000000E0 addiu $sp, -0x20
.text:000000E4 sw $ra, 0x20+var_4($sp)
.text:000000E8 sw $fp, 0x20+var_8($sp)
.text:000000EC move $fp, $sp
.text:000000F0 la $gp, __gnu_local_gp
.text:000000F8 sw $gp, 0x20+var_10($sp)
.text:000000FC sw $a0, 0x20+arg_0($fp)
.text:00000100 sw $a1, 0x20+arg_4($fp)
.text:00000104 lw $v1, 0x20+arg_0($fp)
126
CHAPTER 12. CONDITIONAL JUMPS 12.2. CALCULATING ABSOLUTE VALUE
.text:00000108 lw $v0, 0x20+arg_4($fp)
.text:0000010C or $at, $zero
.text:00000110 sltu $v0, $v1
.text:00000114 beqz $v0, loc_13C
.text:00000118 or $at, $zero
.text:0000011C lui $v0, (unk_230 >> 16)
.text:00000120 addiu $a0, $v0, (unk_230 & 0xFFFF)
.text:00000124 lw $v0, (puts & 0xFFFF)($gp)
.text:00000128 or $at, $zero
.text:0000012C move $t9, $v0
.text:00000130 jalr $t9
.text:00000134 or $at, $zero
.text:00000138 lw $gp, 0x20+var_10($fp)
.text:0000013C
.text:0000013C loc_13C: # CODE XREF: f_unsigned+34
.text:0000013C lw $v1, 0x20+arg_0($fp)
.text:00000140 lw $v0, 0x20+arg_4($fp)
.text:00000144 or $at, $zero
.text:00000148 bne $v1, $v0, loc_170
.text:0000014C or $at, $zero
.text:00000150 lui $v0, (aAB >> 16) # "a==b"
.text:00000154 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b"
.text:00000158 lw $v0, (puts & 0xFFFF)($gp)
.text:0000015C or $at, $zero
.text:00000160 move $t9, $v0
.text:00000164 jalr $t9
.text:00000168 or $at, $zero
.text:0000016C lw $gp, 0x20+var_10($fp)
.text:00000170
.text:00000170 loc_170: # CODE XREF: f_unsigned+68
.text:00000170 lw $v1, 0x20+arg_0($fp)
.text:00000174 lw $v0, 0x20+arg_4($fp)
.text:00000178 or $at, $zero
.text:0000017C sltu $v0, $v1, $v0
.text:00000180 beqz $v0, loc_1A8
.text:00000184 or $at, $zero
.text:00000188 lui $v0, (aAB_0 >> 16) # "a<b"
.text:0000018C addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b"
.text:00000190 lw $v0, (puts & 0xFFFF)($gp)
.text:00000194 or $at, $zero
.text:00000198 move $t9, $v0
.text:0000019C jalr $t9
.text:000001A0 or $at, $zero
.text:000001A4 lw $gp, 0x20+var_10($fp)
.text:000001A8
.text:000001A8 loc_1A8: # CODE XREF: f_unsigned+A0
.text:000001A8 move $sp, $fp
.text:000001AC lw $ra, 0x20+var_4($sp)
.text:000001B0 lw $fp, 0x20+var_8($sp)
.text:000001B4 addiu $sp, 0x20
.text:000001B8 jr $ra
.text:000001BC or $at, $zero
.text:000001BC # End of function f_unsigned
12.2 Calculating absolute value
A simple function:
int my_abs (int i)
{
if (i<0)
return -i;
else
return i;
};
127
CHAPTER 12. CONDITIONAL JUMPS 12.2. CALCULATING ABSOLUTE VALUE
12.2.1 Optimizing MSVC
This is the usual way to generate it:
Listing 12.13: Optimizing MSVC 2012 x64
i$ = 8
my_abs PROC
; ECX = input
test ecx, ecx
; check for sign of input value
; skip NEG instruction if sign is positive
jns SHORT $LN2@my_abs
; negate value
neg ecx
$LN2@my_abs:
; prepare result in EAX:
mov eax, ecx
ret 0
my_abs ENDP
GCC 4.9 does mostly the same.
12.2.2 Optimizing Keil 6/2013: thumb mode
Listing 12.14: Optimizing Keil 6/2013: thumb mode
my_abs PROC
CMP r0,#0
; is input value equal to zero or greater than zero?
; skip RSBS instruction then
BGE |L0.6|
; subtract input value from 0:
RSBS r0,r0,#0
|L0.6|
BX lr
ENDP
ARM lacks a negate instruction, so the Keil compiler uses the “Reverse Subtract” instruction, which just subtract with
reversed operands.
12.2.3 Optimizing Keil 6/2013: ARM mode
It’s possible to add condition codes to some instructions in ARM mode, so that’s what the Keil compiler do:
Listing 12.15: Optimizing Keil 6/2013: ARM mode
my_abs PROC
CMP r0,#0
; execute "Reverse Subtract" instruction only if input value is less than 0:
RSBLT r0,r0,#0
BX lr
ENDP
Now there are no conditional jumps and this is good: 33.1 on page 456.
12.2.4 Non-optimizing GCC 4.9 (ARM64)
ARM64 has the instruction NEG for negating:
Listing 12.16: Optimizing GCC 4.9 (ARM64)
my_abs:
sub sp, sp, #16
str w0, [sp,12]
ldr w0, [sp,12]
; compare input value with contents of WZR register
; (which always holds zero)
cmp w0, wzr
bge .L2
ldr w0, [sp,12]
128
CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR
neg w0, w0
b .L3
.L2:
ldr w0, [sp,12]
.L3:
add sp, sp, 16
ret
12.2.5 MIPS
Listing 12.17: Optimizing GCC 4.4.5 (IDA)
my_abs:
; jump if $a0<0:
bltz $a0, locret_10
; just return input value ($a0) in $v0:
move $v0, $a0
jr $ra
or $at, $zero ; branch delay slot, NOP
locret_10:
; negate input value and store it in $v0:
jr $ra
; this is pseudoinstruction. in fact, this is "subu $v0,$zero,$a0" ($v0=0-$a0)
negu $v0, $a0
Here we see a new instruction: BLTZ (“Branch if Less Than Zero”). There is also the NEGU pseudoinstruction, which just
does subtraction from zero. The “U” suffix in both SUBU and NEGU implies that no exception to be raised in case of integer
overflow.
12.2.6 Branchless version?
There are also could be branchless version, which we are going to see later: 45 on page 512.
12.3 Conditional operator
The conditional operator in C/C++ is:
expression ? expression : expression
Here is an example:
const char* f (int a)
{
return a==10 ? "it is ten" : "it is not ten";
};
12.3.1 x86
Old and non-optimizing compilers generate the code just as if an if/else statement was used:
Listing 12.18: Non-optimizing MSVC 2008
$SG746 DB 'it is ten', 00H
$SG747 DB 'it is not ten', 00H
tv65 = -4 ; this will be used as a temporary variable
_a$ = 8
_f PROC
push ebp
mov ebp, esp
push ecx
; compare input value with 10
cmp DWORD PTR _a$[ebp], 10
; jump to $LN3@f if not equal
jne SHORT $LN3@f
; store pointer to the string into temporary variable:
mov DWORD PTR tv65[ebp], OFFSET $SG746 ; 'it is ten'
129
CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR
; jump to exit
jmp SHORT $LN4@f
$LN3@f:
; store pointer to the string into temporary variable:
mov DWORD PTR tv65[ebp], OFFSET $SG747 ; 'it is not ten'
$LN4@f:
; this is exit. copy pointer to the string from temporary variable to EAX.
mov eax, DWORD PTR tv65[ebp]
mov esp, ebp
pop ebp
ret 0
_f ENDP
Listing 12.19: Optimizing MSVC 2008
$SG792 DB 'it is ten', 00H
$SG793 DB 'it is not ten', 00H
_a$ = 8 ; size = 4
_f PROC
; compare input value with 10
cmp DWORD PTR _a$[esp-4], 10
mov eax, OFFSET $SG792 ; 'it is ten'
; jump to $LN4@f if equal
je SHORT $LN4@f
mov eax, OFFSET $SG793 ; 'it is not ten'
$LN4@f:
ret 0
_f ENDP
Newer compilers are more concise:
Listing 12.20: Optimizing MSVC 2012 x64
$SG1355 DB 'it is ten', 00H
$SG1356 DB 'it is not ten', 00H
a$ = 8
f PROC
; load pointers to the both strings
lea rdx, OFFSET FLAT:$SG1355 ; 'it is ten'
lea rax, OFFSET FLAT:$SG1356 ; 'it is not ten'
; compare input value with 10
cmp ecx, 10
; if equal, copy value from RDX ("it is ten")
; if not, do nothing. pointer to the string "it is not ten" is still in RAX as for now.
cmove rax, rdx
ret 0
f ENDP
Optimizing GCC 4.8 for x86 also uses the CMOVcc instruction, while the non-optimizing GCC 4.8 uses a conditional jumps.
12.3.2 ARM
Optimizing Keil for ARM mode also uses the conditional instructions ADRcc:
Listing 12.21: Optimizing Keil 6/2013 (ARM mode)
f PROC
; compare input value with 10
CMP r0,#0xa
; if comparison result is EQual, copy pointer to the "it is ten" string into R0
ADREQ r0,|L0.16| ; "it is ten"
; if comparison result is Not Equal, copy pointer to the "it is not ten" string into R0
ADRNE r0,|L0.28| ; "it is not ten"
BX lr
ENDP
|L0.16|
DCB "it is ten",0
|L0.28|
DCB "it is not ten",0
130
CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR
Without manual intervention, the two instructions ADREQ and ADRNE cannot be executed in the same run.
Optimizing Keil for Thumb mode needs to use conditional jump instructions, since there are no load instructions that
support conditional flags:
Listing 12.22: Optimizing Keil 6/2013 (thumb mode)
f PROC
; compare input value with 10
CMP r0,#0xa
; jump to |L0.8| if EQual
BEQ |L0.8|
ADR r0,|L0.12| ; "it is not ten"
BX lr
|L0.8|
ADR r0,|L0.28| ; "it is ten"
BX lr
ENDP
|L0.12|
DCB "it is not ten",0
|L0.28|
DCB "it is ten",0
12.3.3 ARM64
Optimizing GCC (Linaro) 4.9 for ARM64 also uses conditional jumps:
Listing 12.23: Optimizing GCC (Linaro) 4.9
f:
cmp x0, 10
beq .L3 ; branch if equal
adrp x0, .LC1 ; "it is ten"
add x0, x0, :lo12:.LC1
ret
.L3:
adrp x0, .LC0 ; "it is not ten"
add x0, x0, :lo12:.LC0
ret
.LC0:
.string "it is ten"
.LC1:
.string "it is not ten"
That’s because ARM64 doesn’t have a simple load instruction with conditional flags, like ADRcc in 32-bit ARM mode or
CMOVcc in x86 [ARM13a, p390, C5.5]. It has, however, “Conditional SELect” instruction (CSEL), but GCC 4.9 doesn’t seem to
be smart enough to use it in such piece of code.
12.3.4 MIPS
Unfortunately, GCC 4.4.5 for MIPS is not very smart, either:
Listing 12.24: Optimizing GCC 4.4.5 (assembly output)
$LC0:
.ascii "it is not ten000"
$LC1:
.ascii "it is ten000"
f:
li $2,10 # 0xa
; compare $a0 and 10, jump if equal:
beq $4,$2,$L2
nop ; branch delay slot
; leave address of "it is not ten" string in $v0 and return:
lui $2,%hi($LC0)
j $31
addiu $2,$2,%lo($LC0)
$L2:
131
CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES
; leave address of "it is ten" string in $v0 and return:
lui $2,%hi($LC1)
j $31
addiu $2,$2,%lo($LC1)
12.3.5 Let’s rewrite it in an if/else way
const char* f (int a)
{
if (a==10)
return "it is ten";
else
return "it is not ten";
};
Interestingly, optimizing GCC 4.8 for x86 was also able to use CMOVcc in this case:
Listing 12.25: Optimizing GCC 4.8
.LC0:
.string "it is ten"
.LC1:
.string "it is not ten"
f:
.LFB0:
; compare input value with 10
cmp DWORD PTR [esp+4], 10
mov edx, OFFSET FLAT:.LC1 ; "it is not ten"
mov eax, OFFSET FLAT:.LC0 ; "it is ten"
; if comparison result is Not Equal, copy EDX value to EAX
; if not, do nothing
cmovne eax, edx
ret
Optimizing Keil in ARM mode generates code identical to listing.12.21.
But the optimizing MSVC 2012 is not that good (yet).
12.3.6 Conclusion
Why optimizing compilers try to get rid of conditional jumps? Read here about it: 33.1 on page 456.
12.3.7 Exercise
Try rewriting the code in listing.12.23 by removing all conditional jump instructions and using the CSEL instruction.
12.4 Getting minimal and maximal values
12.4.1 32-bit
int my_max(int a, int b)
{
if (a>b)
return a;
else
return b;
};
int my_min(int a, int b)
{
if (a<b)
return a;
else
return b;
};
132
CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES
Listing 12.26: Non-optimizing MSVC 2013
_a$ = 8
_b$ = 12
_my_min PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
; compare A and B:
cmp eax, DWORD PTR _b$[ebp]
; jump, if A is greater or equal to B:
jge SHORT $LN2@my_min
; reload A to EAX if otherwise and jump to exit
mov eax, DWORD PTR _a$[ebp]
jmp SHORT $LN3@my_min
jmp SHORT $LN3@my_min ; this is redundant JMP
$LN2@my_min:
; return B
mov eax, DWORD PTR _b$[ebp]
$LN3@my_min:
pop ebp
ret 0
_my_min ENDP
_a$ = 8
_b$ = 12
_my_max PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
; compare A and B:
cmp eax, DWORD PTR _b$[ebp]
; jump if A is less or equal to B:
jle SHORT $LN2@my_max
; reload A to EAX if otherwise and jump to exit
mov eax, DWORD PTR _a$[ebp]
jmp SHORT $LN3@my_max
jmp SHORT $LN3@my_max ; this is redundant JMP
$LN2@my_max:
; return B
mov eax, DWORD PTR _b$[ebp]
$LN3@my_max:
pop ebp
ret 0
_my_max ENDP
These two functions differ only in the conditional jump instruction: JGE (“Jump if Greater or Equal”) is used in the first
one and JLE (“Jump if Less or Equal”) in the second.
There is one unneeded JMP instruction in each function, which MSVC probably left by mistake.
Branchless
ARM for Thumb mode reminds us of x86 code:
Listing 12.27: Optimizing Keil 6/2013 (thumb mode)
my_max PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; branch if A is greater then B:
BGT |L0.6|
; otherwise (A<=B) return R1 (B):
MOVS r0,r1
|L0.6|
; return
BX lr
ENDP
my_min PROC
133
CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; branch if A is less then B:
BLT |L0.14|
; otherwise (A>=B) return R1 (B):
MOVS r0,r1
|L0.14|
; return
BX lr
ENDP
The functions differ in the branching instruction: BGT and BLT.
It’s possible to use conditional suffixes in ARM mode, so the code is shorter. MOVcc is to be executed only if the condition
is met:
Listing 12.28: Optimizing Keil 6/2013 (ARM mode)
my_max PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; return B instead of A by placing B in R0
; this instruction will trigger only if A<=B (hence, LE - Less or Equal)
; if instruction is not triggered (in case of A>B), A is still in R0 register
MOVLE r0,r1
BX lr
ENDP
my_min PROC
; R0=A
; R1=B
; compare A and B:
CMP r0,r1
; return B instead of A by placing B in R0
; this instruction will trigger only if A>=B (hence, GE - Greater or Equal)
; if instruction is not triggered (in case of A<B), A value is still in R0 register
MOVGE r0,r1
BX lr
ENDP
Optimizing GCC 4.8.1 and optimizing MSVC 2013 can use CMOVcc instruction, which is analogous to MOVcc in ARM:
Listing 12.29: Optimizing MSVC 2013
my_max:
mov edx, DWORD PTR [esp+4]
mov eax, DWORD PTR [esp+8]
; EDX=A
; EAX=B
; compare A and B:
cmp edx, eax
; if A>=B, load A value into EAX
; the instruction idle if otherwise (if A<B)
cmovge eax, edx
ret
my_min:
mov edx, DWORD PTR [esp+4]
mov eax, DWORD PTR [esp+8]
; EDX=A
; EAX=B
; compare A and B:
cmp edx, eax
; if A<=B, load A value into EAX
; the instruction idle if otherwise (if A>B)
cmovle eax, edx
ret
134
CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES
12.4.2 64-bit
#include <stdint.h>
int64_t my_max(int64_t a, int64_t b)
{
if (a>b)
return a;
else
return b;
};
int64_t my_min(int64_t a, int64_t b)
{
if (a<b)
return a;
else
return b;
};
There is some unneeded value shuffling, but the code is comprehensible:
Listing 12.30: Non-optimizing GCC 4.9.1 ARM64
my_max:
sub sp, sp, #16
str x0, [sp,8]
str x1, [sp]
ldr x1, [sp,8]
ldr x0, [sp]
cmp x1, x0
ble .L2
ldr x0, [sp,8]
b .L3
.L2:
ldr x0, [sp]
.L3:
add sp, sp, 16
ret
my_min:
sub sp, sp, #16
str x0, [sp,8]
str x1, [sp]
ldr x1, [sp,8]
ldr x0, [sp]
cmp x1, x0
bge .L5
ldr x0, [sp,8]
b .L6
.L5:
ldr x0, [sp]
.L6:
add sp, sp, 16
ret
Branchless
No need to load function arguments from the stack, as they are already in the registers:
Listing 12.31: Optimizing GCC 4.9.1 x64
my_max:
; RDI=A
; RSI=B
; compare A and B:
cmp rdi, rsi
; prepare B in RAX for return:
mov rax, rsi
; if A>=B, put A (RDI) in RAX for return.
135
CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES
; this instruction is idle if otherwise (if A<B)
cmovge rax, rdi
ret
my_min:
; RDI=A
; RSI=B
; compare A and B:
cmp rdi, rsi
; prepare B in RAX for return:
mov rax, rsi
; if A<=B, put A (RDI) in RAX for return.
; this instruction is idle if otherwise (if A>B)
cmovle rax, rdi
ret
MSVC 2013 does almost the same.
ARM64 has the CSEL instruction, which works just as MOVcc in ARM or CMOVcc in x86, just the name is different: “Con-
ditional SELect”.
Listing 12.32: Optimizing GCC 4.9.1 ARM64
my_max:
; X0=A
; X1=B
; compare A and B:
cmp x0, x1
; select X0 (A) to X0 if X0>=X1 or A>=B (Greater or Equal)
; select X1 (B) to X0 if A<B
csel x0, x0, x1, ge
ret
my_min:
; X0=A
; X1=B
; compare A and B:
cmp x0, x1
; select X0 (A) to X0 if X0<=X1 or A<=B (Less or Equal)
; select X1 (B) to X0 if A>B
csel x0, x0, x1, le
ret
12.4.3 MIPS
Unfortunately, GCC 4.4.5 for MIPS is not that good:
Listing 12.33: Optimizing GCC 4.4.5 (IDA)
my_max:
; set $v1 $a1<$a0:
slt $v1, $a1, $a0
; jump, if $a1<$a0:
beqz $v1, locret_10
; this is branch delay slot
; prepare $a1 in $v0 in case of branch triggered:
move $v0, $a1
; no branch triggered, prepare $a0 in $v0:
move $v0, $a0
locret_10:
jr $ra
or $at, $zero ; branch delay slot, NOP
; the min() function is same, but input operands in SLT instruction are swapped:
my_min:
slt $v1, $a0, $a1
beqz $v1, locret_28
move $v0, $a1
move $v0, $a0
136
CHAPTER 12. CONDITIONAL JUMPS 12.5. CONCLUSION
locret_28:
jr $ra
or $at, $zero ; branch delay slot, NOP
Do not forget about the branch delay slots: the first MOVE is executed before BEQZ, the second MOVE is executed only if
the branch wasn’t taken.
12.5 Conclusion
12.5.1 x86
Here’s the rough skeleton of a conditional jump:
Listing 12.34: x86
CMP register, register/value
Jcc true ; cc=condition code
false:
... some code to be executed if comparison result is false ...
JMP exit
true:
... some code to be executed if comparison result is true ...
exit:
12.5.2 ARM
Listing 12.35: ARM
CMP register, register/value
Bcc true ; cc=condition code
false:
... some code to be executed if comparison result is false ...
JMP exit
true:
... some code to be executed if comparison result is true ...
exit:
12.5.3 MIPS
Listing 12.36: Check for zero
BEQZ REG, label
...
Listing 12.37: Check for less than zero:
BLTZ REG, label
...
Listing 12.38: Check for equal values
BEQ REG1, REG2, label
...
Listing 12.39: Check for non-equal values
BNE REG1, REG2, label
...
Listing 12.40: Check for less than, greater than (signed)
SLT REG1, REG2, REG3
BEQ REG1, label
...
137
CHAPTER 12. CONDITIONAL JUMPS 12.5. CONCLUSION
Listing 12.41: Check for less than, greater than (unsigned)
SLTU REG1, REG2, REG3
BEQ REG1, label
...
12.5.4 Branchless
If the body of a condition statement is very short, the conditional move instruction can be used: MOVcc in ARM (in ARM
mode), CSEL in ARM64, CMOVcc in x86.
ARM
It’s possible to use conditional suffixes in ARM mode for some instructions:
Listing 12.42: ARM (ARM mode)
CMP register, register/value
instr1_cc ; some instruction will be executed if condition code is true
instr2_cc ; some other instruction will be executed if other condition code is true
... etc ...
Of course, there is no limit for the number of instructions with conditional code suffixes, as long as the CPU flags are not
modified by any of them.
Thumb mode has the IT instruction, allowing to add conditional suffixes to the next four instructions. Read more about
it: 17.7.2 on page 251.
Listing 12.43: ARM (thumb mode)
CMP register, register/value
ITEEE EQ ; set these suffixes: if-then-else-else-else
instr1 ; instruction will be executed if condition is true
instr2 ; instruction will be executed if condition is false
instr3 ; instruction will be executed if condition is false
instr4 ; instruction will be executed if condition is false
138
CHAPTER 13. SWITCH()/CASE/DEFAULT
Chapter 13
switch()/case/default
13.1 Small number of cases
#include <stdio.h>
void f (int a)
{
switch (a)
{
case 0: printf ("zeron"); break;
case 1: printf ("onen"); break;
case 2: printf ("twon"); break;
default: printf ("something unknownn"); break;
};
};
int main()
{
f (2); // test
};
13.1.1 x86
Non-optimizing MSVC
Result (MSVC 2010):
Listing 13.1: MSVC 2010
tv64 = -4 ; size = 4
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _a$[ebp]
mov DWORD PTR tv64[ebp], eax
cmp DWORD PTR tv64[ebp], 0
je SHORT $LN4@f
cmp DWORD PTR tv64[ebp], 1
je SHORT $LN3@f
cmp DWORD PTR tv64[ebp], 2
je SHORT $LN2@f
jmp SHORT $LN1@f
$LN4@f:
push OFFSET $SG739 ; 'zero', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN7@f
$LN3@f:
push OFFSET $SG741 ; 'one', 0aH, 00H
call _printf
add esp, 4
139
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
jmp SHORT $LN7@f
$LN2@f:
push OFFSET $SG743 ; 'two', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN7@f
$LN1@f:
push OFFSET $SG745 ; 'something unknown', 0aH, 00H
call _printf
add esp, 4
$LN7@f:
mov esp, ebp
pop ebp
ret 0
_f ENDP
Our function with a few cases in switch() is in fact analogous to this construction:
void f (int a)
{
if (a==0)
printf ("zeron");
else if (a==1)
printf ("onen");
else if (a==2)
printf ("twon");
else
printf ("something unknownn");
};
If we work with switch() with a few cases it is impossible to be sure if it was a real switch() in the source code, or just a
pack of if() statements. This implies that switch() is like syntactic sugar for a large number of nested if()s.
There is nothing especially new to us in the generated code, with the exception of the compiler moving input variable a
to a temporary local variable tv64 1
.
If we compile this in GCC 4.4.1, we’ll get almost the same result, even with maximal optimization turned on (-O3 option).
Optimizing MSVC
Now let’s turn on optimization in MSVC (/Ox): cl 1.c /Fa1.asm /Ox
Listing 13.2: MSVC
_a$ = 8 ; size = 4
_f PROC
mov eax, DWORD PTR _a$[esp-4]
sub eax, 0
je SHORT $LN4@f
sub eax, 1
je SHORT $LN3@f
sub eax, 1
je SHORT $LN2@f
mov DWORD PTR _a$[esp-4], OFFSET $SG791 ; 'something unknown', 0aH, 00H
jmp _printf
$LN2@f:
mov DWORD PTR _a$[esp-4], OFFSET $SG789 ; 'two', 0aH, 00H
jmp _printf
$LN3@f:
mov DWORD PTR _a$[esp-4], OFFSET $SG787 ; 'one', 0aH, 00H
jmp _printf
$LN4@f:
mov DWORD PTR _a$[esp-4], OFFSET $SG785 ; 'zero', 0aH, 00H
jmp _printf
_f ENDP
Here we can see some dirty hacks.
First: the value of a is placed in EAX and 0 is subtracted from it. Sounds absurd, but it is done to check if the value in EAX
was 0. If yes, the ZF flag is to be set (e.g. subtracting from 0 is 0) and the first conditional jump JE (Jump if Equal or synonym
JZ —Jump if Zero) is to be triggered and control flow is to be passed to the $LN4@f label, where the 'zero' message is
1Local variables in stack are prefixed with tv — that’s how MSVC names internal variables for its needs
140
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
being printed. If the first jump doesn’t get triggered, 1 is subtracted from the input value and if at some stage the result is
0, the corresponding jump is to be triggered.
And if no jump gets triggered at all, the control flow passes to printf() with string argument 'something unknown'.
Second: we see something unusual for us: a string pointer is placed into the a variable, and then printf() is called not
via CALL, but via JMP. There is a simple explanation for that: the Caller pushes a value to the stack and calls our function
via CALL. CALL itself pushes the return address (RA) to the stack and does an unconditional jump to our function address.
Our function at any point of execution (since it do not contain any instruction that moves the stack pointer) has the following
stack layout:
• ESP—points to RA
• ESP+4—points to the a variable
On the other side, when we need to call printf() here we need exactly the same stack layout, except for the first
printf() argument, which needs to point to the string. And that is what our code does.
It replaces the function’s first argument with the address of the string and jumps to printf(), as if we didn’t call our
function f(), but directly printf(). printf() prints a string to stdout and then executes the RET instruction, which
POPs RA from the stack and control flow is returned not to f() but rather to f()’s callee, bypassing the end of the f()
function.
All this is possible because printf() is called right at the end of the f() function in all cases. In some way, it is similar
to the longjmp()2
function. And of course, it is all done for the sake of speed.
A similar case with the ARM compiler is described in “printf() with several arguments”, section, here ( 6.2.1 on page 44).
2wikipedia
141
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
OllyDbg
Since this example is tricky, let’s trace it in OllyDbg.
OllyDbg can detect such switch() constructs, and it can add some useful comments. EAX is 2 in the beginning, that’s the
function’s input value:
Figure 13.1: OllyDbg: EAX now contain the first (and only) function argument
142
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
0 is subtracted from 2 in EAX. Of course, EAX still contains 2. But the ZF flag is now 0, indicating that the resulting value
is non-zero:
Figure 13.2: OllyDbg: SUB executed
143
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
DEC is executed and EAX now contains 1. But 1 is non-zero, so the ZF flag is still 0:
Figure 13.3: OllyDbg: first DEC executed
144
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
Next DEC is executed. EAX is finally 0 and the ZF flag gets set, because the result is zero:
Figure 13.4: OllyDbg: second DEC executed
OllyDbg shows that this jump is to be taken now.
145
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
A pointer to the string “two” is to be written into the stack now:
Figure 13.5: OllyDbg: pointer to the string is to be written at the place of the first argument
Please note: the current argument of the function is 2 and 2 is now in the stack at the address 0x0020FA44.
146
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
MOV writes the pointer to the string at address 0x0020FA44 (see the stack window). Then, jump happens. This is the
first instruction of the printf() function in MSVCR100.DLL (I compiled the example with /MD switch):
Figure 13.6: OllyDbg: first instruction of printf() in MSVCR100.DLL
Now printf() treats the string at 0x00FF3010 as its only argument and prints the string.
147
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
This is the last instruction of printf():
Figure 13.7: OllyDbg: last instruction of printf() in MSVCR100.DLL
The string “two” was just printed to the console window.
148
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
Now let’s press F7 or F8 (step over) and return…not to f(), but rather to main():
Figure 13.8: OllyDbg: return to main()
Yes, the jump was direct, from the guts of printf() to main(). Because RA in the stack points not to some place in
f(), but rather to main(). And CALL 0x00FF1000 was the actual instruction which called f().
13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode)
.text:0000014C f1:
.text:0000014C 00 00 50 E3 CMP R0, #0
.text:00000150 13 0E 8F 02 ADREQ R0, aZero ; "zeron"
.text:00000154 05 00 00 0A BEQ loc_170
.text:00000158 01 00 50 E3 CMP R0, #1
.text:0000015C 4B 0F 8F 02 ADREQ R0, aOne ; "onen"
.text:00000160 02 00 00 0A BEQ loc_170
.text:00000164 02 00 50 E3 CMP R0, #2
.text:00000168 4A 0F 8F 12 ADRNE R0, aSomethingUnkno ; "something unknownn"
.text:0000016C 4E 0F 8F 02 ADREQ R0, aTwo ; "twon"
.text:00000170
.text:00000170 loc_170: ; CODE XREF: f1+8
.text:00000170 ; f1+14
.text:00000170 78 18 00 EA B __2printf
Again, by investigating this code we cannot say if it was a switch() in the original source code, or just a pack of if()
statements.
Anyway, we see here predicated instructions again (like ADREQ (Equal)) which is triggered only in case R0 = 0, and then
loads the address of the string «zeron» into R0. The next instruction BEQ redirects control flow to loc_170, if R0 = 0. An
astute reader may ask, will BEQ trigger correctly since ADREQ before it has already filled the R0 register with another value?
Yes, it will since BEQ checks the flags set by the CMP instruction, and ADREQ does not modify any flags at all.
The rest of the instructions are already familiar to us. There is only one call to printf(), at the end, and we have
already examined this trick here ( 6.2.1 on page 44). In the end, there are three paths to printf().
The last instruction, ``CMP R0, #2'' , is needed to check if a = 2. If it is not true, then ADRNE loads a pointer to
the string «something unknown n» into R0, since a was already checked to be equal to 0 or 1, and we can sure that the a
variable is not equal to these numbers at this point. And if R0 = 2, a pointer to the string «twon» will be loaded by ADREQ
into R0.
13.1.3 ARM: Optimizing Keil 6/2013 (thumb mode)
149
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
.text:000000D4 f1:
.text:000000D4 10 B5 PUSH {R4,LR}
.text:000000D6 00 28 CMP R0, #0
.text:000000D8 05 D0 BEQ zero_case
.text:000000DA 01 28 CMP R0, #1
.text:000000DC 05 D0 BEQ one_case
.text:000000DE 02 28 CMP R0, #2
.text:000000E0 05 D0 BEQ two_case
.text:000000E2 91 A0 ADR R0, aSomethingUnkno ; "something unknownn"
.text:000000E4 04 E0 B default_case
.text:000000E6 zero_case: ; CODE XREF: f1+4
.text:000000E6 95 A0 ADR R0, aZero ; "zeron"
.text:000000E8 02 E0 B default_case
.text:000000EA one_case: ; CODE XREF: f1+8
.text:000000EA 96 A0 ADR R0, aOne ; "onen"
.text:000000EC 00 E0 B default_case
.text:000000EE two_case: ; CODE XREF: f1+C
.text:000000EE 97 A0 ADR R0, aTwo ; "twon"
.text:000000F0 default_case ; CODE XREF: f1+10
.text:000000F0 ; f1+14
.text:000000F0 06 F0 7E F8 BL __2printf
.text:000000F4 10 BD POP {R4,PC}
As I already mentioned, it is not possible to add conditional predicates to most instructions in thumb mode, so the
thumb-code here is somewhat similar to the easily understandable x86 CISC-style code.
13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9
.LC12:
.string "zero"
.LC13:
.string "one"
.LC14:
.string "two"
.LC15:
.string "something unknown"
f12:
stp x29, x30, [sp, -32]!
add x29, sp, 0
str w0, [x29,28]
ldr w0, [x29,28]
cmp w0, 1
beq .L34
cmp w0, 2
beq .L35
cmp w0, wzr
bne .L38 ; jump to default label
adrp x0, .LC12 ; "zero"
add x0, x0, :lo12:.LC12
bl puts
b .L32
.L34:
adrp x0, .LC13 ; "one"
add x0, x0, :lo12:.LC13
bl puts
b .L32
.L35:
adrp x0, .LC14 ; "two"
add x0, x0, :lo12:.LC14
bl puts
b .L32
.L38:
adrp x0, .LC15 ; "something unknown"
add x0, x0, :lo12:.LC15
bl puts
150
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES
nop
.L32:
ldp x29, x30, [sp], 32
ret
The type of the input value is int, hence register W0 is used to hold it instead of the whole X0 register. The string pointers
are passed to puts() using an ADRP/ADD instructions pair just like I demonstrated in the “Hello, world!” example: 3.4.5 on
page 15.
13.1.5 ARM64: Optimizing GCC (Linaro) 4.9
f12:
cmp w0, 1
beq .L31
cmp w0, 2
beq .L32
cbz w0, .L35
; default case
adrp x0, .LC15 ; "something unknown"
add x0, x0, :lo12:.LC15
b puts
.L35:
adrp x0, .LC12 ; "zero"
add x0, x0, :lo12:.LC12
b puts
.L32:
adrp x0, .LC14 ; "two"
add x0, x0, :lo12:.LC14
b puts
.L31:
adrp x0, .LC13 ; "one"
add x0, x0, :lo12:.LC13
b puts
Better optimized piece of code. CBZ (Compare and Branch on Zero) instruction does jump if W0 is zero. There is also a
direct jump to puts() instead of calling it, like I explained before: 13.1.1 on page 140.
13.1.6 MIPS
Listing 13.3: Optimizing GCC 4.4.5 (IDA)
f:
lui $gp, (__gnu_local_gp >> 16)
; is it 1?
li $v0, 1
beq $a0, $v0, loc_60
la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot
; is it 2?
li $v0, 2
beq $a0, $v0, loc_4C
or $at, $zero ; branch delay slot, NOP
; jump, if not equal to 0:
bnez $a0, loc_38
or $at, $zero ; branch delay slot, NOP
; zero case:
lui $a0, ($LC0 >> 16) # "zero"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jr $t9 ; branch delay slot, NOP
la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot
# ---------------------------------------------------------------------------
loc_38: # CODE XREF: f+1C
lui $a0, ($LC3 >> 16) # "something unknown"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jr $t9
la $a0, ($LC3 & 0xFFFF) # "something unknown" ; branch delay slot
151
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
# ---------------------------------------------------------------------------
loc_4C: # CODE XREF: f+14
lui $a0, ($LC2 >> 16) # "two"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jr $t9
la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot
# ---------------------------------------------------------------------------
loc_60: # CODE XREF: f+8
lui $a0, ($LC1 >> 16) # "one"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jr $t9
la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot
The function always ends with calling puts(), so here we see a jump to puts() (JR: “Jump Register”) instead of “jump
and link”. We talked about this earlier: 13.1.1 on page 140.
We also often see NOP instructions after LW ones. This is “load delay slot”: another delay slot in MIPS. An instruction
next to LW may execute at the moment while LW loads value from memory. However, the next instruction must not use
the result of LW. Modern MIPS CPUs have a feature to wait if the next instruction uses result of LW, so this is somewhat
outdated, but GCC still adds NOPs for older MIPS CPUs. In general, it can be ignored.
13.1.7 Conclusion
A switch() with few cases is indistinguishable from an if/else construction, for example: listing.13.1.1.
13.2 A lot of cases
If a switch() statement contains a lot of cases, it is not very convenient for the compiler to emit too large code with a lot
JE/JNE instructions.
#include <stdio.h>
void f (int a)
{
switch (a)
{
case 0: printf ("zeron"); break;
case 1: printf ("onen"); break;
case 2: printf ("twon"); break;
case 3: printf ("threen"); break;
case 4: printf ("fourn"); break;
default: printf ("something unknownn"); break;
};
};
int main()
{
f (2); // test
};
13.2.1 x86
Non-optimizing MSVC
We get (MSVC 2010):
Listing 13.4: MSVC 2010
tv64 = -4 ; size = 4
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _a$[ebp]
152
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
mov DWORD PTR tv64[ebp], eax
cmp DWORD PTR tv64[ebp], 4
ja SHORT $LN1@f
mov ecx, DWORD PTR tv64[ebp]
jmp DWORD PTR $LN11@f[ecx*4]
$LN6@f:
push OFFSET $SG739 ; 'zero', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN9@f
$LN5@f:
push OFFSET $SG741 ; 'one', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN9@f
$LN4@f:
push OFFSET $SG743 ; 'two', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN9@f
$LN3@f:
push OFFSET $SG745 ; 'three', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN9@f
$LN2@f:
push OFFSET $SG747 ; 'four', 0aH, 00H
call _printf
add esp, 4
jmp SHORT $LN9@f
$LN1@f:
push OFFSET $SG749 ; 'something unknown', 0aH, 00H
call _printf
add esp, 4
$LN9@f:
mov esp, ebp
pop ebp
ret 0
npad 2 ; align next label
$LN11@f:
DD $LN6@f ; 0
DD $LN5@f ; 1
DD $LN4@f ; 2
DD $LN3@f ; 3
DD $LN2@f ; 4
_f ENDP
What we see here is a set of printf() calls with various arguments. All they have not only addresses in the memory of
the process, but also internal symbolic labels assigned by the compiler. All these labels are also mentioned in the $LN11@f
internal table.
At the function start, if a is greater than 4, control flow is passed to label $LN1@f, where printf() with argument
'something unknown' is called.
But if the value of a is less or equals to 4, then it gets multiplied by 4 and added with the $LN11@f table address. That
is how an address inside the table is constructed, pointing exactly to the element we need. For example, let’s say a is equal
to 2. 2 ∗ 4 = 8 (all table elements are addresses in a 32-bit process and that is why all elements are 4 bytes wide). The
address of the $LN11@f table + 8 is the table element where the $LN4@f label is stored. JMP fetches the $LN4@f address
from the table and jumps to it.
This table is sometimes called jumptable or branch table3
.
Then the corresponding printf() is called with argument 'two'. Literally, the jmp DWORD PTR $LN11@f[ecx*4]
instruction implies jump to the DWORD that is stored at address $LN11@f + ecx * 4.
npad ( 88 on page 866) is assembly language macro that aligning the next label so that it is to be stored at an address
aligned on a 4 byte (or 16 byte) boundary. This is very suitable for the processor since it is able to fetch 32-bit values from
memory through the memory bus, cache memory, etc, in a more effective way if it is aligned.
3The whole method was once called computed GOTO in early versions of FORTRAN: wikipedia. Not quite relevant these days, but what a term!
153
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
OllyDbg
Let’s try this example in OllyDbg. The input value of the function (2) is loaded into EAX:
Figure 13.9: OllyDbg: function’s input value is loaded in EAX
154
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
The input value is checked, is it bigger than 4? If not, the “default” jump is not taken:
Figure 13.10: OllyDbg: 2 is no bigger than 4: no jump is taken
155
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
Here we see a jumptable:
Figure 13.11: OllyDbg: calculating destination address using jumptable
Here I’ve clicked “Follow in Dump” → “Address constant”, so now we see the jumptable in the data window. These are
5 32-bit values4
. ECX is now 2, so the second element (counting from zero) of the table is to be used. It’s also possible to
click “Follow in Dump” → “Memory address” and OllyDbg will show the element addressed by the JMP instruction. That’s
0x010B103A.
4They are underlined by OllyDbg because these are also FIXUPs: 68.2.6 on page 688, we are going to come back to them later
156
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
After the jump we are at 0x010B103A: the code printing “two” will now be executed:
Figure 13.12: OllyDbg: now we at the case: label
Non-optimizing GCC
Let’s see what GCC 4.4.1 generates:
Listing 13.5: GCC 4.4.1
public f
f proc near ; CODE XREF: main+10
var_18 = dword ptr -18h
arg_0 = dword ptr 8
push ebp
mov ebp, esp
sub esp, 18h
cmp [ebp+arg_0], 4
ja short loc_8048444
mov eax, [ebp+arg_0]
shl eax, 2
mov eax, ds:off_804855C[eax]
jmp eax
loc_80483FE: ; DATA XREF: .rodata:off_804855C
mov [esp+18h+var_18], offset aZero ; "zero"
call _puts
jmp short locret_8048450
loc_804840C: ; DATA XREF: .rodata:08048560
mov [esp+18h+var_18], offset aOne ; "one"
call _puts
jmp short locret_8048450
loc_804841A: ; DATA XREF: .rodata:08048564
mov [esp+18h+var_18], offset aTwo ; "two"
call _puts
jmp short locret_8048450
loc_8048428: ; DATA XREF: .rodata:08048568
mov [esp+18h+var_18], offset aThree ; "three"
157
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
call _puts
jmp short locret_8048450
loc_8048436: ; DATA XREF: .rodata:0804856C
mov [esp+18h+var_18], offset aFour ; "four"
call _puts
jmp short locret_8048450
loc_8048444: ; CODE XREF: f+A
mov [esp+18h+var_18], offset aSomethingUnkno ; "something unknown"
call _puts
locret_8048450: ; CODE XREF: f+26
; f+34...
leave
retn
f endp
off_804855C dd offset loc_80483FE ; DATA XREF: f+12
dd offset loc_804840C
dd offset loc_804841A
dd offset loc_8048428
dd offset loc_8048436
It is almost the same, with a little nuance: argument arg_0 is multiplied by 4 by shifting it to left by 2 bits (it is almost
the same as multiplication by 4) ( 16.2.1 on page 206). Then the address of the label is taken from the off_804855C array,
stored in EAX, and then ``JMP EAX'' does the actual jump.
13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode)
Listing 13.6: Optimizing Keil 6/2013 (ARM mode)
00000174 f2
00000174 05 00 50 E3 CMP R0, #5 ; switch 5 cases
00000178 00 F1 8F 30 ADDCC PC, PC, R0,LSL#2 ; switch jump
0000017C 0E 00 00 EA B default_case ; jumptable 00000178 default case
00000180
00000180 loc_180 ; CODE XREF: f2+4
00000180 03 00 00 EA B zero_case ; jumptable 00000178 case 0
00000184
00000184 loc_184 ; CODE XREF: f2+4
00000184 04 00 00 EA B one_case ; jumptable 00000178 case 1
00000188
00000188 loc_188 ; CODE XREF: f2+4
00000188 05 00 00 EA B two_case ; jumptable 00000178 case 2
0000018C
0000018C loc_18C ; CODE XREF: f2+4
0000018C 06 00 00 EA B three_case ; jumptable 00000178 case 3
00000190
00000190 loc_190 ; CODE XREF: f2+4
00000190 07 00 00 EA B four_case ; jumptable 00000178 case 4
00000194
00000194 zero_case ; CODE XREF: f2+4
00000194 ; f2:loc_180
00000194 EC 00 8F E2 ADR R0, aZero ; jumptable 00000178 case 0
00000198 06 00 00 EA B loc_1B8
0000019C
0000019C one_case ; CODE XREF: f2+4
0000019C ; f2:loc_184
0000019C EC 00 8F E2 ADR R0, aOne ; jumptable 00000178 case 1
000001A0 04 00 00 EA B loc_1B8
158
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
000001A4
000001A4 two_case ; CODE XREF: f2+4
000001A4 ; f2:loc_188
000001A4 01 0C 8F E2 ADR R0, aTwo ; jumptable 00000178 case 2
000001A8 02 00 00 EA B loc_1B8
000001AC
000001AC three_case ; CODE XREF: f2+4
000001AC ; f2:loc_18C
000001AC 01 0C 8F E2 ADR R0, aThree ; jumptable 00000178 case 3
000001B0 00 00 00 EA B loc_1B8
000001B4
000001B4 four_case ; CODE XREF: f2+4
000001B4 ; f2:loc_190
000001B4 01 0C 8F E2 ADR R0, aFour ; jumptable 00000178 case 4
000001B8
000001B8 loc_1B8 ; CODE XREF: f2+24
000001B8 ; f2+2C
000001B8 66 18 00 EA B __2printf
000001BC
000001BC default_case ; CODE XREF: f2+4
000001BC ; f2+8
000001BC D4 00 8F E2 ADR R0, aSomethingUnkno ; jumptable 00000178 default case
000001C0 FC FF FF EA B loc_1B8
This code makes use of the ARM mode feature in which all instructions have a fixed size of 4 bytes.
Let’s keep in mind that the maximum value for a is 4 and any greater value will cause «something unknownn» string to
be printed.
The first ``CMP R0, #5'' instruction compares the input value of a with 5.
The next ``ADDCC PC, PC, R0,LSL#2'' 5
instruction is being executed only if R0 < 5 (CC=Carry clear / Less than).
Consequently, if ADDCC does not trigger (it is a R0 ≥ 5 case), a jump to default_case label will occur.
But if R0 < 5 and ADDCC triggers, the following is to be happen:
The value in R0 is multiplied by 4. In fact, LSL#2 at the instruction’s suffix stands for “shift left by 2 bits”. But as we will
see later ( 16.2.1 on page 205) in section “Shifts”, shift left by 2 bits is equivalent to multiplying by 4.
Then we add R0 ∗ 4 to the current value in PC, thus jumping to one of the B (Branch) instructions located below.
At the moment of the execution of ADDCC, the value in PC is 8 bytes ahead (0x180) than the address at which the
ADDCC instruction is located (0x178), or, in other words, 2 instructions ahead.
This is how the pipeline in ARM processors works: when ADDCC is executed, the processor at the moment is beginning
to process the instruction after the next one, so that is why PC points there. This has to be memorized.
If a = 0, then is to be added to the value in PC, and the actual value of the PC will be written into PC (which is 8 bytes
ahead) and a jump to the label loc_180 will happen, which is 8 bytes ahead of the point where the ADDCC instruction is.
If a = 1, then PC + 8 + a ∗ 4 = PC + 8 + 1 ∗ 4 = PC + 12 = 0x184 will be written to PC, which is the address of the
loc_184 label.
With every 1 added to a, the resulting PC is increased by 4. 4 is the instruction length in ARM mode and also, the length
of each B instruction, of which there are 5 in row.
Each of these five B instructions passes control further, to what was programmed in the switch(). Pointer loading of the
corresponding string occurs there, etc.
13.2.3 ARM: Optimizing Keil 6/2013 (thumb mode)
Listing 13.7: Optimizing Keil 6/2013 (thumb mode)
000000F6 EXPORT f2
000000F6 f2
000000F6 10 B5 PUSH {R4,LR}
000000F8 03 00 MOVS R3, R0
000000FA 06 F0 69 F8 BL __ARM_common_switch8_thumb ; switch 6 cases
000000FE 05 DCB 5
000000FF 04 06 08 0A 0C 10 DCB 4, 6, 8, 0xA, 0xC, 0x10 ; jump table for switch statement
00000105 00 ALIGN 2
00000106
00000106 zero_case ; CODE XREF: f2+4
00000106 8D A0 ADR R0, aZero ; jumptable 000000FA case 0
5ADD—addition
159
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
00000108 06 E0 B loc_118
0000010A
0000010A one_case ; CODE XREF: f2+4
0000010A 8E A0 ADR R0, aOne ; jumptable 000000FA case 1
0000010C 04 E0 B loc_118
0000010E
0000010E two_case ; CODE XREF: f2+4
0000010E 8F A0 ADR R0, aTwo ; jumptable 000000FA case 2
00000110 02 E0 B loc_118
00000112
00000112 three_case ; CODE XREF: f2+4
00000112 90 A0 ADR R0, aThree ; jumptable 000000FA case 3
00000114 00 E0 B loc_118
00000116
00000116 four_case ; CODE XREF: f2+4
00000116 91 A0 ADR R0, aFour ; jumptable 000000FA case 4
00000118
00000118 loc_118 ; CODE XREF: f2+12
00000118 ; f2+16
00000118 06 F0 6A F8 BL __2printf
0000011C 10 BD POP {R4,PC}
0000011E
0000011E default_case ; CODE XREF: f2+4
0000011E 82 A0 ADR R0, aSomethingUnkno ; jumptable 000000FA default case
00000120 FA E7 B loc_118
000061D0 EXPORT __ARM_common_switch8_thumb
000061D0 __ARM_common_switch8_thumb ; CODE XREF: example6_f2+4
000061D0 78 47 BX PC
000061D2 00 00 ALIGN 4
000061D2 ; End of function __ARM_common_switch8_thumb
000061D2
000061D4 __32__ARM_common_switch8_thumb ; CODE XREF: ⤦
__ARM_common_switch8_thumb
000061D4 01 C0 5E E5 LDRB R12, [LR,#-1]
000061D8 0C 00 53 E1 CMP R3, R12
000061DC 0C 30 DE 27 LDRCSB R3, [LR,R12]
000061E0 03 30 DE 37 LDRCCB R3, [LR,R3]
000061E4 83 C0 8E E0 ADD R12, LR, R3,LSL#1
000061E8 1C FF 2F E1 BX R12
000061E8 ; End of function __32__ARM_common_switch8_thumb
One cannot be sure that all instructions in thumb and thumb-2 modes has the same size. It can even be said that in
these modes the instructions have variable lengths, just like in x86.
So there is a special table added that contains information about how much cases are there (not including default-case),
and an offset for each with a label to which control must be passed in the corresponding case.
A special function is present here in order to deal with the table and pass control, named
__ARM_common_switch8_thumb. It starts with ``BX PC'' , whose function is to switch the processor to ARM-mode. Then
you see the function for table processing. It is too complex to describe it here now, so I’m omitting it.
It is interesting to note that the function uses the LR register as a pointer to the table. Indeed, after calling of this
function, LR contains the address after
``BL __ARM_common_switch8_thumb'' instruction, where the table starts.
It is also worth noting that the code is generated as a separate function in order to reuse it, so the compiler not generates
the same code for every switch() statement.
IDA successfully perceived it as a service function and a table, and added comments to the labels like
jumptable 000000FA case 0.
13.2.4 MIPS
Listing 13.8: Optimizing GCC 4.4.5 (IDA)
160
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES
f:
lui $gp, (__gnu_local_gp >> 16)
; jump to loc_24 if input value is lesser than 5:
sltiu $v0, $a0, 5
bnez $v0, loc_24
la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot
; input value is greater or equal to 5.
; print "something unknown" and finish:
lui $a0, ($LC5 >> 16) # "something unknown"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC5 & 0xFFFF) # "something unknown" ; branch delay slot
loc_24: # CODE XREF: f+8
; load address of jumptable
; LA is pseudoinstruction, LUI and ADDIU pair are there in fact:
la $v0, off_120
; multiply input value by 4:
sll $a0, 2
; sum up multiplied value and jumptable address:
addu $a0, $v0, $a0
; load element from jumptable:
lw $v0, 0($a0)
or $at, $zero ; NOP
; jump to the address we got in jumptable:
jr $v0
or $at, $zero ; branch delay slot, NOP
sub_44: # DATA XREF: .rodata:0000012C
; print "three" and finish
lui $a0, ($LC3 >> 16) # "three"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC3 & 0xFFFF) # "three" ; branch delay slot
sub_58: # DATA XREF: .rodata:00000130
; print "four" and finish
lui $a0, ($LC4 >> 16) # "four"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC4 & 0xFFFF) # "four" ; branch delay slot
sub_6C: # DATA XREF: .rodata:off_120
; print "zero" and finish
lui $a0, ($LC0 >> 16) # "zero"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot
sub_80: # DATA XREF: .rodata:00000124
; print "one" and finish
lui $a0, ($LC1 >> 16) # "one"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot
sub_94: # DATA XREF: .rodata:00000128
; print "two" and finish
lui $a0, ($LC2 >> 16) # "two"
lw $t9, (puts & 0xFFFF)($gp)
or $at, $zero ; NOP
jr $t9
la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot
; may be placed in .rodata section:
161
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK
off_120: .word sub_6C
.word sub_80
.word sub_94
.word sub_44
.word sub_58
The new instruction for us is SLTIU (“Set on Less Than Immediate Unsigned”). This is the same as SLTU (“Set on Less Than
Unsigned”), but “I” stands for “immediate”, i.e., a number has to be specified in the instruction itself.
BNEZ is “Branch if Not Equal to Zero”.
Code is very close to the other ISAs. SLL (“Shift Word Left Logical”) does multiplication by 4. MIPS is a 32-bit CPU after
all, so all addresses in the jumptable are 32-bit ones.
13.2.5 Conclusion
Rough skeleton of switch():
Listing 13.9: x86
MOV REG, input
CMP REG, 4 ; maximal number of cases
JA default
SHL REG, 2 ; find element in table. shift for 3 bits in x64.
MOV REG, jump_table[REG]
JMP REG
case1:
; do something
JMP exit
case2:
; do something
JMP exit
case3:
; do something
JMP exit
case4:
; do something
JMP exit
case5:
; do something
JMP exit
default:
...
exit:
....
jump_table dd case1
dd case2
dd case3
dd case4
dd case5
The jump to the address in the jump table may also be implemented using this instruction: JMP jump_table[REG*4].
Or JMP jump_table[REG*8] in x64.
A jumptable is just array of pointers, like the one described later: 18.5 on page 275.
13.3 When there are several case statements in one block
Here is a very widespread construction: several case statements for a single block:
#include <stdio.h>
void f(int a)
{
switch (a)
{
162
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK
case 1:
case 2:
case 7:
case 10:
printf ("1, 2, 7, 10n");
break;
case 3:
case 4:
case 5:
case 6:
printf ("3, 4, 5n");
break;
case 8:
case 9:
case 20:
case 21:
printf ("8, 9, 21n");
break;
case 22:
printf ("22n");
break;
default:
printf ("defaultn");
break;
};
};
int main()
{
f(4);
};
It’s too wasteful to generate a block for each possible case, so what is usually done is to generate each block plus some
kind of dispatcher.
13.3.1 MSVC
Listing 13.10: Optimizing MSVC 2010
1 $SG2798 DB '1, 2, 7, 10', 0aH, 00H
2 $SG2800 DB '3, 4, 5', 0aH, 00H
3 $SG2802 DB '8, 9, 21', 0aH, 00H
4 $SG2804 DB '22', 0aH, 00H
5 $SG2806 DB 'default', 0aH, 00H
6
7 _a$ = 8
8 _f PROC
9 mov eax, DWORD PTR _a$[esp-4]
10 dec eax
11 cmp eax, 21
12 ja SHORT $LN1@f
13 movzx eax, BYTE PTR $LN10@f[eax]
14 jmp DWORD PTR $LN11@f[eax*4]
15 $LN5@f:
16 mov DWORD PTR _a$[esp-4], OFFSET $SG2798 ; '1, 2, 7, 10'
17 jmp DWORD PTR __imp__printf
18 $LN4@f:
19 mov DWORD PTR _a$[esp-4], OFFSET $SG2800 ; '3, 4, 5'
20 jmp DWORD PTR __imp__printf
21 $LN3@f:
22 mov DWORD PTR _a$[esp-4], OFFSET $SG2802 ; '8, 9, 21'
23 jmp DWORD PTR __imp__printf
24 $LN2@f:
25 mov DWORD PTR _a$[esp-4], OFFSET $SG2804 ; '22'
26 jmp DWORD PTR __imp__printf
27 $LN1@f:
28 mov DWORD PTR _a$[esp-4], OFFSET $SG2806 ; 'default'
29 jmp DWORD PTR __imp__printf
30 npad 2 ; align $LN11@f table on 16-byte boundary
163
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK
31 $LN11@f:
32 DD $LN5@f ; print '1, 2, 7, 10'
33 DD $LN4@f ; print '3, 4, 5'
34 DD $LN3@f ; print '8, 9, 21'
35 DD $LN2@f ; print '22'
36 DD $LN1@f ; print 'default'
37 $LN10@f:
38 DB 0 ; a=1
39 DB 0 ; a=2
40 DB 1 ; a=3
41 DB 1 ; a=4
42 DB 1 ; a=5
43 DB 1 ; a=6
44 DB 0 ; a=7
45 DB 2 ; a=8
46 DB 2 ; a=9
47 DB 0 ; a=10
48 DB 4 ; a=11
49 DB 4 ; a=12
50 DB 4 ; a=13
51 DB 4 ; a=14
52 DB 4 ; a=15
53 DB 4 ; a=16
54 DB 4 ; a=17
55 DB 4 ; a=18
56 DB 4 ; a=19
57 DB 2 ; a=20
58 DB 2 ; a=21
59 DB 3 ; a=22
60 _f ENDP
We see two tables here: the first table ($LN10@f) is an index table, and the second one ($LN11@f) is an array of pointers
to blocks.
First, the input value is used as an index in the index table (line 13).
Here is a short legend for the values in the table: 0 is the first case block (for values 1, 2, 7, 10), 1 is the second one (for
values 3, 4, 5), 2 is the third one (for values 8, 9, 21), 3 is the fourth one (for value 22), 4 is for the default block.
There we get an index for the second table of code pointers and we jump to it (line 14).
What is also worth noting is that there is no case for input value 0. That’s why we see the DEC instruction at line 10,
and the table starts at a = 1, because there is no need to allocate a table element for a = 0.
This is a very widespread pattern.
So why is this economical? Why isn’t it possible to make it as before ( 13.2.1 on page 157), just with one table consisting
of block pointers? The reason is that the elements in index table are 8-bit, hence it’s all more compact.
13.3.2 GCC
GCC does the job in the way we already discussed ( 13.2.1 on page 157), using just one table of pointers.
13.3.3 ARM64: Optimizing GCC 4.9.1
There is no code to be triggered if the input value is 0, so GCC tries to make the jump table more compact and so it starts at
1 as an input value.
GCC 4.9.1 for ARM64 uses an even cleverer trick. It’s able to encode all offsets as 8-bit bytes. Let’s recall that all ARM64
instructions have a size of 4 bytes. GCC is uses the fact that all offsets in my tiny example are in close proximity to each
other. So the jump table consisting of single bytes.
Listing 13.11: Optimizing GCC 4.9.1 ARM64
f14:
; input value in W0
sub w0, w0, #1
cmp w0, 21
; branch if less or equal (unsigned):
bls .L9
.L2:
; print "default":
adrp x0, .LC4
add x0, x0, :lo12:.LC4
b puts
.L9:
164
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK
; load jumptable address to X1:
adrp x1, .L4
add x1, x1, :lo12:.L4
; W0=input_value-1
; load byte from the table:
ldrb w0, [x1,w0,uxtw]
; load address of the Lrtx label:
adr x1, .Lrtx4
; multiply table element by 4 (by shifting 2 bits left) and add (or subtract) to the address of
Lrtx:
add x0, x1, w0, sxtb #2
; jump to the calculated address:
br x0
; this label is pointing in code (text) segment:
.Lrtx4:
.section .rodata
; everything after ".section" statement is allocated in the read-only data (rodata) segment:
.L4:
.byte (.L3 - .Lrtx4) / 4 ; case 1
.byte (.L3 - .Lrtx4) / 4 ; case 2
.byte (.L5 - .Lrtx4) / 4 ; case 3
.byte (.L5 - .Lrtx4) / 4 ; case 4
.byte (.L5 - .Lrtx4) / 4 ; case 5
.byte (.L5 - .Lrtx4) / 4 ; case 6
.byte (.L3 - .Lrtx4) / 4 ; case 7
.byte (.L6 - .Lrtx4) / 4 ; case 8
.byte (.L6 - .Lrtx4) / 4 ; case 9
.byte (.L3 - .Lrtx4) / 4 ; case 10
.byte (.L2 - .Lrtx4) / 4 ; case 11
.byte (.L2 - .Lrtx4) / 4 ; case 12
.byte (.L2 - .Lrtx4) / 4 ; case 13
.byte (.L2 - .Lrtx4) / 4 ; case 14
.byte (.L2 - .Lrtx4) / 4 ; case 15
.byte (.L2 - .Lrtx4) / 4 ; case 16
.byte (.L2 - .Lrtx4) / 4 ; case 17
.byte (.L2 - .Lrtx4) / 4 ; case 18
.byte (.L2 - .Lrtx4) / 4 ; case 19
.byte (.L6 - .Lrtx4) / 4 ; case 20
.byte (.L6 - .Lrtx4) / 4 ; case 21
.byte (.L7 - .Lrtx4) / 4 ; case 22
.text
; everything after ".text" statement is allocated in the code (text) segment:
.L7:
; print "22"
adrp x0, .LC3
add x0, x0, :lo12:.LC3
b puts
.L6:
; print "8, 9, 21"
adrp x0, .LC2
add x0, x0, :lo12:.LC2
b puts
.L5:
; print "3, 4, 5"
adrp x0, .LC1
add x0, x0, :lo12:.LC1
b puts
.L3:
; print "1, 2, 7, 10"
adrp x0, .LC0
add x0, x0, :lo12:.LC0
b puts
.LC0:
.string "1, 2, 7, 10"
.LC1:
.string "3, 4, 5"
.LC2:
.string "8, 9, 21"
.LC3:
.string "22"
165
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.4. FALL-THROUGH
.LC4:
.string "default"
I just compiled my example to object file and opened it in IDA. Here is the jump table:
Listing 13.12: jumptable in IDA
.rodata:0000000000000064 AREA .rodata, DATA, READONLY
.rodata:0000000000000064 ; ORG 0x64
.rodata:0000000000000064 $d DCB 9 ; case 1
.rodata:0000000000000065 DCB 9 ; case 2
.rodata:0000000000000066 DCB 6 ; case 3
.rodata:0000000000000067 DCB 6 ; case 4
.rodata:0000000000000068 DCB 6 ; case 5
.rodata:0000000000000069 DCB 6 ; case 6
.rodata:000000000000006A DCB 9 ; case 7
.rodata:000000000000006B DCB 3 ; case 8
.rodata:000000000000006C DCB 3 ; case 9
.rodata:000000000000006D DCB 9 ; case 10
.rodata:000000000000006E DCB 0xF7 ; case 11
.rodata:000000000000006F DCB 0xF7 ; case 12
.rodata:0000000000000070 DCB 0xF7 ; case 13
.rodata:0000000000000071 DCB 0xF7 ; case 14
.rodata:0000000000000072 DCB 0xF7 ; case 15
.rodata:0000000000000073 DCB 0xF7 ; case 16
.rodata:0000000000000074 DCB 0xF7 ; case 17
.rodata:0000000000000075 DCB 0xF7 ; case 18
.rodata:0000000000000076 DCB 0xF7 ; case 19
.rodata:0000000000000077 DCB 3 ; case 20
.rodata:0000000000000078 DCB 3 ; case 21
.rodata:0000000000000079 DCB 0 ; case 22
.rodata:000000000000007B ; .rodata ends
So in case of 1, 9 is to be multiplied by 4 and added to the address of Lrtx4 label. In case of 22, 0 is to be multiplied
by 4, resulting in 0. Right after the Lrtx4 label is the L7 label, where you can find the code that prints “22”. There is no
jump table in the code segment, it’s allocated in a separate .rodata section (there is no special need to place it in the code
section).
There are also negative bytes (0xF7), they are used for jumping back to the code that prints the “default” string (at .L2).
13.4 Fall-through
Another very popular usage of switch() is the fall-through. Here is a small example:
1 #define R 1
2 #define W 2
3 #define RW 3
4
5 void f(int type)
6 {
7 int read=0, write=0;
8
9 switch (type)
10 {
11 case RW:
12 read=1;
13 case W:
14 write=1;
15 break;
16 case R:
17 read=1;
18 break;
19 default:
20 break;
21 };
22 printf ("read=%d, write=%dn", read, write);
23 };
If type = 1 (R), read is to be set to 1, if type = 2 (W), write is to be set to 2. In case of type = 3 (RW), both read and write
is to be set to 1.
166
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.4. FALL-THROUGH
The code at line 14 is executed in two cases: if type = RW or if type = W. There is no “break” for “case RW”x and that’s
OK.
13.4.1 MSVC x86
Listing 13.13: MSVC 2012
$SG1305 DB 'read=%d, write=%d', 0aH, 00H
_write$ = -12 ; size = 4
_read$ = -8 ; size = 4
tv64 = -4 ; size = 4
_type$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
sub esp, 12
mov DWORD PTR _read$[ebp], 0
mov DWORD PTR _write$[ebp], 0
mov eax, DWORD PTR _type$[ebp]
mov DWORD PTR tv64[ebp], eax
cmp DWORD PTR tv64[ebp], 1 ; R
je SHORT $LN2@f
cmp DWORD PTR tv64[ebp], 2 ; W
je SHORT $LN3@f
cmp DWORD PTR tv64[ebp], 3 ; RW
je SHORT $LN4@f
jmp SHORT $LN5@f
$LN4@f: ; case RW:
mov DWORD PTR _read$[ebp], 1
$LN3@f: ; case W:
mov DWORD PTR _write$[ebp], 1
jmp SHORT $LN5@f
$LN2@f: ; case R:
mov DWORD PTR _read$[ebp], 1
$LN5@f: ; default
mov ecx, DWORD PTR _write$[ebp]
push ecx
mov edx, DWORD PTR _read$[ebp]
push edx
push OFFSET $SG1305 ; 'read=%d, write=%d'
call _printf
add esp, 12
mov esp, ebp
pop ebp
ret 0
_f ENDP
The code mostly resembles what is in the source. There are no jumps between labels $LN4@f and $LN3@f: so when
code flow is at $LN4@f, read is first set to 1, then write. This is why it’s called fall-through: code flow falls through one
piece of code (setting read) to another (setting write). If type = W, we land at $LN3@f, so no code setting read to 1 is
executed.
13.4.2 ARM64
Listing 13.14: GCC (Linaro) 4.9
.LC0:
.string "read=%d, write=%dn"
f:
stp x29, x30, [sp, -48]!
add x29, sp, 0
str w0, [x29,28]
str wzr, [x29,44] ; set "read" and "write" local variables to zero
str wzr, [x29,40]
ldr w0, [x29,28] ; load "type" argument
cmp w0, 2 ; type=W?
beq .L3
167
CHAPTER 13. SWITCH()/CASE/DEFAULT 13.5. EXERCISES
cmp w0, 3 ; type=RW?
beq .L4
cmp w0, 1 ; type=R?
beq .L5
b .L6 ; otherwise...
.L4: ; case RW
mov w0, 1
str w0, [x29,44] ; read=1
.L3: ; case W
mov w0, 1
str w0, [x29,40] ; write=1
b .L6
.L5: ; case R
mov w0, 1
str w0, [x29,44] ; read=1
nop
.L6: ; default
adrp x0, .LC0 ; "read=%d, write=%dn"
add x0, x0, :lo12:.LC0
ldr w1, [x29,44] ; load "read"
ldr w2, [x29,40] ; load "write"
bl printf
ldp x29, x30, [sp], 48
ret
Merely the same thing. There are no jumps between labels .L4 and .L3.
13.5 Exercises
13.5.1 Exercise #1
It’s possible to rework the C example in 13.2 on page 152 in such way that the compiler can produce even smaller code, but
will work just the same. Try to achieve it.
Hint: G.1.3 on page 954.
168
CHAPTER 14. LOOPS
Chapter 14
Loops
14.1 Simple example
14.1.1 x86
There is a special LOOP instruction in x86 instruction set for checking the value in register ECX and if it is not 0, to decrement
ECX and pass control flow to the label in the LOOP operand. Probably this instruction is not very convenient, as I never saw
any modern compiler emit it automatically. So, if you see this instruction somewhere in code, it is most likely that this is a
manually written piece of assembly code.
In C/C++ loops are usually constructed using for(), while() or do/while() statements.
Let’s start with for().
This statement defines loop initialization (set loop counter to initial value), loop condition (is the counter bigger than a
limit?), what is done at each iteration (increment/decrement) and of course loop body.
for (initialization; condition; at each iteration)
{
loop_body;
}
The generated code is consisting of four parts as well.
Let’s start with a simple example:
#include <stdio.h>
void printing_function(int i)
{
printf ("f(%d)n", i);
};
int main()
{
int i;
for (i=2; i<10; i++)
printing_function(i);
return 0;
};
Result (MSVC 2010):
Listing 14.1: MSVC 2010
_i$ = -4
_main PROC
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _i$[ebp], 2 ; loop initialization
jmp SHORT $LN3@main
$LN2@main:
mov eax, DWORD PTR _i$[ebp] ; here is what we do after each iteration:
add eax, 1 ; add 1 to (i) value
mov DWORD PTR _i$[ebp], eax
169
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
$LN3@main:
cmp DWORD PTR _i$[ebp], 10 ; this condition is checked *before* each iteration
jge SHORT $LN1@main ; if (i) is biggest or equals to 10, lets finish loop'
mov ecx, DWORD PTR _i$[ebp] ; loop body: call printing_function(i)
push ecx
call _printing_function
add esp, 4
jmp SHORT $LN2@main ; jump to loop begin
$LN1@main: ; loop end
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
As we see, nothing special.
GCC 4.4.1 emits almost the same code, with one subtle difference:
Listing 14.2: GCC 4.4.1
main proc near
var_20 = dword ptr -20h
var_4 = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 20h
mov [esp+20h+var_4], 2 ; (i) initializing
jmp short loc_8048476
loc_8048465:
mov eax, [esp+20h+var_4]
mov [esp+20h+var_20], eax
call printing_function
add [esp+20h+var_4], 1 ; (i) increment
loc_8048476:
cmp [esp+20h+var_4], 9
jle short loc_8048465 ; if i<=9, continue loop
mov eax, 0
leave
retn
main endp
Now let’s see what we get with optimization turned on (/Ox):
Listing 14.3: Optimizing MSVC
_main PROC
push esi
mov esi, 2
$LL3@main:
push esi
call _printing_function
inc esi
add esp, 4
cmp esi, 10 ; 0000000aH
jl SHORT $LL3@main
xor eax, eax
pop esi
ret 0
_main ENDP
What happens here is that space for the i variable is not allocated in the local stack anymore, but uses an individual
register for it, ESI. This is possible in such small functions where there aren’t many local variables.
One very important thing is that the f() function must not change the value in ESI. Our compiler is sure here. And if
the compiler decides to use the ESI register in f() too, its value would have to be saved at the function’s prologue and
restored at the function’s epilogue, almost like in our listing: please note PUSH ESI/POP ESI at the function start and
end.
Let’s try GCC 4.4.1 with maximal optimization turned on (-O3 option):
170
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
Listing 14.4: Optimizing GCC 4.4.1
main proc near
var_10 = dword ptr -10h
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
mov [esp+10h+var_10], 2
call printing_function
mov [esp+10h+var_10], 3
call printing_function
mov [esp+10h+var_10], 4
call printing_function
mov [esp+10h+var_10], 5
call printing_function
mov [esp+10h+var_10], 6
call printing_function
mov [esp+10h+var_10], 7
call printing_function
mov [esp+10h+var_10], 8
call printing_function
mov [esp+10h+var_10], 9
call printing_function
xor eax, eax
leave
retn
main endp
Huh, GCC just unwound our loop.
Loop unwinding has an advantage in the cases when there aren’t much iterations and we could cut some execution time
by removing all loop support instructions. On the other side, the resulting code is obviously larger.
Big unrolled loops are not recommended in modern times, because bigger functions may require bigger cache footprint 1
.
OK, let’s increase the maximum value of the i variable to 100 and try again. GCC does:
Listing 14.5: GCC
public main
main proc near
var_20 = dword ptr -20h
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
push ebx
mov ebx, 2 ; i=2
sub esp, 1Ch
; aligning label loc_80484D0 (loop body begin) by 16-byte border:
nop
loc_80484D0:
; pass (i) as first argument to printing_function():
mov [esp+20h+var_20], ebx
add ebx, 1 ; i++
call printing_function
cmp ebx, 64h ; i==100?
jnz short loc_80484D0 ; if not, continue
add esp, 1Ch
xor eax, eax ; return 0
pop ebx
mov esp, ebp
pop ebp
retn
main endp
1A very good article about it: [Dre07]. Another recommendations about loop unrolling from Intel are here : [Int14, p. 3.4.1.7].
171
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
It is quite similar to what MSVC 2010 with optimization (/Ox) produce, with the exception that the EBX register is
allocated for the i variable. GCC is sure this register will not be modified inside of the f() function, and if it will, it will be
saved at the function prologue and restored at epilogue, just like here in the main() function.
172
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
14.1.2 x86: OllyDbg
Let’s compile our example in MSVC 2010 with /Ox and /Ob0 options and load it into OllyDbg.
It seems that OllyDbg is able to detect simple loops and show them in square brackets, for convenience:
Figure 14.1: OllyDbg: main() begin
By tracing (F8 (step over)) we see ESI incrementing. Here, for instance, ESI = i = 6:
Figure 14.2: OllyDbg: loop body just executed with i = 6
9 is the last loop value. That’s why JL is not triggering after the increment, and the function will finish:
Figure 14.3: OllyDbg: ESI = 10, loop end
14.1.3 x86: tracer
As we might see, it is not very convenient to trace manulally in the debugger. That’s one of the reasons I wrote a tracer for
myself.
We open compiled example in IDA, find the address of the instruction PUSH ESI (passing the sole argument to f())
which is 0x401026 for me and we run the tracer:
tracer.exe -l:loops_2.exe bpx=loops_2.exe!0x00401026
BPX just sets a breakpoint at the address and tracer will then print the state of the registers.
In the tracer.log This is what we see:
PID=12884|New process loops_2.exe
173
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
(0) loops_2.exe!0x401026
EAX=0x00a328c8 EBX=0x00000000 ECX=0x6f0f4714 EDX=0x00000000
ESI=0x00000002 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=PF ZF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000003 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF PF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000004 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF PF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000005 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000006 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF PF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000007 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000008 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF AF SF IF
(0) loops_2.exe!0x401026
EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188
ESI=0x00000009 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8
EIP=0x00331026
FLAGS=CF PF AF SF IF
PID=12884|Process loops_2.exe exited. ExitCode=0 (0x0)
We see how the value of ESI register changes from 2 to 9.
Even more than that, the tracer can collect register values for all addresses within the function. This is called trace there.
Every instruction gets traced, all interesting register values are recorded. Then, an IDA.idc-script is generated, that adds
comments. So, in the IDA we’ve learned that the main() function address is 0x00401020 and we run:
tracer.exe -l:loops_2.exe bpf=loops_2.exe!0x00401020,trace:cc
BPF stands for set breakpoint on function.
As a result, we get the loops_2.exe.idc and loops_2.exe_clear.idc scripts.
174
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
We load loops_2.exe.idc into IDA and see:
Figure 14.4: IDA with .idc-script loaded
We see that ESI can be from 2 to 9 at the start of the loop body, but from 3 to 0xA (10) after the increment. We can also
see that main() is finishing with 0 in EAX.
tracer also generates loops_2.exe.txt, that contains information about how many times each instruction was exe-
cuted and register values:
Listing 14.6: loops_2.exe.txt
0x401020 (.text+0x20), e= 1 [PUSH ESI] ESI=1
0x401021 (.text+0x21), e= 1 [MOV ESI, 2]
0x401026 (.text+0x26), e= 8 [PUSH ESI] ESI=2..9
0x401027 (.text+0x27), e= 8 [CALL 8D1000h] tracing nested maximum level (1) reached, ⤦
skipping this CALL 8D1000h=0x8d1000
0x40102c (.text+0x2c), e= 8 [INC ESI] ESI=2..9
0x40102d (.text+0x2d), e= 8 [ADD ESP, 4] ESP=0x38fcbc
0x401030 (.text+0x30), e= 8 [CMP ESI, 0Ah] ESI=3..0xa
0x401033 (.text+0x33), e= 8 [JL 8D1026h] SF=false,true OF=false
0x401035 (.text+0x35), e= 1 [XOR EAX, EAX]
0x401037 (.text+0x37), e= 1 [POP ESI]
0x401038 (.text+0x38), e= 1 [RETN] EAX=0
We can use grep here.
14.1.4 ARM
Non-optimizing Keil 6/2013 (ARM mode)
main
STMFD SP!, {R4,LR}
MOV R4, #2
B loc_368
loc_35C ; CODE XREF: main+1C
MOV R0, R4
BL printing_function
ADD R4, R4, #1
loc_368 ; CODE XREF: main+8
CMP R4, #0xA
BLT loc_35C
MOV R0, #0
175
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
LDMFD SP!, {R4,PC}
Iteration counter i is to be stored in the R4 register.
The ``MOV R4, #2'' instruction just initializes i.
The ``MOV R0, R4'' and ``BL printing_function'' instructions compose the body of the loop, the first
instruction preparing the argument for f() function and the second calling the function.
The ``ADD R4, R4, #1'' instruction just adds 1 to the i variable at each iteration.
``CMP R4, #0xA'' compares i with 0xA (10). The next instruction BLT (Branch Less Than) jumps if i is less than 10.
Otherwise, 0 is to be written into R0 (since our function returns 0) and function execution finishes.
Optimizing Keil 6/2013 (thumb mode)
_main
PUSH {R4,LR}
MOVS R4, #2
loc_132 ; CODE XREF: _main+E
MOVS R0, R4
BL printing_function
ADDS R4, R4, #1
CMP R4, #0xA
BLT loc_132
MOVS R0, #0
POP {R4,PC}
Practically the same.
Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
_main
PUSH {R4,R7,LR}
MOVW R4, #0x1124 ; "%dn"
MOVS R1, #2
MOVT.W R4, #0
ADD R7, SP, #4
ADD R4, PC
MOV R0, R4
BLX _printf
MOV R0, R4
MOVS R1, #3
BLX _printf
MOV R0, R4
MOVS R1, #4
BLX _printf
MOV R0, R4
MOVS R1, #5
BLX _printf
MOV R0, R4
MOVS R1, #6
BLX _printf
MOV R0, R4
MOVS R1, #7
BLX _printf
MOV R0, R4
MOVS R1, #8
BLX _printf
MOV R0, R4
MOVS R1, #9
BLX _printf
MOVS R0, #0
POP {R4,R7,PC}
In fact, this was in my f() function:
void printing_function(int i)
{
printf ("%dn", i);
};
176
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
So, LLVM not just unrolled the loop, but also inlined my very simple function f(), and inserted its body 8 times instead
of calling it. This is possible when the function is so primitive (like mine) and when it is not called too much (like here).
ARM64: Optimizing GCC 4.9.1
Listing 14.7: Optimizing GCC 4.9.1
printing_function:
; prepare second argument of printf():
mov w1, w0
; load address of the "f(%d)n" string
adrp x0, .LC0
add x0, x0, :lo12:.LC0
; just branch here instead of branch with link and return:
b printf
main:
; save FP and LR in the local stack:
stp x29, x30, [sp, -32]!
; set up stack frame:
add x29, sp, 0
; save contents of X19 register in the local stack:
str x19, [sp,16]
; we will use W19 register as counter.
; set initial value of 2 to it:
mov w19, 2
.L3:
; prepare first argument of printing_function():
mov w0, w19
; increment counter register.
add w19, w19, 1
; W0 here still holds value of counter value before increment.
bl printing_function
; is it end?
cmp w19, 10
; no, jump to the loop body begin:
bne .L3
; return 0
mov w0, 0
; restore contents of X19 register:
ldr x19, [sp,16]
; restore FP and LR values:
ldp x29, x30, [sp], 32
ret
.LC0:
.string "f(%d)n"
ARM64: Non-optimizing GCC 4.9.1
Listing 14.8: Non-optimizing GCC 4.9.1 -fno-inline
printing_function:
; prepare second argument of printf():
mov w1, w0
; load address of the "f(%d)n" string
adrp x0, .LC0
add x0, x0, :lo12:.LC0
; just branch here instead of branch with link and return:
b printf
main:
; save FP and LR in the local stack:
stp x29, x30, [sp, -32]!
; set up stack frame:
add x29, sp, 0
; save contents of X19 register in the local stack:
str x19, [sp,16]
; we will use W19 register as counter.
; set initial value of 2 to it:
mov w19, 2
177
CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE
.L3:
; prepare first argument of printing_function():
mov w0, w19
; increment counter register.
add w19, w19, 1
; W0 here still holds value of counter value before increment.
bl printing_function
; is it end?
cmp w19, 10
; no, jump to the loop body begin:
bne .L3
; return 0
mov w0, 0
; restore contents of X19 register:
ldr x19, [sp,16]
; restore FP and LR values:
ldp x29, x30, [sp], 32
ret
.LC0:
.string "f(%d)n"
14.1.5 MIPS
Listing 14.9: Non-optimizing GCC 4.4.5 (IDA)
main:
; IDA is not aware of variable names in local stack
; I gave them names manually:
i = -0x10
saved_FP = -8
saved_RA = -4
; function prologue:
addiu $sp, -0x28
sw $ra, 0x28+saved_RA($sp)
sw $fp, 0x28+saved_FP($sp)
move $fp, $sp
; initialize counter at 2 and store this value in local stack
li $v0, 2
sw $v0, 0x28+i($fp)
; pseudoinstruction. "BEQ $ZERO, $ZERO, loc_9C" there in fact:
b loc_9C
or $at, $zero ; branch delay slot, NOP
# ---------------------------------------------------------------------------
loc_80: # CODE XREF: main+48
; load counter value from local stack and call printing_function():
lw $a0, 0x28+i($fp)
jal printing_function
or $at, $zero ; branch delay slot, NOP
; load counter, increment it, store it back:
lw $v0, 0x28+i($fp)
or $at, $zero ; NOP
addiu $v0, 1
sw $v0, 0x28+i($fp)
loc_9C: # CODE XREF: main+18
; check counter, is it 10?
lw $v0, 0x28+i($fp)
or $at, $zero ; NOP
slti $v0, 0xA
; if it is less than 10, jump to loc_80 (loop body begin):
bnez $v0, loc_80
or $at, $zero ; branch delay slot, NOP
; finishing, return 0:
move $v0, $zero
; function epilogue:
move $sp, $fp
178
CHAPTER 14. LOOPS 14.2. MEMORY BLOCKS COPYING ROUTINE
lw $ra, 0x28+saved_RA($sp)
lw $fp, 0x28+saved_FP($sp)
addiu $sp, 0x28
jr $ra
or $at, $zero ; branch delay slot, NOP
The instruction that’s new to us is “B”. It is actually the pseudoinstruction (BEQ).
14.1.6 One more thing
In the generated code we can see: after initializing i , the body of the loop is not to be executed, as the condition for i is
checked first, and only after that loop body can be executed. And that is correct. Because, if the loop condition is not met
at the beginning, the body of the loop must not be executed. This is possible in the following case:
for (i=0; i<total_entries_to_process; i++)
loop_body;
If total_entries_to_process is 0, the body of the loo must not be executed at all. This is why the condition checked before
the execution.
However, an optimizing compiler may swap the condition check and loop body, if it sure that the situation described here
is not possible (like in the case of our very simple example and Keil, Xcode (LLVM), MSVC in optimization mode).
14.2 Memory blocks copying routine
Real-world memory copy routines may copy 4 or 8 bytes at each iteration, use SIMD2
, vectorization, etc. But for the sake of
simplicity, this example is the simplest possible.
#include <stdio.h>
void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt)
{
size_t i;
for (i=0; i<cnt; i++)
dst[i]=src[i];
};
14.2.1 Straight-forward implementation
Listing 14.10: GCC 4.9 x64 optimized for size (-Os)
my_memcpy:
; RDI = destination address
; RSI = source address
; RDX = size of block
; initialize counter (i) at 0
xor eax, eax
.L2:
; all bytes copied? exit then:
cmp rax, rdx
je .L5
; load byte at RSI+i:
mov cl, BYTE PTR [rsi+rax]
; store byte at RDI+i:
mov BYTE PTR [rdi+rax], cl
inc rax ; i++
jmp .L2
.L5:
ret
Listing 14.11: GCC 4.9 ARM64 optimized for size (-Os)
my_memcpy:
; X0 = destination address
; X1 = source address
2Single instruction, multiple data
179
CHAPTER 14. LOOPS 14.2. MEMORY BLOCKS COPYING ROUTINE
; X2 = size of block
; initialize counter (i) at 0
mov x3, 0
.L2:
; all bytes copied? exit then:
cmp x3, x2
beq .L5
; load byte at X1+i:
ldrb w4, [x1,x3]
; store byte at X1+i:
strb w4, [x0,x3]
add x3, x3, 1 ; i++
b .L2
.L5:
ret
Listing 14.12: Optimizing Keil 6/2013 (thumb mode)
my_memcpy PROC
; R0 = destination address
; R1 = source address
; R2 = size of block
PUSH {r4,lr}
; initialize counter (i) at 0
MOVS r3,#0
; condition checked at the end of function, so jump there:
B |L0.12|
|L0.6|
; load byte at R1+i:
LDRB r4,[r1,r3]
; store byte at R1+i:
STRB r4,[r0,r3]
; i++
ADDS r3,r3,#1
|L0.12|
; i<size?
CMP r3,r2
; jump to the loop begin if its so:'
BCC |L0.6|
POP {r4,pc}
ENDP
14.2.2 ARM in ARM mode
Keil in ARM mode takes full advantage of conditional suffixes:
Listing 14.13: Optimizing Keil 6/2013 (ARM mode)
my_memcpy PROC
; R0 = destination address
; R1 = source address
; R2 = size of block
; initialize counter (i) at 0
MOV r3,#0
|L0.4|
; all bytes copied?
CMP r3,r2
; the following block is executed only if "less than" condition,
; i.e., if R2<R3 or i<size.
; load byte at R1+i:
LDRBCC r12,[r1,r3]
; store byte at R1+i:
STRBCC r12,[r0,r3]
; i++
ADDCC r3,r3,#1
; the last instruction of the "conditional block".
180
CHAPTER 14. LOOPS 14.3. CONCLUSION
; jump to loop begin if i<size
; do nothing otherwise (i.e., if i>=size)
BCC |L0.4|
; return
BX lr
ENDP
That’s why there is only one branch instruction instead of 2.
14.2.3 MIPS
Listing 14.14: GCC 4.4.5 optimized for size (-Os) (IDA)
my_memcpy:
; jump to loop check part:
b loc_14
; initialize counter (i) at 0
; it will always reside in $v0:
move $v0, $zero ; branch delay slot
loc_8: # CODE XREF: my_memcpy+1C
; load byte as unsigned at address in $t0 to $v1:
lbu $v1, 0($t0)
; increment counter (i):
addiu $v0, 1
; store byte at $a3
sb $v1, 0($a3)
loc_14: # CODE XREF: my_memcpy
; check if counter (i) in $v0 is still less then 3rd function argument ("cnt" in $a2):
sltu $v1, $v0, $a2
; form address of byte in source block:
addu $t0, $a1, $v0
; $t0 = $a1+$v0 = src+i
; jump to loop body if counter sill less then "cnt":
bnez $v1, loc_8
; form address of byte in destination block ($a3 = $a0+$v0 = dst+i):
addu $a3, $a0, $v0 ; branch delay slot
; finish if BNEZ wasnt triggered:'
jr $ra
or $at, $zero ; branch delay slot, NOP
Here we have two new instructions: LBU (“Load Byte Unsigned”) and SB (“Store Byte”). Just like in ARM, all MIPS registers
are 32-bit wide, there are no byte-wide parts like in x86. So when dealing with single bytes, we have to allocate whole
32-bit registers for them. LBU loads a byte and clears all other bits (“Unsigned”). On the other hand, LB (“Load Byte”)
instruction sign-extends the loaded byte to a 32-bit value. SB just writes a byte from lowest 8 bits of register to memory.
14.2.4 Vectorization
Optimizing GCC can do much more on this example: 25.1.2 on page 419.
14.3 Conclusion
Rough skeleton of loop from 2 to 9 inclusive:
Listing 14.15: x86
mov [counter], 2 ; initialization
jmp check
body:
; loop body
; do something here
; use counter variable in local stack
add [counter], 1 ; increment
check:
cmp [counter], 9
jle body
181
CHAPTER 14. LOOPS 14.3. CONCLUSION
The increment operation may be represented as 3 instructions in non-optimized code:
Listing 14.16: x86
MOV [counter], 2 ; initialization
JMP check
body:
; loop body
; do something here
; use counter variable in local stack
MOV REG, [counter] ; increment
INC REG
MOV [counter], REG
check:
CMP [counter], 9
JLE body
If the body of the loop is short, a whole register can be dedicated to the counter variable:
Listing 14.17: x86
MOV EBX, 2 ; initialization
JMP check
body:
; loop body
; do something here
; use counter in EBX, but do not modify it!
INC EBX ; increment
check:
CMP EBX, 9
JLE body
Some parts of the loop may be generated by compiler in different order:
Listing 14.18: x86
MOV [counter], 2 ; initialization
JMP label_check
label_increment:
ADD [counter], 1 ; increment
label_check:
CMP [counter], 10
JGE exit
; loop body
; do something here
; use counter variable in local stack
JMP label_increment
exit:
Usually the condition is checked before loop body, but the compiler may rearrange it in a way that the condition is checked
after loop body. This is done when the compiler is sure that the condition is always true on the first iteration, so the body
of the loop is to be executed at least once:
Listing 14.19: x86
MOV REG, 2 ; initialization
body:
; loop body
; do something here
; use counter in REG, but do not modify it!
INC REG ; increment
CMP REG, 10
JL body
Using the LOOP instruction. This is rare, compilers are not using it. When you see it, it’s a sign that this piece of code is
hand-written:
Listing 14.20: x86
; count from 10 to 1
MOV ECX, 10
body:
; loop body
; do something here
182
CHAPTER 14. LOOPS 14.4. EXERCISES
; use counter in ECX, but do not modify it!
LOOP body
ARM. The R4 register is dedicated to counter variable in this example:
Listing 14.21: ARM
MOV R4, 2 ; initialization
B check
body:
; loop body
; do something here
; use counter in R4, but do not modify it!
ADD R4,R4, #1 ; increment
check:
CMP R4, #10
BLT body
14.4 Exercises
14.4.1 Exercise #1
Why isn’t the LOOP instruction used by modern compilers anymore?
14.4.2 Exercise #2
Take a loop example from this section ( 14.1.1 on page 169), compile it in your favorite OS and compiler and modify (patch)
the executable file so the loop range will be [6..20].
14.4.3 Exercise #3
What does this code do?
Listing 14.22: Optimizing MSVC 2010
$SG2795 DB '%d', 0aH, 00H
_main PROC
push esi
push edi
mov edi, DWORD PTR __imp__printf
mov esi, 100
npad 3 ; align next label
$LL3@main:
push esi
push OFFSET $SG2795 ; '%d'
call edi
dec esi
add esp, 8
test esi, esi
jg SHORT $LL3@main
pop edi
xor eax, eax
pop esi
ret 0
_main ENDP
Listing 14.23: Non-optimizing Keil 6/2013 (ARM mode)
main PROC
PUSH {r4,lr}
MOV r4,#0x64
|L0.8|
MOV r1,r4
ADR r0,|L0.40|
BL __2printf
SUB r4,r4,#1
CMP r4,#0
183
CHAPTER 14. LOOPS 14.4. EXERCISES
MOVLE r0,#0
BGT |L0.8|
POP {r4,pc}
ENDP
|L0.40|
DCB "%dn",0
Listing 14.24: Non-optimizing Keil 6/2013 (thumb mode)
main PROC
PUSH {r4,lr}
MOVS r4,#0x64
|L0.4|
MOVS r1,r4
ADR r0,|L0.24|
BL __2printf
SUBS r4,r4,#1
CMP r4,#0
BGT |L0.4|
MOVS r0,#0
POP {r4,pc}
ENDP
DCW 0x0000
|L0.24|
DCB "%dn",0
Listing 14.25: Optimizing GCC 4.9 (ARM64)
main:
stp x29, x30, [sp, -32]!
add x29, sp, 0
stp x19, x20, [sp,16]
adrp x20, .LC0
mov w19, 100
add x20, x20, :lo12:.LC0
.L2:
mov w1, w19
mov x0, x20
bl printf
subs w19, w19, #1
bne .L2
ldp x19, x20, [sp,16]
ldp x29, x30, [sp], 32
ret
.LC0:
.string "%dn"
Listing 14.26: Optimizing GCC 4.4.5 (MIPS) (IDA)
main:
var_18 = -0x18
var_C = -0xC
var_8 = -8
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x28
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x28+var_4($sp)
sw $s1, 0x28+var_8($sp)
sw $s0, 0x28+var_C($sp)
sw $gp, 0x28+var_18($sp)
la $s1, $LC0 # "%dn"
li $s0, 0x64 # 'd'
loc_28: # CODE XREF: main+40
lw $t9, (printf & 0xFFFF)($gp)
184
CHAPTER 14. LOOPS 14.4. EXERCISES
move $a1, $s0
move $a0, $s1
jalr $t9
addiu $s0, -1
lw $gp, 0x28+var_18($sp)
bnez $s0, loc_28
or $at, $zero
lw $ra, 0x28+var_4($sp)
lw $s1, 0x28+var_8($sp)
lw $s0, 0x28+var_C($sp)
jr $ra
addiu $sp, 0x28
$LC0: .ascii "%dn"<0> # DATA XREF: main+1C
Answer: G.1.5 on page 954.
14.4.4 Exercise #4
What does this code do?
Listing 14.27: Optimizing MSVC 2010
$SG2795 DB '%d', 0aH, 00H
_main PROC
push esi
push edi
mov edi, DWORD PTR __imp__printf
mov esi, 1
npad 3 ; align next label
$LL3@main:
push esi
push OFFSET $SG2795 ; '%d'
call edi
add esi, 3
add esp, 8
cmp esi, 100
jl SHORT $LL3@main
pop edi
xor eax, eax
pop esi
ret 0
_main ENDP
Listing 14.28: Non-optimizing Keil 6/2013 (ARM mode)
main PROC
PUSH {r4,lr}
MOV r4,#1
|L0.8|
MOV r1,r4
ADR r0,|L0.40|
BL __2printf
ADD r4,r4,#3
CMP r4,#0x64
MOVGE r0,#0
BLT |L0.8|
POP {r4,pc}
ENDP
|L0.40|
DCB "%dn",0
Listing 14.29: Non-optimizing Keil 6/2013 (thumb mode)
main PROC
PUSH {r4,lr}
MOVS r4,#1
|L0.4|
185
CHAPTER 14. LOOPS 14.4. EXERCISES
MOVS r1,r4
ADR r0,|L0.24|
BL __2printf
ADDS r4,r4,#3
CMP r4,#0x64
BLT |L0.4|
MOVS r0,#0
POP {r4,pc}
ENDP
DCW 0x0000
|L0.24|
DCB "%dn",0
Listing 14.30: Optimizing GCC 4.9 (ARM64)
main:
stp x29, x30, [sp, -32]!
add x29, sp, 0
stp x19, x20, [sp,16]
adrp x20, .LC0
mov w19, 1
add x20, x20, :lo12:.LC0
.L2:
mov w1, w19
mov x0, x20
add w19, w19, 3
bl printf
cmp w19, 100
bne .L2
ldp x19, x20, [sp,16]
ldp x29, x30, [sp], 32
ret
.LC0:
.string "%dn"
Listing 14.31: Optimizing GCC 4.4.5 (MIPS) (IDA)
main:
var_18 = -0x18
var_10 = -0x10
var_C = -0xC
var_8 = -8
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x28
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x28+var_4($sp)
sw $s2, 0x28+var_8($sp)
sw $s1, 0x28+var_C($sp)
sw $s0, 0x28+var_10($sp)
sw $gp, 0x28+var_18($sp)
la $s2, $LC0 # "%dn"
li $s0, 1
li $s1, 0x64 # 'd'
loc_30: # CODE XREF: main+48
lw $t9, (printf & 0xFFFF)($gp)
move $a1, $s0
move $a0, $s2
jalr $t9
addiu $s0, 3
lw $gp, 0x28+var_18($sp)
bne $s0, $s1, loc_30
or $at, $zero
lw $ra, 0x28+var_4($sp)
lw $s2, 0x28+var_8($sp)
lw $s1, 0x28+var_C($sp)
186
CHAPTER 14. LOOPS 14.4. EXERCISES
lw $s0, 0x28+var_10($sp)
jr $ra
addiu $sp, 0x28
$LC0: .ascii "%dn"<0> # DATA XREF: main+20
Answer: G.1.6 on page 955.
187
CHAPTER 15. SIMPLE C-STRINGS PROCESSING
Chapter 15
Simple C-strings processing
15.1 strlen()
Let’s talk about loops one more time. Often, the strlen() function1
is implemented using a while() statement. Here is
how it is done in the MSVC standard libraries:
int my_strlen (const char * str)
{
const char *eos = str;
while( *eos++ ) ;
return( eos - str - 1 );
}
int main()
{
// test
return my_strlen("hello!");
};
15.1.1 x86
Non-optimizing MSVC
Let’s compile:
_eos$ = -4 ; size = 4
_str$ = 8 ; size = 4
_strlen PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _str$[ebp] ; place pointer to string from "str"
mov DWORD PTR _eos$[ebp], eax ; place it to local variable "eos"
$LN2@strlen_:
mov ecx, DWORD PTR _eos$[ebp] ; ECX=eos
; take 8-bit byte from address in ECX and place it as 32-bit value to EDX with sign extension
movsx edx, BYTE PTR [ecx]
mov eax, DWORD PTR _eos$[ebp] ; EAX=eos
add eax, 1 ; increment EAX
mov DWORD PTR _eos$[ebp], eax ; place EAX back to "eos"
test edx, edx ; EDX is zero?
je SHORT $LN1@strlen_ ; yes, then finish loop
jmp SHORT $LN2@strlen_ ; continue loop
$LN1@strlen_:
; here we calculate the difference between two pointers
mov eax, DWORD PTR _eos$[ebp]
1counting the characters in a string in the C language
188
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
sub eax, DWORD PTR _str$[ebp]
sub eax, 1 ; subtract 1 and return result
mov esp, ebp
pop ebp
ret 0
_strlen_ ENDP
We get two new instructions here: MOVSX and TEST.
The first one — MOVSX — takes a byte from an address in memory and stores the value in a 32-bit register. MOVSX stands
for MOV with Sign-Extend. MOVSX sets the rest of the bits, from the 8th to the 31th, to 1 if the source byte is negative or to 0
if is positive.
And here is why.
By default, the char type is signed in MSVC and GCC. If we have two values of which one is char and the other is int, (int
is signed too), and if the first value contain −2 (coded as 0xFE) and we just copy this byte into the int container, it makes
0x000000FE, and this from the point of signed int view is 254, but not −2. In signed int, −2 is coded as 0xFFFFFFFE. So if
we need to transfer 0xFE from a variable of char type to int, we need to identify its sign and extend it. That is what MOVSX
does.
You can also read about it in “Signed number representations” section ( 30 on page 451).
I’m not sure if the compiler needs to store a char variable in EDX, it could just take a 8-bit register part (for example DL).
Apparently, the compiler’s register allocator works like that.
Then we see TEST EDX, EDX. You can read more about the TEST instruction in the section about bit fields ( 19 on
page 305). Here this instruction just checks if the value in EDX equals to 0.
Non-optimizing GCC
Let’s try GCC 4.4.1:
public strlen
strlen proc near
eos = dword ptr -4
arg_0 = dword ptr 8
push ebp
mov ebp, esp
sub esp, 10h
mov eax, [ebp+arg_0]
mov [ebp+eos], eax
loc_80483F0:
mov eax, [ebp+eos]
movzx eax, byte ptr [eax]
test al, al
setnz al
add [ebp+eos], 1
test al, al
jnz short loc_80483F0
mov edx, [ebp+eos]
mov eax, [ebp+arg_0]
mov ecx, edx
sub ecx, eax
mov eax, ecx
sub eax, 1
leave
retn
strlen endp
The result is almost the same as in MSVC, but here we see MOVZX instead of MOVSX. MOVZX stands for MOV with Zero-
Extend. This instruction copies a 8-bit or 16-bit value into a 32-bit register and sets the rest of the bits to 0. In fact, this
instruction is convenient only because it enable us to replace this instruction pair: xor eax, eax / mov al, [...].
On the other hand, it is obvious that the compiler could produce this code: mov al, byte ptr [eax] / test
al, al —it is almost the same, however, the highest bits of the EAX register will contain random noise. But let’s think it
is compiler’s drawback —it cannot produce more understandable code. Strictly speaking, the compiler is not obliged to emit
understandable (to humans) code at all.
The next new instruction for us is SETNZ. Here, if AL doesn’t contain zero, test al, al sets the ZF flag to 0, but SETNZ,
if ZF==0 (NZ stands for not zero) sets AL to 1. Speaking in natural language, if AL is not zero, let’s jump to loc_80483F0. The
compiler emits some redundant code, but let’s not forget that the optimizations are turned off.
189
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
Optimizing MSVC
Now let’s compile all this in MSVC 2012, with optimizations turned on (/Ox):
Listing 15.1: Optimizing MSVC 2012 /Ob0
_str$ = 8 ; size = 4
_strlen PROC
mov edx, DWORD PTR _str$[esp-4] ; EDX -> pointer to the string
mov eax, edx ; move to EAX
$LL2@strlen:
mov cl, BYTE PTR [eax] ; CL = *EAX
inc eax ; EAX++
test cl, cl ; CL==0?
jne SHORT $LL2@strlen ; no, continue loop
sub eax, edx ; calculate pointers difference
dec eax ; decrement EAX
ret 0
_strlen ENDP
Now it is all simpler. Needless to say, the compiler could use registers with such efficiency only in small functions with
a few local variables.
INC/DEC— are increment/decrement instructions, in other words: add or substract 1 to/from a variable.
190
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
Optimizing MSVC + OllyDbg
We can try this (optimized) example in OllyDbg. Here is the first iteration:
Figure 15.1: OllyDbg: first iteration start
We see that OllyDbg found a loop and, for convenience, wrapped its instructions in brackets. By clicking the right button
on EAX, we can choose “Follow in Dump” and the memory window scrolls to the right place. Here we can see the string
“hello!” in memory. There is at least one zero byte after it and then random garbage. If OllyDbg sees a register with a valid
address in it, that points to some string, it is shown as a string.
191
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
Let’s press F8 (step over) a few times, to get to the start of the body of the loop:
Figure 15.2: OllyDbg: second iteration start
We see that EAX contains the address of the second character in the string.
192
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
We have to press F8 enough number of times in order to escape from the loop:
Figure 15.3: OllyDbg: pointers difference to be calculated now
We see that EAX now contains the address of zero byte that’s right after the string. Meanwhile, EDX hasn’t changed, so
it still pointing to the start of the string. The difference between these two addresses is being calculated now.
193
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
The SUB instruction just got executed:
Figure 15.4: OllyDbg: EAX to be decremented now
The difference of pointers is in the EAX register now—7. Indeed, the length of the “hello!” string is 6, but with the zero
byte included—7. But strlen() must return the number of non-zero characters in the string. So the decrement executes
and then the function returns.
Optimizing GCC
Let’s check GCC 4.4.1 with optimizations turned on (-O3 key):
public strlen
strlen proc near
arg_0 = dword ptr 8
push ebp
mov ebp, esp
mov ecx, [ebp+arg_0]
mov eax, ecx
loc_8048418:
movzx edx, byte ptr [eax]
add eax, 1
test dl, dl
jnz short loc_8048418
not ecx
add eax, ecx
pop ebp
retn
strlen endp
Here GCC is almost the same as MSVC, except for the presence of MOVZX.
However, here MOVZX could be replaced with mov dl, byte ptr [eax].
Probably it is simpler for GCC’s code generator to remember the whole 32-bit EDX register is allocated for a char variable
and it then can be sure that the highest bits has no any noise at any point.
After that we also see a new instruction — NOT. This instruction inverts all bits in the operand. You can say that it is
a synonym to the XOR ECX, 0ffffffffh instruction. NOT and the following ADD calculate the pointer difference and
subtract 1, just in a different way. At the start ECX, where the pointer to str is stored, gets inverted and 1 is subtracted from
it.
See also: “Signed number representations” ( 30 on page 451).
In other words, at the end of the function just after loop body, these operations are executed:
194
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
ecx=str;
eax=eos;
ecx=(-ecx)-1;
eax=eax+ecx
return eax
…and this is effectively equivalent to:
ecx=str;
eax=eos;
eax=eax-ecx;
eax=eax-1;
return eax
Why did GCC decide it would be better? I cannot be sure. But I’m sure the both variants are equivalent in efficiency.
15.1.2 ARM
32-bit ARM
Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Listing 15.2: Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)
_strlen
eos = -8
str = -4
SUB SP, SP, #8 ; allocate 8 bytes for local variables
STR R0, [SP,#8+str]
LDR R0, [SP,#8+str]
STR R0, [SP,#8+eos]
loc_2CB8 ; CODE XREF: _strlen+28
LDR R0, [SP,#8+eos]
ADD R1, R0, #1
STR R1, [SP,#8+eos]
LDRSB R0, [R0]
CMP R0, #0
BEQ loc_2CD4
B loc_2CB8
loc_2CD4 ; CODE XREF: _strlen+24
LDR R0, [SP,#8+eos]
LDR R1, [SP,#8+str]
SUB R0, R0, R1 ; R0=eos-str
SUB R0, R0, #1 ; R0=R0-1
ADD SP, SP, #8 ; free allocated 8 bytes
BX LR
Non-optimizing LLVM generates too much code, however, here we can see how the function works with local variables
in the stack. There are only two local variables in our function, eos and str.
In this listing, generated by IDA, I have manually renamed var_8 and var_4 to eos and str .
The first instructions just saves the input values into both str and eos.
The body of the loop starts at label loc_2CB8.
The first three instruction in the loop body (LDR, ADD, STR) load the value of eos into R0, then the value is incremented
and saved back into eos, which is located in the stack.
The next instruction, ``LDRSB R0, [R0]'' (Load Register Signed Byte) , loads a byte from memory at the address
stored in R0 and sign-extends it to 32-bit 2
. This is similar to the MOVSX instruction in x86. The compiler treats this byte
as signed since the char type is signed according to the C standard. I already wrote about it ( 15.1.1 on page 189) in this
section, in relation to x86.
It has to be noted that it is impossible to use 8- or 16-bit part of a 32-bit register in ARM separately of the whole register,
as it is in x86. Apparently, it is because x86 has a huge history of backwards compatibility with its ancestors up to the
16-bit 8086 and even 8-bit 8080, but ARM was developed from scratch as a 32-bit RISC-processor. Consequently, in order
to process separate bytes in ARM, one has to use 32-bit registers anyway.
2The Keil compiler treats the char type as signed, just like MSVC and GCC.
195
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
So, LDRSB loads bytes from the string into R0, one by one. The following CMP and BEQ instructions check if the loaded
byte is 0. If it’s not 0, control passes to the start of the body of the loop. And if it’s 0, the loop ends.
At the end of the function, the difference between eos and str is calculated, 1 is subtracted from it, and resulting value is
returned via R0.
N.B. Registers were not saved in this function. That’s because in the ARM calling convention registers R0-R3 are “scratch
registers”, intended for arguments passing, and we’re not required to restore their value when the function exits, since the
calling function will not use them anymore. Consequently, they may be used for anything we want. No other registers are
used here, so that is why we have nothing to save on the stack. Thus, control may be returned back to calling function by a
simple jump (BX), to the address in the LR register.
Optimizing Xcode 4.6.3 (LLVM) (thumb mode)
Listing 15.3: Optimizing Xcode 4.6.3 (LLVM) (thumb mode)
_strlen
MOV R1, R0
loc_2DF6
LDRB.W R2, [R1],#1
CMP R2, #0
BNE loc_2DF6
MVNS R0, R0
ADD R0, R1
BX LR
As optimizing LLVM concludes, eos and str do not need space on the stack, and can always be stored in registers. Before
the start of the loop body, str is always in R0, and eos—in R1.
The ``LDRB.W R2, [R1],#1'' instruction loads a byte from the memory at the address stored in R1, to R2, sign-
extending it to a 32-bit value, but not just that. #1 at the instruction’s end is implies “Post-indexed addressing”, which
means that 1 is to be added to R1 after the byte is loaded.
Read more about it: 28.2 on page 445.
Then you can see CMP and BNE3
in the body of the loop, these instructions continue looping until 0 is found in the string.
MVNS4
(inverts all bits, like NOT in x86) and ADD instructions compute eos − str − 1. In fact, these two instructions
compute R0 = str+eos, which is effectively equivalent to what was in the source code, and why it is so, I already explained
here ( 15.1.1 on page 194).
Apparently, LLVM, just like GCC, concludes that this code can be shorter (or faster).
Optimizing Keil 6/2013 (ARM mode)
Listing 15.4: Optimizing Keil 6/2013 (ARM mode)
_strlen
MOV R1, R0
loc_2C8
LDRB R2, [R1],#1
CMP R2, #0
SUBEQ R0, R1, R0
SUBEQ R0, R0, #1
BNE loc_2C8
BX LR
Almost the same as what we saw before, with the exception that the str − eos − 1 expression can be computed not at
the function’s end, but right in the body of the loop. The -EQ suffix, as we may recall, implies that the instruction executes
only if the operands in the CMP that was executed before were equal to each other. Thus, if R0 contains 0, both SUBEQ
instructions executes and result is left in the R0 register.
ARM64
Optimizing GCC (Linaro) 4.9
3(PowerPC, ARM) Branch if Not Equal
4MoVe Not
196
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN()
my_strlen:
mov x1, x0
; X1 is now temporary pointer (eos), acting like cursor
.L58:
; load byte from X1 to W2, increment X1 (post-index)
ldrb w2, [x1],1
; Compare and Branch if NonZero: compare W2 with 0, jump to .L58 if it is not
cbnz w2, .L58
; calculate difference between initial pointer in X0 and current address in X1
sub x0, x1, x0
; decrement lowest 32-bit of result
sub w0, w0, #1
ret
The algorithm is the same as in 15.1.1 on page 190: find a zero byte, calculate the difference between the pointers and
decrement the result by 1. I have added some comments. The only thing worth noting is that my example is somewhat wrong:
my_strlen() returns 32-bit int, while it has to return size_t or another 64-bit type. The reason is that, theoretically,
strlen() can be called for a huge blocks in memory that exceeds 4GB, so it must able to return a 64-bit value on 64-bit
platforms. Because of my mistake, the last SUB instruction operates on a 32-bit part of register, while the penultimate SUB
instruction works on full the 64-bit register (it calculates the difference between the pointers). It’s my mistake, but I have
decided to leave it as is, as an example of how the code could look like in such case.
Non-optimizing GCC (Linaro) 4.9
my_strlen:
; function prologue
sub sp, sp, #32
; first argument (str) will be stored in [sp,8]
str x0, [sp,8]
ldr x0, [sp,8]
; copy "str" to "eos" variable
str x0, [sp,24]
nop
.L62:
; eos++
ldr x0, [sp,24] ; load "eos" to X0
add x1, x0, 1 ; increment X0
str x1, [sp,24] ; save X0 to "eos"
; load byte from memory at address in X0 to W0
ldrb w0, [x0]
; is it zero? (WZR is the 32-bit register always contain zero)
cmp w0, wzr
; jump if not zero (Branch Not Equal)
bne .L62
; zero byte found. now calculate difference.
; load "eos" to X1
ldr x1, [sp,24]
; load "str" to X0
ldr x0, [sp,8]
; calculate difference
sub x0, x1, x0
; decrement result
sub w0, w0, #1
; function epilogue
add sp, sp, 32
ret
It’s more verbose. The variables are often tossed here to and from memory (local stack). The same mistake here: the
decrement operation happens on a 32-bit register part.
15.1.3 MIPS
Listing 15.5: Optimizing GCC 4.4.5 (IDA)
my_strlen:
; "eos" variable will always reside in $v1:
move $v1, $a0
197
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES
loc_4:
; load byte at address in "eos" into $a1:
lb $a1, 0($v1)
or $at, $zero ; load delay slot, NOP
; if loaded byte is not zero, jump to loc_4:
bnez $a1, loc_4
; increment "eos" anyway:
addiu $v1, 1 ; branch delay slot
; loop finished. invert "str" variable:
nor $v0, $zero, $a0
; $v0=-str-1
jr $ra
; return value = $v1 + $v0 = eos + ( -str-1 ) = eos - str - 1
addu $v0, $v1, $v0 ; branch delay slot
MIPS lacks a “NOT” instruction, but has “NOR” which is OR + NOT operation. This operation is widely used in digital
electronics5
, but isn’t very popular in computer programming. So, the NOT operation is implemented here as “NOR DST,
$ZERO, SRC”.
From fundamentals 30 on page 451 we know that bitwise inverting a signed number is the same as changing its sign
and subtracting 1 from the result. So what NOT does here is to take the value of str and transform it into −str − 1. The
addition operation that follows prepares result.
15.2 Exercises
15.2.1 Exercise #1
What does this code do?
Listing 15.6: Optimizing MSVC 2010
_s$ = 8
_f PROC
mov edx, DWORD PTR _s$[esp-4]
mov cl, BYTE PTR [edx]
xor eax, eax
test cl, cl
je SHORT $LN2@f
npad 4 ; align next label
$LL4@f:
cmp cl, 32
jne SHORT $LN3@f
inc eax
$LN3@f:
mov cl, BYTE PTR [edx+1]
inc edx
test cl, cl
jne SHORT $LL4@f
$LN2@f:
ret 0
_f ENDP
Listing 15.7: GCC 4.8.1 -O3
f:
.LFB24:
push ebx
mov ecx, DWORD PTR [esp+8]
xor eax, eax
movzx edx, BYTE PTR [ecx]
test dl, dl
je .L2
.L3:
cmp dl, 32
lea ebx, [eax+1]
cmove eax, ebx
5NOR is called “universal gate”. For example, the Apollo Guidance Computer used in the Apollo program, was built by only using 5600 NOR gates:
[Eic11].
198
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES
add ecx, 1
movzx edx, BYTE PTR [ecx]
test dl, dl
jne .L3
.L2:
pop ebx
ret
Listing 15.8: Optimizing Keil 6/2013 (ARM mode)
f PROC
MOV r1,#0
|L0.4|
LDRB r2,[r0,#0]
CMP r2,#0
MOVEQ r0,r1
BXEQ lr
CMP r2,#0x20
ADDEQ r1,r1,#1
ADD r0,r0,#1
B |L0.4|
ENDP
Listing 15.9: Optimizing Keil 6/2013 (thumb mode)
f PROC
MOVS r1,#0
B |L0.12|
|L0.4|
CMP r2,#0x20
BNE |L0.10|
ADDS r1,r1,#1
|L0.10|
ADDS r0,r0,#1
|L0.12|
LDRB r2,[r0,#0]
CMP r2,#0
BNE |L0.4|
MOVS r0,r1
BX lr
ENDP
Listing 15.10: Optimizing GCC 4.9 (ARM64)
f:
ldrb w1, [x0]
cbz w1, .L4
mov w2, 0
.L3:
cmp w1, 32
ldrb w1, [x0,1]!
csinc w2, w2, w2, ne
cbnz w1, .L3
.L2:
mov w0, w2
ret
.L4:
mov w2, w1
b .L2
Listing 15.11: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
lb $v1, 0($a0)
or $at, $zero
beqz $v1, locret_48
li $a1, 0x20 # ' '
b loc_28
move $v0, $zero
loc_18: # CODE XREF: f:loc_28
199
CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES
lb $v1, 0($a0)
or $at, $zero
beqz $v1, locret_40
or $at, $zero
loc_28: # CODE XREF: f+10
# f+38
bne $v1, $a1, loc_18
addiu $a0, 1
lb $v1, 0($a0)
or $at, $zero
bnez $v1, loc_28
addiu $v0, 1
locret_40: # CODE XREF: f+20
jr $ra
or $at, $zero
locret_48: # CODE XREF: f+8
jr $ra
move $v0, $zero
Answer G.1.7 on page 955.
200
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES
Chapter 16
Replacing arithmetic instructions to other ones
In the pursuit of optimization, one instruction may be replaced by others, or even with a group of instructions.
For example, the LEA instruction is often used for simple arithmetic calculations: A.6.2 on page 933.
ADD and SUB can replace each other. For example, line 18 in listing.52.1.
16.1 Multiplication
16.1.1 Multiplication using addition
Here is a simple example:
Listing 16.1: Optimizing MSVC 2010
unsigned int f(unsigned int a)
{
return a*8;
};
Multiplication by 8 is replaced by 3 addition instructions, which do the same. Apparently, MSVC’s optimizer decided that
this code can be faster.
_TEXT SEGMENT
_a$ = 8 ; size = 4
_f PROC
; File c:polygonc2.c
mov eax, DWORD PTR _a$[esp-4]
add eax, eax
add eax, eax
add eax, eax
ret 0
_f ENDP
_TEXT ENDS
END
16.1.2 Multiplication using shifting
Multiplication and division instructions by a numbers that’s a power of 2 are often replaced by shift instructions.
unsigned int f(unsigned int a)
{
return a*4;
};
Listing 16.2: Non-optimizing MSVC 2010
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
shl eax, 2
pop ebp
ret 0
_f ENDP
201
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION
Multiplication by 4 is just shifting the number to the left by 2 bits and inserting 2 zero bits at the right (as the last two
bits). It is just like multiplying 3 by 100 —we need to just add two zeroes at the right.
That’s how the shift left instruction works:
..7. 6. 5. 4. 3. 2. 1. 0..
7
.
6
.
5
.
4
.
3
.
2
.
1
.
0
.
CF
.
0
The added bits at right are always zeroes.
Multiplication by 4 in ARM:
Listing 16.3: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
LSL r0,r0,#2
BX lr
ENDP
Multiplication by 4 in MIPS:
Listing 16.4: Optimizing GCC 4.4.5 (IDA)
jr $ra
sll $v0, $a0, 2 ; branch delay slot
SLL is “Shift Left Logical”
16.1.3 Multiplication using shifting/subtracting/adding
It’s still possible to get rid of the multiplication operation when you multiply by numbers like 7 or 17 again by using shifting.
The mathematics used here is relatively easy.
32-bit
#include <stdint.h>
int f1(int a)
{
return a*7;
};
int f2(int a)
{
return a*28;
};
int f3(int a)
{
return a*17;
};
x86
Listing 16.5: Optimizing MSVC 2012
; a*7
_a$ = 8
_f1 PROC
mov ecx, DWORD PTR _a$[esp-4]
; ECX=a
lea eax, DWORD PTR [ecx*8]
; EAX=ECX*8
sub eax, ecx
; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7
ret 0
_f1 ENDP
202
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION
; a*28
_a$ = 8
_f2 PROC
mov ecx, DWORD PTR _a$[esp-4]
; ECX=a
lea eax, DWORD PTR [ecx*8]
; EAX=ECX*8
sub eax, ecx
; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7
shl eax, 2
; EAX=EAX<<2=(a*7)*4=a*28
ret 0
_f2 ENDP
; a*17
_a$ = 8
_f3 PROC
mov eax, DWORD PTR _a$[esp-4]
; EAX=a
shl eax, 4
; EAX=EAX<<4=EAX*16=a*16
add eax, DWORD PTR _a$[esp-4]
; EAX=EAX+a=a*16+a=a*17
ret 0
_f3 ENDP
ARM
Keil for ARM mode takes advantage of the second operand’s shift modifiers:
Listing 16.6: Optimizing Keil 6/2013 (ARM mode)
; a*7
||f1|| PROC
RSB r0,r0,r0,LSL #3
; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7
BX lr
ENDP
; a*28
||f2|| PROC
RSB r0,r0,r0,LSL #3
; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7
LSL r0,r0,#2
; R0=R0<<2=R0*4=a*7*4=a*28
BX lr
ENDP
; a*17
||f3|| PROC
ADD r0,r0,r0,LSL #4
; R0=R0+R0<<4=R0+R0*16=R0*17=a*17
BX lr
ENDP
But there are no such modifiers in Thumb mode. It also can’t optimize f2():
Listing 16.7: Optimizing Keil 6/2013 (thumb mode)
; a*7
||f1|| PROC
LSLS r1,r0,#3
; R1=R0<<3=a<<3=a*8
SUBS r0,r1,r0
; R0=R1-R0=a*8-a=a*7
BX lr
ENDP
; a*28
203
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION
||f2|| PROC
MOVS r1,#0x1c ; 28
; R1=28
MULS r0,r1,r0
; R0=R1*R0=28*a
BX lr
ENDP
; a*17
||f3|| PROC
LSLS r1,r0,#4
; R1=R0<<4=R0*16=a*16
ADDS r0,r0,r1
; R0=R0+R1=a+a*16=a*17
BX lr
ENDP
MIPS
Listing 16.8: Optimizing GCC 4.4.5 (IDA)
_f1:
sll $v0, $a0, 3
; $v0 = $a0<<3 = $a0*8
jr $ra
subu $v0, $a0 ; branch delay slot
; $v0 = $v0-$a0 = $a0*8-$a0 = $a0*7
_f2:
sll $v0, $a0, 5
; $v0 = $a0<<5 = $a0*32
sll $a0, 2
; $a0 = $a0<<2 = $a0*4
jr $ra
subu $v0, $a0 ; branch delay slot
; $v0 = $a0*32-$a0*4 = $a0*28
_f3:
sll $v0, $a0, 4
; $v0 = $a0<<4 = $a0*16
jr $ra
addu $v0, $a0 ; branch delay slot
; $v0 = $a0*16+$a0 = $a0*17
64-bit
#include <stdint.h>
int64_t f1(int64_t a)
{
return a*7;
};
int64_t f2(int64_t a)
{
return a*28;
};
int64_t f3(int64_t a)
{
return a*17;
};
x64
204
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.2. DIVISION
Listing 16.9: Optimizing MSVC 2012
; a*7
f1:
lea rax, [0+rdi*8]
; RAX=RDI*8=a*8
sub rax, rdi
; RAX=RAX-RDI=a*8-a=a*7
ret
; a*28
f2:
lea rax, [0+rdi*4]
; RAX=RDI*4=a*4
sal rdi, 5
; RDI=RDI<<5=RDI*32=a*32
sub rdi, rax
; RDI=RDI-RAX=a*32-a*4=a*28
mov rax, rdi
ret
; a*17
f3:
mov rax, rdi
sal rax, 4
; RAX=RAX<<4=a*16
add rax, rdi
; RAX=a*16+a=a*17
ret
ARM64
GCC 4.9 for ARM64 is also terse, thanks to the shift modifiers:
Listing 16.10: Optimizing GCC (Linaro) 4.9 ARM64
; a*7
f1:
lsl x1, x0, 3
; X1=X0<<3=X0*8=a*8
sub x0, x1, x0
; X0=X1-X0=a*8-a=a*7
ret
; a*28
f2:
lsl x1, x0, 5
; X1=X0<<5=a*32
sub x0, x1, x0, lsl 2
; X0=X1-X0<<2=a*32-a<<2=a*32-a*4=a*28
ret
; a*17
f3:
add x0, x0, x0, lsl 4
; X0=X0+X0<<4=a+a*16=a*17
ret
16.2 Division
16.2.1 Division using shifts
Example:
unsigned int f(unsigned int a)
{
return a/4;
};
205
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.3. EXERCISES
We get (MSVC 2010):
Listing 16.11: MSVC 2010
_a$ = 8 ; size = 4
_f PROC
mov eax, DWORD PTR _a$[esp-4]
shr eax, 2
ret 0
_f ENDP
The SHR (SHift Right) instruction in this example is shifting a number by 2 bits to the right. The two freed bits at left
(e.g., two most significant bits) are set to zero. The two least significant bits are dropped. In fact, these two dropped bits are
the division operation remainder.
The SHR instruction works just like SHL, but in the other direction.
..7. 6. 5. 4. 3. 2. 1. 0..
7
.
6
.
5
.
4
.
3
.
2
.
1
.
0
.
0
.
CF
It is easy to understand if you imagine the number 23 in the decimal numeral system. 23 can be easily divided by 10 just
by dropping last digit (3 —is division remainder). 2 is left after the operation as a quotient.
So the remainder is dropped, but that’s OK, we work on integer values anyway, these are not floating point numbers!
Division by 4 in ARM:
Listing 16.12: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
LSR r0,r0,#2
BX lr
ENDP
Division by 4 in MIPS:
Listing 16.13: Optimizing GCC 4.4.5 (IDA)
jr $ra
srl $v0, $a0, 2 ; branch delay slot
The SRL instruction is “shift-right logical”.
16.3 Exercises
16.3.1 Exercise #2
What does this code do?
Listing 16.14: Optimizing MSVC 2010
_a$ = 8
_f PROC
mov ecx, DWORD PTR _a$[esp-4]
lea eax, DWORD PTR [ecx*8]
sub eax, ecx
ret 0
_f ENDP
Listing 16.15: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
RSB r0,r0,r0,LSL #3
BX lr
ENDP
206
CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.3. EXERCISES
Listing 16.16: Non-optimizing Keil 6/2013 (thumb mode)
f PROC
LSLS r1,r0,#3
SUBS r0,r1,r0
BX lr
ENDP
Listing 16.17: Optimizing GCC 4.9 (ARM64)
f:
lsl w1, w0, 3
sub w0, w1, w0
ret
Listing 16.18: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
sll $v0, $a0, 3
jr $ra
subu $v0, $a0
Answer G.1.8 on page 955.
207
CHAPTER 17. FLOATING-POINT UNIT
Chapter 17
Floating-point unit
The FPU is a device within the main CPU, specially designed to deal with floating point numbers.
It was called “coprocessor” in the past and it stays somewhat aside of the main CPU.
17.1 IEEE 754
A number in the IEEE 754 format consists of a sign, a significand (also called fraction) and an exponent.
17.2 x86
It is worth looking into stack machines1
or learning the basics of the Forth language 2
, before studying the FPU in x86.
It is interesting to know that in the past (before the 80486 CPU) the coprocessor was a separate chip and it was not
always pre-installed on the motherboard. It was possible to buy it separately and install it 3
.
Starting with the 80486 DX CPU, the FPU is integrated in the CPU.
The FWAIT instruction reminds us of that fact—it switches the CPU to a waiting state, so it can wait until the FPU is
done with its work. Another rudiment is the fact that the FPU instruction opcodes start with the so called “escape”-opcodes
(D8..DF), i.e., opcodes passed to a separate coprocessor.
The FPU has a stack capable to holding 8 80-bit registers, and each register can hold a number in the IEEE 7544
format.
They are ST(0)..ST(7). For brevity, IDA and OllyDbg show ST(0) as ST, which is represented in some textbooks and
manuals as “Stack Top”.
17.3 ARM, MIPS, x86/x64 SIMD
In ARM and MIPS the FPU is not a stack, but a set of registers. The same ideology is used in the SIMD extensions of x86/x64
CPUs.
17.4 C/C++
The standard C/C++ languages offer at least two floating number types, float (single-precision5
, 32 bits) 6
and double (double-
precision7
, 64 bits).
GCC also supports the long double type (extended precision8
, 80 bit), which MSVC doesn’t.
1wikipedia
2wikipedia
3For example, John Carmack used fixed-point arithmetic (wikipedia) values in his Doom video game, stored in 32-bit GPR registers (16 bit for integral
part and another 16 bit for fractional part), so Doom could work on 32-bit computers without FPU, i.e., 80386 and 80486 SX
4wikipedia
5wikipedia
6the single precision floating point number format is also addressed in the Working with the float type as with a structure ( 21.6.2 on page 376) section
7wikipedia
8wikipedia
208
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
The float type requires the same number of bits as the int type in 32-bit environments, but the number representation
is completely different.
17.5 Simple example
Let’s consider this simple example:
#include <stdio.h>
double f (double a, double b)
{
return a/3.14 + b*4.1;
};
int main()
{
printf ("%fn", f(1.2, 3.4));
};
17.5.1 x86
MSVC
Compile it in MSVC 2010:
Listing 17.1: MSVC 2010: f()
CONST SEGMENT
__real@4010666666666666 DQ 04010666666666666r ; 4.1
CONST ENDS
CONST SEGMENT
__real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14
CONST ENDS
_TEXT SEGMENT
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f PROC
push ebp
mov ebp, esp
fld QWORD PTR _a$[ebp]
; current stack state: ST(0) = _a
fdiv QWORD PTR __real@40091eb851eb851f
; current stack state: ST(0) = result of _a divided by 3.14
fld QWORD PTR _b$[ebp]
; current stack state: ST(0) = _b; ST(1) = result of _a divided by 3.14
fmul QWORD PTR __real@4010666666666666
; current stack state:
; ST(0) = result of _b * 4.1;
; ST(1) = result of _a divided by 3.14
faddp ST(1), ST(0)
; current stack state: ST(0) = result of addition
pop ebp
ret 0
_f ENDP
FLD takes 8 bytes from stack and loads the number into the ST(0) register, automatically converting it into the internal
80-bit format (extended precision).
209
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
FDIV divides the value in ST(0) by the number stored at address __real@40091eb851eb851f —the value 3.14
is encoded there. The assembly syntax doesn’t support floating point numbers, so what we see here is the hexadecimal
representation of 3.14 in 64-bit IEEE 754 format.
After the execution of FDIV, ST(0) holds the quotient.
By the way, there is also the FDIVP instruction, which divides ST(1) by ST(0), popping both these values from stack
and then pushing the result. If you know the Forth language9
, you can quickly understand that this is a stack machine10
.
The subsequent FLD instruction pushes the value of b into the stack.
After that, the quotient is placed in ST(1), and ST(0) has the value of b.
The next FMUL instruction does multiplication: b from ST(0) is multiplied by by value at __real@4010666666666666
(the numer 4.1 is there) and leaves the result in the ST(0) register.
The last FADDP instruction adds the two values at top of stack, storing the result in ST(1) and then popping the value
of ST(0), thereby leaving the result at the top of the stack, in ST(0).
The function must return its result in the ST(0) register, so there are no any other instructions except the function
epilogue after FADDP.
9wikipedia
10wikipedia
210
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
MSVC + OllyDbg
I have marked red 2 pairs of 32-bit words in the stack. Each pair is a double-number in IEEE 754 format and is passed from
main(). We see how the first FLD loads a value (1.2) from the stack and puts it into ST(0):
Figure 17.1: OllyDbg: first FLD executed
Because of unavoidable conversion errors from 64-bit IEEE 754 float point to 80-bit (used internally in the FPU), here we
see 1.999..., which is close to 1.2. EIP now points to the next instruction (FDIV), which loads a double-number (a constant)
from memory. For convenience, OllyDbg shows its value: 3.14.
211
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
Let’s trace further. FDIV was executed, now ST(0) contains 0.382... (quotient):
Figure 17.2: OllyDbg: FDIV executed
212
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
Third step: the next FLD was executed, loading 3.4 into ST(0) (here we see the approximate value, 3.39999...):
Figure 17.3: OllyDbg: second FLD executed
At the same time, quotient is pushed into ST(1). Right now, EIP points to the next instruction: FMUL. It loads the
constant 4.1 from memory, which OllyDbg shows.
213
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
Next: FMUL was executed, so now the product is in ST(0):
Figure 17.4: OllyDbg: FMUL executed
214
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
Next: FADDP was executed, now the result of the addition is in ST(0), and ST(1) is cleared:
Figure 17.5: OllyDbg: FADDP executed
The result is left in ST(0), because the function returns its value in ST(0). main() takes this value from the register
later.
We also see something unusual: the 13.93... value is now located in ST(7). Why?
As I wrote before, the FPU registers are a stack: 17.2 on page 208. But this is a simplification. Imagine if it was
implemented in hardware as it’s described, then all 7 register’s contents must be moved (or copied) to adjacent registers
during pushing and popping, and that’s a lot of work. In reality, the FPU has just 8 registers and a pointer (called TOP)
which contains a register number, which is the current “top of stack”. When a value is pushed to the stack, TOP is pointed
to the next available register, and then a value is written to that register. The procedure is reversed if a value is popped,
however, the register which was freed is not cleared (it could possibly be cleared, but this is more work which can degrade
performance). So that’s what we see here. It can be said that FADDP saved the sum in the stack, and then popped one
element. But in fact, this instruction saved the sum and then shifted TOP. More precisely, the registers of the FPU are a
circular buffer.
GCC
GCC 4.4.1 (with -O3 option) emits the same code, just slightly different:
Listing 17.2: Optimizing GCC 4.4.1
public f
f proc near
arg_0 = qword ptr 8
arg_8 = qword ptr 10h
push ebp
fld ds:dbl_8048608 ; 3.14
; stack state now: ST(0) = 3.14
mov ebp, esp
fdivr [ebp+arg_0]
215
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
; stack state now: ST(0) = result of division
fld ds:dbl_8048610 ; 4.1
; stack state now: ST(0) = 4.1, ST(1) = result of division
fmul [ebp+arg_8]
; stack state now: ST(0) = result of multiplication, ST(1) = result of division
pop ebp
faddp st(1), st
; stack state now: ST(0) = result of addition
retn
f endp
The difference is that, first of all, 3.14 is pushed to the stack (into ST(0)), and then the value in arg_0 is divided by the
value in ST(0).
FDIVR stands for Reverse Divide —to divide with divisor and dividend swapped with each other. There is no likewise
instruction for multiplication since it is a commutative operation, so we just have FMUL without its -R counterpart.
FADDP adds the two values but also pops one value from the stack. After that operation, ST(0) holds the sum.
17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Until ARM got standardized floating point support, several processor manufacturers added their own instructions extensions.
Then, VFP (Vector Floating Point) was standardized.
One important difference from x86 is that in ARM, there is no stack, you work just with registers.
Listing 17.3: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
f
VLDR D16, =3.14
VMOV D17, R0, R1 ; load "a"
VMOV D18, R2, R3 ; load "b"
VDIV.F64 D16, D17, D16 ; a/3.14
VLDR D17, =4.1
VMUL.F64 D17, D18, D17 ; b*4.1
VADD.F64 D16, D17, D16 ; +
VMOV R0, R1, D16
BX LR
dbl_2C98 DCFD 3.14 ; DATA XREF: f
dbl_2CA0 DCFD 4.1 ; DATA XREF: f+10
So, we see here new some registers used, with D prefix. These are 64-bit registers, there are 32 of them, and they can
be used both for floating-point numbers (double) but also for SIMD (it is called NEON here in ARM). There are also 32 32-bit
S-registers, intended to be used for single precision floating pointer numbers (float). It is easy to remember: D-registers are
for double precision numbers, while S-registers —for single precision numbers. More about it: B.3.3 on page 945.
Both (3.14 and 4.1) constants are stored in memory in IEEE 754 form.
VLDR and VMOV , as it can be easily deduced, are analogous to the LDR and MOV instructions, but they work with D-
registers. It has to be noted that these instructions, just like the D-registers, are intended not only for floating point numbers,
but can be also used for SIMD (NEON) operations and this will also be shown soon.
The arguments are passed to the function in a common way, via the R-registers, however each number that has double
precision has a size of 64 bits, so two R-registers are needed to pass each one.
``VMOV D17, R0, R1'' at the start, composes two 32-bit values from R0 and R1 into one 64-bit value and saves it
to D17.
``VMOV R0, R1, D16'' is the inverse operation, what was in D16 is split in two registers, R0 and R1, becase a
double-precision number that needs 64 bits for storage, is returned in R0 and R1.
VDIV, VMUL and VADD, are instruction for processing floating point numbers that compute quotient, product and sum,
respectively.
The code for thumb-2 is same.
17.5.3 ARM: Optimizing Keil 6/2013 (thumb mode)
216
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
f
PUSH {R3-R7,LR}
MOVS R7, R2
MOVS R4, R3
MOVS R5, R0
MOVS R6, R1
LDR R2, =0x66666666 ; 4.1
LDR R3, =0x40106666
MOVS R0, R7
MOVS R1, R4
BL __aeabi_dmul
MOVS R7, R0
MOVS R4, R1
LDR R2, =0x51EB851F ; 3.14
LDR R3, =0x40091EB8
MOVS R0, R5
MOVS R1, R6
BL __aeabi_ddiv
MOVS R2, R7
MOVS R3, R4
BL __aeabi_dadd
POP {R3-R7,PC}
; 4.1 in IEEE 754 form:
dword_364 DCD 0x66666666 ; DATA XREF: f+A
dword_368 DCD 0x40106666 ; DATA XREF: f+C
; 3.14 in IEEE 754 form:
dword_36C DCD 0x51EB851F ; DATA XREF: f+1A
dword_370 DCD 0x40091EB8 ; DATA XREF: f+1C
Keil generated code for a processor without FPU or NEON support. The double-precision floating-point numbers are
passed via generic R-registers, and instead of FPU-instructions, service library functions are called (like __aeabi_dmul,
__aeabi_ddiv, __aeabi_dadd ) which emulate multiplication, division and addition for floating-point numbers. Of
course, that is slower than FPU-coprocessor, but still better than nothing.
By the way, similar FPU-emulating libraries were very popular in the x86 world when coprocessors were rare and expen-
sive, and were installed only on expensive computers.
The FPU-coprocessor emulation is called soft float or armel in the ARM world, while using the coprocessor’s FPU-instructions
is called hard float or armhf.
17.5.4 ARM64: Optimizing GCC (Linaro) 4.9
Very compact code:
Listing 17.4: Optimizing GCC (Linaro) 4.9
f:
; D0 = a, D1 = b
ldr d2, .LC25 ; 3.14
; D2 = 3.14
fdiv d0, d0, d2
; D0 = D0/D2 = a/3.14
ldr d2, .LC26 ; 4.1
; D2 = 4.1
fmadd d0, d1, d2, d0
; D0 = D1*D2+D0 = b*4.1+a/3.14
ret
; constants in IEEE 754 format:
.LC25:
.word 1374389535 ; 3.14
.word 1074339512
.LC26:
.word 1717986918 ; 4.1
.word 1074816614
17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9
217
CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE
Listing 17.5: Non-optimizing GCC (Linaro) 4.9
f:
sub sp, sp, #16
str d0, [sp,8] ; save "a" in Register Save Area
str d1, [sp] ; save "b" in Register Save Area
ldr x1, [sp,8]
; X1 = a
ldr x0, .LC25
; X0 = 3.14
fmov d0, x1
fmov d1, x0
; D0 = a, D1 = 3.14
fdiv d0, d0, d1
; D0 = D0/D1 = a/3.14
fmov x1, d0
; X1 = a/3.14
ldr x2, [sp]
; X2 = b
ldr x0, .LC26
; X0 = 4.1
fmov d0, x2
; D0 = b
fmov d1, x0
; D1 = 4.1
fmul d0, d0, d1
; D0 = D0*D1 = b*4.1
fmov x0, d0
; X0 = D0 = b*4.1
fmov d0, x1
; D0 = a/3.14
fmov d1, x0
; D1 = X0 = b*4.1
fadd d0, d0, d1
; D0 = D0+D1 = a/3.14 + b*4.1
fmov x0, d0 ;  redundant code
fmov d0, x0 ; /
add sp, sp, 16
ret
.LC25:
.word 1374389535 ; 3.14
.word 1074339512
.LC26:
.word 1717986918 ; 4.1
.word 1074816614
Non-optimizing GCC is more verbose. There is a lot of unnecessary value shuffling, including some clearly redundant
code (the last two FMOV instructions). Probably, GCC 4.9 is not yet good in generating ARM64 code. What is worth noting is
that ARM64 has 64-bit registers, and the D-registers are 64-bit ones as well. So the compiler is free to save values of type
double in GPRs instead of the local stack. This isn’t possible on 32-bit CPUs.
And again, as an exercise, you can try to optimize this function manually, without introducing new instructions like
FMADD.
17.5.6 MIPS
MIPS can support several coprocessors (up to 4), the zeroth of which is a special control coprocessor, and first coprocessor is
the FPU.
As in ARM, the MIPS coprocessor is not a stack machine, it has 32 32-bit registers ($F0-$F31): C.1.2 on page 947. When
one needs to work with 64-bit double values, a pair of 32-bit F-registers is used.
Listing 17.6: Optimizing GCC 4.4.5 (IDA)
f:
; $f12-$f13=A
; $f14-$f15=B
lui $v0, (dword_C4 >> 16) ; ?
; load low 32-bit part of 3.14 constant to $f0:
218
CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS
lwc1 $f0, dword_BC
or $at, $zero ; load delay slot, NOP
; load high 32-bit part of 3.14 constant to $f1:
lwc1 $f1, $LC0
lui $v0, ($LC1 >> 16) ; ?
; A in $f12-$f13, 3.14 constant in $f0-$f1, do division:
div.d $f0, $f12, $f0
; $f0-$f1=A/3.14
; load low 32-bit part of 4.1 to $f2:
lwc1 $f2, dword_C4
or $at, $zero ; load delay slot, NOP
; load high 32-bit part of 4.1 to $f3:
lwc1 $f3, $LC1
or $at, $zero ; load delay slot, NOP
; B in $f14-$f15, 4.1 constant in $f2-$f3, do multiplication:
mul.d $f2, $f14, $f2
; $f2-$f3=B*4.1
jr $ra
; sum 64-bit parts and leave result in $f0-$f1:
add.d $f0, $f2 ; branch delay slot, NOP
.rodata.cst8:000000B8 $LC0: .word 0x40091EB8 # DATA XREF: f+C
.rodata.cst8:000000BC dword_BC: .word 0x51EB851F # DATA XREF: f+4
.rodata.cst8:000000C0 $LC1: .word 0x40106666 # DATA XREF: f+10
.rodata.cst8:000000C4 dword_C4: .word 0x66666666 # DATA XREF: f
The new instructions here are:
• LWC1 loads a 32-bit word into a register of the first coprocessor (hence “1” in instruction name). A pair of LWC1
instructions may be combined into a L.D pseudoinstruction.
• DIV.D, MUL.D, ADD.D do division/multiplication/addition (“.D” in the suffix stands for double precision, “.S” would stands
for single precision)
There is also a weird compiler anomaly: the LUI instructions that I’ve marked with a question mark. It’s hard for me to
understand why load a part of a 64-bit constant of double type into the $V0 register. These instruction have no effect. If
someone knows more about it, please drop me an email11
.
17.6 Passing floating point numbers via arguments
#include <math.h>
#include <stdio.h>
int main ()
{
printf ("32.01 ^ 1.54 = %lfn", pow (32.01,1.54));
return 0;
}
17.6.1 x86
Let’s see what we get in (MSVC 2010):
Listing 17.7: MSVC 2010
CONST SEGMENT
__real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01
__real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54
CONST ENDS
_main PROC
push ebp
mov ebp, esp
sub esp, 8 ; allocate space for the first variable
11dennis(a)yurichev.com
219
CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS
fld QWORD PTR __real@3ff8a3d70a3d70a4
fstp QWORD PTR [esp]
sub esp, 8 ; allocate space for the second variable
fld QWORD PTR __real@40400147ae147ae1
fstp QWORD PTR [esp]
call _pow
add esp, 8 ; "return back" place of one variable.
; in local stack here 8 bytes still reserved for us.
; result now in ST(0)
fstp QWORD PTR [esp] ; move result from ST(0) to local stack for printf()
push OFFSET $SG2651
call _printf
add esp, 12
xor eax, eax
pop ebp
ret 0
_main ENDP
FLD and FSTP move variables between the data segment and the FPU stack. pow()12
takes both values from the stack
of the FPU and returns its result in the ST(0) register. printf() takes 8 bytes from the local stack and interprets them as
double type variable.
By the way, a pair of MOV instructions could be used here for moving values from the memory into the stack, because
the values in memory are stored in IEEE 754 format, and pow() also takes them in this format, so no conversion is necessary.
That’s how it’s done in the next example, for ARM: 17.6.2 on page 220.
17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
_main
var_C = -0xC
PUSH {R7,LR}
MOV R7, SP
SUB SP, SP, #4
VLDR D16, =32.01
VMOV R0, R1, D16
VLDR D16, =1.54
VMOV R2, R3, D16
BLX _pow
VMOV D16, R0, R1
MOV R0, 0xFC1 ; "32.01 ^ 1.54 = %lfn"
ADD R0, PC
VMOV R1, R2, D16
BLX _printf
MOVS R1, 0
STR R0, [SP,#0xC+var_C]
MOV R0, R1
ADD SP, SP, #4
POP {R7,PC}
dbl_2F90 DCFD 32.01 ; DATA XREF: _main+6
dbl_2F98 DCFD 1.54 ; DATA XREF: _main+E
As I wrote before, 64-bit floating pointer numbers are passed in R-registers pairs. This code is a bit redundant (certainly
because optimization is turned off), since it is possible to load values into the R-registers directly without touching the
D-registers.
So, as we see, the _pow function receives its first argument in R0 and R1, and its second one in R2 and R3. The function
leaves its result in R0 and R1. The result of _pow is moved into D16, then in the R1 and R2 pair, from where printf()
takes the resulting number.
17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode)
12a standard C function, raises a number to the given power (exponentiation)
220
CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS
_main
STMFD SP!, {R4-R6,LR}
LDR R2, =0xA3D70A4 ; y
LDR R3, =0x3FF8A3D7
LDR R0, =0xAE147AE1 ; x
LDR R1, =0x40400147
BL pow
MOV R4, R0
MOV R2, R4
MOV R3, R1
ADR R0, a32_011_54Lf ; "32.01 ^ 1.54 = %lfn"
BL __2printf
MOV R0, #0
LDMFD SP!, {R4-R6,PC}
y DCD 0xA3D70A4 ; DATA XREF: _main+4
dword_520 DCD 0x3FF8A3D7 ; DATA XREF: _main+8
; double x
x DCD 0xAE147AE1 ; DATA XREF: _main+C
dword_528 DCD 0x40400147 ; DATA XREF: _main+10
a32_011_54Lf DCB "32.01 ^ 1.54 = %lf",0xA,0
; DATA XREF: _main+24
D-registers are not used here, just R-register pairs.
17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9
Listing 17.8: Optimizing GCC (Linaro) 4.9
f:
stp x29, x30, [sp, -16]!
add x29, sp, 0
ldr d1, .LC1 ; load 1.54 into D1
ldr d0, .LC0 ; load 32.01 into D0
bl pow
; result of pow() in D0
adrp x0, .LC2
add x0, x0, :lo12:.LC2
bl printf
mov w0, 0
ldp x29, x30, [sp], 16
ret
.LC0:
; 32.01 in IEEE 754 format
.word -1374389535
.word 1077936455
.LC1:
; 1.54 in IEEE 754 format
.word 171798692
.word 1073259479
.LC2:
.string "32.01 ^ 1.54 = %lfn"
The constants are loaded into D0 and D1: pow() takes them from there. The result will be in D0 after the execution
of pow(). It is to be passed to printf() without any modification and moving, because printf() takes arguments of
integral types and pointers from X-registers, and floating point arguments from D-registers.
17.6.5 MIPS
Listing 17.9: Optimizing GCC 4.4.5 (IDA)
main:
var_10 = -0x10
var_4 = -4
; function prologue:
lui $gp, (dword_9C >> 16)
221
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
lui $v0, (dword_A4 >> 16) ; ?
; load low 32-bit part of 32.01:
lwc1 $f12, dword_9C
; load address of pow() function:
lw $t9, (pow & 0xFFFF)($gp)
; load high 32-bit part of 32.01:
lwc1 $f13, $LC0
lui $v0, ($LC1 >> 16) ; ?
; load low 32-bit part of 1.54:
lwc1 $f14, dword_A4
or $at, $zero ; load delay slot, NOP
; load high 32-bit part of 1.54:
lwc1 $f15, $LC1
; call pow():
jalr $t9
or $at, $zero ; branch delay slot, NOP
lw $gp, 0x20+var_10($sp)
; copy result from $f0 and $f1 to $a3 and $a2:
mfc1 $a3, $f0
lw $t9, (printf & 0xFFFF)($gp)
mfc1 $a2, $f1
; call printf():
lui $a0, ($LC2 >> 16) # "32.01 ^ 1.54 = %lfn"
jalr $t9
la $a0, ($LC2 & 0xFFFF) # "32.01 ^ 1.54 = %lfn"
; function epilogue:
lw $ra, 0x20+var_4($sp)
; return 0:
move $v0, $zero
jr $ra
addiu $sp, 0x20
.rodata.str1.4:00000084 $LC2: .ascii "32.01 ^ 1.54 = %lfn"<0>
; 32.01:
.rodata.cst8:00000098 $LC0: .word 0x40400147 # DATA XREF: main+20
.rodata.cst8:0000009C dword_9C: .word 0xAE147AE1 # DATA XREF: main
.rodata.cst8:0000009C # main+18
; 1.54:
.rodata.cst8:000000A0 $LC1: .word 0x3FF8A3D7 # DATA XREF: main+24
.rodata.cst8:000000A0 # main+30
.rodata.cst8:000000A4 dword_A4: .word 0xA3D70A4 # DATA XREF: main+14
And again, we see here LUI loading a 32-bit part of a double number into $V0. And again, I honestly don’t know why.
The new instruction for us here is MFC1 (“Move From Coprocessor 1”). The FPU is coprocessor number 1, hence “1” in
the instruction name. This instruction transfers values from the coprocessor’s registers to the registers of the CPU (GPR).
So in the end the result from pow() is moved to registers $A3 and $A2, and printf() takes a 64-bit double value from this
register pair.
17.7 Comparison example
Let’s try this:
#include <stdio.h>
double d_max (double a, double b)
{
if (a>b)
return a;
return b;
};
int main()
{
222
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
printf ("%fn", d_max (1.2, 3.4));
printf ("%fn", d_max (5.6, -4));
};
Despite the simplicity of the function, it will be harder to understand how it works.
17.7.1 x86
Non-optimizing MSVC
MSVC 2010 generates the following:
Listing 17.10: Non-optimizing MSVC 2010
PUBLIC _d_max
_TEXT SEGMENT
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_d_max PROC
push ebp
mov ebp, esp
fld QWORD PTR _b$[ebp]
; current stack state: ST(0) = _b
; compare _b (ST(0)) and _a, and pop register
fcomp QWORD PTR _a$[ebp]
; stack is empty here
fnstsw ax
test ah, 5
jp SHORT $LN1@d_max
; we are here only if a>b
fld QWORD PTR _a$[ebp]
jmp SHORT $LN2@d_max
$LN1@d_max:
fld QWORD PTR _b$[ebp]
$LN2@d_max:
pop ebp
ret 0
_d_max ENDP
So, FLD loads _b into ST(0).
FCOMP compares the value in ST(0) with what is in _a and sets C3/C2/C0 bits in FPU status word register, accordingly.
This is a 16-bit register that reflects the current state of the FPU.
After the bits are set, the FCOMP instruction also pops one variable from the stack. This is what distinguishes it from
FCOM, which is just compares values, leaving the stack in the same state.
Unfortunately, CPUs before Intel P6 13
don’t have any conditional jumps instructions which check the C3/C2/C0 bits.
Probably, it is a matter of history (remember: FPU was separate chip in past).
Modern CPU starting at Intel P6 have FCOMI/FCOMIP/FUCOMI/FUCOMIP instructions —which do the same, but modify the
ZF/PF/CF CPU flags.
The FNSTSW instruction copies FPU the status word register to AX. C3/C2/C0 bits are placed at positions 14/10/8, they
are at the same positions in the AX register and all they are placed in the high part of AX —AH.
• If b > a in our example, then C3/C2/C0 bits are to be set as following: 0, 0, 0.
• If a > b, then the bits are: 0, 0, 1.
• If a = b, then the bits are: 1, 0, 0.
• If the result is unordered (in case of error), then the set bits are: 1, 1, 1.
This is how C3/C2/C0 bits are located in the AX register:
14 10 9 8
C3 C2 C1 C0
13Intel P6 is Pentium Pro, Pentium II, etc
223
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
This is how C3/C2/C0 bits are located in the AH register:
6 2 1 0
C3 C2 C1 C0
After the execution of test ah, 514
, only C0 and C2 bits (on 0 and 2 position) are considered, all other bits are just
ignored.
Now let’s talk about the parity flag, another notable historical rudiment.
This flag is set to 1 if the number of ones in the result of the last calculation is even, and to 0 if it is odd.
Let’s look into Wikipedia 15
:
One common reason to test the parity flag actually has nothing to do with parity. The FPU has four
condition flags (C0 to C3), but they can not be tested directly, and must instead be first copied to the flags
register. When this happens, C0 is placed in the carry flag, C2 in the parity flag and C3 in the zero flag. The
C2 flag is set when e.g. incomparable floating point values (NaN or unsupported format) are compared with
the FUCOM instructions.
As noted in Wikipedia, the parity flag used sometimes in FPU code, let’s see how.
The PF flag is to be set to 1 if both C0 and C2 are set to 0 or both are 1, in which case the subsequent JP (jump if PF==1)
is triggering. If we recall the values of C3/C2/C0 for various cases, we can see that the conditional jump JP is triggering in
two cases: if b > a or a = b (C3 bit is not considered here, since it was cleared by the test ah, 5 instruction).
It is all simple after that. If the conditional jump was triggered, FLD loads the value of _b in ST(0), and if it was not
triggered, the value of _a is loaded there.
And what about checking C2?
The C2 flag is set in case of error (NaN, etc), but our code doesn’t check it. If the programmer cares about FPU errors,
he/she must add additional checks.
145=1001b
15wikipedia
224
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
First OllyDbg example: a=1.2 and b=3.4
Let’s load the example into OllyDbg:
Figure 17.6: OllyDbg: first FLD is executed
Current arguments of the function: a = 1.2 and b = 3.4 (We can see them in the stack: two pairs of 32-bit values). b (3.4)
is already loaded in ST(0). Now FCOMP is being executed. OllyDbg shows the second FCOMP argument, which is in stack
right now.
225
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FCOMP is executed:
Figure 17.7: OllyDbg: FCOMP is executed
We see the state of the FPU’s condition flags: all zeroes. The popped value is reflected as ST(7), I wrote earlier about
reason for this: 17.5.1 on page 215.
226
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FNSTSW is executed:
Figure 17.8: OllyDbg: FNSTSW is executed
We see that the AX register contain zeroes: indeed, all condition flags are zero. (OllyDbg disassembles the FNSTSW
instruction as FSTSW — they are synonyms).
227
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
TEST is executed:
Figure 17.9: OllyDbg: TEST is executed
The PF flag is set to 1. Indeed: the number of bits set in 0 is 0 and 0 is an even number. OllyDbg disassembles JP as
JPE16
— they are synonyms. And it is about to trigger now.
16Jump Parity Even (x86 instruction)
228
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
JPE triggered, FLD loads the value of b (3.4) in ST(0):
Figure 17.10: OllyDbg: second FLD is executed
The function finishes its work.
229
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Second OllyDbg example: a=5.6 and b=-4
Let’s load example into OllyDbg:
Figure 17.11: OllyDbg: first FLD executed
Current function arguments: a = 5.6 and b = −4). b (−4) is already loaded in ST(0). FCOMP about to execute now.
OllyDbg shows the second FCOMP argument, which is in stack right now.
230
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FCOMP executed:
Figure 17.12: OllyDbg: FCOMP executed
We see the state of the FPU’s condition flags: all zeroes except C0.
231
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FNSTSW executed:
Figure 17.13: OllyDbg: FNSTSW executed
We see that the AX register contains 0x100: the C0 flag is at the 16th bit.
232
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
TEST executed:
Figure 17.14: OllyDbg: TEST executed
The PF flag is cleared. Indeed: the count of bits set in 0x100 is 1 and 1 is an odd number. JPE is being skipped now.
233
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
JPE wasn’t triggered, so FLD loads the value of a (5.6) in ST(0):
Figure 17.15: OllyDbg: second FLD executed
The function finishes its work.
Optimizing MSVC 2010
Listing 17.11: Optimizing MSVC 2010
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_d_max PROC
fld QWORD PTR _b$[esp-4]
fld QWORD PTR _a$[esp-4]
; current stack state: ST(0) = _a, ST(1) = _b
fcom ST(1) ; compare _a and ST(1) = (_b)
fnstsw ax
test ah, 65 ; 00000041H
jne SHORT $LN5@d_max
; copy ST(0) to ST(1) and pop register,
; leave (_a) on top
fstp ST(1)
; current stack state: ST(0) = _a
ret 0
$LN5@d_max:
; copy ST(0) to ST(0) and pop register,
; leave (_b) on top
fstp ST(0)
; current stack state: ST(0) = _b
ret 0
234
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
_d_max ENDP
FCOM differs from FCOMP in the sense that it just compares the values and doesn’t change the FPU stack. Unlike the
previous example, here the operands are in reverse order, which is why the result of the comparison in C3/C2/C0 is different:
• If a > b in our example, then C3/C2/C0 bits are to be set as: 0, 0, 0.
• If b > a, then the bits are: 0, 0, 1.
• If a = b, then the bits are: 1, 0, 0.
The test ah, 65 instruction leaves just two bits —C3 and C0. Both will be zero if a > b: in that case the JNE jump will
not be triggered. Then FSTP ST(1) follows —this instruction copies the value from ST(0) to the operand and pops one
value from the FPU stack. In other words, the instruction copies ST(0) (where the value of _a is now) into ST(1). After
that, two copies of _a are at the top of the stack. Then, one value is popped. After that, ST(0) contains _a and the function
is finishes.
The conditional jump JNE is triggering in two cases: if b > a or a = b. ST(0) is copied into ST(0), it is just like an idle
(NOP) operation, then one value is popped from the stack and the top of the stack (ST(0)) is contain what was in ST(1)
before (that is _b). Then the function finishes. The reason this instruction is used here probably is because the FPU has no
other instruction to pop a value from the stack and discard it.
235
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
First OllyDbg example: a=1.2 and b=3.4
Both FLD are executed:
Figure 17.16: OllyDbg: both FLD are executed
FCOM being executed: OllyDbg shows the contents of ST(0) and ST(1), for convenience.
236
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FCOM is done:
Figure 17.17: OllyDbg: FCOM is done
C0 is set, all other condition flags are cleared.
237
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FNSTSW is done, AX=0x3100:
Figure 17.18: OllyDbg: FNSTSW is executed
238
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
TEST is executed:
Figure 17.19: OllyDbg: TEST is executed
ZF=0, conditional jump is about to trigger now.
239
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FSTP ST (or FSTP ST(0)) was executed: 1.2 was popped from the stack, and 3.4 was left on top:
Figure 17.20: OllyDbg: FSTP is executed
We see that the FSTP ST instruction works just like popping one value from the FPU stack.
240
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Second OllyDbg example: a=5.6 and b=-4
Both FLD are executed:
Figure 17.21: OllyDbg: both FLD are executed
FCOM is about to execute.
241
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FCOM is done:
Figure 17.22: OllyDbg: FCOM is finished
All conditional flags are cleared.
242
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FNSTSW done, AX=0x3000:
Figure 17.23: OllyDbg: FNSTSW was executed
243
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
TEST is done:
Figure 17.24: OllyDbg: TEST was executed
ZF=1, jump will not happen now.
244
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
FSTP ST(1) was executed: a value of 5.6 is now at the top of the FPU stack.
Figure 17.25: OllyDbg: FSTP was executed
We now see that the FSTP ST(1) instruction works as follows: it leaves what was at the top of the stack, but clears
ST(1).
GCC 4.4.1
Listing 17.12: GCC 4.4.1
d_max proc near
b = qword ptr -10h
a = qword ptr -8
a_first_half = dword ptr 8
a_second_half = dword ptr 0Ch
b_first_half = dword ptr 10h
b_second_half = dword ptr 14h
push ebp
mov ebp, esp
sub esp, 10h
; put a and b to local stack:
mov eax, [ebp+a_first_half]
mov dword ptr [ebp+a], eax
mov eax, [ebp+a_second_half]
mov dword ptr [ebp+a+4], eax
mov eax, [ebp+b_first_half]
mov dword ptr [ebp+b], eax
mov eax, [ebp+b_second_half]
mov dword ptr [ebp+b+4], eax
; load a and b to FPU stack:
245
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
fld [ebp+a]
fld [ebp+b]
; current stack state: ST(0) - b; ST(1) - a
fxch st(1) ; this instruction swapping ST(1) and ST(0)
; current stack state: ST(0) - a; ST(1) - b
fucompp ; compare a and b and pop two values from stack, i.e., a and b
fnstsw ax ; store FPU status to AX
sahf ; load SF, ZF, AF, PF, and CF flags state from AH
setnbe al ; store 1 to AL, if CF=0 and ZF=0
test al, al ; AL==0 ?
jz short loc_8048453 ; yes
fld [ebp+a]
jmp short locret_8048456
loc_8048453:
fld [ebp+b]
locret_8048456:
leave
retn
d_max endp
FUCOMPP is almost like FCOM, but pops both values from the stack and handles “not-a-numbers” differently.
A bit about not-a-numbers:
The FPU is able to deal with special values which are not-a-numbers or NaNs 17
. These are infinity, result of division by
0, etc. Not-a-numbers can be “quiet” and “signaling”. It is possible to continue to work with “quiet” NaNs, but if one tries to
do any operation with “signaling” NaNs, an exception is to be raised.
FCOM raising an exception if any operand is NaN. FUCOM raising an exception only if any operand is a signaling NaN
(SNaN).
The next instruction is SAHF (Store AH into Flags) —this is a rare instruction in code not related to the FPU. 8 bits from
AH are moved into the lower 8 bits of the CPU flags in the following order:
7 6 4 2 0
SF ZF AF PF CF
Let’s recall that FNSTSW moves the bits that interest us (C3/C2/C0) into AH and they are in positions 6, 2, 0 of the AH
register:
6 2 1 0
C3 C2 C1 C0
In other words, the fnstsw ax / sahf instruction pair moves C3/C2/C0 into ZF, PF and CF.
Now let’s also recall the values of C3/C2/C0 in different conditions:
• If a is greater than b in our example, then C3/C2/C0 are to be set to: 0, 0, 0.
• if a is less than b, then the bits are to be set to: 0, 0, 1.
• If a = b, then: 1, 0, 0.
In other words, these states of the CPU flags are possible after three FUCOMPP/FNSTSW/SAHF instructions:
• If a > b, the CPU flags are to be set as: ZF=0, PF=0, CF=0.
• If a < b, then the flags are to be set as: ZF=0, PF=0, CF=1.
• And if a = b, then: ZF=1, PF=0, CF=0.
Depending on the CPU flags and conditions, SETNBE stores 1 or 0 to AL. It is almost the counterpart of JNBE, with the
exception that SETcc18
stores 1 or 0 in AL, but Jcc does actually jump or not. SETNBE stores 1 only if CF=0 and ZF=0. If
it is not true, 0 is to be stored into AL.
Only in one case both CF and ZF are 0: if a > b.
Then 1 is to be stored to AL, the subsequent JZ is not to be triggered and the function will return _a. In all other cases,
_b is to be returned.
17wikipedia
18cc is condition code
246
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Optimizing GCC 4.4.1
Listing 17.13: Optimizing GCC 4.4.1
public d_max
d_max proc near
arg_0 = qword ptr 8
arg_8 = qword ptr 10h
push ebp
mov ebp, esp
fld [ebp+arg_0] ; _a
fld [ebp+arg_8] ; _b
; stack state now: ST(0) = _b, ST(1) = _a
fxch st(1)
; stack state now: ST(0) = _a, ST(1) = _b
fucom st(1) ; compare _a and _b
fnstsw ax
sahf
ja short loc_8048448
; store ST(0) to ST(0) (idle operation), pop value at top of stack,
; leave _b at top
fstp st
jmp short loc_804844A
loc_8048448:
; store _a to ST(0), pop value at top of stack, leave _a at top
fstp st(1)
loc_804844A:
pop ebp
retn
d_max endp
It is almost the same except that JA is used after SAHF. Actually, conditional jump instructions that check “larger”, “lesser”
or “equal” for unsigned number comparison (these are JA, JAE, JBE, JBE, JE/JZ, JNA, JNAE, JNB, JNBE, JNE/JNZ) check
only flags CF and ZF.
Let’s recall where bits C3/C2/C0 are located in the AH register after the execution of FSTSW/FNSTSW:
6 2 1 0
C3 C2 C1 C0
Let’s also recall, how the bits from AH are stored into the CPU flags the execution of SAHF:
7 6 4 2 0
SF ZF AF PF CF
After the comparison, the C3 and C0 bits are moved into ZF and CF, so the conditional jumps are able work after. JA is
triggering if both CF are ZF zero.
Thereby, the conditional jumps instructions listed here can be used after a FNSTSW/SAHF instruction pair.
Apparently, the FPU C3/C2/C0 status bits were placed there intentionally, to easily map them to base CPU flags without
additional permutations. But I’m not sure.
GCC 4.8.1 with -O3 optimization turned on
Some new FPU instructions were added in the P6 Intel family19
These are FUCOMI (compare operands and set flags of the
main CPU) and FCMOVcc (works like CMOVcc, but on FPU registers). Apparently, the maintainers of GCC decided to drop
support of pre-P6 Intel CPUs (early Pentiums, etc).
And also, the FPU is no longer separate unit in P6 Intel family, so now it is possible to modify/check flags of the main
CPU from the FPU.
So what we get is:
19Starting at Pentium Pro, Pentium-II, etc.
247
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Listing 17.14: Optimizing GCC 4.8.1
fld QWORD PTR [esp+4] ; load "a"
fld QWORD PTR [esp+12] ; load "b"
; ST0=b, ST1=a
fxch st(1)
; ST0=a, ST1=b
; compare "a" and "b"
fucomi st, st(1)
; copy ST1 ("b" here) to ST0 if a<=b
; leave "a" in ST0 otherwise
fcmovbe st, st(1)
; discard value in ST1
fstp st(1)
ret
I’m not sure why FXCH (swap operands) is here. It’s possible to get rid of it easily by swapping the first two FLD
instructions or by replacing FCMOVBE (below or equal) by FCMOVA (above). Probably it’s a compiler inaccuracy.
So FUCOMI compares ST(0) (a) and ST(1) (b) and then sets some flags in the main CPU. FCMOVBE checks the flags
and copies ST(1) (b here at the moment) to ST(0) (a here) if ST0(a) <= ST1(b). Otherwise (a > b), it leaves a in ST(0).
The last FSTP leaves ST(0) on top of the stack, discarding the contents of ST(1).
Let’s trace this function in GDB:
Listing 17.15: Optimizing GCC 4.8.1 and GDB
1 dennis@ubuntuvm:~/polygon$ gcc -O3 d_max.c -o d_max -fno-inline
2 dennis@ubuntuvm:~/polygon$ gdb d_max
3 GNU gdb (GDB) 7.6.1-ubuntu
4 Copyright (C) 2013 Free Software Foundation, Inc.
5 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
6 This is free software: you are free to change and redistribute it.
7 There is NO WARRANTY, to the extent permitted by law. Type "show copying"
8 and "show warranty" for details.
9 This GDB was configured as "i686-linux-gnu".
10 For bug reporting instructions, please see:
11 <http://www.gnu.org/software/gdb/bugs/>...
12 Reading symbols from /home/dennis/polygon/d_max...(no debugging symbols found)...done.
13 (gdb) b d_max
14 Breakpoint 1 at 0x80484a0
15 (gdb) run
16 Starting program: /home/dennis/polygon/d_max
17
18 Breakpoint 1, 0x080484a0 in d_max ()
19 (gdb) ni
20 0x080484a4 in d_max ()
21 (gdb) disas $eip
22 Dump of assembler code for function d_max:
23 0x080484a0 <+0>: fldl 0x4(%esp)
24 => 0x080484a4 <+4>: fldl 0xc(%esp)
25 0x080484a8 <+8>: fxch %st(1)
26 0x080484aa <+10>: fucomi %st(1),%st
27 0x080484ac <+12>: fcmovbe %st(1),%st
28 0x080484ae <+14>: fstp %st(1)
29 0x080484b0 <+16>: ret
30 End of assembler dump.
31 (gdb) ni
32 0x080484a8 in d_max ()
33 (gdb) info float
34 R7: Valid 0x3fff9999999999999800 +1.199999999999999956
35 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911
36 R5: Empty 0x00000000000000000000
37 R4: Empty 0x00000000000000000000
38 R3: Empty 0x00000000000000000000
39 R2: Empty 0x00000000000000000000
40 R1: Empty 0x00000000000000000000
41 R0: Empty 0x00000000000000000000
42
43 Status Word: 0x3000
44 TOP: 6
45 Control Word: 0x037f IM DM ZM OM UM PM
46 PC: Extended Precision (64-bits)
248
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
47 RC: Round to nearest
48 Tag Word: 0x0fff
49 Instruction Pointer: 0x73:0x080484a4
50 Operand Pointer: 0x7b:0xbffff118
51 Opcode: 0x0000
52 (gdb) ni
53 0x080484aa in d_max ()
54 (gdb) info float
55 R7: Valid 0x4000d999999999999800 +3.399999999999999911
56 =>R6: Valid 0x3fff9999999999999800 +1.199999999999999956
57 R5: Empty 0x00000000000000000000
58 R4: Empty 0x00000000000000000000
59 R3: Empty 0x00000000000000000000
60 R2: Empty 0x00000000000000000000
61 R1: Empty 0x00000000000000000000
62 R0: Empty 0x00000000000000000000
63
64 Status Word: 0x3000
65 TOP: 6
66 Control Word: 0x037f IM DM ZM OM UM PM
67 PC: Extended Precision (64-bits)
68 RC: Round to nearest
69 Tag Word: 0x0fff
70 Instruction Pointer: 0x73:0x080484a8
71 Operand Pointer: 0x7b:0xbffff118
72 Opcode: 0x0000
73 (gdb) disas $eip
74 Dump of assembler code for function d_max:
75 0x080484a0 <+0>: fldl 0x4(%esp)
76 0x080484a4 <+4>: fldl 0xc(%esp)
77 0x080484a8 <+8>: fxch %st(1)
78 => 0x080484aa <+10>: fucomi %st(1),%st
79 0x080484ac <+12>: fcmovbe %st(1),%st
80 0x080484ae <+14>: fstp %st(1)
81 0x080484b0 <+16>: ret
82 End of assembler dump.
83 (gdb) ni
84 0x080484ac in d_max ()
85 (gdb) info registers
86 eax 0x1 1
87 ecx 0xbffff1c4 -1073745468
88 edx 0x8048340 134513472
89 ebx 0xb7fbf000 -1208225792
90 esp 0xbffff10c 0xbffff10c
91 ebp 0xbffff128 0xbffff128
92 esi 0x0 0
93 edi 0x0 0
94 eip 0x80484ac 0x80484ac <d_max+12>
95 eflags 0x203 [ CF IF ]
96 cs 0x73 115
97 ss 0x7b 123
98 ds 0x7b 123
99 es 0x7b 123
100 fs 0x0 0
101 gs 0x33 51
102 (gdb) ni
103 0x080484ae in d_max ()
104 (gdb) info float
105 R7: Valid 0x4000d999999999999800 +3.399999999999999911
106 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911
107 R5: Empty 0x00000000000000000000
108 R4: Empty 0x00000000000000000000
109 R3: Empty 0x00000000000000000000
110 R2: Empty 0x00000000000000000000
111 R1: Empty 0x00000000000000000000
112 R0: Empty 0x00000000000000000000
113
114 Status Word: 0x3000
115 TOP: 6
116 Control Word: 0x037f IM DM ZM OM UM PM
249
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
117 PC: Extended Precision (64-bits)
118 RC: Round to nearest
119 Tag Word: 0x0fff
120 Instruction Pointer: 0x73:0x080484ac
121 Operand Pointer: 0x7b:0xbffff118
122 Opcode: 0x0000
123 (gdb) disas $eip
124 Dump of assembler code for function d_max:
125 0x080484a0 <+0>: fldl 0x4(%esp)
126 0x080484a4 <+4>: fldl 0xc(%esp)
127 0x080484a8 <+8>: fxch %st(1)
128 0x080484aa <+10>: fucomi %st(1),%st
129 0x080484ac <+12>: fcmovbe %st(1),%st
130 => 0x080484ae <+14>: fstp %st(1)
131 0x080484b0 <+16>: ret
132 End of assembler dump.
133 (gdb) ni
134 0x080484b0 in d_max ()
135 (gdb) info float
136 =>R7: Valid 0x4000d999999999999800 +3.399999999999999911
137 R6: Empty 0x4000d999999999999800
138 R5: Empty 0x00000000000000000000
139 R4: Empty 0x00000000000000000000
140 R3: Empty 0x00000000000000000000
141 R2: Empty 0x00000000000000000000
142 R1: Empty 0x00000000000000000000
143 R0: Empty 0x00000000000000000000
144
145 Status Word: 0x3800
146 TOP: 7
147 Control Word: 0x037f IM DM ZM OM UM PM
148 PC: Extended Precision (64-bits)
149 RC: Round to nearest
150 Tag Word: 0x3fff
151 Instruction Pointer: 0x73:0x080484ae
152 Operand Pointer: 0x7b:0xbffff118
153 Opcode: 0x0000
154 (gdb) quit
155 A debugging session is active.
156
157 Inferior 1 [process 30194] will be killed.
158
159 Quit anyway? (y or n) y
160 dennis@ubuntuvm:~/polygon$
Using “ni”, let’s execute the first two FLD instructions.
Let’s examine the FPU registers (line 33).
As I wrote before, the FPU registers set is a circular buffer rather than a stack ( 17.5.1 on page 215). And GDB doesn’t
show STx registers, but internal the FPU registers (Rx). The arrow (at line 35) points to the current top of the stack. You
can also see the TOP register contents in Status Word (line 44) — it is 6 now, so the stack top is now pointing to internal
register 6.
The values of a and b are swapped after FXCH is executed (line 54).
FUCOMI is executed (line 83). Let’s see the flags: CF is set (line 95).
FCMOVBE has copied the value of b (see line 104).
FSTP leaves one value at the top of stack (line 136). The value of TOP is now 7, so the FPU stack top is pointing to
internal register 7.
17.7.2 ARM
Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Listing 17.16: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
VMOV D16, R2, R3 ; b
VMOV D17, R0, R1 ; a
VCMPE.F64 D17, D16
VMRS APSR_nzcv, FPSCR
VMOVGT.F64 D16, D17 ; copy "b" to D16
VMOV R0, R1, D16
250
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
BX LR
A very simple case. The input values are placed into the D17 and D16 registers and then compared using the VCMPE
instruction. Just like in the x86 coprocessor, the ARM coprocessor has its own status and flags register, (FPSCR20
), since
there is a need to store coprocessor-specific flags. And just like in x86, there are no conditional jump instruction in ARM,
that can check bits in the status register of the coprocessor, so there is VMRS , which copies 4 bits (N, Z, C, V) from the
coprocessor status word into bits of the general status register (APSR21
).
VMOVGT is the analog of the MOVGT, instruction for D-registers, it executes if one operand is greater than the other while
comparing (GT—Greater Than).
If it gets executed, the value of b is to be written into D16 (that is currently stored in in D17 ).
Otherwise, the value of a stays in the D16 register.
The penultimate instruction VMOV prepares the value in the D16 register for returning it via the R0 and R1 register pair.
Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
Listing 17.17: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
VMOV D16, R2, R3 ; b
VMOV D17, R0, R1 ; a
VCMPE.F64 D17, D16
VMRS APSR_nzcv, FPSCR
IT GT
VMOVGT.F64 D16, D17
VMOV R0, R1, D16
BX LR
Almost the same as in the previous example, however slightly different. As we already know, many instructions in ARM
mode can be supplemented by condition predicate.
But there is no such thing in thumb mode. There is no space in the 16-bit instructions for 4 more bits in which conditions
can be encoded.
However, thumb-2 was extended to make it possible to specify predicates to old thumb instructions.
Here, in the IDA-generated listing, we see the VMOVGT instruction, as in previous example.
In fact, the usual VMOV is encoded there, but IDA adds the -GT suffix to it, since there is a ``IT GT'' instruction
placed right before it.
The IT instruction defines a so-called if-then block. After the instruction it is possible to place up to 4 instructions, each
of them has a predicate suffix. In our example, ``IT GT'' implies that the next instruction is to be executed, if the GT
(Greater Than) condition is true.
Here is a more complex code fragment, by the way, from “Angry Birds” (for iOS):
Listing 17.18: Angry Birds Classic
ITE NE
VMOVNE R2, R3, D16
VMOVEQ R2, R3, D17
ITE stands for if-then-else and it encodes suffixes for the next two instructions. The first instruction executes if the
condition encoded in ITE (NE, not equal) is true at, and the second —if the condition is not true. (The inverse condition of
NE is EQ (equal)).
One more that’s slightly harder, which is also from “Angry Birds”:
Listing 17.19: Angry Birds Classic
ITTTT EQ
MOVEQ R0, R4
ADDEQ SP, SP, #0x20
POPEQ.W {R8,R10}
POPEQ {R4-R7,PC}
Four “T” symbols in the instruction mnemonic mean that the four subsequent instructions are to be executed if the
condition is true. That’s why IDA adds the -EQ suffix to each one of them.
And if there was be, for example, ITEEE EQ (if-then-else-else-else), then the suffixes would have been set as follows:
-EQ
-NE
-NE
-NE
20(ARM) Floating-Point Status and Control Register
21(ARM) Application Program Status Register
251
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Another fragment from “Angry Birds”:
Listing 17.20: Angry Birds Classic
CMP.W R0, #0xFFFFFFFF
ITTE LE
SUBLE.W R10, R0, #1
NEGLE R0, R0
MOVGT R10, R0
ITTE (if-then-then-else) implies that the 1st and 2nd instructions are to be executed if the LE (Less or Equal) condition
is true, and the 3rd—if the inverse condition (GT—Greater Than) is true.
Compilers usually don’t generate all possible combinations. For example, in the mentioned “Angry Birds” game (classic
version for iOS) only these variants of the IT instruction are used: IT, ITE, ITT, ITTE, ITTT, ITTTT. How did I learn this?
In IDA It is possible to produce listing files, so I created them with an option to show 4 bytes for each opcode . Then,
knowing the high part of the 16-bit opcode (IT is 0xBF), I did the following using grep:
cat AngryBirdsClassic.lst | grep " BF" | grep "IT" > results.lst
By the way, if you program in ARM assembly language manually for thumb-2 mode, and you add conditional suffixes, the
assembler will add the IT instructions automatically with the required flags where it is necessary.
Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Listing 17.21: Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode)
b = -0x20
a = -0x18
val_to_return = -0x10
saved_R7 = -4
STR R7, [SP,#saved_R7]!
MOV R7, SP
SUB SP, SP, #0x1C
BIC SP, SP, #7
VMOV D16, R2, R3
VMOV D17, R0, R1
VSTR D17, [SP,#0x20+a]
VSTR D16, [SP,#0x20+b]
VLDR D16, [SP,#0x20+a]
VLDR D17, [SP,#0x20+b]
VCMPE.F64 D16, D17
VMRS APSR_nzcv, FPSCR
BLE loc_2E08
VLDR D16, [SP,#0x20+a]
VSTR D16, [SP,#0x20+val_to_return]
B loc_2E10
loc_2E08
VLDR D16, [SP,#0x20+b]
VSTR D16, [SP,#0x20+val_to_return]
loc_2E10
VLDR D16, [SP,#0x20+val_to_return]
VMOV R0, R1, D16
MOV SP, R7
LDR R7, [SP+0x20+b],#4
BX LR
Almost the same as we already saw, but there is too much redundant code because the a and b variables are stored in
the local stack, as well as the return value.
Optimizing Keil 6/2013 (thumb mode)
Listing 17.22: Optimizing Keil 6/2013 (thumb mode)
PUSH {R3-R7,LR}
MOVS R4, R2
MOVS R5, R3
252
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
MOVS R6, R0
MOVS R7, R1
BL __aeabi_cdrcmple
BCS loc_1C0
MOVS R0, R6
MOVS R1, R7
POP {R3-R7,PC}
loc_1C0
MOVS R0, R4
MOVS R1, R5
POP {R3-R7,PC}
Keil doesn’t generate FPU-instructions since it cannot rely on them being supported on the target CPU, and it can-
not be done by straightforward bitwise comparing. So it calls an external library function to do the comparison: __ae-
abi_cdrcmple.
N.B. The result of the comparison is to be left in the flags by this function, so the following BCS (Carry set - Greater than or
equal) instruction can work without any additional code.
17.7.3 ARM64
Optimizing GCC (Linaro) 4.9
d_max:
; D0 - a, D1 - b
fcmpe d0, d1
fcsel d0, d0, d1, gt
; now result in D0
ret
The ARM64 ISA has FPU-instructions which set APSR the CPU flags instead of FPSCR, for convenience. TheFPU is not
a separate device here anymore (at least, logically). Here we see FCMPE, it compares the two values passed in D0 and D1
(which are the first and second arguments of the function) and sets APSR flags (N, Z, C, V).
FCSEL (Floating Conditional Select) copies the value of D0 or D1 into D0 depending on the condition (GT (Greater Than)
here), and again, it uses flags in APSR register instead of FPSCR. This is much more convenient, compared to the instruction
set in older CPUs.
If the condition is true (GT) then the value of D0 is copied into D0 (i.e., nothing happens). If the condition is not true, the
value of D1 is copied into D0.
Non-optimizing GCC (Linaro) 4.9
d_max:
; save input arguments in "Register Save Area"
sub sp, sp, #16
str d0, [sp,8]
str d1, [sp]
; reload values
ldr x1, [sp,8]
ldr x0, [sp]
fmov d0, x1
fmov d1, x0
; D0 - a, D1 - b
fcmpe d0, d1
ble .L76
; a>b; load D0 (a) into X0
ldr x0, [sp,8]
b .L74
.L76:
; a<=b; load D1 (b) into X0
ldr x0, [sp]
.L74:
; result in X0
fmov d0, x0
; result in D0
add sp, sp, 16
ret
253
CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE
Non-optimizing GCC is more verbose. First, the function saves its input argument values in the local stack (Register
Save Area). Then the code reloads these values into registers X0/X1 and finally copies them to D0/D1 to be compared using
FCMPE. A lot of redundant code, but that is how non-optimizing compilers work. FCMPE compares the values and sets the
APSR flags. At this moment, the compiler is not thinking yet about the more convenient FCSEL instruction, so it proceed
using old methods: using the BLE instruction (Branch if Less than or Equal). In the first case (a > b), the value of a gets loaded
into X0. In the other case (a <= b), the value of b gets loadedin X0. Finally, the value from X0 gets copied into D0, because
the return value needs to be in this register.
Exercise
As an exercise, you can try optimizing this piece of code manually by removing redundant instructions and not introducing
new ones (including FCSEL).
Optimizing GCC (Linaro) 4.9—float
I also rewrote this example to use float instead of double.
float f_max (float a, float b)
{
if (a>b)
return a;
return b;
};
f_max:
; S0 - a, S1 - b
fcmpe s0, s1
fcsel s0, s0, s1, gt
; now result in S0
ret
It is the same code, but the S-registers are used instead of D- ones. It’s because numbers of type float are passed in
32-bit S-registers (which are in fact the lower parts of the 64-bit D-registers).
17.7.4 MIPS
The co-processor of the most popular MIPS processor has only one condition bit which can be set in the FPU and checked in
the CPU. Earlier MIPS-es have only one condition bit (called FCC0), later ones have 8 (called FCC7-FCC0). These bits are
located in the register called FCCR.
Listing 17.23: Optimizing GCC 4.4.5 (IDA)
d_max:
; set FPU condition bit if $f14<$f12 (b<a):
c.lt.d $f14, $f12
or $at, $zero ; NOP
; jump to locret_14 if condition bit is set
bc1t locret_14
; this instruction is always executed (set return value to "a"):
mov.d $f0, $f12 ; branch delay slot
; this instruction is executed only if branch was not taken (i.e., if b>=a)
; set return value to "b":
mov.d $f0, $f14
locret_14:
jr $ra
or $at, $zero ; branch delay slot, NOP
“C.LT.D” compares two values. “LT” is the condition “Less Than”. “D” implies values of type double. Depending on the
result of the comparison, the FCC0 condition bit is either set or cleared.
“BC1T” checks the FCC0 bit and jumps if the bit is set. “T” mean that the jump is to be taken if the bit is set (“True”). There
is also the instruction “BC1F” which jumps if the bit is cleared (“False”).
Depending on the jump, one of function arguments is placed into $F0.
254
CHAPTER 17. FLOATING-POINT UNIT 17.8. STACK, CALCULATORS AND REVERSE POLISH NOTATION
17.8 Stack, calculators and reverse Polish notation
Now we undestand why some old calculators used reverse Polish notation 22
. For example, for addition of 12 and 34, one
has to enter 12, then 34, then press “plus” sign. It’s because old calculators were just stack machine implementations, and
this was much simpler than to handle complex expressions with parentheses.
17.9 x64
On how float point numbers are processed in x86-64, read more here: 27 on page 434.
17.10 Exercises
17.10.1 Exercise #1
Eliminate the FXCH instruction in the example 17.7.1 on page 247 and test it.
17.10.2 Exercise #2
What does this code do?
Listing 17.24: Optimizing MSVC 2010
__real@4014000000000000 DQ 04014000000000000r ; 5
_a1$ = 8 ; size = 8
_a2$ = 16 ; size = 8
_a3$ = 24 ; size = 8
_a4$ = 32 ; size = 8
_a5$ = 40 ; size = 8
_f PROC
fld QWORD PTR _a1$[esp-4]
fadd QWORD PTR _a2$[esp-4]
fadd QWORD PTR _a3$[esp-4]
fadd QWORD PTR _a4$[esp-4]
fadd QWORD PTR _a5$[esp-4]
fdiv QWORD PTR __real@4014000000000000
ret 0
_f ENDP
Listing 17.25: Non-optimizing Keil 6/2013 (thumb mode / compiled for Cortex-R4F CPU)
f PROC
VADD.F64 d0,d0,d1
VMOV.F64 d1,#5.00000000
VADD.F64 d0,d0,d2
VADD.F64 d0,d0,d3
VADD.F64 d2,d0,d4
VDIV.F64 d0,d2,d1
BX lr
ENDP
Listing 17.26: Optimizing GCC 4.9 (ARM64)
f:
fadd d0, d0, d1
fmov d1, 5.0e+0
fadd d2, d0, d2
fadd d3, d2, d3
fadd d0, d3, d4
fdiv d0, d0, d1
ret
22wikipedia
255
CHAPTER 17. FLOATING-POINT UNIT 17.10. EXERCISES
Listing 17.27: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
arg_10 = 0x10
arg_14 = 0x14
arg_18 = 0x18
arg_1C = 0x1C
arg_20 = 0x20
arg_24 = 0x24
lwc1 $f0, arg_14($sp)
add.d $f2, $f12, $f14
lwc1 $f1, arg_10($sp)
lui $v0, ($LC0 >> 16)
add.d $f0, $f2, $f0
lwc1 $f2, arg_1C($sp)
or $at, $zero
lwc1 $f3, arg_18($sp)
or $at, $zero
add.d $f0, $f2
lwc1 $f2, arg_24($sp)
or $at, $zero
lwc1 $f3, arg_20($sp)
or $at, $zero
add.d $f0, $f2
lwc1 $f2, dword_6C
or $at, $zero
lwc1 $f3, $LC0
jr $ra
div.d $f0, $f2
$LC0: .word 0x40140000 # DATA XREF: f+C
# f+44
dword_6C: .word 0 # DATA XREF: f+3C
Answer G.1.9 on page 955.
256
CHAPTER 18. ARRAYS
Chapter 18
Arrays
An array is just a set of variables in memory that lie next to each other and that have the same type 1
.
18.1 Simple example
#include <stdio.h>
int main()
{
int a[20];
int i;
for (i=0; i<20; i++)
a[i]=i*2;
for (i=0; i<20; i++)
printf ("a[%d]=%dn", i, a[i]);
return 0;
};
18.1.1 x86
MSVC
Let’s compile:
Listing 18.1: MSVC 2008
_TEXT SEGMENT
_i$ = -84 ; size = 4
_a$ = -80 ; size = 80
_main PROC
push ebp
mov ebp, esp
sub esp, 84 ; 00000054H
mov DWORD PTR _i$[ebp], 0
jmp SHORT $LN6@main
$LN5@main:
mov eax, DWORD PTR _i$[ebp]
add eax, 1
mov DWORD PTR _i$[ebp], eax
$LN6@main:
cmp DWORD PTR _i$[ebp], 20 ; 00000014H
jge SHORT $LN4@main
mov ecx, DWORD PTR _i$[ebp]
shl ecx, 1
mov edx, DWORD PTR _i$[ebp]
mov DWORD PTR _a$[ebp+edx*4], ecx
jmp SHORT $LN5@main
$LN4@main:
1AKA2 “homogeneous container”
257
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
mov DWORD PTR _i$[ebp], 0
jmp SHORT $LN3@main
$LN2@main:
mov eax, DWORD PTR _i$[ebp]
add eax, 1
mov DWORD PTR _i$[ebp], eax
$LN3@main:
cmp DWORD PTR _i$[ebp], 20 ; 00000014H
jge SHORT $LN1@main
mov ecx, DWORD PTR _i$[ebp]
mov edx, DWORD PTR _a$[ebp+ecx*4]
push edx
mov eax, DWORD PTR _i$[ebp]
push eax
push OFFSET $SG2463
call _printf
add esp, 12 ; 0000000cH
jmp SHORT $LN2@main
$LN1@main:
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
Nothing very special, just two loops: the first is a filling loop and second is a printing loop. The shl ecx, 1 instruction
is used for value multiplication by 2 in ECX, more about below 16.2.1 on page 206.
80 bytes are allocated on the stack for the array, 20 elements of 4 bytes.
258
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
Let’s try this example in OllyDbg.
We see how the array gets filled: each element is 32-bit word of int type and its value is the index multiplied by 2:
Figure 18.1: OllyDbg: after array filling
Since this array is located in the stack, we can see all its 20 elements there.
GCC
Here is what GCC 4.4.1 does:
Listing 18.2: GCC 4.4.1
public main
main proc near ; DATA XREF: _start+17
var_70 = dword ptr -70h
var_6C = dword ptr -6Ch
var_68 = dword ptr -68h
i_2 = dword ptr -54h
i = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 70h
mov [esp+70h+i], 0 ; i=0
jmp short loc_804840A
loc_80483F7:
mov eax, [esp+70h+i]
mov edx, [esp+70h+i]
add edx, edx ; edx=i*2
mov [esp+eax*4+70h+i_2], edx
add [esp+70h+i], 1 ; i++
259
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
loc_804840A:
cmp [esp+70h+i], 13h
jle short loc_80483F7
mov [esp+70h+i], 0
jmp short loc_8048441
loc_804841B:
mov eax, [esp+70h+i]
mov edx, [esp+eax*4+70h+i_2]
mov eax, offset aADD ; "a[%d]=%dn"
mov [esp+70h+var_68], edx
mov edx, [esp+70h+i]
mov [esp+70h+var_6C], edx
mov [esp+70h+var_70], eax
call _printf
add [esp+70h+i], 1
loc_8048441:
cmp [esp+70h+i], 13h
jle short loc_804841B
mov eax, 0
leave
retn
main endp
By the way, variable a is of type int* (the pointer to int) —you can pass a pointer to an array to another function, but
it’s more correct to say that a pointer to the first element of the array is passed (the addresses of rest of the elements are
calculated in an obvious way). If you index this pointer as a[idx], idx is just to be added to the pointer and the element
placed there (to which calculated pointer is pointing) is to be returned.
An interesting example: a string of characters like “string” is an array of characters and it has a type of const char[]. An
index can also be applied to this pointer. And that is why it is possible to write things like ``string''[i] —this is a
correct C/C++ expression!
18.1.2 ARM
Non-optimizing Keil 6/2013 (ARM mode)
EXPORT _main
_main
STMFD SP!, {R4,LR}
SUB SP, SP, #0x50 ; allocate place for 20 int variables
; first loop
MOV R4, #0 ; i
B loc_4A0
loc_494
MOV R0, R4,LSL#1 ; R0=R4*2
STR R0, [SP,R4,LSL#2] ; store R0 to SP+R4<<2 (same as SP+R4*4)
ADD R4, R4, #1 ; i=i+1
loc_4A0
CMP R4, #20 ; i<20?
BLT loc_494 ; yes, run loop body again
; second loop
MOV R4, #0 ; i
B loc_4C4
loc_4B0
LDR R2, [SP,R4,LSL#2] ; (second printf argument) R2=*(SP+R4<<4) (same as
*(SP+R4*4))
MOV R1, R4 ; (first printf argument) R1=i
ADR R0, aADD ; "a[%d]=%dn"
BL __2printf
ADD R4, R4, #1 ; i=i+1
loc_4C4
260
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
CMP R4, #20 ; i<20?
BLT loc_4B0 ; yes, run loop body again
MOV R0, #0 ; value to return
ADD SP, SP, #0x50 ; deallocate chunk, allocated for 20 int variables
LDMFD SP!, {R4,PC}
int type requires 32 bits for storage (or 4 bytes), so to store 20 int variables 80 (0x50) bytes are needed. So that is why
the ``SUB SP, SP, #0x50'' instruction in the function’s prologie allocates exactly this amount of space in the stack.
In both the first and second loops, the loop iterator i is placed in the R4 register.
The number that is to be written into the array is calculated as i ∗ 2, which is effectively equivalent to shifting it left by
one bit, so ``MOV R0, R4,LSL#1'' instruction does this.
``STR R0, [SP,R4,LSL#2]'' writes the contents of R0 into the array. Here is how a pointer to array element is
calculated: SP points to the start of the array, R4 is i. So shifting i left by 2 bits is effectively equivalent to multiplication
by 4 (since each array element has a size of 4 bytes) and then it’s added to the address of the start of the array.
The second loop has an inverse ``LDR R2, [SP,R4,LSL#2]'' instruction, it loads the value we need from the array,
and the pointer to it is calculated likewise.
Optimizing Keil 6/2013 (thumb mode)
_main
PUSH {R4,R5,LR}
; allocate place for 20 int variables + one more variable
SUB SP, SP, #0x54
; first loop
MOVS R0, #0 ; i
MOV R5, SP ; pointer to first array element
loc_1CE
LSLS R1, R0, #1 ; R1=i<<1 (same as i*2)
LSLS R2, R0, #2 ; R2=i<<2 (same as i*4)
ADDS R0, R0, #1 ; i=i+1
CMP R0, #20 ; i<20?
STR R1, [R5,R2] ; store R1 to *(R5+R2) (same R5+i*4)
BLT loc_1CE ; yes, i<20, run loop body again
; second loop
MOVS R4, #0 ; i=0
loc_1DC
LSLS R0, R4, #2 ; R0=i<<2 (same as i*4)
LDR R2, [R5,R0] ; load from *(R5+R0) (same as R5+i*4)
MOVS R1, R4
ADR R0, aADD ; "a[%d]=%dn"
BL __2printf
ADDS R4, R4, #1 ; i=i+1
CMP R4, #20 ; i<20?
BLT loc_1DC ; yes, i<20, run loop body again
MOVS R0, #0 ; value to return
; deallocate chunk, allocated for 20 int variables + one more variable
ADD SP, SP, #0x54
POP {R4,R5,PC}
Thumb code is very similar. Thumb mode has special instructions for bit shifting (like LSLS), which calculates the value
to be written into the array and the address of each element in the array as well.
The compiler allocates slightly more space in the local stack, however, the last 4 bytes are not used.
Non-optimizing GCC 4.9.1 (ARM64)
Listing 18.3: Non-optimizing GCC 4.9.1 (ARM64)
.LC0:
.string "a[%d]=%dn"
main:
; save FP and LR in stack frame:
stp x29, x30, [sp, -112]!
; set stack frame (FP=SP)
261
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
add x29, sp, 0
; setting initial counter variable at 0 (WZR is the register always holding zero):
str wzr, [x29,108]
; jump to loop condition checking code:
b .L2
.L3:
; load value of "i" variable:
ldr w0, [x29,108]
; multiplicate it by 2:
lsl w2, w0, 1
; find a place of an array in local stack:
add x0, x29, 24
; load 32-bit integer from local stack and sign extend it to 64-bit one:
ldrsw x1, [x29,108]
; calculate address of element (X0+X1<<2=array address+i*4) and store W2 (i*2) there:
str w2, [x0,x1,lsl 2]
; increment counter (i):
ldr w0, [x29,108]
add w0, w0, 1
str w0, [x29,108]
.L2:
; check if we finished:
ldr w0, [x29,108]
cmp w0, 19
; jump to L3 (loop body begin) if not:
ble .L3
; second part of the function begins here.
; setting initial counter variable at 0.
; by the way, the same place in the local stack was used for counter,
; because the same local variable (i) is being used as counter.
str wzr, [x29,108]
b .L4
.L5:
; calculate array address:
add x0, x29, 24
; load "i" value:
ldrsw x1, [x29,108]
; load value from the array at the address (X0+X1<<2 = address of array + i*4)
ldr w2, [x0,x1,lsl 2]
; load address of the "a[%d]=%dn" string:
adrp x0, .LC0
add x0, x0, :lo12:.LC0
; load "i" variable to W1 and pass it to printf() as second argument:
ldr w1, [x29,108]
; W2 still contains the value of array element which was just loaded.
; call printf():
bl printf
; increment "i" variable:
ldr w0, [x29,108]
add w0, w0, 1
str w0, [x29,108]
.L4:
; are we finished?
ldr w0, [x29,108]
cmp w0, 19
; jump to the loop body begin if not:
ble .L5
; return 0
mov w0, 0
; restore FP and LR:
ldp x29, x30, [sp], 112
ret
18.1.3 MIPS
The function uses a lot of S- registers which must be preserved, so that’s why its values are saved in the function prologue
and restored in the epilogue.
262
CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE
Listing 18.4: Optimizing GCC 4.4.5 (IDA)
main:
var_70 = -0x70
var_68 = -0x68
var_14 = -0x14
var_10 = -0x10
var_C = -0xC
var_8 = -8
var_4 = -4
; function prologue:
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x80
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x80+var_4($sp)
sw $s3, 0x80+var_8($sp)
sw $s2, 0x80+var_C($sp)
sw $s1, 0x80+var_10($sp)
sw $s0, 0x80+var_14($sp)
sw $gp, 0x80+var_70($sp)
addiu $s1, $sp, 0x80+var_68
move $v1, $s1
move $v0, $zero
; that value will be used as a loop terminator.
; it was precalculated by GCC compiler at compile stage:
li $a0, 0x28 # '('
loc_34: # CODE XREF: main+3C
; store value into memory:
sw $v0, 0($v1)
; increase value to be stored by 2 at each iteration:
addiu $v0, 2
; loop terminator reached?
bne $v0, $a0, loc_34
; add 4 to address anyway:
addiu $v1, 4
; array filling loop is ended
; second loop begin
la $s3, $LC0 # "a[%d]=%dn"
; "i" variable will reside in $s0:
move $s0, $zero
li $s2, 0x14
loc_54: # CODE XREF: main+70
; call printf():
lw $t9, (printf & 0xFFFF)($gp)
lw $a2, 0($s1)
move $a1, $s0
move $a0, $s3
jalr $t9
; increment "i":
addiu $s0, 1
lw $gp, 0x80+var_70($sp)
; jump to loop body if end is not reached:
bne $s0, $s2, loc_54
; move memory pointer to the next 32-bit word:
addiu $s1, 4
; function epilogue
lw $ra, 0x80+var_4($sp)
move $v0, $zero
lw $s3, 0x80+var_8($sp)
lw $s2, 0x80+var_C($sp)
lw $s1, 0x80+var_10($sp)
lw $s0, 0x80+var_14($sp)
jr $ra
addiu $sp, 0x80
$LC0: .ascii "a[%d]=%dn"<0> # DATA XREF: main+44
263
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
Something interesting: there are two loops and the first one doesn’t needs i, it needs only i ∗ 2 (increased by 2 at each
iteration) and also the address in memory (increased by 4 at each iteration). So here we see two variables, one (in $V0)
increasing by 2 each time, and another (in $V1) — by 4.
The second loop is where printf() is called and it reports the value of i to the user, so there is a variable which is
increased by 1 each time (in $S0) and also a memory address (in $S1) increased by 4 each time.
That reminds us of loop optimizations we considered earlier: 39 on page 480. Their goal is to get rid of of multiplica-
tions.
18.2 Buffer overflow
18.2.1 Reading outside array bounds
So, array indexing is just array[index]. If you study the generated code closely, you’ll probably note the missing index bounds
checking, which could check if it is less than 20. What if the index is 20 or greater? That’s the one C/C++ feature it is often
blamed for.
Here is a code that successfully compiles and works:
#include <stdio.h>
int main()
{
int a[20];
int i;
for (i=0; i<20; i++)
a[i]=i*2;
printf ("a[20]=%dn", a[20]);
return 0;
};
Compilation results (MSVC 2008):
Listing 18.5: Non-optimizing MSVC 2008
$SG2474 DB 'a[20]=%d', 0aH, 00H
_i$ = -84 ; size = 4
_a$ = -80 ; size = 80
_main PROC
push ebp
mov ebp, esp
sub esp, 84
mov DWORD PTR _i$[ebp], 0
jmp SHORT $LN3@main
$LN2@main:
mov eax, DWORD PTR _i$[ebp]
add eax, 1
mov DWORD PTR _i$[ebp], eax
$LN3@main:
cmp DWORD PTR _i$[ebp], 20
jge SHORT $LN1@main
mov ecx, DWORD PTR _i$[ebp]
shl ecx, 1
mov edx, DWORD PTR _i$[ebp]
mov DWORD PTR _a$[ebp+edx*4], ecx
jmp SHORT $LN2@main
$LN1@main:
mov eax, DWORD PTR _a$[ebp+80]
push eax
push OFFSET $SG2474 ; 'a[20]=%d'
call DWORD PTR __imp__printf
add esp, 8
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
264
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
_TEXT ENDS
END
When I run it, I get:
Figure 18.2: OllyDbg: console output
It is just something that was lying in the stack near to the array, 80 bytes away from its first element.
265
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
Let’s try to find out where did this value come from, using OllyDbg. Let’s load and find the value located right after the
last array element:
Figure 18.3: OllyDbg: reading of the 20th element and execution of printf()
What is this? Judging by the stack layout, this is the saved value of the EBP register.
266
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
Let’s trace further and see how it gets restored:
Figure 18.4: OllyDbg: restoring value of EBP
Indeed, how it could be different? The compiler may generate some additional code to check the index value to be always
in the array’s bounds (like in higher-level programming languages3
) but this makes the code slower.
18.2.2 Writing beyond array bounds
OK, we read some values from the stack illegally, but what if we could write something to it?
Here is what we have got:
#include <stdio.h>
int main()
{
int a[20];
int i;
for (i=0; i<30; i++)
a[i]=i;
return 0;
};
MSVC
And what we get:
Listing 18.6: Non-optimizing MSVC 2008
_TEXT SEGMENT
3Java, Python, etc
267
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
_i$ = -84 ; size = 4
_a$ = -80 ; size = 80
_main PROC
push ebp
mov ebp, esp
sub esp, 84
mov DWORD PTR _i$[ebp], 0
jmp SHORT $LN3@main
$LN2@main:
mov eax, DWORD PTR _i$[ebp]
add eax, 1
mov DWORD PTR _i$[ebp], eax
$LN3@main:
cmp DWORD PTR _i$[ebp], 30 ; 0000001eH
jge SHORT $LN1@main
mov ecx, DWORD PTR _i$[ebp]
mov edx, DWORD PTR _i$[ebp] ; that instruction is obviously redundant
mov DWORD PTR _a$[ebp+ecx*4], edx ; ECX could be used as second operand here instead
jmp SHORT $LN2@main
$LN1@main:
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
The compiled program crashes after running. No wonder. Let’s see where exactly does it is crash.
268
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
Let’s load it into OllyDbg, and trace until all 30 elements are written:
Figure 18.5: OllyDbg: after restoring the value of EBP
269
CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW
Trace until the function end:
Figure 18.6: OllyDbg: EIP was restored, but OllyDbg can’t disassemble at 0x15
Now please keep your eyes on the registers.
EIP is 0x15 now. It is not a legal address for code —at least for win32 code! We got there somehow against our will. It
is also interesting that the EBP register contain 0x14, ECX and EDX —0x1D.
Let’s study stack layout a bit more.
After the control flow was passed to main(), the value in the EBP register was saved on the stack. Then, 84 bytes were
allocated for the array and the i variable. That’s (20+1)*sizeof(int). ESP now points to the _i variable in the local
stack and after the execution of the next PUSH something, something is appearing next to _i.
That’s the stack layout while the control is in main():
ESP 4 bytes allocated for i variable
ESP+4 80 bytes allocated for a[20] array
ESP+84 saved EBP value
ESP+88 return address
a[19]=something statement writes the last int in the bounds of the array (in bounds so far!)
a[20]=something statement writes something to the place where the value of EBP is saved.
Please take a look at the register state at the moment of the crash. In our case, 20 was written in the 20th element. At
the function end, the function epilogue restores the original EBP value. (20 in decimal is 0x14 in hexadecimal). Then RET
gets executed, which is effectively equivalent to POP EIP instruction.
The RET instruction takes the return address from the stack (that is the address in CRT), which was called main()),
and 21 iss stored there (0x15 in hexadecimal). The CPU traps at address 0x15, but there is no executable code there, so
exception gets raised.
Welcome! It is called a buffer overflow4
.
4wikipedia
270
CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS
Replace the int array with a string (char array), create a long string deliberately and pass it to the program, to the function,
which doesn’t check the length of the string and copies it in a short buffer, and you’ll able to point the program to an address
to which it must jump. It’s not that simple in reality, but that is how it emerged 5
GCC
Let’s try the same code in GCC 4.4.1. We get:
public main
main proc near
a = dword ptr -54h
i = dword ptr -4
push ebp
mov ebp, esp
sub esp, 60h ; 96
mov [ebp+i], 0
jmp short loc_80483D1
loc_80483C3:
mov eax, [ebp+i]
mov edx, [ebp+i]
mov [ebp+eax*4+a], edx
add [ebp+i], 1
loc_80483D1:
cmp [ebp+i], 1Dh
jle short loc_80483C3
mov eax, 0
leave
retn
main endp
Running this in Linux will produce: Segmentation fault.
If we run this in the GDB debugger, we get this:
(gdb) r
Starting program: /home/dennis/RE/1
Program received signal SIGSEGV, Segmentation fault.
0x00000016 in ?? ()
(gdb) info registers
eax 0x0 0
ecx 0xd2f96388 -755407992
edx 0x1d 29
ebx 0x26eff4 2551796
esp 0xbffff4b0 0xbffff4b0
ebp 0x15 0x15
esi 0x0 0
edi 0x0 0
eip 0x16 0x16
eflags 0x10202 [ IF RF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb)
The register values are slightly different than in win32 example, since the stack layout is slightly different too.
18.3 Buffer overflow protection methods
There are several methods to protect against this scourge, regardless of the C/C++ programmers’ negligence. MSVC has
options like6
:
5Classic article about it: [One96].
6Wikipedia: compiler-side buffer overflow protection methods:
wikipedia
271
CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS
/RTCs Stack Frame runtime checking
/GZ Enable stack checks (/RTCs)
One of the methods is to write a random value between the local variables in stack at function prologue and to check it
in function epilogue before the function exits. If value is not the same, do not execute the last instruction RET, but stop (or
hang). The process will halt, but that is much better than a remote attack to your host.
This random value is called a “canary” sometimes, it is related to the miners’ canary7
, they were used by miners in the
past days in order to detect poisonous gases quickly. Canaries are very sensitive to mine gases, they become very agitated
in case of danger, or even die.
If we compile our very simple array example ( 18.1 on page 257) in MSVC with RTC1 and RTCs option, you can see a call
to
@_RTC_CheckStackVars@8 a function at the end of the function that checks if the “canary” is correct.
Let’s see how GCC handles this. Let’s take an alloca() ( 5.2.4 on page 25) example:
#ifdef __GNUC__
#include <alloca.h> // GCC
#else
#include <malloc.h> // MSVC
#endif
#include <stdio.h>
void f()
{
char *buf=(char*)alloca (600);
#ifdef __GNUC__
snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // GCC
#else
_snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // MSVC
#endif
puts (buf);
};
By default, without any additional options, GCC 4.7.3 inserts a “canary” check into the code:
Listing 18.7: GCC 4.7.3
.LC0:
.string "hi! %d, %d, %dn"
f:
push ebp
mov ebp, esp
push ebx
sub esp, 676
lea ebx, [esp+39]
and ebx, -16
mov DWORD PTR [esp+20], 3
mov DWORD PTR [esp+16], 2
mov DWORD PTR [esp+12], 1
mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %dn"
mov DWORD PTR [esp+4], 600
mov DWORD PTR [esp], ebx
mov eax, DWORD PTR gs:20 ; canary
mov DWORD PTR [ebp-12], eax
xor eax, eax
call _snprintf
mov DWORD PTR [esp], ebx
call puts
mov eax, DWORD PTR [ebp-12]
xor eax, DWORD PTR gs:20 ; check canary
jne .L5
mov ebx, DWORD PTR [ebp-4]
leave
ret
.L5:
call __stack_chk_fail
7wikipedia
272
CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS
The random value is located in gs:20. It gets written on the stack and then at the end of the function the value in the
stack is compared with the correct “canary” in gs:20. If the values are not equal, the __stack_chk_fail function is
called and we can see in the console something like that (Ubuntu 13.04 x86):
*** buffer overflow detected ***: ./2_1 terminated
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x63)[0xb7699bc3]
/lib/i386-linux-gnu/libc.so.6(+0x10593a)[0xb769893a]
/lib/i386-linux-gnu/libc.so.6(+0x105008)[0xb7698008]
/lib/i386-linux-gnu/libc.so.6(_IO_default_xsputn+0x8c)[0xb7606e5c]
/lib/i386-linux-gnu/libc.so.6(_IO_vfprintf+0x165)[0xb75d7a45]
/lib/i386-linux-gnu/libc.so.6(__vsprintf_chk+0xc9)[0xb76980d9]
/lib/i386-linux-gnu/libc.so.6(__sprintf_chk+0x2f)[0xb7697fef]
./2_1[0x8048404]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0xb75ac935]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:01 2097586 /home/dennis/2_1
08049000-0804a000 r--p 00000000 08:01 2097586 /home/dennis/2_1
0804a000-0804b000 rw-p 00001000 08:01 2097586 /home/dennis/2_1
094d1000-094f2000 rw-p 00000000 00:00 0 [heap]
b7560000-b757b000 r-xp 00000000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1
b757b000-b757c000 r--p 0001a000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1
b757c000-b757d000 rw-p 0001b000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1
b7592000-b7593000 rw-p 00000000 00:00 0
b7593000-b7740000 r-xp 00000000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so
b7740000-b7742000 r--p 001ad000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so
b7742000-b7743000 rw-p 001af000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so
b7743000-b7746000 rw-p 00000000 00:00 0
b775a000-b775d000 rw-p 00000000 00:00 0
b775d000-b775e000 r-xp 00000000 00:00 0 [vdso]
b775e000-b777e000 r-xp 00000000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so
b777e000-b777f000 r--p 0001f000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so
b777f000-b7780000 rw-p 00020000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so
bff35000-bff56000 rw-p 00000000 00:00 0 [stack]
Aborted (core dumped)
gs—is the so-called segment register, these registers were used widely in MS-DOS and DOS-extenders times. Today, its
function is different. To say it briefly, the gs register in Linux always points to the TLS ( 65 on page 671) —some information
specific to thread is stored there (by the way, in win32 the fs register plays the same role, pointing to TIB8 9
).
More information can be found in the Linux kernel source code (at least in 3.11 version), in arch/x86/include/asm/stackprotector.h
this variable is described in the comments.
18.3.1 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
Let’s get back to our simple array example ( 18.1 on page 257), again, now we can see how LLVM checks the correctness of
the “canary”:
_main
var_64 = -0x64
var_60 = -0x60
var_5C = -0x5C
var_58 = -0x58
var_54 = -0x54
var_50 = -0x50
var_4C = -0x4C
var_48 = -0x48
var_44 = -0x44
var_40 = -0x40
var_3C = -0x3C
var_38 = -0x38
var_34 = -0x34
var_30 = -0x30
var_2C = -0x2C
var_28 = -0x28
var_24 = -0x24
var_20 = -0x20
8Thread Information Block
9wikipedia
273
CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS
var_1C = -0x1C
var_18 = -0x18
canary = -0x14
var_10 = -0x10
PUSH {R4-R7,LR}
ADD R7, SP, #0xC
STR.W R8, [SP,#0xC+var_10]!
SUB SP, SP, #0x54
MOVW R0, #aObjc_methtype ; "objc_methtype"
MOVS R2, #0
MOVT.W R0, #0
MOVS R5, #0
ADD R0, PC
LDR.W R8, [R0]
LDR.W R0, [R8]
STR R0, [SP,#0x64+canary]
MOVS R0, #2
STR R2, [SP,#0x64+var_64]
STR R0, [SP,#0x64+var_60]
MOVS R0, #4
STR R0, [SP,#0x64+var_5C]
MOVS R0, #6
STR R0, [SP,#0x64+var_58]
MOVS R0, #8
STR R0, [SP,#0x64+var_54]
MOVS R0, #0xA
STR R0, [SP,#0x64+var_50]
MOVS R0, #0xC
STR R0, [SP,#0x64+var_4C]
MOVS R0, #0xE
STR R0, [SP,#0x64+var_48]
MOVS R0, #0x10
STR R0, [SP,#0x64+var_44]
MOVS R0, #0x12
STR R0, [SP,#0x64+var_40]
MOVS R0, #0x14
STR R0, [SP,#0x64+var_3C]
MOVS R0, #0x16
STR R0, [SP,#0x64+var_38]
MOVS R0, #0x18
STR R0, [SP,#0x64+var_34]
MOVS R0, #0x1A
STR R0, [SP,#0x64+var_30]
MOVS R0, #0x1C
STR R0, [SP,#0x64+var_2C]
MOVS R0, #0x1E
STR R0, [SP,#0x64+var_28]
MOVS R0, #0x20
STR R0, [SP,#0x64+var_24]
MOVS R0, #0x22
STR R0, [SP,#0x64+var_20]
MOVS R0, #0x24
STR R0, [SP,#0x64+var_1C]
MOVS R0, #0x26
STR R0, [SP,#0x64+var_18]
MOV R4, 0xFDA ; "a[%d]=%dn"
MOV R0, SP
ADDS R6, R0, #4
ADD R4, PC
B loc_2F1C
; second loop begin
loc_2F14
ADDS R0, R5, #1
LDR.W R2, [R6,R5,LSL#2]
MOV R5, R0
loc_2F1C
274
CHAPTER 18. ARRAYS 18.4. ONE MORE WORD ABOUT ARRAYS
MOV R0, R4
MOV R1, R5
BLX _printf
CMP R5, #0x13
BNE loc_2F14
LDR.W R0, [R8]
LDR R1, [SP,#0x64+canary]
CMP R0, R1
ITTTT EQ ; canary still correct?
MOVEQ R0, #0
ADDEQ SP, SP, #0x54
LDREQ.W R8, [SP+0x64+var_64],#4
POPEQ {R4-R7,PC}
BLX ___stack_chk_fail
First of all, as we see, LLVM “unrolled” the loop and all values were written into an array one-by-one, pre-calculated, as
LLVM concluded it can work faster. By the way, instructions in ARM mode may help to do this even faster, and finding this
could be your homework.
At the function end we see the comparison of the “canaries” —the one in the local stack and the correct one, to which
R8 points. If they are equal to each other, a 4-instruction block is triggered by ``ITTTT EQ'', which contains writ-
ing 0 in R0, the function epilogue and exit. If the “canaries” are not equal, the block being skipped, and the jump to
___stack_chk_fail function will occur, which, as I suppose, will halt execution.
18.4 One more word about arrays
Now we understand why it is impossible to write something like this in C/C++ code 10
:
void f(int size)
{
int a[size];
...
};
That’s just because the compiler must know the exact array size to allocate space for it in the local stack layout on at the
compiling stage.
If you need an array of arbitrary size, allocate it by using malloc(), then access the allocated memory block as an array
of variables of the type you need. Or use the C99 standard feature[ISO07, pp. 6.7.5/2], but it looks like alloca() ( 5.2.4 on
page 25) internally.
18.5 Array of pointers to strings
Here is an example for an array of pointers.
Listing 18.8: Get month name
#include <stdio.h>
const char* month1[]=
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
// in 0..11 range
const char* get_month1 (int month)
10However, it is possible in C99 standard[ISO07, pp. 6.7.5/2]: GCC actually does this by allocating an array dynamically on the stack (like alloca() ( 5.2.4
on page 25))
275
CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS
{
return month1[month];
};
18.5.1 x64
Listing 18.9: Optimizing MSVC 2013 x64
_DATA SEGMENT
month1 DQ FLAT:$SG3122
DQ FLAT:$SG3123
DQ FLAT:$SG3124
DQ FLAT:$SG3125
DQ FLAT:$SG3126
DQ FLAT:$SG3127
DQ FLAT:$SG3128
DQ FLAT:$SG3129
DQ FLAT:$SG3130
DQ FLAT:$SG3131
DQ FLAT:$SG3132
DQ FLAT:$SG3133
$SG3122 DB 'January', 00H
$SG3123 DB 'February', 00H
$SG3124 DB 'March', 00H
$SG3125 DB 'April', 00H
$SG3126 DB 'May', 00H
$SG3127 DB 'June', 00H
$SG3128 DB 'July', 00H
$SG3129 DB 'August', 00H
$SG3130 DB 'September', 00H
$SG3156 DB '%s', 0aH, 00H
$SG3131 DB 'October', 00H
$SG3132 DB 'November', 00H
$SG3133 DB 'December', 00H
_DATA ENDS
month$ = 8
get_month1 PROC
movsxd rax, ecx
lea rcx, OFFSET FLAT:month1
mov rax, QWORD PTR [rcx+rax*8]
ret 0
get_month1 ENDP
The code is very simple:
• The first MOVSXD instruction copies a 32-bit value from ECX (where month argument is passed) to RAX with sign-
extension (because the month argument is of type int). The reason for the sign extension is that this 32-bit value is
to be used in calculations with other 64-bit values. Hence, it has to be promoted to 64-bit 11
.
• Then the address of the pointer table is loaded into RCX.
• Finally, the input value (month) is multiplied by 8 and added to the address. Indeed: we are in a 64-bit environment
and all address (or pointers) require exactly 64 bits (or 8 bytes) for storage. Hence, each table element is 8 bytes wide.
And that’s why to pick a specific element, month ∗ 8 bytes has to be skipped from the start. That’s what MOV does. In
addition, this instruction also loads the element at this address. For 1, an element would be a pointer to a string that
contains “February”, etc.
Optimizing GCC 4.9 can do the job even better 12
:
Listing 18.10: Optimizing GCC 4.9 x64
movsx rdi, edi
mov rax, QWORD PTR month1[0+rdi*8]
ret
11It is somewhat weird, but negative array index could be passed here as month (negative array indices will have been explained later: 52 on page 589)
. And if this happens, the negative input value of int type is sign-extended correctly and the corresponding element before table is picked. It is not going
to work correctly without sign-extension.
12“0+” was left in the listing because GCC assembler output is not tidy enough to eliminate it. It’s displacement, and it’s zero here.
276
CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS
32-bit MSVC
Let’s also compile it in the 32-bit MSVC compiler:
Listing 18.11: Optimizing MSVC 2013 x86
_month$ = 8
_get_month1 PROC
mov eax, DWORD PTR _month$[esp-4]
mov eax, DWORD PTR _month1[eax*4]
ret 0
_get_month1 ENDP
The input value does not need to be extended to 64-bit value, so it is used as is. And it’s multiplied by 4, because the
table elements are 32-bit (or 4 bytes) wide.
18.5.2 32-bit ARM
ARM in ARM mode
Listing 18.12: Optimizing Keil 6/2013 (ARM mode)
get_month1 PROC
LDR r1,|L0.100|
LDR r0,[r1,r0,LSL #2]
BX lr
ENDP
|L0.100|
DCD ||.data||
DCB "January",0
DCB "February",0
DCB "March",0
DCB "April",0
DCB "May",0
DCB "June",0
DCB "July",0
DCB "August",0
DCB "September",0
DCB "October",0
DCB "November",0
DCB "December",0
AREA ||.data||, DATA, ALIGN=2
month1
DCD ||.conststring||
DCD ||.conststring||+0x8
DCD ||.conststring||+0x11
DCD ||.conststring||+0x17
DCD ||.conststring||+0x1d
DCD ||.conststring||+0x21
DCD ||.conststring||+0x26
DCD ||.conststring||+0x2b
DCD ||.conststring||+0x32
DCD ||.conststring||+0x3c
DCD ||.conststring||+0x44
DCD ||.conststring||+0x4d
The address of the able is loaded in R1. All the rest is done using just one LDR instruction. Then input value month
is shifted left by 2 (which is the same as multiplying by 4), then added to R1 (where the address of the table is) and then a
table element is loaded from this address. The 32-bit table element is loaded into R0 from the table.
ARM in Thumb mode
The code is mostly the same, but less dense, because the LSL suffix cannot be specified in the LDR instruction here:
get_month1 PROC
LSLS r0,r0,#2
LDR r1,|L0.64|
LDR r0,[r1,r0]
277
CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS
BX lr
ENDP
18.5.3 ARM64
Listing 18.13: Optimizing GCC 4.9 ARM64
get_month1:
adrp x1, .LANCHOR0
add x1, x1, :lo12:.LANCHOR0
ldr x0, [x1,w0,sxtw 3]
ret
.LANCHOR0 = . + 0
.type month1, %object
.size month1, 96
month1:
.xword .LC2
.xword .LC3
.xword .LC4
.xword .LC5
.xword .LC6
.xword .LC7
.xword .LC8
.xword .LC9
.xword .LC10
.xword .LC11
.xword .LC12
.xword .LC13
.LC2:
.string "January"
.LC3:
.string "February"
.LC4:
.string "March"
.LC5:
.string "April"
.LC6:
.string "May"
.LC7:
.string "June"
.LC8:
.string "July"
.LC9:
.string "August"
.LC10:
.string "September"
.LC11:
.string "October"
.LC12:
.string "November"
.LC13:
.string "December"
The address of the table is loaded in X1 using ADRP/ADD pair. Then corresponding element is picked using just one LDR,
which takes W0 (the register where input argument month is), shifts it 3 bits to the left (which is the same as multiplying by
8), sign-extends it (this is what “sxtw” suffix implies) and adds to X0. Then the 64-bit value is loaded from the table into X0.
18.5.4 MIPS
Listing 18.14: Optimizing GCC 4.4.5 (IDA)
get_month1:
; load address of table into $v0:
la $v0, month1
; take input value and multiply it by 4:
sll $a0, 2
; sum up address of table and multiplied value:
278
CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS
addu $a0, $v0
; load table element at this address into $v0:
lw $v0, 0($a0)
; return
jr $ra
or $at, $zero ; branch delay slot, NOP
.data # .data.rel.local
.globl month1
month1: .word aJanuary # "January"
.word aFebruary # "February"
.word aMarch # "March"
.word aApril # "April"
.word aMay # "May"
.word aJune # "June"
.word aJuly # "July"
.word aAugust # "August"
.word aSeptember # "September"
.word aOctober # "October"
.word aNovember # "November"
.word aDecember # "December"
.data # .rodata.str1.4
aJanuary: .ascii "January"<0>
aFebruary: .ascii "February"<0>
aMarch: .ascii "March"<0>
aApril: .ascii "April"<0>
aMay: .ascii "May"<0>
aJune: .ascii "June"<0>
aJuly: .ascii "July"<0>
aAugust: .ascii "August"<0>
aSeptember: .ascii "September"<0>
aOctober: .ascii "October"<0>
aNovember: .ascii "November"<0>
aDecember: .ascii "December"<0>
18.5.5 Array overflow
Our function accepts values in the range of 0..11, but what if 12 is passed? There is no element in table at this place. So
the function will load some value which happens to be there, and return it. Soon after, some other function can try to get
a text string from this address and may crash.
I have compiled the example in MSVC for win64 and opened it in IDA to see what the linker has placed after the table:
Listing 18.15: Executable file in IDA
off_140011000 dq offset aJanuary_1 ; DATA XREF: .text:0000000140001003
; "January"
dq offset aFebruary_1 ; "February"
dq offset aMarch_1 ; "March"
dq offset aApril_1 ; "April"
dq offset aMay_1 ; "May"
dq offset aJune_1 ; "June"
dq offset aJuly_1 ; "July"
dq offset aAugust_1 ; "August"
dq offset aSeptember_1 ; "September"
dq offset aOctober_1 ; "October"
dq offset aNovember_1 ; "November"
dq offset aDecember_1 ; "December"
aJanuary_1 db 'January',0 ; DATA XREF: sub_140001020+4
; .data:off_140011000
aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008
align 4
aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010
align 4
aApril_1 db 'April',0 ; DATA XREF: .data:0000000140011018
Month names are came right after. Our program is tiny, so there isn’t much data to pack in the data segment, so it just
the month names. But I have to note that there might be really anything that linker has decided to put by chance.
So what if 12 is passed to the function? The 13th element will be returned. Let’s see how the CPU treating the bytes
there as a 64-bit value:
279
CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS
Listing 18.16: Executable file in IDA
off_140011000 dq offset qword_140011060
; DATA XREF: .text:0000000140001003
dq offset aFebruary_1 ; "February"
dq offset aMarch_1 ; "March"
dq offset aApril_1 ; "April"
dq offset aMay_1 ; "May"
dq offset aJune_1 ; "June"
dq offset aJuly_1 ; "July"
dq offset aAugust_1 ; "August"
dq offset aSeptember_1 ; "September"
dq offset aOctober_1 ; "October"
dq offset aNovember_1 ; "November"
dq offset aDecember_1 ; "December"
qword_140011060 dq 797261756E614Ah ; DATA XREF: sub_140001020+4
; .data:off_140011000
aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008
align 4
aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010
And this is 0x797261756E614A. Soon after, some other function (presumably, one that processes strings) may try to read
bytes at this address, expecting a C-string there. Most likely it is about to crash, because this value does’t look like a valid
address.
Array overflow protection
If something can go wrong, it will
Murphy’s Law
It’s a bit naïve to expect that every programmer who use your function or library will never pass an argument larger than
11.
There exists the philosophy that says “fail early and fail loudly” or “fail-fast”, which teaches to report problems as early
as possible and stop.
One such method in C/C++ is assertions. We can modify our program to fail if an incorrect value is passed:
Listing 18.17: assert() added
const char* get_month1_checked (int month)
{
assert (month<12);
return month1[month];
};
The assertion macro checks for valid values at every function start and fails if the expression is false.
Listing 18.18: Optimizing MSVC 2013 x64
$SG3143 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '.', 00H
DB 'c', 00H, 00H, 00H
$SG3144 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '<', 00H
DB '1', 00H, '2', 00H, 00H, 00H
month$ = 48
get_month1_checked PROC
$LN5:
push rbx
sub rsp, 32
movsxd rbx, ecx
cmp ebx, 12
jl SHORT $LN3@get_month1
lea rdx, OFFSET FLAT:$SG3143
lea rcx, OFFSET FLAT:$SG3144
mov r8d, 29
call _wassert
$LN3@get_month1:
lea rcx, OFFSET FLAT:month1
mov rax, QWORD PTR [rcx+rbx*8]
add rsp, 32
pop rbx
280
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
ret 0
get_month1_checked ENDP
In fact, assert() is not a function, but macro. It checks for a condition, then passes also the line number and file name to
another function which reports this information to the user.
Here we see that both file name and condition are encoded in UTF-16. The line number is also passed (it’s 29).
This mechanism is probably the same in all compilers. Here is what GCC does:
Listing 18.19: Optimizing GCC 4.9 x64
.LC1:
.string "month.c"
.LC2:
.string "month<12"
get_month1_checked:
cmp edi, 11
jg .L6
movsx rdi, edi
mov rax, QWORD PTR month1[0+rdi*8]
ret
.L6:
push rax
mov ecx, OFFSET FLAT:__PRETTY_FUNCTION__.2423
mov edx, 29
mov esi, OFFSET FLAT:.LC1
mov edi, OFFSET FLAT:.LC2
call __assert_fail
__PRETTY_FUNCTION__.2423:
.string "get_month1_checked"
So the macro in GCC also passes the function name for convenience.
Nothing is really free, and this is true for the sanitizing checks as well. They make your program slower, especially if
the assert() macros used in small time-critical functions. So MSVC, for example, leaves the checks in Debug builds, but in
Release builds they all disappear.
Microsoft Windows NT kernels come in “checked” and “free” builds 13
. The first has validation checks (hence, “checked”),
the second one doesn’t (hence, “free” of checks).
18.6 Multidimensional arrays
Internally, a multidimensional array is essentially the same thing as a linear array.
Since the computer memory is linear, it is an one-dimensional array. For convenience, this multi-dimensional array can
be easily represented as one-dimensional.
For example, thit is how the elements of the a[3][4] array are placed in one-dimensional array of 12 cells:
[0][0]
[0][1]
[0][2]
[0][3]
[1][0]
[1][1]
[1][2]
[1][3]
[2][0]
[2][1]
[2][2]
[2][3]
Table 18.1: Two-dimensional array represented in memory as one-dimensional
Here is how each cell of 3*4 array are placed in memory:
13MSDN
281
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
0 1 2 3
4 5 6 7
8 9 10 11
Table 18.2: Memory addresses of each cell of two-dimensional array
So, in order to calculate the address of the element we need, we first multiply the first index by 4 (matrix width) and then
add the second index. That’s called row-major order, and this method of array and matrix representation is used in at least
C/C++ and Python. The term row-major order in plain English language means: “first, write the elements of the first row,
then the second row …and finally the elements of the last row”.
Another method for representation is called column-major order (the array indices are used in reverse order) and it is used
at least in FORTRAN, MATLAB and R. column-major order term in plain English language means: “first, write the elements of
the first column, then the second column …and finally the elements of the last column”.
Which method is better? In general, in terms of performance and cache memory, the best scheme for data organization
is the one, in which the elements are accessed sequentially. So if your function accesses data per row, row-major order is
better, and vice versa.
18.6.1 Two-dimensional array example
We are going to work with an array of type char, which implies that each element requires only one byte in memory.
Row filling example
Let’s fill the second row with these values: 0...3:
Listing 18.20: Row filling example
#include <stdio.h>
char a[3][4];
int main()
{
int x, y;
// clear array
for (x=0; x<3; x++)
for (y=0; y<4; y++)
a[x][y]=0;
// fill second row by 0..3:
for (y=0; y<4; y++)
a[1][y]=y;
};
I have marked all three rows with red. We see that second row now has values 0, 1, 2 and 3:
Figure 18.7: OllyDbg: array is filled
Column filling example
Let’s fill the third column with values: 0...2.
Listing 18.21: Column filling example
#include <stdio.h>
char a[3][4];
int main()
282
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
{
int x, y;
// clear array
for (x=0; x<3; x++)
for (y=0; y<4; y++)
a[x][y]=0;
// fill third column by 0..2:
for (x=0; x<3; x++)
a[x][2]=x;
};
I have also marked the three rows in red here. We see that in each row, at third position these values are written: 0, 1
and 2.
Figure 18.8: OllyDbg: array is filled
18.6.2 Access two-dimensional array as one-dimensional
I can easily show you how to access a two-dimensional array as one-dimensional array in at least two other ways:
#include <stdio.h>
char a[3][4];
char get_by_coordinates1 (char array[3][4], int a, int b)
{
return array[a][b];
};
char get_by_coordinates2 (char *array, int a, int b)
{
// treat input array as one-dimensional
// 4 is array width here
return array[a*4+b];
};
char get_by_coordinates3 (char *array, int a, int b)
{
// treat input array as pointer,
// calculate address, get value at it
// 4 is array width here
return *(array+a*4+b);
};
int main()
{
a[2][3]=123;
printf ("%dn", get_by_coordinates1(a, 2, 3));
printf ("%dn", get_by_coordinates2(a, 2, 3));
printf ("%dn", get_by_coordinates3(a, 2, 3));
};
Compile and run it: it shows correct values.
What MSVC 2013 did is fascinating, all three routines are just the same!
Listing 18.22: Optimizing MSVC 2013 x64
array$ = 8
a$ = 16
b$ = 24
283
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
get_by_coordinates3 PROC
; RCX=address of array
; RDX=a
; R8=b
movsxd rax, r8d
; EAX=b
movsxd r9, edx
; R9=a
add rax, rcx
; RAX=b+address of array
movzx eax, BYTE PTR [rax+r9*4]
; AL=load byte at address RAX+R9*4=b+address of array+a*4=address of array+a*4+b
ret 0
get_by_coordinates3 ENDP
array$ = 8
a$ = 16
b$ = 24
get_by_coordinates2 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
ret 0
get_by_coordinates2 ENDP
array$ = 8
a$ = 16
b$ = 24
get_by_coordinates1 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
ret 0
get_by_coordinates1 ENDP
GCC also generates equivalent routines, but slightly different:
Listing 18.23: Optimizing GCC 4.9 x64
; RDI=address of array
; RSI=a
; RDX=b
get_by_coordinates1:
; sign-extend input 32-bit int values "a" and "b" to 64-bit ones
movsx rsi, esi
movsx rdx, edx
lea rax, [rdi+rsi*4]
; RAX=RDI+RSI*4=address of array+a*4
movzx eax, BYTE PTR [rax+rdx]
; AL=load byte at address RAX+RDX=address of array+a*4+b
ret
get_by_coordinates2:
lea eax, [rdx+rsi*4]
; RAX=RDX+RSI*4=b+a*4
cdqe
movzx eax, BYTE PTR [rdi+rax]
; AL=load byte at address RDI+RAX=address of array+b+a*4
ret
get_by_coordinates3:
sal esi, 2
; ESI=a<<2=a*4
; sign-extend input 32-bit int values "a*4" and "b" to 64-bit ones
movsx rdx, edx
movsx rsi, esi
add rdi, rsi
; RDI=RDI+RSI=address of array+a*4
284
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
movzx eax, BYTE PTR [rdi+rdx]
; AL=load byte at address RDI+RDX=address of array+a*4+b
ret
18.6.3 Three-dimensional array example
It’s thing in multidimensional arrays.
Now we are going to work with an array of type int: each element requires 4 bytes in memory.
Let’s see:
Listing 18.24: simple example
#include <stdio.h>
int a[10][20][30];
void insert(int x, int y, int z, int value)
{
a[x][y][z]=value;
};
x86
We get (MSVC 2010):
Listing 18.25: MSVC 2010
_DATA SEGMENT
COMM _a:DWORD:01770H
_DATA ENDS
PUBLIC _insert
_TEXT SEGMENT
_x$ = 8 ; size = 4
_y$ = 12 ; size = 4
_z$ = 16 ; size = 4
_value$ = 20 ; size = 4
_insert PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _x$[ebp]
imul eax, 2400 ; eax=600*4*x
mov ecx, DWORD PTR _y$[ebp]
imul ecx, 120 ; ecx=30*4*y
lea edx, DWORD PTR _a[eax+ecx] ; edx=a + 600*4*x + 30*4*y
mov eax, DWORD PTR _z$[ebp]
mov ecx, DWORD PTR _value$[ebp]
mov DWORD PTR [edx+eax*4], ecx ; *(edx+z*4)=value
pop ebp
ret 0
_insert ENDP
_TEXT ENDS
Nothing special. For index calculation, three input arguments are used in the formula address = 600⋅4⋅x+30⋅4⋅y +4z,
to represent the array as multidimensional. Do not forget that the int type is 32-bit (4 bytes), so all coefficients must be
multiplied by 4.
Listing 18.26: GCC 4.4.1
public insert
insert proc near
x = dword ptr 8
y = dword ptr 0Ch
z = dword ptr 10h
value = dword ptr 14h
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp+x]
285
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
mov eax, [ebp+y]
mov ecx, [ebp+z]
lea edx, [eax+eax] ; edx=y*2
mov eax, edx ; eax=y*2
shl eax, 4 ; eax=(y*2)<<4 = y*2*16 = y*32
sub eax, edx ; eax=y*32 - y*2=y*30
imul edx, ebx, 600 ; edx=x*600
add eax, edx ; eax=eax+edx=y*30 + x*600
lea edx, [eax+ecx] ; edx=y*30 + x*600 + z
mov eax, [ebp+value]
mov dword ptr ds:a[edx*4], eax ; *(a+edx*4)=value
pop ebx
pop ebp
retn
insert endp
The GCC compiler does it differently. For one of the operations in the calculation (30y), GCC produces code without
multiplication instructions. This is how it done: (y + y) ≪ 4 − (y + y) = (2y) ≪ 4 − 2y = 2 ⋅ 16 ⋅ y − 2y = 32y − 2y = 30y.
Thus, for the 30y calculation, only one addition operation, one bitwise shift operation and one subtraction operation are
used. This works faster.
ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb mode)
Listing 18.27: Non-optimizing Xcode 4.6.3 (LLVM) (thumb mode)
_insert
value = -0x10
z = -0xC
y = -8
x = -4
; allocate place in local stack for 4 values of int type
SUB SP, SP, #0x10
MOV R9, 0xFC2 ; a
ADD R9, PC
LDR.W R9, [R9]
STR R0, [SP,#0x10+x]
STR R1, [SP,#0x10+y]
STR R2, [SP,#0x10+z]
STR R3, [SP,#0x10+value]
LDR R0, [SP,#0x10+value]
LDR R1, [SP,#0x10+z]
LDR R2, [SP,#0x10+y]
LDR R3, [SP,#0x10+x]
MOV R12, 2400
MUL.W R3, R3, R12
ADD R3, R9
MOV R9, 120
MUL.W R2, R2, R9
ADD R2, R3
LSLS R1, R1, #2 ; R1=R1<<2
ADD R1, R2
STR R0, [R1] ; R1 - address of array element
; deallocate chunk in local stack, allocated for 4 values of int type
ADD SP, SP, #0x10
BX LR
Non-optimizing LLVM saves all variables in local stack, which is redundant. The address of the array element is
calculated by the formula we already saw.
ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb mode)
Listing 18.28: Optimizing Xcode 4.6.3 (LLVM) (thumb mode)
_insert
MOVW R9, #0x10FC
MOV.W R12, #2400
MOVT.W R9, #0
286
CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS
RSB.W R1, R1, R1,LSL#4 ; R1 - y. R1=y<<4 - y = y*16 - y = y*15
ADD R9, PC ; R9 = pointer to a array
LDR.W R9, [R9]
MLA.W R0, R0, R12, R9 ; R0 - x, R12 - 2400, R9 - pointer to a. R0=x*2400 + ptr to a
ADD.W R0, R0, R1,LSL#3 ; R0 = R0+R1<<3 = R0+R1*8 = x*2400 + ptr to a + y*15*8 =
; ptr to a + y*30*4 + x*600*4
STR.W R3, [R0,R2,LSL#2] ; R2 - z, R3 - value. address=R0+z*4 =
; ptr to a + y*30*4 + x*600*4 + z*4
BX LR
The tricks for replacing multiplication by shift, addition and subtraction which we already saw are also present here.
Here we also see a new instruction for us: RSB (Reverse Subtract). It works just as SUB, but it swaps its operands with each
other before execution. Why? SUB and RSB are instructions, to the second operand of which shift coefficient may be applied:
(LSL#4). But this coefficient can be applied only to second operand. That’s fine for commutative operations like addition
or multiplication (operands may be swapped there without changing the result). But subtraction is a non-commutative
operation, so RSB exist for these cases.
The ``LDR.W R9, [R9]'' instruction works like LEA ( A.6.2 on page 933) in x86, but it does nothing here, it is
redundant. Apparently, the compiler did not optimize it out.
MIPS
My example is tiny, so the GCC compiler decided to put the a table into the 64KiB area addressable by the Global Pointer.
Listing 18.29: Optimizing GCC 4.4.5 (IDA)
insert:
; $a0=x
; $a1=y
; $a2=z
; $a3=value
sll $v0, $a0, 5
; $v0 = $a0<<5 = x*32
sll $a0, 3
; $a0 = $a0<<3 = x*8
addu $a0, $v0
; $a0 = $a0+$v0 = x*8+x*32 = x*40
sll $v1, $a1, 5
; $v1 = $a1<<5 = y*32
sll $v0, $a0, 4
; $v0 = $a0<<4 = x*40*16 = x*640
sll $a1, 1
; $a1 = $a1<<1 = y*2
subu $a1, $v1, $a1
; $a1 = $v1-$a1 = y*32-y*2 = y*30
subu $a0, $v0, $a0
; $a0 = $v0-$a0 = x*640-x*40 = x*600
la $gp, __gnu_local_gp
addu $a0, $a1, $a0
; $a0 = $a1+$a0 = y*30+x*600
addu $a0, $a2
; $a0 = $a0+$a2 = y*30+x*600+z
; load address of table:
lw $v0, (a & 0xFFFF)($gp)
; multiply index by 4 to seek array element:
sll $a0, 2
; sum up multiplied index and table address:
addu $a0, $v0, $a0
; store value into table and return:
jr $ra
sw $a3, 0($a0)
.comm a:0x1770
18.6.4 More examples
The computer screen is represented as a 2D array, but the video-buffer is a linear 1D array. We talk about it here: 83.2 on
page 824.
287
CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY
18.7 Pack of strings as a two-dimensional array
Let’s revisit the function that returns the name of a month: listing.18.8. As you see, at least one memory load operation is
needed to prepare a pointer to the string that’s the month’s name. Is it possible to get rid of this memory load operation?
In fact yes, if you represent the list of strings as a two-dimensional array:
#include <stdio.h>
#include <assert.h>
const char month2[12][10]=
{
{ 'J','a','n','u','a','r','y', 0, 0, 0 },
{ 'F','e','b','r','u','a','r','y', 0, 0 },
{ 'M','a','r','c','h', 0, 0, 0, 0, 0 },
{ 'A','p','r','i','l', 0, 0, 0, 0, 0 },
{ 'M','a','y', 0, 0, 0, 0, 0, 0, 0 },
{ 'J','u','n','e', 0, 0, 0, 0, 0, 0 },
{ 'J','u','l','y', 0, 0, 0, 0, 0, 0 },
{ 'A','u','g','u','s','t', 0, 0, 0, 0 },
{ 'S','e','p','t','e','m','b','e','r', 0 },
{ 'O','c','t','o','b','e','r', 0, 0, 0 },
{ 'N','o','v','e','m','b','e','r', 0, 0 },
{ 'D','e','c','e','m','b','e','r', 0, 0 }
};
// in 0..11 range
const char* get_month2 (int month)
{
return &month2[month][0];
};
Here is what we’ve get:
Listing 18.30: Optimizing MSVC 2013 x64
month2 DB 04aH
DB 061H
DB 06eH
DB 075H
DB 061H
DB 072H
DB 079H
DB 00H
DB 00H
DB 00H
...
get_month2 PROC
; sign-extend input argument and promote to 64-bit value
movsxd rax, ecx
lea rcx, QWORD PTR [rax+rax*4]
; RCX=month+month*4=month*5
lea rax, OFFSET FLAT:month2
; RAX=pointer to table
lea rax, QWORD PTR [rax+rcx*2]
; RAX=pointer to table + RCX*2=pointer to table + month*5*2=pointer to table + month*10
ret 0
get_month2 ENDP
There are no memory accesses at all. All this function does is to calculate a point at which the first character of the
name of the month is: pointer_to_the_table + month ∗ 10. There are also two LEA instructions, which effectively work as
several MUL and MOV instructions.
The width of the array is 10 bytes. Indeed, the longest string here — “September” — is 9 bytes, and plus the terminating
zero is 10 bytes. The rest of the month names are padded by zero bytes, so they all occupy the same space (10 bytes). Thus,
our function works even faster, because all string start at an address which can be calculated easily.
Optimizing GCC 4.9 can do it even shorter:
Listing 18.31: Optimizing GCC 4.9 x64
movsx rdi, edi
lea rax, [rdi+rdi*4]
288
CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY
lea rax, month2[rax+rax]
ret
LEA is also used here for multiplication by 10.
Non-optimizing compilers do multiplication differently.
Listing 18.32: Non-optimizing GCC 4.9 x64
get_month2:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov eax, DWORD PTR [rbp-4]
movsx rdx, eax
; RDX = sign-extended input value
mov rax, rdx
; RAX = month
sal rax, 2
; RAX = month<<2 = month*4
add rax, rdx
; RAX = RAX+RDX = month*4+month = month*5
add rax, rax
; RAX = RAX*2 = month*5*2 = month*10
add rax, OFFSET FLAT:month2
; RAX = month*10 + pointer to the table
pop rbp
ret
Non-optimizing MSVC just use IMUL instruction:
Listing 18.33: Non-optimizing MSVC 2013 x64
month$ = 8
get_month2 PROC
mov DWORD PTR [rsp+8], ecx
movsxd rax, DWORD PTR month$[rsp]
; RAX = sign-extended input value into 64-bit one
imul rax, rax, 10
; RAX = RAX*10
lea rcx, OFFSET FLAT:month2
; RCX = pointer to the table
add rcx, rax
; RCX = RCX+RAX = pointer to the table+month*10
mov rax, rcx
; RAX = pointer to the table+month*10
mov ecx, 1
; RCX = 1
imul rcx, rcx, 0
; RCX = 1*0 = 0
add rax, rcx
; RAX = pointer to the table+month*10 + 0 = pointer to the table+month*10
ret 0
get_month2 ENDP
… but one thing is weird here: why add multiplication by zero and adding zero to the final result? I don’t know, this
looks like a compiler code generator quirk, which wasn’t caught by the compiler’s tests (the resulting code works correctly,
after all). I intentionally add such pieces of code so the reader would understand, that sometimes one shouldn’t puzzle over
such compiler artifacts.
18.7.1 32-bit ARM
Optimizing Keil for Thumb mode uses the multiplication instruction MULS:
Listing 18.34: Optimizing Keil 6/2013 (thumb mode)
; R0 = month
MOVS r1,#0xa
; R1 = 10
MULS r0,r1,r0
; R0 = R1*R0 = 10*month
LDR r1,|L0.68|
; R1 = pointer to the table
289
CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY
ADDS r0,r0,r1
; R0 = R0+R1 = 10*month + pointer to the table
BX lr
Optimizing Keil for ARM mode uses add and shift operations:
Listing 18.35: Optimizing Keil 6/2013 (ARM mode)
; R0 = month
LDR r1,|L0.104|
; R1 = pointer to the table
ADD r0,r0,r0,LSL #2
; R0 = R0+R0<<2 = R0+R0*4 = month*5
ADD r0,r1,r0,LSL #1
; R0 = R1+R0<<2 = pointer to the table + month*5*2 = pointer to the table + month*10
BX lr
18.7.2 ARM64
Listing 18.36: Optimizing GCC 4.9 ARM64
; W0 = month
sxtw x0, w0
; X0 = sign-extended input value
adrp x1, .LANCHOR1
add x1, x1, :lo12:.LANCHOR1
; X1 = pointer to the table
add x0, x0, x0, lsl 2
; X0 = X0+X0<<2 = X0+X0*4 = X0*5
add x0, x1, x0, lsl 1
; X0 = X1+X0<<1 = X1+X0*2 = pointer to the table + X0*10
ret
SXTW is used for sign-extension and promoting input 32-bit value into a 64-bit one and storing it in X0. ADRP/ADD pair
is used for loading the address of the table. The ADD instructions also has a LSL suffix, which helps with multiplications.
18.7.3 MIPS
Listing 18.37: Optimizing GCC 4.4.5 (IDA)
.globl get_month2
get_month2:
; $a0=month
sll $v0, $a0, 3
; $v0 = $a0<<3 = month*8
sll $a0, 1
; $a0 = $a0<<1 = month*2
addu $a0, $v0
; $a0 = month*2+month*8 = month*10
; load address of the table:
la $v0, month2
; sum up table address and index we calculated and return:
jr $ra
addu $v0, $a0
month2: .ascii "January"<0>
.byte 0, 0
aFebruary: .ascii "February"<0>
.byte 0
aMarch: .ascii "March"<0>
.byte 0, 0, 0, 0
aApril: .ascii "April"<0>
.byte 0, 0, 0, 0
aMay: .ascii "May"<0>
.byte 0, 0, 0, 0, 0, 0
aJune: .ascii "June"<0>
.byte 0, 0, 0, 0, 0
aJuly: .ascii "July"<0>
.byte 0, 0, 0, 0, 0
290
CHAPTER 18. ARRAYS 18.8. CONCLUSION
aAugust: .ascii "August"<0>
.byte 0, 0, 0
aSeptember: .ascii "September"<0>
aOctober: .ascii "October"<0>
.byte 0, 0
aNovember: .ascii "November"<0>
.byte 0
aDecember: .ascii "December"<0>
.byte 0, 0, 0, 0, 0, 0, 0, 0, 0
18.7.4 Conclusion
This is a bit old-school technique to store text strings. You may find a lot of it in Oracle RDBMS, for example. But I don’t
really know if it’s worth doing on modern computers. Nevertheless, it was a good example of arrays, so I added it to this
book.
18.8 Conclusion
An array is a pack of values in memory located adjacently. It’s true for any element type, including structures. Access to a
specific array element is just a calculation of its address.
18.9 Exercises
18.9.1 Exercise #1
What does this code do?
Listing 18.38: MSVC 2010 + /O1
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_c$ = 16 ; size = 4
?s@@YAXPAN00@Z PROC ; s, COMDAT
mov eax, DWORD PTR _b$[esp-4]
mov ecx, DWORD PTR _a$[esp-4]
mov edx, DWORD PTR _c$[esp-4]
push esi
push edi
sub ecx, eax
sub edx, eax
mov edi, 200 ; 000000c8H
$LL6@s:
push 100 ; 00000064H
pop esi
$LL3@s:
fld QWORD PTR [ecx+eax]
fadd QWORD PTR [eax]
fstp QWORD PTR [edx+eax]
add eax, 8
dec esi
jne SHORT $LL3@s
dec edi
jne SHORT $LL6@s
pop edi
pop esi
ret 0
?s@@YAXPAN00@Z ENDP ; s
(/O1: minimize space).
Listing 18.39: Optimizing Keil 6/2013 (ARM mode)
PUSH {r4-r12,lr}
MOV r9,r2
MOV r10,r1
MOV r11,r0
MOV r5,#0
291
CHAPTER 18. ARRAYS 18.9. EXERCISES
|L0.20|
ADD r0,r5,r5,LSL #3
ADD r0,r0,r5,LSL #4
MOV r4,#0
ADD r8,r10,r0,LSL #5
ADD r7,r11,r0,LSL #5
ADD r6,r9,r0,LSL #5
|L0.44|
ADD r0,r8,r4,LSL #3
LDM r0,{r2,r3}
ADD r1,r7,r4,LSL #3
LDM r1,{r0,r1}
BL __aeabi_dadd
ADD r2,r6,r4,LSL #3
ADD r4,r4,#1
STM r2,{r0,r1}
CMP r4,#0x64
BLT |L0.44|
ADD r5,r5,#1
CMP r5,#0xc8
BLT |L0.20|
POP {r4-r12,pc}
Listing 18.40: Optimizing Keil 6/2013 (thumb mode)
PUSH {r0-r2,r4-r7,lr}
MOVS r4,#0
SUB sp,sp,#8
|L0.6|
MOVS r1,#0x19
MOVS r0,r4
LSLS r1,r1,#5
MULS r0,r1,r0
LDR r2,[sp,#8]
LDR r1,[sp,#0xc]
ADDS r2,r0,r2
STR r2,[sp,#0]
LDR r2,[sp,#0x10]
MOVS r5,#0
ADDS r7,r0,r2
ADDS r0,r0,r1
STR r0,[sp,#4]
|L0.32|
LSLS r6,r5,#3
ADDS r0,r0,r6
LDM r0!,{r2,r3}
LDR r0,[sp,#0]
ADDS r1,r0,r6
LDM r1,{r0,r1}
BL __aeabi_dadd
ADDS r2,r7,r6
ADDS r5,r5,#1
STM r2!,{r0,r1}
CMP r5,#0x64
BGE |L0.62|
LDR r0,[sp,#4]
B |L0.32|
|L0.62|
ADDS r4,r4,#1
CMP r4,#0xc8
BLT |L0.6|
ADD sp,sp,#0x14
POP {r4-r7,pc}
Listing 18.41: Non-optimizing GCC 4.9 (ARM64)
s:
sub sp, sp, #48
str x0, [sp,24]
str x1, [sp,16]
292
CHAPTER 18. ARRAYS 18.9. EXERCISES
str x2, [sp,8]
str wzr, [sp,44]
b .L2
.L5:
str wzr, [sp,40]
b .L3
.L4:
ldr w1, [sp,44]
mov w0, 100
mul w0, w1, w0
sxtw x1, w0
ldrsw x0, [sp,40]
add x0, x1, x0
lsl x0, x0, 3
ldr x1, [sp,8]
add x0, x1, x0
ldr w2, [sp,44]
mov w1, 100
mul w1, w2, w1
sxtw x2, w1
ldrsw x1, [sp,40]
add x1, x2, x1
lsl x1, x1, 3
ldr x2, [sp,24]
add x1, x2, x1
ldr x2, [x1]
ldr w3, [sp,44]
mov w1, 100
mul w1, w3, w1
sxtw x3, w1
ldrsw x1, [sp,40]
add x1, x3, x1
lsl x1, x1, 3
ldr x3, [sp,16]
add x1, x3, x1
ldr x1, [x1]
fmov d0, x2
fmov d1, x1
fadd d0, d0, d1
fmov x1, d0
str x1, [x0]
ldr w0, [sp,40]
add w0, w0, 1
str w0, [sp,40]
.L3:
ldr w0, [sp,40]
cmp w0, 99
ble .L4
ldr w0, [sp,44]
add w0, w0, 1
str w0, [sp,44]
.L2:
ldr w0, [sp,44]
cmp w0, 199
ble .L5
add sp, sp, 48
ret
Listing 18.42: Optimizing GCC 4.4.5 (MIPS) (IDA)
sub_0:
li $t3, 0x27100
move $t2, $zero
li $t1, 0x64 # 'd'
loc_10: # CODE XREF: sub_0+54
addu $t0, $a1, $t2
addu $a3, $a2, $t2
move $v1, $a0
move $v0, $zero
293
CHAPTER 18. ARRAYS 18.9. EXERCISES
loc_20: # CODE XREF: sub_0+48
lwc1 $f2, 4($v1)
lwc1 $f0, 4($t0)
lwc1 $f3, 0($v1)
lwc1 $f1, 0($t0)
addiu $v0, 1
add.d $f0, $f2, $f0
addiu $v1, 8
swc1 $f0, 4($a3)
swc1 $f1, 0($a3)
addiu $t0, 8
bne $v0, $t1, loc_20
addiu $a3, 8
addiu $t2, 0x320
bne $t2, $t3, loc_10
addiu $a0, 0x320
jr $ra
or $at, $zero
Answer G.1.10 on page 955.
18.9.2 Exercise #2
What does this code do?
Listing 18.43: MSVC 2010 + /O1
tv315 = -8 ; size = 4
tv291 = -4 ; size = 4
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_c$ = 16 ; size = 4
?m@@YAXPAN00@Z PROC ; m, COMDAT
push ebp
mov ebp, esp
push ecx
push ecx
mov edx, DWORD PTR _a$[ebp]
push ebx
mov ebx, DWORD PTR _c$[ebp]
push esi
mov esi, DWORD PTR _b$[ebp]
sub edx, esi
push edi
sub esi, ebx
mov DWORD PTR tv315[ebp], 100 ; 00000064H
$LL9@m:
mov eax, ebx
mov DWORD PTR tv291[ebp], 300 ; 0000012cH
$LL6@m:
fldz
lea ecx, DWORD PTR [esi+eax]
fstp QWORD PTR [eax]
mov edi, 200 ; 000000c8H
$LL3@m:
dec edi
fld QWORD PTR [ecx+edx]
fmul QWORD PTR [ecx]
fadd QWORD PTR [eax]
fstp QWORD PTR [eax]
jne HORT $LL3@m
add eax, 8
dec DWORD PTR tv291[ebp]
jne SHORT $LL6@m
add ebx, 800 ; 00000320H
dec DWORD PTR tv315[ebp]
jne SHORT $LL9@m
pop edi
pop esi
294
CHAPTER 18. ARRAYS 18.9. EXERCISES
pop ebx
leave
ret 0
?m@@YAXPAN00@Z ENDP ; m
(/O1: minimize space).
Listing 18.44: Optimizing Keil 6/2013 (ARM mode)
PUSH {r0-r2,r4-r11,lr}
SUB sp,sp,#8
MOV r5,#0
|L0.12|
LDR r1,[sp,#0xc]
ADD r0,r5,r5,LSL #3
ADD r0,r0,r5,LSL #4
ADD r1,r1,r0,LSL #5
STR r1,[sp,#0]
LDR r1,[sp,#8]
MOV r4,#0
ADD r11,r1,r0,LSL #5
LDR r1,[sp,#0x10]
ADD r10,r1,r0,LSL #5
|L0.52|
MOV r0,#0
MOV r1,r0
ADD r7,r10,r4,LSL #3
STM r7,{r0,r1}
MOV r6,r0
LDR r0,[sp,#0]
ADD r8,r11,r4,LSL #3
ADD r9,r0,r4,LSL #3
|L0.84|
LDM r9,{r2,r3}
LDM r8,{r0,r1}
BL __aeabi_dmul
LDM r7,{r2,r3}
BL __aeabi_dadd
ADD r6,r6,#1
STM r7,{r0,r1}
CMP r6,#0xc8
BLT |L0.84|
ADD r4,r4,#1
CMP r4,#0x12c
BLT |L0.52|
ADD r5,r5,#1
CMP r5,#0x64
BLT |L0.12|
ADD sp,sp,#0x14
POP {r4-r11,pc}
Listing 18.45: Optimizing Keil 6/2013 (thumb mode)
PUSH {r0-r2,r4-r7,lr}
MOVS r0,#0
SUB sp,sp,#0x10
STR r0,[sp,#0]
|L0.8|
MOVS r1,#0x19
LSLS r1,r1,#5
MULS r0,r1,r0
LDR r2,[sp,#0x10]
LDR r1,[sp,#0x14]
ADDS r2,r0,r2
STR r2,[sp,#4]
LDR r2,[sp,#0x18]
MOVS r5,#0
ADDS r7,r0,r2
ADDS r0,r0,r1
STR r0,[sp,#8]
|L0.32|
295
CHAPTER 18. ARRAYS 18.9. EXERCISES
LSLS r4,r5,#3
MOVS r0,#0
ADDS r2,r7,r4
STR r0,[r2,#0]
MOVS r6,r0
STR r0,[r2,#4]
|L0.44|
LDR r0,[sp,#8]
ADDS r0,r0,r4
LDM r0!,{r2,r3}
LDR r0,[sp,#4]
ADDS r1,r0,r4
LDM r1,{r0,r1}
BL __aeabi_dmul
ADDS r3,r7,r4
LDM r3,{r2,r3}
BL __aeabi_dadd
ADDS r2,r7,r4
ADDS r6,r6,#1
STM r2!,{r0,r1}
CMP r6,#0xc8
BLT |L0.44|
MOVS r0,#0xff
ADDS r5,r5,#1
ADDS r0,r0,#0x2d
CMP r5,r0
BLT |L0.32|
LDR r0,[sp,#0]
ADDS r0,r0,#1
CMP r0,#0x64
STR r0,[sp,#0]
BLT |L0.8|
ADD sp,sp,#0x1c
POP {r4-r7,pc}
Listing 18.46: Non-optimizing GCC 4.9 (ARM64)
m:
sub sp, sp, #48
str x0, [sp,24]
str x1, [sp,16]
str x2, [sp,8]
str wzr, [sp,44]
b .L2
.L7:
str wzr, [sp,40]
b .L3
.L6:
ldr w1, [sp,44]
mov w0, 100
mul w0, w1, w0
sxtw x1, w0
ldrsw x0, [sp,40]
add x0, x1, x0
lsl x0, x0, 3
ldr x1, [sp,8]
add x0, x1, x0
ldr x1, .LC0
str x1, [x0]
str wzr, [sp,36]
b .L4
.L5:
ldr w1, [sp,44]
mov w0, 100
mul w0, w1, w0
sxtw x1, w0
ldrsw x0, [sp,40]
add x0, x1, x0
lsl x0, x0, 3
ldr x1, [sp,8]
296
CHAPTER 18. ARRAYS 18.9. EXERCISES
add x0, x1, x0
ldr w2, [sp,44]
mov w1, 100
mul w1, w2, w1
sxtw x2, w1
ldrsw x1, [sp,40]
add x1, x2, x1
lsl x1, x1, 3
ldr x2, [sp,8]
add x1, x2, x1
ldr x2, [x1]
ldr w3, [sp,44]
mov w1, 100
mul w1, w3, w1
sxtw x3, w1
ldrsw x1, [sp,40]
add x1, x3, x1
lsl x1, x1, 3
ldr x3, [sp,24]
add x1, x3, x1
ldr x3, [x1]
ldr w4, [sp,44]
mov w1, 100
mul w1, w4, w1
sxtw x4, w1
ldrsw x1, [sp,40]
add x1, x4, x1
lsl x1, x1, 3
ldr x4, [sp,16]
add x1, x4, x1
ldr x1, [x1]
fmov d0, x3
fmov d1, x1
fmul d0, d0, d1
fmov x1, d0
fmov d0, x2
fmov d1, x1
fadd d0, d0, d1
fmov x1, d0
str x1, [x0]
ldr w0, [sp,36]
add w0, w0, 1
str w0, [sp,36]
.L4:
ldr w0, [sp,36]
cmp w0, 199
ble .L5
ldr w0, [sp,40]
add w0, w0, 1
str w0, [sp,40]
.L3:
ldr w0, [sp,40]
cmp w0, 299
ble .L6
ldr w0, [sp,44]
add w0, w0, 1
str w0, [sp,44]
.L2:
ldr w0, [sp,44]
cmp w0, 99
ble .L7
add sp, sp, 48
ret
Listing 18.47: Optimizing GCC 4.4.5 (MIPS) (IDA)
m:
li $t5, 0x13880
move $t4, $zero
li $t1, 0xC8
297
CHAPTER 18. ARRAYS 18.9. EXERCISES
li $t3, 0x12C
loc_14: # CODE XREF: m+7C
addu $t0, $a0, $t4
addu $a3, $a1, $t4
move $v1, $a2
move $t2, $zero
loc_24: # CODE XREF: m+70
mtc1 $zero, $f0
move $v0, $zero
mtc1 $zero, $f1
or $at, $zero
swc1 $f0, 4($v1)
swc1 $f1, 0($v1)
loc_3C: # CODE XREF: m+5C
lwc1 $f4, 4($t0)
lwc1 $f2, 4($a3)
lwc1 $f5, 0($t0)
lwc1 $f3, 0($a3)
addiu $v0, 1
mul.d $f2, $f4, $f2
add.d $f0, $f2
swc1 $f0, 4($v1)
bne $v0, $t1, loc_3C
swc1 $f1, 0($v1)
addiu $t2, 1
addiu $v1, 8
addiu $t0, 8
bne $t2, $t3, loc_24
addiu $a3, 8
addiu $t4, 0x320
bne $t4, $t5, loc_14
addiu $a2, 0x320
jr $ra
or $at, $zero
Answer G.1.10 on page 956.
18.9.3 Exercise #3
What does this code do?
Try to determine the dimensions of the array, at least partially.
Listing 18.48: Optimizing MSVC 2010
_array$ = 8
_x$ = 12
_y$ = 16
_f PROC
mov eax, DWORD PTR _x$[esp-4]
mov edx, DWORD PTR _y$[esp-4]
mov ecx, eax
shl ecx, 4
sub ecx, eax
lea eax, DWORD PTR [edx+ecx*8]
mov ecx, DWORD PTR _array$[esp-4]
fld QWORD PTR [ecx+eax*8]
ret 0
_f ENDP
Listing 18.49: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
RSB r1,r1,r1,LSL #4
ADD r0,r0,r1,LSL #6
ADD r1,r0,r2,LSL #3
LDM r1,{r0,r1}
BX lr
ENDP
298
CHAPTER 18. ARRAYS 18.9. EXERCISES
Listing 18.50: Non-optimizing Keil 6/2013 (thumb mode)
f PROC
MOVS r3,#0xf
LSLS r3,r3,#6
MULS r1,r3,r1
ADDS r0,r1,r0
LSLS r1,r2,#3
ADDS r1,r0,r1
LDM r1,{r0,r1}
BX lr
ENDP
Listing 18.51: Optimizing GCC 4.9 (ARM64)
f:
sxtw x1, w1
add x0, x0, x2, sxtw 3
lsl x2, x1, 10
sub x1, x2, x1, lsl 6
ldr d0, [x0,x1]
ret
Listing 18.52: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
sll $v0, $a1, 10
sll $a1, 6
subu $a1, $v0, $a1
addu $a1, $a0, $a1
sll $a2, 3
addu $a1, $a2
lwc1 $f0, 4($a1)
or $at, $zero
lwc1 $f1, 0($a1)
jr $ra
or $at, $zero
Answer G.1.10 on page 956
18.9.4 Exercise #4
What does this code do?
Try to determine the dimensions of the array, at least partially.
Listing 18.53: Optimizing MSVC 2010
_array$ = 8
_x$ = 12
_y$ = 16
_z$ = 20
_f PROC
mov eax, DWORD PTR _x$[esp-4]
mov edx, DWORD PTR _y$[esp-4]
mov ecx, eax
shl ecx, 4
sub ecx, eax
lea eax, DWORD PTR [edx+ecx*4]
mov ecx, DWORD PTR _array$[esp-4]
lea eax, DWORD PTR [eax+eax*4]
shl eax, 4
add eax, DWORD PTR _z$[esp-4]
mov eax, DWORD PTR [ecx+eax*4]
ret 0
_f ENDP
Listing 18.54: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
RSB r1,r1,r1,LSL #4
ADD r1,r1,r1,LSL #2
299
CHAPTER 18. ARRAYS 18.9. EXERCISES
ADD r0,r0,r1,LSL #8
ADD r1,r2,r2,LSL #2
ADD r0,r0,r1,LSL #6
LDR r0,[r0,r3,LSL #2]
BX lr
ENDP
Listing 18.55: Non-optimizing Keil 6/2013 (thumb mode)
f PROC
PUSH {r4,lr}
MOVS r4,#0x4b
LSLS r4,r4,#8
MULS r1,r4,r1
ADDS r0,r1,r0
MOVS r1,#0xff
ADDS r1,r1,#0x41
MULS r2,r1,r2
ADDS r0,r0,r2
LSLS r1,r3,#2
LDR r0,[r0,r1]
POP {r4,pc}
ENDP
Listing 18.56: Optimizing GCC 4.9 (ARM64)
f:
sxtw x2, w2
mov w4, 19200
add x2, x2, x2, lsl 2
smull x1, w1, w4
lsl x2, x2, 4
add x3, x2, x3, sxtw
add x0, x0, x3, lsl 2
ldr w0, [x0,x1]
ret
Listing 18.57: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
sll $v0, $a1, 10
sll $a1, 8
addu $a1, $v0
sll $v0, $a2, 6
sll $a2, 4
addu $a2, $v0
sll $v0, $a1, 4
subu $a1, $v0, $a1
addu $a2, $a3
addu $a1, $a0, $a1
sll $a2, 2
addu $a1, $a2
lw $v0, 0($a1)
jr $ra
or $at, $zero
Answer G.1.10 on page 956
18.9.5 Exercise #5
What does this code do?
Listing 18.58: Optimizing MSVC 2012 /GS-
COMM _tbl:DWORD:064H
tv759 = -4 ; size = 4
_main PROC
push ecx
push ebx
300
CHAPTER 18. ARRAYS 18.9. EXERCISES
push ebp
push esi
xor edx, edx
push edi
xor esi, esi
xor edi, edi
xor ebx, ebx
xor ebp, ebp
mov DWORD PTR tv759[esp+20], edx
mov eax, OFFSET _tbl+4
npad 8 ; align next label
$LL6@main:
lea ecx, DWORD PTR [edx+edx]
mov DWORD PTR [eax+4], ecx
mov ecx, DWORD PTR tv759[esp+20]
add DWORD PTR tv759[esp+20], 3
mov DWORD PTR [eax+8], ecx
lea ecx, DWORD PTR [edx*4]
mov DWORD PTR [eax+12], ecx
lea ecx, DWORD PTR [edx*8]
mov DWORD PTR [eax], edx
mov DWORD PTR [eax+16], ebp
mov DWORD PTR [eax+20], ebx
mov DWORD PTR [eax+24], edi
mov DWORD PTR [eax+32], esi
mov DWORD PTR [eax-4], 0
mov DWORD PTR [eax+28], ecx
add eax, 40
inc edx
add ebp, 5
add ebx, 6
add edi, 7
add esi, 9
cmp eax, OFFSET _tbl+404
jl SHORT $LL6@main
pop edi
pop esi
pop ebp
xor eax, eax
pop ebx
pop ecx
ret 0
_main ENDP
Listing 18.59: Non-optimizing Keil 6/2013 (ARM mode)
main PROC
LDR r12,|L0.60|
MOV r1,#0
|L0.8|
ADD r2,r1,r1,LSL #2
MOV r0,#0
ADD r2,r12,r2,LSL #3
|L0.20|
MUL r3,r1,r0
STR r3,[r2,r0,LSL #2]
ADD r0,r0,#1
CMP r0,#0xa
BLT |L0.20|
ADD r1,r1,#1
CMP r1,#0xa
MOVGE r0,#0
BLT |L0.8|
BX lr
ENDP
|L0.60|
DCD ||.bss||
AREA ||.bss||, DATA, NOINIT, ALIGN=2
301
CHAPTER 18. ARRAYS 18.9. EXERCISES
tbl
% 400
Listing 18.60: Non-optimizing Keil 6/2013 (thumb mode)
main PROC
PUSH {r4,r5,lr}
LDR r4,|L0.40|
MOVS r1,#0
|L0.6|
MOVS r2,#0x28
MULS r2,r1,r2
MOVS r0,#0
ADDS r3,r2,r4
|L0.14|
MOVS r2,r1
MULS r2,r0,r2
LSLS r5,r0,#2
ADDS r0,r0,#1
CMP r0,#0xa
STR r2,[r3,r5]
BLT |L0.14|
ADDS r1,r1,#1
CMP r1,#0xa
BLT |L0.6|
MOVS r0,#0
POP {r4,r5,pc}
ENDP
DCW 0x0000
|L0.40|
DCD ||.bss||
AREA ||.bss||, DATA, NOINIT, ALIGN=2
tbl
% 400
Listing 18.61: Non-optimizing GCC 4.9 (ARM64)
.comm tbl,400,8
main:
sub sp, sp, #16
str wzr, [sp,12]
b .L2
.L5:
str wzr, [sp,8]
b .L3
.L4:
ldr w1, [sp,12]
ldr w0, [sp,8]
mul w3, w1, w0
adrp x0, tbl
add x2, x0, :lo12:tbl
ldrsw x4, [sp,8]
ldrsw x1, [sp,12]
mov x0, x1
lsl x0, x0, 2
add x0, x0, x1
lsl x0, x0, 1
add x0, x0, x4
str w3, [x2,x0,lsl 2]
ldr w0, [sp,8]
add w0, w0, 1
str w0, [sp,8]
.L3:
ldr w0, [sp,8]
cmp w0, 9
ble .L4
302
CHAPTER 18. ARRAYS 18.9. EXERCISES
ldr w0, [sp,12]
add w0, w0, 1
str w0, [sp,12]
.L2:
ldr w0, [sp,12]
cmp w0, 9
ble .L5
mov w0, 0
add sp, sp, 16
ret
Listing 18.62: Non-optimizing GCC 4.4.5 (MIPS) (IDA)
main:
var_18 = -0x18
var_10 = -0x10
var_C = -0xC
var_4 = -4
addiu $sp, -0x18
sw $fp, 0x18+var_4($sp)
move $fp, $sp
la $gp, __gnu_local_gp
sw $gp, 0x18+var_18($sp)
sw $zero, 0x18+var_C($fp)
b loc_A0
or $at, $zero
loc_24: # CODE XREF: main+AC
sw $zero, 0x18+var_10($fp)
b loc_7C
or $at, $zero
loc_30: # CODE XREF: main+88
lw $v0, 0x18+var_C($fp)
lw $a0, 0x18+var_10($fp)
lw $a1, 0x18+var_C($fp)
lw $v1, 0x18+var_10($fp)
or $at, $zero
mult $a1, $v1
mflo $a2
lw $v1, (tbl & 0xFFFF)($gp)
sll $v0, 1
sll $a1, $v0, 2
addu $v0, $a1
addu $v0, $a0
sll $v0, 2
addu $v0, $v1, $v0
sw $a2, 0($v0)
lw $v0, 0x18+var_10($fp)
or $at, $zero
addiu $v0, 1
sw $v0, 0x18+var_10($fp)
loc_7C: # CODE XREF: main+28
lw $v0, 0x18+var_10($fp)
or $at, $zero
slti $v0, 0xA
bnez $v0, loc_30
or $at, $zero
lw $v0, 0x18+var_C($fp)
or $at, $zero
addiu $v0, 1
sw $v0, 0x18+var_C($fp)
loc_A0: # CODE XREF: main+1C
lw $v0, 0x18+var_C($fp)
or $at, $zero
slti $v0, 0xA
303
CHAPTER 18. ARRAYS 18.9. EXERCISES
bnez $v0, loc_24
or $at, $zero
move $v0, $zero
move $sp, $fp
lw $fp, 0x18+var_4($sp)
addiu $sp, 0x18
jr $ra
or $at, $zero
.comm tbl:0x64 # DATA XREF: main+4C
Answer G.1.10 on page 956
304
CHAPTER 19. MANIPULATING SPECIFIC BIT(S)
Chapter 19
Manipulating specific bit(s)
A lot of functions define their input arguments as flags in bit fields. Of course, they could be substituted by a set of bool-typed
variables, but it is not frugally.
19.1 Specific bit checking
19.1.1 x86
Win32 API example:
HANDLE fh;
fh=CreateFile ("file", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS⤦
, FILE_ATTRIBUTE_NORMAL, NULL);
We get (MSVC 2010):
Listing 19.1: MSVC 2010
push 0
push 128 ; 00000080H
push 4
push 0
push 1
push -1073741824 ; c0000000H
push OFFSET $SG78813
call DWORD PTR __imp__CreateFileA@28
mov DWORD PTR _fh$[ebp], eax
Let’s take a look in WinNT.h:
Listing 19.2: WinNT.h
#define GENERIC_READ (0x80000000L)
#define GENERIC_WRITE (0x40000000L)
#define GENERIC_EXECUTE (0x20000000L)
#define GENERIC_ALL (0x10000000L)
Everything is clear, GENERIC_READ | GENERIC_WRITE = 0x80000000 | 0x40000000 = 0xC0000000, and
that value is used as the second argument for the CreateFile()1
function.
How would CreateFile() check these flags?
If we look in KERNEL32.DLL in Windows XP SP3 x86, we’ll find this fragment of code in CreateFileW:
Listing 19.3: KERNEL32.DLL (Windows XP SP3 x86)
.text:7C83D429 test byte ptr [ebp+dwDesiredAccess+3], 40h
.text:7C83D42D mov [ebp+var_8], 1
.text:7C83D434 jz short loc_7C83D417
.text:7C83D436 jmp loc_7C810817
Here we see the TEST instruction, however it doesn’t take the whole second argument, but only the most significant byte
(ebp+dwDesiredAccess+3) and checks it for flag 0x40 (which implies the GENERIC_WRITE flag here)
TEST is basically the same instruction as AND, but without saving the result (recall the fact CMP is merely the same as
SUB, but without saving the result ( 7.3.1 on page 74)).
The logic of this code fragment is as follows:
1MSDN: CreateFile function
305
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.1. SPECIFIC BIT CHECKING
if ((dwDesiredAccess&0x40000000) == 0) goto loc_7C83D417
If AND instruction leaves this bit, the ZF flag is to be cleared and the JZ conditional jump is not to be triggered. The
conditional jump is triggered only if the 0x40000000 bit is absent in dwDesiredAccess variable —then the result of
AND is 0, ZF is to be set and the conditional jump is to be triggered.
Let’s try GCC 4.4.1 and Linux:
#include <stdio.h>
#include <fcntl.h>
void main()
{
int handle;
handle=open ("file", O_RDWR | O_CREAT);
};
We get:
Listing 19.4: GCC 4.4.1
public main
main proc near
var_20 = dword ptr -20h
var_1C = dword ptr -1Ch
var_4 = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 20h
mov [esp+20h+var_1C], 42h
mov [esp+20h+var_20], offset aFile ; "file"
call _open
mov [esp+20h+var_4], eax
leave
retn
main endp
If we take a look in the open() function in the libc.so.6 library, it is only a syscall:
Listing 19.5: open() (libc.so.6)
.text:000BE69B mov edx, [esp+4+mode] ; mode
.text:000BE69F mov ecx, [esp+4+flags] ; flags
.text:000BE6A3 mov ebx, [esp+4+filename] ; filename
.text:000BE6A7 mov eax, 5
.text:000BE6AC int 80h ; LINUX - sys_open
So, the bit fields for open() are apparently checked somewhere in the Linux kernel.
Of course, it is easy to download both Glibc and the Linux kernel source code, but we are interested in understanding the
matter without it.
So, as of Linux 2.6, when the sys_open syscall is called, control eventually passes to do_sys_open, and from there —to
the do_filp_open() function (it’s located in the kernel source tree in fs/namei.c).
N.B. Aside from passing arguments via the stack, there is also a method of passing some of them via registers. This is
also called fastcall ( 64.3 on page 664). This works faster since CPU does not need to access the stack in memory to read
argument values. GCC has the option regparm2
, through which it’s possible to set the number of arguments that can be
passed via registers.
The Linux 2.6 kernel is compiled with -mregparm=3 option 3 4
.
What this means to us is that the first 3 arguments are to be passed via registers EAX, EDX and ECX, and the rest via the
stack. Of course, if the number of arguments is less than 3, only part of registers set is to be used.
So, let’s download Linux Kernel 2.6.31, compile it in Ubuntu: make vmlinux, open it in IDA, and find the do_filp_open()
function. At the beginning, we see (the comments are mine):
Listing 19.6: do_filp_open() (linux kernel 2.6.31)
2http://go.yurichev.com/17040
3http://go.yurichev.com/17066
4See also archx86includeasmcalling.h file in kernel tree
306
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.1. SPECIFIC BIT CHECKING
do_filp_open proc near
...
push ebp
mov ebp, esp
push edi
push esi
push ebx
mov ebx, ecx
add ebx, 1
sub esp, 98h
mov esi, [ebp+arg_4] ; acc_mode (5th arg)
test bl, 3
mov [ebp+var_80], eax ; dfd (1th arg)
mov [ebp+var_7C], edx ; pathname (2th arg)
mov [ebp+var_78], ecx ; open_flag (3th arg)
jnz short loc_C01EF684
mov ebx, ecx ; ebx <- open_flag
GCC saves the values of the first 3 arguments in the local stack. If that wasn’t done, the compiler would not touch these
registers, and that would be too tight environment for the compiler’s register allocator.
Let’s find this fragment of code:
Listing 19.7: do_filp_open() (linux kernel 2.6.31)
loc_C01EF6B4: ; CODE XREF: do_filp_open+4F
test bl, 40h ; O_CREAT
jnz loc_C01EF810
mov edi, ebx
shr edi, 11h
xor edi, 1
and edi, 1
test ebx, 10000h
jz short loc_C01EF6D3
or edi, 2
0x40 —is what the O_CREAT macro equals to. open_flag gets checked for the presence of the 0x40 bit, and if this
bit is 1, the next JNZ instruction is triggered.
19.1.2 ARM
The O_CREAT bit is checked differently in Linux kernel 3.8.0.
Listing 19.8: linux kernel 3.8.0
struct file *do_filp_open(int dfd, struct filename *pathname,
const struct open_flags *op)
{
...
filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
...
}
static struct file *path_openat(int dfd, struct filename *pathname,
struct nameidata *nd, const struct open_flags *op, int flags)
{
...
error = do_last(nd, &path, file, op, &opened, pathname);
...
}
static int do_last(struct nameidata *nd, struct path *path,
struct file *file, const struct open_flags *op,
int *opened, struct filename *name)
{
...
if (!(open_flag & O_CREAT)) {
...
error = lookup_fast(nd, path, &inode);
...
} else {
307
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
...
error = complete_walk(nd);
}
...
}
Here is how the kernel compiled for ARM mode looks in IDA:
Listing 19.9: do_last() (vmlinux)
...
.text:C0169EA8 MOV R9, R3 ; R3 - (4th argument) open_flag
...
.text:C0169ED4 LDR R6, [R9] ; R6 - open_flag
...
.text:C0169F68 TST R6, #0x40 ; jumptable C0169F00 default case
.text:C0169F6C BNE loc_C016A128
.text:C0169F70 LDR R2, [R4,#0x10]
.text:C0169F74 ADD R12, R4, #8
.text:C0169F78 LDR R3, [R4,#0xC]
.text:C0169F7C MOV R0, R4
.text:C0169F80 STR R12, [R11,#var_50]
.text:C0169F84 LDRB R3, [R2,R3]
.text:C0169F88 MOV R2, R8
.text:C0169F8C CMP R3, #0
.text:C0169F90 ORRNE R1, R1, #3
.text:C0169F94 STRNE R1, [R4,#0x24]
.text:C0169F98 ANDS R3, R6, #0x200000
.text:C0169F9C MOV R1, R12
.text:C0169FA0 LDRNE R3, [R4,#0x24]
.text:C0169FA4 ANDNE R3, R3, #1
.text:C0169FA8 EORNE R3, R3, #1
.text:C0169FAC STR R3, [R11,#var_54]
.text:C0169FB0 SUB R3, R11, #-var_38
.text:C0169FB4 BL lookup_fast
...
.text:C016A128 loc_C016A128 ; CODE XREF: do_last.isra.14+DC
.text:C016A128 MOV R0, R4
.text:C016A12C BL complete_walk
...
TST is analogous to the TEST instruction in x86.
We can “spot” visually this code fragment by the fact the lookup_fast() is to be executed in one case and com-
plete_walk() in the other. This corresponds to the source code of the do_last() function.
The O_CREAT macro equals to 0x40 here too.
19.2 Specific bit setting/clearing
For example:
#include <stdio.h>
#define IS_SET(flag, bit) ((flag) & (bit))
#define SET_BIT(var, bit) ((var) |= (bit))
#define REMOVE_BIT(var, bit) ((var) &= ~(bit))
int f(int a)
{
int rt=a;
SET_BIT (rt, 0x4000);
REMOVE_BIT (rt, 0x200);
return rt;
};
int main()
{
f(0x12340678);
};
308
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
19.2.1 x86
Non-optimizing MSVC
We get (MSVC 2010):
Listing 19.10: MSVC 2010
_rt$ = -4 ; size = 4
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _a$[ebp]
mov DWORD PTR _rt$[ebp], eax
mov ecx, DWORD PTR _rt$[ebp]
or ecx, 16384 ; 00004000H
mov DWORD PTR _rt$[ebp], ecx
mov edx, DWORD PTR _rt$[ebp]
and edx, -513 ; fffffdffH
mov DWORD PTR _rt$[ebp], edx
mov eax, DWORD PTR _rt$[ebp]
mov esp, ebp
pop ebp
ret 0
_f ENDP
The OR instruction adds one more bit to value while ignoring the rest.
AND resets one bit. It can be said that AND just copies all bits except one. Indeed, in the second AND operand only the
bits that need to be saved are set, just the one do not want to copy is not (which is 0 in the bitmask). It is the easier way to
memorize the logic.
309
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
OllyDbg
Let’s try this example in OllyDbg. First, let’s see the binary form of the constants we are going to use:
0x200 (00000000000000000001000000000) (i.e., the 10th bit (counting from 1st)).
Inverted 0x200 is 0xFFFFFDFF (11111111111111111110111111111).
0x4000 (00000000000000100000000000000) (i.e., the 15th bit).
The input value is: 0x12340678 (10010001101000000011001111000). We see how it’s loaded:
Figure 19.1: OllyDbg: value is loaded into ECX
310
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
OR got executed:
Figure 19.2: OllyDbg: OR executed
15th bit is set: 0x12344678 (10010001101000100011001111000).
311
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
The value is reloaded again (because the compiler is not in optimizing mode):
Figure 19.3: OllyDbg: value was reloaded into EDX
312
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
AND got executed:
Figure 19.4: OllyDbg: AND executed
The 10th bit was cleared (or, in other words, all bits were left except the 10th) and the final value now is
0x12344478 (10010001101000100010001111000).
Optimizing MSVC
If we compile it in MSVC with optimization turned on (/Ox), the code is even shorter:
Listing 19.11: Optimizing MSVC
_a$ = 8 ; size = 4
_f PROC
mov eax, DWORD PTR _a$[esp-4]
and eax, -513 ; fffffdffH
or eax, 16384 ; 00004000H
ret 0
_f ENDP
Non-optimizing GCC
Let’s try GCC 4.4.1 without optimization:
Listing 19.12: Non-optimizing GCC
public f
f proc near
var_4 = dword ptr -4
arg_0 = dword ptr 8
push ebp
mov ebp, esp
sub esp, 10h
mov eax, [ebp+arg_0]
mov [ebp+var_4], eax
or [ebp+var_4], 4000h
and [ebp+var_4], 0FFFFFDFFh
mov eax, [ebp+var_4]
leave
retn
f endp
There is a redundant code present, however, it is shorter than the MSVC version without optimization.
Now let’s try GCC with optimization turned on -O3:
313
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
Optimizing GCC
Listing 19.13: Optimizing GCC
public f
f proc near
arg_0 = dword ptr 8
push ebp
mov ebp, esp
mov eax, [ebp+arg_0]
pop ebp
or ah, 40h
and ah, 0FDh
retn
f endp
That’s shorter. It is worth noting the compiler works with the EAX register part via the AH register —that is the EAX
register part from the 8th to the 15th bits included.
7th (byte number)
6th 5th 4th 3rd 2nd 1st 0th
RAXx64
EAX
AX
AH AL
N.B. The 16-bit CPU 8086 accumulator was named AX and consisted of two 8-bit halves —AL (lower byte) and AH
(higher byte). In 80386 almost all registers were extended to 32-bit, the accumulator was named EAX, but for the sake of
compatibility, its older parts may be still accessed as AX/AH/AL.
Since all x86 CPUs are successors of the 16-bit 8086 CPU, these older 16-bit opcodes are shorter than the newer 32-bit
ones. That’s why the ``or ah, 40h'' instruction occupies only 3 bytes. It would be more logical way to emit here ``or
eax, 04000h'' but that is 5 bytes, or even 6 (in case the register in the first operand is not EAX).
Optimizing GCC and regparm
It would be even shorter if to turn on the -O3 optimization flag and also set regparm=3.
Listing 19.14: Optimizing GCC
public f
f proc near
push ebp
or ah, 40h
mov ebp, esp
and ah, 0FDh
pop ebp
retn
f endp
Indeed —the first argument is already loaded in EAX, so it is possible to work with it in-place. It is worth noting that both
the function prologue (``push ebp / mov ebp,esp'') and epilogue (``pop ebp'') can easily be omitted here, but
GCC probably is not good enough to do such code size optimizations. However, such short functions are better to be inlined
functions ( 43 on page 500).
19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode)
Listing 19.15: Optimizing Keil 6/2013 (ARM mode)
02 0C C0 E3 BIC R0, R0, #0x200
01 09 80 E3 ORR R0, R0, #0x4000
1E FF 2F E1 BX LR
BIC (BItwise bit Clear) is an instruction for clearing specific bits. This is just like the AND instruction, but with inverted
operand. I.e., it’s analogous to a NOT+AND instruction pair.
ORR is “logical or”, analogous to OR in x86.
So far it’s easy.
314
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING
19.2.3 ARM + Optimizing Keil 6/2013 (thumb mode)
Listing 19.16: Optimizing Keil 6/2013 (thumb mode)
01 21 89 03 MOVS R1, 0x4000
08 43 ORRS R0, R1
49 11 ASRS R1, R1, #5 ; generate 0x200 and place to R1
88 43 BICS R0, R1
70 47 BX LR
Seems like Keil decided that the code in thumb mode, making 0x200 from 0x4000, is more compact than the code for
writing 0x200 to an arbitrary register.
So that is why, with the help of ASRS (arithmetic shift right), this value is calculated as 0x4000 ≫ 5.
19.2.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Listing 19.17: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
42 0C C0 E3 BIC R0, R0, #0x4200
01 09 80 E3 ORR R0, R0, #0x4000
1E FF 2F E1 BX LR
The code that was generated by LLVM, in source code form could be something like this:
REMOVE_BIT (rt, 0x4200);
SET_BIT (rt, 0x4000);
And it does exactly what we need. But why 0x4200? Perhaps, that an artifact from LLVM’s optimizer 5
. Probably a
compiler’s optimizer error, but the generated code works correctly anyway.
You can read more about compiler anomalies here ( 91 on page 870).
Optimizing Xcode 4.6.3 (LLVM) for thumb mode generates the same code.
19.2.5 ARM: more about the BIC instruction
Let’s rework the example slightly:
int f(int a)
{
int rt=a;
REMOVE_BIT (rt, 0x1234);
return rt;
};
Then the optimizing Keil 5.03 in ARM mode does:
f PROC
BIC r0,r0,#0x1000
BIC r0,r0,#0x234
BX lr
ENDP
There are two BIC instructions, i.e., bit 0x1234 are cleared in two passes. This is because it’s not possible to encode
0x1234 in a BIC instruction, but it’s possible to encode 0x1000 and 0x234.
19.2.6 ARM64: Optimizing GCC (Linaro) 4.9
Optimizing GCC compiling for ARM64 can use the AND instruction instead of BIC:
Listing 19.18: Optimizing GCC (Linaro) 4.9
f:
and w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF
orr w0, w0, 16384 ; 0x4000
ret
5It was LLVM build 2410.2.00 bundled with Apple Xcode 4.6.3
315
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.3. SHIFTS
19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9
Non-optimizing GCC generates more redundant code, but works just like optimized:
Listing 19.19: Non-optimizing GCC (Linaro) 4.9
f:
sub sp, sp, #32
str w0, [sp,12]
ldr w0, [sp,12]
str w0, [sp,28]
ldr w0, [sp,28]
orr w0, w0, 16384 ; 0x4000
str w0, [sp,28]
ldr w0, [sp,28]
and w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF
str w0, [sp,28]
ldr w0, [sp,28]
add sp, sp, 32
ret
19.2.8 MIPS
Listing 19.20: Optimizing GCC 4.4.5 (IDA)
f:
; $a0=a
ori $a0, 0x4000
; $a0=a|0x4000
li $v0, 0xFFFFFDFF
jr $ra
and $v0, $a0, $v0
; at finish: $v0 = $a0&$v0 = a|0x4000 & 0xFFFFFDFF
ORI is,of course, the OR operation. “I” in the instruction name mean that the value is embedded in the machine code.
But after that we have AND. There was no way to use ANDI because it’s not possible to embed the 0xFFFFFDFF number
in a single instruction, so the compiler has to load 0xFFFFFDFF into register $V0 first and then generate AND which takes
all its values from registers.
19.3 Shifts
Bit shifts in C/C++ are implemented using ≪ and ≫ operators.
The x86 ISA has the SHL (SHift Left) and SHR (SHift Right) instructions for this.
Shift instructions are often used in division and multiplications by powers of two: 2n
(e.g., 1, 2, 4, 8, etc): 16.1.2 on
page 201, 16.2.1 on page 205.
Shifting operations are also so important because they are often used for specific bit isolation or for constructing a value
of several scattered bits.
19.4 Specific bit setting/clearing: FPU example
Here is how bits are located in the float type in IEEE 754 form:
022233031
S exponent mantissa or fraction
( S—sign )
The sign of number is in the MSB6
. Will it be possible to change the sign of a floating point number without any FPU
instructions?
6Most significant bit/byte
316
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE
#include <stdio.h>
float my_abs (float i)
{
unsigned int tmp=(*(unsigned int*)&i) & 0x7FFFFFFF;
return *(float*)&tmp;
};
float set_sign (float i)
{
unsigned int tmp=(*(unsigned int*)&i) | 0x80000000;
return *(float*)&tmp;
};
float negate (float i)
{
unsigned int tmp=(*(unsigned int*)&i) ^ 0x80000000;
return *(float*)&tmp;
};
int main()
{
printf ("my_abs():n");
printf ("%fn", my_abs (123.456));
printf ("%fn", my_abs (-456.123));
printf ("set_sign():n");
printf ("%fn", set_sign (123.456));
printf ("%fn", set_sign (-456.123));
printf ("negate():n");
printf ("%fn", negate (123.456));
printf ("%fn", negate (-456.123));
};
We need this trickery in C/C++ to copy to/from float value without actual conversion. So there are three functions:
my_abs() resets MSB; set_sign() sets MSB and negate() flips it.
19.4.1 A word about the XOR operation
XOR is widely used when one need just to flip specific bit(s). Indeed, the XOR operation applied with 1 is effectively inverting
a bit:
input A input B output
0 0 0
0 1 1
1 0 1
1 1 0
And on the contrary, the XOR operation applied with 0 does nothing, i.e., it’s an idle operation. This is a very important
property of the XOR operation and it’s highly recommended to memorize it.
19.4.2 x86
The code is pretty straightforward:
Listing 19.21: Optimizing MSVC 2012
_tmp$ = 8
_i$ = 8
_my_abs PROC
and DWORD PTR _i$[esp-4], 2147483647 ; 7fffffffH
fld DWORD PTR _tmp$[esp-4]
ret 0
_my_abs ENDP
_tmp$ = 8
_i$ = 8
_set_sign PROC
or DWORD PTR _i$[esp-4], -2147483648 ; 80000000H
fld DWORD PTR _tmp$[esp-4]
317
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE
ret 0
_set_sign ENDP
_tmp$ = 8
_i$ = 8
_negate PROC
xor DWORD PTR _i$[esp-4], -2147483648 ; 80000000H
fld DWORD PTR _tmp$[esp-4]
ret 0
_negate ENDP
An input value of type float is taken from the stack, but treated as an integer value.
AND and OR reset and set the desired bit. XOR flips it.
Finally, the modified value is loaded into ST0, because floating-point numbers are returned in this register.
Now let’s try optimizing MSVC 2012 for x64:
Listing 19.22: Optimizing MSVC 2012 x64
tmp$ = 8
i$ = 8
my_abs PROC
movss DWORD PTR [rsp+8], xmm0
mov eax, DWORD PTR i$[rsp]
btr eax, 31
mov DWORD PTR tmp$[rsp], eax
movss xmm0, DWORD PTR tmp$[rsp]
ret 0
my_abs ENDP
_TEXT ENDS
tmp$ = 8
i$ = 8
set_sign PROC
movss DWORD PTR [rsp+8], xmm0
mov eax, DWORD PTR i$[rsp]
bts eax, 31
mov DWORD PTR tmp$[rsp], eax
movss xmm0, DWORD PTR tmp$[rsp]
ret 0
set_sign ENDP
tmp$ = 8
i$ = 8
negate PROC
movss DWORD PTR [rsp+8], xmm0
mov eax, DWORD PTR i$[rsp]
btc eax, 31
mov DWORD PTR tmp$[rsp], eax
movss xmm0, DWORD PTR tmp$[rsp]
ret 0
negate ENDP
The input value is passed in XMM0, then it is copied into the local stack and then we see some instructions that are new
to us: BTR, BTS, BTC.
These instructions are used for resetting (BTR), setting (BTS) and inverting (or complementing: BTC) specific bits. The
31st bit is MSB, counting from 0.
Finally, the result is copied into XMM0, because floating point values are returned through XMM0 in Win64 environment.
19.4.3 MIPS
GCC 4.4.5 for MIPS does mostly the same:
Listing 19.23: Optimizing GCC 4.4.5 (IDA)
my_abs:
; move from coprocessor 1:
mfc1 $v1, $f12
li $v0, 0x7FFFFFFF
; $v0=0x7FFFFFFF
; do AND:
and $v0, $v1
318
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE
; move to coprocessor 1:
mtc1 $v0, $f0
; return
jr $ra
or $at, $zero ; branch delay slot
set_sign:
; move from coprocessor 1:
mfc1 $v0, $f12
lui $v1, 0x8000
; $v1=0x80000000
; do OR:
or $v0, $v1, $v0
; move to coprocessor 1:
mtc1 $v0, $f0
; return
jr $ra
or $at, $zero ; branch delay slot
negate:
; move from coprocessor 1:
mfc1 $v0, $f12
lui $v1, 0x8000
; $v1=0x80000000
; do XOR:
xor $v0, $v1, $v0
; move to coprocessor 1:
mtc1 $v0, $f0
; return
jr $ra
or $at, $zero ; branch delay slot
One single LUI instruction is used to load 0x80000000 into a register, because LUI is clearing the low 16 bits and these
are zeroes in the constant, so one LUI without subsequent ORI is enough.
19.4.4 ARM
Optimizing Keil 6/2013 (ARM mode)
Listing 19.24: Optimizing Keil 6/2013 (ARM mode)
my_abs PROC
; clear bit:
BIC r0,r0,#0x80000000
BX lr
ENDP
set_sign PROC
; do OR:
ORR r0,r0,#0x80000000
BX lr
ENDP
negate PROC
; do XOR:
EOR r0,r0,#0x80000000
BX lr
ENDP
So far so good. ARM has the BIC instruction, which explicitly clears specific bit(s). EOR is the ARM instruction name for
XOR (“Exclusive OR”).
Optimizing Keil 6/2013 (thumb mode)
Listing 19.25: Optimizing Keil 6/2013 (thumb mode)
my_abs PROC
LSLS r0,r0,#1
; r0=i<<1
319
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE
LSRS r0,r0,#1
; r0=(i<<1)>>1
BX lr
ENDP
set_sign PROC
MOVS r1,#1
; r1=1
LSLS r1,r1,#31
; r1=1<<31=0x80000000
ORRS r0,r0,r1
; r0=r0 | 0x80000000
BX lr
ENDP
negate PROC
MOVS r1,#1
; r1=1
LSLS r1,r1,#31
; r1=1<<31=0x80000000
EORS r0,r0,r1
; r0=r0 ^ 0x80000000
BX lr
ENDP
Thumb mode in ARM offers 16-bit instructions and not much data can be encoded in them, so here a MOVS/LSLS instruc-
tion pair is used for forming the 0x80000000 constant. It works like this: 1 << 31 = 0x80000000.
The code of my_abs is weird and it effectively works like this expression: (i << 1) >> 1. This statement looks meaningless.
But nevertheless, when input << 1 is executed, the MSB (sign bit) is just dropped. When the subsequent result >> 1
statement is executed, all bits are now in their own places, but MSB is zero, because all “new” bits appearing from the shift
operations are always zeroes. That is how the LSLS/LSRS instruction pair clears MSB.
Optimizing GCC 4.6.3 (Raspberry Pi, ARM mode)
Listing 19.26: Optimizing GCC 4.6.3 for Raspberry Pi (ARM mode)
my_abs
; copy from S0 to R2:
FMRS R2, S0
; clear bit:
BIC R3, R2, #0x80000000
; copy from R3 to S0:
FMSR S0, R3
BX LR
set_sign
; copy from S0 to R2:
FMRS R2, S0
; do OR:
ORR R3, R2, #0x80000000
; copy from R3 to S0:
FMSR S0, R3
BX LR
negate
; copy from S0 to R2:
FMRS R2, S0
; do ADD:
ADD R3, R2, #0x80000000
; copy from R3 to S0:
FMSR S0, R3
BX LR
I run Raspberry Pi Linux in QEMU and it emulates an ARM FPU, so S-registers are used here for floating point numbers
instead of R-registers.
The FMRS instruction copies data from GPR to the FPU and back.
my_abs() and set_sign() looks as expected, but negate()? Why is there ADD instead of XOR?
It’s hard to believe, but the instruction “ADD register, 0x80000000” works just like “XOR register, 0x80000000”. First
of all, what’s our goal? The goal is to flip the MSB, so let’s forget about the XOR operation. From school-level math-
320
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
ematics we may remember that adding values like 1000 to other values never affects the last 3 digits. For example:
1234567 + 10000 = 1244567 ( last 4 digits are never affected). But here we operate in binary base and 0x80000000 is
100000000000000000000000000000000, i.e., only the highest bit is set. Adding 0x80000000 to any value never affects
the lowest 31 bits, but affects only the MSB. Adding 1 to 0 is resulting in 1. Adding 1 to 1 is resulting in 10 in binary form,
but the 32th bit (counting from zero) gets dropped, because our registers are 32 bit wide, so the result is 0. That’s why XOR
can be replaced by ADD here. I’m not sure why GCC decided to do this, but it works correctly.
19.5 Counting bits set to 1
Here is a simple example of a function that calculates the number of bits set in the input value.
This operation is also called “population count” 7
.
#include <stdio.h>
#define IS_SET(flag, bit) ((flag) & (bit))
int f(unsigned int a)
{
int i;
int rt=0;
for (i=0; i<32; i++)
if (IS_SET (a, 1<<i))
rt++;
return rt;
};
int main()
{
f(0x12345678); // test
};
In this loop, the iteration count value i is counting from 0 to 31, so the 1 ≪ i statement is counting from 1 to 0x80000000.
Describing this operation in natural language, we would say shift 1 by n bits left. In other words, 1 ≪ i statement consequently
produces all possible bit positions in a 32-bit number. The freed bit at right is always cleared.
Here is a table of all possible 1 ≪ i for i = 0...31:
7modern x86 CPUs (supporting SSE4) even have a POPCNT instruction for it
321
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
C/C++ expression Power of two Decimal form Hexadecimal form
1 ≪ 0 1 1 1
1 ≪ 1 21
2 2
1 ≪ 2 22
4 4
1 ≪ 3 23
8 8
1 ≪ 4 24
16 0x10
1 ≪ 5 25
32 0x20
1 ≪ 6 26
64 0x40
1 ≪ 7 27
128 0x80
1 ≪ 8 28
256 0x100
1 ≪ 9 29
512 0x200
1 ≪ 10 210
1024 0x400
1 ≪ 11 211
2048 0x800
1 ≪ 12 212
4096 0x1000
1 ≪ 13 213
8192 0x2000
1 ≪ 14 214
16384 0x4000
1 ≪ 15 215
32768 0x8000
1 ≪ 16 216
65536 0x10000
1 ≪ 17 217
131072 0x20000
1 ≪ 18 218
262144 0x40000
1 ≪ 19 219
524288 0x80000
1 ≪ 20 220
1048576 0x100000
1 ≪ 21 221
2097152 0x200000
1 ≪ 22 222
4194304 0x400000
1 ≪ 23 223
8388608 0x800000
1 ≪ 24 224
16777216 0x1000000
1 ≪ 25 225
33554432 0x2000000
1 ≪ 26 226
67108864 0x4000000
1 ≪ 27 227
134217728 0x8000000
1 ≪ 28 228
268435456 0x10000000
1 ≪ 29 229
536870912 0x20000000
1 ≪ 30 230
1073741824 0x40000000
1 ≪ 31 231
2147483648 0x80000000
These constant numbers (bit masks) very often appear in code and a practicing reverse engineer must be able to spot
them quickly. You probably haven’t to memorize the decimal numbers, but the hexadecimal ones are very easy to remember.
These constants are very often used for mapping flags to specific bits. For example, here is excerpt from ssl_private.h
from Apache 2.4.6 source code:
/**
* Define the SSL options
*/
#define SSL_OPT_NONE (0)
#define SSL_OPT_RELSET (1<<0)
#define SSL_OPT_STDENVVARS (1<<1)
#define SSL_OPT_EXPORTCERTDATA (1<<3)
#define SSL_OPT_FAKEBASICAUTH (1<<4)
#define SSL_OPT_STRICTREQUIRE (1<<5)
#define SSL_OPT_OPTRENEGOTIATE (1<<6)
#define SSL_OPT_LEGACYDNFORMAT (1<<7)
Let’s get back to our example.
The IS_SET macro checks bit presence in a.
The IS_SET macro is in fact the logical AND operation (AND) and it returns 0 if the specific bit is absent there, or the bit
mask, if the bit is present. The if() operator in C/C++ triggers if the expression in it is not zero, it might be even 123456, that
is why it always works correctly.
19.5.1 x86
MSVC
Let’s compile (MSVC 2010):
Listing 19.27: MSVC 2010
_rt$ = -8 ; size = 4
322
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
_i$ = -4 ; size = 4
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
sub esp, 8
mov DWORD PTR _rt$[ebp], 0
mov DWORD PTR _i$[ebp], 0
jmp SHORT $LN4@f
$LN3@f:
mov eax, DWORD PTR _i$[ebp] ; increment of i
add eax, 1
mov DWORD PTR _i$[ebp], eax
$LN4@f:
cmp DWORD PTR _i$[ebp], 32 ; 00000020H
jge SHORT $LN2@f ; loop finished?
mov edx, 1
mov ecx, DWORD PTR _i$[ebp]
shl edx, cl ; EDX=EDX<<CL
and edx, DWORD PTR _a$[ebp]
je SHORT $LN1@f ; result of AND instruction was 0?
; then skip next instructions
mov eax, DWORD PTR _rt$[ebp] ; no, not zero
add eax, 1 ; increment rt
mov DWORD PTR _rt$[ebp], eax
$LN1@f:
jmp SHORT $LN3@f
$LN2@f:
mov eax, DWORD PTR _rt$[ebp]
mov esp, ebp
pop ebp
ret 0
_f ENDP
323
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
OllyDbg
Let’s load this example into OllyDbg. Let the input value be 0x12345678.
For i = 1, we see how i is loaded into ECX:
Figure 19.5: OllyDbg: i = 1, i is loaded into ECX
EDX is 1. SHL is to be executed now.
324
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
SHL was executed:
Figure 19.6: OllyDbg: i = 1, EDX =1 ≪ 1 = 2
EDX contain 1 ≪ 1 (or 2). This is a bit mask.
325
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
AND sets ZF to 1, which implies that the input value (0x12345678) ANDed with 2 results in 0:
Figure 19.7: OllyDbg: i = 1, is there that bit in the input value? No. (ZF =1)
So, there is no corresponding bit in the input value. The piece of code, which increments the counter is not to be
executed: the JZ instruction bypassing it.
326
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
I traced a bit further and i is now 4. SHL is to be executed now:
Figure 19.8: OllyDbg: i = 4, i is loaded into ECX
327
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
EDX =1 ≪ 4 (or 0x10 or 16):
Figure 19.9: OllyDbg: i = 4, EDX =1 ≪ 4 = 0x10
This is another bit mask.
328
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
AND is executed:
Figure 19.10: OllyDbg: i = 4, is there that bit in the input value? Yes. (ZF =0)
ZF is 0 because this bit is present in the input value. Indeed, 0x12345678 & 0x10 = 0x10. This bit counts: the
jump is not triggering and the bit counter incrementing.
The function returns 13. This is total number of bits set in 0x12345678.
GCC
Let’s compile it in GCC 4.4.1:
Listing 19.28: GCC 4.4.1
public f
f proc near
rt = dword ptr -0Ch
i = dword ptr -8
arg_0 = dword ptr 8
push ebp
mov ebp, esp
push ebx
sub esp, 10h
mov [ebp+rt], 0
mov [ebp+i], 0
jmp short loc_80483EF
loc_80483D0:
mov eax, [ebp+i]
mov edx, 1
mov ebx, edx
mov ecx, eax
shl ebx, cl
mov eax, ebx
and eax, [ebp+arg_0]
test eax, eax
jz short loc_80483EB
add [ebp+rt], 1
loc_80483EB:
add [ebp+i], 1
loc_80483EF:
cmp [ebp+i], 1Fh
jle short loc_80483D0
mov eax, [ebp+rt]
add esp, 10h
pop ebx
pop ebp
retn
329
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
f endp
19.5.2 x64
I modified the example slightly to extend it to 64-bit:
#include <stdio.h>
#include <stdint.h>
#define IS_SET(flag, bit) ((flag) & (bit))
int f(uint64_t a)
{
uint64_t i;
int rt=0;
for (i=0; i<64; i++)
if (IS_SET (a, 1ULL<<i))
rt++;
return rt;
};
Non-optimizing GCC 4.8.2
So far so easy.
Listing 19.29: Non-optimizing GCC 4.8.2
f:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-24], rdi ; a
mov DWORD PTR [rbp-12], 0 ; rt=0
mov QWORD PTR [rbp-8], 0 ; i=0
jmp .L2
.L4:
mov rax, QWORD PTR [rbp-8]
mov rdx, QWORD PTR [rbp-24]
; RAX = i, RDX = a
mov ecx, eax
; ECX = i
shr rdx, cl
; RDX = RDX>>CL = a>>i
mov rax, rdx
; RAX = RDX = a>>i
and eax, 1
; EAX = EAX&1 = (a>>i)&1
test rax, rax
; the last bit is zero?
; skip the next ADD instruction, if it was so.
je .L3
add DWORD PTR [rbp-12], 1 ; rt++
.L3:
add QWORD PTR [rbp-8], 1 ; i++
.L2:
cmp QWORD PTR [rbp-8], 63 ; i<63?
jbe .L4 ; jump to the loop body begin, if so
mov eax, DWORD PTR [rbp-12] ; return rt
pop rbp
ret
Optimizing GCC 4.8.2
Listing 19.30: Optimizing GCC 4.8.2
1 f:
330
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
2 xor eax, eax ; rt variable will be in EAX register
3 xor ecx, ecx ; i variable will be in ECX register
4 .L3:
5 mov rsi, rdi ; load input value
6 lea edx, [rax+1] ; EDX=EAX+1
7 ; EDX here is a "new version of rt", which will be written into rt variable, if the last bit is 1
8 shr rsi, cl ; RSI=RSI>>CL
9 and esi, 1 ; ESI=ESI&1
10 ; the last bit is 1? If so, write "new version of rt" into EAX
11 cmovne eax, edx
12 add rcx, 1 ; RCX++
13 cmp rcx, 64
14 jne .L3
15 rep ret ; AKA fatret
This code is terser, but has a quirk. In all examples that we see so far, we were incrementing the “rt” value after comparing
a specific bit, but the code here increments “rt” before (line 6), writing the new value into register EDX. Thus, if the last bit is
1, the CMOVNE 8
instruction (which is a synonym for CMOVNZ 9
) commits the new value of “rt” by moving EDX (“proposed rt
value”) into EAX (“current rt” to be returned at the end). Hence, the incrementing is done at each step of loop, i.e., 64 times,
without any relation to the input value.
The advantage of this code is that it contain only one conditional jump (at the end of the loop) instead of two jumps
(skipping the “rt” value increment and at the end of loop). And that might work faster on the modern CPUs with branch
predictors: 33.1 on page 456.
The last instruction is REP RET (opcode F3 C3) which is also called FATRET by MSVC. This is somewhat optimized
version of RET, which is recommended by AMD to be placed at the end of function, if RET goes right after conditional jump:
[AMD13b, p.15] 10
.
Optimizing MSVC 2010
Listing 19.31: MSVC 2010
a$ = 8
f PROC
; RCX = input value
xor eax, eax
mov edx, 1
lea r8d, QWORD PTR [rax+64]
; R8D=64
npad 5
$LL4@f:
test rdx, rcx
; there are no such bit in input value?
; skip the next INC instruction then.
je SHORT $LN3@f
inc eax ; rt++
$LN3@f:
rol rdx, 1 ; RDX=RDX<<1
dec r8 ; R8--
jne SHORT $LL4@f
fatret 0
f ENDP
Here the ROL instruction is used instead of SHL, which is in fact “rotate left” instead of “shift left”, but in this example it
works just as SHL.
You can read more about the rotate instruction here: A.6.3 on page 939.
R8 here is counting from 64 to 0. It’s just like an inverted i.
Here is a table of some registers during the execution:
8Conditional MOVe if Not Equal
9Conditional MOVe if Not Zero
10More information on it: http://go.yurichev.com/17328
331
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
RDX R8
0x0000000000000001 64
0x0000000000000002 63
0x0000000000000004 62
0x0000000000000008 61
... ...
0x4000000000000000 2
0x8000000000000000 1
At the end we see the FATRET instruction, which was explained here: 19.5.2 on page 331.
Optimizing MSVC 2012
Listing 19.32: MSVC 2012
a$ = 8
f PROC
; RCX = input value
xor eax, eax
mov edx, 1
lea r8d, QWORD PTR [rax+32]
; EDX = 1, R8D = 32
npad 5
$LL4@f:
; pass 1 ------------------------------------
test rdx, rcx
je SHORT $LN3@f
inc eax ; rt++
$LN3@f:
rol rdx, 1 ; RDX=RDX<<1
; -------------------------------------------
; pass 2 ------------------------------------
test rdx, rcx
je SHORT $LN11@f
inc eax ; rt++
$LN11@f:
rol rdx, 1 ; RDX=RDX<<1
; -------------------------------------------
dec r8 ; R8--
jne SHORT $LL4@f
fatret 0
f ENDP
Optimizing MSVC 2012 does almost the same job as optimizing MSVC 2010, but somehow, it generates two identical
loop bodies and the loop count is now 32 instead of 64. To be honest, I don’t know why. Some optimization trick? Maybe
it’s better for the loop body to be slightly longer? Anyway, I have added the code here intentionally to show that sometimes
the compiler output may be really weird and illogical, but perfectly working.
19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
Listing 19.33: Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
MOV R1, R0
MOV R0, #0
MOV R2, #1
MOV R3, R0
loc_2E54
TST R1, R2,LSL R3 ; set flags according to R1 & (R2<<R3)
ADD R3, R3, #1 ; R3++
ADDNE R0, R0, #1 ; if ZF flag is cleared by TST, then R0++
CMP R3, #32
BNE loc_2E54
BX LR
TST is the same things as TEST in x86.
As I mentioned before ( 41.2.1 on page 489), there are no separate shifting instructions in ARM mode. However, there
are modifiers LSL (Logical Shift Left), LSR (Logical Shift Right), ASR (Arithmetic Shift Right), ROR (Rotate Right) and RRX (Rotate
Right with Extend) , which may be added to such instructions as MOV, TST, CMP, ADD, SUB, RSB11
.
11These instructions are also called “data processing instructions”
332
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
These modificators define how to shift the second operand and by how many bits.
Thus the ``TST R1, R2,LSL R3'' instruction works here as R1 ∧ (R2 ≪ R3).
19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
Almost the same, but here are two LSL.W/TST instructions are used instead of a single TST, because in thumb mode it is
not possible to define LSL modifier directly in TST.
MOV R1, R0
MOVS R0, #0
MOV.W R9, #1
MOVS R3, #0
loc_2F7A
LSL.W R2, R9, R3
TST R2, R1
ADD.W R3, R3, #1
IT NE
ADDNE R0, #1
CMP R3, #32
BNE loc_2F7A
BX LR
19.5.5 ARM64 + Optimizing GCC 4.9
I took the 64-bit example I already used: 19.5.2 on page 330.
Listing 19.34: Optimizing GCC (Linaro) 4.8
f:
mov w2, 0 ; rt=0
mov x5, 1
mov w1, w2
.L2:
lsl x4, x5, x1 ; w4 = w5<<w1 = 1<<i
add w3, w2, 1 ; new_rt=rt+1
tst x4, x0 ; (1<<i) & a
add w1, w1, 1 ; i++
; result of TST was non-zero?
; then w2=w3 or rt=new_rt.
; otherwise: w2=w2 or rt=rt (idle operation)
csel w2, w3, w2, ne
cmp w1, 64 ; i<64?
bne .L2 ; yes
mov w0, w2 ; return rt
ret
The result is very similar to what GCC generates for x64: 19.30 on page 330.
The CSEL instruction is “Conditional SELect”, it just choose one variable of two depending on the flags set by TST and
copies the value into W2 , which holds the “rt” variable.
19.5.6 ARM64 + Non-optimizing GCC 4.9
And again, the 64-bit example I already used: 19.5.2 on page 330.
The code is more verbose, as usual.
Listing 19.35: Non-optimizing GCC (Linaro) 4.8
f:
sub sp, sp, #32
str x0, [sp,8] ; store "a" value to Register Save Area
str wzr, [sp,24] ; rt=0
str wzr, [sp,28] ; i=0
b .L2
.L4:
ldr w0, [sp,28]
mov x1, 1
lsl x0, x1, x0 ; X0 = X1<<X0 = 1<<i
mov x1, x0
; X1 = 1<<1
333
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
ldr x0, [sp,8]
; X0 = a
and x0, x1, x0
; X0 = X1&X0 = (1<<i) & a
; X0 contain zero? then jump to .L3, skipping "rt" increment
cmp x0, xzr
beq .L3
; rt++
ldr w0, [sp,24]
add w0, w0, 1
str w0, [sp,24]
.L3:
; i++
ldr w0, [sp,28]
add w0, w0, 1
str w0, [sp,28]
.L2:
; i<=63? then jump to .L4
ldr w0, [sp,28]
cmp w0, 63
ble .L4
; return rt
ldr w0, [sp,24]
add sp, sp, 32
ret
19.5.7 MIPS
Non-optimizing GCC
Listing 19.36: Non-optimizing GCC 4.4.5 (IDA)
f:
; IDA is not aware of variable names, I gave them manually:
rt = -0x10
i = -0xC
var_4 = -4
a = 0
addiu $sp, -0x18
sw $fp, 0x18+var_4($sp)
move $fp, $sp
sw $a0, 0x18+a($fp)
; initialize rt and i variables to zero:
sw $zero, 0x18+rt($fp)
sw $zero, 0x18+i($fp)
; jump to loop check instructions:
b loc_68
or $at, $zero ; branch delay slot, NOP
loc_20:
li $v1, 1
lw $v0, 0x18+i($fp)
or $at, $zero ; load delay slot, NOP
sllv $v0, $v1, $v0
; $v0 = 1<<i
move $v1, $v0
lw $v0, 0x18+a($fp)
or $at, $zero ; load delay slot, NOP
and $v0, $v1, $v0
; $v0 = a&(1<<i)
; is a&(1<<i) equals to zero? jump to loc_58 then:
beqz $v0, loc_58
or $at, $zero
; no jump occurred, that means a&(1<<i)!=0, so increment "rt" then:
lw $v0, 0x18+rt($fp)
or $at, $zero ; load delay slot, NOP
addiu $v0, 1
sw $v0, 0x18+rt($fp)
334
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1
loc_58:
; increment i:
lw $v0, 0x18+i($fp)
or $at, $zero ; load delay slot, NOP
addiu $v0, 1
sw $v0, 0x18+i($fp)
loc_68:
; load i and compare it with 0x20 (32).
; jump to loc_20 if it is less then 0x20 (32):
lw $v0, 0x18+i($fp)
or $at, $zero ; load delay slot, NOP
slti $v0, 0x20 # ' '
bnez $v0, loc_20
or $at, $zero ; branch delay slot, NOP
; function epilogue. return rt:
lw $v0, 0x18+rt($fp)
move $sp, $fp ; load delay slot
lw $fp, 0x18+var_4($sp)
addiu $sp, 0x18 ; load delay slot
jr $ra
or $at, $zero ; branch delay slot, NOP
That is verbose: all local variables are located in the local stack and reloaded each time they’re needed. The SLLV
instruction is “Shift Word Left Logical Variable”, it differs from SLL only in that the shift amount is encoded in the SLL
instruction (and is fixed, as a consequence), but SLLV takes shift amount from a register.
Optimizing GCC
That is terser. There are two shift instructions instead of one. Why? It’s possible to replace the first SLLV instruction with
an unconditional branch instruction that jumps right to the second SLLV. But this is another branching instruction in the
function, and it’s always favorable to get rid of them: 33.1 on page 456.
Listing 19.37: Optimizing GCC 4.4.5 (IDA)
f:
; $a0=a
; rt variable will reside in $v0:
move $v0, $zero
; i variable will reside in $v1:
move $v1, $zero
li $t0, 1
li $a3, 32
sllv $a1, $t0, $v1
; $a1 = $t0<<$v1 = 1<<i
loc_14:
and $a1, $a0
; $a1 = a&(1<<i)
; increment i:
addiu $v1, 1
; jump to loc_28 if a&(1<<i)==0 and increment rt:
beqz $a1, loc_28
addiu $a2, $v0, 1
; if BEQZ was not triggered, save updated rt into $v0:
move $v0, $a2
loc_28:
; if i!=32, jump to loc_14 and also prepare next shifted value:
bne $v1, $a3, loc_14
sllv $a1, $t0, $v1
; return
jr $ra
or $at, $zero ; branch delay slot, NOP
335
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.6. CONCLUSION
19.6 Conclusion
Analogous to the C/C++ shifting operators ≪ and ≫, the shift instructions in x86 are SHR/SHL (for unsigned values) and
SAR/SHL (for signed values).
The shift instructions in ARM are LSR/LSL (for unsigned values) and ASR/LSL (for signed values). It’s also possible to
add shift suffix to some instructions (which are called “data processing instructions”).
19.6.1 Check for specific bit (known at compile stage)
Test if the 1000000 bit (0x40) is present in the register’s value:
Listing 19.38: C/C++
if (input&0x40)
...
Listing 19.39: x86
TEST REG, 40h
JNZ is_set
; bit is not set
Listing 19.40: x86
TEST REG, 40h
JZ is_cleared
; bit is set
Listing 19.41: ARM (ARM mode)
TST REG, #0x40
BNE is_set
; bit is not set
Sometimes, AND is used instead of TEST, but the flags that are set are the same.
19.6.2 Check for specific bit (specified at runtime)
This is usually done by this C/C++ code snippet (shift value by n bits right, then cut off lowest bit):
Listing 19.42: C/C++
if ((value>>n)&1)
....
This is usually implemented in x86 code as:
Listing 19.43: x86
; REG=input_value
; CL=n
SHR REG, CL
AND REG, 1
Or (shift 1 bit n times left, isolate this bit in input value and check if it’s not zero):
Listing 19.44: C/C++
if (value & (1<<n))
....
This is usually implemented in x86 code as:
Listing 19.45: x86
; CL=n
MOV REG, 1
SHL REG, CL
AND input_value, REG
336
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.6. CONCLUSION
19.6.3 Set specific bit (known at compile stage)
Listing 19.46: C/C++
value=value|0x40;
Listing 19.47: x86
OR REG, 40h
Listing 19.48: ARM (ARM mode) and ARM64
ORR R0, R0, #0x40
19.6.4 Set specific bit (specified at runtime)
Listing 19.49: C/C++
value=value|(1<<n);
This is usually implemented in x86 code as:
Listing 19.50: x86
; CL=n
MOV REG, 1
SHL REG, CL
OR input_value, REG
19.6.5 Clear specific bit (known at compile stage)
Just apply AND operation with the inverted value:
Listing 19.51: C/C++
value=value&(~0x40);
Listing 19.52: x86
AND REG, 0FFFFFFBFh
Listing 19.53: x64
AND REG, 0FFFFFFFFFFFFFFBFh
This is actually leaving all bits set except one.
ARM in ARM mode has BIC instruction, which works like the NOT+AND instruction pair:
Listing 19.54: ARM (ARM mode)
BIC R0, R0, #0x40
19.6.6 Clear specific bit (specified at runtime)
Listing 19.55: C/C++
value=value&(~(1<<n));
Listing 19.56: x86
; CL=n
MOV REG, 1
SHL REG, CL
NOT REG
AND input_value, REG
337
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
19.7 Exercises
19.7.1 Exercise #1
What does this code do?
Listing 19.57: Optimizing MSVC 2010
_a$ = 8
_f PROC
mov ecx, DWORD PTR _a$[esp-4]
mov eax, ecx
mov edx, ecx
shl edx, 16 ; 00000010H
and eax, 65280 ; 0000ff00H
or eax, edx
mov edx, ecx
and edx, 16711680 ; 00ff0000H
shr ecx, 16 ; 00000010H
or edx, ecx
shl eax, 8
shr edx, 8
or eax, edx
ret 0
_f ENDP
Listing 19.58: Optimizing Keil 6/2013 (ARM mode)
f PROC
MOV r1,#0xff0000
AND r1,r1,r0,LSL #8
MOV r2,#0xff00
ORR r1,r1,r0,LSR #24
AND r2,r2,r0,LSR #8
ORR r1,r1,r2
ORR r0,r1,r0,LSL #24
BX lr
ENDP
Listing 19.59: Optimizing Keil 6/2013 (thumb mode)
f PROC
MOVS r3,#0xff
LSLS r2,r0,#8
LSLS r3,r3,#16
ANDS r2,r2,r3
LSRS r1,r0,#24
ORRS r1,r1,r2
LSRS r2,r0,#8
ASRS r3,r3,#8
ANDS r2,r2,r3
ORRS r1,r1,r2
LSLS r0,r0,#24
ORRS r0,r0,r1
BX lr
ENDP
Listing 19.60: Optimizing GCC 4.9 (ARM64)
f:
rev w0, w0
ret
Listing 19.61: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
srl $v0, $a0, 24
sll $v1, $a0, 24
sll $a1, $a0, 8
or $v1, $v0
338
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
lui $v0, 0xFF
and $v0, $a1, $v0
srl $a0, 8
or $v0, $v1, $v0
andi $a0, 0xFF00
jr $ra
or $v0, $a0
Answer: G.1.11 on page 956.
19.7.2 Exercise #2
What does this code do?
Listing 19.62: Optimizing MSVC 2010
_a$ = 8 ; size = 4
_f PROC
push esi
mov esi, DWORD PTR _a$[esp]
xor ecx, ecx
push edi
lea edx, DWORD PTR [ecx+1]
xor eax, eax
npad 3 ; align next label
$LL3@f:
mov edi, esi
shr edi, cl
add ecx, 4
and edi, 15
imul edi, edx
lea edx, DWORD PTR [edx+edx*4]
add eax, edi
add edx, edx
cmp ecx, 28
jle SHORT $LL3@f
pop edi
pop esi
ret 0
_f ENDP
Listing 19.63: Optimizing Keil 6/2013 (ARM mode)
f PROC
MOV r3,r0
MOV r1,#0
MOV r2,#1
MOV r0,r1
|L0.16|
LSR r12,r3,r1
AND r12,r12,#0xf
MLA r0,r12,r2,r0
ADD r1,r1,#4
ADD r2,r2,r2,LSL #2
CMP r1,#0x1c
LSL r2,r2,#1
BLE |L0.16|
BX lr
ENDP
Listing 19.64: Optimizing Keil 6/2013 (thumb mode)
f PROC
PUSH {r4,lr}
MOVS r3,r0
MOVS r1,#0
MOVS r2,#1
MOVS r0,r1
|L0.10|
MOVS r4,r3
339
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
LSRS r4,r4,r1
LSLS r4,r4,#28
LSRS r4,r4,#28
MULS r4,r2,r4
ADDS r0,r4,r0
MOVS r4,#0xa
MULS r2,r4,r2
ADDS r1,r1,#4
CMP r1,#0x1c
BLE |L0.10|
POP {r4,pc}
ENDP
Listing 19.65: Non-optimizing GCC 4.9 (ARM64)
f:
sub sp, sp, #32
str w0, [sp,12]
str wzr, [sp,28]
mov w0, 1
str w0, [sp,24]
str wzr, [sp,20]
b .L2
.L3:
ldr w0, [sp,28]
ldr w1, [sp,12]
lsr w0, w1, w0
and w1, w0, 15
ldr w0, [sp,24]
mul w0, w1, w0
ldr w1, [sp,20]
add w0, w1, w0
str w0, [sp,20]
ldr w0, [sp,28]
add w0, w0, 4
str w0, [sp,28]
ldr w1, [sp,24]
mov w0, w1
lsl w0, w0, 2
add w0, w0, w1
lsl w0, w0, 1
str w0, [sp,24]
.L2:
ldr w0, [sp,28]
cmp w0, 28
ble .L3
ldr w0, [sp,20]
add sp, sp, 32
ret
Listing 19.66: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
srl $v0, $a0, 8
srl $a3, $a0, 20
andi $a3, 0xF
andi $v0, 0xF
srl $a1, $a0, 12
srl $a2, $a0, 16
andi $a1, 0xF
andi $a2, 0xF
sll $t2, $v0, 4
sll $v1, $a3, 2
sll $t0, $v0, 2
srl $t1, $a0, 4
sll $t5, $a3, 7
addu $t0, $t2
subu $t5, $v1
andi $t1, 0xF
srl $v1, $a0, 28
340
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
sll $t4, $a1, 7
sll $t2, $a2, 2
sll $t3, $a1, 2
sll $t7, $a2, 7
srl $v0, $a0, 24
addu $a3, $t5, $a3
subu $t3, $t4, $t3
subu $t7, $t2
andi $v0, 0xF
sll $t5, $t1, 3
sll $t6, $v1, 8
sll $t2, $t0, 2
sll $t4, $t1, 1
sll $t1, $v1, 3
addu $a2, $t7, $a2
subu $t1, $t6, $t1
addu $t2, $t0, $t2
addu $t4, $t5
addu $a1, $t3, $a1
sll $t5, $a3, 2
sll $t3, $v0, 8
sll $t0, $v0, 3
addu $a3, $t5
subu $t0, $t3, $t0
addu $t4, $t2, $t4
sll $t3, $a2, 2
sll $t2, $t1, 6
sll $a1, 3
addu $a1, $t4, $a1
subu $t1, $t2, $t1
addu $a2, $t3
sll $t2, $t0, 6
sll $t3, $a3, 2
andi $a0, 0xF
addu $v1, $t1, $v1
addu $a0, $a1
addu $a3, $t3
subu $t0, $t2, $t0
sll $a2, 4
addu $a2, $a0, $a2
addu $v0, $t0, $v0
sll $a1, $v1, 2
sll $a3, 5
addu $a3, $a2, $a3
addu $v1, $a1
sll $v0, 6
addu $v0, $a3, $v0
sll $v1, 7
jr $ra
addu $v0, $v1, $v0
Answer: G.1.11 on page 957.
19.7.3 Exercise #3
Using the MSDN12
documentation, find out which flags were used in the MessageBox() win32 function call.
Listing 19.67: Optimizing MSVC 2010
_main PROC
push 278595 ; 00044043H
push OFFSET $SG79792 ; 'caption'
push OFFSET $SG79793 ; 'hello, world!'
push 0
call DWORD PTR __imp__MessageBoxA@16
xor eax, eax
ret 0
_main ENDP
12Microsoft Developer Network
341
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
Answer: G.1.11 on page 957.
19.7.4 Exercise #4
What does this code do?
Listing 19.68: Optimizing MSVC 2010
_m$ = 8 ; size = 4
_n$ = 12 ; size = 4
_f PROC
mov ecx, DWORD PTR _n$[esp-4]
xor eax, eax
xor edx, edx
test ecx, ecx
je SHORT $LN2@f
push esi
mov esi, DWORD PTR _m$[esp]
$LL3@f:
test cl, 1
je SHORT $LN1@f
add eax, esi
adc edx, 0
$LN1@f:
add esi, esi
shr ecx, 1
jne SHORT $LL3@f
pop esi
$LN2@f:
ret 0
_f ENDP
Listing 19.69: Optimizing Keil 6/2013 (ARM mode)
f PROC
PUSH {r4,lr}
MOV r3,r0
MOV r0,#0
MOV r2,r0
MOV r12,r0
B |L0.48|
|L0.24|
TST r1,#1
BEQ |L0.40|
ADDS r0,r0,r3
ADC r2,r2,r12
|L0.40|
LSL r3,r3,#1
LSR r1,r1,#1
|L0.48|
CMP r1,#0
MOVEQ r1,r2
BNE |L0.24|
POP {r4,pc}
ENDP
Listing 19.70: Optimizing Keil 6/2013 (thumb mode)
f PROC
PUSH {r4,r5,lr}
MOVS r3,r0
MOVS r0,#0
MOVS r2,r0
MOVS r4,r0
B |L0.24|
|L0.12|
LSLS r5,r1,#31
BEQ |L0.20|
ADDS r0,r0,r3
ADCS r2,r2,r4
342
CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES
|L0.20|
LSLS r3,r3,#1
LSRS r1,r1,#1
|L0.24|
CMP r1,#0
BNE |L0.12|
MOVS r1,r2
POP {r4,r5,pc}
ENDP
Listing 19.71: Optimizing GCC 4.9 (ARM64)
f:
mov w2, w0
mov x0, 0
cbz w1, .L2
.L3:
and w3, w1, 1
lsr w1, w1, 1
cmp w3, wzr
add x3, x0, x2, uxtw
lsl w2, w2, 1
csel x0, x3, x0, ne
cbnz w1, .L3
.L2:
ret
Listing 19.72: Optimizing GCC 4.4.5 (MIPS) (IDA)
mult:
beqz $a1, loc_40
move $a3, $zero
move $a2, $zero
addu $t0, $a3, $a0
loc_10: # CODE XREF: mult+38
sltu $t1, $t0, $a3
move $v1, $t0
andi $t0, $a1, 1
addu $t1, $a2
beqz $t0, loc_30
srl $a1, 1
move $a3, $v1
move $a2, $t1
loc_30: # CODE XREF: mult+20
beqz $a1, loc_44
sll $a0, 1
b loc_10
addu $t0, $a3, $a0
loc_40: # CODE XREF: mult
move $a2, $zero
loc_44: # CODE XREF: mult:loc_30
move $v0, $a2
jr $ra
move $v1, $a3
Answer: G.1.11 on page 957.
343
CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR
Chapter 20
Linear congruential generator as pseudorandom
number generator
The linear congruential generator is probably the simplest possible way to generate random numbers. It’s not in favour in
modern times1
, but it’s so simple (just one multiplication, one addition and one AND operation), we can use it as an example.
#include <stdint.h>
// constants from the Numerical Recipes book
#define RNG_a 1664525
#define RNG_c 1013904223
static uint32_t rand_state;
void my_srand (uint32_t init)
{
rand_state=init;
}
int my_rand ()
{
rand_state=rand_state*RNG_a;
rand_state=rand_state+RNG_c;
return rand_state & 0x7fff;
}
There are two functions: the first one is used to initialize the internal state, and the second one is called to generate
pseudorandom numbers.
We see that two constants are used in the algorithm. They are taken from [Pre+07]. I defined them using a #define
C/C++ statement. It’s a macro. The difference between a C/C++ macro and a constant is that all macros are replaced with
their value by C/C++ preprocessor, and they don’t take any memory, unlike variables. In contrast, a constant is a read-only
variable. It’s possible to take a pointer (or address) of a constant variable, but impossible to do so with a macro.
The last AND operation is needed because by C-standard, my_rand() has to return a value in the 0..32767 range. If
you want to get 32-bit pseudorandom values, just omit the last AND operation.
20.1 x86
Listing 20.1: Optimizing MSVC 2013
_BSS SEGMENT
_rand_state DD 01H DUP (?)
_BSS ENDS
_init$ = 8
_srand PROC
mov eax, DWORD PTR _init$[esp-4]
mov DWORD PTR _rand_state, eax
ret 0
_srand ENDP
_TEXT SEGMENT
1Mersenne twister is better
344
CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.2. X64
_rand PROC
imul eax, DWORD PTR _rand_state, 1664525
add eax, 1013904223 ; 3c6ef35fH
mov DWORD PTR _rand_state, eax
and eax, 32767 ; 00007fffH
ret 0
_rand ENDP
_TEXT ENDS
Here we see it: both constants are embedded into the code. There is no memory allocated for them. The my_srand()
function just copies its input value into the internal rand_state variable.
my_rand() takes it, calculates the next rand_state, cuts it and leaves it in the EAX register.
The non-optimized version is more verbose:
Listing 20.2: Non-optimizing MSVC 2013
_BSS SEGMENT
_rand_state DD 01H DUP (?)
_BSS ENDS
_init$ = 8
_srand PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _init$[ebp]
mov DWORD PTR _rand_state, eax
pop ebp
ret 0
_srand ENDP
_TEXT SEGMENT
_rand PROC
push ebp
mov ebp, esp
imul eax, DWORD PTR _rand_state, 1664525
mov DWORD PTR _rand_state, eax
mov ecx, DWORD PTR _rand_state
add ecx, 1013904223 ; 3c6ef35fH
mov DWORD PTR _rand_state, ecx
mov eax, DWORD PTR _rand_state
and eax, 32767 ; 00007fffH
pop ebp
ret 0
_rand ENDP
_TEXT ENDS
20.2 x64
The x64 version is mostly the same and uses 32-bit registers instead of 64-bit ones (because we are working with int values
here). But my_srand() takes its input argument from the ECX register rather than from stack:
Listing 20.3: Optimizing MSVC 2013 x64
_BSS SEGMENT
rand_state DD 01H DUP (?)
_BSS ENDS
init$ = 8
my_srand PROC
; ECX = input argument
mov DWORD PTR rand_state, ecx
ret 0
my_srand ENDP
_TEXT SEGMENT
my_rand PROC
imul eax, DWORD PTR rand_state, 1664525 ; 0019660dH
345
CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.3. 32-BIT ARM
add eax, 1013904223 ; 3c6ef35fH
mov DWORD PTR rand_state, eax
and eax, 32767 ; 00007fffH
ret 0
my_rand ENDP
_TEXT ENDS
GCC compiler generates mostly the same code.
20.3 32-bit ARM
Listing 20.4: Optimizing Keil 6/2013 (ARM mode)
my_srand PROC
LDR r1,|L0.52| ; load pointer to rand_state
STR r0,[r1,#0] ; save rand_state
BX lr
ENDP
my_rand PROC
LDR r0,|L0.52| ; load pointer to rand_state
LDR r2,|L0.56| ; load RNG_a
LDR r1,[r0,#0] ; load rand_state
MUL r1,r2,r1
LDR r2,|L0.60| ; load RNG_c
ADD r1,r1,r2
STR r1,[r0,#0] ; save rand_state
; AND with 0x7FFF:
LSL r0,r1,#17
LSR r0,r0,#17
BX lr
ENDP
|L0.52|
DCD ||.data||
|L0.56|
DCD 0x0019660d
|L0.60|
DCD 0x3c6ef35f
AREA ||.data||, DATA, ALIGN=2
rand_state
DCD 0x00000000
It’s not possible to embed 32-bit constants into ARM instructions, so Keil has to place them externally and load them
additionally.
One interesting thing is that it’s not possible to embed the 0x7FFF constant as well. So what Keil does is shifting
rand_state left by 17 bits and then shifting it right by 17 bits. This is analogous to the (rand_state ≪ 17) ≫ 17 state-
ment in C/C++. It seems to be useless operation, but what it does is clearing the high 17 bits, leaving the low 15 bits intact,
and that’s our goal after all.
Optimizing Keil for Thumb mode generates mostly the same code.
20.4 MIPS
Listing 20.5: Optimizing GCC 4.4.5 (IDA)
my_srand:
; store $a0 to rand_state:
lui $v0, (rand_state >> 16)
jr $ra
sw $a0, rand_state
my_rand:
; load rand_state to $v0:
lui $v1, (rand_state >> 16)
346
CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.4. MIPS
lw $v0, rand_state
or $at, $zero ; load delay slot
; multiplicate rand_state in $v0 by 1664525 (RNG_a):
sll $a1, $v0, 2
sll $a0, $v0, 4
addu $a0, $a1, $a0
sll $a1, $a0, 6
subu $a0, $a1, $a0
addu $a0, $v0
sll $a1, $a0, 5
addu $a0, $a1
sll $a0, 3
addu $v0, $a0, $v0
sll $a0, $v0, 2
addu $v0, $a0
; add 1013904223 (RNG_c)
; the LI instruction is coalesced by IDA from LUI and ORI
li $a0, 0x3C6EF35F
addu $v0, $a0
; store to rand_state:
sw $v0, (rand_state & 0xFFFF)($v1)
jr $ra
andi $v0, 0x7FFF ; branch delay slot
Wow, here we see only one constant (0x3C6EF35F or 1013904223). Where is the other one (1664525)?
It seems that multiplication by 1664525 is done by just using shifts and additions! Let’s check this assumption:
#define RNG_a 1664525
int f (int a)
{
return a*RNG_a;
}
Listing 20.6: Optimizing GCC 4.4.5 (IDA)
f:
sll $v1, $a0, 2
sll $v0, $a0, 4
addu $v0, $v1, $v0
sll $v1, $v0, 6
subu $v0, $v1, $v0
addu $v0, $a0
sll $v1, $v0, 5
addu $v0, $v1
sll $v0, 3
addu $a0, $v0, $a0
sll $v0, $a0, 2
jr $ra
addu $v0, $a0, $v0 ; branch delay slot
Indeed!
20.4.1 MIPS relocations
I want also to focus on how such operations as load from memory and store to memory actually work. The listings here are
produced by IDA, which hides some details.
I’ll run objdump twice to get a disassembled listing and also relocations list:
Listing 20.7: Optimizing GCC 4.4.5 (objdump)
# objdump -D rand_O3.o
...
00000000 <my_srand>:
0: 3c020000 lui v0,0x0
4: 03e00008 jr ra
8: ac440000 sw a0,0(v0)
0000000c <my_rand>:
347
CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.5. THREAD-SAFE VERSION OF THE EXAMPLE
c: 3c030000 lui v1,0x0
10: 8c620000 lw v0,0(v1)
14: 00200825 move at,at
18: 00022880 sll a1,v0,0x2
1c: 00022100 sll a0,v0,0x4
20: 00a42021 addu a0,a1,a0
24: 00042980 sll a1,a0,0x6
28: 00a42023 subu a0,a1,a0
2c: 00822021 addu a0,a0,v0
30: 00042940 sll a1,a0,0x5
34: 00852021 addu a0,a0,a1
38: 000420c0 sll a0,a0,0x3
3c: 00821021 addu v0,a0,v0
40: 00022080 sll a0,v0,0x2
44: 00441021 addu v0,v0,a0
48: 3c043c6e lui a0,0x3c6e
4c: 3484f35f ori a0,a0,0xf35f
50: 00441021 addu v0,v0,a0
54: ac620000 sw v0,0(v1)
58: 03e00008 jr ra
5c: 30427fff andi v0,v0,0x7fff
...
# objdump -r rand_O3.o
...
RELOCATION RECORDS FOR [.text]:
OFFSET TYPE VALUE
00000000 R_MIPS_HI16 .bss
00000008 R_MIPS_LO16 .bss
0000000c R_MIPS_HI16 .bss
00000010 R_MIPS_LO16 .bss
00000054 R_MIPS_LO16 .bss
...
Let’s consider the two relocations for the my_srand() function. The first one, for address 0 has a type of R_MIPS_HI16
and the second one for address 8 has a type of R_MIPS_LO16. That implies that address of the beginning of the .bss segment
is to be written into the instructions at address of 0 (high part of address) and 8 (low part of address).
The rand_state variable is at the very start of the .bss segment.
So we see zeroes in the operands of instructions LUI and SW, because nothing is there yet — the compiler don’t know
what to write there. The linker will fix this, and the high part of the address will be written into the operand of LUI and the
low part of the address — to the operand of SW. SW will sum up the low part of the address and what is in register $V0 (the
high part is there).
It’s the same story with the my_rand() function: R_MIPS_HI16 relocation instructs the linker to write the high part of the
.bss segment address into instruction LUI. So the high part of the rand_state variable address is residing in register $V1.
The LW instruction at address 0x10 sums up the high and low parts and loads the value of the rand_state variable into $V1.
The SW instruction at address 0x54 do the summing again and then stores the new value to the rand_state global variable.
IDA processes relocations while loading, thus hiding these details, but we ought to remember them.
20.5 Thread-safe version of the example
The thread-safe version of the example is to be demonstrated later: 65.1 on page 671.
348
CHAPTER 21. STRUCTURES
Chapter 21
Structures
A C/C++ structure, with some assumptions, is just a set of variables, always stored in memory together, not necessary of the
same type 1
.
21.1 MSVC: SYSTEMTIME example
Let’s take the SYSTEMTIME2
win32 structure that describes time.
This is how it’s defined:
Listing 21.1: WinBase.h
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
Let’s write a C function to get the current time:
#include <windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME t;
GetSystemTime (&t);
printf ("%04d-%02d-%02d %02d:%02d:%02dn",
t.wYear, t.wMonth, t.wDay,
t.wHour, t.wMinute, t.wSecond);
return;
};
We get (MSVC 2010):
Listing 21.2: MSVC 2010 /GS-
_t$ = -16 ; size = 16
_main PROC
push ebp
mov ebp, esp
sub esp, 16
lea eax, DWORD PTR _t$[ebp]
push eax
call DWORD PTR __imp__GetSystemTime@4
movzx ecx, WORD PTR _t$[ebp+12] ; wSecond
push ecx
1AKA “heterogeneous container”
2MSDN: SYSTEMTIME structure
349
CHAPTER 21. STRUCTURES 21.1. MSVC: SYSTEMTIME EXAMPLE
movzx edx, WORD PTR _t$[ebp+10] ; wMinute
push edx
movzx eax, WORD PTR _t$[ebp+8] ; wHour
push eax
movzx ecx, WORD PTR _t$[ebp+6] ; wDay
push ecx
movzx edx, WORD PTR _t$[ebp+2] ; wMonth
push edx
movzx eax, WORD PTR _t$[ebp] ; wYear
push eax
push OFFSET $SG78811 ; '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H
call _printf
add esp, 28
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
16 bytes are allocated for this structure in the local stack —that is exactly sizeof(WORD)*8 (there are 8 WORD variables
in the structure).
Pay attention to the fact that the structure begins with the wYear field. It can be said that a pointer to the SYSTEMTIME
structure is passed to the GetSystemTime()3
, but it is also can be said that a pointer to the wYear field is passed, and
that is the same! GetSystemTime() writes the current year to the WORD pointer pointing to, then shifts 2 bytes ahead,
writes current month, etc, etc.
3MSDN: SYSTEMTIME structure
350
CHAPTER 21. STRUCTURES 21.1. MSVC: SYSTEMTIME EXAMPLE
21.1.1 OllyDbg
Let’s compile this example in MSVC 2010 with /GS- /MD keys and run it in OllyDbg. Let’s open windows for data and stack
at the address which is passed as the first argument of the GetSystemTime() function, and let’s wait until it’s executed.
We see this:
Figure 21.1: OllyDbg: GetSystemTime() just executed
The system time of the function execution on my computer is 9 december 2014, 22:29:52:
Figure 21.2: OllyDbg: printf() output
So we see these 16 bytes in the data window:
DE 07 0C 00 02 00 09 00 16 00 1D 00 34 00 D4 03
Each two bytes represent one field of the structure. Since the endianness is little endian, we see the low byte first and
then the high one. Hence, these are the values currently stored in memory:
Hexadecimal number decimal number field name
0x07DE 2014 wYear
0x000C 12 wMonth
0x0002 2 wDayOfWeek
0x0009 9 wDay
0x0016 22 wHour
0x001D 29 wMinute
0x0034 52 wSecond
0x03D4 980 wMilliseconds
The same values are seen in the stack window, but they are grouped as 32-bit values.
And then printf() just takes the values it needs and outputs them to the console.
Some values aren’t output by printf() (wDayOfWeek and wMilliseconds), but they are in memory right now,
available for use.
21.1.2 Replacing the structure with array
The fact that the structure fields are just variables located side-by-side, I can demonstrate by doing the following. Keeping
in mind the SYSTEMTIME structure description, I can rewrite this simple example like this:
#include <windows.h>
#include <stdio.h>
351
CHAPTER 21. STRUCTURES 21.2. LET’S ALLOCATE SPACE FOR A STRUCTURE USING MALLOC()
void main()
{
WORD array[8];
GetSystemTime (array);
printf ("%04d-%02d-%02d %02d:%02d:%02dn",
array[0] /* wYear */, array[1] /* wMonth */, array[3] /* wDay */,
array[4] /* wHour */, array[5] /* wMinute */, array[6] /* wSecond */);
return;
};
The compiler grumbles a bit:
systemtime2.c(7) : warning C4133: 'function' : incompatible types - from 'WORD [8]' to '⤦
LPSYSTEMTIME'
But nevertheless, it produces this code:
Listing 21.3: Non-optimizing MSVC 2010
$SG78573 DB '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H
_array$ = -16 ; size = 16
_main PROC
push ebp
mov ebp, esp
sub esp, 16
lea eax, DWORD PTR _array$[ebp]
push eax
call DWORD PTR __imp__GetSystemTime@4
movzx ecx, WORD PTR _array$[ebp+12] ; wSecond
push ecx
movzx edx, WORD PTR _array$[ebp+10] ; wMinute
push edx
movzx eax, WORD PTR _array$[ebp+8] ; wHoure
push eax
movzx ecx, WORD PTR _array$[ebp+6] ; wDay
push ecx
movzx edx, WORD PTR _array$[ebp+2] ; wMonth
push edx
movzx eax, WORD PTR _array$[ebp] ; wYear
push eax
push OFFSET $SG78573
call _printf
add esp, 28
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
And it works just as the same!
It is very interesting that the result in assembly form cannot be distinguished from the result of the previous compilation.
So by looking at this code, one cannot say for sure if there was a structure declared, or an array.
Nevertheless, no sane person would do it, as it is not convenient. Also the structure fields may be changed by developers,
swapped, etc.
I’m not adding OllyDbg example here, because it is just the same as in the case with the structure.
21.2 Let’s allocate space for a structure using malloc()
Sometimes it is simpler to place structures not the in local stack, but in the heap:
#include <windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME *t;
352
CHAPTER 21. STRUCTURES 21.2. LET’S ALLOCATE SPACE FOR A STRUCTURE USING MALLOC()
t=(SYSTEMTIME *)malloc (sizeof (SYSTEMTIME));
GetSystemTime (t);
printf ("%04d-%02d-%02d %02d:%02d:%02dn",
t->wYear, t->wMonth, t->wDay,
t->wHour, t->wMinute, t->wSecond);
free (t);
return;
};
Let’s compile it now with optimization (/Ox) so it would be easy see what we need.
Listing 21.4: Optimizing MSVC
_main PROC
push esi
push 16
call _malloc
add esp, 4
mov esi, eax
push esi
call DWORD PTR __imp__GetSystemTime@4
movzx eax, WORD PTR [esi+12] ; wSecond
movzx ecx, WORD PTR [esi+10] ; wMinute
movzx edx, WORD PTR [esi+8] ; wHour
push eax
movzx eax, WORD PTR [esi+6] ; wDay
push ecx
movzx ecx, WORD PTR [esi+2] ; wMonth
push edx
movzx edx, WORD PTR [esi] ; wYear
push eax
push ecx
push edx
push OFFSET $SG78833
call _printf
push esi
call _free
add esp, 32
xor eax, eax
pop esi
ret 0
_main ENDP
So, sizeof(SYSTEMTIME) = 16 and that is exact number of bytes to be allocated by malloc(). It returns a pointer
to a freshly allocated memory block in the EAX register, which is then moved into the ESI register. GetSystemTime()
win32 function takes care of saving value in ESI, and that is why it is not saved here and continues to be used after the
GetSystemTime() call.
New instruction —MOVZX (Move with Zero eXtend). It may be used in most cases as MOVSX, but it sets the remaining bits
to 0. That’s because printf() requires a 32-bit int, but we got a WORD in the structure —that is 16-bit unsigned type.
That’s why by copying the value from a WORD into int, bits from 16 to 31 must be cleared, because a random noise may be
there, which is left from the previous operations on the register(s).
In this example, I again can represent the structure as an array of 8 WORDs:
#include <windows.h>
#include <stdio.h>
void main()
{
WORD *t;
t=(WORD *)malloc (16);
GetSystemTime (t);
printf ("%04d-%02d-%02d %02d:%02d:%02dn",
t[0] /* wYear */, t[1] /* wMonth */, t[3] /* wDay */,
353
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
t[4] /* wHour */, t[5] /* wMinute */, t[6] /* wSecond */);
free (t);
return;
};
We get:
Listing 21.5: Optimizing MSVC
$SG78594 DB '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H
_main PROC
push esi
push 16
call _malloc
add esp, 4
mov esi, eax
push esi
call DWORD PTR __imp__GetSystemTime@4
movzx eax, WORD PTR [esi+12]
movzx ecx, WORD PTR [esi+10]
movzx edx, WORD PTR [esi+8]
push eax
movzx eax, WORD PTR [esi+6]
push ecx
movzx ecx, WORD PTR [esi+2]
push edx
movzx edx, WORD PTR [esi]
push eax
push ecx
push edx
push OFFSET $SG78594
call _printf
push esi
call _free
add esp, 32
xor eax, eax
pop esi
ret 0
_main ENDP
Again, we got the code cannot be distinguished from the previous one. And again I have to note, you haven’t to do this
in practice, unless you really know what you are doing.
21.3 UNIX: struct tm
21.3.1 Linux
Let’s take the tm structure from time.h in Linux for example:
#include <stdio.h>
#include <time.h>
void main()
{
struct tm t;
time_t unix_time;
unix_time=time(NULL);
localtime_r (&unix_time, &t);
printf ("Year: %dn", t.tm_year+1900);
printf ("Month: %dn", t.tm_mon);
printf ("Day: %dn", t.tm_mday);
printf ("Hour: %dn", t.tm_hour);
printf ("Minutes: %dn", t.tm_min);
printf ("Seconds: %dn", t.tm_sec);
354
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
};
Let’s compile it in GCC 4.4.1:
Listing 21.6: GCC 4.4.1
main proc near
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 40h
mov dword ptr [esp], 0 ; first argument for time()
call time
mov [esp+3Ch], eax
lea eax, [esp+3Ch] ; take pointer to what time() returned
lea edx, [esp+10h] ; at ESP+10h struct tm will begin
mov [esp+4], edx ; pass pointer to the structure begin
mov [esp], eax ; pass pointer to result of time()
call localtime_r
mov eax, [esp+24h] ; tm_year
lea edx, [eax+76Ch] ; edx=eax+1900
mov eax, offset format ; "Year: %dn"
mov [esp+4], edx
mov [esp], eax
call printf
mov edx, [esp+20h] ; tm_mon
mov eax, offset aMonthD ; "Month: %dn"
mov [esp+4], edx
mov [esp], eax
call printf
mov edx, [esp+1Ch] ; tm_mday
mov eax, offset aDayD ; "Day: %dn"
mov [esp+4], edx
mov [esp], eax
call printf
mov edx, [esp+18h] ; tm_hour
mov eax, offset aHourD ; "Hour: %dn"
mov [esp+4], edx
mov [esp], eax
call printf
mov edx, [esp+14h] ; tm_min
mov eax, offset aMinutesD ; "Minutes: %dn"
mov [esp+4], edx
mov [esp], eax
call printf
mov edx, [esp+10h]
mov eax, offset aSecondsD ; "Seconds: %dn"
mov [esp+4], edx ; tm_sec
mov [esp], eax
call printf
leave
retn
main endp
Somehow, IDA did not write the local variables’ names in the local stack. But since we already are experienced reverse
engineers :-) we may do it without this information in this simple example.
Please also pay attention to the lea edx, [eax+76Ch] —this instruction just adds 0x76C (1900) to value in EAX,
but doesn’t modify any flags. See also the relevant section about LEA ( A.6.2 on page 933).
GDB
Let’s try to load the example into GDB 4
:
Listing 21.7: GDB
dennis@ubuntuvm:~/polygon$ date
Mon Jun 2 18:10:37 EEST 2014
dennis@ubuntuvm:~/polygon$ gcc GCC_tm.c -o GCC_tm
dennis@ubuntuvm:~/polygon$ gdb GCC_tm
4I corrected the date result slightly for demonstration purposes. Of course, I wasn’t able to run GDB that quickly, in the same second.
355
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dennis/polygon/GCC_tm...(no debugging symbols found)...done.
(gdb) b printf
Breakpoint 1 at 0x8048330
(gdb) run
Starting program: /home/dennis/polygon/GCC_tm
Breakpoint 1, __printf (format=0x80485c0 "Year: %dn") at printf.c:29
29 printf.c: No such file or directory.
(gdb) x/20x $esp
0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000
0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 0x0000000a
0xbffff0fc: 0x00000012 0x00000002 0x00000005 0x00000072
0xbffff10c: 0x00000001 0x00000098 0x00000001 0x00002a30
0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000
(gdb)
We can easily find our structure in the stack. First, let’s see how it’s defined in time.h:
Listing 21.8: time.h
struct tm
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
Pay attention that 32-bit int is used here instead of WORD in SYSTEMTIME. So, each field occupies 32-bit.
Here are the fields of our structure in the stack:
0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000
0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 sec 0x0000000a min
0xbffff0fc: 0x00000012 hour 0x00000002 mday 0x00000005 mon 0x00000072 year
0xbffff10c: 0x00000001 wday 0x00000098 yday 0x00000001 isdst0x00002a30
0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000
Or as a table:
Hexadecimal number decimal number field name
0x00000025 37 tm_sec
0x0000000a 10 tm_min
0x00000012 18 tm_hour
0x00000002 2 tm_mday
0x00000005 5 tm_mon
0x00000072 114 tm_year
0x00000001 1 tm_wday
0x00000098 152 tm_yday
0x00000001 1 tm_isdst
Just like SYSTEMTIME ( 21.1 on page 349), there are also other fields available that are not used, like tm_wday, tm_yday,
tm_isdst.
21.3.2 ARM
Optimizing Keil 6/2013 (thumb mode)
Same example:
356
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
Listing 21.9: Optimizing Keil 6/2013 (thumb mode)
var_38 = -0x38
var_34 = -0x34
var_30 = -0x30
var_2C = -0x2C
var_28 = -0x28
var_24 = -0x24
timer = -0xC
PUSH {LR}
MOVS R0, #0 ; timer
SUB SP, SP, #0x34
BL time
STR R0, [SP,#0x38+timer]
MOV R1, SP ; tp
ADD R0, SP, #0x38+timer ; timer
BL localtime_r
LDR R1, =0x76C
LDR R0, [SP,#0x38+var_24]
ADDS R1, R0, R1
ADR R0, aYearD ; "Year: %dn"
BL __2printf
LDR R1, [SP,#0x38+var_28]
ADR R0, aMonthD ; "Month: %dn"
BL __2printf
LDR R1, [SP,#0x38+var_2C]
ADR R0, aDayD ; "Day: %dn"
BL __2printf
LDR R1, [SP,#0x38+var_30]
ADR R0, aHourD ; "Hour: %dn"
BL __2printf
LDR R1, [SP,#0x38+var_34]
ADR R0, aMinutesD ; "Minutes: %dn"
BL __2printf
LDR R1, [SP,#0x38+var_38]
ADR R0, aSecondsD ; "Seconds: %dn"
BL __2printf
ADD SP, SP, #0x34
POP {PC}
Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
IDA “knows” the tm structure (because IDA “knows” the types of the arguments of library functions like localtime_r()),
so it shows here structure elements accesses and their names.
Listing 21.10: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
var_38 = -0x38
var_34 = -0x34
PUSH {R7,LR}
MOV R7, SP
SUB SP, SP, #0x30
MOVS R0, #0 ; time_t *
BLX _time
ADD R1, SP, #0x38+var_34 ; struct tm *
STR R0, [SP,#0x38+var_38]
MOV R0, SP ; time_t *
BLX _localtime_r
LDR R1, [SP,#0x38+var_34.tm_year]
MOV R0, 0xF44 ; "Year: %dn"
ADD R0, PC ; char *
ADDW R1, R1, #0x76C
BLX _printf
LDR R1, [SP,#0x38+var_34.tm_mon]
MOV R0, 0xF3A ; "Month: %dn"
ADD R0, PC ; char *
BLX _printf
LDR R1, [SP,#0x38+var_34.tm_mday]
357
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
MOV R0, 0xF35 ; "Day: %dn"
ADD R0, PC ; char *
BLX _printf
LDR R1, [SP,#0x38+var_34.tm_hour]
MOV R0, 0xF2E ; "Hour: %dn"
ADD R0, PC ; char *
BLX _printf
LDR R1, [SP,#0x38+var_34.tm_min]
MOV R0, 0xF28 ; "Minutes: %dn"
ADD R0, PC ; char *
BLX _printf
LDR R1, [SP,#0x38+var_34]
MOV R0, 0xF25 ; "Seconds: %dn"
ADD R0, PC ; char *
BLX _printf
ADD SP, SP, #0x30
POP {R7,PC}
...
00000000 tm struc ; (sizeof=0x2C, standard type)
00000000 tm_sec DCD ?
00000004 tm_min DCD ?
00000008 tm_hour DCD ?
0000000C tm_mday DCD ?
00000010 tm_mon DCD ?
00000014 tm_year DCD ?
00000018 tm_wday DCD ?
0000001C tm_yday DCD ?
00000020 tm_isdst DCD ?
00000024 tm_gmtoff DCD ?
00000028 tm_zone DCD ? ; offset
0000002C tm ends
21.3.3 MIPS
Listing 21.11: Optimizing GCC 4.4.5 (IDA)
1 main:
2
3 ; IDA is not aware of structure field names, I named them manually:
4
5 var_40 = -0x40
6 var_38 = -0x38
7 seconds = -0x34
8 minutes = -0x30
9 hour = -0x2C
10 day = -0x28
11 month = -0x24
12 year = -0x20
13 var_4 = -4
14
15 lui $gp, (__gnu_local_gp >> 16)
16 addiu $sp, -0x50
17 la $gp, (__gnu_local_gp & 0xFFFF)
18 sw $ra, 0x50+var_4($sp)
19 sw $gp, 0x50+var_40($sp)
20 lw $t9, (time & 0xFFFF)($gp)
21 or $at, $zero ; load delay slot, NOP
22 jalr $t9
23 move $a0, $zero ; branch delay slot, NOP
24 lw $gp, 0x50+var_40($sp)
25 addiu $a0, $sp, 0x50+var_38
26 lw $t9, (localtime_r & 0xFFFF)($gp)
27 addiu $a1, $sp, 0x50+seconds
28 jalr $t9
29 sw $v0, 0x50+var_38($sp) ; branch delay slot
30 lw $gp, 0x50+var_40($sp)
31 lw $a1, 0x50+year($sp)
358
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
32 lw $t9, (printf & 0xFFFF)($gp)
33 la $a0, $LC0 # "Year: %dn"
34 jalr $t9
35 addiu $a1, 1900 ; branch delay slot
36 lw $gp, 0x50+var_40($sp)
37 lw $a1, 0x50+month($sp)
38 lw $t9, (printf & 0xFFFF)($gp)
39 lui $a0, ($LC1 >> 16) # "Month: %dn"
40 jalr $t9
41 la $a0, ($LC1 & 0xFFFF) # "Month: %dn" ; branch delay slot
42 lw $gp, 0x50+var_40($sp)
43 lw $a1, 0x50+day($sp)
44 lw $t9, (printf & 0xFFFF)($gp)
45 lui $a0, ($LC2 >> 16) # "Day: %dn"
46 jalr $t9
47 la $a0, ($LC2 & 0xFFFF) # "Day: %dn" ; branch delay slot
48 lw $gp, 0x50+var_40($sp)
49 lw $a1, 0x50+hour($sp)
50 lw $t9, (printf & 0xFFFF)($gp)
51 lui $a0, ($LC3 >> 16) # "Hour: %dn"
52 jalr $t9
53 la $a0, ($LC3 & 0xFFFF) # "Hour: %dn" ; branch delay slot
54 lw $gp, 0x50+var_40($sp)
55 lw $a1, 0x50+minutes($sp)
56 lw $t9, (printf & 0xFFFF)($gp)
57 lui $a0, ($LC4 >> 16) # "Minutes: %dn"
58 jalr $t9
59 la $a0, ($LC4 & 0xFFFF) # "Minutes: %dn" ; branch delay slot
60 lw $gp, 0x50+var_40($sp)
61 lw $a1, 0x50+seconds($sp)
62 lw $t9, (printf & 0xFFFF)($gp)
63 lui $a0, ($LC5 >> 16) # "Seconds: %dn"
64 jalr $t9
65 la $a0, ($LC5 & 0xFFFF) # "Seconds: %dn" ; branch delay slot
66 lw $ra, 0x50+var_4($sp)
67 or $at, $zero ; load delay slot, NOP
68 jr $ra
69 addiu $sp, 0x50
70
71 $LC0: .ascii "Year: %dn"<0>
72 $LC1: .ascii "Month: %dn"<0>
73 $LC2: .ascii "Day: %dn"<0>
74 $LC3: .ascii "Hour: %dn"<0>
75 $LC4: .ascii "Minutes: %dn"<0>
76 $LC5: .ascii "Seconds: %dn"<0>
This is an example where the branch delay slots can confuse us. For example, there is the instruction “addiu $a1, 1900”
at line 35 which adds 1900 to the year number. It’s executed before the corresponding JALR at line 34, do not forget about
it.
21.3.4 Structure as a set of values
In order to illustrate that the structure is just variables laying side-by-side in one place, let’s rework our example while
looking at the tm structure definition again: listing.21.8.
#include <stdio.h>
#include <time.h>
void main()
{
int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, tm_yday, tm_isdst;
time_t unix_time;
unix_time=time(NULL);
localtime_r (&unix_time, &tm_sec);
printf ("Year: %dn", tm_year+1900);
printf ("Month: %dn", tm_mon);
printf ("Day: %dn", tm_mday);
359
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
printf ("Hour: %dn", tm_hour);
printf ("Minutes: %dn", tm_min);
printf ("Seconds: %dn", tm_sec);
};
N.B. The pointer to the tm_sec field is passed into localtime_r, i.e., to the first element of the “structure”.
The compiler warns us:
Listing 21.12: GCC 4.7.3
GCC_tm2.c: In function 'main':
GCC_tm2.c:11:5: warning: passing argument 2 of 'localtime_r' from incompatible pointer type [⤦
enabled by default]
In file included from GCC_tm2.c:2:0:
/usr/include/time.h:59:12: note: expected 'struct tm *' but argument is of type 'int *'
But nevertheless, it generates this:
Listing 21.13: GCC 4.7.3
main proc near
var_30 = dword ptr -30h
var_2C = dword ptr -2Ch
unix_time = dword ptr -1Ch
tm_sec = dword ptr -18h
tm_min = dword ptr -14h
tm_hour = dword ptr -10h
tm_mday = dword ptr -0Ch
tm_mon = dword ptr -8
tm_year = dword ptr -4
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 30h
call __main
mov [esp+30h+var_30], 0 ; arg 0
call time
mov [esp+30h+unix_time], eax
lea eax, [esp+30h+tm_sec]
mov [esp+30h+var_2C], eax
lea eax, [esp+30h+unix_time]
mov [esp+30h+var_30], eax
call localtime_r
mov eax, [esp+30h+tm_year]
add eax, 1900
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aYearD ; "Year: %dn"
call printf
mov eax, [esp+30h+tm_mon]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aMonthD ; "Month: %dn"
call printf
mov eax, [esp+30h+tm_mday]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aDayD ; "Day: %dn"
call printf
mov eax, [esp+30h+tm_hour]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aHourD ; "Hour: %dn"
call printf
mov eax, [esp+30h+tm_min]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aMinutesD ; "Minutes: %dn"
call printf
mov eax, [esp+30h+tm_sec]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aSecondsD ; "Seconds: %dn"
call printf
leave
retn
360
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
main endp
This code is identical to what we saw previously and it is not possible to say, was it a structure in original source code or
just a pack of variables.
And this works. However, it is not recommended to do this in practice. Usually, non-optimizing compilers allocates
variables in the local stack in the same order as they were declared in the function. Nevertheless, there is no guarantee.
By the way, some other compiler may warn about the tm_year, tm_mon, tm_mday, tm_hour, tm_min variables,
but not tm_sec are used without being initialized. Indeed, the compiler is not aware that these are to be filled by
localtime_r() function.
I chose this example, since all structure fields are of type int. This would not work if structure fields are 16-bit (WORD),
like in the case of the SYSTEMTIME structure—GetSystemTime() will fill them incorrectly ( because the local variables
are aligned on a 32-bit boundary). Read more about it in next section: “Fields packing in structure” ( 21.4 on the following
page).
So, a structure is just a pack of variables laying on one place, side-by-side. I could say that the structure is syntactic
sugar, directing the compiler to hold them in one place. However, I’m not an expert on programming languages, so most
likely I’m wrong with this term. By the way, in some very early C versions (before 1972), there were no structures at all
[Rit93].
I’m not adding a debugger example here: it is just the same as you already saw.
21.3.5 Structure as an array of 32-bit words
#include <stdio.h>
#include <time.h>
void main()
{
struct tm t;
time_t unix_time;
int i;
unix_time=time(NULL);
localtime_r (&unix_time, &t);
for (i=0; i<9; i++)
{
int tmp=((int*)&t)[i];
printf ("0x%08X (%d)n", tmp, tmp);
};
};
I just cast a pointer to structure to an array of int’s. And that works! I ran the example at 23:51:45 26-July-2014.
0x0000002D (45)
0x00000033 (51)
0x00000017 (23)
0x0000001A (26)
0x00000006 (6)
0x00000072 (114)
0x00000006 (6)
0x000000CE (206)
0x00000001 (1)
The variables here are in the same order as they are enumerated in the definition of the structure: 21.8 on page 356.
Here is how it gets compiled:
Listing 21.14: Optimizing GCC 4.8.1
main proc near
push ebp
mov ebp, esp
push esi
push ebx
and esp, 0FFFFFFF0h
sub esp, 40h
mov dword ptr [esp], 0 ; timer
lea ebx, [esp+14h]
call _time
lea esi, [esp+38h]
361
CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM
mov [esp+4], ebx ; tp
mov [esp+10h], eax
lea eax, [esp+10h]
mov [esp], eax ; timer
call _localtime_r
nop
lea esi, [esi+0] ; NOP
loc_80483D8:
; EBX here is pointer to structure, ESI is the pointer to the end of it.
mov eax, [ebx] ; get 32-bit word from array
add ebx, 4 ; next field in structure
mov dword ptr [esp+4], offset a0x08xD ; "0x%08X (%d)n"
mov dword ptr [esp], 1
mov [esp+0Ch], eax ; pass value to printf()
mov [esp+8], eax ; pass value to printf()
call ___printf_chk
cmp ebx, esi ; meet structure end?
jnz short loc_80483D8 ; no - load next value then
lea esp, [ebp-8]
pop ebx
pop esi
pop ebp
retn
main endp
Indeed: the space in the local stack is first treated as a structure, and then it’s treated as an array.
It’s even possible to modify the fields of the structure through this pointer.
And again, it’s dubiously hackish way to do things, not recommended for use in production code.
Exercise
As an exercise, try to modify (increase by 1) the current month number, treating the structure as an array.
21.3.6 Structure as an array of bytes
I can do even more. Let’s cast the pointer to an array of bytes and dump it:
#include <stdio.h>
#include <time.h>
void main()
{
struct tm t;
time_t unix_time;
int i, j;
unix_time=time(NULL);
localtime_r (&unix_time, &t);
for (i=0; i<9; i++)
{
for (j=0; j<4; j++)
printf ("0x%02X ", ((unsigned char*)&t)[i*4+j]);
printf ("n");
};
};
0x2D 0x00 0x00 0x00
0x33 0x00 0x00 0x00
0x17 0x00 0x00 0x00
0x1A 0x00 0x00 0x00
0x06 0x00 0x00 0x00
0x72 0x00 0x00 0x00
0x06 0x00 0x00 0x00
0xCE 0x00 0x00 0x00
0x01 0x00 0x00 0x00
362
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
I ran this example also at 23:51:45 26-July-2014. The values are just the same as in the previous dump ( 21.3.5 on
page 361), and of course, the lowest byte goes first, because this is a little-endian architecture ( 31 on page 453).
Listing 21.15: Optimizing GCC 4.8.1
main proc near
push ebp
mov ebp, esp
push edi
push esi
push ebx
and esp, 0FFFFFFF0h
sub esp, 40h
mov dword ptr [esp], 0 ; timer
lea esi, [esp+14h]
call _time
lea edi, [esp+38h] ; struct end
mov [esp+4], esi ; tp
mov [esp+10h], eax
lea eax, [esp+10h]
mov [esp], eax ; timer
call _localtime_r
lea esi, [esi+0] ; NOP
; ESI here is the pointer to structure in local stack. EDI is the pointer to structure end.
loc_8048408:
xor ebx, ebx ; j=0
loc_804840A:
movzx eax, byte ptr [esi+ebx] ; load byte
add ebx, 1 ; j=j+1
mov dword ptr [esp+4], offset a0x02x ; "0x%02X "
mov dword ptr [esp], 1
mov [esp+8], eax ; pass loaded byte to printf()
call ___printf_chk
cmp ebx, 4
jnz short loc_804840A
; print carriage return character (CR)
mov dword ptr [esp], 0Ah ; c
add esi, 4
call _putchar
cmp esi, edi ; meet struct end?
jnz short loc_8048408 ; j=0
lea esp, [ebp-0Ch]
pop ebx
pop esi
pop edi
pop ebp
retn
main endp
21.4 Fields packing in structure
One important thing is fields packing in structures5
.
Let’s take a simple example:
#include <stdio.h>
struct s
{
char a;
int b;
char c;
int d;
};
void f(struct s s)
{
5See also: Wikipedia: Data structure alignment
363
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
printf ("a=%d; b=%d; c=%d; d=%dn", s.a, s.b, s.c, s.d);
};
int main()
{
struct s tmp;
tmp.a=1;
tmp.b=2;
tmp.c=3;
tmp.d=4;
f(tmp);
};
As we see, we have two char fields (each is exactly one byte) and two more —int (each - 4 bytes).
21.4.1 x86
This compiles to:
Listing 21.16: MSVC 2012 /GS- /Ob0
1 _tmp$ = -16
2 _main PROC
3 push ebp
4 mov ebp, esp
5 sub esp, 16
6 mov BYTE PTR _tmp$[ebp], 1 ; set field a
7 mov DWORD PTR _tmp$[ebp+4], 2 ; set field b
8 mov BYTE PTR _tmp$[ebp+8], 3 ; set field c
9 mov DWORD PTR _tmp$[ebp+12], 4 ; set field d
10 sub esp, 16 ; allocate place for temporary structure
11 mov eax, esp
12 mov ecx, DWORD PTR _tmp$[ebp] ; copy our structure to the temporary one
13 mov DWORD PTR [eax], ecx
14 mov edx, DWORD PTR _tmp$[ebp+4]
15 mov DWORD PTR [eax+4], edx
16 mov ecx, DWORD PTR _tmp$[ebp+8]
17 mov DWORD PTR [eax+8], ecx
18 mov edx, DWORD PTR _tmp$[ebp+12]
19 mov DWORD PTR [eax+12], edx
20 call _f
21 add esp, 16
22 xor eax, eax
23 mov esp, ebp
24 pop ebp
25 ret 0
26 _main ENDP
27
28 _s$ = 8 ; size = 16
29 ?f@@YAXUs@@@Z PROC ; f
30 push ebp
31 mov ebp, esp
32 mov eax, DWORD PTR _s$[ebp+12]
33 push eax
34 movsx ecx, BYTE PTR _s$[ebp+8]
35 push ecx
36 mov edx, DWORD PTR _s$[ebp+4]
37 push edx
38 movsx eax, BYTE PTR _s$[ebp]
39 push eax
40 push OFFSET $SG3842
41 call _printf
42 add esp, 20
43 pop ebp
44 ret 0
45 ?f@@YAXUs@@@Z ENDP ; f
46 _TEXT ENDS
We pass the structure as a whole, but in fact, as we can see, the structure is being copied to a temporary one (a place in
stack is allocated in line 10 for it, and then all 4 fields, one by one, are copied in lines 12 … 19), and then its pointer (address)
364
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
is to be passed. The structure is copied because it’s not know if the f() function going to modify the structure or not. If it
gets changed, then the structure in main() has to remain as it was. We could use C/C++ pointers, and the resulting code
will be almost the same, but without the copying.
As we can see, each field’s address is aligned on a 4-byte boundary. That’s why each char occupies 4 bytes here (like int).
Why? Because it is easier for the CPU to access memory at aligned addresses and to cache data from it.
However, it is not very economical.
Let’s try to compile it with option (/Zp1) (/Zp[n] pack structures on n-byte boundary).
Listing 21.17: MSVC 2012 /GS- /Zp1
1 _main PROC
2 push ebp
3 mov ebp, esp
4 sub esp, 12
5 mov BYTE PTR _tmp$[ebp], 1 ; set field a
6 mov DWORD PTR _tmp$[ebp+1], 2 ; set field b
7 mov BYTE PTR _tmp$[ebp+5], 3 ; set field c
8 mov DWORD PTR _tmp$[ebp+6], 4 ; set field d
9 sub esp, 12 ; allocate place for temporary structure
10 mov eax, esp
11 mov ecx, DWORD PTR _tmp$[ebp] ; copy 10 bytes
12 mov DWORD PTR [eax], ecx
13 mov edx, DWORD PTR _tmp$[ebp+4]
14 mov DWORD PTR [eax+4], edx
15 mov cx, WORD PTR _tmp$[ebp+8]
16 mov WORD PTR [eax+8], cx
17 call _f
18 add esp, 12
19 xor eax, eax
20 mov esp, ebp
21 pop ebp
22 ret 0
23 _main ENDP
24
25 _TEXT SEGMENT
26 _s$ = 8 ; size = 10
27 ?f@@YAXUs@@@Z PROC ; f
28 push ebp
29 mov ebp, esp
30 mov eax, DWORD PTR _s$[ebp+6]
31 push eax
32 movsx ecx, BYTE PTR _s$[ebp+5]
33 push ecx
34 mov edx, DWORD PTR _s$[ebp+1]
35 push edx
36 movsx eax, BYTE PTR _s$[ebp]
37 push eax
38 push OFFSET $SG3842
39 call _printf
40 add esp, 20
41 pop ebp
42 ret 0
43 ?f@@YAXUs@@@Z ENDP ; f
Now the structure takes only 10 bytes and each char value takes 1 byte. What does it give to us? Size economy. And as
drawback —the CPU accessing these fields slower than it could.
The structure is also copied in main(). Not field-by-field, but directly 10 bytes, using three pairs of MOV. Why not 4?
The compiler decided that it’s better to copy 10 bytes using 3 MOV pairs than to copy two 32-bit words and two bytes using
4 MOV pairs. By the way, such copy implementation using MOV instead of calling the memcpy() function is widely used,
because it’s faster than a call to memcpy()—for short blocks, of course: 43.1.5 on page 504.
As it can be easily guessed, if the structure is used in many source and object files, all these must be compiled with the
same convention about structures packing.
Aside from MSVC /Zp option which sets how to align each structure field, there is also the #pragma pack compiler
option, which can be defined right in the source code. It is available in both MSVC6
and GCC7
.
Let’s get back to the SYSTEMTIME structure that consists of 16-bit fields. How does our compiler know to pack them on
1-byte alignment boundary?
WinNT.h file has this:
6MSDN: Working with Packing Structures
7Structure-Packing Pragmas
365
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
Listing 21.18: WinNT.h
#include "pshpack1.h"
And this:
Listing 21.19: WinNT.h
#include "pshpack4.h" // 4 byte packing is the default
The file PshPack1.h looks like:
Listing 21.20: PshPack1.h
#if ! (defined(lint) || defined(RC_INVOKED))
#if ( _MSC_VER >= 800 && !defined(_M_I86)) || defined(_PUSHPOP_SUPPORTED)
#pragma warning(disable:4103)
#if !(defined( MIDL_PASS )) || defined( __midl )
#pragma pack(push,1)
#else
#pragma pack(1)
#endif
#else
#pragma pack(1)
#endif
#endif /* ! (defined(lint) || defined(RC_INVOKED)) */
This tell the compiler how to pack the structures defined after #pragma pack.
366
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
OllyDbg + fields are packed by default
Let’s try our example (where the fields are aligned by default (4 bytes)) in OllyDbg:
Figure 21.3: OllyDbg: Before printf() execution
We see our 4 fields in the data window. But where do the random bytes (0x30, 0x37, 0x01) come from, that are next to
the first (a) and third (c) fields? By looking at our listing 21.16 on page 364, we can see that the first and third fields are char,
therefore only one byte is written, 1 and 3 respectively (lines 6 and 8). The remaining 3 bytes of the 32-bit words are not
being modified in memory! Hence, random garbage is left there. This garbage doesn’t influence the printf() output in
any way, because the values for it are prepared using the MOVSX instruction, which takes bytes, but not words: listing.21.16
(lines 34 and 38).
By the way, the MOVSX (sign-extending) instruction is used here, because char is signed by default in MSVC and GCC. If
the type unsigned char or uint8_t was used here, MOVZX instruction would have been used instead.
367
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
OllyDbg + fields aligning on 1 byte boundary
Things are much clearer here: 4 fields occupy 10 bytes and the values are stored side-by-side
Figure 21.4: OllyDbg: Before printf() execution
21.4.2 ARM
Optimizing Keil 6/2013 (thumb mode)
Listing 21.21: Optimizing Keil 6/2013 (thumb mode)
.text:0000003E exit ; CODE XREF: f+16
.text:0000003E 05 B0 ADD SP, SP, #0x14
.text:00000040 00 BD POP {PC}
.text:00000280 f
.text:00000280
.text:00000280 var_18 = -0x18
.text:00000280 a = -0x14
.text:00000280 b = -0x10
.text:00000280 c = -0xC
.text:00000280 d = -8
.text:00000280
.text:00000280 0F B5 PUSH {R0-R3,LR}
.text:00000282 81 B0 SUB SP, SP, #4
.text:00000284 04 98 LDR R0, [SP,#16] ; d
.text:00000286 02 9A LDR R2, [SP,#8] ; b
.text:00000288 00 90 STR R0, [SP]
.text:0000028A 68 46 MOV R0, SP
.text:0000028C 03 7B LDRB R3, [R0,#12] ; c
.text:0000028E 01 79 LDRB R1, [R0,#4] ; a
.text:00000290 59 A0 ADR R0, aADBDCDDD ; "a=%d; b=%d; c=%d; d=%dn"
.text:00000292 05 F0 AD FF BL __2printf
.text:00000296 D2 E6 B exit
As we may recall, here a structure is passed instead of pointer to one, and since the first 4 function arguments in ARM
are passed via registers, the structure’s fields are passed via R0-R3.
LDRB loads one byte from memory and extends it to 32-bit, taking its sign into account. This is similar to MOVSX in x86.
Here it is used to load fields a and c from the structure.
One more thing we spot easily is that instead of function epilogue, there is jump to another function’s epilogue! Indeed,
that was quite different function, not related in any way to ours, however, it has exactly the same epilogue (probably because,
it hold 5 local variables too (5∗4 = 0x14)). Also it is located nearby (take a look at the addresses). Indeed, it doesn’t matter
which epilogue gets executed, if it works just as we need. Apparently, Keil decides to reuse a part of another function to
economize. The epilogue takes 4 bytes while jump —only 2.
368
CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE
ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
Listing 21.22: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
var_C = -0xC
PUSH {R7,LR}
MOV R7, SP
SUB SP, SP, #4
MOV R9, R1 ; b
MOV R1, R0 ; a
MOVW R0, #0xF10 ; "a=%d; b=%d; c=%d; d=%dn"
SXTB R1, R1 ; prepare a
MOVT.W R0, #0
STR R3, [SP,#0xC+var_C] ; place d to stack for printf()
ADD R0, PC ; format-string
SXTB R3, R2 ; prepare c
MOV R2, R9 ; b
BLX _printf
ADD SP, SP, #4
POP {R7,PC}
SXTB (Signed Extend Byte) is analogous to MOVSX in x86. All the rest —just the same.
21.4.3 MIPS
Listing 21.23: Optimizing GCC 4.4.5 (IDA)
1 f:
2
3 var_18 = -0x18
4 var_10 = -0x10
5 var_4 = -4
6 arg_0 = 0
7 arg_4 = 4
8 arg_8 = 8
9 arg_C = 0xC
10
11 ; $a0=s.a
12 ; $a1=s.b
13 ; $a2=s.c
14 ; $a3=s.d
15 lui $gp, (__gnu_local_gp >> 16)
16 addiu $sp, -0x28
17 la $gp, (__gnu_local_gp & 0xFFFF)
18 sw $ra, 0x28+var_4($sp)
19 sw $gp, 0x28+var_10($sp)
20 ; prepare byte from 32-bit big-endian integer:
21 sra $t0, $a0, 24
22 move $v1, $a1
23 ; prepare byte from 32-bit big-endian integer:
24 sra $v0, $a2, 24
25 lw $t9, (printf & 0xFFFF)($gp)
26 sw $a0, 0x28+arg_0($sp)
27 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%dn"
28 sw $a3, 0x28+var_18($sp)
29 sw $a1, 0x28+arg_4($sp)
30 sw $a2, 0x28+arg_8($sp)
31 sw $a3, 0x28+arg_C($sp)
32 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%dn"
33 move $a1, $t0
34 move $a2, $v1
35 jalr $t9
36 move $a3, $v0 ; branch delay slot
37 lw $ra, 0x28+var_4($sp)
38 or $at, $zero ; load delay slot, NOP
39 jr $ra
40 addiu $sp, 0x28 ; branch delay slot
41
42 $LC0: .ascii "a=%d; b=%d; c=%d; d=%dn"<0>
369
CHAPTER 21. STRUCTURES 21.5. NESTED STRUCTURES
Structure fields come in registers $A0..$A3 and then get reshuffled into $A1..$A4 for printf(). But there are two SRA
(“Shift Word Right Arithmetic”) instructions, which prepare char fields. Why? MIPS is a big-endian architecture by default 31
on page 453, and the Debian Linux I work in is big-endian too. So when byte variables are stored in 32-bit structure slots,
they occupy the high 31..24 bits. And when a char variable needs to be extended into a 32-bit value, it must be shifted right
by 24 bits. char is a signed type, so an arithmetical shift is used here instead of logical.
21.4.4 One more word
Passing a structure as a function argument (instead of a passing pointer to structure) is the same as passing all structure
fields one by one. If the structure fields are packed by default, the f() function can be rewritten as:
void f(char a, int b, char c, int d)
{
printf ("a=%d; b=%d; c=%d; d=%dn", a, b, c, d);
};
And that leads to the same code.
21.5 Nested structures
Now what about situations when one structure is defined inside of another?
#include <stdio.h>
struct inner_struct
{
int a;
int b;
};
struct outer_struct
{
char a;
int b;
struct inner_struct c;
char d;
int e;
};
void f(struct outer_struct s)
{
printf ("a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%dn",
s.a, s.b, s.c.a, s.c.b, s.d, s.e);
};
int main()
{
struct outer_struct s;
s.a=1;
s.b=2;
s.c.a=100;
s.c.b=101;
s.d=3;
s.e=4;
f(s);
};
… in this case, both inner_struct fields are to be placed between the a,b and d,e fields of the outer_struct.
Let’s compile (MSVC 2010):
Listing 21.24: Optimizing MSVC 2010 /Ob0
$SG2802 DB 'a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d', 0aH, 00H
_TEXT SEGMENT
_s$ = 8
_f PROC
mov eax, DWORD PTR _s$[esp+16]
movsx ecx, BYTE PTR _s$[esp+12]
370
CHAPTER 21. STRUCTURES 21.5. NESTED STRUCTURES
mov edx, DWORD PTR _s$[esp+8]
push eax
mov eax, DWORD PTR _s$[esp+8]
push ecx
mov ecx, DWORD PTR _s$[esp+8]
push edx
movsx edx, BYTE PTR _s$[esp+8]
push eax
push ecx
push edx
push OFFSET $SG2802 ; 'a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d'
call _printf
add esp, 28
ret 0
_f ENDP
_s$ = -24
_main PROC
sub esp, 24
push ebx
push esi
push edi
mov ecx, 2
sub esp, 24
mov eax, esp
mov BYTE PTR _s$[esp+60], 1
mov ebx, DWORD PTR _s$[esp+60]
mov DWORD PTR [eax], ebx
mov DWORD PTR [eax+4], ecx
lea edx, DWORD PTR [ecx+98]
lea esi, DWORD PTR [ecx+99]
lea edi, DWORD PTR [ecx+2]
mov DWORD PTR [eax+8], edx
mov BYTE PTR _s$[esp+76], 3
mov ecx, DWORD PTR _s$[esp+76]
mov DWORD PTR [eax+12], esi
mov DWORD PTR [eax+16], ecx
mov DWORD PTR [eax+20], edi
call _f
add esp, 24
pop edi
pop esi
xor eax, eax
pop ebx
add esp, 24
ret 0
_main ENDP
One curious thing here is that by looking onto this assembly code, we do not even see that another structure was used
inside of it! Thus, we would say, nested structures are unfolded into linear or one-dimensional structure.
Of course, if we replace the struct inner_struct c; declaration with struct inner_struct *c; (thus making
a pointer here) the situation will be quite different.
371
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
21.5.1 OllyDbg
Let’s load the example into OllyDbg and take a look at outer_struct in memory:
Figure 21.5: OllyDbg: Before printf() execution
That’s how the values are located in memory:
• (outer_struct.a) byte 1 + 3 bytes of random garbage;
• (outer_struct.b) 32-bit word 2;
• (inner_struct.a) 32-bit word 0x64 (100);
• (inner_struct.b) 32-bit word 0x65 (101);
• (outer_struct.d) byte 3 + 3 bytes of random garbage;
• (outer_struct.e) 32-bit word 4.
21.6 Bit fields in a structure
21.6.1 CPUID example
The C/C++ language allows to define the exact number of bits for each structure field. It is very useful if one needs to save
memory space. For example, one bit is enough for a bool variable. But of course, it is not rational if speed is important.
Let’s consider the CPUID8
instruction example. This instruction returns information about the current CPU and its features.
If the EAX is set to 1 before the instruction’s execution, CPUID returning this information packed into the EAX register:
3:0 (4 bits) Stepping
7:4 (4 bits) Model
11:8 (4 bits) Family
13:12 (2 bits) Processor Type
19:16 (4 bits) Extended Model
27:20 (8 bits) Extended Family
MSVC 2010 has CPUID macro, but GCC 4.4.1 does not. So let’s make this function by ourselves for GCC with the help of
its built-in assembler9
.
#include <stdio.h>
#ifdef __GNUC__
static inline void cpuid(int code, int *a, int *b, int *c, int *d) {
asm volatile("cpuid":"=a"(*a),"=b"(*b),"=c"(*c),"=d"(*d):"a"(code));
}
#endif
8wikipedia
9More about internal GCC assembler
372
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
#ifdef _MSC_VER
#include <intrin.h>
#endif
struct CPUID_1_EAX
{
unsigned int stepping:4;
unsigned int model:4;
unsigned int family_id:4;
unsigned int processor_type:2;
unsigned int reserved1:2;
unsigned int extended_model_id:4;
unsigned int extended_family_id:8;
unsigned int reserved2:4;
};
int main()
{
struct CPUID_1_EAX *tmp;
int b[4];
#ifdef _MSC_VER
__cpuid(b,1);
#endif
#ifdef __GNUC__
cpuid (1, &b[0], &b[1], &b[2], &b[3]);
#endif
tmp=(struct CPUID_1_EAX *)&b[0];
printf ("stepping=%dn", tmp->stepping);
printf ("model=%dn", tmp->model);
printf ("family_id=%dn", tmp->family_id);
printf ("processor_type=%dn", tmp->processor_type);
printf ("extended_model_id=%dn", tmp->extended_model_id);
printf ("extended_family_id=%dn", tmp->extended_family_id);
return 0;
};
After CPUID fills EAX/EBX/ECX/EDX, these registers are to be written in the b[] array. Then, we have a pointer to the
CPUID_1_EAX structure and we point it to the value in EAX from the b[] array.
In other words, we treat a 32-bit int value as a structure. Then we read from the structure.
MSVC
Let’s compile it in MSVC 2008 with /Ox option:
Listing 21.25: Optimizing MSVC 2008
_b$ = -16 ; size = 16
_main PROC
sub esp, 16
push ebx
xor ecx, ecx
mov eax, 1
cpuid
push esi
lea esi, DWORD PTR _b$[esp+24]
mov DWORD PTR [esi], eax
mov DWORD PTR [esi+4], ebx
mov DWORD PTR [esi+8], ecx
mov DWORD PTR [esi+12], edx
mov esi, DWORD PTR _b$[esp+24]
mov eax, esi
and eax, 15
373
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
push eax
push OFFSET $SG15435 ; 'stepping=%d', 0aH, 00H
call _printf
mov ecx, esi
shr ecx, 4
and ecx, 15
push ecx
push OFFSET $SG15436 ; 'model=%d', 0aH, 00H
call _printf
mov edx, esi
shr edx, 8
and edx, 15
push edx
push OFFSET $SG15437 ; 'family_id=%d', 0aH, 00H
call _printf
mov eax, esi
shr eax, 12
and eax, 3
push eax
push OFFSET $SG15438 ; 'processor_type=%d', 0aH, 00H
call _printf
mov ecx, esi
shr ecx, 16
and ecx, 15
push ecx
push OFFSET $SG15439 ; 'extended_model_id=%d', 0aH, 00H
call _printf
shr esi, 20
and esi, 255
push esi
push OFFSET $SG15440 ; 'extended_family_id=%d', 0aH, 00H
call _printf
add esp, 48
pop esi
xor eax, eax
pop ebx
add esp, 16
ret 0
_main ENDP
The SHR instruction shifting the value in EAX by the number of bits that must be skipped, e.g., we ignore some bits at the
right side.
The AND instruction clears the unneeded bits on the left, or, in other words, leaves only those bits in the EAX register we
need.
374
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
MSVC + OllyDbg
Let’s load our example into OllyDbg and see, what values are set in EAX/EBX/ECX/EDX after the execution of CPUID:
Figure 21.6: OllyDbg: After CPUID execution
EAX has 0x000206A7 (my CPU is Intel Xeon E3-1220).
This is 00000000000000100000011010100111 in binary form.
Here is how the bits are distributed by fields:
field in binary form in decimal form
reserved2 0000 0
extended_family_id 00000000 0
extended_model_id 0010 2
reserved1 00 0
processor_id 00 0
family_id 0110 6
model 1010 10
stepping 0111 7
Figure 21.7: OllyDbg: Result
GCC
Let’s try GCC 4.4.1 with -O3 option.
Listing 21.26: Optimizing GCC 4.4.1
main proc near ; DATA XREF: _start+17
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
push esi
mov esi, 1
375
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
push ebx
mov eax, esi
sub esp, 18h
cpuid
mov esi, eax
and eax, 0Fh
mov [esp+8], eax
mov dword ptr [esp+4], offset aSteppingD ; "stepping=%dn"
mov dword ptr [esp], 1
call ___printf_chk
mov eax, esi
shr eax, 4
and eax, 0Fh
mov [esp+8], eax
mov dword ptr [esp+4], offset aModelD ; "model=%dn"
mov dword ptr [esp], 1
call ___printf_chk
mov eax, esi
shr eax, 8
and eax, 0Fh
mov [esp+8], eax
mov dword ptr [esp+4], offset aFamily_idD ; "family_id=%dn"
mov dword ptr [esp], 1
call ___printf_chk
mov eax, esi
shr eax, 0Ch
and eax, 3
mov [esp+8], eax
mov dword ptr [esp+4], offset aProcessor_type ; "processor_type=%dn"
mov dword ptr [esp], 1
call ___printf_chk
mov eax, esi
shr eax, 10h
shr esi, 14h
and eax, 0Fh
and esi, 0FFh
mov [esp+8], eax
mov dword ptr [esp+4], offset aExtended_model ; "extended_model_id=%dn"
mov dword ptr [esp], 1
call ___printf_chk
mov [esp+8], esi
mov dword ptr [esp+4], offset unk_80486D0
mov dword ptr [esp], 1
call ___printf_chk
add esp, 18h
xor eax, eax
pop ebx
pop esi
mov esp, ebp
pop ebp
retn
main endp
Almost the same. The only thing worth noting is that GCC somehow combines the calculation of extended_model_id
and extended_family_id into one block, instead of calculating them separately before each printf() call.
21.6.2 Working with the float type as with a structure
As we already noted in the section about FPU ( 17 on page 208), both float and double types consist of a sign, a significand
(or fraction) and an exponent. But will we be able to work with these fields directly? Let’s try this with float.
022233031
S exponent mantissa or fraction
( S—sign )
#include <stdio.h>
#include <assert.h>
376
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
#include <stdlib.h>
#include <memory.h>
struct float_as_struct
{
unsigned int fraction : 23; // fractional part
unsigned int exponent : 8; // exponent + 0x3FF
unsigned int sign : 1; // sign bit
};
float f(float in)
{
float f=in;
struct float_as_struct t;
assert (sizeof (struct float_as_struct) == sizeof (float));
memcpy (&t, &f, sizeof (float));
t.sign=1; // set negative sign
t.exponent=t.exponent+2; // multiply d by 2n
(n here is 2)
memcpy (&f, &t, sizeof (float));
return f;
};
int main()
{
printf ("%fn", f(1.234));
};
The float_as_struct structure occupies the same amount of memory as float, i.e., 4 bytes or 32 bits.
Now we are setting the negative sign in the input value and also, by adding 2 to the exponent, we thereby multiply the
whole number by 22
, i.e., by 4.
Let’s compile in MSVC 2008 without optimization turned on:
Listing 21.27: Non-optimizing MSVC 2008
_t$ = -8 ; size = 4
_f$ = -4 ; size = 4
__in$ = 8 ; size = 4
?f@@YAMM@Z PROC ; f
push ebp
mov ebp, esp
sub esp, 8
fld DWORD PTR __in$[ebp]
fstp DWORD PTR _f$[ebp]
push 4
lea eax, DWORD PTR _f$[ebp]
push eax
lea ecx, DWORD PTR _t$[ebp]
push ecx
call _memcpy
add esp, 12
mov edx, DWORD PTR _t$[ebp]
or edx, -2147483648 ; 80000000H - set minus sign
mov DWORD PTR _t$[ebp], edx
mov eax, DWORD PTR _t$[ebp]
shr eax, 23 ; 00000017H - drop significand
and eax, 255 ; 000000ffH - leave here only exponent
add eax, 2 ; add 2 to it
and eax, 255 ; 000000ffH
shl eax, 23 ; 00000017H - shift result to place of bits 30:23
mov ecx, DWORD PTR _t$[ebp]
and ecx, -2139095041 ; 807fffffH - drop exponent
377
CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE
; add original value without exponent with new calculated exponent
or ecx, eax
mov DWORD PTR _t$[ebp], ecx
push 4
lea edx, DWORD PTR _t$[ebp]
push edx
lea eax, DWORD PTR _f$[ebp]
push eax
call _memcpy
add esp, 12
fld DWORD PTR _f$[ebp]
mov esp, ebp
pop ebp
ret 0
?f@@YAMM@Z ENDP ; f
A bit redundant. If it was compiled with /Ox flag there would be no memcpy() call, the f variable is used directly. But
it is easier to understand by looking at the unoptimized version.
What would GCC 4.4.1 with -O3 do?
Listing 21.28: Optimizing GCC 4.4.1
; f(float)
public _Z1ff
_Z1ff proc near
var_4 = dword ptr -4
arg_0 = dword ptr 8
push ebp
mov ebp, esp
sub esp, 4
mov eax, [ebp+arg_0]
or eax, 80000000h ; set minus sig
mov edx, eax
and eax, 807FFFFFh ; leave only significand and exponent in EAX
shr edx, 23 ; prepare exponent
add edx, 2 ; add 2
movzx edx, dl ; clear all bits except 7:0 in EAX
shl edx, 23 ; shift new calculated exponent to its place
or eax, edx ; add new exponent and original value without exponent
mov [ebp+var_4], eax
fld [ebp+var_4]
leave
retn
_Z1ff endp
public main
main proc near
push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
fld ds:dword_8048614 ; -4.936
fstp qword ptr [esp+8]
mov dword ptr [esp+4], offset asc_8048610 ; "%fn"
mov dword ptr [esp], 1
call ___printf_chk
xor eax, eax
leave
retn
main endp
The f() function is almost understandable. However, what is interesting is that GCC was able to calculate the result
of f(1.234) during compilation despite all this hodge-podge with the structure fields and prepared this argument to
printf() as precalculated at compile time!
378
CHAPTER 21. STRUCTURES 21.7. EXERCISES
21.7 Exercises
21.7.1 Exercise #1
Linux x86 (beginners.re)10
Linux MIPS (beginners.re)11
This program for Linux x86 and Linux MIPS opens a file and prints a number. What is this number?
Answer: G.1.12 on page 958.
21.7.2 Exercise #2
This function takes some structure on input and does something. Try to reverse engineer structure field types. Function
contents may be ignored for the moment.
Listing 21.29: Optimizing MSVC 2010
$SG2802 DB '%f', 0aH, 00H
$SG2803 DB '%c, %d', 0aH, 00H
$SG2805 DB 'error #2', 0aH, 00H
$SG2807 DB 'error #1', 0aH, 00H
__real@405ec00000000000 DQ 0405ec00000000000r ; 123
__real@407bc00000000000 DQ 0407bc00000000000r ; 444
_s$ = 8
_f PROC
push esi
mov esi, DWORD PTR _s$[esp]
cmp DWORD PTR [esi], 1000
jle SHORT $LN4@f
cmp DWORD PTR [esi+4], 10
jbe SHORT $LN3@f
fld DWORD PTR [esi+8]
sub esp, 8
fmul QWORD PTR __real@407bc00000000000
fld QWORD PTR [esi+16]
fmul QWORD PTR __real@405ec00000000000
faddp ST(1), ST(0)
fstp QWORD PTR [esp]
push OFFSET $SG2802 ; '%f'
call _printf
movzx eax, BYTE PTR [esi+25]
movsx ecx, BYTE PTR [esi+24]
push eax
push ecx
push OFFSET $SG2803 ; '%c, %d'
call _printf
add esp, 24
pop esi
ret 0
$LN3@f:
pop esi
mov DWORD PTR _s$[esp-4], OFFSET $SG2805 ; 'error #2'
jmp _printf
$LN4@f:
pop esi
mov DWORD PTR _s$[esp-4], OFFSET $SG2807 ; 'error #1'
jmp _printf
_f ENDP
Listing 21.30: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
PUSH {r4-r6,lr}
MOV r4,r0
LDR r0,[r0,#0]
CMP r0,#0x3e8
10GCC 4.8.1 -O3
11GCC 4.4.5 -O3
379
CHAPTER 21. STRUCTURES 21.7. EXERCISES
ADRLE r0,|L0.140|
BLE |L0.132|
LDR r0,[r4,#4]
CMP r0,#0xa
ADRLS r0,|L0.152|
BLS |L0.132|
ADD r0,r4,#0x10
LDM r0,{r0,r1}
LDR r3,|L0.164|
MOV r2,#0
BL __aeabi_dmul
MOV r5,r0
MOV r6,r1
LDR r0,[r4,#8]
LDR r1,|L0.168|
BL __aeabi_fmul
BL __aeabi_f2d
MOV r2,r5
MOV r3,r6
BL __aeabi_dadd
MOV r2,r0
MOV r3,r1
ADR r0,|L0.172|
BL __2printf
LDRB r2,[r4,#0x19]
LDRB r1,[r4,#0x18]
POP {r4-r6,lr}
ADR r0,|L0.176|
B __2printf
|L0.132|
POP {r4-r6,lr}
B __2printf
ENDP
|L0.140|
DCB "error #1n",0
DCB 0
DCB 0
|L0.152|
DCB "error #2n",0
DCB 0
DCB 0
|L0.164|
DCD 0x405ec000
|L0.168|
DCD 0x43de0000
|L0.172|
DCB "%fn",0
|L0.176|
DCB "%c, %dn",0
Listing 21.31: Non-optimizing Keil 6/2013 (thumb mode)
f PROC
PUSH {r4-r6,lr}
MOV r4,r0
LDR r0,[r0,#0]
CMP r0,#0x3e8
ADRLE r0,|L0.140|
BLE |L0.132|
LDR r0,[r4,#4]
CMP r0,#0xa
ADRLS r0,|L0.152|
BLS |L0.132|
ADD r0,r4,#0x10
LDM r0,{r0,r1}
LDR r3,|L0.164|
MOV r2,#0
BL __aeabi_dmul
MOV r5,r0
380
CHAPTER 21. STRUCTURES 21.7. EXERCISES
MOV r6,r1
LDR r0,[r4,#8]
LDR r1,|L0.168|
BL __aeabi_fmul
BL __aeabi_f2d
MOV r2,r5
MOV r3,r6
BL __aeabi_dadd
MOV r2,r0
MOV r3,r1
ADR r0,|L0.172|
BL __2printf
LDRB r2,[r4,#0x19]
LDRB r1,[r4,#0x18]
POP {r4-r6,lr}
ADR r0,|L0.176|
B __2printf
|L0.132|
POP {r4-r6,lr}
B __2printf
ENDP
|L0.140|
DCB "error #1n",0
DCB 0
DCB 0
|L0.152|
DCB "error #2n",0
DCB 0
DCB 0
|L0.164|
DCD 0x405ec000
|L0.168|
DCD 0x43de0000
|L0.172|
DCB "%fn",0
|L0.176|
DCB "%c, %dn",0
Listing 21.32: Optimizing GCC 4.9 (ARM64)
f:
stp x29, x30, [sp, -32]!
add x29, sp, 0
ldr w1, [x0]
str x19, [sp,16]
cmp w1, 1000
ble .L2
ldr w1, [x0,4]
cmp w1, 10
bls .L3
ldr s1, [x0,8]
mov x19, x0
ldr s0, .LC1
adrp x0, .LC0
ldr d2, [x19,16]
add x0, x0, :lo12:.LC0
fmul s1, s1, s0
ldr d0, .LC2
fmul d0, d2, d0
fcvt d1, s1
fadd d0, d1, d0
bl printf
ldrb w1, [x19,24]
adrp x0, .LC3
ldrb w2, [x19,25]
add x0, x0, :lo12:.LC3
ldr x19, [sp,16]
ldp x29, x30, [sp], 32
b printf
381
CHAPTER 21. STRUCTURES 21.7. EXERCISES
.L3:
ldr x19, [sp,16]
adrp x0, .LC4
ldp x29, x30, [sp], 32
add x0, x0, :lo12:.LC4
b puts
.L2:
ldr x19, [sp,16]
adrp x0, .LC5
ldp x29, x30, [sp], 32
add x0, x0, :lo12:.LC5
b puts
.size f, .-f
.LC1:
.word 1138622464
.LC2:
.word 0
.word 1079951360
.LC0:
.string "%fn"
.LC3:
.string "%c, %dn"
.LC4:
.string "error #2"
.LC5:
.string "error #1"
Listing 21.33: Optimizing GCC 4.4.5 (MIPS) (IDA)
f:
var_10 = -0x10
var_8 = -8
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $s0, 0x20+var_8($sp)
sw $gp, 0x20+var_10($sp)
lw $v0, 0($a0)
or $at, $zero
slti $v0, 0x3E9
bnez $v0, loc_C8
move $s0, $a0
lw $v0, 4($a0)
or $at, $zero
sltiu $v0, 0xB
bnez $v0, loc_AC
lui $v0, (dword_134 >> 16)
lwc1 $f4, $LC1
lwc1 $f2, 8($a0)
lui $v0, ($LC2 >> 16)
lwc1 $f0, 0x14($a0)
mul.s $f2, $f4, $f2
lwc1 $f4, dword_134
lwc1 $f1, 0x10($a0)
lwc1 $f5, $LC2
cvt.d.s $f2, $f2
mul.d $f0, $f4, $f0
lw $t9, (printf & 0xFFFF)($gp)
lui $a0, ($LC0 >> 16) # "%fn"
add.d $f4, $f2, $f0
mfc1 $a2, $f5
mfc1 $a3, $f4
jalr $t9
la $a0, ($LC0 & 0xFFFF) # "%fn"
lw $gp, 0x20+var_10($sp)
lbu $a2, 0x19($s0)
382
CHAPTER 21. STRUCTURES 21.7. EXERCISES
lb $a1, 0x18($s0)
lui $a0, ($LC3 >> 16) # "%c, %dn"
lw $t9, (printf & 0xFFFF)($gp)
lw $ra, 0x20+var_4($sp)
lw $s0, 0x20+var_8($sp)
la $a0, ($LC3 & 0xFFFF) # "%c, %dn"
jr $t9
addiu $sp, 0x20
loc_AC: # CODE XREF: f+38
lui $a0, ($LC4 >> 16) # "error #2"
lw $t9, (puts & 0xFFFF)($gp)
lw $ra, 0x20+var_4($sp)
lw $s0, 0x20+var_8($sp)
la $a0, ($LC4 & 0xFFFF) # "error #2"
jr $t9
addiu $sp, 0x20
loc_C8: # CODE XREF: f+24
lui $a0, ($LC5 >> 16) # "error #1"
lw $t9, (puts & 0xFFFF)($gp)
lw $ra, 0x20+var_4($sp)
lw $s0, 0x20+var_8($sp)
la $a0, ($LC5 & 0xFFFF) # "error #1"
jr $t9
addiu $sp, 0x20
$LC0: .ascii "%fn"<0>
$LC3: .ascii "%c, %dn"<0>
$LC4: .ascii "error #2"<0>
$LC5: .ascii "error #1"<0>
.data # .rodata.cst4
$LC1: .word 0x43DE0000
.data # .rodata.cst8
$LC2: .word 0x405EC000
dword_134: .word 0
Answer: G.1.12 on page 958.
383
CHAPTER 22. UNIONS
Chapter 22
Unions
22.1 Pseudo-random number generator example
If we need float random numbers between 0 and 1, the simplest thing is to use a PRNG like the Mersenne twister. It
produces random 32-bit values in DWORD form. Then we can transform this value to float and then divide it by RAND_MAX
(0xFFFFFFFF in our case) — we getting a value in the 0..1 interval.
But as we know, division is slow. Also, we would like to issue as few FPU operations as possible. Can we get rid of the
division?
Let’s recall what a floating point number consists of: sign bit, significand bits and exponent bits. We just need to store
random bits in all significand bits to get a random float number!
The exponent cannot be zero (the number is denormalized in this case), so we are storing 01111111 to exponent —this
means that the exponent is 1. Then we filling the significand with random bits, set the sign bit to 0 (which means a positive
number) and voilà. The generated numbers is to be between 1 and 2, so we must also subtract 1.
A very simple linear congruential random numbers generator is used in my example1
, it produces 32-bit numbers. The
PRNG is initialized with the current time in UNIX timestamp format.
Here we represent the float type as an union —it is the C/C++ construction that enables us to interpret a piece of memory
as different types. In our case, we are able to create a variable of type union and then access to it as it is float or as it is
uint32_t. It can be said, it is just a hack. A dirty one.
The integer PRNG code is the same as we already considered: 20 on page 344. So this code in compiled form is omitted.
#include <stdio.h>
#include <stdint.h>
#include <time.h>
// integer PRNG definitions, data and routines:
// constants from the Numerical Recipes book
const uint32_t RNG_a=1664525;
const uint32_t RNG_c=1013904223;
uint32_t RNG_state; // global variable
void my_srand(uint32_t i)
{
RNG_state=i;
};
uint32_t my_rand()
{
RNG_state=RNG_state*RNG_a+RNG_c;
return RNG_state;
};
// FPU PRNG definitions and routines:
union uint32_t_float
{
uint32_t i;
float f;
};
float float_rand()
{
1the idea was taken from: http://go.yurichev.com/17308
384
CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE
union uint32_t_float tmp;
tmp.i=my_rand() & 0x007fffff | 0x3F800000;
return tmp.f-1;
};
// test
int main()
{
my_srand(time(NULL)); // PRNG initialization
for (int i=0; i<100; i++)
printf ("%fn", float_rand());
return 0;
};
22.1.1 x86
Listing 22.1: Optimizing MSVC 2010
$SG4238 DB '%f', 0aH, 00H
__real@3ff0000000000000 DQ 03ff0000000000000r ; 1
tv130 = -4
_tmp$ = -4
?float_rand@@YAMXZ PROC
push ecx
call ?my_rand@@YAIXZ
; EAX=pseudorandom value
and eax, 8388607 ; 007fffffH
or eax, 1065353216 ; 3f800000H
; EAX=pseudorandom value & 0x007fffff | 0x3f800000
; store it into local stack:
mov DWORD PTR _tmp$[esp+4], eax
; reload it as float point number:
fld DWORD PTR _tmp$[esp+4]
; subtract 1.0:
fsub QWORD PTR __real@3ff0000000000000
; store value we got into local stack and reload it:
fstp DWORD PTR tv130[esp+4] ;  these instructions are redundant
fld DWORD PTR tv130[esp+4] ; /
pop ecx
ret 0
?float_rand@@YAMXZ ENDP
_main PROC
push esi
xor eax, eax
call _time
push eax
call ?my_srand@@YAXI@Z
add esp, 4
mov esi, 100
$LL3@main:
call ?float_rand@@YAMXZ
sub esp, 8
fstp QWORD PTR [esp]
push OFFSET $SG4238
call _printf
add esp, 12
dec esi
jne SHORT $LL3@main
xor eax, eax
pop esi
ret 0
_main ENDP
385
CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE
Function names are so strange here because I compiled this example as C++ and this is name mangling in C++, we will
talk about it later: 51.1.1 on page 541.
If we compile this in MSVC 2012, it uses the SIMD instructions for the FPU, read more about it here: 27.5 on page 444.
22.1.2 MIPS
Listing 22.2: Optimizing GCC 4.4.5
float_rand:
var_10 = -0x10
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
; call my_rand():
jal my_rand
or $at, $zero ; branch delay slot, NOP
; $v0=32-bit pseudorandom value
li $v1, 0x7FFFFF
; $v1=0x7FFFFF
and $v1, $v0, $v1
; $v1=pseudorandom value & 0x7FFFFF
lui $a0, 0x3F80
; $a0=0x3F800000
or $v1, $a0
; $v1=pseudorandom value & 0x7FFFFF | 0x3F800000
; I still dont get matter of the following instruction:'
lui $v0, ($LC0 >> 16)
; load 1.0 into $f0:
lwc1 $f0, $LC0
; move value from $v1 to coprocessor 1 (into register $f2)
; it behaves like bitwise copy, no conversion done:
mtc1 $v1, $f2
lw $ra, 0x20+var_4($sp)
; subtract 1.0. leave result in $f0:
sub.s $f0, $f2, $f0
jr $ra
addiu $sp, 0x20 ; branch delay slot
main:
var_18 = -0x18
var_10 = -0x10
var_C = -0xC
var_8 = -8
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x28
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x28+var_4($sp)
sw $s2, 0x28+var_8($sp)
sw $s1, 0x28+var_C($sp)
sw $s0, 0x28+var_10($sp)
sw $gp, 0x28+var_18($sp)
lw $t9, (time & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jalr $t9
move $a0, $zero ; branch delay slot
lui $s2, ($LC1 >> 16) # "%fn"
move $a0, $v0
la $s2, ($LC1 & 0xFFFF) # "%fn"
move $s0, $zero
jal my_srand
li $s1, 0x64 # 'd' ; branch delay slot
386
CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE
loc_104:
jal float_rand
addiu $s0, 1
lw $gp, 0x28+var_18($sp)
; convert value we got from float_rand() to double type (printf() need it):
cvt.d.s $f2, $f0
lw $t9, (printf & 0xFFFF)($gp)
mfc1 $a3, $f2
mfc1 $a2, $f3
jalr $t9
move $a0, $s2
bne $s0, $s1, loc_104
move $v0, $zero
lw $ra, 0x28+var_4($sp)
lw $s2, 0x28+var_8($sp)
lw $s1, 0x28+var_C($sp)
lw $s0, 0x28+var_10($sp)
jr $ra
addiu $sp, 0x28 ; branch delay slot
$LC1: .ascii "%fn"<0>
$LC0: .float 1.0
There is also an useless LUI instruction added for some weird reason. We considered this artifact earlier: 17.5.6 on
page 219.
22.1.3 ARM (ARM mode)
Listing 22.3: Optimizing GCC 4.6.3 (IDA)
float_rand
STMFD SP!, {R3,LR}
BL my_rand
; R0=pseudorandom value
FLDS S0, =1.0
; S0=1.0
BIC R3, R0, #0xFF000000
BIC R3, R3, #0x800000
ORR R3, R3, #0x3F800000
; R3=pseudorandom value & 0x007fffff | 0x3f800000
; copy from R3 to FPU (register S15).
; it behaves like bitwise copy, no conversion done:
FMSR S15, R3
; subtract 1.0 and leave result in S0:
FSUBS S0, S15, S0
LDMFD SP!, {R3,PC}
flt_5C DCFS 1.0
main
STMFD SP!, {R4,LR}
MOV R0, #0
BL time
BL my_srand
MOV R4, #0x64 ; 'd'
loc_78
BL float_rand
; S0=pseudorandom value
LDR R0, =aF ; "%f"
; convert float type value into double type value (printf() will need it):
FCVTDS D7, S0
; bitwise copy from D7 into R2/R3 pair of registers (for printf()):
FMRRD R2, R3, D7
BL printf
SUBS R4, R4, #1
BNE loc_78
MOV R0, R4
387
CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON
LDMFD SP!, {R4,PC}
aF DCB "%f",0xA,0
I also made a dump in objdump and I saw that the FPU instructions have different names than in IDA. Apparently, IDA
and binutils developers used different manuals? I suppose, it would be good to know both instruction name variants.
Listing 22.4: Optimizing GCC 4.6.3 (objdump)
00000038 <float_rand>:
38: e92d4008 push {r3, lr}
3c: ebfffffe bl 10 <my_rand>
40: ed9f0a05 vldr s0, [pc, #20] ; 5c <float_rand+0x24>
44: e3c034ff bic r3, r0, #-16777216 ; 0xff000000
48: e3c33502 bic r3, r3, #8388608 ; 0x800000
4c: e38335fe orr r3, r3, #1065353216 ; 0x3f800000
50: ee073a90 vmov s15, r3
54: ee370ac0 vsub.f32 s0, s15, s0
58: e8bd8008 pop {r3, pc}
5c: 3f800000 svccc 0x00800000
00000000 <main>:
0: e92d4010 push {r4, lr}
4: e3a00000 mov r0, #0
8: ebfffffe bl 0 <time>
c: ebfffffe bl 0 <main>
10: e3a04064 mov r4, #100 ; 0x64
14: ebfffffe bl 38 <main+0x38>
18: e59f0018 ldr r0, [pc, #24] ; 38 <main+0x38>
1c: eeb77ac0 vcvt.f64.f32 d7, s0
20: ec532b17 vmov r2, r3, d7
24: ebfffffe bl 0 <printf>
28: e2544001 subs r4, r4, #1
2c: 1afffff8 bne 14 <main+0x14>
30: e1a00004 mov r0, r4
34: e8bd8010 pop {r4, pc}
38: 00000000 andeq r0, r0, r0
The instructions at 5c in float_rand() and at 38 in main() are random noise.
22.2 Calculating machine epsilon
The machine epsilon is the smallest possible value the FPU can work with. The more bits allocated for floating point
number, the smaller the machine epsilon. It is 2−23
= 1.19e − 07 for float and 2−52
= 2.22e − 16 for double.
It’s interesting, how easy it’s to calculate the machine epsilon:
#include <stdio.h>
#include <stdint.h>
union uint_float
{
uint32_t i;
float f;
};
float calculate_machine_epsilon(float start)
{
union uint_float v;
v.f=start;
v.i++;
return v.f-start;
}
void main()
{
printf ("%gn", calculate_machine_epsilon(1.234567));
};
388
CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON
What we do here is just treat the fraction part of the IEEE 754 number as integer and add 1 to it. The resulting floating
number is equal to starting_value + machine_epsilon, so we just need to subtract the starting value (using floating point
arithmetic) to measure, what difference one bit reflects in the single precision (float).
The union serves here as a way to access IEEE 754 number as a regular integer. Adding 1 to it in fact adds 1 to the
fraction part of the number, however, needless to say, overflow is possible, which will add another 1 to the exponent part.
22.2.1 x86
Listing 22.5: Optimizing MSVC 2010
tv130 = 8
_v$ = 8
_start$ = 8
_calculate_machine_epsilon PROC
fld DWORD PTR _start$[esp-4]
fst DWORD PTR _v$[esp-4] ; this instruction is redundant
inc DWORD PTR _v$[esp-4]
fsubr DWORD PTR _v$[esp-4]
fstp DWORD PTR tv130[esp-4] ;  this instruction pair is also redundant
fld DWORD PTR tv130[esp-4] ; /
ret 0
_calculate_machine_epsilon ENDP
The second FST instruction is redundant: there is no need to store the input value in the same place (the compiler decided
to allocate the v variable at the same point in the local stack as the input argument).
Then it is incremented with INC, as it is a normal integer variable. Then it is loaded into the FPU as a 32-bit IEEE 754
number, FSUBR does the rest of job and the resulting value is stored in ST0.
The last FSTP/FLD instruction pair is redundant, but the compiler didn’t optimize it out.
22.2.2 ARM64
Let’s extend our example to 64-bit:
#include <stdio.h>
#include <stdint.h>
typedef union
{
uint64_t i;
double d;
} uint_double;
double calculate_machine_epsilon(double start)
{
uint_double v;
v.d=start;
v.i++;
return v.d-start;
}
void main()
{
printf ("%gn", calculate_machine_epsilon(1.234567));
};
ARM64 has no instruction that can add a number to a FPU D-register, so the input value (that came in D0) is first copied
into GPR, incremented, copied to FPU register D1, and then subtraction occurs.
Listing 22.6: Optimizing GCC 4.9 ARM64
calculate_machine_epsilon:
fmov x0, d0 ; load input value of double type into X0
add x0, x0, 1 ; X0++
fmov d1, x0 ; move it to FPU register
fsub d0, d1, d0 ; subtract
ret
See also this example compiled for x64 with SIMD instructions: 27.4 on page 443.
389
CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON
22.2.3 MIPS
The new instruction here is MTC1 (“Move To Coprocessor 1”), it just transfers data from GPR to the FPU’s registers.
Listing 22.7: Optimizing GCC 4.4.5 (IDA)
calculate_machine_epsilon:
mfc1 $v0, $f12
or $at, $zero ; NOP
addiu $v1, $v0, 1
mtc1 $v1, $f2
jr $ra
sub.s $f0, $f2, $f12 ; branch delay slot
22.2.4 Conclusion
It’s hard to say whether someone may need this trickery in real-world code, but as I write many times in this book, this
example serves well for explaining the IEEE 754 format and unions in C/C++.
390
CHAPTER 23. POINTERS TO FUNCTIONS
Chapter 23
Pointers to functions
A pointer to a function, as any other pointer, is just the address of the function’s start in its code segment.
They are often used as callbacks 1
.
Well-known examples are:
• qsort()2
, atexit()3
from the standard C library;
• *NIX OS signals4
;
• thread starting: CreateThread() (win32), pthread_create() (POSIX);
• lots of win32 functions, like EnumChildWindows()5
.
• lots of places in the Linux kernel, for example the filesystem driver functions are called via callbacks: http://go.
yurichev.com/17076
• The GCC plugin functions are also called via callbacks: http://go.yurichev.com/17077
• Another example of function pointers is a table in the “dwm” Linux window manager that defines shortcuts. Each
shortcut has a corresponding function to call if a specific key is pressed:
GitHub
As we can see, such table is easier to handle than a large switch() statement.
So, the qsort() function is an implementation of quicksort in the C/C++ standard library. The functions is able to sort
anything, any type of data, as long as you have a function to compare these two elements and qsort() is able to call it.
The comparison function can be defined as:
int (*compare)(const void *, const void *)
Let’s use a slightly modified example I found here:
1 /* ex3 Sorting ints with qsort */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 int comp(const void * _a, const void * _b)
7 {
8 const int *a=(const int *)_a;
9 const int *b=(const int *)_b;
10
11 if (*a==*b)
12 return 0;
13 else
14 if (*a < *b)
15 return -1;
16 else
17 return 1;
18 }
19
20 int main(int argc, char* argv[])
1wikipedia
2wikipedia
3http://go.yurichev.com/17073
4wikipedia
5MSDN
391
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
21 {
22 int numbers[10]={1892,45,200,-98,4087,5,-12345,1087,88,-100000};
23 int i;
24
25 /* Sort the array */
26 qsort(numbers,10,sizeof(int),comp) ;
27 for (i=0;i<9;i++)
28 printf("Number = %dn",numbers[ i ]) ;
29 return 0;
30 }
23.1 MSVC
Let’s compile it in MSVC 2010 (I omitted some parts for the sake of brevity) with /Ox option:
Listing 23.1: Optimizing MSVC 2010: /GS- /MD
__a$ = 8 ; size = 4
__b$ = 12 ; size = 4
_comp PROC
mov eax, DWORD PTR __a$[esp-4]
mov ecx, DWORD PTR __b$[esp-4]
mov eax, DWORD PTR [eax]
mov ecx, DWORD PTR [ecx]
cmp eax, ecx
jne SHORT $LN4@comp
xor eax, eax
ret 0
$LN4@comp:
xor edx, edx
cmp eax, ecx
setge dl
lea eax, DWORD PTR [edx+edx-1]
ret 0
_comp ENDP
_numbers$ = -40 ; size = 40
_argc$ = 8 ; size = 4
_argv$ = 12 ; size = 4
_main PROC
sub esp, 40 ; 00000028H
push esi
push OFFSET _comp
push 4
lea eax, DWORD PTR _numbers$[esp+52]
push 10 ; 0000000aH
push eax
mov DWORD PTR _numbers$[esp+60], 1892 ; 00000764H
mov DWORD PTR _numbers$[esp+64], 45 ; 0000002dH
mov DWORD PTR _numbers$[esp+68], 200 ; 000000c8H
mov DWORD PTR _numbers$[esp+72], -98 ; ffffff9eH
mov DWORD PTR _numbers$[esp+76], 4087 ; 00000ff7H
mov DWORD PTR _numbers$[esp+80], 5
mov DWORD PTR _numbers$[esp+84], -12345 ; ffffcfc7H
mov DWORD PTR _numbers$[esp+88], 1087 ; 0000043fH
mov DWORD PTR _numbers$[esp+92], 88 ; 00000058H
mov DWORD PTR _numbers$[esp+96], -100000 ; fffe7960H
call _qsort
add esp, 16 ; 00000010H
...
Nothing surprising so far. As a fourth argument, the address of label _comp is passed, which is just a place where comp()
is located, or, in other words, the address of the very first instruction of that function.
How does qsort() call it?
Let’s take a look at this function, located in MSVCR80.DLL (a MSVC DLL module with C standard library functions):
392
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
Listing 23.2: MSVCR80.DLL
.text:7816CBF0 ; void __cdecl qsort(void *, unsigned int, unsigned int, int (__cdecl *)(const ⤦
void *, const void *))
.text:7816CBF0 public _qsort
.text:7816CBF0 _qsort proc near
.text:7816CBF0
.text:7816CBF0 lo = dword ptr -104h
.text:7816CBF0 hi = dword ptr -100h
.text:7816CBF0 var_FC = dword ptr -0FCh
.text:7816CBF0 stkptr = dword ptr -0F8h
.text:7816CBF0 lostk = dword ptr -0F4h
.text:7816CBF0 histk = dword ptr -7Ch
.text:7816CBF0 base = dword ptr 4
.text:7816CBF0 num = dword ptr 8
.text:7816CBF0 width = dword ptr 0Ch
.text:7816CBF0 comp = dword ptr 10h
.text:7816CBF0
.text:7816CBF0 sub esp, 100h
....
.text:7816CCE0 loc_7816CCE0: ; CODE XREF: _qsort+B1
.text:7816CCE0 shr eax, 1
.text:7816CCE2 imul eax, ebp
.text:7816CCE5 add eax, ebx
.text:7816CCE7 mov edi, eax
.text:7816CCE9 push edi
.text:7816CCEA push ebx
.text:7816CCEB call [esp+118h+comp]
.text:7816CCF2 add esp, 8
.text:7816CCF5 test eax, eax
.text:7816CCF7 jle short loc_7816CD04
comp— is the fourth function argument. Here the control gets passed to the address in the comp argument. Before it,
two arguments are prepared for comp(). Its result is checked after its execution.
That’s why it is dangerous to use pointers to functions. First of all, if you call qsort() with an incorrect function pointer,
qsort() may pass control flow to an incorrect point, the process may crash and this bug will be hard to find.
The second reason is that the callback function types must comply strictly, calling the wrong function with wrong ar-
guments of wrong types may lead to serious problems, however, the crashing of the process is not a problem here —the
problem is how to determine the reason for the crash —because the compiler may be silent about the potential problems
while compiling.
393
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
23.1.1 MSVC + OllyDbg
Let’s load our example into OllyDbg and set a breakpoint on comp().
We can see how the values are compared at the first comp() call:
Figure 23.1: OllyDbg: first call of comp()
OllyDbg shows the compared values in the window under the code window, for convenience. We can also see that the
SP points to RA , where the qsort() function is (located in MSVCR100.DLL).
394
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
By tracing (F8) until the RETN instruction and pressing F8 one more time, we return to the qsort() function:
Figure 23.2: OllyDbg: the code in qsort() right after comp() call
That was a call to the comparison function.
395
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
Here is also a screenshot of the moment of the second call of comp()— now values that have to be compared are
different:
Figure 23.3: OllyDbg: second call of comp()
23.1.2 MSVC + tracer
Let’s also see which pairs are compared. These 10 numbers are being sorted: 1892, 45, 200, -98, 4087, 5, -12345, 1087, 88,
-100000.
I got the address of the first CMP instruction in comp(), it is 0x0040100C and I’ve set a breakpoint on it:
tracer.exe -l:17_1.exe bpx=17_1.exe!0x0040100C
Now I get some information about the registers at the breakpoint:
PID=4336|New process 17_1.exe
(0) 17_1.exe!0x40100c
EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000
ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c
EIP=0x0028100c
FLAGS=IF
(0) 17_1.exe!0x40100c
EAX=0x00000005 EBX=0x0051f7c8 ECX=0xfffe7960 EDX=0x00000000
ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c
EIP=0x0028100c
FLAGS=PF ZF IF
(0) 17_1.exe!0x40100c
EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000
ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c
EIP=0x0028100c
FLAGS=CF PF ZF IF
...
I’ve filtered out EAX and ECX and gotten:
EAX=0x00000764 ECX=0x00000005
EAX=0x00000005 ECX=0xfffe7960
EAX=0x00000764 ECX=0x00000005
EAX=0x0000002d ECX=0x00000005
EAX=0x00000058 ECX=0x00000005
EAX=0x0000043f ECX=0x00000005
EAX=0xffffcfc7 ECX=0x00000005
EAX=0x000000c8 ECX=0x00000005
EAX=0xffffff9e ECX=0x00000005
EAX=0x00000ff7 ECX=0x00000005
EAX=0x00000ff7 ECX=0x00000005
EAX=0xffffff9e ECX=0x00000005
EAX=0xffffff9e ECX=0x00000005
EAX=0xffffcfc7 ECX=0xfffe7960
EAX=0x00000005 ECX=0xffffcfc7
396
CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC
EAX=0xffffff9e ECX=0x00000005
EAX=0xffffcfc7 ECX=0xfffe7960
EAX=0xffffff9e ECX=0xffffcfc7
EAX=0xffffcfc7 ECX=0xfffe7960
EAX=0x000000c8 ECX=0x00000ff7
EAX=0x0000002d ECX=0x00000ff7
EAX=0x0000043f ECX=0x00000ff7
EAX=0x00000058 ECX=0x00000ff7
EAX=0x00000764 ECX=0x00000ff7
EAX=0x000000c8 ECX=0x00000764
EAX=0x0000002d ECX=0x00000764
EAX=0x0000043f ECX=0x00000764
EAX=0x00000058 ECX=0x00000764
EAX=0x000000c8 ECX=0x00000058
EAX=0x0000002d ECX=0x000000c8
EAX=0x0000043f ECX=0x000000c8
EAX=0x000000c8 ECX=0x00000058
EAX=0x0000002d ECX=0x000000c8
EAX=0x0000002d ECX=0x00000058
That’s 34 pairs. Therefore, the quick sort algorithm needs 34 comparison operations to sort these 10 numbers.
397
CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC
23.1.3 MSVC + tracer (code coverage)
We can also use the tracer’s feature to collect all possible register values and show them in IDA.
Let’s trace all instructions in comp():
tracer.exe -l:17_1.exe bpf=17_1.exe!0x00401000,trace:cc
We get an .idc-script for loading into IDA and load it:
Figure 23.4: tracer and IDA. N.B.: some values are cut at right
IDA gave the function a name (PtFuncCompare) — because IDA sees that the pointer to this function is passed to qsort().
We see that the a and b pointers are pointing to various places in the array, but the step between them is 4, as 32-bit
values are stored in the array.
We see that the instructions at 0x401010 and 0x401012 were never executed (so they left as white): indeed, comp()
has never returned 0, because there no equal elements in the array.
23.2 GCC
Not a big difference:
Listing 23.3: GCC
lea eax, [esp+40h+var_28]
mov [esp+40h+var_40], eax
mov [esp+40h+var_28], 764h
mov [esp+40h+var_24], 2Dh
mov [esp+40h+var_20], 0C8h
mov [esp+40h+var_1C], 0FFFFFF9Eh
mov [esp+40h+var_18], 0FF7h
mov [esp+40h+var_14], 5
mov [esp+40h+var_10], 0FFFFCFC7h
mov [esp+40h+var_C], 43Fh
mov [esp+40h+var_8], 58h
mov [esp+40h+var_4], 0FFFE7960h
mov [esp+40h+var_34], offset comp
mov [esp+40h+var_38], 4
mov [esp+40h+var_3C], 0Ah
call _qsort
comp() function:
public comp
comp proc near
398
CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC
arg_0 = dword ptr 8
arg_4 = dword ptr 0Ch
push ebp
mov ebp, esp
mov eax, [ebp+arg_4]
mov ecx, [ebp+arg_0]
mov edx, [eax]
xor eax, eax
cmp [ecx], edx
jnz short loc_8048458
pop ebp
retn
loc_8048458:
setnl al
movzx eax, al
lea eax, [eax+eax-1]
pop ebp
retn
comp endp
The implementation of qsort() is located in libc.so.6 and it is in fact just a wrapper 6
for qsort_r().
In turn, it is calling quicksort(), where our defined function is called via a passed pointer:
Listing 23.4: (file libc.so.6, glibc version—2.10.1)
.text:0002DDF6 mov edx, [ebp+arg_10]
.text:0002DDF9 mov [esp+4], esi
.text:0002DDFD mov [esp], edi
.text:0002DE00 mov [esp+8], edx
.text:0002DE04 call [ebp+arg_C]
...
23.2.1 GCC + GDB (with source code)
Obviously, we have the C-source code of our example ( 23 on page 391), so we can set a breakpoint (b) on line number
(11—the line where the first comparison occurs). We also need to compile the example with debugging information included
(-g), so the table with addresses and corresponding line numbers is present. We can also print values using variable names
(p): the debugging information also has tells us which register and/or local stack element contains which variable.
We can also see the stack (bt) and find out that there is some intermediate function msort_with_tmp() used in Glibc.
Listing 23.5: GDB session
dennis@ubuntuvm:~/polygon$ gcc 17_1.c -g
dennis@ubuntuvm:~/polygon$ gdb ./a.out
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dennis/polygon/a.out...done.
(gdb) b 17_1.c:11
Breakpoint 1 at 0x804845f: file 17_1.c, line 11.
(gdb) run
Starting program: /home/dennis/polygon/./a.out
Breakpoint 1, comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11
11 if (*a==*b)
(gdb) p *a
$1 = 1892
(gdb) p *b
$2 = 45
6a concept like thunk function
399
CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC
(gdb) c
Continuing.
Breakpoint 1, comp (_a=0xbffff104, _b=_b@entry=0xbffff108) at 17_1.c:11
11 if (*a==*b)
(gdb) p *a
$3 = -98
(gdb) p *b
$4 = 4087
(gdb) bt
#0 comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11
#1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2)
at msort.c:65
#2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53
#4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53
#6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d <⤦
comp>,
arg=arg@entry=0x0) at msort.c:297
#8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307
#9 0x0804850d in main (argc=1, argv=0xbffff1c4) at 17_1.c:26
(gdb)
23.2.2 GCC + GDB (no source code)
But often there is no source code at all, so we can disassemble the comp() function (disas), find the very first CMP
instruction and set a breakpoint (b) at that address. At each breakpoint, we are going to dump all register contents (info
registers). The stack information is also available (bt), but partially: there is no line number information for comp().
Listing 23.6: GDB session
dennis@ubuntuvm:~/polygon$ gcc 17_1.c
dennis@ubuntuvm:~/polygon$ gdb ./a.out
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dennis/polygon/a.out...(no debugging symbols found)...done.
(gdb) set disassembly-flavor intel
(gdb) disas comp
Dump of assembler code for function comp:
0x0804844d <+0>: push ebp
0x0804844e <+1>: mov ebp,esp
0x08048450 <+3>: sub esp,0x10
0x08048453 <+6>: mov eax,DWORD PTR [ebp+0x8]
0x08048456 <+9>: mov DWORD PTR [ebp-0x8],eax
0x08048459 <+12>: mov eax,DWORD PTR [ebp+0xc]
0x0804845c <+15>: mov DWORD PTR [ebp-0x4],eax
0x0804845f <+18>: mov eax,DWORD PTR [ebp-0x8]
0x08048462 <+21>: mov edx,DWORD PTR [eax]
0x08048464 <+23>: mov eax,DWORD PTR [ebp-0x4]
0x08048467 <+26>: mov eax,DWORD PTR [eax]
0x08048469 <+28>: cmp edx,eax
0x0804846b <+30>: jne 0x8048474 <comp+39>
0x0804846d <+32>: mov eax,0x0
0x08048472 <+37>: jmp 0x804848e <comp+65>
0x08048474 <+39>: mov eax,DWORD PTR [ebp-0x8]
0x08048477 <+42>: mov edx,DWORD PTR [eax]
0x08048479 <+44>: mov eax,DWORD PTR [ebp-0x4]
0x0804847c <+47>: mov eax,DWORD PTR [eax]
0x0804847e <+49>: cmp edx,eax
0x08048480 <+51>: jge 0x8048489 <comp+60>
400
CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC
0x08048482 <+53>: mov eax,0xffffffff
0x08048487 <+58>: jmp 0x804848e <comp+65>
0x08048489 <+60>: mov eax,0x1
0x0804848e <+65>: leave
0x0804848f <+66>: ret
End of assembler dump.
(gdb) b *0x08048469
Breakpoint 1 at 0x8048469
(gdb) run
Starting program: /home/dennis/polygon/./a.out
Breakpoint 1, 0x08048469 in comp ()
(gdb) info registers
eax 0x2d 45
ecx 0xbffff0f8 -1073745672
edx 0x764 1892
ebx 0xb7fc0000 -1208221696
esp 0xbfffeeb8 0xbfffeeb8
ebp 0xbfffeec8 0xbfffeec8
esi 0xbffff0fc -1073745668
edi 0xbffff010 -1073745904
eip 0x8048469 0x8048469 <comp+28>
eflags 0x286 [ PF SF IF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb) c
Continuing.
Breakpoint 1, 0x08048469 in comp ()
(gdb) info registers
eax 0xff7 4087
ecx 0xbffff104 -1073745660
edx 0xffffff9e -98
ebx 0xb7fc0000 -1208221696
esp 0xbfffee58 0xbfffee58
ebp 0xbfffee68 0xbfffee68
esi 0xbffff108 -1073745656
edi 0xbffff010 -1073745904
eip 0x8048469 0x8048469 <comp+28>
eflags 0x282 [ SF IF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
(gdb) c
Continuing.
Breakpoint 1, 0x08048469 in comp ()
(gdb) info registers
eax 0xffffff9e -98
ecx 0xbffff100 -1073745664
edx 0xc8 200
ebx 0xb7fc0000 -1208221696
esp 0xbfffeeb8 0xbfffeeb8
ebp 0xbfffeec8 0xbfffeec8
esi 0xbffff104 -1073745660
edi 0xbffff010 -1073745904
eip 0x8048469 0x8048469 <comp+28>
eflags 0x286 [ PF SF IF ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
401
CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC
gs 0x33 51
(gdb) bt
#0 0x08048469 in comp ()
#1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2)
at msort.c:65
#2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53
#4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53
#6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45
#7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d <⤦
comp>,
arg=arg@entry=0x0) at msort.c:297
#8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307
#9 0x0804850d in main ()
402
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT
Chapter 24
64-bit values in 32-bit environment
In a 32-bit environment, GPR’s are 32-bit, so 64-bit values are stored and passed as 32-bit value pairs 1
.
24.1 Returning of 64-bit value
#include <stdint.h>
uint64_t f ()
{
return 0x1234567890ABCDEF;
};
24.1.1 x86
In a 32-bit environment, 64-bit values are returned from functions in the EDX:EAX register pair.
Listing 24.1: Optimizing MSVC 2010
_f PROC
mov eax, -1867788817 ; 90abcdefH
mov edx, 305419896 ; 12345678H
ret 0
_f ENDP
24.1.2 ARM
A 64-bit value is returned in the R0-R1 register pair (R1 is for the high part and R0 for the low part):
Listing 24.2: Optimizing Keil 6/2013 (ARM mode)
||f|| PROC
LDR r0,|L0.12|
LDR r1,|L0.16|
BX lr
ENDP
|L0.12|
DCD 0x90abcdef
|L0.16|
DCD 0x12345678
24.1.3 MIPS
A 64-bit value is returned in the V0-V1 ($2-$3) register pair (V0 ($2) is for the high part and V1 ($3) for the low part):
Listing 24.3: Optimizing GCC 4.4.5 (assembly listing)
li $3,-1867841536 # 0xffffffff90ab0000
li $2,305397760 # 0x12340000
ori $3,$3,0xcdef
1By the way, 32-bit values are passed as pairs in 16-bit environment in the same way: 53.4 on page 594
403
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION
j $31
ori $2,$2,0x5678
Listing 24.4: Optimizing GCC 4.4.5 (IDA)
lui $v1, 0x90AB
lui $v0, 0x1234
li $v1, 0x90ABCDEF
jr $ra
li $v0, 0x12345678
24.2 Arguments passing, addition, subtraction
#include <stdint.h>
uint64_t f_add (uint64_t a, uint64_t b)
{
return a+b;
};
void f_add_test ()
{
#ifdef __GNUC__
printf ("%lldn", f_add(12345678901234, 23456789012345));
#else
printf ("%I64dn", f_add(12345678901234, 23456789012345));
#endif
};
uint64_t f_sub (uint64_t a, uint64_t b)
{
return a-b;
};
24.2.1 x86
Listing 24.5: Optimizing MSVC 2012 /Ob1
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f_add PROC
mov eax, DWORD PTR _a$[esp-4]
add eax, DWORD PTR _b$[esp-4]
mov edx, DWORD PTR _a$[esp]
adc edx, DWORD PTR _b$[esp]
ret 0
_f_add ENDP
_f_add_test PROC
push 5461 ; 00001555H
push 1972608889 ; 75939f79H
push 2874 ; 00000b3aH
push 1942892530 ; 73ce2ff_subH
call _f_add
push edx
push eax
push OFFSET $SG1436 ; '%I64d', 0aH, 00H
call _printf
add esp, 28
ret 0
_f_add_test ENDP
_f_sub PROC
mov eax, DWORD PTR _a$[esp-4]
sub eax, DWORD PTR _b$[esp-4]
mov edx, DWORD PTR _a$[esp]
404
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION
sbb edx, DWORD PTR _b$[esp]
ret 0
_f_sub ENDP
We can see in the f_add_test() function that each 64-bit value is passed using two 32-bit values, high part first, then
low part.
Addition and subtraction occur in pairs as well.
In addition, the low 32-bit part are added first. If carry was occurred while adding, the CF flag is set. The following
ADC instruction adds the high parts of the values, and also adds 1 if CF = 1.
Subtraction also occurs in pairs. The first SUB may also turn on the CF flag, which is to be checked in the subsequent
SBB instruction: if the carry flag is on, then 1 is also to be subtracted from the result.
It is easy to see how the f_add() function result is then passed to printf().
Listing 24.6: GCC 4.8.1 -O1 -fno-inline
_f_add:
mov eax, DWORD PTR [esp+12]
mov edx, DWORD PTR [esp+16]
add eax, DWORD PTR [esp+4]
adc edx, DWORD PTR [esp+8]
ret
_f_add_test:
sub esp, 28
mov DWORD PTR [esp+8], 1972608889 ; 75939f79H
mov DWORD PTR [esp+12], 5461 ; 00001555H
mov DWORD PTR [esp], 1942892530 ; 73ce2ff_subH
mov DWORD PTR [esp+4], 2874 ; 00000b3aH
call _f_add
mov DWORD PTR [esp+4], eax
mov DWORD PTR [esp+8], edx
mov DWORD PTR [esp], OFFSET FLAT:LC0 ; "%lld120"
call _printf
add esp, 28
ret
_f_sub:
mov eax, DWORD PTR [esp+4]
mov edx, DWORD PTR [esp+8]
sub eax, DWORD PTR [esp+12]
sbb edx, DWORD PTR [esp+16]
ret
GCC code is the same.
24.2.2 ARM
Listing 24.7: Optimizing Keil 6/2013 (ARM mode)
f_add PROC
ADDS r0,r0,r2
ADC r1,r1,r3
BX lr
ENDP
f_sub PROC
SUBS r0,r0,r2
SBC r1,r1,r3
BX lr
ENDP
f_add_test PROC
PUSH {r4,lr}
LDR r2,|L0.68| ; 0x75939f79
LDR r3,|L0.72| ; 0x00001555
405
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION
LDR r0,|L0.76| ; 0x73ce2ff2
LDR r1,|L0.80| ; 0x00000b3a
BL f_add
POP {r4,lr}
MOV r2,r0
MOV r3,r1
ADR r0,|L0.84| ; "%I64dn"
B __2printf
ENDP
|L0.68|
DCD 0x75939f79
|L0.72|
DCD 0x00001555
|L0.76|
DCD 0x73ce2ff2
|L0.80|
DCD 0x00000b3a
|L0.84|
DCB "%I64dn",0
The first 64-bit value is passed in R0 and R1 register pair, the second in R2 and R3 register pair. ARM has the ADC
instruction as well (which counts carry flag) and SBC (“subtract with carry”).
Important thing: when the low parts are added/subtracted, ADDS and SUBS instructions with -S suffix are used. The -S
suffix stands for “set flags”, and flags (esp. carry flag) is what consequent ADC/SBC instructions definitely need.
Otherwise, instructions without the -S suffix would do the job (ADD and SUB).
24.2.3 MIPS
Listing 24.8: Optimizing GCC 4.4.5 (IDA)
f_add:
; $a0 - high part of a
; $a1 - low part of a
; $a2 - high part of b
; $a3 - low part of b
addu $v1, $a3, $a1 ; sum up low parts
addu $a0, $a2, $a0 ; sum up high parts
; will carry generated while summing up low parts?
; if yes, set $v0 to 1
sltu $v0, $v1, $a3
jr $ra
; add 1 to high part of result if carry should be generated:
addu $v0, $a0 ; branch delay slot
; $v0 - high part of result
; $v1 - low part of result
f_sub:
; $a0 - high part of a
; $a1 - low part of a
; $a2 - high part of b
; $a3 - low part of b
subu $v1, $a1, $a3 ; subtract low parts
subu $v0, $a0, $a2 ; subtract high parts
; will carry generated while subtracting low parts?
; if yes, set $a0 to 1
sltu $a1, $v1
jr $ra
; subtract 1 from high part of result if carry should be generated:
subu $v0, $a1 ; branch delay slot
; $v0 - high part of result
; $v1 - low part of result
f_add_test:
var_10 = -0x10
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
406
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
lui $a1, 0x73CE
lui $a3, 0x7593
li $a0, 0xB3A
li $a3, 0x75939F79
li $a2, 0x1555
jal f_add
li $a1, 0x73CE2FF2
lw $gp, 0x20+var_10($sp)
lui $a0, ($LC0 >> 16) # "%lldn"
lw $t9, (printf & 0xFFFF)($gp)
lw $ra, 0x20+var_4($sp)
la $a0, ($LC0 & 0xFFFF) # "%lldn"
move $a3, $v1
move $a2, $v0
jr $t9
addiu $sp, 0x20
$LC0: .ascii "%lldn"<0>
MIPS has no flags register, so there is no such information present after the execution of arithmetic operations. So there
are no instructions like x86’s ADC and SBB. To know if the carry flag would be set, a comparison (using “SLTU” instruction)
also occurs, which sets the destination register to 1 or 0. This 1 or 0 is then added or subtracted to/from the final result.
24.3 Multiplication, division
#include <stdint.h>
uint64_t f_mul (uint64_t a, uint64_t b)
{
return a*b;
};
uint64_t f_div (uint64_t a, uint64_t b)
{
return a/b;
};
uint64_t f_rem (uint64_t a, uint64_t b)
{
return a % b;
};
24.3.1 x86
Listing 24.9: Optimizing MSVC 2012 /Ob1
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f_mul PROC
push DWORD PTR _b$[esp]
push DWORD PTR _b$[esp]
push DWORD PTR _a$[esp+8]
push DWORD PTR _a$[esp+8]
call __allmul ; long long multiplication
ret 0
_f_mul ENDP
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f_div PROC
push DWORD PTR _b$[esp]
push DWORD PTR _b$[esp]
push DWORD PTR _a$[esp+8]
407
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION
push DWORD PTR _a$[esp+8]
call __aulldiv ; unsigned long long division
ret 0
_f_div ENDP
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f_rem PROC
push DWORD PTR _b$[esp]
push DWORD PTR _b$[esp]
push DWORD PTR _a$[esp+8]
push DWORD PTR _a$[esp+8]
call __aullrem ; unsigned long long remainder
ret 0
_f_rem ENDP
Multiplication and division are more complex operations, so usually the compiler embeds calls to a library functions
doing that.
These functions are described here: E on page 950.
Listing 24.10: Optimizing GCC 4.8.1 -fno-inline
_f_mul:
push ebx
mov edx, DWORD PTR [esp+8]
mov eax, DWORD PTR [esp+16]
mov ebx, DWORD PTR [esp+12]
mov ecx, DWORD PTR [esp+20]
imul ebx, eax
imul ecx, edx
mul edx
add ecx, ebx
add edx, ecx
pop ebx
ret
_f_div:
sub esp, 28
mov eax, DWORD PTR [esp+40]
mov edx, DWORD PTR [esp+44]
mov DWORD PTR [esp+8], eax
mov eax, DWORD PTR [esp+32]
mov DWORD PTR [esp+12], edx
mov edx, DWORD PTR [esp+36]
mov DWORD PTR [esp], eax
mov DWORD PTR [esp+4], edx
call ___udivdi3 ; unsigned division
add esp, 28
ret
_f_rem:
sub esp, 28
mov eax, DWORD PTR [esp+40]
mov edx, DWORD PTR [esp+44]
mov DWORD PTR [esp+8], eax
mov eax, DWORD PTR [esp+32]
mov DWORD PTR [esp+12], edx
mov edx, DWORD PTR [esp+36]
mov DWORD PTR [esp], eax
mov DWORD PTR [esp+4], edx
call ___umoddi3 ; unsigned modulo
add esp, 28
ret
GCC does the expected, but the multiplication code is inlined right in the function, thinking it could be more efficient.
GCC has different library function names: D on page 949.
24.3.2 ARM
Keil for thumb mode inserts library subroutine calls:
408
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION
Listing 24.11: Optimizing Keil 6/2013 (thumb mode)
||f_mul|| PROC
PUSH {r4,lr}
BL __aeabi_lmul
POP {r4,pc}
ENDP
||f_div|| PROC
PUSH {r4,lr}
BL __aeabi_uldivmod
POP {r4,pc}
ENDP
||f_rem|| PROC
PUSH {r4,lr}
BL __aeabi_uldivmod
MOVS r0,r2
MOVS r1,r3
POP {r4,pc}
ENDP
Keil for ARM mode, on the other hand, is able to produce 64-bit multiplication code:
Listing 24.12: Optimizing Keil 6/2013 (ARM mode)
||f_mul|| PROC
PUSH {r4,lr}
UMULL r12,r4,r0,r2
MLA r1,r2,r1,r4
MLA r1,r0,r3,r1
MOV r0,r12
POP {r4,pc}
ENDP
||f_div|| PROC
PUSH {r4,lr}
BL __aeabi_uldivmod
POP {r4,pc}
ENDP
||f_rem|| PROC
PUSH {r4,lr}
BL __aeabi_uldivmod
MOV r0,r2
MOV r1,r3
POP {r4,pc}
ENDP
24.3.3 MIPS
Optimizing GCC for MIPS can generate 64-bit multiplication code, but has to call a library routine for 64-bit division:
Listing 24.13: Optimizing GCC 4.4.5 (IDA)
f_mul:
mult $a2, $a1
mflo $v0
or $at, $zero ; NOP
or $at, $zero ; NOP
mult $a0, $a3
mflo $a0
addu $v0, $a0
or $at, $zero ; NOP
multu $a3, $a1
mfhi $a2
mflo $v1
jr $ra
addu $v0, $a2
f_div:
409
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.4. SHIFTING RIGHT
var_10 = -0x10
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
lw $t9, (__udivdi3 & 0xFFFF)($gp)
or $at, $zero
jalr $t9
or $at, $zero
lw $ra, 0x20+var_4($sp)
or $at, $zero
jr $ra
addiu $sp, 0x20
f_rem:
var_10 = -0x10
var_4 = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+var_4($sp)
sw $gp, 0x20+var_10($sp)
lw $t9, (__umoddi3 & 0xFFFF)($gp)
or $at, $zero
jalr $t9
or $at, $zero
lw $ra, 0x20+var_4($sp)
or $at, $zero
jr $ra
addiu $sp, 0x20
There are a lot of NOPs, probably delay slots filled after the multiplication instruction (it’s slower than other instructions,
after all), but I’m not completely sure.
24.4 Shifting right
#include <stdint.h>
uint64_t f (uint64_t a)
{
return a>>7;
};
24.4.1 x86
Listing 24.14: Optimizing MSVC 2012 /Ob1
_a$ = 8 ; size = 8
_f PROC
mov eax, DWORD PTR _a$[esp-4]
mov edx, DWORD PTR _a$[esp]
shrd eax, edx, 7
shr edx, 7
ret 0
_f ENDP
Listing 24.15: Optimizing GCC 4.8.1 -fno-inline
_f:
mov edx, DWORD PTR [esp+8]
mov eax, DWORD PTR [esp+4]
410
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.5. CONVERTING 32-BIT VALUE INTO 64-BIT ONE
shrd eax, edx, 7
shr edx, 7
ret
Shifting also occurs in two passes: first the lower part is shifted, then the higher part. But the lower part is shifted with
the help of the SHRD instruction, it shifts the value of EDX by 7 bits, but pulls new bits from EAX, i.e., from the higher part.
The higher part is shifted using the more popular SHR instruction: indeed, the freed bits in the higher part must be filled
with zeroes.
24.4.2 ARM
ARM doesn’t have such instruction as SHRD in x86, so the Keil compiler ought to do this using simple shifts and OR operations:
Listing 24.16: Optimizing Keil 6/2013 (ARM mode)
||f|| PROC
LSR r0,r0,#7
ORR r0,r0,r1,LSL #25
LSR r1,r1,#7
BX lr
ENDP
Listing 24.17: Optimizing Keil 6/2013 (thumb mode)
||f|| PROC
LSLS r2,r1,#25
LSRS r0,r0,#7
ORRS r0,r0,r2
LSRS r1,r1,#7
BX lr
ENDP
24.4.3 MIPS
GCC for MIPS follows the same algorithm as Keil does for thumb mode:
Listing 24.18: Optimizing GCC 4.4.5 (IDA)
f:
sll $v0, $a0, 25
srl $v1, $a1, 7
or $v1, $v0, $v1
jr $ra
srl $v0, $a0, 7
24.5 Converting 32-bit value into 64-bit one
#include <stdint.h>
int64_t f (int32_t a)
{
return a;
};
24.5.1 x86
Listing 24.19: Optimizing MSVC 2012
_a$ = 8
_f PROC
mov eax, DWORD PTR _a$[esp-4]
cdq
ret 0
_f ENDP
411
CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.5. CONVERTING 32-BIT VALUE INTO 64-BIT ONE
Here we also run into necessity to extend a 32-bit signed value into a 64-bit signed one. Unsigned values are converted
straightforwardly: all bits in the higher part must be set to 0. But this is not appropriate for signed data types: the sign
has to be copied into the higher part of the resulting number. The CDQ instruction does that here, it takes its input value
in EAX, extends it to 64-bit and leaves it in the EDX:EAX register pair. In other words, CDQ gets the number sign from EAX
(by getting the most significant bit in EAX), and depending of it, sets all 32 bits in EDX to 0 or 1. Its operation is somewhat
similar to the MOVSX instruction.
24.5.2 ARM
Listing 24.20: Optimizing Keil 6/2013 (ARM mode)
||f|| PROC
ASR r1,r0,#31
BX lr
ENDP
Keil for ARM is different: it just arithmetically shifts right the input value by 31 bits. As we know, the sign bit is MSB,
and the arithmetical shift copies the sign bit into the “emerged” bits. So after “ASR r1,r0,#31”, R1 containing 0xFFFFFFFF if
the input value was negative and 0 otherwise. R1 contains the high part of the resulting 64-bit value.
In other words, this code just copies the MSB (sign bit) from the input value in R0 to all bits of the high 32-bit part of the
resulting 64-bit value.
24.5.3 MIPS
GCC for MIPS does the same as Keil did for ARM mode:
Listing 24.21: Optimizing GCC 4.4.5 (IDA)
f:
sra $v0, $a0, 31
jr $ra
move $v1, $a0
412
CHAPTER 25. SIMD
Chapter 25
SIMD
SIMD is an acronym: Single Instruction, Multiple Data.
As its name implies, it processes multiple data using only one instruction.
Like the FPU, that CPU subsystem looks like a separate processor inside x86.
SIMD began as MMX in x86. 8 new 64-bit registers appeared: MM0-MM7.
Each MMX register can hold 2 32-bit values, 4 16-bit values or 8 bytes. For example, it is possible to add 8 8-bit values
(bytes) simultaneously by adding two values in MMX registers.
One simple example is a graphics editor that represents an image as a two dimensional array. When the user changes
the brightness of the image, the editor must add or subtract a coefficient to/from each pixel value. For the sake of brevity if
we say that the image is grayscale and each pixel is defined by one 8-bit byte, then it is possible to change the brightness of
8 pixels simultaneously. By the way, this is the reason why the saturation instructions are present in SIMD. When the user
changes the brightness in the graphics editor, overflow and underflow is not desirable, so there are addition instructions in
SIMD which are not adding anything if the maximum value is reached, etc.
When MMX appeared, these registers were actually located in the FPU’s registers. It was possible to use either FPU
or MMX at the same time. One might think that Intel saved on transistors, but in fact the reason of such symbiosis was
simpler —older OSes that are not aware of the additional CPU registers would not save them at the context switch, but
saving the FPU registers. Thus, MMX-enabled CPU + old OS + process utilizing MMX features will still work.
SSE—is extension of the SIMD registers to 128 bits, now separate from the FPU.
AVX—another extension, to 256 bits.
Now about practical usage.
Of course, memory copy routines (memcpy), memory comparing (memcmp) and so on.
One more example: the DES encryption algorithm takes a 64-bit block and a 56-bit key, encrypt the block and produces
a 64-bit result. The DES algorithm may be considered as a very large electronic circuit, with wires and AND/OR/NOT gates.
Bitslice DES1
—is the idea of processing groups of blocks and keys simultaneously. Let’s say, variable of type unsigned
int on x86 can hold up to 32 bits, so it is possible to store there intermediate results for 32 block-key pairs simultaneously,
using 64+56 variables of type unsigned int.
I wrote an utility to brute-force Oracle RDBMS passwords/hashes (ones based on DES), using slightly modified bitslice
DES algorithm for SSE2 and AVX —now it is possible to encrypt 128 or 256 block-keys pairs simultaneously.
http://go.yurichev.com/17313
25.1 Vectorization
Vectorization2
is when, for example, you have a loop taking couple of arrays for input and producing one array. The loop
body takes values from the input arrays, does something and puts the result into the output array. It is important that there
is only a single operation applied to each element. Vectorization is to process several elements simultaneously.
Vectorization is not very fresh technology: the author of this textbook saw it at least on the Cray Y-MP supercomputer
line from 1988 when he played with its “lite” version Cray Y-MP EL 3
.
For example:
for (i = 0; i < 1024; i++)
{
C[i] = A[i]*B[i];
}
This fragment of code takes elements from A and B, multiplies them and saves the result into C.
If each array element we have is 32-bit int, then it is possible to load 4 elements from A into a 128-bit XMM-register,
from B to another XMM-registers, and by executing PMULLD ( Multiply Packed Signed Dword Integers and Store Low Result) and
PMULHW ( Multiply Packed Signed Integers and Store High Result), it is possible to get 4 64-bit products at once.
1http://go.yurichev.com/17329
2Wikipedia: vectorization
3Remotely. It is installed in the museum of supercomputers: http://go.yurichev.com/17081
413
CHAPTER 25. SIMD 25.1. VECTORIZATION
Thus, loop body execution count is 1024/4 instead of 1024, that is 4 times less and, of course, faster.
25.1.1 Addition example
Some compilers can do vectorization automatically in simple cases, e.g., Intel C++4
.
I wrote this tiny function:
int f (int sz, int *ar1, int *ar2, int *ar3)
{
for (int i=0; i<sz; i++)
ar3[i]=ar1[i]+ar2[i];
return 0;
};
Intel C++
Let’s compile it with Intel C++ 11.1.051 win32:
icl intel.cpp /QaxSSE2 /Faintel.asm /Ox
We got (in IDA):
; int __cdecl f(int, int *, int *, int *)
public ?f@@YAHHPAH00@Z
?f@@YAHHPAH00@Z proc near
var_10 = dword ptr -10h
sz = dword ptr 4
ar1 = dword ptr 8
ar2 = dword ptr 0Ch
ar3 = dword ptr 10h
push edi
push esi
push ebx
push esi
mov edx, [esp+10h+sz]
test edx, edx
jle loc_15B
mov eax, [esp+10h+ar3]
cmp edx, 6
jle loc_143
cmp eax, [esp+10h+ar2]
jbe short loc_36
mov esi, [esp+10h+ar2]
sub esi, eax
lea ecx, ds:0[edx*4]
neg esi
cmp ecx, esi
jbe short loc_55
loc_36: ; CODE XREF: f(int,int *,int *,int *)+21
cmp eax, [esp+10h+ar2]
jnb loc_143
mov esi, [esp+10h+ar2]
sub esi, eax
lea ecx, ds:0[edx*4]
cmp esi, ecx
jb loc_143
loc_55: ; CODE XREF: f(int,int *,int *,int *)+34
cmp eax, [esp+10h+ar1]
jbe short loc_67
mov esi, [esp+10h+ar1]
sub esi, eax
neg esi
4More about Intel C++ automatic vectorization: Excerpt: Effective Automatic Vectorization
414
CHAPTER 25. SIMD 25.1. VECTORIZATION
cmp ecx, esi
jbe short loc_7F
loc_67: ; CODE XREF: f(int,int *,int *,int *)+59
cmp eax, [esp+10h+ar1]
jnb loc_143
mov esi, [esp+10h+ar1]
sub esi, eax
cmp esi, ecx
jb loc_143
loc_7F: ; CODE XREF: f(int,int *,int *,int *)+65
mov edi, eax ; edi = ar1
and edi, 0Fh ; is ar1 16-byte aligned?
jz short loc_9A ; yes
test edi, 3
jnz loc_162
neg edi
add edi, 10h
shr edi, 2
loc_9A: ; CODE XREF: f(int,int *,int *,int *)+84
lea ecx, [edi+4]
cmp edx, ecx
jl loc_162
mov ecx, edx
sub ecx, edi
and ecx, 3
neg ecx
add ecx, edx
test edi, edi
jbe short loc_D6
mov ebx, [esp+10h+ar2]
mov [esp+10h+var_10], ecx
mov ecx, [esp+10h+ar1]
xor esi, esi
loc_C1: ; CODE XREF: f(int,int *,int *,int *)+CD
mov edx, [ecx+esi*4]
add edx, [ebx+esi*4]
mov [eax+esi*4], edx
inc esi
cmp esi, edi
jb short loc_C1
mov ecx, [esp+10h+var_10]
mov edx, [esp+10h+sz]
loc_D6: ; CODE XREF: f(int,int *,int *,int *)+B2
mov esi, [esp+10h+ar2]
lea esi, [esi+edi*4] ; is ar2+i*4 16-byte aligned?
test esi, 0Fh
jz short loc_109 ; yes!
mov ebx, [esp+10h+ar1]
mov esi, [esp+10h+ar2]
loc_ED: ; CODE XREF: f(int,int *,int *,int *)+105
movdqu xmm1, xmmword ptr [ebx+edi*4] ; ar1+i*4
movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to XMM0
paddd xmm1, xmm0
movdqa xmmword ptr [eax+edi*4], xmm1 ; ar3+i*4
add edi, 4
cmp edi, ecx
jb short loc_ED
jmp short loc_127
loc_109: ; CODE XREF: f(int,int *,int *,int *)+E3
mov ebx, [esp+10h+ar1]
mov esi, [esp+10h+ar2]
loc_111: ; CODE XREF: f(int,int *,int *,int *)+125
415
CHAPTER 25. SIMD 25.1. VECTORIZATION
movdqu xmm0, xmmword ptr [ebx+edi*4]
paddd xmm0, xmmword ptr [esi+edi*4]
movdqa xmmword ptr [eax+edi*4], xmm0
add edi, 4
cmp edi, ecx
jb short loc_111
loc_127: ; CODE XREF: f(int,int *,int *,int *)+107
; f(int,int *,int *,int *)+164
cmp ecx, edx
jnb short loc_15B
mov esi, [esp+10h+ar1]
mov edi, [esp+10h+ar2]
loc_133: ; CODE XREF: f(int,int *,int *,int *)+13F
mov ebx, [esi+ecx*4]
add ebx, [edi+ecx*4]
mov [eax+ecx*4], ebx
inc ecx
cmp ecx, edx
jb short loc_133
jmp short loc_15B
loc_143: ; CODE XREF: f(int,int *,int *,int *)+17
; f(int,int *,int *,int *)+3A ...
mov esi, [esp+10h+ar1]
mov edi, [esp+10h+ar2]
xor ecx, ecx
loc_14D: ; CODE XREF: f(int,int *,int *,int *)+159
mov ebx, [esi+ecx*4]
add ebx, [edi+ecx*4]
mov [eax+ecx*4], ebx
inc ecx
cmp ecx, edx
jb short loc_14D
loc_15B: ; CODE XREF: f(int,int *,int *,int *)+A
; f(int,int *,int *,int *)+129 ...
xor eax, eax
pop ecx
pop ebx
pop esi
pop edi
retn
loc_162: ; CODE XREF: f(int,int *,int *,int *)+8C
; f(int,int *,int *,int *)+9F
xor ecx, ecx
jmp short loc_127
?f@@YAHHPAH00@Z endp
The SSE2-related instructions are:
• MOVDQU (Move Unaligned Double Quadword)— just loads 16 bytes from memory into a XMM-register.
• PADDD (Add Packed Integers)— adds 4 pairs of 32-bit numbers and leaves the result in the first operand. By the way, no
exception is raised in case of overflow and no flags are to be set, just the low 32 bits of the result are to be stored. If
one of PADDD’s operands is the address of a value in memory, then the address must be aligned on a 16-byte boundary.
If it is not aligned, an exception will be triggered 5
.
• MOVDQA (Move Aligned Double Quadword) is the same as MOVDQU, but requires the address of the value in memory to
be aligned on a 16-bit boundary. If it is not aligned, exception will be raised. MOVDQA works faster than MOVDQU, but
requires aforesaid.
So, these SSE2-instructions are to be executed only in case there are more than 4 pairs to work on and the pointer ar3
is aligned on a 16-byte boundary.
Also, if ar2 is aligned on a 16-byte boundary as well, this fragment of code is to be executed:
5More about data alignment: Wikipedia: Data structure alignment
416
CHAPTER 25. SIMD 25.1. VECTORIZATION
movdqu xmm0, xmmword ptr [ebx+edi*4] ; ar1+i*4
paddd xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4
movdqa xmmword ptr [eax+edi*4], xmm0 ; ar3+i*4
Otherwise, the value from ar2 is to be loaded into XMM0 using MOVDQU, which does not require aligned pointer, but may
work slower:
movdqu xmm1, xmmword ptr [ebx+edi*4] ; ar1+i*4
movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to XMM0
paddd xmm1, xmm0
movdqa xmmword ptr [eax+edi*4], xmm1 ; ar3+i*4
In all other cases, non-SSE2 code is to be executed.
GCC
GCC may also vectorize in simple cases6
, if the -O3 option is used and SSE2 support is turned on: -msse2.
What we get (GCC 4.4.1):
; f(int, int *, int *, int *)
public _Z1fiPiS_S_
_Z1fiPiS_S_ proc near
var_18 = dword ptr -18h
var_14 = dword ptr -14h
var_10 = dword ptr -10h
arg_0 = dword ptr 8
arg_4 = dword ptr 0Ch
arg_8 = dword ptr 10h
arg_C = dword ptr 14h
push ebp
mov ebp, esp
push edi
push esi
push ebx
sub esp, 0Ch
mov ecx, [ebp+arg_0]
mov esi, [ebp+arg_4]
mov edi, [ebp+arg_8]
mov ebx, [ebp+arg_C]
test ecx, ecx
jle short loc_80484D8
cmp ecx, 6
lea eax, [ebx+10h]
ja short loc_80484E8
loc_80484C1: ; CODE XREF: f(int,int *,int *,int *)+4B
; f(int,int *,int *,int *)+61 ...
xor eax, eax
nop
lea esi, [esi+0]
loc_80484C8: ; CODE XREF: f(int,int *,int *,int *)+36
mov edx, [edi+eax*4]
add edx, [esi+eax*4]
mov [ebx+eax*4], edx
add eax, 1
cmp eax, ecx
jnz short loc_80484C8
loc_80484D8: ; CODE XREF: f(int,int *,int *,int *)+17
; f(int,int *,int *,int *)+A5
add esp, 0Ch
xor eax, eax
pop ebx
pop esi
pop edi
6More about GCC vectorization support: http://go.yurichev.com/17083
417
CHAPTER 25. SIMD 25.1. VECTORIZATION
pop ebp
retn
align 8
loc_80484E8: ; CODE XREF: f(int,int *,int *,int *)+1F
test bl, 0Fh
jnz short loc_80484C1
lea edx, [esi+10h]
cmp ebx, edx
jbe loc_8048578
loc_80484F8: ; CODE XREF: f(int,int *,int *,int *)+E0
lea edx, [edi+10h]
cmp ebx, edx
ja short loc_8048503
cmp edi, eax
jbe short loc_80484C1
loc_8048503: ; CODE XREF: f(int,int *,int *,int *)+5D
mov eax, ecx
shr eax, 2
mov [ebp+var_14], eax
shl eax, 2
test eax, eax
mov [ebp+var_10], eax
jz short loc_8048547
mov [ebp+var_18], ecx
mov ecx, [ebp+var_14]
xor eax, eax
xor edx, edx
nop
loc_8048520: ; CODE XREF: f(int,int *,int *,int *)+9B
movdqu xmm1, xmmword ptr [edi+eax]
movdqu xmm0, xmmword ptr [esi+eax]
add edx, 1
paddd xmm0, xmm1
movdqa xmmword ptr [ebx+eax], xmm0
add eax, 10h
cmp edx, ecx
jb short loc_8048520
mov ecx, [ebp+var_18]
mov eax, [ebp+var_10]
cmp ecx, eax
jz short loc_80484D8
loc_8048547: ; CODE XREF: f(int,int *,int *,int *)+73
lea edx, ds:0[eax*4]
add esi, edx
add edi, edx
add ebx, edx
lea esi, [esi+0]
loc_8048558: ; CODE XREF: f(int,int *,int *,int *)+CC
mov edx, [edi]
add eax, 1
add edi, 4
add edx, [esi]
add esi, 4
mov [ebx], edx
add ebx, 4
cmp ecx, eax
jg short loc_8048558
add esp, 0Ch
xor eax, eax
pop ebx
pop esi
pop edi
pop ebp
418
CHAPTER 25. SIMD 25.1. VECTORIZATION
retn
loc_8048578: ; CODE XREF: f(int,int *,int *,int *)+52
cmp eax, esi
jnb loc_80484C1
jmp loc_80484F8
_Z1fiPiS_S_ endp
Almost the same, however, not as meticulously as Intel C++.
25.1.2 Memory copy example
Let’s revisit the simple memcpy() example ( 14.2 on page 179):
#include <stdio.h>
void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt)
{
size_t i;
for (i=0; i<cnt; i++)
dst[i]=src[i];
};
And that’s what optimizations GCC 4.9.1 did:
Listing 25.1: Optimizing GCC 4.9.1 x64
my_memcpy:
; RDI = destination address
; RSI = source address
; RDX = size of block
test rdx, rdx
je .L41
lea rax, [rdi+16]
cmp rsi, rax
lea rax, [rsi+16]
setae cl
cmp rdi, rax
setae al
or cl, al
je .L13
cmp rdx, 22
jbe .L13
mov rcx, rsi
push rbp
push rbx
neg rcx
and ecx, 15
cmp rcx, rdx
cmova rcx, rdx
xor eax, eax
test rcx, rcx
je .L4
movzx eax, BYTE PTR [rsi]
cmp rcx, 1
mov BYTE PTR [rdi], al
je .L15
movzx eax, BYTE PTR [rsi+1]
cmp rcx, 2
mov BYTE PTR [rdi+1], al
je .L16
movzx eax, BYTE PTR [rsi+2]
cmp rcx, 3
mov BYTE PTR [rdi+2], al
je .L17
movzx eax, BYTE PTR [rsi+3]
cmp rcx, 4
mov BYTE PTR [rdi+3], al
je .L18
movzx eax, BYTE PTR [rsi+4]
cmp rcx, 5
419
CHAPTER 25. SIMD 25.1. VECTORIZATION
mov BYTE PTR [rdi+4], al
je .L19
movzx eax, BYTE PTR [rsi+5]
cmp rcx, 6
mov BYTE PTR [rdi+5], al
je .L20
movzx eax, BYTE PTR [rsi+6]
cmp rcx, 7
mov BYTE PTR [rdi+6], al
je .L21
movzx eax, BYTE PTR [rsi+7]
cmp rcx, 8
mov BYTE PTR [rdi+7], al
je .L22
movzx eax, BYTE PTR [rsi+8]
cmp rcx, 9
mov BYTE PTR [rdi+8], al
je .L23
movzx eax, BYTE PTR [rsi+9]
cmp rcx, 10
mov BYTE PTR [rdi+9], al
je .L24
movzx eax, BYTE PTR [rsi+10]
cmp rcx, 11
mov BYTE PTR [rdi+10], al
je .L25
movzx eax, BYTE PTR [rsi+11]
cmp rcx, 12
mov BYTE PTR [rdi+11], al
je .L26
movzx eax, BYTE PTR [rsi+12]
cmp rcx, 13
mov BYTE PTR [rdi+12], al
je .L27
movzx eax, BYTE PTR [rsi+13]
cmp rcx, 15
mov BYTE PTR [rdi+13], al
jne .L28
movzx eax, BYTE PTR [rsi+14]
mov BYTE PTR [rdi+14], al
mov eax, 15
.L4:
mov r10, rdx
lea r9, [rdx-1]
sub r10, rcx
lea r8, [r10-16]
sub r9, rcx
shr r8, 4
add r8, 1
mov r11, r8
sal r11, 4
cmp r9, 14
jbe .L6
lea rbp, [rsi+rcx]
xor r9d, r9d
add rcx, rdi
xor ebx, ebx
.L7:
movdqa xmm0, XMMWORD PTR [rbp+0+r9]
add rbx, 1
movups XMMWORD PTR [rcx+r9], xmm0
add r9, 16
cmp rbx, r8
jb .L7
add rax, r11
cmp r10, r11
je .L1
.L6:
movzx ecx, BYTE PTR [rsi+rax]
mov BYTE PTR [rdi+rax], cl
420
CHAPTER 25. SIMD 25.1. VECTORIZATION
lea rcx, [rax+1]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+1+rax]
mov BYTE PTR [rdi+1+rax], cl
lea rcx, [rax+2]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+2+rax]
mov BYTE PTR [rdi+2+rax], cl
lea rcx, [rax+3]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+3+rax]
mov BYTE PTR [rdi+3+rax], cl
lea rcx, [rax+4]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+4+rax]
mov BYTE PTR [rdi+4+rax], cl
lea rcx, [rax+5]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+5+rax]
mov BYTE PTR [rdi+5+rax], cl
lea rcx, [rax+6]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+6+rax]
mov BYTE PTR [rdi+6+rax], cl
lea rcx, [rax+7]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+7+rax]
mov BYTE PTR [rdi+7+rax], cl
lea rcx, [rax+8]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+8+rax]
mov BYTE PTR [rdi+8+rax], cl
lea rcx, [rax+9]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+9+rax]
mov BYTE PTR [rdi+9+rax], cl
lea rcx, [rax+10]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+10+rax]
mov BYTE PTR [rdi+10+rax], cl
lea rcx, [rax+11]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+11+rax]
mov BYTE PTR [rdi+11+rax], cl
lea rcx, [rax+12]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+12+rax]
mov BYTE PTR [rdi+12+rax], cl
lea rcx, [rax+13]
cmp rdx, rcx
jbe .L1
movzx ecx, BYTE PTR [rsi+13+rax]
mov BYTE PTR [rdi+13+rax], cl
lea rcx, [rax+14]
cmp rdx, rcx
jbe .L1
movzx edx, BYTE PTR [rsi+14+rax]
mov BYTE PTR [rdi+14+rax], dl
421
CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION
.L1:
pop rbx
pop rbp
.L41:
rep ret
.L13:
xor eax, eax
.L3:
movzx ecx, BYTE PTR [rsi+rax]
mov BYTE PTR [rdi+rax], cl
add rax, 1
cmp rax, rdx
jne .L3
rep ret
.L28:
mov eax, 14
jmp .L4
.L15:
mov eax, 1
jmp .L4
.L16:
mov eax, 2
jmp .L4
.L17:
mov eax, 3
jmp .L4
.L18:
mov eax, 4
jmp .L4
.L19:
mov eax, 5
jmp .L4
.L20:
mov eax, 6
jmp .L4
.L21:
mov eax, 7
jmp .L4
.L22:
mov eax, 8
jmp .L4
.L23:
mov eax, 9
jmp .L4
.L24:
mov eax, 10
jmp .L4
.L25:
mov eax, 11
jmp .L4
.L26:
mov eax, 12
jmp .L4
.L27:
mov eax, 13
jmp .L4
25.2 SIMD strlen() implementation
It has to be noted that the SIMD instructions can be inserted in C/C++ code via special macros7
. For MSVC, some of them are
located in the intrin.h file.
It is possible to implement the strlen() function8
using SIMD instructions that works 2-2.5 times faster than the
common implementation. This function loads 16 characters into a XMM-register and check each against zero 9
.
7MSDN: MMX, SSE, and SSE2 Intrinsics
8strlen() —standard C library function for calculating string length
9The example is based on source code from: http://go.yurichev.com/17330.
422
CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION
size_t strlen_sse2(const char *str)
{
register size_t len = 0;
const char *s=str;
bool str_is_aligned=(((unsigned int)str)&0xFFFFFFF0) == (unsigned int)str;
if (str_is_aligned==false)
return strlen (str);
__m128i xmm0 = _mm_setzero_si128();
__m128i xmm1;
int mask = 0;
for (;;)
{
xmm1 = _mm_load_si128((__m128i *)s);
xmm1 = _mm_cmpeq_epi8(xmm1, xmm0);
if ((mask = _mm_movemask_epi8(xmm1)) != 0)
{
unsigned long pos;
_BitScanForward(&pos, mask);
len += (size_t)pos;
break;
}
s += sizeof(__m128i);
len += sizeof(__m128i);
};
return len;
}
Let’s compile it in MSVC 2010 with /Ox option:
Listing 25.2: Optimizing MSVC 2010
_pos$75552 = -4 ; size = 4
_str$ = 8 ; size = 4
?strlen_sse2@@YAIPBD@Z PROC ; strlen_sse2
push ebp
mov ebp, esp
and esp, -16 ; fffffff0H
mov eax, DWORD PTR _str$[ebp]
sub esp, 12 ; 0000000cH
push esi
mov esi, eax
and esi, -16 ; fffffff0H
xor edx, edx
mov ecx, eax
cmp esi, eax
je SHORT $LN4@strlen_sse
lea edx, DWORD PTR [eax+1]
npad 3 ; align next label
$LL11@strlen_sse:
mov cl, BYTE PTR [eax]
inc eax
test cl, cl
jne SHORT $LL11@strlen_sse
sub eax, edx
pop esi
mov esp, ebp
pop ebp
ret 0
$LN4@strlen_sse:
movdqa xmm1, XMMWORD PTR [eax]
pxor xmm0, xmm0
pcmpeqb xmm1, xmm0
pmovmskb eax, xmm1
test eax, eax
jne SHORT $LN9@strlen_sse
423
CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION
$LL3@strlen_sse:
movdqa xmm1, XMMWORD PTR [ecx+16]
add ecx, 16 ; 00000010H
pcmpeqb xmm1, xmm0
add edx, 16 ; 00000010H
pmovmskb eax, xmm1
test eax, eax
je SHORT $LL3@strlen_sse
$LN9@strlen_sse:
bsf eax, eax
mov ecx, eax
mov DWORD PTR _pos$75552[esp+16], eax
lea eax, DWORD PTR [ecx+edx]
pop esi
mov esp, ebp
pop ebp
ret 0
?strlen_sse2@@YAIPBD@Z ENDP ; strlen_sse2
First, we check if the str pointer is aligned on a 16-byte boundary. If not, we call the generic strlen() implementation.
Then, we load the next 16 bytes into the XMM1 register using MOVDQA.
An observant reader might ask, why can’t MOVDQU be used here since it can load data from the memory regardless pointer
alignment?
Yes, it might be done in this way: if the pointer is aligned, load data using MOVDQA, if not —use the slower MOVDQU.
But here we are may hit another caveat:
In the Windows NT line of OS (but not limited to it), memory is allocated by pages of 4 KiB (4096 bytes). Each win32-
process has 4 GiB available, but in fact, only some parts of the address space are connected to real physical memory. If the
process is accessing an absent memory block, an exception is to be raised. That’s how VM works10
.
So, a function loading 16 bytes at once may step over the border of an allocated memory block. Let’s say that the OS has
allocated 8192 (0x2000) bytes at address 0x008c0000. Thus, the block is the bytes starting from address 0x008c0000 to
0x008c1fff inclusive.
After the block, that is, starting from address 0x008c2000 there is nothing at all, e.g. the OS not allocated any memory
there. Any attempt to access memory starting from that address will raise an exception.
And let’s consider the example in which the program is holding a string that contains 5 characters almost at the end of
a block, and that is not a crime.
0x008c1ff8 ’h’
0x008c1ff9 ’e’
0x008c1ffa ’l’
0x008c1ffb ’l’
0x008c1ffc ’o’
0x008c1ffd ’x00’
0x008c1ffe random noise
0x008c1fff random noise
So, in normal conditions the program calls strlen(), passing it a pointer to the string 'hello' placed in memory at
address 0x008c1ff8. strlen() reads one byte at a time until 0x008c1ffd, where there’s a zero byte, and then it stops.
Now if we implement our own strlen() reading 16 byte at once, starting at any address, aligned or not, MOVDQU
may attempt to load 16 bytes at once at address 0x008c1ff8 up to 0x008c2008, and then an exception will be raised. That
situation is to be avoided, of course.
So then we’ll work only with the addresses aligned on a 16 byte boundary, which in combination with the knowledge
that the OS’ page size is usually aligned on a 16-byte boundary gives us some warranty that our function will not read from
unallocated memory.
Let’s get back to our function.
_mm_setzero_si128()— is a macro generating pxor xmm0, xmm0 —it just clears the XMM0 register.
_mm_load_si128()— is a macro for MOVDQA, it just loads 16 bytes from the address into the XMM1 register.
_mm_cmpeq_epi8()— is a macro for PCMPEQB, an instruction that compares two XMM-registers bytewise.
And if some byte was equals to the one in the other register, there will be 0xff at this point in the result or 0 if otherwise.
For example.
XMM1: 11223344556677880000000000000000
XMM0: 11ab3444007877881111111111111111
After the execution of pcmpeqb xmm1, xmm0, the XMM1 register contains:
XMM1: ff0000ff0000ffff0000000000000000
10wikipedia
424
CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION
In our case, this instruction compares each 16-byte block with a block of 16 zero-bytes, which was set in the XMM0 register
by pxor xmm0, xmm0.
The next macro is _mm_movemask_epi8() —that is the PMOVMSKB instruction.
It is very useful with PCMPEQB.
pmovmskb eax, xmm1
This instruction sets first EAX bit to 1 if the most significant bit of the first byte in XMM1 is 1. In other words, if the first
byte of the XMM1 register is 0xff, then the first bit of EAX is to be 1, too.
If the second byte in the XMM1 register is 0xff, then the second bit in EAX is to be set to 1. In other words, the instruction
is answering the question “which bytes in XMM1 are 0xff?” and returns 16 bits in the EAX register. The other bits in the
EAX register are to be cleared.
By the way, do not forget about this quirk of our algorithm. There might be 16 bytes in the input like:
15 14 13 12 11 10 9 3 2 1 0
“h” “e” “l” “l” “o” 0 garbage 0 garbage
It is the 'hello' string, terminating zero, and some random noise in memory. If we load these 16 bytes into XMM1 and
compare them with the zeroed XMM0, we are getting something like 11
:
XMM1: 0000ff00000000000000ff0000000000
This means that the instruction found two zero bytes, and it is not surprising.
PMOVMSKB in our case will set EAX to (in binary representation): 0010000000100000b.
Obviously, our function must take only the first zero bit and ignore the rest.
The next instruction is BSF (Bit Scan Forward). This instruction finds the first bit set to 1 and stores its position into the
first operand.
EAX=0010000000100000b
After the execution of bsf eax, eax, EAX contains 5, meaning 1 was found at the 5th bit position (starting from zero).
MSVC has a macro for this instruction: _BitScanForward.
Now it is simple. If a zero byte was found, its position is added to what we have already counted and now we have the
return result.
Almost all.
By the way, it is also has to be noted that the MSVC compiler emitted two loop bodies side by side, for optimization.
By the way, SSE 4.2 (that appeared in Intel Core i7) offers more instructions where these string manipulations might be
even easier: http://go.yurichev.com/17331
11I use here order from MSB to LSB12
425
CHAPTER 26. 64 BITS
Chapter 26
64 bits
26.1 x86-64
It is a 64-bit extension to the x86 architecture.
From the reverse engineer’s perspective, the most important changes are:
• Almost all registers (except FPU and SIMD) were extended to 64 bits and got a R- prefix. 8 additional registers wer
added. Now GPR’s are: RAX, RBX, RCX, RDX, RBP, RSP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15.
It is still possible to access the older register parts as usual. For example, it is possible to access the lower 32-bit part
of the RAX register using EAX:
7th (byte number)
6th 5th 4th 3rd 2nd 1st 0th
RAXx64
EAX
AX
AH AL
The new R8-R15 registers also have their lower parts: R8D-R15D (lower 32-bit parts), R8W-R15W (lower 16-bit parts),
R8L-R15L (lower 8-bit parts).
7th (byte number)
6th 5th 4th 3rd 2nd 1st 0th
R8
R8D
R8W
R8L
The number of SIMD registers was doubled from 8 to 16: XMM0-XMM15.
• In Win64, the function calling convention is slightly different, somewhat resembling fastcall ( 64.3 on page 664) .
The first 4 arguments are stored in the RCX, RDX, R8, R9 registers, the rest —in the stack. The Caller function must
also allocate 32 bytes so the callee may save there 4 first arguments and use these registers for its own needs. Short
functions may use arguments just from registers, but larger ones may save their values on the stack.
System V AMD64 ABI (Linux, *BSD, Mac OS X)[Mit13] also somewhat resembles fastcall, it uses 6 registers RDI, RSI,
RDX, RCX, R8, R9 for the first 6 arguments. All the rest are passed via the stack.
See also the section on calling conventions ( 64 on page 663).
• The C/C++ int type is still 32-bit for compatibility.
• All pointers are 64-bit now.
This provokes irritation sometimes: now one needs twice as much memory for storing pointers, including cache mem-
ory, despite the fact that x64 CPUs can address only 48 bits of external RAM.
Since now the number of registers is doubled, the compilers have more space for maneuvering called register allocation.
For us this implies that the emitted code containing less number of local variables.
For example, the function that calculates the first S-box of the DES encryption algorithm processes 32/64/128/256 values
at once (depending on DES_type type (uint32, uint64, SSE2 or AVX)) using the bitslice DES method (read more about this
technique here ( 25 on page 413)):
426
CHAPTER 26. 64 BITS 26.1. X86-64
/*
* Generated S-box files.
*
* This software may be modified, redistributed, and used for any purpose,
* so long as its origin is acknowledged.
*
* Produced by Matthew Kwan - March 1998
*/
#ifdef _WIN64
#define DES_type unsigned __int64
#else
#define DES_type unsigned int
#endif
void
s1 (
DES_type a1,
DES_type a2,
DES_type a3,
DES_type a4,
DES_type a5,
DES_type a6,
DES_type *out1,
DES_type *out2,
DES_type *out3,
DES_type *out4
) {
DES_type x1, x2, x3, x4, x5, x6, x7, x8;
DES_type x9, x10, x11, x12, x13, x14, x15, x16;
DES_type x17, x18, x19, x20, x21, x22, x23, x24;
DES_type x25, x26, x27, x28, x29, x30, x31, x32;
DES_type x33, x34, x35, x36, x37, x38, x39, x40;
DES_type x41, x42, x43, x44, x45, x46, x47, x48;
DES_type x49, x50, x51, x52, x53, x54, x55, x56;
x1 = a3 & ~a5;
x2 = x1 ^ a4;
x3 = a3 & ~a4;
x4 = x3 | a5;
x5 = a6 & x4;
x6 = x2 ^ x5;
x7 = a4 & ~a5;
x8 = a3 ^ a4;
x9 = a6 & ~x8;
x10 = x7 ^ x9;
x11 = a2 | x10;
x12 = x6 ^ x11;
x13 = a5 ^ x5;
x14 = x13 & x8;
x15 = a5 & ~a4;
x16 = x3 ^ x14;
x17 = a6 | x16;
x18 = x15 ^ x17;
x19 = a2 | x18;
x20 = x14 ^ x19;
x21 = a1 & x20;
x22 = x12 ^ ~x21;
*out2 ^= x22;
x23 = x1 | x5;
x24 = x23 ^ x8;
x25 = x18 & ~x2;
x26 = a2 & ~x25;
x27 = x24 ^ x26;
x28 = x6 | x7;
x29 = x28 ^ x25;
x30 = x9 ^ x24;
x31 = x18 & ~x30;
x32 = a2 & x31;
427
CHAPTER 26. 64 BITS 26.1. X86-64
x33 = x29 ^ x32;
x34 = a1 & x33;
x35 = x27 ^ x34;
*out4 ^= x35;
x36 = a3 & x28;
x37 = x18 & ~x36;
x38 = a2 | x3;
x39 = x37 ^ x38;
x40 = a3 | x31;
x41 = x24 & ~x37;
x42 = x41 | x3;
x43 = x42 & ~a2;
x44 = x40 ^ x43;
x45 = a1 & ~x44;
x46 = x39 ^ ~x45;
*out1 ^= x46;
x47 = x33 & ~x9;
x48 = x47 ^ x39;
x49 = x4 ^ x36;
x50 = x49 & ~x5;
x51 = x42 | x18;
x52 = x51 ^ a5;
x53 = a2 & ~x52;
x54 = x50 ^ x53;
x55 = a1 | x54;
x56 = x48 ^ ~x55;
*out3 ^= x56;
}
There are a lot of local variables. Of course, not all those going into the local stack. Let’s compile it with MSVC 2008
with /Ox option:
Listing 26.1: Optimizing MSVC 2008
PUBLIC _s1
; Function compile flags: /Ogtpy
_TEXT SEGMENT
_x6$ = -20 ; size = 4
_x3$ = -16 ; size = 4
_x1$ = -12 ; size = 4
_x8$ = -8 ; size = 4
_x4$ = -4 ; size = 4
_a1$ = 8 ; size = 4
_a2$ = 12 ; size = 4
_a3$ = 16 ; size = 4
_x33$ = 20 ; size = 4
_x7$ = 20 ; size = 4
_a4$ = 20 ; size = 4
_a5$ = 24 ; size = 4
tv326 = 28 ; size = 4
_x36$ = 28 ; size = 4
_x28$ = 28 ; size = 4
_a6$ = 28 ; size = 4
_out1$ = 32 ; size = 4
_x24$ = 36 ; size = 4
_out2$ = 36 ; size = 4
_out3$ = 40 ; size = 4
_out4$ = 44 ; size = 4
_s1 PROC
sub esp, 20 ; 00000014H
mov edx, DWORD PTR _a5$[esp+16]
push ebx
mov ebx, DWORD PTR _a4$[esp+20]
push ebp
push esi
mov esi, DWORD PTR _a3$[esp+28]
push edi
mov edi, ebx
not edi
mov ebp, edi
and edi, DWORD PTR _a5$[esp+32]
428
CHAPTER 26. 64 BITS 26.1. X86-64
mov ecx, edx
not ecx
and ebp, esi
mov eax, ecx
and eax, esi
and ecx, ebx
mov DWORD PTR _x1$[esp+36], eax
xor eax, ebx
mov esi, ebp
or esi, edx
mov DWORD PTR _x4$[esp+36], esi
and esi, DWORD PTR _a6$[esp+32]
mov DWORD PTR _x7$[esp+32], ecx
mov edx, esi
xor edx, eax
mov DWORD PTR _x6$[esp+36], edx
mov edx, DWORD PTR _a3$[esp+32]
xor edx, ebx
mov ebx, esi
xor ebx, DWORD PTR _a5$[esp+32]
mov DWORD PTR _x8$[esp+36], edx
and ebx, edx
mov ecx, edx
mov edx, ebx
xor edx, ebp
or edx, DWORD PTR _a6$[esp+32]
not ecx
and ecx, DWORD PTR _a6$[esp+32]
xor edx, edi
mov edi, edx
or edi, DWORD PTR _a2$[esp+32]
mov DWORD PTR _x3$[esp+36], ebp
mov ebp, DWORD PTR _a2$[esp+32]
xor edi, ebx
and edi, DWORD PTR _a1$[esp+32]
mov ebx, ecx
xor ebx, DWORD PTR _x7$[esp+32]
not edi
or ebx, ebp
xor edi, ebx
mov ebx, edi
mov edi, DWORD PTR _out2$[esp+32]
xor ebx, DWORD PTR [edi]
not eax
xor ebx, DWORD PTR _x6$[esp+36]
and eax, edx
mov DWORD PTR [edi], ebx
mov ebx, DWORD PTR _x7$[esp+32]
or ebx, DWORD PTR _x6$[esp+36]
mov edi, esi
or edi, DWORD PTR _x1$[esp+36]
mov DWORD PTR _x28$[esp+32], ebx
xor edi, DWORD PTR _x8$[esp+36]
mov DWORD PTR _x24$[esp+32], edi
xor edi, ecx
not edi
and edi, edx
mov ebx, edi
and ebx, ebp
xor ebx, DWORD PTR _x28$[esp+32]
xor ebx, eax
not eax
mov DWORD PTR _x33$[esp+32], ebx
and ebx, DWORD PTR _a1$[esp+32]
and eax, ebp
xor eax, ebx
mov ebx, DWORD PTR _out4$[esp+32]
xor eax, DWORD PTR [ebx]
xor eax, DWORD PTR _x24$[esp+32]
mov DWORD PTR [ebx], eax
429
CHAPTER 26. 64 BITS 26.1. X86-64
mov eax, DWORD PTR _x28$[esp+32]
and eax, DWORD PTR _a3$[esp+32]
mov ebx, DWORD PTR _x3$[esp+36]
or edi, DWORD PTR _a3$[esp+32]
mov DWORD PTR _x36$[esp+32], eax
not eax
and eax, edx
or ebx, ebp
xor ebx, eax
not eax
and eax, DWORD PTR _x24$[esp+32]
not ebp
or eax, DWORD PTR _x3$[esp+36]
not esi
and ebp, eax
or eax, edx
xor eax, DWORD PTR _a5$[esp+32]
mov edx, DWORD PTR _x36$[esp+32]
xor edx, DWORD PTR _x4$[esp+36]
xor ebp, edi
mov edi, DWORD PTR _out1$[esp+32]
not eax
and eax, DWORD PTR _a2$[esp+32]
not ebp
and ebp, DWORD PTR _a1$[esp+32]
and edx, esi
xor eax, edx
or eax, DWORD PTR _a1$[esp+32]
not ebp
xor ebp, DWORD PTR [edi]
not ecx
and ecx, DWORD PTR _x33$[esp+32]
xor ebp, ebx
not eax
mov DWORD PTR [edi], ebp
xor eax, ecx
mov ecx, DWORD PTR _out3$[esp+32]
xor eax, DWORD PTR [ecx]
pop edi
pop esi
xor eax, ebx
pop ebp
mov DWORD PTR [ecx], eax
pop ebx
add esp, 20 ; 00000014H
ret 0
_s1 ENDP
5 variables were allocated in the local stack by the compiler.
Now let’s try the same thing in the 64-bit version of MSVC 2008:
Listing 26.2: Optimizing MSVC 2008
a1$ = 56
a2$ = 64
a3$ = 72
a4$ = 80
x36$1$ = 88
a5$ = 88
a6$ = 96
out1$ = 104
out2$ = 112
out3$ = 120
out4$ = 128
s1 PROC
$LN3:
mov QWORD PTR [rsp+24], rbx
mov QWORD PTR [rsp+32], rbp
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+8], rcx
push rsi
430
CHAPTER 26. 64 BITS 26.1. X86-64
push rdi
push r12
push r13
push r14
push r15
mov r15, QWORD PTR a5$[rsp]
mov rcx, QWORD PTR a6$[rsp]
mov rbp, r8
mov r10, r9
mov rax, r15
mov rdx, rbp
not rax
xor rdx, r9
not r10
mov r11, rax
and rax, r9
mov rsi, r10
mov QWORD PTR x36$1$[rsp], rax
and r11, r8
and rsi, r8
and r10, r15
mov r13, rdx
mov rbx, r11
xor rbx, r9
mov r9, QWORD PTR a2$[rsp]
mov r12, rsi
or r12, r15
not r13
and r13, rcx
mov r14, r12
and r14, rcx
mov rax, r14
mov r8, r14
xor r8, rbx
xor rax, r15
not rbx
and rax, rdx
mov rdi, rax
xor rdi, rsi
or rdi, rcx
xor rdi, r10
and rbx, rdi
mov rcx, rdi
or rcx, r9
xor rcx, rax
mov rax, r13
xor rax, QWORD PTR x36$1$[rsp]
and rcx, QWORD PTR a1$[rsp]
or rax, r9
not rcx
xor rcx, rax
mov rax, QWORD PTR out2$[rsp]
xor rcx, QWORD PTR [rax]
xor rcx, r8
mov QWORD PTR [rax], rcx
mov rax, QWORD PTR x36$1$[rsp]
mov rcx, r14
or rax, r8
or rcx, r11
mov r11, r9
xor rcx, rdx
mov QWORD PTR x36$1$[rsp], rax
mov r8, rsi
mov rdx, rcx
xor rdx, r13
not rdx
and rdx, rdi
mov r10, rdx
and r10, r9
xor r10, rax
431
CHAPTER 26. 64 BITS 26.2. ARM
xor r10, rbx
not rbx
and rbx, r9
mov rax, r10
and rax, QWORD PTR a1$[rsp]
xor rbx, rax
mov rax, QWORD PTR out4$[rsp]
xor rbx, QWORD PTR [rax]
xor rbx, rcx
mov QWORD PTR [rax], rbx
mov rbx, QWORD PTR x36$1$[rsp]
and rbx, rbp
mov r9, rbx
not r9
and r9, rdi
or r8, r11
mov rax, QWORD PTR out1$[rsp]
xor r8, r9
not r9
and r9, rcx
or rdx, rbp
mov rbp, QWORD PTR [rsp+80]
or r9, rsi
xor rbx, r12
mov rcx, r11
not rcx
not r14
not r13
and rcx, r9
or r9, rdi
and rbx, r14
xor r9, r15
xor rcx, rdx
mov rdx, QWORD PTR a1$[rsp]
not r9
not rcx
and r13, r10
and r9, r11
and rcx, rdx
xor r9, rbx
mov rbx, QWORD PTR [rsp+72]
not rcx
xor rcx, QWORD PTR [rax]
or r9, rdx
not r9
xor rcx, r8
mov QWORD PTR [rax], rcx
mov rax, QWORD PTR out3$[rsp]
xor r9, r13
xor r9, QWORD PTR [rax]
xor r9, r8
mov QWORD PTR [rax], r9
pop r15
pop r14
pop r13
pop r12
pop rdi
pop rsi
ret 0
s1 ENDP
Nothing was allocated in the local stack by the compiler, x36 is synonym for a5.
By the way, there are CPUs with much more GPR’s, e.g. Itanium (128 registers).
26.2 ARM
64-bit instructions appeared in ARMv8.
432
CHAPTER 26. 64 BITS 26.3. FLOAT POINT NUMBERS
26.3 Float point numbers
How float point numbers are processed in x86-64 is explained here: 27 on the previous page.
433
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD
Chapter 27
Working with floating point numbers using SIMD
Of course, the FPU has remained in x86-compatible processors when the SIMD extensions were added.
The SIMD extensions (SSE2) offer an easier way to work with floating-point numbers.
The number format remains the same (IEEE 754).
So, modern compilers (including those generating for x86-64) usually use SIMD instructions instead of FPU ones.
It can be said that it’s good news, because it’s easier to work with them.
We are going to reuse the examples from the FPU section here: 17 on page 208.
27.1 Simple example
#include <stdio.h>
double f (double a, double b)
{
return a/3.14 + b*4.1;
};
int main()
{
printf ("%fn", f(1.2, 3.4));
};
27.1.1 x64
Listing 27.1: Optimizing MSVC 2012 x64
__real@4010666666666666 DQ 04010666666666666r ; 4.1
__real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14
a$ = 8
b$ = 16
f PROC
divsd xmm0, QWORD PTR __real@40091eb851eb851f
mulsd xmm1, QWORD PTR __real@4010666666666666
addsd xmm0, xmm1
ret 0
f ENDP
The input floating point values are passed in the XMM0-XMM3 registers, all the rest—via the stack 1
.
a is passed in XMM0, b—via XMM1. The XMM-registers are 128-bit (as we know from the section about SIMD: 25 on
page 413), but the double values are 64 bit, so only lower register half is used.
DIVSD is an SSE-instruction that stands for “Divide Scalar Double-Precision Floating-Point Values”, it just divides one
value of type double by another, stored in the lower halves of operands.
The constants are encoded by compiler in IEEE 754 format.
MULSD and ADDSD work just as the same, but do multiplication and addition.
The result of the function’s execution in type double is left in the in XMM0 register.
That is how non-optimizing MSVC works:
1MSDN: Parameter Passing
434
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Listing 27.2: MSVC 2012 x64
__real@4010666666666666 DQ 04010666666666666r ; 4.1
__real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14
a$ = 8
b$ = 16
f PROC
movsdx QWORD PTR [rsp+16], xmm1
movsdx QWORD PTR [rsp+8], xmm0
movsdx xmm0, QWORD PTR a$[rsp]
divsd xmm0, QWORD PTR __real@40091eb851eb851f
movsdx xmm1, QWORD PTR b$[rsp]
mulsd xmm1, QWORD PTR __real@4010666666666666
addsd xmm0, xmm1
ret 0
f ENDP
Slightly redundant. The input arguments are saved in the “shadow space” ( 8.2.1 on page 89), but only their lower register
halves, i.e., only 64-bit values of type double. GCC produces the same code.
27.1.2 x86
I also compiled this example for x86. Despite the fact it’s generating for x86, MSVC 2012 uses SSE2 instructions:
Listing 27.3: Non-optimizing MSVC 2012 x86
tv70 = -8 ; size = 8
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f PROC
push ebp
mov ebp, esp
sub esp, 8
movsd xmm0, QWORD PTR _a$[ebp]
divsd xmm0, QWORD PTR __real@40091eb851eb851f
movsd xmm1, QWORD PTR _b$[ebp]
mulsd xmm1, QWORD PTR __real@4010666666666666
addsd xmm0, xmm1
movsd QWORD PTR tv70[ebp], xmm0
fld QWORD PTR tv70[ebp]
mov esp, ebp
pop ebp
ret 0
_f ENDP
Listing 27.4: Optimizing MSVC 2012 x86
tv67 = 8 ; size = 8
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_f PROC
movsd xmm1, QWORD PTR _a$[esp-4]
divsd xmm1, QWORD PTR __real@40091eb851eb851f
movsd xmm0, QWORD PTR _b$[esp-4]
mulsd xmm0, QWORD PTR __real@4010666666666666
addsd xmm1, xmm0
movsd QWORD PTR tv67[esp-4], xmm1
fld QWORD PTR tv67[esp-4]
ret 0
_f ENDP
It’s almost the same code, however, there are some differences related to calling conventions: 1) the arguments are
passed not in XMM registers, but in the stack, like in the FPU examples ( 17 on page 208); 2) the result of the function is
returned in ST(0) — in order to do so, it’s copied (through local variable tv) from one of the XMM registers to ST(0).
435
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Let’s try the optimized example in OllyDbg:
Figure 27.1: OllyDbg: MOVSD loads the value of a into XMM1
436
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Figure 27.2: OllyDbg: DIVSD calculated quotient and stored it in XMM1
437
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Figure 27.3: OllyDbg: MULSD calculated product and stored it in XMM0
438
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Figure 27.4: OllyDbg: ADDSD adds value in XMM0 to XMM1
439
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE
Figure 27.5: OllyDbg: FLD left function result in ST(0)
We see that OllyDbg shows the XMM registers as pairs of double numbers, but only the lower part is used. Apparently,
OllyDbg shows them in that format because the SSE2 instructions (suffixed with -SD) are executed right now. But of course,
it’s possible to switch the register format and to see their contents as 4 float-numbers or just as 16 bytes.
440
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.2. PASSING FLOATING POINT NUMBER VIA ARGUMENTS
27.2 Passing floating point number via arguments
#include <math.h>
#include <stdio.h>
int main ()
{
printf ("32.01 ^ 1.54 = %lfn", pow (32.01,1.54));
return 0;
}
They are passed in the lower halves of the XMM0-XMM3 registers.
Listing 27.5: Optimizing MSVC 2012 x64
$SG1354 DB '32.01 ^ 1.54 = %lf', 0aH, 00H
__real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01
__real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54
main PROC
sub rsp, 40 ; 00000028H
movsdx xmm1, QWORD PTR __real@3ff8a3d70a3d70a4
movsdx xmm0, QWORD PTR __real@40400147ae147ae1
call pow
lea rcx, OFFSET FLAT:$SG1354
movaps xmm1, xmm0
movd rdx, xmm1
call printf
xor eax, eax
add rsp, 40 ; 00000028H
ret 0
main ENDP
There is no MOVSDX instruction in Intel [Int13] and AMD [AMD13a] manuals, there it is called just MOVSD. So there are
two instructions sharing the same name in x86 (about the other see: A.6.2 on page 934). Apparently, Microsoft developers
wanted to get rid of the mess, so they renamed it to MOVSDX. It just loads a value into the lower half of a XMM register.
pow() takes arguments from XMM0 and XMM1, and returns result in XMM0. It is then moved to RDX for printf(). Why?
Honestly speaking, I don’t know, maybe because printf()—is a variable arguments function?
Listing 27.6: Optimizing GCC 4.4.6 x64
.LC2:
.string "32.01 ^ 1.54 = %lfn"
main:
sub rsp, 8
movsd xmm1, QWORD PTR .LC0[rip]
movsd xmm0, QWORD PTR .LC1[rip]
call pow
; result is now in XMM0
mov edi, OFFSET FLAT:.LC2
mov eax, 1 ; number of vector registers passed
call printf
xor eax, eax
add rsp, 8
ret
.LC0:
.long 171798692
.long 1073259479
.LC1:
.long 2920577761
.long 1077936455
GCC generates clearer output. The value for printf() is passed in XMM0. By the way, here is a case when 1 is written
into EAX for printf()—this implies that one argument will be passed in vector registers, just as the standard requires
[Mit13].
27.3 Comparison example
441
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.3. COMPARISON EXAMPLE
#include <stdio.h>
double d_max (double a, double b)
{
if (a>b)
return a;
return b;
};
int main()
{
printf ("%fn", d_max (1.2, 3.4));
printf ("%fn", d_max (5.6, -4));
};
27.3.1 x64
Listing 27.7: Optimizing MSVC 2012 x64
a$ = 8
b$ = 16
d_max PROC
comisd xmm0, xmm1
ja SHORT $LN2@d_max
movaps xmm0, xmm1
$LN2@d_max:
fatret 0
d_max ENDP
Optimizing MSVC generates a code very easy to understand.
COMISD is “Compare Scalar Ordered Double-Precision Floating-Point Values and Set EFLAGS”. Essentially, that is what it
does.
Non-optimizing MSVC generates more redundant code, but it is still not hard to understand:
Listing 27.8: MSVC 2012 x64
a$ = 8
b$ = 16
d_max PROC
movsdx QWORD PTR [rsp+16], xmm1
movsdx QWORD PTR [rsp+8], xmm0
movsdx xmm0, QWORD PTR a$[rsp]
comisd xmm0, QWORD PTR b$[rsp]
jbe SHORT $LN1@d_max
movsdx xmm0, QWORD PTR a$[rsp]
jmp SHORT $LN2@d_max
$LN1@d_max:
movsdx xmm0, QWORD PTR b$[rsp]
$LN2@d_max:
fatret 0
d_max ENDP
However, GCC 4.4.6 did more optimizations and used the MAXSD (“Return Maximum Scalar Double-Precision Floating-
Point Value”) instruction, which just choose the maximum value!
Listing 27.9: Optimizing GCC 4.4.6 x64
d_max:
maxsd xmm0, xmm1
ret
442
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.4. CALCULATING MACHINE EPSILON: X64 AND SIMD
27.3.2 x86
Let’s compile this example in MSVC 2012 with optimization turned on:
Listing 27.10: Optimizing MSVC 2012 x86
_a$ = 8 ; size = 8
_b$ = 16 ; size = 8
_d_max PROC
movsd xmm0, QWORD PTR _a$[esp-4]
comisd xmm0, QWORD PTR _b$[esp-4]
jbe SHORT $LN1@d_max
fld QWORD PTR _a$[esp-4]
ret 0
$LN1@d_max:
fld QWORD PTR _b$[esp-4]
ret 0
_d_max ENDP
Almost the same, but the values of a and b are taken from the stack and the function result is left in ST(0).
If we load this example in OllyDbg, we can see how the COMISD instruction compares values and sets/clears the CF and
PF flags:
Figure 27.6: OllyDbg: COMISD changed CF and PF flags
27.4 Calculating machine epsilon: x64 and SIMD
Let’s revisit the “calculating machine epsilon” example for double listing.22.2.2.
Now we compile it for x64:
Listing 27.11: Optimizing MSVC 2012 x64
v$ = 8
calculate_machine_epsilon PROC
movsdx QWORD PTR v$[rsp], xmm0
443
CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.5. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE REVISITED
movaps xmm1, xmm0
inc QWORD PTR v$[rsp]
movsdx xmm0, QWORD PTR v$[rsp]
subsd xmm0, xmm1
ret 0
calculate_machine_epsilon ENDP
There is no way to add 1 to a value in 128-bit XMM register, so it must be placed into memory.
There is, however, the ADDSD instruction (Add Scalar Double-Precision Floating-Point Values) which can add a value to the
lowest 64-bit half of a XMM register while ignoring the higher one, but MSVC 2012 probably is not that good yet 2
.
Nevertheless, the value is then reloaded to a XMM register and subtraction occurs. SUBSD is “Subtract Scalar Double-
Precision Floating-Point Values”, i.e., it operates on the lower 64-bit part of 128-bit XMM register. The result is returned in
the XMM0 register.
27.5 Pseudo-random number generator example revisited
Let’s revisit “pseudo-random number generator example” example listing.22.1.
If we compile this in MSVC 2012, it will use the SIMD instructions for the FPU.
Listing 27.12: Optimizing MSVC 2012
__real@3f800000 DD 03f800000r ; 1
tv128 = -4
_tmp$ = -4
?float_rand@@YAMXZ PROC
push ecx
call ?my_rand@@YAIXZ
; EAX=pseudorandom value
and eax, 8388607 ; 007fffffH
or eax, 1065353216 ; 3f800000H
; EAX=pseudorandom value & 0x007fffff | 0x3f800000
; store it into local stack:
mov DWORD PTR _tmp$[esp+4], eax
; reload it as float point number:
movss xmm0, DWORD PTR _tmp$[esp+4]
; subtract 1.0:
subss xmm0, DWORD PTR __real@3f800000
; move value to ST0 by placing it in temporary variable...
movss DWORD PTR tv128[esp+4], xmm0
; ... and reloading it into ST0:
fld DWORD PTR tv128[esp+4]
pop ecx
ret 0
?float_rand@@YAMXZ ENDP
All instructions have the -SS suffix, which stands for “Scalar Single”. “Scalar” implies that only one value is stored in the
register. “Single” stands for float data type.
27.6 Summary
Only the lower half of XMM registers is used in all examples here, to store number in IEEE 754 format.
Essentially, all instructions prefixed by -SD (“Scalar Double-Precision”)—are instructions working with floating point
numbers in IEEE 754 format, stored in the lower 64-bit half of a XMM register.
And it is easier than in the FPU, probably because the SIMD extensions were evolved in a less chaotic way than the FPU
ones in the past. The stack register model is not used.
If you would try to replace double with float in these examples, the same instructions will be used, but prefixed with -SS
(“Scalar Single-Precision”), for example, MOVSS, COMISS, ADDSS, etc.
“Scalar” implies that the SIMD register containing only one value instead of several. Instructions working with several
values in a register simultaneously have “Packed” in their name.
Needless to say, the SSE2 instructions work with 64-bit IEEE 754 numbers (double), while the internal representation of the
floating-point numbers in FPU is 80-bit numbers. Hence, the FPU may produce less round-off errors and as a consequence,
FPU may give more precise calculation results.
2As an exercise, you may try to rework this code to eliminate the usage of the local stack.
444
CHAPTER 28. MORE ABOUT ARM
Chapter 28
More about ARM
28.1 Number sign (#) before number
The Keil compiler, IDA and objdump precede all numbers with the “#” number sign, for example: listing.14.1.4. But when
GCC 4.9 generates assembly language output, it doesn’t, for example: listing.39.3.
The ARM listings in this book are somewhat mixed.
I’m not sure which method is right. Supposedly, one has to obey the rules accepted in environment he/she works in.
28.2 Addressing modes
This instruction is possible in ARM64:
ldr x0, [x29,24]
This means add 24 to the value in X29 and load the value from this address. Please note that 24 is inside the brackets.
The meaning is different if the number is outside the brackets:
ldr w4, [x1],28
This means load the value at the address in X1, then add 28 to X1.
ARM allows you to add or subtract a constant to/from the address used for loading. And it’s possible to do that both
before and after loading.
There is no such addressing mode in x86, but it is present in some other processors, even on PDP-11. There is a
legend that the pre-increment, post-increment, pre-decrement and post-decrement modes in PDP-11, were “guilty” for the
appearance of such C language (which developed on PDP-11) constructs as *ptr++, *++ptr, *ptr--, *--ptr. By the way, this is
one of the hard to memorize C features. This is how it is:
C term ARM term C statement how it works
Post-increment post-indexed addressing *ptr++ use *ptr value,
then increment ptr pointer
Post-decrement post-indexed addressing *ptr-- use *ptr value,
then decrement ptr pointer
Pre-increment pre-indexed addressing *++ptr increment ptr pointer,
then use *ptr value
Pre-decrement pre-indexed addressing *--ptr decrement ptr pointer,
then use *ptr value
Pre-indexing is marked with an exclamation mark in the ARM assembly language. For example, see line 2 in listing.3.15.
Dennis Ritchie (one of the creators of the C language) mentioned that it probably was invented by Ken Thompson (another
C creator) because this processor feature was present in PDP-7 [Rit86][Rit93]. Thus, C language compilers may use it, if it
is present on the target processor.
That’s very convenient for array processing.
28.3 Loading a constant into a register
28.3.1 32-bit ARM
Aa we already know, all instructions have a length of 4 bytes in ARM mode and 2 bytes in Thumb mode. Then how can we
load a 32-bit value into a register, if it’s not possible to encode it in one instruction?
Let’s try:
445
CHAPTER 28. MORE ABOUT ARM 28.3. LOADING A CONSTANT INTO A REGISTER
unsigned int f()
{
return 0x12345678;
};
Listing 28.1: GCC 4.6.3 -O3 ARM mode
f:
ldr r0, .L2
bx lr
.L2:
.word 305419896 ; 0x12345678
So, the 0x12345678 value is just stored aside in memory and loaded if needed. But it’s possible to get rid of the
additional memory access.
Listing 28.2: GCC 4.6.3 -O3 -march=armv7-a (ARM mode)
movw r0, #22136 ; 0x5678
movt r0, #4660 ; 0x1234
bx lr
We see that the value is loaded into the register by parts, the lower part first (using MOVW), then the higher (using MOVT).
This implies that 2 instructions are necessary in ARM mode for loading a 32-bit value into a register. It’s not a real
problem, because in fact there are not many constants in real code (except of 0 and 1). Does it mean that the two-instruction
version is slower than one-instruction version? Doubtfully. Most likely, modern ARM processors are able to detect such
sequences and execute them fast.
On the other hand, IDA is able to detect such patterns in the code and disassembles this function as:
MOV R0, 0x12345678
BX LR
28.3.2 ARM64
uint64_t f()
{
return 0x12345678ABCDEF01;
};
Listing 28.3: GCC 4.9.1 -O3
mov x0, 61185 ; 0xef01
movk x0, 0xabcd, lsl 16
movk x0, 0x5678, lsl 32
movk x0, 0x1234, lsl 48
ret
MOVK stands for “MOV Keep”, i.e., it writes a 16-bit value into the register, not touching the rest of the bits. The LSL suffix
shifts left the value by 16, 32 and 48 bits at each step. The shifting is done before loading. This implies that 4 instructions
are necessary to load a 64-bit value into a register.
Storing floating-point number into register
It’s possible to store a floating-point number into a D-register using only one instruction.
For example:
double a()
{
return 1.5;
};
Listing 28.4: GCC 4.9.1 -O3 + objdump
0000000000000000 <a>:
0: 1e6f1000 fmov d0, #1.500000000000000000e+000
4: d65f03c0 ret
446
CHAPTER 28. MORE ABOUT ARM 28.4. RELOCS IN ARM64
The number 1.5 was indeed encoded in a 32-bit instruction. But how? In ARM64, there are 8 bits in the FMOV instruction
for encoding some floating-point numbers. The algorithm is called VFPExpandImm() in [ARM13a]. This is also called
minifloat1
. I tried it with different values: the compiler is able to encode 30.0 and 31.0, but it couldn’t encode 32.0, as 8
bytes have to be allocated for this number in the IEEE 754 format:
double a()
{
return 32;
};
Listing 28.5: GCC 4.9.1 -O3
a:
ldr d0, .LC0
ret
.LC0:
.word 0
.word 1077936128
28.4 Relocs in ARM64
As we know, there are 4-byte instructions in ARM64, so it is impossible to write a large number into a register using a single
instruction. Nevertheless, an executable image can be loaded at any random address in memory, so that’s why relocs exists.
Read more about them (in relation to Win32 PE): 68.2.6 on page 688.
The address is formed using the ADRP and ADD instruction pair in ARM64. The first loads a 4Kb-page address and the
second one adds the remainder. I compiled the example from “Hello, world!” (listing.6) in GCC (Linaro) 4.9 under win32:
Listing 28.6: GCC (Linaro) 4.9 and objdump of object file
...>aarch64-linux-gnu-gcc.exe hw.c -c
...>aarch64-linux-gnu-objdump.exe -d hw.o
...
0000000000000000 <main>:
0: a9bf7bfd stp x29, x30, [sp,#-16]!
4: 910003fd mov x29, sp
8: 90000000 adrp x0, 0 <main>
c: 91000000 add x0, x0, #0x0
10: 94000000 bl 0 <printf>
14: 52800000 mov w0, #0x0 // #0
18: a8c17bfd ldp x29, x30, [sp],#16
1c: d65f03c0 ret
...>aarch64-linux-gnu-objdump.exe -r hw.o
...
RELOCATION RECORDS FOR [.text]:
OFFSET TYPE VALUE
0000000000000008 R_AARCH64_ADR_PREL_PG_HI21 .rodata
000000000000000c R_AARCH64_ADD_ABS_LO12_NC .rodata
0000000000000010 R_AARCH64_CALL26 printf
So there are 3 relocs in this object file.
• The first one takes the page address, cuts the lowest 12 bits and writes the remaining high 21 bits to the ADRP
instruction’s bit fields. This is because we don’t need to encode the low 12 bits, and the ADRP instruction has space
only for 21 bits.
• The second one puts the 12 bits of the address relative to the page start into the ADD instruction’s bit fields.
• The last, 26-bit one, is applied to the instruction at address 0x10 where the jump to the printf() function is. All
ARM64 (and in ARM in ARM mode) instruction addresses have zeroes in the two lowest bits (because all instructions
have a size of 4 bytes), so one need to encode only the highest 26 bits of 28-bit address space (±128MB).
1wikipedia
447
CHAPTER 28. MORE ABOUT ARM 28.4. RELOCS IN ARM64
There are no such relocs in the executable file: because it’s known where the “Hello!” string is located, in which page,
and the address of puts() is also known. So there are values set already in the ADRP, ADD and BL instructions (the linker
has written them while linking):
Listing 28.7: objdump of executable file
0000000000400590 <main>:
400590: a9bf7bfd stp x29, x30, [sp,#-16]!
400594: 910003fd mov x29, sp
400598: 90000000 adrp x0, 400000 <_init-0x3b8>
40059c: 91192000 add x0, x0, #0x648
4005a0: 97ffffa0 bl 400420 <puts@plt>
4005a4: 52800000 mov w0, #0x0 // #0
4005a8: a8c17bfd ldp x29, x30, [sp],#16
4005ac: d65f03c0 ret
...
Contents of section .rodata:
400640 01000200 00000000 48656c6c 6f210000 ........Hello!..
As an example, let’s try to disassemble the BL instruction manually.
0x97ffffa0 is 10010111111111111111111110100000b. According to [ARM13a, p. C5.6.26], imm26 is the last 26 bits:
imm26 = 11111111111111111110100000. It is 0x3FFFFA0, but the MSB is 1, so the number is negative, and in terms
of modular arithmetic by modulo 232
, it is 0xFFFFFFA0. Again, by modulo 232
, 0xFFFFFFA0 * 4 = 0xFFFFFE80, and
0x4005a0 + FFFFFE80 = 0x400420 (please note: we consider the address of the BL instruction, not the current value of
PC, which may be different! ). So the destination address is 0x400420.
More about ARM64-related relocs: [ARM13b].
448
CHAPTER 29. MORE ABOUT MIPS
Chapter 29
More about MIPS
29.1 Loading constants into register
unsigned int f()
{
return 0x12345678;
};
All instructions in MIPS, just like ARM, have a of 32-bit, so it’s not possible to embed a 32-bit constant into one instruction.
So this translates to at least two instructions: the first loads the high part of the 32-bit number and the second one applies
an OR operation, which effectively sets the low 16-bit part of the target register:
Listing 29.1: GCC 4.4.5 -O3 (assembly output)
li $2,305397760 # 0x12340000
j $31
ori $2,$2,0x5678 ; branch delay slot
IDA is fully aware of such frequently encountered code patterns, so, for convenience it shows the last ORI instruction as
the LI pseudoinstruction, which allegedly loads a full 32-bit number into the $V0 register.
Listing 29.2: GCC 4.4.5 -O3 (IDA)
lui $v0, 0x1234
jr $ra
li $v0, 0x12345678 ; branch delay slot
The GCC assembly output has the LI pseudoinstruction, but in fact, LUI (“Load Upper Imeddiate”) is there, which stores a
16-bit value into the high part of the register.
29.2 Further reading about MIPS
[Swe10].
449
Part II
Important fundamentals
450
CHAPTER 30. SIGNED NUMBER REPRESENTATIONS
Chapter 30
Signed number representations
There are several methods for representing signed numbers1
, but “two’s complement” is the most popular one in computers.
Here is a table for some byte values:
binary hexadecimal unsigned signed (2’s complement)
01111111 0x7f 127 127
01111110 0x7e 126 126
...
00000110 0x6 6 6
00000101 0x5 5 5
00000100 0x4 4 4
00000011 0x3 3 3
00000010 0x2 2 2
00000001 0x1 1 1
00000000 0x0 0 0
11111111 0xff 255 -1
11111110 0xfe 254 -2
11111101 0xfd 253 -3
11111100 0xfc 252 -4
11111011 0xfb 251 -5
11111010 0xfa 250 -6
...
10000010 0x82 130 -126
10000001 0x81 129 -127
10000000 0x80 128 -128
The difference between signed and unsigned numbers is that if we represent 0xFFFFFFFE and 0x0000002 as unsigned,
then the first number (4294967294) is bigger than the second one(2). If we represent them both as signed, the first one is to
be −2, and it is smaller than the second (2). That is the reason why conditional jumps ( 12 on page 111) are present both for
signed (e.g. JG, JL) and unsigned (JA, JBE) operations.
For the sake of simplicity, that is what one need to know:
• Number can be signed or unsigned.
• C/C++ signed types:
– int64_t (-9223372036854775806..9223372036854775807) or
0x8000000000000000..0x7FFFFFFFFFFFFFFF),
– int (-2147483646..2147483647 or 0x80000000..0x7FFFFFFF),
– char (-127..128 or 0x7F..0x80),
– ssize_t.
Unsigned:
– uint64_t (0..18446744073709551615 or 0..0xFFFFFFFFFFFFFFFF),
– unsigned int (0..4294967295 or 0..0xFFFFFFFF),
– unsigned char (0..255 or 0..0xFF),
1wikipedia
451
CHAPTER 30. SIGNED NUMBER REPRESENTATIONS
– size_t.
• Signed types have the sign in the most significant bit: 1 mean “minus”, 0 mean “plus”.
• Promoting to a larger data types is simple: 24.5 on page 411.
• Negation is simple: just invert all bits and add 1. We can remember that a number of inverse sign is located on the
opposite side at the same proximity from zero. The addition of one is needed because zero is present in the middle.
• The addition and subtraction operations work well for both signed and unsigned values. But for multiplication and
division operations, x86 has different instructions: IDIV/IMUL for signed and DIV/MUL for unsigned.
• Here are some more instructions that work with signed numbers: CBW/CWD/CWDE/CDQ/CDQE ( A.6.3 on page 936),
MOVSX ( 15.1.1 on page 189), SAR ( A.6.3 on page 940).
452
CHAPTER 31. ENDIANNESS
Chapter 31
Endianness
The endianness is a way of representing values in memory.
31.1 Big-endian
The 0x12345678 value is represented in memory as:
address in memory byte value
+0 0x12
+1 0x34
+2 0x56
+3 0x78
Big-endian CPUs include Motorola 68k, IBM POWER.
31.2 Little-endian
The 0x12345678 value is represented in memory as:
address in memory byte value
+0 0x78
+1 0x56
+2 0x34
+3 0x12
Little-endian CPUs include Intel x86.
31.3 Example
I have big-endian MIPS Linux installed and ready in QEMU 1
.
And I have compiled this simple example:
#include <stdio.h>
int main()
{
int v, i;
v=123;
printf ("%02X %02X %02X %02Xn",
*(char*)&v,
*(((char*)&v)+1),
*(((char*)&v)+2),
*(((char*)&v)+3));
};
And after running it I get:
1I’ve uploaded it here: http://go.yurichev.com/17008
453
CHAPTER 31. ENDIANNESS 31.4. BI-ENDIAN
root@debian-mips:~# ./a.out
00 00 00 7B
That is it. 0x7B is 123 in decimal. In little-endian architectures, 7B is the first byte (you can check on x86 or x86-64),
but here it is the last one, because the highest byte goes first.
That’s why there are separate Linux distributions for MIPS (“mips” (big-endian) and “mipsel” (little-endian)). It is impos-
sible for a binary compiled for one endianness to work on an OS with different endianness.
There is another example of MIPS big-endiannes in this book: 21.4.3 on page 369.
31.4 Bi-endian
CPUs that may switch between endianness are ARM, PowerPC, SPARC, MIPS, IA642
, etc.
31.5 Converting data
The BSWAP instruction can be used for conversion.
TCP/IP network data packets use the big-endian conventions, so that is why a program working on a little-endian archi-
tecture has to convert the values.
The htonl() and htons() functions are usually used.
In TCP/IP, big-endian is also called “network byte order”, while byte order on the computer—“host byte order”. “host byte
order” is little-endian on Intel x86 and other little-endian architectures, but it is big-endian on IBM POWER, so htonl()
and htons() are not shuffle any bytes on latter.
2Intel Architecture 64 (Itanium): 93 on page 877
454
CHAPTER 32. MEMORY
Chapter 32
Memory
There are 3 main types of memory:
• Global memory. AKA “static memory allocation”. No need to allocate explicitly, the allocation is done just by declaring
variables/arrays globally. These are global variables, residing in the data or constant segments. The are available
globally (hence, considered as an anti-pattern). Not convenient for buffers/arrays, because they must have a fixed
size. Buffer overflows that occur here usually overwrite variables or buffers reside next to them in memory. There’s
an example in this book: 7.2 on page 65.
• Stack. AKA “allocate on stack”. The allocation is done just by declaring variables/arrays locally in the function. These
are usually local variables for the function. Sometimes these local variable are also available to descending functions
(if one passes a pointer to a variable to the function to be executed). Allocation and deallocation are very fast, only SP
needs to be shifted. But they’re also not convenient for buffers/arrays, because the buffer size has to be fixed, unless
alloca() ( 5.2.4 on page 25) (or a variable-length array) is used. Buffer overflows usually overwrite important stack
structures: 18.2 on page 264.
• Heap. AKA “dynamic memory allocation”. Allocation is done by calling malloc()/free() or new/delete in C++.
This is the most convenient method: the block size may be set at runtime. Resizing is possible (using realloc()), but
can be slow. This is the slowest way to allocate memory: the memory allocator must support and update all control
structures while allocating and deallocating. Buffer overflows usually overwrite these structures. Heap allocations
are also source of memory leak problems: each memory block has to be deallocated explicitly, but one may forget
about it, or do it incorrectly. Another problem is the “use after free”—using a memory block after free() was called
on it, which is very dangerous. Example in this book: 21.2 on page 352.
455
CHAPTER 33. CPU
Chapter 33
CPU
33.1 Branch predictors
Some modern compilers try to get rid of conditional jump instructions. Examples in this book are: 12.1.2 on page 122, 12.3
on page 129, 19.5.2 on page 330.
This is because the branch predictor is not always perfect, so the compilers try to do without conditional jumps, if possible.
Conditional instructions in ARM (like ADRcc) are one way, another one is the CMOVcc x86 instruction.
33.2 Data dependencies
Modern CPUs are able to execute instructions simultaneously (OOE1
), but in order to do so, the results of one instruction in a
group must not influence the execution of others. Hence, the compiler endeavors to use instructions with minimal influence
to the CPU state.
That’s why the LEA instruction is so popular, because it does not modify CPU flags, while other arithmetic instructions
do this.
1Out-of-order execution
456
CHAPTER 34. HASH FUNCTIONS
Chapter 34
Hash functions
A very simple example is CRC32, an algorithm that provides “stronger” checksum for integrity checking purposes. it is
impossible to restore the original text from the hash value, it has much less information: the input can be long, but CRC32’s
result is always limited to 32 bits. But CRC32 is not cryptographically secure: it is known how to alter a text in a way that
the resulting CRC32 hash value will be the one we need. Cryptographic hash functions are protected from this.
Such functions are MD5, SHA1, etc., and they are widely used to hash user passwords in order to store them in a database.
Indeed: an internet forum database may not contain user passwords (a stolen database can compromise all user’s passwords)
but only hashes (a cracker can’t reveal passwords). Besides, an internet forum engine is not aware of your password, it has
only to check if its hash is the same as the one in the database, and give you access if they match. One of the simplest
password cracking methods is just to try hashing all possible passwords in order to see which is matching the resulting value
that we need. Other methods are much more complex.
34.1 How one-way function works?
One-way function is a function which is able to transform one value into another, while it is impossible (or very hard) to do
reverse it back. Some people have difficulties while understanding how it’s possible at all. I’ll try to demonstrate it.
We’ve got vector of 10 numbers in range 0..9, each encounters only once, for example:
4 6 0 1 3 5 7 8 9 2
Algorithm of simplest possible one-way function is:
• take a number at zeroth position (4 in our case);
• take a number at first position (6 in our case);
• swap numbers at positions of 4 and 6.
Let’s mark numbers on positions of 4 and 6:
4 6 0 1 3 5 7 8 9 2
^ ^
Let’s swap them and we’ve got a result:
4 6 0 1 7 5 3 8 9 2
While looking at the result and even if we know algorithm, we can’t say unambiguously initial numbers set. Because first
two numbers could be 0 and/or 1, and then they could be participate in swapping procedure.
This is utterly simplified example for demonstration, real one-way functions may be much more complex.
457
Part III
Slightly more advanced examples
458
CHAPTER 35. TEMPERATURE CONVERTING
Chapter 35
Temperature converting
Another very popular example in programming books for beginners is a small program that converts Fahrenheit temperature
to Celsius or back.
C =
5 ⋅ (F − 32)
9
I have also added simple error handling: 1) we must check if the user has entered a correct number; 2) we must check if
the Celsius temperature is not below −273 (which is below absolute zero, as we may remember from school physics lessons).
The exit() function terminates the program instantly, without returning to the caller function.
35.1 Integer values
#include <stdio.h>
#include <stdlib.h>
int main()
{
int celsius, fahr;
printf ("Enter temperature in Fahrenheit:n");
if (scanf ("%d", &fahr)!=1)
{
printf ("Error while parsing your inputn");
exit(0);
};
celsius = 5 * (fahr-32) / 9;
if (celsius<-273)
{
printf ("Error: incorrect temperature!n");
exit(0);
};
printf ("Celsius: %dn", celsius);
};
35.1.1 Optimizing MSVC 2012 x86
Listing 35.1: Optimizing MSVC 2012 x86
$SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H
$SG4230 DB '%d', 00H
$SG4231 DB 'Error while parsing your input', 0aH, 00H
$SG4233 DB 'Error: incorrect temperature!', 0aH, 00H
$SG4234 DB 'Celsius: %d', 0aH, 00H
_fahr$ = -4 ; size = 4
_main PROC
push ecx
push esi
mov esi, DWORD PTR __imp__printf
push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:'
459
CHAPTER 35. TEMPERATURE CONVERTING 35.1. INTEGER VALUES
call esi ; call printf()
lea eax, DWORD PTR _fahr$[esp+12]
push eax
push OFFSET $SG4230 ; '%d'
call DWORD PTR __imp__scanf
add esp, 12 ; 0000000cH
cmp eax, 1
je SHORT $LN2@main
push OFFSET $SG4231 ; 'Error while parsing your input'
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
$LN9@main:
$LN2@main:
mov eax, DWORD PTR _fahr$[esp+8]
add eax, -32 ; ffffffe0H
lea ecx, DWORD PTR [eax+eax*4]
mov eax, 954437177 ; 38e38e39H
imul ecx
sar edx, 1
mov eax, edx
shr eax, 31 ; 0000001fH
add eax, edx
cmp eax, -273 ; fffffeefH
jge SHORT $LN1@main
push OFFSET $SG4233 ; 'Error: incorrect temperature!'
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
$LN10@main:
$LN1@main:
push eax
push OFFSET $SG4234 ; 'Celsius: %d'
call esi ; call printf()
add esp, 8
; return 0 - by C99 standard
xor eax, eax
pop esi
pop ecx
ret 0
$LN8@main:
_main ENDP
What we can say about it:
• The address of printf() is first loaded in the ESI register, so the subsequent printf() calls are done just by the
CALL ESI instruction. It’s a very popular compiler technique, possible if several consequent calls to the same function
are present in the code, and/or if there is a free register which can be used for this.
• We see the ADD EAX, -32 instruction at the place where 32 has to be subtracted from the value. EAX = EAX +
(−32) is equivalent to EAX = EAX − 32 and somehow, the compiler decided to use ADD instead of SUB. Maybe it’s
worth it, but I’m not sure.
• The LEA instruction is used when the value is to be multiplied by 5: lea ecx, DWORD PTR [eax+eax*4]. Yes,
i + i ∗ 4 is equivalent to i ∗ 5 and LEA works faster then IMUL. By the way, the SHL EAX, 2 / ADD EAX, EAX
instruction pair could be also used here instead— some compilers do it like.
• The division by multiplication trick ( 41 on page 488) is also used here.
• main() returns 0 if we don’t have return 0 at its end. The C99 standard tells us [ISO07, p. 5.1.2.2.3] that main()
will return 0 in case the return statement is missing. This rule works only for the main() function. Though, MSVC
doesn’t officially support C99, but maybe it support it partially?
35.1.2 Optimizing MSVC 2012 x64
The code is almost the same, but I’ve found INT 3 instructions after each exit() call:
460
CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES
xor ecx, ecx
call QWORD PTR __imp_exit
int 3
INT 3 is a debugger breakpoint.
It is known that exit() is one of the functions which can never return 1
, so if it does, something really odd has happened
and it’s time to load the debugger.
35.2 Floating-point values
#include <stdio.h>
#include <stdlib.h>
int main()
{
double celsius, fahr;
printf ("Enter temperature in Fahrenheit:n");
if (scanf ("%lf", &fahr)!=1)
{
printf ("Error while parsing your inputn");
exit(0);
};
celsius = 5 * (fahr-32) / 9;
if (celsius<-273)
{
printf ("Error: incorrect temperature!n");
exit(0);
};
printf ("Celsius: %lfn", celsius);
};
MSVC 2010 x86 uses FPU instructions…
Listing 35.2: Optimizing MSVC 2010 x86
$SG4038 DB 'Enter temperature in Fahrenheit:', 0aH, 00H
$SG4040 DB '%lf', 00H
$SG4041 DB 'Error while parsing your input', 0aH, 00H
$SG4043 DB 'Error: incorrect temperature!', 0aH, 00H
$SG4044 DB 'Celsius: %lf', 0aH, 00H
__real@c071100000000000 DQ 0c071100000000000r ; -273
__real@4022000000000000 DQ 04022000000000000r ; 9
__real@4014000000000000 DQ 04014000000000000r ; 5
__real@4040000000000000 DQ 04040000000000000r ; 32
_fahr$ = -8 ; size = 8
_main PROC
sub esp, 8
push esi
mov esi, DWORD PTR __imp__printf
push OFFSET $SG4038 ; 'Enter temperature in Fahrenheit:'
call esi ; call printf()
lea eax, DWORD PTR _fahr$[esp+16]
push eax
push OFFSET $SG4040 ; '%lf'
call DWORD PTR __imp__scanf
add esp, 12 ; 0000000cH
cmp eax, 1
je SHORT $LN2@main
push OFFSET $SG4041 ; 'Error while parsing your input'
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
1another popular one is longjmp()
461
CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES
$LN2@main:
fld QWORD PTR _fahr$[esp+12]
fsub QWORD PTR __real@4040000000000000 ; 32
fmul QWORD PTR __real@4014000000000000 ; 5
fdiv QWORD PTR __real@4022000000000000 ; 9
fld QWORD PTR __real@c071100000000000 ; -273
fcomp ST(1)
fnstsw ax
test ah, 65 ; 00000041H
jne SHORT $LN1@main
push OFFSET $SG4043 ; 'Error: incorrect temperature!'
fstp ST(0)
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
$LN1@main:
sub esp, 8
fstp QWORD PTR [esp]
push OFFSET $SG4044 ; 'Celsius: %lf'
call esi
add esp, 12 ; 0000000cH
; return 0 - by C99 standard
xor eax, eax
pop esi
add esp, 8
ret 0
$LN10@main:
_main ENDP
…but MSVC 2012 uses SIMD instructions instead:
Listing 35.3: Optimizing MSVC 2010 x86
$SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H
$SG4230 DB '%lf', 00H
$SG4231 DB 'Error while parsing your input', 0aH, 00H
$SG4233 DB 'Error: incorrect temperature!', 0aH, 00H
$SG4234 DB 'Celsius: %lf', 0aH, 00H
__real@c071100000000000 DQ 0c071100000000000r ; -273
__real@4040000000000000 DQ 04040000000000000r ; 32
__real@4022000000000000 DQ 04022000000000000r ; 9
__real@4014000000000000 DQ 04014000000000000r ; 5
_fahr$ = -8 ; size = 8
_main PROC
sub esp, 8
push esi
mov esi, DWORD PTR __imp__printf
push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:'
call esi ; call printf()
lea eax, DWORD PTR _fahr$[esp+16]
push eax
push OFFSET $SG4230 ; '%lf'
call DWORD PTR __imp__scanf
add esp, 12 ; 0000000cH
cmp eax, 1
je SHORT $LN2@main
push OFFSET $SG4231 ; 'Error while parsing your input'
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
$LN9@main:
$LN2@main:
movsd xmm1, QWORD PTR _fahr$[esp+12]
subsd xmm1, QWORD PTR __real@4040000000000000 ; 32
movsd xmm0, QWORD PTR __real@c071100000000000 ; -273
mulsd xmm1, QWORD PTR __real@4014000000000000 ; 5
divsd xmm1, QWORD PTR __real@4022000000000000 ; 9
comisd xmm0, xmm1
462
CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES
jbe SHORT $LN1@main
push OFFSET $SG4233 ; 'Error: incorrect temperature!'
call esi ; call printf()
add esp, 4
push 0
call DWORD PTR __imp__exit
$LN10@main:
$LN1@main:
sub esp, 8
movsd QWORD PTR [esp], xmm1
push OFFSET $SG4234 ; 'Celsius: %lf'
call esi ; call printf()
add esp, 12 ; 0000000cH
; return 0 - by C99 standard
xor eax, eax
pop esi
add esp, 8
ret 0
$LN8@main:
_main ENDP
Of course, SIMD instructions are available in x86 mode, including those working with floating point numbers. It’s
somewhat easier to use them for calculations, so the new Microsoft compiler uses them.
We can also see that the −273 value is loaded into XMM0 register too early. And that’s OK, because the compiler may emit
instructions not in the order they are in the source code.
463
CHAPTER 36. FIBONACCI NUMBERS
Chapter 36
Fibonacci numbers
Another widespread example used in programming textbooks is a recursive function that generates the Fibonacci numbers1
.
The sequence is very simple: each consecutive number is the sum of the previous two. The first two numbers are 1’s or 0, 1
and 1.
The sequence starts like this:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181...
36.1 Example #1
The implementation is simple. This program generates the sequence until 21.
#include <stdio.h>
void fib (int a, int b, int limit)
{
printf ("%dn", a+b);
if (a+b > limit)
return;
fib (b, a+b, limit);
};
int main()
{
printf ("0n1n1n");
fib (1, 1, 20);
};
Listing 36.1: MSVC 2010 x86
_TEXT SEGMENT
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_limit$ = 16 ; size = 4
_fib PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
add eax, DWORD PTR _b$[ebp]
push eax
push OFFSET $SG2750 ; "%d"
call DWORD PTR __imp__printf
add esp, 8
mov ecx, DWORD PTR _limit$[ebp]
push ecx
mov edx, DWORD PTR _a$[ebp]
add edx, DWORD PTR _b$[ebp]
push edx
mov eax, DWORD PTR _b$[ebp]
push eax
call _fib
add esp, 12
1http://go.yurichev.com/17332
464
CHAPTER 36. FIBONACCI NUMBERS 36.1. EXAMPLE #1
pop ebp
ret 0
_fib ENDP
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG2753 ; "0n1n1n"
call DWORD PTR __imp__printf
add esp, 4
push 20
push 1
push 1
call _fib
add esp, 12
xor eax, eax
pop ebp
ret 0
_main ENDP
I want to illustrate the stack frames with this.
465
CHAPTER 36. FIBONACCI NUMBERS 36.1. EXAMPLE #1
Let’s load the example in OllyDbg and trace to the last call of f():
Figure 36.1: OllyDbg: last call of f()
466
CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2
Let’s investigate the stack more closely. I have added some comments to it 2
:
0035F940 00FD1039 RETURN to fib.00FD1039 from fib.00FD1000
0035F944 00000008 1st argument: a
0035F948 0000000D 2nd argument: b
0035F94C 00000014 3rd argument: limit
0035F950 /0035F964 saved EBP register
0035F954 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000
0035F958 |00000005 1st argument: a
0035F95C |00000008 2nd argument: b
0035F960 |00000014 3rd argument: limit
0035F964 ]0035F978 saved EBP register
0035F968 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000
0035F96C |00000003 1st argument: a
0035F970 |00000005 2nd argument: b
0035F974 |00000014 3rd argument: limit
0035F978 ]0035F98C saved EBP register
0035F97C |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000
0035F980 |00000002 1st argument: a
0035F984 |00000003 2nd argument: b
0035F988 |00000014 3rd argument: limit
0035F98C ]0035F9A0 saved EBP register
0035F990 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000
0035F994 |00000001 1st argument: a
0035F998 |00000002 2nd argument: b
0035F99C |00000014 3rd argument: limit
0035F9A0 ]0035F9B4 saved EBP register
0035F9A4 |00FD105C RETURN to fib.00FD105C from fib.00FD1000
0035F9A8 |00000001 1st argument: a 
0035F9AC |00000001 2nd argument: b | prepared in main() for f1()
0035F9B0 |00000014 3rd argument: limit /
0035F9B4 ]0035F9F8 saved EBP register
0035F9B8 |00FD11D0 RETURN to fib.00FD11D0 from fib.00FD1040
0035F9BC |00000001 main() 1st argument: argc 
0035F9C0 |006812C8 main() 2nd argument: argv | prepared in CRT for main()
0035F9C4 |00682940 main() 3rd argument: envp /
The function is recursive 3
, hence stack looks like a “sandwich”. We see that the limit argument is always the same
(0x14 or 20), but the a and b arguments are different for each call. There are also the RA-s and the saved EBP values.
OllyDbg is able to determine the EBP-based frames, so it draws these brackets. The values inside each bracket make the
stack frame, in other words, the stack area which each function incarnation uses as scratch space. We can also say that each
function incarnation must not access stack elements beyond the boundaries of its frame (excluding function arguments),
although it’s technically possible. It’s usually true, unless the function has bugs. Each saved EBP value is the address of the
previous stack frame: this is the reason why some debuggers can easily divide the stack in frames and dump each function’s
arguments.
As we see here, each function incarnation prepares the arguments for the next function call.
At the very end we see the 3 arguments for main(). argc is 1 (yes, indeed, I ran the program without command-line
arguments).
It’s easy to create a stack overflow: just remove (or comment) the limit check and it will crash with exception 0xC00000FD
(stack overflow).
36.2 Example #2
My function has some redundancy, so let’s add a new local variable next and replace all “a+b” with it:
#include <stdio.h>
void fib (int a, int b, int limit)
{
int next=a+b;
printf ("%dn", next);
if (next > limit)
return;
fib (b, next, limit);
};
2By the way, it’s possible to select several entries in OllyDbg and copy them to the clipboard (Ctrl-C). That’s what I just did.
3i.e., it calls itself
467
CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2
int main()
{
printf ("0n1n1n");
fib (1, 1, 20);
};
This is the output of non-optimizing MSVC, so the next variable is actually allocated in the local stack:
Listing 36.2: MSVC 2010 x86
_next$ = -4 ; size = 4
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_limit$ = 16 ; size = 4
_fib PROC
push ebp
mov ebp, esp
push ecx
mov eax, DWORD PTR _a$[ebp]
add eax, DWORD PTR _b$[ebp]
mov DWORD PTR _next$[ebp], eax
mov ecx, DWORD PTR _next$[ebp]
push ecx
push OFFSET $SG2751 ; '%d'
call DWORD PTR __imp__printf
add esp, 8
mov edx, DWORD PTR _next$[ebp]
cmp edx, DWORD PTR _limit$[ebp]
jle SHORT $LN1@fib
jmp SHORT $LN2@fib
$LN1@fib:
mov eax, DWORD PTR _limit$[ebp]
push eax
mov ecx, DWORD PTR _next$[ebp]
push ecx
mov edx, DWORD PTR _b$[ebp]
push edx
call _fib
add esp, 12
$LN2@fib:
mov esp, ebp
pop ebp
ret 0
_fib ENDP
_main PROC
push ebp
mov ebp, esp
push OFFSET $SG2753 ; "0n1n1n"
call DWORD PTR __imp__printf
add esp, 4
push 20
push 1
push 1
call _fib
add esp, 12
xor eax, eax
pop ebp
ret 0
_main ENDP
468
CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2
Let’s load OllyDbg once again:
Figure 36.2: OllyDbg: last call of f()
Now the next variable is present in each frame.
469
CHAPTER 36. FIBONACCI NUMBERS 36.3. SUMMARY
Let’s investigate the stack more closely. I have added my comments again:
0029FC14 00E0103A RETURN to fib2.00E0103A from fib2.00E01000
0029FC18 00000008 1st argument: a
0029FC1C 0000000D 2nd argument: b
0029FC20 00000014 3rd argument: limit
0029FC24 0000000D "next" variable
0029FC28 /0029FC40 saved EBP register
0029FC2C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000
0029FC30 |00000005 1st argument: a
0029FC34 |00000008 2nd argument: b
0029FC38 |00000014 3rd argument: limit
0029FC3C |00000008 "next" variable
0029FC40 ]0029FC58 saved EBP register
0029FC44 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000
0029FC48 |00000003 1st argument: a
0029FC4C |00000005 2nd argument: b
0029FC50 |00000014 3rd argument: limit
0029FC54 |00000005 "next" variable
0029FC58 ]0029FC70 saved EBP register
0029FC5C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000
0029FC60 |00000002 1st argument: a
0029FC64 |00000003 2nd argument: b
0029FC68 |00000014 3rd argument: limit
0029FC6C |00000003 "next" variable
0029FC70 ]0029FC88 saved EBP register
0029FC74 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000
0029FC78 |00000001 1st argument: a 
0029FC7C |00000002 2nd argument: b | prepared in f1() for next f1()
0029FC80 |00000014 3rd argument: limit /
0029FC84 |00000002 "next" variable
0029FC88 ]0029FC9C saved EBP register
0029FC8C |00E0106C RETURN to fib2.00E0106C from fib2.00E01000
0029FC90 |00000001 1st argument: a 
0029FC94 |00000001 2nd argument: b | prepared in main() for f1()
0029FC98 |00000014 3rd argument: limit /
0029FC9C ]0029FCE0 saved EBP register
0029FCA0 |00E011E0 RETURN to fib2.00E011E0 from fib2.00E01050
0029FCA4 |00000001 main() 1st argument: argc 
0029FCA8 |000812C8 main() 2nd argument: argv | prepared in CRT for main()
0029FCAC |00082940 main() 3rd argument: envp /
Here we see it: the next value is calculated in each function incarnation, then passed as argument b to the next incarnation.
36.3 Summary
Recursive functions are æsthetically nice, but technically may degrade performance because of their heavy stack usage.
Everyone who writes performance critical code probably should should avoid recursion.
For example, I once wrote a function to seek a particular node in a binary tree. As a recursive function it looked quite
stylish but since additional time was to be spent at each function call for the prologue/epilogue, it was working a couple of
times slower than an iterative (recursion-free) implementation.
By the way, that is the reason compilers use tail call.
470
CHAPTER 37. CRC32 CALCULATION EXAMPLE
Chapter 37
CRC32 calculation example
This is a very popular table-based CRC32 hash calculation technique1
.
/* By Bob Jenkins, (c) 2006, Public Domain */
#include <stdio.h>
#include <stddef.h>
#include <string.h>
typedef unsigned long ub4;
typedef unsigned char ub1;
static const ub4 crctab[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
1The source code was taken from here: http://go.yurichev.com/17327
471
CHAPTER 37. CRC32 CALCULATION EXAMPLE
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
/* how to derive the values in crctab[] from polynomial 0xedb88320 */
void build_table()
{
ub4 i, j;
for (i=0; i<256; ++i) {
j = i;
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0);
printf("0x%.8lx, ", j);
if (i%6 == 5) printf("n");
}
}
/* the hash function */
ub4 crc(const void *key, ub4 len, ub4 hash)
{
ub4 i;
const ub1 *k = key;
for (hash=len, i=0; i<len; ++i)
hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ k[i]];
return hash;
}
/* To use, try "gcc -O crc.c -o crc; crc < crc.c" */
int main()
{
char s[1000];
while (gets(s)) printf("%.8lxn", crc(s, strlen(s), 0));
return 0;
}
We are interesting in the crc() function only. By the way, pay attention to the two loop initializers in the for()
statement: hash=len, i=0. The C/C++ standard allows this, of course. The emitted code will contain two operations in
the loop initialization part instead of one.
Let’s compile it in MSVC with optimization (/Ox). For the sake of brevity, only the crc() function is listed here, with my
comments.
_key$ = 8 ; size = 4
_len$ = 12 ; size = 4
_hash$ = 16 ; size = 4
_crc PROC
mov edx, DWORD PTR _len$[esp-4]
xor ecx, ecx ; i will be stored in ECX
mov eax, edx
test edx, edx
jbe SHORT $LN1@crc
push ebx
push esi
mov esi, DWORD PTR _key$[esp+4] ; ESI = key
push edi
$LL3@crc:
; work with bytes using only 32-bit registers. byte from address key+i we store into EDI
movzx edi, BYTE PTR [ecx+esi]
mov ebx, eax ; EBX = (hash = len)
and ebx, 255 ; EBX = hash & 0xff
472
CHAPTER 37. CRC32 CALCULATION EXAMPLE
; XOR EDI, EBX (EDI=EDI^EBX) - this operation uses all 32 bits of each register
; but other bits (8-31) are cleared all time, so its OK'
; these are cleared because, as for EDI, it was done by MOVZX instruction above
; high bits of EBX was cleared by AND EBX, 255 instruction above (255 = 0xff)
xor edi, ebx
; EAX=EAX>>8; bits 24-31 taken "from nowhere" will be cleared
shr eax, 8
; EAX=EAX^crctab[EDI*4] - choose EDI-th element from crctab[] table
xor eax, DWORD PTR _crctab[edi*4]
inc ecx ; i++
cmp ecx, edx ; i<len ?
jb SHORT $LL3@crc ; yes
pop edi
pop esi
pop ebx
$LN1@crc:
ret 0
_crc ENDP
Let’s try the same in GCC 4.4.1 with -O3 option:
public crc
crc proc near
key = dword ptr 8
hash = dword ptr 0Ch
push ebp
xor edx, edx
mov ebp, esp
push esi
mov esi, [ebp+key]
push ebx
mov ebx, [ebp+hash]
test ebx, ebx
mov eax, ebx
jz short loc_80484D3
nop ; padding
lea esi, [esi+0] ; padding; works as NOP (ESI does not changing here)
loc_80484B8:
mov ecx, eax ; save previous state of hash to ECX
xor al, [esi+edx] ; AL=*(key+i)
add edx, 1 ; i++
shr ecx, 8 ; ECX=hash>>8
movzx eax, al ; EAX=*(key+i)
mov eax, dword ptr ds:crctab[eax*4] ; EAX=crctab[EAX]
xor eax, ecx ; hash=EAX^ECX
cmp ebx, edx
ja short loc_80484B8
loc_80484D3:
pop ebx
pop esi
pop ebp
retn
crc endp

GCC has aligned the loop start on a 8-byte boundary by adding NOP and lea esi, [esi+0] (that is an idle operation
too). Read more about it in npad section ( 88 on page 866).
473
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE
Chapter 38
Network address calculation example
As we know, a TCP/IP address (IPv4) consists of four numbers in the 0...255 range, i.e., four bytes. Four bytes can be fit in
a 32-bit variable easily, so an IPv4 host address, network mask or network address can all be 32-bit integers.
From the user’s point of view, the network mask is defined as four numbers and is formatted like 255.255.255.0 or so, but
network engineers (sysadmins) use a more compact notation (CIDR1
), like /8, /16 or similar. This notation just defines the
number of bits the mask has, starting at the MSB.
Mask Hosts Usable Netmask Hex mask
/30 4 2 255.255.255.252 fffffffc
/29 8 6 255.255.255.248 fffffff8
/28 16 14 255.255.255.240 fffffff0
/27 32 30 255.255.255.224 ffffffe0
/26 64 62 255.255.255.192 ffffffc0
/24 256 254 255.255.255.0 ffffff00 class C network
/23 512 510 255.255.254.0 fffffe00
/22 1024 1022 255.255.252.0 fffffc00
/21 2048 2046 255.255.248.0 fffff800
/20 4096 4094 255.255.240.0 fffff000
/19 8192 8190 255.255.224.0 ffffe000
/18 16384 16382 255.255.192.0 ffffc000
/17 32768 32766 255.255.128.0 ffff8000
/16 65536 65534 255.255.0.0 ffff0000 class B network
/8 16777216 16777214 255.0.0.0 ff000000 class A network
Here is a small example, which calculates the network address by applying the network mask to the host address.
#include <stdio.h>
#include <stdint.h>
uint32_t form_IP (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4)
{
return (ip1<<24) | (ip2<<16) | (ip3<<8) | ip4;
};
void print_as_IP (uint32_t a)
{
printf ("%d.%d.%d.%dn",
(a>>24)&0xFF,
(a>>16)&0xFF,
(a>>8)&0xFF,
(a)&0xFF);
};
// bit=31..0
uint32_t set_bit (uint32_t input, int bit)
{
return input=input|(1<<bit);
};
uint32_t form_netmask (uint8_t netmask_bits)
{
1Classless Inter-Domain Routing
474
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.1. CALC_NETWORK_ADDRESS()
uint32_t netmask=0;
uint8_t i;
for (i=0; i<netmask_bits; i++)
netmask=set_bit(netmask, 31-i);
return netmask;
};
void calc_network_address (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint8_t ⤦
netmask_bits)
{
uint32_t netmask=form_netmask(netmask_bits);
uint32_t ip=form_IP(ip1, ip2, ip3, ip4);
uint32_t netw_adr;
printf ("netmask=");
print_as_IP (netmask);
netw_adr=ip&netmask;
printf ("network address=");
print_as_IP (netw_adr);
};
int main()
{
calc_network_address (10, 1, 2, 4, 24); // 10.1.2.4, /24
calc_network_address (10, 1, 2, 4, 8); // 10.1.2.4, /8
calc_network_address (10, 1, 2, 4, 25); // 10.1.2.4, /25
calc_network_address (10, 1, 2, 64, 26); // 10.1.2.4, /26
};
38.1 calc_network_address()
calc_network_address() function is simplest one: it just ANDs the host address with the network mask, resulting in
the network address.
Listing 38.1: Optimizing MSVC 2012 /Ob0
1 _ip1$ = 8 ; size = 1
2 _ip2$ = 12 ; size = 1
3 _ip3$ = 16 ; size = 1
4 _ip4$ = 20 ; size = 1
5 _netmask_bits$ = 24 ; size = 1
6 _calc_network_address PROC
7 push edi
8 push DWORD PTR _netmask_bits$[esp]
9 call _form_netmask
10 push OFFSET $SG3045 ; 'netmask='
11 mov edi, eax
12 call DWORD PTR __imp__printf
13 push edi
14 call _print_as_IP
15 push OFFSET $SG3046 ; 'network address='
16 call DWORD PTR __imp__printf
17 push DWORD PTR _ip4$[esp+16]
18 push DWORD PTR _ip3$[esp+20]
19 push DWORD PTR _ip2$[esp+24]
20 push DWORD PTR _ip1$[esp+28]
21 call _form_IP
22 and eax, edi ; network address = host address & netmask
23 push eax
24 call _print_as_IP
25 add esp, 36
26 pop edi
27 ret 0
28 _calc_network_address ENDP
475
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.2. FORM_IP()
At line 22 we see the most important AND— here the network address is calculated.
38.2 form_IP()
The form_IP() function just puts all 4 bytes into a 32-bit value.
Here is how it is usually done:
• Allocate a variable for the return value. Set it to 0.
• Take the fourth (lowest) byte, apply OR operation to this byte and return the value. The return value contain the 4th
byte now.
• Take the third byte, shift it left by 8 bits. You’ll get a value like 0x0000bb00 where bb is your third byte. Apply the
OR operation to the resulting value and it. The return value has contained 0x000000aa so far, so ORing the values
will produce a value like 0x0000bbaa.
• Take the second byte, shift it left by 16 bits. You’ll get a value like 0x00cc0000, where cc is your second byte. Apply
the OR operation to the resulting value and return it. The return value has contained 0x0000bbaa so far, so ORing
the values will produce a value like 0x00ccbbaa.
• Take the first byte, shift it left by 24 bits. You’ll get a value like 0xdd000000, where dd is your first byte. Apply the
OR operation to the resulting value and return it. The return value contain 0x00ccbbaa so far, so ORing the values
will produce a value like 0xddccbbaa.
And this is how it’s done by non-optimizing MSVC 2012:
Listing 38.2: Non-optimizing MSVC 2012
; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa".
_ip1$ = 8 ; size = 1
_ip2$ = 12 ; size = 1
_ip3$ = 16 ; size = 1
_ip4$ = 20 ; size = 1
_form_IP PROC
push ebp
mov ebp, esp
movzx eax, BYTE PTR _ip1$[ebp]
; EAX=000000dd
shl eax, 24
; EAX=dd000000
movzx ecx, BYTE PTR _ip2$[ebp]
; ECX=000000cc
shl ecx, 16
; ECX=00cc0000
or eax, ecx
; EAX=ddcc0000
movzx edx, BYTE PTR _ip3$[ebp]
; EDX=000000bb
shl edx, 8
; EDX=0000bb00
or eax, edx
; EAX=ddccbb00
movzx ecx, BYTE PTR _ip4$[ebp]
; ECX=000000aa
or eax, ecx
; EAX=ddccbbaa
pop ebp
ret 0
_form_IP ENDP
Well, the order is different, but, of course, the order of the operations doesn’t matters.
Optimizing MSVC 2012 does essentially the same, but in a different way:
Listing 38.3: Optimizing MSVC 2012 /Ob0
; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa".
_ip1$ = 8 ; size = 1
_ip2$ = 12 ; size = 1
_ip3$ = 16 ; size = 1
_ip4$ = 20 ; size = 1
476
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.3. PRINT_AS_IP()
_form_IP PROC
movzx eax, BYTE PTR _ip1$[esp-4]
; EAX=000000dd
movzx ecx, BYTE PTR _ip2$[esp-4]
; ECX=000000cc
shl eax, 8
; EAX=0000dd00
or eax, ecx
; EAX=0000ddcc
movzx ecx, BYTE PTR _ip3$[esp-4]
; ECX=000000bb
shl eax, 8
; EAX=00ddcc00
or eax, ecx
; EAX=00ddccbb
movzx ecx, BYTE PTR _ip4$[esp-4]
; ECX=000000aa
shl eax, 8
; EAX=ddccbb00
or eax, ecx
; EAX=ddccbbaa
ret 0
_form_IP ENDP
We could say that each byte is written to the lowest 8 bits of the return value, and then the return value is shifted left by
one byte at each step. Repeat 4 times for each input byte.
That’s it! Unfortunately, there are probably no other ways to do it. I’ve never heard of a CPUs or ISAs which has instruction
for composing a value from bits or bytes. It’s all usually done by bit shifting and ORing.
38.3 print_as_IP()
print_as_IP() does the inverse: splitting a 32-bit value into 4 bytes.
Slicing works somewhat simpler: just shift input value by 24, 16, 8 or 0 bits, take the bits from zeroth to seventh (lowest
byte), and that’s it:
Listing 38.4: Non-optimizing MSVC 2012
_a$ = 8 ; size = 4
_print_as_IP PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
; EAX=ddccbbaa
and eax, 255
; EAX=000000aa
push eax
mov ecx, DWORD PTR _a$[ebp]
; ECX=ddccbbaa
shr ecx, 8
; ECX=00ddccbb
and ecx, 255
; ECX=000000bb
push ecx
mov edx, DWORD PTR _a$[ebp]
; EDX=ddccbbaa
shr edx, 16
; EDX=0000ddcc
and edx, 255
; EDX=000000cc
push edx
mov eax, DWORD PTR _a$[ebp]
; EAX=ddccbbaa
shr eax, 24
; EAX=000000dd
and eax, 255 ; probably redundant instruction
; EAX=000000dd
push eax
push OFFSET $SG2973 ; '%d.%d.%d.%d'
477
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.4. FORM_NETMASK() AND SET_BIT()
call DWORD PTR __imp__printf
add esp, 20
pop ebp
ret 0
_print_as_IP ENDP
Optimizing MSVC 2012 does almost the same, but without unnecessary reloading of the input value:
Listing 38.5: Optimizing MSVC 2012 /Ob0
_a$ = 8 ; size = 4
_print_as_IP PROC
mov ecx, DWORD PTR _a$[esp-4]
; ECX=ddccbbaa
movzx eax, cl
; EAX=000000aa
push eax
mov eax, ecx
; EAX=ddccbbaa
shr eax, 8
; EAX=00ddccbb
and eax, 255
; EAX=000000bb
push eax
mov eax, ecx
; EAX=ddccbbaa
shr eax, 16
; EAX=0000ddcc
and eax, 255
; EAX=000000cc
push eax
; ECX=ddccbbaa
shr ecx, 24
; ECX=000000dd
push ecx
push OFFSET $SG3020 ; '%d.%d.%d.%d'
call DWORD PTR __imp__printf
add esp, 20
ret 0
_print_as_IP ENDP
38.4 form_netmask() and set_bit()
form_netmask() makes a network mask value from CIDR notation. Of course, it would be much effective to use here
some kind of a precalculated table, but I wrote it in this way intentionally, to demonstrate bit shifts. I also wrote a separate
function set_bit(). It’s a not very good idea to create a function for such primitive operation, but it would be easy to
understand how it all works.
Listing 38.6: Optimizing MSVC 2012 /Ob0
_input$ = 8 ; size = 4
_bit$ = 12 ; size = 4
_set_bit PROC
mov ecx, DWORD PTR _bit$[esp-4]
mov eax, 1
shl eax, cl
or eax, DWORD PTR _input$[esp-4]
ret 0
_set_bit ENDP
_netmask_bits$ = 8 ; size = 1
_form_netmask PROC
push ebx
push esi
movzx esi, BYTE PTR _netmask_bits$[esp+4]
xor ecx, ecx
xor bl, bl
test esi, esi
jle SHORT $LN9@form_netma
478
CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.5. SUMMARY
xor edx, edx
$LL3@form_netma:
mov eax, 31
sub eax, edx
push eax
push ecx
call _set_bit
inc bl
movzx edx, bl
add esp, 8
mov ecx, eax
cmp edx, esi
jl SHORT $LL3@form_netma
$LN9@form_netma:
pop esi
mov eax, ecx
pop ebx
ret 0
_form_netmask ENDP
set_bit() is primitive: it just shift left 1 to number of bits we need and then ORs it with the “input” value. form_netmask()
has a loop: it will set as many bits (starting from the MSB) as passed in the netmask_bits argument
38.5 Summary
That’s it! I run it and get:
netmask=255.255.255.0
network address=10.1.2.0
netmask=255.0.0.0
network address=10.0.0.0
netmask=255.255.255.128
network address=10.1.2.0
netmask=255.255.255.192
network address=10.1.2.64
479
CHAPTER 39. LOOPS: SEVERAL ITERATORS
Chapter 39
Loops: several iterators
In most cases loops have only one iterator, but there could be several in the resulting code.
Here is a very simple example:
#include <stdio.h>
void f(int *a1, int *a2, size_t cnt)
{
size_t i;
// copy from one array to another in some weird scheme
for (i=0; i<cnt; i++)
a1[i*3]=a2[i*7];
};
There are two multiplications at each iteration and they are costly operations. Can we optimize it somehow? Yes, if we
notice that both array indices are jumping on values that we can easily calculate without multiplication.
39.1 Three iterators
Listing 39.1: Optimizing MSVC 2013 x64
f PROC
; RDX=a1
; RCX=a2
; R8=cnt
test r8, r8 ; cnt==0? exit then
je SHORT $LN1@f
npad 11
$LL3@f:
mov eax, DWORD PTR [rdx]
lea rcx, QWORD PTR [rcx+12]
lea rdx, QWORD PTR [rdx+28]
mov DWORD PTR [rcx-12], eax
dec r8
jne SHORT $LL3@f
$LN1@f:
ret 0
f ENDP
Now there are 3 iterators: the cnt variable and two indices, which are increased by 12 and 28 at each iteration. We can
rewrite this code in C/C++:
#include <stdio.h>
void f(int *a1, int *a2, size_t cnt)
{
size_t i;
size_t idx1=0; idx2=0;
// copy from one array to another in some weird scheme
for (i=0; i<cnt; i++)
{
a1[idx1]=a2[idx2];
480
CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.2. TWO ITERATORS
idx1+=3;
idx2+=7;
};
};
So, at the cost of updating 3 iterators at each iteration instead of one, we can remove two multiplication operations.
39.2 Two iterators
GCC 4.9 does even more, leaving only 2 iterators:
Listing 39.2: Optimizing GCC 4.9 x64
; RDI=a1
; RSI=a2
; RDX=cnt
f:
test rdx, rdx ; cnt==0? exit then
je .L1
; calculate last element address in "a2" and leave it in RDX
lea rax, [0+rdx*4]
; RAX=RDX*4=cnt*4
sal rdx, 5
; RDX=RDX<<5=cnt*32
sub rdx, rax
; RDX=RDX-RAX=cnt*32-cnt*4=cnt*28
add rdx, rsi
; RDX=RDX+RSI=a2+cnt*28
.L3:
mov eax, DWORD PTR [rsi]
add rsi, 28
add rdi, 12
mov DWORD PTR [rdi-12], eax
cmp rsi, rdx
jne .L3
.L1:
rep ret
There is no counter variable any more: GCC concluded that it is not needed. The last element of the a2 array is calculated
before the loop begins (which is easy: cnt ∗ 7) and that’s how the loop is to be stopped: just iterate until the second index
has not reached this precalculated value.
You can read more about multiplication using shifts/additions/subtractions here: 16.1.3 on page 202.
This code can be rewritten into C/C++ like that:
#include <stdio.h>
void f(int *a1, int *a2, size_t cnt)
{
size_t i;
size_t idx1=0; idx2=0;
size_t last_idx2=cnt*7;
// copy from one array to another in some weird scheme
for (;;)
{
a1[idx1]=a2[idx2];
idx1+=3;
idx2+=7;
if (idx2==last_idx2)
break;
};
};
GCC (Linaro) 4.9 for ARM64 does the same, but it precalculates the last index of a1 instead of a2, which, of course has
the same effect:
Listing 39.3: Optimizing GCC (Linaro) 4.9 ARM64
; X0=a1
; X1=a2
481
CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE
; X2=cnt
f:
cbz x2, .L1 ; cnt==0? exit then
; calculate last element of "a1" array
add x2, x2, x2, lsl 1
; X2=X2+X2<<1=X2+X2*2=X2*3
mov x3, 0
lsl x2, x2, 2
; X2=X2<<2=X2*4=X2*3*4=X2*12
.L3:
ldr w4, [x1],28 ; load at X1, add 28 to X1 (post-increment)
str w4, [x0,x3] ; store at X0+X3=a1+X3
add x3, x3, 12 ; shift X3
cmp x3, x2 ; end?
bne .L3
.L1:
ret
GCC 4.4.5 for MIPS does the same:
Listing 39.4: Optimizing GCC 4.4.5 for MIPS (IDA)
; $a0=a1
; $a1=a2
; $a2=cnt
f:
; jump to loop check code:
beqz $a2, locret_24
; initialize counter (i) at 0:
move $v0, $zero ; branch delay slot, NOP
loc_8:
; load 32-bit word at $a1
lw $a3, 0($a1)
; increment counter (i):
addiu $v0, 1
; check for finish (compare "i" in $v0 and "cnt" in $a2):
sltu $v1, $v0, $a2
; store 32-bit word at $a0:
sw $a3, 0($a0)
; add 0x1C (28) to $a1 at each iteration:
addiu $a1, 0x1C
; jump to loop body if i<cnt:
bnez $v1, loc_8
; add 0xC (12) to $a0 at each iteration:
addiu $a0, 0xC ; branch delay slot
locret_24:
jr $ra
or $at, $zero ; branch delay slot, NOP
39.3 Intel C++ 2011 case
Compiler optimizations can also be weird, but nevertheless, still correct. Here is what the Intel C++ compiler 2011 does:
Listing 39.5: Optimizing Intel C++ 2011 x64
f PROC
; parameter 1: rcx = a1
; parameter 2: rdx = a2
; parameter 3: r8 = cnt
.B1.1:: ; Preds .B1.0
test r8, r8 ;8.14
jbe exit ; Prob 50% ;8.14
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.2:: ; Preds .B1.1
cmp r8, 6 ;8.2
jbe just_copy ; Prob 50% ;8.2
482
CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.3:: ; Preds .B1.2
cmp rcx, rdx ;9.11
jbe .B1.5 ; Prob 50% ;9.11
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.4:: ; Preds .B1.3
mov r10, r8 ;9.11
mov r9, rcx ;9.11
shl r10, 5 ;9.11
lea rax, QWORD PTR [r8*4] ;9.11
sub r9, rdx ;9.11
sub r10, rax ;9.11
cmp r9, r10 ;9.11
jge just_copy2 ; Prob 50% ;9.11
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.5:: ; Preds .B1.3 .B1.4
cmp rdx, rcx ;9.11
jbe just_copy ; Prob 50% ;9.11
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.6:: ; Preds .B1.5
mov r9, rdx ;9.11
lea rax, QWORD PTR [r8*8] ;9.11
sub r9, rcx ;9.11
lea r10, QWORD PTR [rax+r8*4] ;9.11
cmp r9, r10 ;9.11
jl just_copy ; Prob 50% ;9.11
; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦
xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
just_copy2:: ; Preds .B1.4 .B1.6
; R8 = cnt
; RDX = a2
; RCX = a1
xor r10d, r10d ;8.2
xor r9d, r9d ;
xor eax, eax ;
; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦
xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.8:: ; Preds .B1.8 just_copy2
mov r11d, DWORD PTR [rax+rdx] ;3.6
inc r10 ;8.2
mov DWORD PTR [r9+rcx], r11d ;3.6
add r9, 12 ;8.2
add rax, 28 ;8.2
cmp r10, r8 ;8.2
jb .B1.8 ; Prob 82% ;8.2
jmp exit ; Prob 100% ;8.2
; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦
xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
just_copy:: ; Preds .B1.2 .B1.5 .B1.6
; R8 = cnt
; RDX = a2
; RCX = a1
xor r10d, r10d ;8.2
xor r9d, r9d ;
xor eax, eax ;
; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦
xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
.B1.11:: ; Preds .B1.11 just_copy
mov r11d, DWORD PTR [rax+rdx] ;3.6
inc r10 ;8.2
mov DWORD PTR [r9+rcx], r11d ;3.6
add r9, 12 ;8.2
add rax, 28 ;8.2
cmp r10, r8 ;8.2
jb .B1.11 ; Prob 82% ;8.2
; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦
483
CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE
xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15
exit:: ; Preds .B1.11 .B1.8 .B1.1
ret ;10.1
First, there are some decisions taken, then one of the routines is executed. Looks like it is a check if arrays intersect.
This is very well known way of optimizing memory block copy routines. But copy routines are the same! This is probably
an error of the Intel C++ optimizer, which still produces workable code, though.
I’m adding such example code to my book so the reader would understand that compiler output is weird at times, but
still correct, because when the compiler was tested, is passed the tests.
484
CHAPTER 40. DUFF’S DEVICE
Chapter 40
Duff’s device
Duff’s device 1
is an unrolled loop with the possibility to jump inside it. The unrolled loop is implemented using a
fallthrough switch() statement.
I would use here a slightly simplified version of Tom Duff’s original code.
Let’s say, we need to write a function that clears a region in memory. One can come with a simple loop, clearing byte
by byte. It’s obviously slow, since all modern computers have much wider memory bus. So the better way is to clear the
memory region using 4 or 8 byte blocks. Since we are going to work with a 64-bit example here, we are going to clear the
memory in 8 byte blocks. So far so good. But what about the tail? Memory clearing routine can also be called for regions
of size that’s not a multiple of 8.
So here is the algorithm:
• calculate the number of 8-byte blocks, clear them using 8-byte (64-bit) memory accesses;
• calculate the size of the tail, clear it using 1-byte memory accesses.
The second step can be implemented using a simple loop. But let’s implement it as an unrolled loop:
#include <stdint.h>
#include <stdio.h>
void bzero(uint8_t* dst, size_t count)
{
int i;
if (count&(~7))
// work out 8-byte blocks
for (i=0; i<count>>3; i++)
{
*(uint64_t*)dst=0;
dst=dst+8;
};
// work out the tail
switch(count & 7)
{
case 7: *dst++ = 0;
case 6: *dst++ = 0;
case 5: *dst++ = 0;
case 4: *dst++ = 0;
case 3: *dst++ = 0;
case 2: *dst++ = 0;
case 1: *dst++ = 0;
case 0: // do nothing
break;
}
}
Let’s first understand how the calculation is done. The memory region size comes as a 64-bit value. And this value can
be divided in two parts:
7 6 5 4 3 2 1 0
… B B B B B S S S
1wikipedia
485
CHAPTER 40. DUFF’S DEVICE
( “B” is number of 8-byte blocks and “S” is length of the tail in bytes ).
When we divide the input memory region size by 8, the value is just shifted right by 3 bits. But to calculate the remainder,
we just need to isolate the lowest 3 bits! So the number of 8-byte blocks is calculated as count >> 3 and remainder as
count&7.
We also need to find out if we are going to execute the 8-byte procedure at all, so we need to check if the value of count
is greater than 7. We do this by clearing the 3 lowest bits and comparing the resulting number with zero, because all we
need here is to answer the question, is the high part of count non-zero.
Of course, this works because 8 is 23
and division by numbers that are 2n
is easy. It’s not possible for other numbers.
It’s actually hard to say if these hacks are worth using, because they lead to hard-to-read code. However, these tricks
are very popular and a practicing programmer, even if he/she is not using them, nevertheless has to understand them.
So the first part is simple: get the number of 8-byte blocks and write 64-bit zero values to memory.
The second part is an unrolled loop implemented as fallthrough switch() statement. First, let’s express in plain English
what we have to do here. We have to “write as many zero bytes in memory, as count&7 value tells us”. If it’s 0, jump to the
end, there is no work to do. If it’s 1, jump to the place inside switch() statement where only one storage operation is to be
executed. If it’s 2, jump to another place, where two storage operation are to be executed, etc. 7 as input value leads to
the execution of all 7 operations. There is no 8, because a memory region of 8 bytes is to be processed by the first part of
our function.
So we wrote an unrolled loop. It was definitely faster on older computers than normal loops (and conversely, modern
CPUs works better for short loops than for unrolled ones). Maybe this is still meaningful on modern low-cost embedded
MCU2
s.
Let’s see what the optimizing MSVC 2012 does:
dst$ = 8
count$ = 16
bzero PROC
test rdx, -8
je SHORT $LN11@bzero
; work out 8-byte blocks
xor r10d, r10d
mov r9, rdx
shr r9, 3
mov r8d, r10d
test r9, r9
je SHORT $LN11@bzero
npad 5
$LL19@bzero:
inc r8d
mov QWORD PTR [rcx], r10
add rcx, 8
movsxd rax, r8d
cmp rax, r9
jb SHORT $LL19@bzero
$LN11@bzero:
; work out the tail
and edx, 7
dec rdx
cmp rdx, 6
ja SHORT $LN9@bzero
lea r8, OFFSET FLAT:__ImageBase
mov eax, DWORD PTR $LN22@bzero[r8+rdx*4]
add rax, r8
jmp rax
$LN8@bzero:
mov BYTE PTR [rcx], 0
inc rcx
$LN7@bzero:
mov BYTE PTR [rcx], 0
inc rcx
$LN6@bzero:
mov BYTE PTR [rcx], 0
inc rcx
$LN5@bzero:
mov BYTE PTR [rcx], 0
inc rcx
$LN4@bzero:
mov BYTE PTR [rcx], 0
inc rcx
2Microcontroller unit
486
CHAPTER 40. DUFF’S DEVICE
$LN3@bzero:
mov BYTE PTR [rcx], 0
inc rcx
$LN2@bzero:
mov BYTE PTR [rcx], 0
$LN9@bzero:
fatret 0
npad 1
$LN22@bzero:
DD $LN2@bzero
DD $LN3@bzero
DD $LN4@bzero
DD $LN5@bzero
DD $LN6@bzero
DD $LN7@bzero
DD $LN8@bzero
bzero ENDP
The first part of the function is predictable. The second part is just an unrolled loop and a jump passing control flow to
the correct instruction inside it. There is no other code between the MOV/INC instruction pairs, so the execution is to fall
until the very end, executing as many pairs as needed.
By the way, we can observe that the MOV/INC pair consumes a fixed number of bytes (3+3). So the pair consumes 6
bytes. Knowing that, we can get rid of the switch() jumptable, we can just multiple the input value by 6 and jump to
current_RIP + input_value ∗ 6. This can also be faster because we are not in need to fetch a value from the jumptable.
It’s possible that 6 probably is not a very good constant for fast multiplication and maybe it’s not worth it, but you get the
idea3
. That is what old-school demomakers did in the past with unrolled loops.
3As an exercise, you can try to rework the code to get rid of the jumptable. The instruction pair can be rewritten in a way that it will consume 4 bytes
or maybe 8. 1 byte is also possible (using STOSB instruction).
487
CHAPTER 41. DIVISION BY 9
Chapter 41
Division by 9
A very simple function:
int f(int a)
{
return a/9;
};
41.1 x86
…is compiled in a very predictable way:
Listing 41.1: MSVC
_a$ = 8 ; size = 4
_f PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
cdq ; sign extend EAX to EDX:EAX
mov ecx, 9
idiv ecx
pop ebp
ret 0
_f ENDP
IDIV divides the 64-bit number stored in the EDX:EAX register pair by the value in the ECX. As a result, EAX will contain
the quotient, and EDX —the remainder. The result is returned from the f() function in the EAX register, so the value is not
moved after the division operation, it is in right place already. Since IDIV uses the value in the EDX:EAX register pair, the
CDQ instruction (before IDIV) extends the value in EAX to a 64-bit value taking its sign into account, just as MOVSX does.
If we turn optimization on (/Ox), we get:
Listing 41.2: Optimizing MSVC
_a$ = 8 ; size = 4
_f PROC
mov ecx, DWORD PTR _a$[esp-4]
mov eax, 954437177 ; 38e38e39H
imul ecx
sar edx, 1
mov eax, edx
shr eax, 31 ; 0000001fH
add eax, edx
ret 0
_f ENDP
This is division by multiplication. Multiplication operations work much faster. And it is possible to use this trick 1
to
produce code which is effectively equivalent and faster.
This is also called “strength reduction” in compiler optimizations.
GCC 4.4.1 generates almost the same code even without additional optimization flags, just like MSVC with optimization
turned on:
1Read more about division by multiplication in [War02, pp. 10-3]
488
CHAPTER 41. DIVISION BY 9 41.2. ARM
Listing 41.3: Non-optimizing GCC 4.4.1
public f
f proc near
arg_0 = dword ptr 8
push ebp
mov ebp, esp
mov ecx, [ebp+arg_0]
mov edx, 954437177 ; 38E38E39h
mov eax, ecx
imul edx
sar edx, 1
mov eax, ecx
sar eax, 1Fh
mov ecx, edx
sub ecx, eax
mov eax, ecx
pop ebp
retn
f endp
41.2 ARM
The ARM processor, just like in any other ”pure” RISC processor lacks an instruction for division. It also lacks a single
instruction for multiplication by a 32-bit constant (recall that a 32-bit constant cannot fit into a 32-bit opcode). By taking
advantage of this clever trick (or hack), it is possible to do division using only three instructions: addition, subtraction and
bit shifts ( 19 on page 305).
Here is an example that divides a 32-bit number by 10, from [Ltd94, 3.3 Division by a Constant]. The output consists of
the quotient and the remainder.
; takes argument in a1
; returns quotient in a1, remainder in a2
; cycles could be saved if only divide or remainder is required
SUB a2, a1, #10 ; keep (x-10) for later
SUB a1, a1, a1, lsr #2
ADD a1, a1, a1, lsr #4
ADD a1, a1, a1, lsr #8
ADD a1, a1, a1, lsr #16
MOV a1, a1, lsr #3
ADD a3, a1, a1, asl #2
SUBS a2, a2, a3, asl #1 ; calc (x-10) - (x/10)*10
ADDPL a1, a1, #1 ; fix-up quotient
ADDMI a2, a2, #10 ; fix-up remainder
MOV pc, lr
41.2.1 Optimizing Xcode 4.6.3 (LLVM) (ARM mode)
__text:00002C58 39 1E 08 E3 E3 18 43 E3 MOV R1, 0x38E38E39
__text:00002C60 10 F1 50 E7 SMMUL R0, R0, R1
__text:00002C64 C0 10 A0 E1 MOV R1, R0,ASR#1
__text:00002C68 A0 0F 81 E0 ADD R0, R1, R0,LSR#31
__text:00002C6C 1E FF 2F E1 BX LR
This code is almost the same as the one generated by the optimizing MSVC and GCC. Apparently, LLVM uses the same
algorithm for generating constants.
The observant reader may ask, how does MOV writes a 32-bit value in a register, when this is not possible in ARM mode.
it is impossible indeed, but, as we see, there are 8 bytes per instruction instead of the standard 4, in fact, there are two
instructions. The first instruction loads 0x8E39 into the low 16 bits of register and the second instruction is MOVT, it loads
0x383E into the high 16 bits of the register. IDA is fully aware of such sequences, and for the the sake of compactness
reduces them to one single “pseudo-instruction”.
The SMMUL (Signed Most Significant Word Multiply) instruction two multiplies numbers, treating them as signed numbers
and leaving the high 32-bit part of result in the R0 register, dropping the low 32-bit part of the result.
The``MOV R1, R0,ASR#1'' instruction is an arithmetic shift right by one bit.
``ADD R0, R1, R0,LSR#31'' is R0 = R1 + R0 >> 31
489
CHAPTER 41. DIVISION BY 9 41.3. MIPS
There is no separate shifting instruction in ARM mode. Instead, an instructions like (MOV, ADD, SUB, RSB)2
can have a
suffix added, that says if the second operand must be shifted, and if yes, by what value and how. ASR stands for Arithmetic
Shift Right, LSR—Logical Shift Right.
41.2.2 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode)
MOV R1, 0x38E38E39
SMMUL.W R0, R0, R1
ASRS R1, R0, #1
ADD.W R0, R1, R0,LSR#31
BX LR
There are separate instructions for shifting in thumb mode, and one of them is used here—ASRS (arithmetic shift right).
41.2.3 Non-optimizing Xcode 4.6.3 (LLVM) and Keil 6/2013
Non-optimizing LLVM does not generate the code we saw before in this section, but instead inserts a call to the library
function ___divsi3.
What about Keil: it inserts a call to the library function __aeabi_idivmod in all cases.
41.3 MIPS
For some reason, optimizing GCC 4.4.5 generate just a division instruction:
Listing 41.4: Optimizing GCC 4.4.5 (IDA)
f:
li $v0, 9
bnez $v0, loc_10
div $a0, $v0 ; branch delay slot
break 0x1C00 ; "break 7" in assembly output and objdump
loc_10:
mflo $v0
jr $ra
or $at, $zero ; branch delay slot, NOP
Here we see here a new instruction: BREAK. It just raises an exception. In this case, an exception is raised if the divisor
is zero (it’s not possible to divide by zero in conventional math). But GCC probably did not do very well the optimization
job and did not see that $V0 is never zero. So the check is left here. So if $V0 is zero somehow, BREAK is to be executed,
signaling to the OS about the exception. Otherwise, MFLO executes, which takes the result of the division from the LO
register and copies it in $V0.
By the way, as we may know, the MUL instruction leaves the high 32 bits of the result in register HI and the low 32 bits
in register LO. DIV leaves the result in the LO register, and remainder in the HI register.
If we alter the statement to “a % 9”, the MFHI instruction is to be used here instead of MFLO.
41.4 How it works
That’s how division can be replaced by multiplication and division with 2n
numbers:
result =
input
divisor
=
input ⋅ 2n
divisor
2n
=
input ⋅ M
2n
Where M is a magic coefficient.
This is how M can be computed:
M =
2n
divisor
So these code snippets usually have this form:
result =
input ⋅ M
2n
Division by 2n
is usually done by simply shifting to the right. If n < 32, then the low part of the product is shifted (in
EAX or RAX). If n ≥ 32, then the high part of the product is shifted (in EDX or RDX).
2These instructions are also called “data processing instructions”
490
CHAPTER 41. DIVISION BY 9 41.5. GETTING THE DIVISOR
n is chosen in order to minimize the error.
When doing signed division, the sign of the multiplication result is also added to the output result.
Take a look at the difference:
int f3_32_signed(int a)
{
return a/3;
};
unsigned int f3_32_unsigned(unsigned int a)
{
return a/3;
};
In the unsigned version of the function, the magic coefficient is 0xAAAAAAAB and the multiplication result is divided by
233
.
In the signed version of the function, the magic coefficient is 0x55555556 and the multiplication result is divided by
232
. There are no division instruction though: the result is just taken from EDX.
The sign is also taken from the multiplication result: the high 32 bits of the result are shifted by 31 (leaving the sign in
the least significant bit of EAX). 1 is added to the final result if the sign is negative, for result correction.
Listing 41.5: Optimizing MSVC 2012
_f3_32_unsigned PROC
mov eax, -1431655765 ; aaaaaaabH
mul DWORD PTR _a$[esp-4] ; unsigned multiply
; EDX=(input*0xaaaaaaab)/2^32
shr edx, 1
; EDX=(input*0xaaaaaaab)/2^33
mov eax, edx
ret 0
_f3_32_unsigned ENDP
_f3_32_signed PROC
mov eax, 1431655766 ; 55555556H
imul DWORD PTR _a$[esp-4] ; signed multiply
; take high part of product
; it is just the same as if to shift product by 32 bits right or to divide it by 2^32
mov eax, edx ; EAX=EDX=(input*0x55555556)/2^32
shr eax, 31 ; 0000001fH
add eax, edx ; add 1 if sign is negative
ret 0
_f3_32_signed ENDP
Read more about it in [War02, pp. 10-3].
41.5 Getting the divisor
41.5.1 Variant #1
Often, the code looks like this:
mov eax, MAGICAL CONSTANT
imul input value
sar edx, SHIFTING COEFFICIENT ; signed division by 2x
using arithmetic shift right
mov eax, edx
shr eax, 31
add eax, edx
Let’s denote the 32-bit magic coefficient as M, the shifting coefficient as C and the divisor as D.
The divisor we need to get is:
D =
232+C
M
For example:
Listing 41.6: Optimizing MSVC 2012
mov eax, 2021161081 ; 78787879H
imul DWORD PTR _a$[esp-4]
491
CHAPTER 41. DIVISION BY 9 41.5. GETTING THE DIVISOR
sar edx, 3
mov eax, edx
shr eax, 31 ; 0000001fH
add eax, edx
This is:
D =
232+3
2021161081
The numbers are larger than 32-bit, so I used Wolfram Mathematica for convenience:
Listing 41.7: Wolfram Mathematica
In[1]:=N[2^(32+3)/2021161081]
Out[1]:=17.
So the divisor from the code I used as example is 17.
For x64 division, things are the same, but 264
has to be used instead of 232
:
uint64_t f1234(uint64_t a)
{
return a/1234;
};
Listing 41.8: Optimizing MSVC 2012 x64
f1234 PROC
mov rax, 7653754429286296943 ; 6a37991a23aead6fH
mul rcx
shr rdx, 9
mov rax, rdx
ret 0
f1234 ENDP
Listing 41.9: Wolfram Mathematica
In[1]:=N[2^(64+9)/16^^6a37991a23aead6f]
Out[1]:=1234.
41.5.2 Variant #2
A variant with omitted arithmetic shift also exist:
mov eax, 55555556h ; 1431655766
imul ecx
mov eax, edx
shr eax, 1Fh
The method of getting divisor is simplified:
D =
232
M
As of my example, this is:
D =
232
1431655766
And again I used Wolfram Mathematica:
Listing 41.10: Wolfram Mathematica
In[1]:=N[2^32/16^^55555556]
Out[1]:=3.
The divisor is 3.
492
CHAPTER 41. DIVISION BY 9 41.6. EXERCISE #1
41.6 Exercise #1
What does this code do?
Listing 41.11: Optimizing MSVC 2010
_a$ = 8
_f PROC
mov ecx, DWORD PTR _a$[esp-4]
mov eax, -968154503 ; c64b2279H
imul ecx
add edx, ecx
sar edx, 9
mov eax, edx
shr eax, 31 ; 0000001fH
add eax, edx
ret 0
_f ENDP
Listing 41.12: Optimizing GCC 4.9 (ARM64)
f:
mov w1, 8825
movk w1, 0xc64b, lsl 16
smull x1, w0, w1
lsr x1, x1, 32
add w1, w0, w1
asr w1, w1, 9
sub w0, w1, w0, asr 31
ret
Answer G.1.14 on page 959.
493
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI())
Chapter 42
String to number conversion (atoi())
Let’s try to reimplement the standard atoi() C function.
42.1 Simple example
Here is the simplest possible way to read a number represented in ASCII1
encoding. It’s not error-prone: a character other
than a digit leads to incorrect result.
#include <stdio.h>
int my_atoi (char *s)
{
int rt=0;
while (*s)
{
rt=rt*10 + (*s-'0');
s++;
};
return rt;
};
int main()
{
printf ("%dn", my_atoi ("1234"));
printf ("%dn", my_atoi ("1234567890"));
};
So what the algorithm does is just reading digits from left to right. The zero ASCII character is subtracted from each
digit. The digits from “0” to “9” are consecutive in the ASCII table, so we do not even need to know the exact value of
the “0” character. All we need to know is that “0” minus “0” is 0, “9” minus “0”’is 9 and so on. Subtracting “0” from each
character results in a number from 0 to 9 inclusive. Any other character leads to an incorrect result, of course! Each digit
has to be added to the final result (in variable “rt”), but the final result is also multiplied by 10 at each digit. In other words,
the result is shifted left by one position in decimal form on each iteration. The last digit is added, but there is no no shift.
42.1.1 Optimizing MSVC 2013 x64
Listing 42.1: Optimizing MSVC 2013 x64
s$ = 8
my_atoi PROC
; load first character
movzx r8d, BYTE PTR [rcx]
; EAX is allocated for "rt" variable
; its 0 at start'
xor eax, eax
; first character is zero-byte, i.e., string terminator?
; exit then.
test r8b, r8b
je SHORT $LN9@my_atoi
1American Standard Code for Information Interchange
494
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.1. SIMPLE EXAMPLE
$LL2@my_atoi:
lea edx, DWORD PTR [rax+rax*4]
; EDX=RAX+RAX*4=rt+rt*4=rt*5
movsx eax, r8b
; EAX=input character
; load next character to R8D
movzx r8d, BYTE PTR [rcx+1]
; shift pointer in RCX to the next character:
lea rcx, QWORD PTR [rcx+1]
lea eax, DWORD PTR [rax+rdx*2]
; EAX=RAX+RDX*2=input character + rt*5*2=input character + rt*10
; correct digit by subtracting 48 (0x30 or '0')
add eax, -48 ; ffffffffffffffd0H
; was last character zero?
test r8b, r8b
; jump to loop begin, if not
jne SHORT $LL2@my_atoi
$LN9@my_atoi:
ret 0
my_atoi ENDP
A character can be loaded in two places: the first character and all subsequent characters. This is done for loop regrouping.
There is no instruction for multiplication by 10, two LEA instruction do this instead. MSVC sometimes uses the ADD
instruction with a negative constant instead of SUB. This is the case. I truly don’t know why this is better then SUB. But
MSVC does this often.
42.1.2 Optimizing GCC 4.9.1 x64
Optimizing GCC 4.9.1 is more concise, but there is one redundant RET instruction at the end. One would be enough.
Listing 42.2: Optimizing GCC 4.9.1 x64
my_atoi:
; load input character into EDX
movsx edx, BYTE PTR [rdi]
; EAX is allocated for "rt" variable
xor eax, eax
; exit, if loaded character is null byte
test dl, dl
je .L4
.L3:
lea eax, [rax+rax*4]
; EAX=RAX*5=rt*5
; shift pointer to the next character:
add rdi, 1
lea eax, [rdx-48+rax*2]
; EAX=input character - 48 + RAX*2 = input character - '0' + rt*10
; load next character:
movsx edx, BYTE PTR [rdi]
; goto loop begin, if loaded character is not null byte
test dl, dl
jne .L3
rep ret
.L4:
rep ret
42.1.3 Optimizing Keil 6/2013 (ARM mode)
Listing 42.3: Optimizing Keil 6/2013 (ARM mode)
my_atoi PROC
; R1 will contain pointer to character
MOV r1,r0
; R0 will contain "rt" variable
MOV r0,#0
B |L0.28|
|L0.12|
ADD r0,r0,r0,LSL #2
; R0=R0+R0<<2=rt*5
495
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.1. SIMPLE EXAMPLE
ADD r0,r2,r0,LSL #1
; R0=input character + rt*5<<1 = input character + rt*10
; correct whole thing by subtracting '0' from rt:
SUB r0,r0,#0x30
; shift pointer to the next character:
ADD r1,r1,#1
|L0.28|
; load input character to R2
LDRB r2,[r1,#0]
; is it null byte? if no, jump to loop body.
CMP r2,#0
BNE |L0.12|
; exit if null byte.
; "rt" variable is still in R0 register, ready to be used in caller function
BX lr
ENDP
42.1.4 Optimizing Keil 6/2013 (thumb mode)
Listing 42.4: Optimizing Keil 6/2013 (thumb mode)
my_atoi PROC
; R1 will be pointer to the input character
MOVS r1,r0
; R0 is allocated to "rt" variable
MOVS r0,#0
B |L0.16|
|L0.6|
MOVS r3,#0xa
; R3=10
MULS r0,r3,r0
; R0=R3*R0=rt*10
; shift pointer to the next character:
ADDS r1,r1,#1
; correct whole thing by subtracting 0' character from it':
SUBS r0,r0,#0x30
ADDS r0,r2,r0
; rt=R2+R0=input character + (rt*10 - '0')
|L0.16|
; load input character to R2
LDRB r2,[r1,#0]
; is it zero?
CMP r2,#0
; jump to loop body if its not'
BNE |L0.6|
; rt variable in R0 now, ready to be used in caller function
BX lr
ENDP
Interestingly, from school mathematics we may remember that the order of addition and subtraction operations doesn’t
matter. That’s our case: first, the rt ∗ 10 −′
0′
expression is computed, then the input character value is added to it. Indeed,
the result is the same, but the compiler did some regrouping.
42.1.5 Optimizing GCC 4.9.1 ARM64
The ARM64 compiler can use the pre-increment instruction suffix:
Listing 42.5: Optimizing GCC 4.9.1 ARM64
my_atoi:
; load input character into W1
ldrb w1, [x0]
mov x2, x0
; X2=address of input string
; is loaded character zero?
; jump to exit if its so'
; W1 will contain 0 in this case.
; it will be reloaded into W0 at L4.
cbz w1, .L4
496
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE
; W0 will contain "rt" variable
; initialize it at zero:
mov w0, 0
.L3:
; subtract 48 or '0' from input variable and put result into W3:
sub w3, w1, #48
; load next character at address X2+1 into W1 with pre-increment:
ldrb w1, [x2,1]!
add w0, w0, w0, lsl 2
; W0=W0+W0<<2=W0+W0*4=rt*5
add w0, w3, w0, lsl 1
; W0=input digit + W0<<1 = input digit + rt*5*2 = input digit + rt*10
; if the character we just loaded is not null byte, jump to the loop begin
cbnz w1, .L3
; variable to be returned (rt) is in W0, ready to be used in caller function
ret
.L4:
mov w0, w1
ret
42.2 A slightly advanced example
My new code snippet is more advanced, now it checks for the “minus” sign at the first character and reports an error if a
non-digit was found in the input string:
#include <stdio.h>
int my_atoi (char *s)
{
int negative=0;
int rt=0;
if (*s=='-')
{
negative=1;
s++;
};
while (*s)
{
if (*s<'0' || *s>'9')
{
printf ("Error! Unexpected char: '%c'n", *s);
exit(0);
};
rt=rt*10 + (*s-'0');
s++;
};
if (negative)
return -rt;
return rt;
};
int main()
{
printf ("%dn", my_atoi ("1234"));
printf ("%dn", my_atoi ("1234567890"));
printf ("%dn", my_atoi ("-1234"));
printf ("%dn", my_atoi ("-1234567890"));
printf ("%dn", my_atoi ("-a1234567890")); // error
};
42.2.1 Optimizing GCC 4.9.1 x64
Listing 42.6: Optimizing GCC 4.9.1 x64
497
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE
.LC0:
.string "Error! Unexpected char: '%c'n"
my_atoi:
sub rsp, 8
movsx edx, BYTE PTR [rdi]
; check for minus sign
cmp dl, 45 ; '-'
je .L22
xor esi, esi
test dl, dl
je .L20
.L10:
; ESI=0 here if there was no minus sign and 1 if it was
lea eax, [rdx-48]
; any character other than digit will result unsigned number greater than 9 after subtraction
; so if it is not digit, jump to L4, where error will be reported:
cmp al, 9
ja .L4
xor eax, eax
jmp .L6
.L7:
lea ecx, [rdx-48]
cmp cl, 9
ja .L4
.L6:
lea eax, [rax+rax*4]
add rdi, 1
lea eax, [rdx-48+rax*2]
movsx edx, BYTE PTR [rdi]
test dl, dl
jne .L7
; if there was no minus sign, skip NEG instruction
; if it was, execute it.
test esi, esi
je .L18
neg eax
.L18:
add rsp, 8
ret
.L22:
movsx edx, BYTE PTR [rdi+1]
lea rax, [rdi+1]
test dl, dl
je .L20
mov rdi, rax
mov esi, 1
jmp .L10
.L20:
xor eax, eax
jmp .L18
.L4:
; report error. character is in EDX
mov edi, 1
mov esi, OFFSET FLAT:.LC0 ; "Error! Unexpected char: '%c'n"
xor eax, eax
call __printf_chk
xor edi, edi
call exit
If the “minus” sign was encountered at the string start, the NEG instruction is to be executed at the end. It just negates
the number.
There is one more thing that needs mentioning. How would a common programmer check if the character is not a digit?
Just how I wrote it in the source code:
if (*s<'0' || *s>'9')
...
There are two comparison operations. What is interesting is that we can replace both operations by single one: just
subtract “0” from character value, treat result as unsigned value (this is important) and check if it’s greater than 9.
498
CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE
For example, let’s say that the user input contains the dot character (“.”) which has ASCII code 46. 46−48 = −2 if we treat
the result as a signed number. Indeed, the dot character is located two places earlier than the “0” character in the ASCII
table. But it is 0xFFFFFFFE (4294967294) if we treat the result as an unsigned value, and that’s definitely bigger than 9!
The compilers do this often, so it’s important to recognize these tricks.
Another example of it in this book: 48.1.2 on page 529.
Optimizing MSVC 2013 x64 does the same tricks.
42.2.2 Optimizing Keil 6/2013 (ARM mode)
Listing 42.7: Optimizing Keil 6/2013 (ARM mode)
1 my_atoi PROC
2 PUSH {r4-r6,lr}
3 MOV r4,r0
4 LDRB r0,[r0,#0]
5 MOV r6,#0
6 MOV r5,r6
7 CMP r0,#0x2d '-'
8 ; R6 will contain 1 if minus was encountered, 0 if otherwise
9 MOVEQ r6,#1
10 ADDEQ r4,r4,#1
11 B |L0.80|
12 |L0.36|
13 SUB r0,r1,#0x30
14 CMP r0,#0xa
15 BCC |L0.64|
16 ADR r0,|L0.220|
17 BL __2printf
18 MOV r0,#0
19 BL exit
20 |L0.64|
21 LDRB r0,[r4],#1
22 ADD r1,r5,r5,LSL #2
23 ADD r0,r0,r1,LSL #1
24 SUB r5,r0,#0x30
25 |L0.80|
26 LDRB r1,[r4,#0]
27 CMP r1,#0
28 BNE |L0.36|
29 CMP r6,#0
30 ; negate result
31 RSBNE r0,r5,#0
32 MOVEQ r0,r5
33 POP {r4-r6,pc}
34 ENDP
35
36 |L0.220|
37 DCB "Error! Unexpected char: '%c'n",0
There is no NEG instruction in 32-bit ARM, so the “Reverse Subtraction” operation (line 31) is used here. It is triggered
if the result of the CMP instruction (at line 29) was “Not Equal” (hence -NE suffix). So what RSBNE does is to subtract the
resulting value from 0. It works just like the regular subtraction operation, but swaps operands. Subtracting any number
from 0 results in negation: 0 − x = −x.
Thumb mode code is mostly the same.
GCC 4.9 for ARM64 can use the NEG instruction, which is available in ARM64.
499
CHAPTER 43. INLINE FUNCTIONS
Chapter 43
Inline functions
Inlined code is when the compiler, instead of placing a call instruction to a small or tiny function, just places its body right
in-place.
Listing 43.1: A simple example
#include <stdio.h>
int celsius_to_fahrenheit (int celsius)
{
return celsius * 9 / 5 + 32;
};
int main(int argc, char *argv[])
{
int celsius=atol(argv[1]);
printf ("%dn", celsius_to_fahrenheit (celsius));
};
… is compiled in very predictable way, however, if we turn on GCC optimizations (-O3), we’ll see:
Listing 43.2: Optimizing GCC 4.8.1
_main:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
call ___main
mov eax, DWORD PTR [ebp+12]
mov eax, DWORD PTR [eax+4]
mov DWORD PTR [esp], eax
call _atol
mov edx, 1717986919
mov DWORD PTR [esp], OFFSET FLAT:LC2 ; "%d120"
lea ecx, [eax+eax*8]
mov eax, ecx
imul edx
sar ecx, 31
sar edx
sub edx, ecx
add edx, 32
mov DWORD PTR [esp+4], edx
call _printf
leave
ret
(Here the division is done by multiplication( 41 on page 488).)
Yes, our small function celsius_to_fahrenheit() was just placed before the printf() call. Why? It can be
faster than executing this function’s code plus the overhead of calling/returning.
Modern optimizing compilers are choosing small functions for inlining automatically. But it’s possible to force compiler
additionally to inline some function, if to mark it with the “inline” keyword in its declaration.
500
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
43.1 Strings and memory functions
Another very common automatic optimization tactic is the inlining of string functions like strcpy(), strcmp(), strlen(), memset(),
memcmp(), memcpy(), etc.
Sometimes it’s faster than to call a separate function.
These are very frequent patterns and it is highly advisable for reverse engineers to learn to detect automatically.
43.1.1 strcmp()
Listing 43.3: strcmp() example
bool is_bool (char *s)
{
if (strcmp (s, "true")==0)
return true;
if (strcmp (s, "false")==0)
return false;
assert(0);
};
Listing 43.4: Optimizing GCC 4.8.1
.LC0:
.string "true"
.LC1:
.string "false"
is_bool:
.LFB0:
push edi
mov ecx, 5
push esi
mov edi, OFFSET FLAT:.LC0
sub esp, 20
mov esi, DWORD PTR [esp+32]
repz cmpsb
je .L3
mov esi, DWORD PTR [esp+32]
mov ecx, 6
mov edi, OFFSET FLAT:.LC1
repz cmpsb
seta cl
setb dl
xor eax, eax
cmp cl, dl
jne .L8
add esp, 20
pop esi
pop edi
ret
.L8:
mov DWORD PTR [esp], 0
call assert
add esp, 20
pop esi
pop edi
ret
.L3:
add esp, 20
mov eax, 1
pop esi
pop edi
ret
Listing 43.5: Optimizing MSVC 2010
$SG3454 DB 'true', 00H
$SG3456 DB 'false', 00H
501
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
_s$ = 8 ; size = 4
?is_bool@@YA_NPAD@Z PROC ; is_bool
push esi
mov esi, DWORD PTR _s$[esp]
mov ecx, OFFSET $SG3454 ; 'true'
mov eax, esi
npad 4 ; align next label
$LL6@is_bool:
mov dl, BYTE PTR [eax]
cmp dl, BYTE PTR [ecx]
jne SHORT $LN7@is_bool
test dl, dl
je SHORT $LN8@is_bool
mov dl, BYTE PTR [eax+1]
cmp dl, BYTE PTR [ecx+1]
jne SHORT $LN7@is_bool
add eax, 2
add ecx, 2
test dl, dl
jne SHORT $LL6@is_bool
$LN8@is_bool:
xor eax, eax
jmp SHORT $LN9@is_bool
$LN7@is_bool:
sbb eax, eax
sbb eax, -1
$LN9@is_bool:
test eax, eax
jne SHORT $LN2@is_bool
mov al, 1
pop esi
ret 0
$LN2@is_bool:
mov ecx, OFFSET $SG3456 ; 'false'
mov eax, esi
$LL10@is_bool:
mov dl, BYTE PTR [eax]
cmp dl, BYTE PTR [ecx]
jne SHORT $LN11@is_bool
test dl, dl
je SHORT $LN12@is_bool
mov dl, BYTE PTR [eax+1]
cmp dl, BYTE PTR [ecx+1]
jne SHORT $LN11@is_bool
add eax, 2
add ecx, 2
test dl, dl
jne SHORT $LL10@is_bool
$LN12@is_bool:
xor eax, eax
jmp SHORT $LN13@is_bool
$LN11@is_bool:
sbb eax, eax
sbb eax, -1
$LN13@is_bool:
test eax, eax
jne SHORT $LN1@is_bool
xor al, al
pop esi
ret 0
$LN1@is_bool:
push 11
push OFFSET $SG3458
push OFFSET $SG3459
502
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
call DWORD PTR __imp___wassert
add esp, 12
pop esi
ret 0
?is_bool@@YA_NPAD@Z ENDP ; is_bool
43.1.2 strlen()
Listing 43.6: strlen() example
int strlen_test(char *s1)
{
return strlen(s1);
};
Listing 43.7: Optimizing MSVC 2010
_s1$ = 8 ; size = 4
_strlen_test PROC
mov eax, DWORD PTR _s1$[esp-4]
lea edx, DWORD PTR [eax+1]
$LL3@strlen_tes:
mov cl, BYTE PTR [eax]
inc eax
test cl, cl
jne SHORT $LL3@strlen_tes
sub eax, edx
ret 0
_strlen_test ENDP
43.1.3 strcpy()
Listing 43.8: strcpy() example
void strcpy_test(char *s1, char *outbuf)
{
strcpy(outbuf, s1);
};
Listing 43.9: Optimizing MSVC 2010
_s1$ = 8 ; size = 4
_outbuf$ = 12 ; size = 4
_strcpy_test PROC
mov eax, DWORD PTR _s1$[esp-4]
mov edx, DWORD PTR _outbuf$[esp-4]
sub edx, eax
npad 6 ; align next label
$LL3@strcpy_tes:
mov cl, BYTE PTR [eax]
mov BYTE PTR [edx+eax], cl
inc eax
test cl, cl
jne SHORT $LL3@strcpy_tes
ret 0
_strcpy_test ENDP
43.1.4 memset()
Example#1
Listing 43.10: 32 bytes
#include <stdio.h>
503
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
void f(char *out)
{
memset(out, 0, 32);
};
Many compilers don’t generate a call to memset() for short blocks, but rather insert a MOV:
Listing 43.11: Optimizing GCC 4.9.1 x64
f:
mov QWORD PTR [rdi], 0
mov QWORD PTR [rdi+8], 0
mov QWORD PTR [rdi+16], 0
mov QWORD PTR [rdi+24], 0
ret
By the way, that remind us of unrolled loops: 14.1.4 on page 176.
Example#2
Listing 43.12: 67 bytes
#include <stdio.h>
void f(char *out)
{
memset(out, 0, 67);
};
When the block size is not a multiple of 4 or 8, the compilers can behave differently.
For instance, MSVC 2012 continues to insert MOVs:
Listing 43.13: Optimizing MSVC 2012 x64
out$ = 8
f PROC
xor eax, eax
mov QWORD PTR [rcx], rax
mov QWORD PTR [rcx+8], rax
mov QWORD PTR [rcx+16], rax
mov QWORD PTR [rcx+24], rax
mov QWORD PTR [rcx+32], rax
mov QWORD PTR [rcx+40], rax
mov QWORD PTR [rcx+48], rax
mov QWORD PTR [rcx+56], rax
mov WORD PTR [rcx+64], ax
mov BYTE PTR [rcx+66], al
ret 0
f ENDP
…while GCC uses REP STOSQ, concluding that this would be shorter than a pack of MOVs:
Listing 43.14: Optimizing GCC 4.9.1 x64
f:
mov QWORD PTR [rdi], 0
mov QWORD PTR [rdi+59], 0
mov rcx, rdi
lea rdi, [rdi+8]
xor eax, eax
and rdi, -8
sub rcx, rdi
add ecx, 67
shr ecx, 3
rep stosq
ret
43.1.5 memcpy()
Short blocks
The routine to copy short blocks is often implemented as a sequence of MOV instructions.
504
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
Listing 43.15: memcpy() example
void memcpy_7(char *inbuf, char *outbuf)
{
memcpy(outbuf+10, inbuf, 7);
};
Listing 43.16: Optimizing MSVC 2010
_inbuf$ = 8 ; size = 4
_outbuf$ = 12 ; size = 4
_memcpy_7 PROC
mov ecx, DWORD PTR _inbuf$[esp-4]
mov edx, DWORD PTR [ecx]
mov eax, DWORD PTR _outbuf$[esp-4]
mov DWORD PTR [eax+10], edx
mov dx, WORD PTR [ecx+4]
mov WORD PTR [eax+14], dx
mov cl, BYTE PTR [ecx+6]
mov BYTE PTR [eax+16], cl
ret 0
_memcpy_7 ENDP
Listing 43.17: Optimizing GCC 4.8.1
memcpy_7:
push ebx
mov eax, DWORD PTR [esp+8]
mov ecx, DWORD PTR [esp+12]
mov ebx, DWORD PTR [eax]
lea edx, [ecx+10]
mov DWORD PTR [ecx+10], ebx
movzx ecx, WORD PTR [eax+4]
mov WORD PTR [edx+4], cx
movzx eax, BYTE PTR [eax+6]
mov BYTE PTR [edx+6], al
pop ebx
ret
That’s usually done as follows: 4-byte blocks are copied first, then a 16-bit word (if needed), then the last byte (if needed).
Structures are also copied using MOV: 21.4.1 on page 365.
Long blocks
The compilers behave differently in this case.
Listing 43.18: memcpy() example
void memcpy_128(char *inbuf, char *outbuf)
{
memcpy(outbuf+10, inbuf, 128);
};
void memcpy_123(char *inbuf, char *outbuf)
{
memcpy(outbuf+10, inbuf, 123);
};
For copying 128 bytes, MSVC uses a single MOVSD instruction (because 128 divides evenly by 4):
Listing 43.19: Optimizing MSVC 2010
_inbuf$ = 8 ; size = 4
_outbuf$ = 12 ; size = 4
_memcpy_128 PROC
push esi
mov esi, DWORD PTR _inbuf$[esp]
push edi
mov edi, DWORD PTR _outbuf$[esp+4]
add edi, 10
mov ecx, 32
rep movsd
505
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
pop edi
pop esi
ret 0
_memcpy_128 ENDP
When copying 123 bytes, 30 32-byte words are copied first using MOVSD (that’s 120 bytes), then 2 bytes are copied using
MOVSW, then one more byte using MOVSB.
Listing 43.20: Optimizing MSVC 2010
_inbuf$ = 8 ; size = 4
_outbuf$ = 12 ; size = 4
_memcpy_123 PROC
push esi
mov esi, DWORD PTR _inbuf$[esp]
push edi
mov edi, DWORD PTR _outbuf$[esp+4]
add edi, 10
mov ecx, 30
rep movsd
movsw
movsb
pop edi
pop esi
ret 0
_memcpy_123 ENDP
GCC uses one big universal functions, that works for any block size:
Listing 43.21: Optimizing GCC 4.8.1
memcpy_123:
.LFB3:
push edi
mov eax, 123
push esi
mov edx, DWORD PTR [esp+16]
mov esi, DWORD PTR [esp+12]
lea edi, [edx+10]
test edi, 1
jne .L24
test edi, 2
jne .L25
.L7:
mov ecx, eax
xor edx, edx
shr ecx, 2
test al, 2
rep movsd
je .L8
movzx edx, WORD PTR [esi]
mov WORD PTR [edi], dx
mov edx, 2
.L8:
test al, 1
je .L5
movzx eax, BYTE PTR [esi+edx]
mov BYTE PTR [edi+edx], al
.L5:
pop esi
pop edi
ret
.L24:
movzx eax, BYTE PTR [esi]
lea edi, [edx+11]
add esi, 1
test edi, 2
mov BYTE PTR [edx+10], al
mov eax, 122
je .L7
.L25:
movzx edx, WORD PTR [esi]
506
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
add edi, 2
add esi, 2
sub eax, 2
mov WORD PTR [edi-2], dx
jmp .L7
.LFE3:
Universal memory copy functions usually work as follows: calculate how many 32-bit words can be copied, then copy
them using MOVSD, then copy the remaining bytes.
More complex copy functions use SIMD instructions and also take the memory alignment in consideration.
43.1.6 memcmp()
Listing 43.22: memcmp() example
void memcpy_1235(char *inbuf, char *outbuf)
{
memcpy(outbuf+10, inbuf, 1235);
};
For any block size, MSVC 2010 inserts the same universal function:
Listing 43.23: Optimizing MSVC 2010
_buf1$ = 8 ; size = 4
_buf2$ = 12 ; size = 4
_memcmp_1235 PROC
mov edx, DWORD PTR _buf2$[esp-4]
mov ecx, DWORD PTR _buf1$[esp-4]
push esi
push edi
mov esi, 1235
add edx, 10
$LL4@memcmp_123:
mov eax, DWORD PTR [edx]
cmp eax, DWORD PTR [ecx]
jne SHORT $LN10@memcmp_123
sub esi, 4
add ecx, 4
add edx, 4
cmp esi, 4
jae SHORT $LL4@memcmp_123
$LN10@memcmp_123:
movzx edi, BYTE PTR [ecx]
movzx eax, BYTE PTR [edx]
sub eax, edi
jne SHORT $LN7@memcmp_123
movzx eax, BYTE PTR [edx+1]
movzx edi, BYTE PTR [ecx+1]
sub eax, edi
jne SHORT $LN7@memcmp_123
movzx eax, BYTE PTR [edx+2]
movzx edi, BYTE PTR [ecx+2]
sub eax, edi
jne SHORT $LN7@memcmp_123
cmp esi, 3
jbe SHORT $LN6@memcmp_123
movzx eax, BYTE PTR [edx+3]
movzx ecx, BYTE PTR [ecx+3]
sub eax, ecx
$LN7@memcmp_123:
sar eax, 31
pop edi
or eax, 1
pop esi
ret 0
$LN6@memcmp_123:
pop edi
xor eax, eax
pop esi
507
CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS
ret 0
_memcmp_1235 ENDP
43.1.7 IDA script
I wrote a small IDA script for searching and folding such very frequently seen pieces of inline code:
GitHub.
508
CHAPTER 44. C99 RESTRICT
Chapter 44
C99 restrict
Here is a reason why FORTRAN programs, in some cases, work faster than C/C++ ones.
void f1 (int* x, int* y, int* sum, int* product, int* sum_product, int* update_me, size_t s)
{
for (int i=0; i<s; i++)
{
sum[i]=x[i]+y[i];
product[i]=x[i]*y[i];
update_me[i]=i*123; // some dummy value
sum_product[i]=sum[i]+product[i];
};
};
That’s very simple example with one specific thing in it: the pointer to the update_me array could be a pointer to the
sum array, product array, or even the sum_product array—nothing forbids that, right?
The compiler is fully aware of this, so it generates code with four stages in the loop body:
• calculate next sum[i]
• calculate next product[i]
• calculate next update_me[i]
• calculate next sum_product[i]— on this stage, we need to load from memory the already calculated sum[i] and
product[i]
Is it possible to optimize the last stage? Since we have already calculated sum[i] and product[i] it is not necessary
to load them again from memory. Yes, but compiler is not sure that nothing was overwritten in the 3rd stage! This is
called “pointer aliasing”, a situation when the compiler cannot be sure that a memory to which a pointer is pointing was not
changed.
restrict in the C99 standard[ISO07, pp. 6.7.3/1] is a promise, given by programmer to the compiler that the function
arguments marked by this keyword always points to different memory locations and never intersects.
To be more precise and describe this formally, restrict shows that only this pointer is to be used to access an object, and
no other pointer will be used for it. It can be even said the object will be accessed only via one single pointer, if it is marked
as restrict.
Let’s add this keyword to each pointer argument:
void f2 (int* restrict x, int* restrict y, int* restrict sum, int* restrict product, int* ⤦
restrict sum_product,
int* restrict update_me, size_t s)
{
for (int i=0; i<s; i++)
{
sum[i]=x[i]+y[i];
product[i]=x[i]*y[i];
update_me[i]=i*123; // some dummy value
sum_product[i]=sum[i]+product[i];
};
};
Let’s see results:
Listing 44.1: GCC x64: f1()
f1:
push r15 r14 r13 r12 rbp rdi rsi rbx
509
CHAPTER 44. C99 RESTRICT
mov r13, QWORD PTR 120[rsp]
mov rbp, QWORD PTR 104[rsp]
mov r12, QWORD PTR 112[rsp]
test r13, r13
je .L1
add r13, 1
xor ebx, ebx
mov edi, 1
xor r11d, r11d
jmp .L4
.L6:
mov r11, rdi
mov rdi, rax
.L4:
lea rax, 0[0+r11*4]
lea r10, [rcx+rax]
lea r14, [rdx+rax]
lea rsi, [r8+rax]
add rax, r9
mov r15d, DWORD PTR [r10]
add r15d, DWORD PTR [r14]
mov DWORD PTR [rsi], r15d ; store to sum[]
mov r10d, DWORD PTR [r10]
imul r10d, DWORD PTR [r14]
mov DWORD PTR [rax], r10d ; store to product[]
mov DWORD PTR [r12+r11*4], ebx ; store to update_me[]
add ebx, 123
mov r10d, DWORD PTR [rsi] ; reload sum[i]
add r10d, DWORD PTR [rax] ; reload product[i]
lea rax, 1[rdi]
cmp rax, r13
mov DWORD PTR 0[rbp+r11*4], r10d ; store to sum_product[]
jne .L6
.L1:
pop rbx rsi rdi rbp r12 r13 r14 r15
ret
Listing 44.2: GCC x64: f2()
f2:
push r13 r12 rbp rdi rsi rbx
mov r13, QWORD PTR 104[rsp]
mov rbp, QWORD PTR 88[rsp]
mov r12, QWORD PTR 96[rsp]
test r13, r13
je .L7
add r13, 1
xor r10d, r10d
mov edi, 1
xor eax, eax
jmp .L10
.L11:
mov rax, rdi
mov rdi, r11
.L10:
mov esi, DWORD PTR [rcx+rax*4]
mov r11d, DWORD PTR [rdx+rax*4]
mov DWORD PTR [r12+rax*4], r10d ; store to update_me[]
add r10d, 123
lea ebx, [rsi+r11]
imul r11d, esi
mov DWORD PTR [r8+rax*4], ebx ; store to sum[]
mov DWORD PTR [r9+rax*4], r11d ; store to product[]
add r11d, ebx
mov DWORD PTR 0[rbp+rax*4], r11d ; store to sum_product[]
lea r11, 1[rdi]
cmp r11, r13
jne .L11
.L7:
pop rbx rsi rdi rbp r12 r13
510
CHAPTER 44. C99 RESTRICT
ret
The difference between the compiled f1() and f2() functions is as follows: in f1(), sum[i] and product[i] are
reloaded in the middle of the loop, and in f2() there is no such thing, the already calculated values are used, since we
“promised” the compiler that no one and nothing will change the values in sum[i] and product[i] during the execution
of the loop’s body, so it is “sure” that there is no need to load the value from memory again. Obviously, the second example
works faster.
But what if the pointers in the function’s arguments intersect somehow? This is on the programmer’s conscience, and
the results will be incorrect.
Let’s go back to FORTRAN. Compilers of this programming language treats all pointers as such, so when it was not
possible to set restrict in C, FORTRAN can generate faster code in these cases.
How practical is it? In the cases when the function works with several big blocks in memory. There are a lot of such in
linear algebra, for instance. A lot of linear algebra is done on supercomputers/HPC1
, so probably that is why, traditionally,
FORTRAN is still used there [Loh10].
But when the number of iterations is not very big, certainly, the speed boost may not to be significant.
1High-Performance Computing
511
CHAPTER 45. BRANCHLESS ABS() FUNCTION
Chapter 45
Branchless abs() function
Let’s revisit an example I gave earlier 12.2 on page 127 and ask ourselves, is it possible to make a branchless version of the
function in x86 code?
int my_abs (int i)
{
if (i<0)
return -i;
else
return i;
};
And the answer is yes.
45.1 Optimizing GCC 4.9.1 x64
We could see it if we compile it using optimizing GCC 4.9:
Listing 45.1: Optimizing GCC 4.9 x64
my_abs:
mov edx, edi
mov eax, edi
sar edx, 31
; EDX is 0xFFFFFFFF here if sign of input value is minus
; EDX is 0 if sign of input value is plus (including 0)
; the following two instructions have effect only if EDX is 0xFFFFFFFF
; or idle if EDX is 0
xor eax, edx
sub eax, edx
ret
This is how it works:
Arithmetically shift the input value left by 31. Arithmetical shift implies sign extension, so if the MSB is 1, all 32 bits are
to be filled with 1, or with 0 if otherwise. In other words, the SAR REG, 31 instruction makes 0xFFFFFFFF if the sign was
negative or 0 if positive. After the execution of SAR, we have this value in EDX. Then, if the value is 0xFFFFFFFF (i.e., the
sign is negative), the input value is inverted (because XOR REG, 0xFFFFFFFF is effectively an inverse all bits operation).
Then, again, if the value is 0xFFFFFFFF (i.e., the sign is negative), 1 is added to the final result (because subtracting −1
from some value resulting in incrementing it). Inversion of all bits and incrementing is exactly how two’s complement value
is negated: 30 on page 451.
We may observe that the last two instruction do something if the sign of the input value is negative. Otherwise (if the
sign is positive) they do nothing at all, leaving the input value untouched.
The algorithm is explained in [War02, pp. 2-4]. I’m not sure, how GCC did it, deduced it by itself or found a suitable
pattern among known ones?
45.2 Optimizing GCC 4.9 ARM64
GCC 4.9 for ARM64 generates mostly the same, just decides to use the full 64-bit registers. There are less instructions,
because the input value can be shifted using a suffixed instruction (“asr”) instead of using a separate instruction.
Listing 45.2: Optimizing GCC 4.9 ARM64
my_abs:
512
CHAPTER 45. BRANCHLESS ABS() FUNCTION 45.2. OPTIMIZING GCC 4.9 ARM64
; sign-extend input 32-bit value to X0 64-bit register:
sxtw x0, w0
eor x1, x0, x0, asr 63
; X1=X0^(X0>>63) (shift is arithmetical)
sub x0, x1, x0, asr 63
; X0=X1-(X0>>63)=X0^(X0>>63)-(X0>>63) (all shifts are arithmetical)
ret
513
CHAPTER 46. VARIADIC FUNCTIONS
Chapter 46
Variadic functions
Functions like printf() and scanf() can have a variable number of arguments. How are these arguments accessed?
46.1 Computing arithmetic mean
Let’s imagine that we need to calculate arithmetic mean, and for some weird reason we need to specify all the values as
function arguments.
But it’s impossible to get the number of arguments in a variadic function in C/C++, so I’ll denote the value of −1 as a
terminator.
There is the standard stdarg.h header file which define macros for dealing with such arguments. The printf() and
scanf() functions use them as well.
#include <stdio.h>
#include <stdarg.h>
int arith_mean(int v, ...)
{
va_list args;
int sum=v, count=1, i;
va_start(args, v);
while(1)
{
i=va_arg(args, int);
if (i==-1) // terminator
break;
sum=sum+i;
count++;
}
va_end(args);
return sum/count;
};
int main()
{
printf ("%dn", arith_mean (1, 2, 7, 10, 15, -1 /* terminator */));
};
The first argument has to be treated just like a normal argument. All other arguments are loaded using the va_arg
macro and then summed.
So what is inside?
46.1.1 cdecl calling conventions
Listing 46.1: Optimizing MSVC 6.0
_v$ = 8
_arith_mean PROC NEAR
mov eax, DWORD PTR _v$[esp-4] ; load 1st argument into sum
push esi
mov esi, 1 ; count=1
lea edx, DWORD PTR _v$[esp] ; address of the 1st argument
514
CHAPTER 46. VARIADIC FUNCTIONS 46.1. COMPUTING ARITHMETIC MEAN
$L838:
mov ecx, DWORD PTR [edx+4] ; load next argument
add edx, 4 ; shift pointer to the next argument
cmp ecx, -1 ; is it -1?
je SHORT $L856 ; exit if so
add eax, ecx ; sum = sum + loaded argument
inc esi ; count++
jmp SHORT $L838
$L856:
; calculate quotient
cdq
idiv esi
pop esi
ret 0
_arith_mean ENDP
$SG851 DB '%d', 0aH, 00H
_main PROC NEAR
push -1
push 15
push 10
push 7
push 2
push 1
call _arith_mean
push eax
push OFFSET FLAT:$SG851 ; '%d'
call _printf
add esp, 32
ret 0
_main ENDP
The arguments, as we may see, are passed to main() one-by-one. The first argument is pushed into the local stack as
first. The terminating value (−1) is pushed last.
The arith_mean() function takes the value of the first argument and stores it in the sum variable. Then, it sets the
EDX register to the address of the second argument, takes the value from it, adds it to sum, and does this in an infinite loop,
until −1 is found.
When it’s found, the sum is divided by the number of all values (excluding −1) and the quotient is returned.
So, in other words, the function treats the stack fragment as an array of integer values of infinite length. Now we can
understand why the cdecl calling convention forces us to push the first argument into the stack as last. Because otherwise,
it would not be possible to find the first argument, or, for printf-like functions, it would not be possible to find the address
of the format-string.
46.1.2 Register-based calling conventions
The observant reader may ask, what about calling conventions where the first few arguments are passed in registers? Let’s
see:
Listing 46.2: Optimizing MSVC 2012 x64
$SG3013 DB '%d', 0aH, 00H
v$ = 8
arith_mean PROC
mov DWORD PTR [rsp+8], ecx ; 1st argument
mov QWORD PTR [rsp+16], rdx ; 2nd argument
mov QWORD PTR [rsp+24], r8 ; 3rd argument
mov eax, ecx ; sum = 1st argument
lea rcx, QWORD PTR v$[rsp+8] ; pointer to the 2nd argument
mov QWORD PTR [rsp+32], r9 ; 4th argument
mov edx, DWORD PTR [rcx] ; load 2nd argument
mov r8d, 1 ; count=1
cmp edx, -1 ; 2nd argument is -1?
je SHORT $LN8@arith_mean ; exit if so
$LL3@arith_mean:
add eax, edx ; sum = sum + loaded argument
mov edx, DWORD PTR [rcx+8] ; load next argument
515
CHAPTER 46. VARIADIC FUNCTIONS 46.1. COMPUTING ARITHMETIC MEAN
lea rcx, QWORD PTR [rcx+8] ; shift pointer to point to the argument after next
inc r8d ; count++
cmp edx, -1 ; is loaded argument -1?
jne SHORT $LL3@arith_mean ; go to loop begin if its not'
$LN8@arith_mean:
; calculate quotient
cdq
idiv r8d
ret 0
arith_mean ENDP
main PROC
sub rsp, 56
mov edx, 2
mov DWORD PTR [rsp+40], -1
mov DWORD PTR [rsp+32], 15
lea r9d, QWORD PTR [rdx+8]
lea r8d, QWORD PTR [rdx+5]
lea ecx, QWORD PTR [rdx-1]
call arith_mean
lea rcx, OFFSET FLAT:$SG3013
mov edx, eax
call printf
xor eax, eax
add rsp, 56
ret 0
main ENDP
We see that the first 4 arguments are passed in the registers and two more — in the stack. The arith_mean() function
first places these 4 arguments into the Shadow Space and then treats the Shadow Space and stack behind it as a single
continuous array!
What about GCC? Things are slightly clumsier here, because now the function is divided in two parts: the first part saves
the registers into the “red zone”, processes that space, and the second part of the function processes the stack:
Listing 46.3: Optimizing GCC 4.9.1 x64
arith_mean:
lea rax, [rsp+8]
; save 6 input registers in "red zone" in the local stack
mov QWORD PTR [rsp-40], rsi
mov QWORD PTR [rsp-32], rdx
mov QWORD PTR [rsp-16], r8
mov QWORD PTR [rsp-24], rcx
mov esi, 8
mov QWORD PTR [rsp-64], rax
lea rax, [rsp-48]
mov QWORD PTR [rsp-8], r9
mov DWORD PTR [rsp-72], 8
lea rdx, [rsp+8]
mov r8d, 1
mov QWORD PTR [rsp-56], rax
jmp .L5
.L7:
; work out saved arguments
lea rax, [rsp-48]
mov ecx, esi
add esi, 8
add rcx, rax
mov ecx, DWORD PTR [rcx]
cmp ecx, -1
je .L4
.L8:
add edi, ecx
add r8d, 1
.L5:
; decide, which part we will work out now.
; is current argument number less or equal 6?
cmp esi, 47
jbe .L7 ; no, process saved arguments then
; work out arguments from stack
mov rcx, rdx
516
CHAPTER 46. VARIADIC FUNCTIONS 46.2. VPRINTF() FUNCTION CASE
add rdx, 8
mov ecx, DWORD PTR [rcx]
cmp ecx, -1
jne .L8
.L4:
mov eax, edi
cdq
idiv r8d
ret
.LC1:
.string "%dn"
main:
sub rsp, 8
mov edx, 7
mov esi, 2
mov edi, 1
mov r9d, -1
mov r8d, 15
mov ecx, 10
xor eax, eax
call arith_mean
mov esi, OFFSET FLAT:.LC1
mov edx, eax
mov edi, 1
xor eax, eax
add rsp, 8
jmp __printf_chk
By the way, a similar usage of the Shadow Space is also considered here : 64.8 on page 669.
46.2 vprintf() function case
Many programmers define their own logging functions which take a printf-like format string + a variable number of argu-
ments.
Another popular example is the die() function, which prints some message and exits. We need some way to pack input
arguments of unknown number and pass them to the printf() function. But how? That’s why there are functions with
“v” in name. One of them is vprintf(): it takes a format-string and a pointer to a variable of type va_list:
#include <stdlib.h>
#include <stdarg.h>
void die (const char * fmt, ...)
{
va_list va;
va_start (va, fmt);
vprintf (fmt, va);
exit(0);
};
By closer examination, we can see that va_list is a pointer to an array. Let’s compile:
Listing 46.4: Optimizing MSVC 2010
_fmt$ = 8
_die PROC
; load 1st argument (format-string)
mov ecx, DWORD PTR _fmt$[esp-4]
; get pointer to the 2nd argument
lea eax, DWORD PTR _fmt$[esp]
push eax ; pass pointer
push ecx
call _vprintf
add esp, 8
push 0
call _exit
$LN3@die:
int 3
_die ENDP
517
CHAPTER 46. VARIADIC FUNCTIONS 46.2. VPRINTF() FUNCTION CASE
We see that all our function does is just taking a pointer to the arguments and passing it to vprintf(), and that function is
treating it like an infinite array of arguments!
Listing 46.5: Optimizing MSVC 2012 x64
fmt$ = 48
die PROC
; save first 4 arguments in Shadow Space
mov QWORD PTR [rsp+8], rcx
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+24], r8
mov QWORD PTR [rsp+32], r9
sub rsp, 40
lea rdx, QWORD PTR fmt$[rsp+8] ; pass pointer to the 1st argument
; RCX here is still points to the 1st argument (format-string) of die()
; so vprintf() will take it right from RCX
call vprintf
xor ecx, ecx
call exit
int 3
die ENDP
518
CHAPTER 47. STRINGS TRIMMING
Chapter 47
Strings trimming
A very common string processing task is to remove some characters at the start and/or at the end.
In this example, we are going to work with a function which removes all newline characters (CR1
/LF2
) from the end of
the input string:
#include <stdio.h>
#include <string.h>
char* str_trim (char *s)
{
char c;
size_t str_len;
// work as long as r or n is at the end of string
// stop if some other character there or its an empty string'
// (at start or due to our operation)
for (str_len=strlen(s); str_len>0 && (c=s[str_len-1]); str_len--)
{
if (c=='r' || c=='n')
s[str_len-1]=0;
else
break;
};
return s;
};
int main()
{
// test
// strdup() is used to copy text string into data segment,
// because it will crash on Linux otherwise,
// where text strings are allocated in constant data segment,
// and not modifiable.
printf ("[%s]n", str_trim (strdup("")));
printf ("[%s]n", str_trim (strdup("n")));
printf ("[%s]n", str_trim (strdup("r")));
printf ("[%s]n", str_trim (strdup("nr")));
printf ("[%s]n", str_trim (strdup("rn")));
printf ("[%s]n", str_trim (strdup("test1rn")));
printf ("[%s]n", str_trim (strdup("test2nr")));
printf ("[%s]n", str_trim (strdup("test3nrnr")));
printf ("[%s]n", str_trim (strdup("test4n")));
printf ("[%s]n", str_trim (strdup("test5r")));
printf ("[%s]n", str_trim (strdup("test6rrr")));
};
The input argument is always returned on exit, this is convenient when you need to chain string processing functions,
like it was done here in the main() function.
The second part of for() (str_len>0 && (c=s[str_len-1])) is the so called “short-circuit” in C/C++ and is very
convenient [Yur13, p. 1.3.8]. The C/C++ compilers guarantee an evaluation sequence from left to right. So if the first clause
1Carriage return (13 or’r’ in C/C++)
2Line feed (10 or’n’ in C/C++)
519
CHAPTER 47. STRINGS TRIMMING 47.1. X64: OPTIMIZING MSVC 2013
is false after evaluation, the second one is never to be evaluated.
47.1 x64: Optimizing MSVC 2013
Listing 47.1: Optimizing MSVC 2013 x64
s$ = 8
str_trim PROC
; RCX is the first function argument and it always holds pointer to the string
; this is strlen() function inlined right here:
; set RAX to 0xFFFFFFFFFFFFFFFF (-1)
or rax, -1
$LL14@str_trim:
inc rax
cmp BYTE PTR [rcx+rax], 0
jne SHORT $LL14@str_trim
; is string length zero? exit then
test eax, eax
$LN18@str_trim:
je SHORT $LN15@str_trim
; RAX holds string length
; here is probably disassembler (or assembler printing routine) error,
; LEA RDX... should be here instead of LEA EDX...
lea edx, DWORD PTR [rax-1]
; idle instruction: EAX will be reset at the next instructions execution'
mov eax, edx
; load character at address s[str_len-1]
movzx eax, BYTE PTR [rdx+rcx]
; save also pointer to the last character to R8
lea r8, QWORD PTR [rdx+rcx]
cmp al, 13 ; is it 'r'?
je SHORT $LN2@str_trim
cmp al, 10 ; is it 'n'?
jne SHORT $LN15@str_trim
$LN2@str_trim:
; store 0 to that place
mov BYTE PTR [r8], 0
mov eax, edx
; check character for 0, but conditional jump is above...
test edx, edx
jmp SHORT $LN18@str_trim
$LN15@str_trim:
; return "s"
mov rax, rcx
ret 0
str_trim ENDP
First, MSVC inlined the strlen() function code, because it concluded this is to be faster than the usual strlen()
work + the cost of calling it and returning from it. This is called inlining: 43 on page 500.
The first instruction of the inlined strlen() is OR RAX, 0xFFFFFFFFFFFFFFFF. I don’t know why MSVC uses OR
instead of MOV RAX, 0xFFFFFFFFFFFFFFFF, but it does this often. And of course, it is equivalent: all bits are set, and
a number with all bits set is −1 in two’s complement arithmetic: 30 on page 451.
Why would the −1 number be used in strlen(), one might ask. Due to optimizations, of course. Here is the code that
MSVC generated:
Listing 47.2: Inlined strlen() by MSVC 2013 x64
; RCX = pointer to the input string
; RAX = current string length
or rax, -1
label:
inc rax
cmp BYTE PTR [rcx+rax], 0
jne SHORT label
; RAX = string length
Try to write shorter if you want to initialize the counter at 0! Here is my attempt:
520
CHAPTER 47. STRINGS TRIMMING 47.2. X64: NON-OPTIMIZING GCC 4.9.1
Listing 47.3: My version of strlen()
; RCX = pointer to the input string
; RAX = current string length
xor rax, rax
label:
cmp byte ptr [rcx+rax], 0
jz exit
inc rax
jmp label
exit:
; RAX = string length
I failed. We need to use additional JMP instruction!
So what the MSVC 2013 compiler did is to move the INC instruction to the place before the actual character loading. If
the first character is 0, that’s OK, RAX is 0 at this moment, so the resulting string length is 0.
The rest in this function seems easy to understand. There is another trick at the end. If we do not count strlen()’s
inlined code, there are only 3 conditional jumps in the function. There should be 4: the 4th has to be located at the function
end, to check if the character is zero. But there is an unconditional jump to the “$LN18@str_trim” label, where we see JE,
which was first used to check if the input string is empty, right after strlen() finishes. So the code uses the JE instruction
at this place for two purposes! This may be overkill, but nevertheless, MSVC did it.
You can read more on why it’s important to do the job without conditional jumps, if possible: 33.1 on page 456.
47.2 x64: Non-optimizing GCC 4.9.1
str_trim:
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR [rbp-24], rdi
; for() first part begins here
mov rax, QWORD PTR [rbp-24]
mov rdi, rax
call strlen
mov QWORD PTR [rbp-8], rax ; str_len
; for() first part ends here
jmp .L2
; for() body begins here
.L5:
cmp BYTE PTR [rbp-9], 13 ; c=='r'?
je .L3
cmp BYTE PTR [rbp-9], 10 ; c=='n'?
jne .L4
.L3:
mov rax, QWORD PTR [rbp-8] ; str_len
lea rdx, [rax-1] ; EDX=str_len-1
mov rax, QWORD PTR [rbp-24] ; s
add rax, rdx ; RAX=s+str_len-1
mov BYTE PTR [rax], 0 ; s[str_len-1]=0
; for() body ends here
; for() third part begins here
sub QWORD PTR [rbp-8], 1 ; str_len--
; for() third part ends here
.L2:
; for() second part begins here
cmp QWORD PTR [rbp-8], 0 ; str_len==0?
je .L4 ; exit then
; check second clause, and load "c"
mov rax, QWORD PTR [rbp-8] ; RAX=str_len
lea rdx, [rax-1] ; RDX=str_len-1
mov rax, QWORD PTR [rbp-24] ; RAX=s
add rax, rdx ; RAX=s+str_len-1
movzx eax, BYTE PTR [rax] ; AL=s[str_len-1]
mov BYTE PTR [rbp-9], al ; store loaded char into "c"
cmp BYTE PTR [rbp-9], 0 ; is it zero?
jne .L5 ; yes? exit then
; for() second part ends here
.L4:
521
CHAPTER 47. STRINGS TRIMMING 47.3. X64: OPTIMIZING GCC 4.9.1
; return "s"
mov rax, QWORD PTR [rbp-24]
leave
ret
I have added my comments. After the execution of strlen(), the control is passed to the L2 label, and there two clauses
are checked, one after another. The second will never be checked, if the first one (str_len==0) is false (this is “short-circuit”).
Now let’s see this function in short form:
• First for() part (call to strlen())
• goto L2
• L5:
• for() body. goto exit, if needed
• for() third part (decrement of str_len)
• L2:
• for() second part: check first clause, then second. goto loop body begin or exit.
• L4:
• // exit
• return s
47.3 x64: Optimizing GCC 4.9.1
str_trim:
push rbx
mov rbx, rdi
; RBX will always be "s"
call strlen
; check for str_len==0 and exit if its so'
test rax, rax
je .L9
lea rdx, [rax-1]
; RDX will always contain str_len-1 value, not str_len
; so RDX is more like buffer index variable
lea rsi, [rbx+rdx] ; RSI=s+str_len-1
movzx ecx, BYTE PTR [rsi] ; load character
test cl, cl
je .L9 ; exit if its zero'
cmp cl, 10
je .L4
cmp cl, 13 ; exit if its not' 'n' and not 'r'
jne .L9
.L4:
; this is weird instruction. we need RSI=s-1 here.
; its possible to get it by' MOV RSI, EBX / DEC RSI
; but this is two instructions instead of one
sub rsi, rax
; RSI = s+str_len-1-str_len = s-1
; main loop begin
.L12:
test rdx, rdx
; store zero at address s-1+str_len-1+1 = s-1+str_len = s+str_len-1
mov BYTE PTR [rsi+1+rdx], 0
; check for str_len-1==0. exit if so.
je .L9
sub rdx, 1 ; equivalent to str_len--
; load next character at address s+str_len-1
movzx ecx, BYTE PTR [rbx+rdx]
test cl, cl ; is it zero? exit then
je .L9
cmp cl, 10 ; is it 'n'?
je .L12
522
CHAPTER 47. STRINGS TRIMMING 47.4. ARM64: NON-OPTIMIZING GCC (LINARO) 4.9
cmp cl, 13 ; is it 'r'?
je .L12
.L9:
; return "s"
mov rax, rbx
pop rbx
ret
Now this is more complex. The code before the loop’s body start is executed only once, but it has the CR/LF characters
check too! What is this code duplication for?
The common way to implement the main loop is probably this:
• (loop start) check for CR/LF characters, make decisions
• store zero character
But GCC has decided to reverse these two steps. Of course, store zero character cannot be first step, so another check is
needed:
• workout first character. match it to CR/LF, exit if character is not CR/LF
• (loop begin) store zero character
• check for CR/LF characters, make decisions
Now the main loop is very short, which is good for modern CPUs.
The code doesn’t use the str_len variable, but str_len-1. So this is more like an index in a buffer. Apparently, GCC notices
that the str_len-1 statement is used twice. So it’s better to allocate a variable which always holds a value that’s smaller
than the current string length by one, and decrement it (this is the same effect as decrementing the str_len variable).
47.4 ARM64: Non-optimizing GCC (Linaro) 4.9
This implementation is straightforward:
Listing 47.4: Non-optimizing GCC (Linaro) 4.9
str_trim:
stp x29, x30, [sp, -48]!
add x29, sp, 0
str x0, [x29,24] ; copy input argument into local stack
ldr x0, [x29,24] ; s
bl strlen
str x0, [x29,40] ; str_len variable in local stack
b .L2
; main loop begin
.L5:
ldrb w0, [x29,39]
; W0=c
cmp w0, 13 ; is it 'r'?
beq .L3
ldrb w0, [x29,39]
; W0=c
cmp w0, 10 ; is it 'n'?
bne .L4 ; goto exit if it is not
.L3:
ldr x0, [x29,40]
; X0=str_len
sub x0, x0, #1
; X0=str_len-1
ldr x1, [x29,24]
; X1=s
add x0, x1, x0
; X0=s+str_len-1
strb wzr, [x0] ; write byte at s+str_len-1
; decrement str_len:
ldr x0, [x29,40]
; X0=str_len
sub x0, x0, #1
; X0=str_len-1
str x0, [x29,40]
523
CHAPTER 47. STRINGS TRIMMING 47.5. ARM64: OPTIMIZING GCC (LINARO) 4.9
; save X0 (or str_len-1) to local stack
.L2:
ldr x0, [x29,40]
; str_len==0?
cmp x0, xzr
; goto exit then
beq .L4
ldr x0, [x29,40]
; X0=str_len
sub x0, x0, #1
; X0=str_len-1
ldr x1, [x29,24]
; X1=s
add x0, x1, x0
; X0=s+str_len-1
; load byte at address s+str_len-1 to W0
ldrb w0, [x0]
strb w0, [x29,39] ; store loaded byte to "c"
ldrb w0, [x29,39] ; reload it
; is it zero byte?
cmp w0, wzr
; goto exit, if its zero or to L5 if its not''
bne .L5
.L4:
; return s
ldr x0, [x29,24]
ldp x29, x30, [sp], 48
ret
47.5 ARM64: Optimizing GCC (Linaro) 4.9
This is a more advanced optimization. The first character is loaded at the beginning, and compared against 10 (the LF
character). Characters are also loaded in the main loop, for the characters after first one. This is somewhat similar to
the 47.3 on page 522 example.
Listing 47.5: Optimizing GCC (Linaro) 4.9
str_trim:
stp x29, x30, [sp, -32]!
add x29, sp, 0
str x19, [sp,16]
mov x19, x0
; X19 will always hold value of "s"
bl strlen
; X0=str_len
cbz x0, .L9 ; goto L9 (exit) if str_len==0
sub x1, x0, #1
; X1=X0-1=str_len-1
add x3, x19, x1
; X3=X19+X1=s+str_len-1
ldrb w2, [x19,x1] ; load byte at address X19+X1=s+str_len-1
; W2=loaded character
cbz w2, .L9 ; is it zero? jump to exit then
cmp w2, 10 ; is it 'n'?
bne .L15
.L12:
; main loop body. loaded character is always 10 or 13 at this moment!
sub x2, x1, x0
; X2=X1-X0=str_len-1-str_len=-1
add x2, x3, x2
; X2=X3+X2=s+str_len-1+(-1)=s+str_len-2
strb wzr, [x2,1] ; store zero byte at address s+str_len-2+1=s+str_len-1
cbz x1, .L9 ; str_len-1==0? goto exit, if so
sub x1, x1, #1 ; str_len--
ldrb w2, [x19,x1] ; load next character at address X19+X1=s+str_len-1
cmp w2, 10 ; is it 'n'?
cbz w2, .L9 ; jump to exit, if its zero'
beq .L12 ; jump to begin loop, if its' 'n'
.L15:
524
CHAPTER 47. STRINGS TRIMMING 47.6. ARM: OPTIMIZING KEIL 6/2013 (ARM MODE)
cmp w2, 13 ; is it 'r'?
beq .L12 ; yes, jump to the loop body begin
.L9:
; return "s"
mov x0, x19
ldr x19, [sp,16]
ldp x29, x30, [sp], 32
ret
47.6 ARM: Optimizing Keil 6/2013 (ARM mode)
And again, the compiler took advantage of ARM mode’s conditional instructions, so the code is much more compact.
Listing 47.6: Optimizing Keil 6/2013 (ARM mode)
str_trim PROC
PUSH {r4,lr}
; R0=s
MOV r4,r0
; R4=s
BL strlen ; strlen() takes "s" value from R0
; R0=str_len
MOV r3,#0
; R3 will always hold 0
|L0.16|
CMP r0,#0 ; str_len==0?
ADDNE r2,r4,r0 ; (if str_len!=0) R2=R4+R0=s+str_len
LDRBNE r1,[r2,#-1] ; (if str_len!=0) R1=load byte at address R2-1=s+str_len-1
CMPNE r1,#0 ; (if str_len!=0) compare loaded byte against 0
BEQ |L0.56| ; jump to exit if str_len==0 or loaded byte is 0
CMP r1,#0xd ; is loaded byte 'r'?
CMPNE r1,#0xa ; (if loaded byte is not 'r') is loaded byte 'r'?
SUBEQ r0,r0,#1 ; (if loaded byte is 'r' or 'n') R0-- or str_len--
STRBEQ r3,[r2,#-1] ; (if loaded byte is 'r' or 'n') store R3 (zero) at
address R2-1=s+str_len-1
BEQ |L0.16| ; jump to loop begin if loaded byte was 'r' or 'n'
|L0.56|
; return "s"
MOV r0,r4
POP {r4,pc}
ENDP
47.7 ARM: Optimizing Keil 6/2013 (thumb mode)
There are less conditional instructions in Thumb mode, so the code is simpler. But there are is really weird thing with
the 0x20 and 0x19 offsets. Why did the Keil compiler do so? Honestly, I have no idea. Probably, this is a quirk of Keil’s
optimization process. Nevertheless, the code works correctly.
Listing 47.7: Optimizing Keil 6/2013 (thumb mode)
str_trim PROC
PUSH {r4,lr}
MOVS r4,r0
; R4=s
BL strlen ; strlen() takes "s" value from R0
; R0=str_len
MOVS r3,#0
; R3 will always hold 0
B |L0.24|
|L0.12|
CMP r1,#0xd ; is loaded byte 'r'?
BEQ |L0.20|
CMP r1,#0xa ; is loaded byte 'n'?
BNE |L0.38| ; jump to exit, if no
|L0.20|
SUBS r0,r0,#1 ; R0-- or str_len--
STRB r3,[r2,#0x1f] ; store 0 at address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1
525
CHAPTER 47. STRINGS TRIMMING 47.8. MIPS
|L0.24|
CMP r0,#0 ; str_len==0?
BEQ |L0.38| ; yes? jump to exit
ADDS r2,r4,r0 ; R2=R4+R0=s+str_len
SUBS r2,r2,#0x20 ; R2=R2-0x20=s+str_len-0x20
LDRB r1,[r2,#0x1f] ; load byte at
address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1 to R1
CMP r1,#0 ; is loaded byte 0?
BNE |L0.12| ; jump to loop begin, if its not 0'
|L0.38|
; return "s"
MOVS r0,r4
POP {r4,pc}
ENDP
47.8 MIPS
Listing 47.8: Optimizing GCC 4.4.5 (IDA)
str_trim:
; IDA is not aware of local variable names, I gave them manually:
saved_GP = -0x10
saved_S0 = -8
saved_RA = -4
lui $gp, (__gnu_local_gp >> 16)
addiu $sp, -0x20
la $gp, (__gnu_local_gp & 0xFFFF)
sw $ra, 0x20+saved_RA($sp)
sw $s0, 0x20+saved_S0($sp)
sw $gp, 0x20+saved_GP($sp)
; call strlen(). input string address is still in $a0, strlen() will take it from there:
lw $t9, (strlen & 0xFFFF)($gp)
or $at, $zero ; load delay slot, NOP
jalr $t9
; input string address is still in $a0, put it to $s0:
move $s0, $a0 ; branch delay slot
; result of strlen() (i.e, length of string) is in $v0 now
; jump to exit if $v0==0 (i.e., if length of string is 0):
beqz $v0, exit
or $at, $zero ; branch delay slot, NOP
addiu $a1, $v0, -1
; $a1 = $v0-1 = str_len-1
addu $a1, $s0, $a1
; $a1 = input string address + $a1 = s+strlen-1
; load byte at address $a1:
lb $a0, 0($a1)
or $at, $zero ; load delay slot, NOP
; loaded byte is zero? jump to exit if its so':
beqz $a0, exit
or $at, $zero ; branch delay slot, NOP
addiu $v1, $v0, -2
; $v1 = str_len-2
addu $v1, $s0, $v1
; $v1 = $s0+$v1 = s+str_len-2
li $a2, 0xD
; skip loop body:
b loc_6C
li $a3, 0xA ; branch delay slot
loc_5C:
; load next byte from memory to $a0:
lb $a0, 0($v1)
move $a1, $v1
; $a1=s+str_len-2
; jump to exit if loaded byte is zero:
beqz $a0, exit
; decrement str_len:
addiu $v1, -1 ; branch delay slot
526
CHAPTER 47. STRINGS TRIMMING 47.8. MIPS
loc_6C:
; at this moment, $a0=loaded byte, $a2=0xD (CR symbol) and $a3=0xA (LF symbol)
; loaded byte is CR? jump to loc_7C then:
beq $a0, $a2, loc_7C
addiu $v0, -1 ; branch delay slot
; loaded byte is LF? jump to exit if its not LF':
bne $a0, $a3, exit
or $at, $zero ; branch delay slot, NOP
loc_7C:
; loaded byte is CR at this moment
; jump to loc_5c (loop body begin) if str_len (in $v0) is not zero:
bnez $v0, loc_5C
; simultaneously, store zero at that place in memory:
sb $zero, 0($a1) ; branch delay slot
; "exit" label was named by me manually:
exit:
lw $ra, 0x20+saved_RA($sp)
move $v0, $s0
lw $s0, 0x20+saved_S0($sp)
jr $ra
addiu $sp, 0x20 ; branch delay slot
Registers prefixed with S- are also called “saved temporaries”, so $S0 value is saved in the local stack and restored upon
finish.
527
CHAPTER 48. TOUPPER() FUNCTION
Chapter 48
toupper() function
Another very popular function transforms symbol from lower case to upper case, if needed:
char toupper (char c)
{
if(c>='a' && c<='z')
return c-'a'+'A';
else
return c;
}
'a'+'A' expression is left in source code for better readability, it is to be optimized by compiler, of course 1
.
The ASCII code of “a” symbol is 97 (or 0x61), and 65 (or 0x41) for “A” symbol. The difference (or distance) between them
in ASCII table is 32 (or 0x20).
For better understanding, reader may take a look at 7-bit standard ASCII table:
Figure 48.1: 7-bit ASCII table in Emacs
48.1 x64
48.1.1 Two comparison operations
Non-optimizing MSVC is straightforward: the code checks if input symbol is in [97..122] range (or in [‘a’..‘z’] range) and
subtracts 32 in this case. There are also minor compiler artefact:
Listing 48.1: Non-optimizing MSVC 2013 (x64)
1 c$ = 8
2 toupper PROC
3 mov BYTE PTR [rsp+8], cl
4 movsx eax, BYTE PTR c$[rsp]
5 cmp eax, 97
6 jl SHORT $LN2@toupper
7 movsx eax, BYTE PTR c$[rsp]
8 cmp eax, 122
9 jg SHORT $LN2@toupper
10 movsx eax, BYTE PTR c$[rsp]
11 sub eax, 32
12 jmp SHORT $LN3@toupper
1However, if to be meticulous, I think, there are still could be compilers which can’t optimize such expressions and leaving them right in the code.
528
CHAPTER 48. TOUPPER() FUNCTION 48.1. X64
13 jmp SHORT $LN1@toupper ; compiler artefact
14 $LN2@toupper:
15 movzx eax, BYTE PTR c$[rsp] ; unnecessary casting
16 $LN1@toupper:
17 $LN3@toupper: ; compiler artefact
18 ret 0
19 toupper ENDP
It’s important to notice that input byte is loaded into 64-bit local stack slot at line 3. All the rest bits ([8..63]) are
untouched, i.e., contains some random noise (you’ll see it in debugger). All instructions operates only on byte-level, so it’s
fine. The last MOVZX instruction at line 15 takes byte from local stack slot and zero-extends it into int 32-bit data type.
Non-optimizing GCC does mostly the same:
Listing 48.2: Non-optimizing GCC 4.9 (x64)
toupper:
push rbp
mov rbp, rsp
mov eax, edi
mov BYTE PTR [rbp-4], al
cmp BYTE PTR [rbp-4], 96
jle .L2
cmp BYTE PTR [rbp-4], 122
jg .L2
movzx eax, BYTE PTR [rbp-4]
sub eax, 32
jmp .L3
.L2:
movzx eax, BYTE PTR [rbp-4]
.L3:
pop rbp
ret
48.1.2 One comparison operation
Optimizing MSVC does its job better, it generates only one comparison operation:
Listing 48.3: Optimizing MSVC 2013 (x64)
toupper PROC
lea eax, DWORD PTR [rcx-97]
cmp al, 25
ja SHORT $LN2@toupper
movsx eax, cl
sub eax, 32
ret 0
$LN2@toupper:
movzx eax, cl
ret 0
toupper ENDP
It was explained earlier, how to replace two comparison operations by one : 42.2.1 on page 498.
I would rewrite this into C/C++:
int tmp=c-97;
if (tmp>25)
return c;
else
return c-32;
tmp variable should be signed. This makes two subtracting operations in case of transformation plus one comparison
operation. While original algorithm uses two comparison operations plus one subtracting operation.
Optimizing GCC is even better, it got rid of jumps (which is good: 33.1 on page 456) by using CMOVcc instruction:
Listing 48.4: Optimizing GCC 4.9 (x64)
1 toupper:
2 lea edx, [rdi-97] ; 0x61
3 lea eax, [rdi-32] ; 0x20
4 cmp dl, 25
529
CHAPTER 48. TOUPPER() FUNCTION 48.2. ARM
5 cmova eax, edi
6 ret
At line 3 the code prepares the subtracted value in advance, as if conversion will happen always. At line 5 subtracted
value in EAX is replaced by untouched input value if conversion is not needed. And then this value (of course incorrect) is
dropped. Advance subtracting is a price compiler paying for the absence of conditional jumps.
48.2 ARM
Optimizing Keil for ARM mode also generates only one comparison:
Listing 48.5: Optimizing Keil 6/2013 (ARM mode)
toupper PROC
SUB r1,r0,#0x61
CMP r1,#0x19
SUBLS r0,r0,#0x20
ANDLS r0,r0,#0xff
BX lr
ENDP
SUBLS and ANDLS instructions are executing only if R1 value is less than 0x19 (or equal). They do actual conversion.
Optimizing Keil for thumb mode generates only one comparison operation as well:
Listing 48.6: Optimizing Keil 6/2013 (thumb mode)
toupper PROC
MOVS r1,r0
SUBS r1,r1,#0x61
CMP r1,#0x19
BHI |L0.14|
SUBS r0,r0,#0x20
LSLS r0,r0,#24
LSRS r0,r0,#24
|L0.14|
BX lr
ENDP
Last two LSLS and LSRS instructions works like AND reg, 0xFF: they are analogous to C/C++-expression (i << 24) >> 24.
Apparently, Keil for thumb mode deduced that two 2-byte instructions is shorter then the code loading 0xFF constant into
register plus AND instruction.
48.2.1 GCC for ARM64
Listing 48.7: Non-optimizing GCC 4.9 (ARM64)
toupper:
sub sp, sp, #16
strb w0, [sp,15]
ldrb w0, [sp,15]
cmp w0, 96
bls .L2
ldrb w0, [sp,15]
cmp w0, 122
bhi .L2
ldrb w0, [sp,15]
sub w0, w0, #32
uxtb w0, w0
b .L3
.L2:
ldrb w0, [sp,15]
.L3:
add sp, sp, 16
ret
Listing 48.8: Optimizing GCC 4.9 (ARM64)
toupper:
uxtb w0, w0
530
CHAPTER 48. TOUPPER() FUNCTION 48.3. SUMMARY
sub w1, w0, #97
uxtb w1, w1
cmp w1, 25
bhi .L2
sub w0, w0, #32
uxtb w0, w0
.L2:
ret
48.3 Summary
All these compiler optimizations are very popular nowadays and practicing reverse engineer usually sees such code patterns
often.
531
CHAPTER 49. INCORRECTLY DISASSEMBLED CODE
Chapter 49
Incorrectly disassembled code
Practicing reverse engineers often have to deal with incorrectly disassembled code.
49.1 Disassembling from an incorrect start (x86)
Unlike ARM and MIPS (where any instruction has a length of 2 or 4 bytes), x86 instructions have variable size, so any
disassembler that starts in the middle of a x86 instruction may produce incorrect results.
As an example:
add [ebp-31F7Bh], cl
dec dword ptr [ecx-3277Bh]
dec dword ptr [ebp-2CF7Bh]
inc dword ptr [ebx-7A76F33Ch]
fdiv st(4), st
db 0FFh
dec dword ptr [ecx-21F7Bh]
dec dword ptr [ecx-22373h]
dec dword ptr [ecx-2276Bh]
dec dword ptr [ecx-22B63h]
dec dword ptr [ecx-22F4Bh]
dec dword ptr [ecx-23343h]
jmp dword ptr [esi-74h]
xchg eax, ebp
clc
std
db 0FFh
db 0FFh
mov word ptr [ebp-214h], cs ; <- disassembler finally found right track here
mov word ptr [ebp-238h], ds
mov word ptr [ebp-23Ch], es
mov word ptr [ebp-240h], fs
mov word ptr [ebp-244h], gs
pushf
pop dword ptr [ebp-210h]
mov eax, [ebp+4]
mov [ebp-218h], eax
lea eax, [ebp+4]
mov [ebp-20Ch], eax
mov dword ptr [ebp-2D0h], 10001h
mov eax, [eax-4]
mov [ebp-21Ch], eax
mov eax, [ebp+0Ch]
mov [ebp-320h], eax
mov eax, [ebp+10h]
mov [ebp-31Ch], eax
mov eax, [ebp+4]
mov [ebp-314h], eax
call ds:IsDebuggerPresent
mov edi, eax
lea eax, [ebp-328h]
push eax
call sub_407663
pop ecx
test eax, eax
532
CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED?
jnz short loc_402D7B
There are incorrectly disassembled instructions at the beginning, but eventually the disassembler gets on the right track.
49.2 How does random noise looks disassembled?
Common properties that can be spotted easily are:
• Unusually big instruction dispersion. The most frequent x86 instructions are PUSH, MOV, CALL, but here we see
instructions from all instruction groups: FPU instructions, IN/OUT instructions, rare and system instructions, everything
mixed up in one single place.
• Big and random values, offsets and immediates.
• Jumps having incorrect offsets, often jumping in the middle of another instructions.
Listing 49.1: random noise (x86)
mov bl, 0Ch
mov ecx, 0D38558Dh
mov eax, ds:2C869A86h
db 67h
mov dl, 0CCh
insb
movsb
push eax
xor [edx-53h], ah
fcom qword ptr [edi-45A0EF72h]
pop esp
pop ss
in eax, dx
dec ebx
push esp
lds esp, [esi-41h]
retf
rcl dword ptr [eax], cl
mov cl, 9Ch
mov ch, 0DFh
push cs
insb
mov esi, 0D9C65E4Dh
imul ebp, [ecx], 66h
pushf
sal dword ptr [ebp-64h], cl
sub eax, 0AC433D64h
out 8Ch, eax
pop ss
sbb [eax], ebx
aas
xchg cl, [ebx+ebx*4+14B31Eh]
jecxz short near ptr loc_58+1
xor al, 0C6h
inc edx
db 36h
pusha
stosb
test [ebx], ebx
sub al, 0D3h ; 'L'
pop eax
stosb
loc_58: ; CODE XREF: seg000:0000004A
test [esi], eax
inc ebp
das
db 64h
pop ecx
das
hlt
533
CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED?
pop edx
out 0B0h, al
lodsb
push ebx
cdq
out dx, al
sub al, 0Ah
sti
outsd
add dword ptr [edx], 96FCBE4Bh
and eax, 0E537EE4Fh
inc esp
stosd
cdq
push ecx
in al, 0CBh
mov ds:0D114C45Ch, al
mov esi, 659D1985h
Listing 49.2: random noise (x86-64)
lea esi, [rax+rdx*4+43558D29h]
loc_AF3: ; CODE XREF: seg000:0000000000000B46
rcl byte ptr [rsi+rax*8+29BB423Ah], 1
lea ecx, cs:0FFFFFFFFB2A6780Fh
mov al, 96h
mov ah, 0CEh
push rsp
lods byte ptr [esi]
db 2Fh ; /
pop rsp
db 64h
retf 0E993h
cmp ah, [rax+4Ah]
movzx rsi, dword ptr [rbp-25h]
push 4Ah
movzx rdi, dword ptr [rdi+rdx*8]
db 9Ah
rcr byte ptr [rax+1Dh], cl
lodsd
xor [rbp+6CF20173h], edx
xor [rbp+66F8B593h], edx
push rbx
sbb ch, [rbx-0Fh]
stosd
int 87h
db 46h, 4Ch
out 33h, rax
xchg eax, ebp
test ecx, ebp
movsd
leave
push rsp
db 16h
xchg eax, esi
pop rdi
loc_B3D: ; CODE XREF: seg000:0000000000000B5F
mov ds:93CA685DF98A90F9h, eax
jnz short near ptr loc_AF3+6
out dx, eax
534
CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED?
cwde
mov bh, 5Dh ; ']'
movsb
pop rbp
Listing 49.3: random noise (ARM (ARM mode))
BLNE 0xFE16A9D8
BGE 0x1634D0C
SVCCS 0x450685
STRNVT R5, [PC],#-0x964
LDCGE p6, c14, [R0],#0x168
STCCSL p9, c9, [LR],#0x14C
CMNHIP PC, R10,LSL#22
FLDMIADNV LR!, {D4}
MCR p5, 2, R2,c15,c6, 4
BLGE 0x1139558
BLGT 0xFF9146E4
STRNEB R5, [R4],#0xCA2
STMNEIB R5, {R0,R4,R6,R7,R9-SP,PC}
STMIA R8, {R0,R2-R4,R7,R8,R10,SP,LR}^
STRB SP, [R8],PC,ROR#18
LDCCS p9, c13, [R6,#0x1BC]
LDRGE R8, [R9,#0x66E]
STRNEB R5, [R8],#-0x8C3
STCCSL p15, c9, [R7,#-0x84]
RSBLS LR, R2, R11,ASR LR
SVCGT 0x9B0362
SVCGT 0xA73173
STMNEDB R11!, {R0,R1,R4-R6,R8,R10,R11,SP}
STR R0, [R3],#-0xCE4
LDCGT p15, c8, [R1,#0x2CC]
LDRCCB R1, [R11],-R7,ROR#30
BLLT 0xFED9D58C
BL 0x13E60F4
LDMVSIB R3!, {R1,R4-R7}^
USATNE R10, #7, SP,LSL#11
LDRGEB LR, [R1],#0xE56
STRPLT R9, [LR],#0x567
LDRLT R11, [R1],#-0x29B
SVCNV 0x12DB29
MVNNVS R5, SP,LSL#25
LDCL p8, c14, [R12,#-0x288]
STCNEL p2, c6, [R6,#-0xBC]!
SVCNV 0x2E5A2F
BLX 0x1A8C97E
TEQGE R3, #0x1100000
STMLSIA R6, {R3,R6,R10,R11,SP}
BICPLS R12, R2, #0x5800
BNE 0x7CC408
TEQGE R2, R4,LSL#20
SUBS R1, R11, #0x28C
BICVS R3, R12, R7,ASR R0
LDRMI R7, [LR],R3,LSL#21
BLMI 0x1A79234
STMVCDB R6, {R0-R3,R6,R7,R10,R11}
EORMI R12, R6, #0xC5
MCRRCS p1, 0xF, R1,R3,c2
Listing 49.4: random noise (ARM (thumb mode))
LSRS R3, R6, #0x12
LDRH R1, [R7,#0x2C]
SUBS R0, #0x55 ; 'U'
ADR R1, loc_3C
LDR R2, [SP,#0x218]
CMP R4, #0x86
SXTB R7, R4
LDR R4, [R1,#0x4C]
STR R4, [R4,R2]
535
CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED?
STR R0, [R6,#0x20]
BGT 0xFFFFFF72
LDRH R7, [R2,#0x34]
LDRSH R0, [R2,R4]
LDRB R2, [R7,R2]
DCB 0x17
DCB 0xED
STRB R3, [R1,R1]
STR R5, [R0,#0x6C]
LDMIA R3, {R0-R5,R7}
ASRS R3, R2, #3
LDR R4, [SP,#0x2C4]
SVC 0xB5
LDR R6, [R1,#0x40]
LDR R5, =0xB2C5CA32
STMIA R6, {R1-R4,R6}
LDR R1, [R3,#0x3C]
STR R1, [R5,#0x60]
BCC 0xFFFFFF70
LDR R4, [SP,#0x1D4]
STR R5, [R5,#0x40]
ORRS R5, R7
loc_3C ; DATA XREF: ROM:00000006
B 0xFFFFFF98
Listing 49.5: random noise (MIPS little endian)
lw $t9, 0xCB3($t5)
sb $t5, 0x3855($t0)
sltiu $a2, $a0, -0x657A
ldr $t4, -0x4D99($a2)
daddi $s0, $s1, 0x50A4
lw $s7, -0x2353($s4)
bgtzl $a1, 0x17C5C
.byte 0x17
.byte 0xED
.byte 0x4B # K
.byte 0x54 # T
lwc2 $31, 0x66C5($sp)
lwu $s1, 0x10D3($a1)
ldr $t6, -0x204B($zero)
lwc1 $f30, 0x4DBE($s2)
daddiu $t1, $s1, 0x6BD9
lwu $s5, -0x2C64($v1)
cop0 0x13D642D
bne $gp, $t4, 0xFFFF9EF0
lh $ra, 0x1819($s1)
sdl $fp, -0x6474($t8)
jal 0x78C0050
ori $v0, $s2, 0xC634
blez $gp, 0xFFFEA9D4
swl $t8, -0x2CD4($s2)
sltiu $a1, $k0, 0x685
sdc1 $f15, 0x5964($at)
sw $s0, -0x19A6($a1)
sltiu $t6, $a3, -0x66AD
lb $t7, -0x4F6($t3)
sd $fp, 0x4B02($a1)
It is also important to keep in mind that cleverly constructed unpacking and decryption code (including self-modifying)
may looks like noise as well, but still execute correctly.
536
CHAPTER 50. OBFUSCATION
Chapter 50
Obfuscation
The obfuscation is an attempt to hide the code (or its meaning) from reverse engineers.
50.1 Text strings
As I explained in ( 57 on page 646) , text strings may be really helpful. Programmers who are aware of this try to hide them,
making it impossible to find the string in IDA or any hex editor.
Here is the simplest method.
This is how the string can be constructed:
mov byte ptr [ebx], 'h'
mov byte ptr [ebx+1], 'e'
mov byte ptr [ebx+2], 'l'
mov byte ptr [ebx+3], 'l'
mov byte ptr [ebx+4], 'o'
mov byte ptr [ebx+5], ' '
mov byte ptr [ebx+6], 'w'
mov byte ptr [ebx+7], 'o'
mov byte ptr [ebx+8], 'r'
mov byte ptr [ebx+9], 'l'
mov byte ptr [ebx+10], 'd'
The string is also can be compared with another one like this:
mov ebx, offset username
cmp byte ptr [ebx], 'j'
jnz fail
cmp byte ptr [ebx+1], 'o'
jnz fail
cmp byte ptr [ebx+2], 'h'
jnz fail
cmp byte ptr [ebx+3], 'n'
jnz fail
jz it_is_john
In both cases, it is impossible to find these strings straightforwardly in a hex editor.
By the way, this is a way to work with the strings when it is impossible to allocate space for them in the data segment,
for example in a PIC or in shellcode.
Another method I once saw is to use sprintf() for the construction:
sprintf(buf, "%s%c%s%c%s", "hel",'l',"o w",'o',"rld");
The code looks weird, but as a simple anti-reversing measure, it may be helpful.
Text strings may also be present in encrypted form, then every string usage is to be preceded by a string decrypting
routine. For example: 78.2 on page 750.
50.2 Executable code
50.2.1 Inserting garbage
Executable code obfuscation implies inserting random garbage code between real one, which executes but does nothing
useful.
A simple example:
537
CHAPTER 50. OBFUSCATION 50.2. EXECUTABLE CODE
Listing 50.1: original code
add eax, ebx
mul ecx
Listing 50.2: obfuscated code
xor esi, 011223344h ; garbage
add esi, eax ; garbage
add eax, ebx
mov edx, eax ; garbage
shl edx, 4 ; garbage
mul ecx
xor esi, ecx ; garbage
Here the garbage code uses registers which are not used in the real code (ESI and EDX). However, the intermediate
results produced by the real code may be used by the garbage instructions for some extra mess—why not?
50.2.2 Replacing instructions with bloated equivalents
• MOV op1, op2 can be replaced by the PUSH op2 / POP op1 pair.
• JMP label can be replaced by the PUSH label / RET pair. IDA will not show the references to the label.
• CALL label can be replaced by the PUSH label_after_CALL_instruction / PUSH label / RET triplet.
• PUSH op can also be replaced with the SUB ESP, 4 (or 8) / MOV [ESP], op pair.
50.2.3 Always executed/never executed code
If the developer is sure that ESI at always 0 at that point:
mov esi, 1
... ; some code not touching ESI
dec esi
... ; some code not touching ESI
cmp esi, 0
jz real_code
; fake luggage
real_code:
The reverse engineer needs some time to get into it.
This is also called an opaque predicate.
Another example ( and again, the developer is sure that ESI is always zero):
add eax, ebx ; real code
mul ecx ; real code
add eax, esi ; opaque predicate. XOR, AND or SHL, etc, can be here instead of ADD.
50.2.4 Making a lot of mess
instruction 1
instruction 2
instruction 3
Can be replaced with:
begin: jmp ins1_label
ins2_label: instruction 2
jmp ins3_label
ins3_label: instruction 3
jmp exit:
ins1_label: instruction 1
jmp ins2_label
exit:
538
CHAPTER 50. OBFUSCATION 50.3. VIRTUAL MACHINE / PSEUDO-CODE
50.2.5 Using indirect pointers
dummy_data1 db 100h dup (0)
message1 db 'hello world',0
dummy_data2 db 200h dup (0)
message2 db 'another message',0
func proc
...
mov eax, offset dummy_data1 ; PE or ELF reloc here
add eax, 100h
push eax
call dump_string
...
mov eax, offset dummy_data2 ; PE or ELF reloc here
add eax, 200h
push eax
call dump_string
...
func endp
IDA will show references only to dummy_data1 and dummy_data2, but not to the text strings.
Global variables and even functions may be accessed like that.
50.3 Virtual machine / pseudo-code
A programmer can construct his/her own PL or ISA and interpreter for it. (Like the pre-5.0 Visual Basic, .NET or Java machines).
The reverse engineer will have to spend some time to understand the meaning and details of all of the ISA’s instructions.
Probably, he/she will also have to write a disassembler/decompiler of some sort.
50.4 Other things to mention
My own (yet weak) attempt to patch the Tiny C compiler to produce obfuscated code: http://go.yurichev.com/17220.
Using the MOV instruction for really complicated things: [Dol13].
50.5 Exercises
50.5.1 Exercise #1
This is a very short program, compiled using the patched Tiny C compiler 1
. Try to find out what it does.
beginners.re.
Answer: G.1.13 on page 959.
1blog.yurichev.com
539
CHAPTER 51. C++
Chapter 51
C++
51.1 Classes
51.1.1 A simple example
Internally, the representation of C++ classes is almost the same as the structures.
Let’s try an example with two variables, two constructors and one method:
#include <stdio.h>
class c
{
private:
int v1;
int v2;
public:
c() // default ctor
{
v1=667;
v2=999;
};
c(int a, int b) // ctor
{
v1=a;
v2=b;
};
void dump()
{
printf ("%d; %dn", v1, v2);
};
};
int main()
{
class c c1;
class c c2(5,6);
c1.dump();
c2.dump();
return 0;
};
MSVC—x86
Here is how the main() function looks like, translated into assembly language:
Listing 51.1: MSVC
_c2$ = -16 ; size = 8
_c1$ = -8 ; size = 8
_main PROC
540
CHAPTER 51. C++ 51.1. CLASSES
push ebp
mov ebp, esp
sub esp, 16
lea ecx, DWORD PTR _c1$[ebp]
call ??0c@@QAE@XZ ; c::c
push 6
push 5
lea ecx, DWORD PTR _c2$[ebp]
call ??0c@@QAE@HH@Z ; c::c
lea ecx, DWORD PTR _c1$[ebp]
call ?dump@c@@QAEXXZ ; c::dump
lea ecx, DWORD PTR _c2$[ebp]
call ?dump@c@@QAEXXZ ; c::dump
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
Here’s what’s going on. For each object (instance of class c) 8 bytes are allocated, exactly the size needed to store the 2
variables.
For c1 a default argumentless constructor ??0c@@QAE@XZ is called. For c2 another constructor ??0c@@QAE@HH@Z is
called and two numbers are passed as arguments.
A pointer to the object (this in C++ terminology) is passed in the ECX register. This is called thiscall ( 51.1.1 on page 541) —
the method for passing a pointer to the object.
MSVC does it using the ECX register. Needless to say, it is not a standardized method, other compilers can do it differently,
e.g., via the first function argument (like GCC).
Why do these functions have such odd names? That’s name mangling.
A C++ class may contain several methods sharing the same name but having different arguments —that is polymorphism.
And of course, different classes may have their own methods with the same name.
Name mangling enable us to encode the class name + method name + all method argument types in one ASCII string,
which is then used as an internal function name. That’s all because neither the linker, nor the DLL OS loader (mangled names
may be among the DLL exports as well) knows anything about C++ or OOP1
.
The dump() function is called two times.
Now let’s see the constructors’ code:
Listing 51.2: MSVC
_this$ = -4 ; size = 4
??0c@@QAE@XZ PROC ; c::c, COMDAT
; _this$ = ecx
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _this$[ebp], ecx
mov eax, DWORD PTR _this$[ebp]
mov DWORD PTR [eax], 667
mov ecx, DWORD PTR _this$[ebp]
mov DWORD PTR [ecx+4], 999
mov eax, DWORD PTR _this$[ebp]
mov esp, ebp
pop ebp
ret 0
??0c@@QAE@XZ ENDP ; c::c
_this$ = -4 ; size = 4
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
??0c@@QAE@HH@Z PROC ; c::c, COMDAT
; _this$ = ecx
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _this$[ebp], ecx
mov eax, DWORD PTR _this$[ebp]
mov ecx, DWORD PTR _a$[ebp]
mov DWORD PTR [eax], ecx
mov edx, DWORD PTR _this$[ebp]
1Object-Oriented Programming
541
CHAPTER 51. C++ 51.1. CLASSES
mov eax, DWORD PTR _b$[ebp]
mov DWORD PTR [edx+4], eax
mov eax, DWORD PTR _this$[ebp]
mov esp, ebp
pop ebp
ret 8
??0c@@QAE@HH@Z ENDP ; c::c
The constructors are just functions, they use a pointer to the structure in ECX, copying the pointer into their own local
variable, however, it is not necessary.
From the C++ standard [ISO13, p. 12.1] we know that constructors are not required to return any values. In fact, internally,
the constructors return a pointer to the newly created object, i.e., this.
Now the dump() method:
Listing 51.3: MSVC
_this$ = -4 ; size = 4
?dump@c@@QAEXXZ PROC ; c::dump, COMDAT
; _this$ = ecx
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _this$[ebp], ecx
mov eax, DWORD PTR _this$[ebp]
mov ecx, DWORD PTR [eax+4]
push ecx
mov edx, DWORD PTR _this$[ebp]
mov eax, DWORD PTR [edx]
push eax
push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@
call _printf
add esp, 12
mov esp, ebp
pop ebp
ret 0
?dump@c@@QAEXXZ ENDP ; c::dump
Simple enough: dump() takes a pointer to the structure that contains the two int’s from ECX, takes both values from it
and passes them to printf().
The code is much shorter if compiled with optimizations (/Ox):
Listing 51.4: MSVC
??0c@@QAE@XZ PROC ; c::c, COMDAT
; _this$ = ecx
mov eax, ecx
mov DWORD PTR [eax], 667
mov DWORD PTR [eax+4], 999
ret 0
??0c@@QAE@XZ ENDP ; c::c
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
??0c@@QAE@HH@Z PROC ; c::c, COMDAT
; _this$ = ecx
mov edx, DWORD PTR _b$[esp-4]
mov eax, ecx
mov ecx, DWORD PTR _a$[esp-4]
mov DWORD PTR [eax], ecx
mov DWORD PTR [eax+4], edx
ret 8
??0c@@QAE@HH@Z ENDP ; c::c
?dump@c@@QAEXXZ PROC ; c::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push eax
push ecx
push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@
call _printf
542
CHAPTER 51. C++ 51.1. CLASSES
add esp, 12
ret 0
?dump@c@@QAEXXZ ENDP ; c::dump
That’s all. The other thing we need to note is that the stack pointer was not corrected with add esp, X after the
constructor was called. At the same time, the constructor has ret 8 instead of RET at the end.
This is all because the thiscall ( 51.1.1 on page 541) calling convention is used here, which together with the stdcall ( 64.2
on page 663) method offers the callee to correct the stack instead of the caller. The ret x instruction adds X to the value
in ESP, then passes the control to the caller function.
See also the section about calling conventions ( 64 on page 663).
It also has to be noted that the compiler decides when to call the constructor and destructor —but we already know that
from the C++ language basics.
MSVC—x86-64
As we already know, the first 4 function arguments in x86-64 are passed in RCX, RDX, R8 and R9 registers, all the rest—via
the stack. Nevertheless, the this pointer to the object is passed in RCX, the first argument of the method in RDX, etc. We
can see this in the c(int a, int b) method internals:
Listing 51.5: Optimizing MSVC 2012 x64
; void dump()
?dump@c@@QEAAXXZ PROC ; c::dump
mov r8d, DWORD PTR [rcx+4]
mov edx, DWORD PTR [rcx]
lea rcx, OFFSET FLAT:??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ ; '%d; %d'
jmp printf
?dump@c@@QEAAXXZ ENDP ; c::dump
; c(int a, int b)
??0c@@QEAA@HH@Z PROC ; c::c
mov DWORD PTR [rcx], edx ; 1st argument: a
mov DWORD PTR [rcx+4], r8d ; 2nd argument: b
mov rax, rcx
ret 0
??0c@@QEAA@HH@Z ENDP ; c::c
; default ctor
??0c@@QEAA@XZ PROC ; c::c
mov DWORD PTR [rcx], 667
mov DWORD PTR [rcx+4], 999
mov rax, rcx
ret 0
??0c@@QEAA@XZ ENDP ; c::c
The int data type is still 32-bit in x64 2
, so that is why 32-bit register parts are used here.
We also see JMP printf instead of RET in the dump() method, that hack we already saw earlier: 13.1.1 on page 140.
GCC—x86
It is almost the same story in GCC 4.4.1, with a few exceptions.
Listing 51.6: GCC 4.4.1
public main
main proc near
var_20 = dword ptr -20h
var_1C = dword ptr -1Ch
var_18 = dword ptr -18h
var_10 = dword ptr -10h
var_8 = dword ptr -8
push ebp
mov ebp, esp
2Apparently, for easier porting of 32-bit C/C++ code to x64
543
CHAPTER 51. C++ 51.1. CLASSES
and esp, 0FFFFFFF0h
sub esp, 20h
lea eax, [esp+20h+var_8]
mov [esp+20h+var_20], eax
call _ZN1cC1Ev
mov [esp+20h+var_18], 6
mov [esp+20h+var_1C], 5
lea eax, [esp+20h+var_10]
mov [esp+20h+var_20], eax
call _ZN1cC1Eii
lea eax, [esp+20h+var_8]
mov [esp+20h+var_20], eax
call _ZN1c4dumpEv
lea eax, [esp+20h+var_10]
mov [esp+20h+var_20], eax
call _ZN1c4dumpEv
mov eax, 0
leave
retn
main endp
Here we see another name mangling style, specific to GNU 3
It can also be noted that the pointer to the object is passed
as the first function argument —invisible to programmer, of course.
First constructor:
public _ZN1cC1Ev ; weak
_ZN1cC1Ev proc near ; CODE XREF: main+10
arg_0 = dword ptr 8
push ebp
mov ebp, esp
mov eax, [ebp+arg_0]
mov dword ptr [eax], 667
mov eax, [ebp+arg_0]
mov dword ptr [eax+4], 999
pop ebp
retn
_ZN1cC1Ev endp
It just writes two numbers using the pointer passed in the first (and only) argument.
Second constructor:
public _ZN1cC1Eii
_ZN1cC1Eii proc near
arg_0 = dword ptr 8
arg_4 = dword ptr 0Ch
arg_8 = dword ptr 10h
push ebp
mov ebp, esp
mov eax, [ebp+arg_0]
mov edx, [ebp+arg_4]
mov [eax], edx
mov eax, [ebp+arg_0]
mov edx, [ebp+arg_8]
mov [eax+4], edx
pop ebp
retn
_ZN1cC1Eii endp
This is a function, the analog of which can look like this:
void ZN1cC1Eii (int *obj, int a, int b)
{
*obj=a;
*(obj+1)=b;
};
3There is a good document about the various name mangling conventions in different compilers: [Fog14].
544
CHAPTER 51. C++ 51.1. CLASSES
…and that is completely predictable.
Now the dump() function:
public _ZN1c4dumpEv
_ZN1c4dumpEv proc near
var_18 = dword ptr -18h
var_14 = dword ptr -14h
var_10 = dword ptr -10h
arg_0 = dword ptr 8
push ebp
mov ebp, esp
sub esp, 18h
mov eax, [ebp+arg_0]
mov edx, [eax+4]
mov eax, [ebp+arg_0]
mov eax, [eax]
mov [esp+18h+var_10], edx
mov [esp+18h+var_14], eax
mov [esp+18h+var_18], offset aDD ; "%d; %dn"
call _printf
leave
retn
_ZN1c4dumpEv endp
This function in its internal representation has only one argument, used as pointer to the object (this).
This function could be rewritten in C like this:
void ZN1c4dumpEv (int *obj)
{
printf ("%d; %dn", *obj, *(obj+1));
};
Thus, if we base our judgment on these simple examples, the difference between MSVC and GCC is the style of the
encoding of function names (name mangling) and the method for passing a pointer to the object (via the ECX register or via
the first argument).
GCC—x86-64
The first 6 arguments, as we already know, are passed in the RDI, RSI, RDX, RCX, R8 and R9 [Mit13] registers, and the
pointer to this via the first one (RDI) and that is what we see here. The int data type is also 32-bit here. The JMP instead
of RET hack is also used here.
Listing 51.7: GCC 4.4.6 x64
; default ctor
_ZN1cC2Ev:
mov DWORD PTR [rdi], 667
mov DWORD PTR [rdi+4], 999
ret
; c(int a, int b)
_ZN1cC2Eii:
mov DWORD PTR [rdi], esi
mov DWORD PTR [rdi+4], edx
ret
; dump()
_ZN1c4dumpEv:
mov edx, DWORD PTR [rdi+4]
mov esi, DWORD PTR [rdi]
xor eax, eax
mov edi, OFFSET FLAT:.LC0 ; "%d; %dn"
jmp printf
545
CHAPTER 51. C++ 51.1. CLASSES
51.1.2 Class inheritance
Inherited classes are similar to the simple structures we already discussed, but extended in inheritable classes.
Let’s take this simple example:
#include <stdio.h>
class object
{
public:
int color;
object() { };
object (int color) { this->color=color; };
void print_color() { printf ("color=%dn", color); };
};
class box : public object
{
private:
int width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color=color;
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
{
printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦
height, depth);
};
};
class sphere : public object
{
private:
int radius;
public:
sphere(int color, int radius)
{
this->color=color;
this->radius=radius;
};
void dump()
{
printf ("this is sphere. color=%d, radius=%dn", color, radius);
};
};
int main()
{
box b(1, 10, 20, 30);
sphere s(2, 40);
b.print_color();
s.print_color();
b.dump();
s.dump();
return 0;
};
Let’s investigate the generated code of the dump() functions/methods and also object::print_color(), and see
the memory layout for the structures-objects (for 32-bit code).
So, here are the dump() methods for several classes, generated by MSVC 2008 with /Ox and /Ob0 options 4
4The /Ob0 option stands for disabling inline expansion since function inlining can make our experiment harder
546
CHAPTER 51. C++ 51.1. CLASSES
Listing 51.8: Optimizing MSVC 2008 /Ob0
??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@ DB 'color=%d', 0aH, 00H ; `string'
?print_color@object@@QAEXXZ PROC ; object::print_color, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx]
push eax
; 'color=%d', 0aH, 00H
push OFFSET ??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@
call _printf
add esp, 8
ret 0
?print_color@object@@QAEXXZ ENDP ; object::print_color
Listing 51.9: Optimizing MSVC 2008 /Ob0
?dump@box@@QAEXXZ PROC ; box::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+12]
mov edx, DWORD PTR [ecx+8]
push eax
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push edx
push eax
push ecx
; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H ; `string'
push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@
call _printf
add esp, 20
ret 0
?dump@box@@QAEXXZ ENDP ; box::dump
Listing 51.10: Optimizing MSVC 2008 /Ob0
?dump@sphere@@QAEXXZ PROC ; sphere::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push eax
push ecx
; 'this is sphere. color=%d, radius=%d', 0aH, 00H
push OFFSET ??_C@_0CF@EFEDJLDC@this?5is?5sphere?4?5color?$DN?$CFd?0?5radius@
call _printf
add esp, 12
ret 0
?dump@sphere@@QAEXXZ ENDP ; sphere::dump
So, here is the memory layout:
(base class object)
offset description
+0x0 int color
(inherited classes)
box:
offset description
+0x0 int color
+0x4 int width
+0x8 int height
+0xC int depth
sphere:
offset description
+0x0 int color
+0x4 int radius
547
CHAPTER 51. C++ 51.1. CLASSES
Let’s see main() function body:
Listing 51.11: Optimizing MSVC 2008 /Ob0
PUBLIC _main
_TEXT SEGMENT
_s$ = -24 ; size = 8
_b$ = -16 ; size = 16
_main PROC
sub esp, 24
push 30
push 20
push 10
push 1
lea ecx, DWORD PTR _b$[esp+40]
call ??0box@@QAE@HHHH@Z ; box::box
push 40
push 2
lea ecx, DWORD PTR _s$[esp+32]
call ??0sphere@@QAE@HH@Z ; sphere::sphere
lea ecx, DWORD PTR _b$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _s$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _b$[esp+24]
call ?dump@box@@QAEXXZ ; box::dump
lea ecx, DWORD PTR _s$[esp+24]
call ?dump@sphere@@QAEXXZ ; sphere::dump
xor eax, eax
add esp, 24
ret 0
_main ENDP
The inherited classes must always add their fields after the base classes’ fields, to make it possible for the base class
methods to work with their own fields.
When the object::print_color() method is called, a pointers to both the box and sphere objects are passed as
this, and it can work with these objects easily since the color field in these objects is always at the pinned address (at offset
+0x0).
It can be said that the object::print_color() method is agnostic in relation to the input object type as long as
the fields are pinned at the same addresses, and this condition is always true.
And if you create inherited class of the box class, the compiler will add the new fields after the depth field, leaving the
box class fields at the pinned addresses.
Thus, the box::dump() method will work fine for accessing the color/width/height/depths fields, which are always
pinned at known addresses.
The code generated by GCC is almost the same, with the sole exception of passing the this pointer (as it was explained
above, it is passed as the first argument instead of using the ECX register.
51.1.3 Encapsulation
Encapsulation is hiding the data in the private sections of the class, e.g. to allow access to them only from this class methods.
However, are there any marks in code the about the fact that some field is private and some other —not?
No, there are no such marks.
Let’s try this simple example:
#include <stdio.h>
class box
{
private:
int color, width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color=color;
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
548
CHAPTER 51. C++ 51.1. CLASSES
{
printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦
height, depth);
};
};
Let’s compile it again in MSVC 2008 with /Ox and /Ob0 options and see the box::dump() method code:
?dump@box@@QAEXXZ PROC ; box::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+12]
mov edx, DWORD PTR [ecx+8]
push eax
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push edx
push eax
push ecx
; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H
push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@
call _printf
add esp, 20
ret 0
?dump@box@@QAEXXZ ENDP ; box::dump
Here is a memory layout of the class:
offset description
+0x0 int color
+0x4 int width
+0x8 int height
+0xC int depth
All fields are private and not allowed to be accessed from any other function, but knowing this layout, can we create code
that modifies these fields?
To do this I’ve added the hack_oop_encapsulation() function, which is not going to compile if it looked like this:
void hack_oop_encapsulation(class box * o)
{
o->width=1; // that code cant be compiled':
// "error C2248: 'box::width' : cannot access private member declared in class ⤦
'box'"
};
Nevertheless, if we cast the box type to a pointer to an int array, and we modify the array of int-s that we have, we can
succeed.
void hack_oop_encapsulation(class box * o)
{
unsigned int *ptr_to_object=reinterpret_cast<unsigned int*>(o);
ptr_to_object[1]=123;
};
This function’s code is very simple —it can be said that the function takes a pointer to an array of int-s for input and writes
123 to the second int:
?hack_oop_encapsulation@@YAXPAVbox@@@Z PROC ; hack_oop_encapsulation
mov eax, DWORD PTR _o$[esp-4]
mov DWORD PTR [eax+4], 123
ret 0
?hack_oop_encapsulation@@YAXPAVbox@@@Z ENDP ; hack_oop_encapsulation
Let’s check how it works:
int main()
{
box b(1, 10, 20, 30);
b.dump();
hack_oop_encapsulation(&b);
549
CHAPTER 51. C++ 51.1. CLASSES
b.dump();
return 0;
};
Let’s run:
this is box. color=1, width=10, height=20, depth=30
this is box. color=1, width=123, height=20, depth=30
We see that the encapsulation is just protection of class fields only in the compilation stage. The C++ compiler is not
allowing the generation of code that modifies protected fields straightforwardly, nevertheless, it is possible with the help of
dirty hacks.
51.1.4 Multiple inheritance
Multiple inheritance is creating a class which inherits fields and methods from two or more classes.
Let’s write a simple example again:
#include <stdio.h>
class box
{
public:
int width, height, depth;
box() { };
box(int width, int height, int depth)
{
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
{
printf ("this is box. width=%d, height=%d, depth=%dn", width, height, depth);
};
int get_volume()
{
return width * height * depth;
};
};
class solid_object
{
public:
int density;
solid_object() { };
solid_object(int density)
{
this->density=density;
};
int get_density()
{
return density;
};
void dump()
{
printf ("this is solid_object. density=%dn", density);
};
};
class solid_box: box, solid_object
{
public:
solid_box (int width, int height, int depth, int density)
{
this->width=width;
this->height=height;
this->depth=depth;
this->density=density;
550
CHAPTER 51. C++ 51.1. CLASSES
};
void dump()
{
printf ("this is solid_box. width=%d, height=%d, depth=%d, density=%dn", width, ⤦
height, depth, density);
};
int get_weight() { return get_volume() * get_density(); };
};
int main()
{
box b(10, 20, 30);
solid_object so(100);
solid_box sb(10, 20, 30, 3);
b.dump();
so.dump();
sb.dump();
printf ("%dn", sb.get_weight());
return 0;
};
Let’s compile it in MSVC 2008 with the /Ox and /Ob0 options and see the code of box::dump(), solid_object::dump()
and solid_box::dump():
Listing 51.12: Optimizing MSVC 2008 /Ob0
?dump@box@@QAEXXZ PROC ; box::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+8]
mov edx, DWORD PTR [ecx+4]
push eax
mov eax, DWORD PTR [ecx]
push edx
push eax
; 'this is box. width=%d, height=%d, depth=%d', 0aH, 00H
push OFFSET ??_C@_0CM@DIKPHDFI@this?5is?5box?4?5width?$DN?$CFd?0?5height?$DN?$CFd@
call _printf
add esp, 16
ret 0
?dump@box@@QAEXXZ ENDP ; box::dump
Listing 51.13: Optimizing MSVC 2008 /Ob0
?dump@solid_object@@QAEXXZ PROC ; solid_object::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx]
push eax
; 'this is solid_object. density=%d', 0aH
push OFFSET ??_C@_0CC@KICFJINL@this?5is?5solid_object?4?5density?$DN?$CFd@
call _printf
add esp, 8
ret 0
?dump@solid_object@@QAEXXZ ENDP ; solid_object::dump
Listing 51.14: Optimizing MSVC 2008 /Ob0
?dump@solid_box@@QAEXXZ PROC ; solid_box::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+12]
mov edx, DWORD PTR [ecx+8]
push eax
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push edx
push eax
push ecx
; 'this is solid_box. width=%d, height=%d, depth=%d, density=%d', 0aH
push OFFSET ??_C@_0DO@HNCNIHNN@this?5is?5solid_box?4?5width?$DN?$CFd?0?5hei@
call _printf
551
CHAPTER 51. C++ 51.1. CLASSES
add esp, 20
ret 0
?dump@solid_box@@QAEXXZ ENDP ; solid_box::dump
So, the memory layout for all three classes is:
box class:
offset description
+0x0 width
+0x4 height
+0x8 depth
solid_object class:
offset description
+0x0 density
It can be said that the solid_box class memory layout is united:
solid_box class:
offset description
+0x0 width
+0x4 height
+0x8 depth
+0xC density
The code of the box::get_volume() and solid_object::get_density() methods is trivial:
Listing 51.15: Optimizing MSVC 2008 /Ob0
?get_volume@box@@QAEHXZ PROC ; box::get_volume, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+8]
imul eax, DWORD PTR [ecx+4]
imul eax, DWORD PTR [ecx]
ret 0
?get_volume@box@@QAEHXZ ENDP ; box::get_volume
Listing 51.16: Optimizing MSVC 2008 /Ob0
?get_density@solid_object@@QAEHXZ PROC ; solid_object::get_density, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx]
ret 0
?get_density@solid_object@@QAEHXZ ENDP ; solid_object::get_density
But the code of the solid_box::get_weight() method is much more interesting:
Listing 51.17: Optimizing MSVC 2008 /Ob0
?get_weight@solid_box@@QAEHXZ PROC ; solid_box::get_weight, COMDAT
; _this$ = ecx
push esi
mov esi, ecx
push edi
lea ecx, DWORD PTR [esi+12]
call ?get_density@solid_object@@QAEHXZ ; solid_object::get_density
mov ecx, esi
mov edi, eax
call ?get_volume@box@@QAEHXZ ; box::get_volume
imul eax, edi
pop edi
pop esi
ret 0
?get_weight@solid_box@@QAEHXZ ENDP ; solid_box::get_weight
get_weight() just calls two methods, but for get_volume() it just passes pointer to this, and for get_density()
it passes a pointer to this incremented by 12 (or 0xC) bytes, and there, in the solid_box class memory layout, the fields
of the solid_object class start.
Thus, the solid_object::get_density() method will believe like it is dealing with the usual solid_object
class, and the box::get_volume() method will work with its three fields, believing this is just the usual object of class
box.
Thus, we can say, an object of a class, that inherits from several other classes, is representing in memory as a united class,
that contains all inherited fields. And each inherited method is called with a pointer to the corresponding structure’s part.
552
CHAPTER 51. C++ 51.1. CLASSES
51.1.5 Virtual methods
Yet another simple example:
#include <stdio.h>
class object
{
public:
int color;
object() { };
object (int color) { this->color=color; };
virtual void dump()
{
printf ("color=%dn", color);
};
};
class box : public object
{
private:
int width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color=color;
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
{
printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦
height, depth);
};
};
class sphere : public object
{
private:
int radius;
public:
sphere(int color, int radius)
{
this->color=color;
this->radius=radius;
};
void dump()
{
printf ("this is sphere. color=%d, radius=%dn", color, radius);
};
};
int main()
{
box b(1, 10, 20, 30);
sphere s(2, 40);
object *o1=&b;
object *o2=&s;
o1->dump();
o2->dump();
return 0;
};
Class object has a virtual method dump() that is being replaced in the inheriting box and sphere classes.
If we are in an environment where it is not known the type of an object, as in the main() function in example, where the
virtual method dump() is called, the information about its type must be stored somewhere, to be able to call the relevant
virtual method.
553
CHAPTER 51. C++ 51.1. CLASSES
Let’s compile it in MSVC 2008 with the /Ox and /Ob0 options and see the code of main():
_s$ = -32 ; size = 12
_b$ = -20 ; size = 20
_main PROC
sub esp, 32
push 30
push 20
push 10
push 1
lea ecx, DWORD PTR _b$[esp+48]
call ??0box@@QAE@HHHH@Z ; box::box
push 40
push 2
lea ecx, DWORD PTR _s$[esp+40]
call ??0sphere@@QAE@HH@Z ; sphere::sphere
mov eax, DWORD PTR _b$[esp+32]
mov edx, DWORD PTR [eax]
lea ecx, DWORD PTR _b$[esp+32]
call edx
mov eax, DWORD PTR _s$[esp+32]
mov edx, DWORD PTR [eax]
lea ecx, DWORD PTR _s$[esp+32]
call edx
xor eax, eax
add esp, 32
ret 0
_main ENDP
A pointer to the dump() function is taken somewhere from the object. Where could we store the address of the new
method? Only somewhere in the constructors: there is no other place since nothing else is called in the main() function. 5
Let’s see the code of the constructor of the box class:
??_R0?AVbox@@@8 DD FLAT:??_7type_info@@6B@ ; box `RTTI Type Descriptor'
DD 00H
DB '.?AVbox@@', 00H
??_R1A@?0A@EA@box@@8 DD FLAT:??_R0?AVbox@@@8 ; box::`RTTI Base Class Descriptor at (0,-1,0,64)'
DD 01H
DD 00H
DD 0ffffffffH
DD 00H
DD 040H
DD FLAT:??_R3box@@8
??_R2box@@8 DD FLAT:??_R1A@?0A@EA@box@@8 ; box::`RTTI Base Class Array'
DD FLAT:??_R1A@?0A@EA@object@@8
??_R3box@@8 DD 00H ; box::`RTTI Class Hierarchy Descriptor'
DD 00H
DD 02H
DD FLAT:??_R2box@@8
??_R4box@@6B@ DD 00H ; box::`RTTI Complete Object Locator'
DD 00H
DD 00H
DD FLAT:??_R0?AVbox@@@8
DD FLAT:??_R3box@@8
??_7box@@6B@ DD FLAT:??_R4box@@6B@ ; box::`vftable'
DD FLAT:?dump@box@@UAEXXZ
_color$ = 8 ; size = 4
_width$ = 12 ; size = 4
_height$ = 16 ; size = 4
_depth$ = 20 ; size = 4
??0box@@QAE@HHHH@Z PROC ; box::box, COMDAT
; _this$ = ecx
push esi
5You can read more about pointers to functions in the relevant section:( 23 on page 391)
554
CHAPTER 51. C++ 51.2. OSTREAM
mov esi, ecx
call ??0object@@QAE@XZ ; object::object
mov eax, DWORD PTR _color$[esp]
mov ecx, DWORD PTR _width$[esp]
mov edx, DWORD PTR _height$[esp]
mov DWORD PTR [esi+4], eax
mov eax, DWORD PTR _depth$[esp]
mov DWORD PTR [esi+16], eax
mov DWORD PTR [esi], OFFSET ??_7box@@6B@
mov DWORD PTR [esi+8], ecx
mov DWORD PTR [esi+12], edx
mov eax, esi
pop esi
ret 16
??0box@@QAE@HHHH@Z ENDP ; box::box
Here we see a slightly different memory layout: the first field is a pointer to some table box::`vftable' (the name
was set by the MSVC compiler).
In this table we see a link to a table named box::`RTTI Complete Object Locator' and also a link to the
box::dump() method. These are called virtual methods table and RTTI6
. The table of virtual methods contains the
addresses of methods and the RTTI table contains information about types. By the way, the RTTI tables are used while
calling dynamic_cast and typeid in C++. You can also see here the class name as a plain text string. Thus, a method of the
base object class may call the virtual method object::dump(), which in turn will call a method of an inherited class, since that
information is present right in the object’s structure.
Some additional CPU time is needed for doing look-ups in these tables and finding the right virtual method address, thus
virtual methods are widely considered as slightly slower than common methods.
In GCC-generated code the RTTI tables are constructed slightly differently.
51.2 ostream
Let’s start again with a “hello world” example, but now we are going to use ostream:
#include <iostream>
int main()
{
std::cout << "Hello, world!n";
}
Almost any C++ textbook tells us that the << operation can be replaced (overloaded) for other types. That is what is done
in ostream. We see that operator<< is called for ostream:
Listing 51.18: MSVC 2012 (reduced listing)
$SG37112 DB 'Hello, world!', 0aH, 00H
_main PROC
push OFFSET $SG37112
push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout
call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦
$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> >
add esp, 8
xor eax, eax
ret 0
_main ENDP
Let’s modify the example:
#include <iostream>
int main()
{
std::cout << "Hello, " << "world!n";
}
And again, from many C++ textbooks we know that the result of each operator<< in ostream is forwarded to the next
one. Indeed:
6Run-time type information
555
CHAPTER 51. C++ 51.3. REFERENCES
Listing 51.19: MSVC 2012
$SG37112 DB 'world!', 0aH, 00H
$SG37113 DB 'Hello, ', 00H
_main PROC
push OFFSET $SG37113 ; 'Hello, '
push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout
call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦
$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> >
add esp, 8
push OFFSET $SG37112 ; 'world!'
push eax ; result of previous function execution
call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦
$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> >
add esp, 8
xor eax, eax
ret 0
_main ENDP
If we replace operator<< by f(), that code can be rewritten as:
f(f(std::cout, "Hello, "), "world!")
GCC generates almost the same code as MSVC.
51.3 References
In C++, references are pointers ( 10 on page 98) as well, but they are called safe, because it is harder to make a mistake while
dealing with them [ISO13, p. 8.3.2]. For example, reference must always be pointing to an object of the corresponding type
and cannot be NULL [Cli, p. 8.6]. Even more than that, references cannot be changed, it is impossible to point them to
another object (reseat) [Cli, p. 8.5].
If we are going to try to change the example with pointers ( 10 on page 98) to use references instead …
void f2 (int x, int y, int & sum, int & product)
{
sum=x+y;
product=x*y;
};
…then we can see that the compiled code is just the same as in the pointers example ( 10 on page 98):
Listing 51.20: Optimizing MSVC 2010
_x$ = 8 ; size = 4
_y$ = 12 ; size = 4
_sum$ = 16 ; size = 4
_product$ = 20 ; size = 4
?f2@@YAXHHAAH0@Z PROC ; f2
mov ecx, DWORD PTR _y$[esp-4]
mov eax, DWORD PTR _x$[esp-4]
lea edx, DWORD PTR [eax+ecx]
imul eax, ecx
mov ecx, DWORD PTR _product$[esp-4]
push esi
mov esi, DWORD PTR _sum$[esp]
mov DWORD PTR [esi], edx
mov DWORD PTR [ecx], eax
pop esi
ret 0
?f2@@YAXHHAAH0@Z ENDP ; f2
( The reason why C++ functions has such strange names is explained here: 51.1.1 on page 541.)
51.4 STL
N.B.: all examples here were checked only in 32-bit environment. x64 wasn’t checked.
556
CHAPTER 51. C++ 51.4. STL
51.4.1 std::string
Internals
Many string libraries [Yur13, p. 2.2] implement a structure that contains a pointer to a string buffer, a variable that always
contains the current string length (which is very convenient for many functions: [Yur13, p. 2.2.1]) and a variable containing
the current buffer size. The string in the buffer is usually terminated with zero, in order to be able to pass a pointer to the
buffer into the functions that take usual C ASCIIZ strings.
It is not specified in the C++ standard [ISO13] how std::string has to be implemented, however, it is usually implemented
as explained above.
The C++ string is not a class (as QString in Qt, for instance) but a template (basic_string), this is done in order to support
various character types: at least char and wchar_t.
So, std::string is a class with char as its base type. And std::wstring is a class with wchar_t as its base type.
MSVC
The MSVC implementation may store the buffer in place instead of using a pointer to a buffer (if the string is shorter than
16 symbols).
This implies that a short string is to occupy at least 16+4+4 = 24 bytes in 32-bit environment or at least 16+8+8 = 32
bytes in 64-bit one, and if the string is longer than 16 characters, we also have to add the length of the string itself.
Listing 51.21: example for MSVC
#include <string>
#include <stdio.h>
struct std_string
{
union
{
char buf[16];
char* ptr;
} u;
size_t size; // AKA 'Mysize' in MSVC
size_t capacity; // AKA 'Myres' in MSVC
};
void dump_std_string(std::string s)
{
struct std_string *p=(struct std_string*)&s;
printf ("[%s] size:%d capacity:%dn", p->size>16 ? p->u.ptr : p->u.buf, p->size, p->⤦
capacity);
};
int main()
{
std::string s1="short string";
std::string s2="string longer that 16 bytes";
dump_std_string(s1);
dump_std_string(s2);
// that works without using c_str()
printf ("%sn", &s1);
printf ("%sn", s2);
};
Almost everything is clear from the source code.
A couple of notes:
If the string is shorter than 16 symbols, a buffer for the string is not to be allocated in the heap. This is convenient
because in practice, a lot of strings are short indeed. Looks like that Microsoft’s developers chose 16 characters as a good
balance.
One very important thing here can be seen at the end of main(): I’m not using the c_str() method, nevertheless, if we
compile and run this code, both strings will appear in the console!
This is why it works.
In the first case the string is shorter than 16 characters and the buffer with the string is located in the beginning of the
std::string object (it can be treated as a structure). printf() treats the pointer as a pointer to the null-terminated array of
characters, hence it works.
557
CHAPTER 51. C++ 51.4. STL
Printing the second string (longer than 16 characters) is even more dangerous: it is a typical programmer’s mistake (or
typo) to forget to write c_str(). This works because at the moment a pointer to buffer is located at the start of structure.
This may stay unnoticed for a long time, until a longer string appears there at some time, then the process will crash.
GCC
GCC’s implementation of this structure has one more variable—reference count.
One interesting fact is that in GCC a pointer an instance of std::string instance points not to the beginning of the structure,
but to the buffer pointer. In libstdc++-v3includebitsbasic_string.h we can read that it was done for more convenient
debugging:
* The reason you want _M_data pointing to the character %array and
* not the _Rep is so that the debugger can see the string
* contents. (Probably we should add a non-inline member to get
* the _Rep for the debugger to use, so users can check the actual
* string length.)
basic_string.h source code
I consider this in my example:
Listing 51.22: example for GCC
#include <string>
#include <stdio.h>
struct std_string
{
size_t length;
size_t capacity;
size_t refcount;
};
void dump_std_string(std::string s)
{
char *p1=*(char**)&s; // GCC type checking workaround
struct std_string *p2=(struct std_string*)(p1-sizeof(struct std_string));
printf ("[%s] size:%d capacity:%dn", p1, p2->length, p2->capacity);
};
int main()
{
std::string s1="short string";
std::string s2="string longer that 16 bytes";
dump_std_string(s1);
dump_std_string(s2);
// GCC type checking workaround:
printf ("%sn", *(char**)&s1);
printf ("%sn", *(char**)&s2);
};
A trickery has to be used to imitate the mistake I already wrote above because GCC has stronger type checking, never-
theless, printf() works here without c_str() as well.
A more complex example
#include <string>
#include <stdio.h>
int main()
{
std::string s1="Hello, ";
std::string s2="world!n";
std::string s3=s1+s2;
printf ("%sn", s3.c_str());
}
558
CHAPTER 51. C++ 51.4. STL
Listing 51.23: MSVC 2012
$SG39512 DB 'Hello, ', 00H
$SG39514 DB 'world!', 0aH, 00H
$SG39581 DB '%s', 0aH, 00H
_s2$ = -72 ; size = 24
_s3$ = -48 ; size = 24
_s1$ = -24 ; size = 24
_main PROC
sub esp, 72
push 7
push OFFSET $SG39512
lea ecx, DWORD PTR _s1$[esp+80]
mov DWORD PTR _s1$[esp+100], 15
mov DWORD PTR _s1$[esp+96], 0
mov BYTE PTR _s1$[esp+80], 0
call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign
push 7
push OFFSET $SG39514
lea ecx, DWORD PTR _s2$[esp+80]
mov DWORD PTR _s2$[esp+100], 15
mov DWORD PTR _s2$[esp+96], 0
mov BYTE PTR _s2$[esp+80], 0
call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign
lea eax, DWORD PTR _s2$[esp+72]
push eax
lea eax, DWORD PTR _s1$[esp+76]
push eax
lea eax, DWORD PTR _s3$[esp+80]
push eax
call ??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?⤦
$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z ; std::operator+<char,std::char_traits<⤦
char>,std::allocator<char> >
; inlined c_str() method:
cmp DWORD PTR _s3$[esp+104], 16
lea eax, DWORD PTR _s3$[esp+84]
cmovae eax, DWORD PTR _s3$[esp+84]
push eax
push OFFSET $SG39581
call _printf
add esp, 20
cmp DWORD PTR _s3$[esp+92], 16
jb SHORT $LN119@main
push DWORD PTR _s3$[esp+72]
call ??3@YAXPAX@Z ; operator delete
add esp, 4
$LN119@main:
cmp DWORD PTR _s2$[esp+92], 16
mov DWORD PTR _s3$[esp+92], 15
mov DWORD PTR _s3$[esp+88], 0
mov BYTE PTR _s3$[esp+72], 0
jb SHORT $LN151@main
push DWORD PTR _s2$[esp+72]
call ??3@YAXPAX@Z ; operator delete
add esp, 4
$LN151@main:
cmp DWORD PTR _s1$[esp+92], 16
mov DWORD PTR _s2$[esp+92], 15
mov DWORD PTR _s2$[esp+88], 0
mov BYTE PTR _s2$[esp+72], 0
jb SHORT $LN195@main
push DWORD PTR _s1$[esp+72]
559
CHAPTER 51. C++ 51.4. STL
call ??3@YAXPAX@Z ; operator delete
add esp, 4
$LN195@main:
xor eax, eax
add esp, 72
ret 0
_main ENDP
The compiler does not construct strings statically: it would not be possible anyway if the buffer needs to be located in
the heap. Instead, the ASCIIZ strings are stored in the data segment, and later, at runtime, with the help of the “assign”
method, the s1 and s2 strings are constructed. And with the help of operator+, the s3 string is constructed.
Please note that there is no call to the c_str() method, because its code is tiny enough so the compiler inlined it right
there: if the string is shorter than 16 characters, a pointer to buffer is left in EAX, otherwise the address of the string buffer
located in the heap is fetched.
Next, we see calls to the 3 destructors, they are called if the string is longer than 16 characters: then the buffers in the
heap have to be freed. Otherwise, since all three std::string objects are stored in the stack, they are freed automatically,
when the function ends.
As a consequence, processing short strings is faster, because of less heap accesses.
GCC code is even simpler (because the GCC way, as I mentioned above, is to not store shorter strings right in the structure):
Listing 51.24: GCC 4.8.1
.LC0:
.string "Hello, "
.LC1:
.string "world!n"
main:
push ebp
mov ebp, esp
push edi
push esi
push ebx
and esp, -16
sub esp, 32
lea ebx, [esp+28]
lea edi, [esp+20]
mov DWORD PTR [esp+8], ebx
lea esi, [esp+24]
mov DWORD PTR [esp+4], OFFSET FLAT:.LC0
mov DWORD PTR [esp], edi
call _ZNSsC1EPKcRKSaIcE
mov DWORD PTR [esp+8], ebx
mov DWORD PTR [esp+4], OFFSET FLAT:.LC1
mov DWORD PTR [esp], esi
call _ZNSsC1EPKcRKSaIcE
mov DWORD PTR [esp+4], edi
mov DWORD PTR [esp], ebx
call _ZNSsC1ERKSs
mov DWORD PTR [esp+4], esi
mov DWORD PTR [esp], ebx
call _ZNSs6appendERKSs
; inlined c_str():
mov eax, DWORD PTR [esp+28]
mov DWORD PTR [esp], eax
call puts
mov eax, DWORD PTR [esp+28]
lea ebx, [esp+19]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
560
CHAPTER 51. C++ 51.4. STL
call _ZNSs4_Rep10_M_disposeERKSaIcE
mov eax, DWORD PTR [esp+24]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
mov eax, DWORD PTR [esp+20]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
lea esp, [ebp-12]
xor eax, eax
pop ebx
pop esi
pop edi
pop ebp
ret
It can be seen that it’s not a pointer to the object that is passed to destructors, but rather an address 12 bytes (or 3 words)
before, i.e., a pointer to the real start of the structure.
std::string as a global variable
Experienced C++ programmers may not agree, but a global variables with an STL7
type can be defined.
Yes, indeed:
#include <stdio.h>
#include <string>
std::string s="a string";
int main()
{
printf ("%sn", s.c_str());
};
In fact, this variable is to be initialized even before main() start.
Listing 51.25: MSVC 2012: here is how a global variable is constructed and also its destructor is registered
??__Es@@YAXXZ PROC
push 8
push OFFSET $SG39512 ; 'a string'
mov ecx, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign
push OFFSET ??__Fs@@YAXXZ ; `dynamic atexit destructor for 's''
call _atexit
pop ecx
ret 0
??__Es@@YAXXZ ENDP
Listing 51.26: MSVC 2012: here a global variable is used in main()
$SG39512 DB 'a string', 00H
$SG39519 DB '%s', 0aH, 00H
_main PROC
cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16
mov eax, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
cmovae eax, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A
push eax
push OFFSET $SG39519 ; '%s'
call _printf
add esp, 8
xor eax, eax
ret 0
_main ENDP
7(C++) Standard Template Library: 51.4 on page 556
561
CHAPTER 51. C++ 51.4. STL
Listing 51.27: MSVC 2012: this destructor function is called before exit
??__Fs@@YAXXZ PROC
push ecx
cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16
jb SHORT $LN23@dynamic
push esi
mov esi, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A
lea ecx, DWORD PTR $T2[esp+8]
call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ
push OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
lea ecx, DWORD PTR $T2[esp+12]
call ??$destroy@PAD@?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAEXPAPAD@Z
lea ecx, DWORD PTR $T1[esp+8]
call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ
push esi
call ??3@YAXPAX@Z ; operator delete
add esp, 4
pop esi
$LN23@dynamic:
mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 15
mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+16, 0
mov BYTE PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A, 0
pop ecx
ret 0
??__Fs@@YAXXZ ENDP
In fact, a special function with all constructors of global variables is called from CRT, before main(). More than that:
with the help of atexit() another function is registered, which contain calls to all destructors of such global variables.
GCC works likewise:
Listing 51.28: GCC 4.8.1
main:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov eax, DWORD PTR s
mov DWORD PTR [esp], eax
call puts
xor eax, eax
leave
ret
.LC0:
.string "a string"
_GLOBAL__sub_I_s:
sub esp, 44
lea eax, [esp+31]
mov DWORD PTR [esp+8], eax
mov DWORD PTR [esp+4], OFFSET FLAT:.LC0
mov DWORD PTR [esp], OFFSET FLAT:s
call _ZNSsC1EPKcRKSaIcE
mov DWORD PTR [esp+8], OFFSET FLAT:__dso_handle
mov DWORD PTR [esp+4], OFFSET FLAT:s
mov DWORD PTR [esp], OFFSET FLAT:_ZNSsD1Ev
call __cxa_atexit
add esp, 44
ret
.LFE645:
.size _GLOBAL__sub_I_s, .-_GLOBAL__sub_I_s
.section .init_array,"aw"
.align 4
.long _GLOBAL__sub_I_s
.globl s
.bss
.align 4
.type s, @object
.size s, 4
s:
.zero 4
.hidden __dso_handle
562
CHAPTER 51. C++ 51.4. STL
But it does not create a separate function for this, each destructor is passed to atexit(), one by one.
51.4.2 std::list
This is the well-known doubly-linked list: each element has two pointers, to the previous and next elements.
This implies that the memory footprint is enlarged by 2 words for each element (8 bytes in 32-bit environment or 16
bytes in 64-bit).
C++ STL just adds the “next” and “previous” pointers to the existing structure of the type that you want to unite in a list.
Let’s work out an example with a simple 2-variable structure that we want to store in a list.
Although the C++ standard [ISO13] does not say how to implement it, both MSVC’s and GCC’s implementations are straight-
forward and similar, so here is only one source code for both:
#include <stdio.h>
#include <list>
#include <iostream>
struct a
{
int x;
int y;
};
struct List_node
{
struct List_node* _Next;
struct List_node* _Prev;
int x;
int y;
};
void dump_List_node (struct List_node *n)
{
printf ("ptr=0x%p _Next=0x%p _Prev=0x%p x=%d y=%dn",
n, n->_Next, n->_Prev, n->x, n->y);
};
void dump_List_vals (struct List_node* n)
{
struct List_node* current=n;
for (;;)
{
dump_List_node (current);
current=current->_Next;
if (current==n) // end
break;
};
};
void dump_List_val (unsigned int *a)
{
#ifdef _MSC_VER
// GCC implementation does not have "size" field
printf ("_Myhead=0x%p, _Mysize=%dn", a[0], a[1]);
#endif
dump_List_vals ((struct List_node*)a[0]);
};
int main()
{
std::list<struct a> l;
printf ("* empty list:n");
dump_List_val((unsigned int*)(void*)&l);
struct a t1;
t1.x=1;
t1.y=2;
563
CHAPTER 51. C++ 51.4. STL
l.push_front (t1);
t1.x=3;
t1.y=4;
l.push_front (t1);
t1.x=5;
t1.y=6;
l.push_back (t1);
printf ("* 3-elements list:n");
dump_List_val((unsigned int*)(void*)&l);
std::list<struct a>::iterator tmp;
printf ("node at .begin:n");
tmp=l.begin();
dump_List_node ((struct List_node *)*(void**)&tmp);
printf ("node at .end:n");
tmp=l.end();
dump_List_node ((struct List_node *)*(void**)&tmp);
printf ("* let's count from the begin:n");
std::list<struct a>::iterator it=l.begin();
printf ("1st element: %d %dn", (*it).x, (*it).y);
it++;
printf ("2nd element: %d %dn", (*it).x, (*it).y);
it++;
printf ("3rd element: %d %dn", (*it).x, (*it).y);
it++;
printf ("element at .end(): %d %dn", (*it).x, (*it).y);
printf ("* let's count from the end:n");
std::list<struct a>::iterator it2=l.end();
printf ("element at .end(): %d %dn", (*it2).x, (*it2).y);
it2--;
printf ("3rd element: %d %dn", (*it2).x, (*it2).y);
it2--;
printf ("2nd element: %d %dn", (*it2).x, (*it2).y);
it2--;
printf ("1st element: %d %dn", (*it2).x, (*it2).y);
printf ("removing last element...n");
l.pop_back();
dump_List_val((unsigned int*)(void*)&l);
};
GCC
Let’s start with GCC.
When we run the example, we’ll see a long dump, let’s work with it in pieces.
* empty list:
ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0
Here we see an empty list. Despite the fact it is empty, it has one element with garbage (AKA dummy node) in x and y.
Both the “next” and “prev” pointers are pointing to the self node:
..Next .
Prev
.
X=garbage
.
Y=garbage
.
Variable std::list
.
list.begin()
.
list.end()
........
564
CHAPTER 51. C++ 51.4. STL
At this moment, the .begin and .end iterators are equal to each other.
If we push 3 elements, the list internally will be:
* 3-elements list:
ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4
ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2
ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6
ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6
The last element is still at 0x0028fe90, it not to be moved until the list’s disposal. It still contain random garbage
in x and y (5 and 6). By coincidence, these values are the same as in the last element, but it doesn’t mean that they are
meaningful.
Here is how these 3 elements are stored in memory:
..Next .
Prev
.
X=1st element
.
Y=1st element
. Next.
Prev
.
X=2nd element
.
Y=2nd element
. Next.
Prev
.
X=3rd element
.
Y=3rd element
. Next.
Prev
.
X=garbage
.
Y=garbage
.
Variable std::list
.
list.begin()
.
list.end()
........
The l variable always points to the first node.
The .begin() and .end() iterators are not variables, but functions, which when called return pointers to the corresponding
nodes.
Having a dummy element (AKA sentinel node) is a very popular practice in implementing doubly-linked lists. Without it,
a lot of operations may become slightly more complex and, hence, slower.
The iterator is in fact just a pointer to a node. list.begin() and list.end() just return pointers.
node at .begin:
ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4
node at .end:
ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6
The fact that the last element has a pointer to the first and the first element has a pointer to the last one remind us
circular list.
This is very helpful here: having a pointer to the first list element, i.e., that is in the l variable, it is easy to get a pointer
to the last one quickly, without the need to traverse the whole list. Inserting an element at the list end is also quick, thanks
to this feature.
operator-- and operator++ just set the current iterator’s value to the current_node->prev or
current_node->next values. The reverse iterators (.rbegin, .rend) work just as the same, but in reverse.
operator* just returns a pointer to the point in the node structure, where the user’s structure starts, i.e., a pointer to
the first element of the structure (x).
The list insertion and deletion are trivial: just allocate a new node (or deallocate) and update all pointers to be valid.
That’s why an iterator may become invalid after element deletion: it may still point to the node that was already deal-
located. This is also called a dangling pointer. And of course, the information from the freed node (to which iterator still
points) cannot be used anymore.
The GCC implementation (as of 4.8.1) doesn’t store the current size of the list: this implies a slow .size() method: it has
to traverse the whole list to count the elements, because it doesn’t have any other way to get the information. This mean
that this operation is O(n), i.e., it gets slower steadily as the list grows.
Listing 51.29: Optimizing GCC 4.8.1 -fno-inline-small-functions
main proc near
push ebp
mov ebp, esp
push esi
push ebx
565
CHAPTER 51. C++ 51.4. STL
and esp, 0FFFFFFF0h
sub esp, 20h
lea ebx, [esp+10h]
mov dword ptr [esp], offset s ; "* empty list:"
mov [esp+10h], ebx
mov [esp+14h], ebx
call puts
mov [esp], ebx
call _Z13dump_List_valPj ; dump_List_val(uint *)
lea esi, [esp+18h]
mov [esp+4], esi
mov [esp], ebx
mov dword ptr [esp+18h], 1 ; X for new element
mov dword ptr [esp+1Ch], 2 ; Y for new element
call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a⤦
const&)
mov [esp+4], esi
mov [esp], ebx
mov dword ptr [esp+18h], 3 ; X for new element
mov dword ptr [esp+1Ch], 4 ; Y for new element
call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a⤦
const&)
mov dword ptr [esp], 10h
mov dword ptr [esp+18h], 5 ; X for new element
mov dword ptr [esp+1Ch], 6 ; Y for new element
call _Znwj ; operator new(uint)
cmp eax, 0FFFFFFF8h
jz short loc_80002A6
mov ecx, [esp+1Ch]
mov edx, [esp+18h]
mov [eax+0Ch], ecx
mov [eax+8], edx
loc_80002A6: ; CODE XREF: main+86
mov [esp+4], ebx
mov [esp], eax
call _ZNSt8__detail15_List_node_base7_M_hookEPS0_ ; std::__detail::_List_node_base::_M_hook⤦
(std::__detail::_List_node_base*)
mov dword ptr [esp], offset a3ElementsList ; "* 3-elements list:"
call puts
mov [esp], ebx
call _Z13dump_List_valPj ; dump_List_val(uint *)
mov dword ptr [esp], offset aNodeAt_begin ; "node at .begin:"
call puts
mov eax, [esp+10h]
mov [esp], eax
call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *)
mov dword ptr [esp], offset aNodeAt_end ; "node at .end:"
call puts
mov [esp], ebx
call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *)
mov dword ptr [esp], offset aLetSCountFromT ; "* let's count from the begin:"
call puts
mov esi, [esp+10h]
mov eax, [esi+0Ch]
mov [esp+0Ch], eax
mov eax, [esi+8]
mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov esi, [esi] ; operator++: get ->next pointer
mov eax, [esi+0Ch]
mov [esp+0Ch], eax
mov eax, [esi+8]
mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov esi, [esi] ; operator++: get ->next pointer
566
CHAPTER 51. C++ 51.4. STL
mov eax, [esi+0Ch]
mov [esp+0Ch], eax
mov eax, [esi+8]
mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov eax, [esi] ; operator++: get ->next pointer
mov edx, [eax+0Ch]
mov [esp+0Ch], edx
mov eax, [eax+8]
mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov dword ptr [esp], offset aLetSCountFro_0 ; "* let's count from the end:"
call puts
mov eax, [esp+1Ch]
mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %dn"
mov dword ptr [esp], 1
mov [esp+0Ch], eax
mov eax, [esp+18h]
mov [esp+8], eax
call __printf_chk
mov esi, [esp+14h]
mov eax, [esi+0Ch]
mov [esp+0Ch], eax
mov eax, [esi+8]
mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov esi, [esi+4] ; operator--: get ->prev pointer
mov eax, [esi+0Ch]
mov [esp+0Ch], eax
mov eax, [esi+8]
mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov eax, [esi+4] ; operator--: get ->prev pointer
mov edx, [eax+0Ch]
mov [esp+0Ch], edx
mov eax, [eax+8]
mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %dn"
mov dword ptr [esp], 1
mov [esp+8], eax
call __printf_chk
mov dword ptr [esp], offset aRemovingLastEl ; "removing last element..."
call puts
mov esi, [esp+14h]
mov [esp], esi
call _ZNSt8__detail15_List_node_base9_M_unhookEv ; std::__detail::_List_node_base::⤦
_M_unhook(void)
mov [esp], esi ; void *
call _ZdlPv ; operator delete(void *)
mov [esp], ebx
call _Z13dump_List_valPj ; dump_List_val(uint *)
mov [esp], ebx
call _ZNSt10_List_baseI1aSaIS0_EE8_M_clearEv ; std::_List_base<a,std::allocator<a>>::⤦
_M_clear(void)
lea esp, [ebp-8]
xor eax, eax
pop ebx
pop esi
pop ebp
retn
main endp
567
CHAPTER 51. C++ 51.4. STL
Listing 51.30: The whole output
* empty list:
ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0
* 3-elements list:
ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4
ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2
ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6
ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6
node at .begin:
ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4
node at .end:
ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6
* let's count from the begin:
1st element: 3 4
2nd element: 1 2
3rd element: 5 6
element at .end(): 5 6
* let's count from the end:
element at .end(): 5 6
3rd element: 5 6
2nd element: 1 2
1st element: 3 4
removing last element...
ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4
ptr=0x00034988 _Next=0x0028fe90 _Prev=0x000349a0 x=1 y=2
ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034988 x=5 y=6
MSVC
MSVC’s implementation (2012) is just the same, but it also stores the current size of the list. This implies that the .size()
method is very fast (O(1)): it just reads one value from memory. On the other hand, the size variable must be updated at
each insertion/deletion.
MSVC’s implementation is also slightly different in the way it arranges the nodes:
..Next .
Prev
.
X=garbage
.
Y=garbage
. Next.
Prev
.
X=1st element
.
Y=1st element
. Next.
Prev
.
X=2nd element
.
Y=2nd element
. Next.
Prev
.
X=3rd element
.
Y=3rd element
.
Variable std::list
.
list.end()
.
list.begin()
........
GCC has its dummy element at the end of the list, while MSVC’s is at the beginning.
Listing 51.31: Optimizing MSVC 2012 /Fa2.asm /GS- /Ob1
_l$ = -16 ; size = 8
_t1$ = -8 ; size = 8
_main PROC
sub esp, 16
push ebx
push esi
push edi
push 0
push 0
lea ecx, DWORD PTR _l$[esp+36]
mov DWORD PTR _l$[esp+40], 0
568
CHAPTER 51. C++ 51.4. STL
; allocate first "garbage" element
call ?_Buynode0@?$_List_alloc@$0A@U?$_List_base_types@Ua@@V?⤦
$allocator@Ua@@@std@@@std@@@std@@QAEPAU?$_List_node@Ua@@PAX@2@PAU32@0@Z ; std::⤦
_List_alloc<0,std::_List_base_types<a,std::allocator<a> > >::_Buynode0
mov edi, DWORD PTR __imp__printf
mov ebx, eax
push OFFSET $SG40685 ; '* empty list:'
mov DWORD PTR _l$[esp+32], ebx
call edi ; printf
lea eax, DWORD PTR _l$[esp+32]
push eax
call ?dump_List_val@@YAXPAI@Z ; dump_List_val
mov esi, DWORD PTR [ebx]
add esp, 8
lea eax, DWORD PTR _t1$[esp+28]
push eax
push DWORD PTR [esi+4]
lea ecx, DWORD PTR _l$[esp+36]
push esi
mov DWORD PTR _t1$[esp+40], 1 ; data for a new node
mov DWORD PTR _t1$[esp+44], 2 ; data for a new node
; allocate new node
call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦
$_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦
const &>
mov DWORD PTR [esi+4], eax
mov ecx, DWORD PTR [eax+4]
mov DWORD PTR _t1$[esp+28], 3 ; data for a new node
mov DWORD PTR [ecx], eax
mov esi, DWORD PTR [ebx]
lea eax, DWORD PTR _t1$[esp+28]
push eax
push DWORD PTR [esi+4]
lea ecx, DWORD PTR _l$[esp+36]
push esi
mov DWORD PTR _t1$[esp+44], 4 ; data for a new node
; allocate new node
call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦
$_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦
const &>
mov DWORD PTR [esi+4], eax
mov ecx, DWORD PTR [eax+4]
mov DWORD PTR _t1$[esp+28], 5 ; data for a new node
mov DWORD PTR [ecx], eax
lea eax, DWORD PTR _t1$[esp+28]
push eax
push DWORD PTR [ebx+4]
lea ecx, DWORD PTR _l$[esp+36]
push ebx
mov DWORD PTR _t1$[esp+44], 6 ; data for a new node
; allocate new node
call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦
$_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦
const &>
mov DWORD PTR [ebx+4], eax
mov ecx, DWORD PTR [eax+4]
push OFFSET $SG40689 ; '* 3-elements list:'
mov DWORD PTR _l$[esp+36], 3
mov DWORD PTR [ecx], eax
call edi ; printf
lea eax, DWORD PTR _l$[esp+32]
push eax
call ?dump_List_val@@YAXPAI@Z ; dump_List_val
push OFFSET $SG40831 ; 'node at .begin:'
call edi ; printf
push DWORD PTR [ebx] ; get next field of node l variable points to
call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node
push OFFSET $SG40835 ; 'node at .end:'
call edi ; printf
push ebx ; pointer to the node $l$ variable points to!
569
CHAPTER 51. C++ 51.4. STL
call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node
push OFFSET $SG40839 ; '* let''s count from the begin:'
call edi ; printf
mov esi, DWORD PTR [ebx] ; operator++: get ->next pointer
push DWORD PTR [esi+12]
push DWORD PTR [esi+8]
push OFFSET $SG40846 ; '1st element: %d %d'
call edi ; printf
mov esi, DWORD PTR [esi] ; operator++: get ->next pointer
push DWORD PTR [esi+12]
push DWORD PTR [esi+8]
push OFFSET $SG40848 ; '2nd element: %d %d'
call edi ; printf
mov esi, DWORD PTR [esi] ; operator++: get ->next pointer
push DWORD PTR [esi+12]
push DWORD PTR [esi+8]
push OFFSET $SG40850 ; '3rd element: %d %d'
call edi ; printf
mov eax, DWORD PTR [esi] ; operator++: get ->next pointer
add esp, 64
push DWORD PTR [eax+12]
push DWORD PTR [eax+8]
push OFFSET $SG40852 ; 'element at .end(): %d %d'
call edi ; printf
push OFFSET $SG40853 ; '* let''s count from the end:'
call edi ; printf
push DWORD PTR [ebx+12] ; use x and y fields from the node l variable points to
push DWORD PTR [ebx+8]
push OFFSET $SG40860 ; 'element at .end(): %d %d'
call edi ; printf
mov esi, DWORD PTR [ebx+4] ; operator--: get ->prev pointer
push DWORD PTR [esi+12]
push DWORD PTR [esi+8]
push OFFSET $SG40862 ; '3rd element: %d %d'
call edi ; printf
mov esi, DWORD PTR [esi+4] ; operator--: get ->prev pointer
push DWORD PTR [esi+12]
push DWORD PTR [esi+8]
push OFFSET $SG40864 ; '2nd element: %d %d'
call edi ; printf
mov eax, DWORD PTR [esi+4] ; operator--: get ->prev pointer
push DWORD PTR [eax+12]
push DWORD PTR [eax+8]
push OFFSET $SG40866 ; '1st element: %d %d'
call edi ; printf
add esp, 64
push OFFSET $SG40867 ; 'removing last element...'
call edi ; printf
mov edx, DWORD PTR [ebx+4]
add esp, 4
; prev=next?
; it is the only element, "garbage one"?
; if yes, do not delete it!
cmp edx, ebx
je SHORT $LN349@main
mov ecx, DWORD PTR [edx+4]
mov eax, DWORD PTR [edx]
mov DWORD PTR [ecx], eax
mov ecx, DWORD PTR [edx]
mov eax, DWORD PTR [edx+4]
push edx
mov DWORD PTR [ecx+4], eax
call ??3@YAXPAX@Z ; operator delete
add esp, 4
mov DWORD PTR _l$[esp+32], 2
$LN349@main:
lea eax, DWORD PTR _l$[esp+28]
push eax
call ?dump_List_val@@YAXPAI@Z ; dump_List_val
570
CHAPTER 51. C++ 51.4. STL
mov eax, DWORD PTR [ebx]
add esp, 4
mov DWORD PTR [ebx], ebx
mov DWORD PTR [ebx+4], ebx
cmp eax, ebx
je SHORT $LN412@main
$LL414@main:
mov esi, DWORD PTR [eax]
push eax
call ??3@YAXPAX@Z ; operator delete
add esp, 4
mov eax, esi
cmp esi, ebx
jne SHORT $LL414@main
$LN412@main:
push ebx
call ??3@YAXPAX@Z ; operator delete
add esp, 4
xor eax, eax
pop edi
pop esi
pop ebx
add esp, 16
ret 0
_main ENDP
Unlike GCC, MSVC’s code allocates the dummy element at the start of the function with the help of the “Buynode” function,
it is also used to allocate the rest of the nodes ( GCC’s code allocates the first element in the local stack).
Listing 51.32: The whole output
* empty list:
_Myhead=0x003CC258, _Mysize=0
ptr=0x003CC258 _Next=0x003CC258 _Prev=0x003CC258 x=6226002 y=4522072
* 3-elements list:
_Myhead=0x003CC258, _Mysize=3
ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072
ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4
ptr=0x003CC270 _Next=0x003CC2A0 _Prev=0x003CC288 x=1 y=2
ptr=0x003CC2A0 _Next=0x003CC258 _Prev=0x003CC270 x=5 y=6
node at .begin:
ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4
node at .end:
ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072
* let's count from the begin:
1st element: 3 4
2nd element: 1 2
3rd element: 5 6
element at .end(): 6226002 4522072
* let's count from the end:
element at .end(): 6226002 4522072
3rd element: 5 6
2nd element: 1 2
1st element: 3 4
removing last element...
_Myhead=0x003CC258, _Mysize=2
ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC270 x=6226002 y=4522072
ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4
ptr=0x003CC270 _Next=0x003CC258 _Prev=0x003CC288 x=1 y=2
C++11 std::forward_list
The same thing as std::list, but singly-linked one, i.e., having only the “next” field at each node. It has a smaller memory
footprint, but also don’t offer the ability to traverse list backwards.
571
CHAPTER 51. C++ 51.4. STL
51.4.3 std::vector
I would call std::vector a “safe wrapper” of thePODT8
C array. Internally it is somewhat similar to std::string ( 51.4.1
on page 557): it has a pointer to the allocated buffer, a pointer to the end of the array, and a pointer to the end of the allocated
buffer.
The array’s elements lie in memory adjacently to each other, just like in a normal array ( 18 on page 257). In C++11 there
is a new method called .data() , that returns a pointer to the buffer, like .c_str() in std::string.
The buffer allocated in the heap can be larger than the array itself.
Both MSVC’s and GCC’s implementations are similar, just the names of the structure’s fields are slightly different9
, so here
is one source code that works for both compilers. Here is again the C-like code for dumping the structure of std::vector:
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <functional>
struct vector_of_ints
{
// MSVC names:
int *Myfirst;
int *Mylast;
int *Myend;
// GCC structure is the same, but names are: _M_start, _M_finish, _M_end_of_storage
};
void dump(struct vector_of_ints *in)
{
printf ("_Myfirst=%p, _Mylast=%p, _Myend=%pn", in->Myfirst, in->Mylast, in->Myend);
size_t size=(in->Mylast-in->Myfirst);
size_t capacity=(in->Myend-in->Myfirst);
printf ("size=%d, capacity=%dn", size, capacity);
for (size_t i=0; i<size; i++)
printf ("element %d: %dn", i, in->Myfirst[i]);
};
int main()
{
std::vector<int> c;
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(1);
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(2);
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(3);
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(4);
dump ((struct vector_of_ints*)(void*)&c);
c.reserve (6);
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(5);
dump ((struct vector_of_ints*)(void*)&c);
c.push_back(6);
dump ((struct vector_of_ints*)(void*)&c);
printf ("%dn", c.at(5)); // with bounds checking
printf ("%dn", c[8]); // operator[], without bounds checking
};
Here is the output of this program when compiled in MSVC:
_Myfirst=00000000, _Mylast=00000000, _Myend=00000000
size=0, capacity=0
_Myfirst=0051CF48, _Mylast=0051CF4C, _Myend=0051CF4C
size=1, capacity=1
element 0: 1
_Myfirst=0051CF58, _Mylast=0051CF60, _Myend=0051CF60
size=2, capacity=2
element 0: 1
8(C++) Plain Old Data Type
9GCC internals: http://go.yurichev.com/17086
572
CHAPTER 51. C++ 51.4. STL
element 1: 2
_Myfirst=0051C278, _Mylast=0051C284, _Myend=0051C284
size=3, capacity=3
element 0: 1
element 1: 2
element 2: 3
_Myfirst=0051C290, _Mylast=0051C2A0, _Myend=0051C2A0
size=4, capacity=4
element 0: 1
element 1: 2
element 2: 3
element 3: 4
_Myfirst=0051B180, _Mylast=0051B190, _Myend=0051B198
size=4, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
_Myfirst=0051B180, _Mylast=0051B194, _Myend=0051B198
size=5, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
element 4: 5
_Myfirst=0051B180, _Mylast=0051B198, _Myend=0051B198
size=6, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
element 4: 5
element 5: 6
6
6619158
As it can be seen, there is no allocated buffer when main() starts. After the first push_back() call, a buffer is allocated.
And then, after each push_back() call, both array size and buffer size (capacity) are increased. But the buffer address
changes as well, because push_back() reallocates the buffer in the heap each time. It is costly operation, that’s why it is
very important to predict the size of the array in the future and reserve enough space for it with the .reserve() method.
The last number is garbage: there are no array elements at this point, so a random number is printed. This illustrates the
fact that operator[] of std::vector does not check of the index is in the array’s bounds. The slower .at() method,
however, does this checking and throws an std::out_of_range exception in case of error.
Let’s see the code:
Listing 51.33: MSVC 2012 /GS- /Ob1
$SG52650 DB '%d', 0aH, 00H
$SG52651 DB '%d', 0aH, 00H
_this$ = -4 ; size = 4
__Pos$ = 8 ; size = 4
?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z PROC ; std::vector<int,std::allocator<int> ⤦
>::at, COMDAT
; _this$ = ecx
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _this$[ebp], ecx
mov eax, DWORD PTR _this$[ebp]
mov ecx, DWORD PTR _this$[ebp]
mov edx, DWORD PTR [eax+4]
sub edx, DWORD PTR [ecx]
sar edx, 2
cmp edx, DWORD PTR __Pos$[ebp]
ja SHORT $LN1@at
push OFFSET ??_C@_0BM@NMJKDPPO@invalid?5vector?$DMT?$DO?5subscript?$AA@
call DWORD PTR __imp_?_Xout_of_range@std@@YAXPBD@Z
$LN1@at:
mov eax, DWORD PTR _this$[ebp]
573
CHAPTER 51. C++ 51.4. STL
mov ecx, DWORD PTR [eax]
mov edx, DWORD PTR __Pos$[ebp]
lea eax, DWORD PTR [ecx+edx*4]
$LN3@at:
mov esp, ebp
pop ebp
ret 4
?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ENDP ; std::vector<int,std::allocator<int> ⤦
>::at
_c$ = -36 ; size = 12
$T1 = -24 ; size = 4
$T2 = -20 ; size = 4
$T3 = -16 ; size = 4
$T4 = -12 ; size = 4
$T5 = -8 ; size = 4
$T6 = -4 ; size = 4
_main PROC
push ebp
mov ebp, esp
sub esp, 36
mov DWORD PTR _c$[ebp], 0 ; Myfirst
mov DWORD PTR _c$[ebp+4], 0 ; Mylast
mov DWORD PTR _c$[ebp+8], 0 ; Myend
lea eax, DWORD PTR _c$[ebp]
push eax
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T6[ebp], 1
lea ecx, DWORD PTR $T6[ebp]
push ecx
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea edx, DWORD PTR _c$[ebp]
push edx
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T5[ebp], 2
lea eax, DWORD PTR $T5[ebp]
push eax
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea ecx, DWORD PTR _c$[ebp]
push ecx
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T4[ebp], 3
lea edx, DWORD PTR $T4[ebp]
push edx
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea eax, DWORD PTR _c$[ebp]
push eax
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T3[ebp], 4
lea ecx, DWORD PTR $T3[ebp]
push ecx
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea edx, DWORD PTR _c$[ebp]
push edx
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
push 6
lea ecx, DWORD PTR _c$[ebp]
574
CHAPTER 51. C++ 51.4. STL
call ?reserve@?$vector@HV?$allocator@H@std@@@std@@QAEXI@Z ; std::vector<int,std::allocator<⤦
int> >::reserve
lea eax, DWORD PTR _c$[ebp]
push eax
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T2[ebp], 5
lea ecx, DWORD PTR $T2[ebp]
push ecx
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea edx, DWORD PTR _c$[ebp]
push edx
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
mov DWORD PTR $T1[ebp], 6
lea eax, DWORD PTR $T1[ebp]
push eax
lea ecx, DWORD PTR _c$[ebp]
call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦
allocator<int> >::push_back
lea ecx, DWORD PTR _c$[ebp]
push ecx
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump
add esp, 4
push 5
lea ecx, DWORD PTR _c$[ebp]
call ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ; std::vector<int,std::allocator<int⤦
> >::at
mov edx, DWORD PTR [eax]
push edx
push OFFSET $SG52650 ; '%d'
call DWORD PTR __imp__printf
add esp, 8
mov eax, 8
shl eax, 2
mov ecx, DWORD PTR _c$[ebp]
mov edx, DWORD PTR [ecx+eax]
push edx
push OFFSET $SG52651 ; '%d'
call DWORD PTR __imp__printf
add esp, 8
lea ecx, DWORD PTR _c$[ebp]
call ?_Tidy@?$vector@HV?$allocator@H@std@@@std@@IAEXXZ ; std::vector<int,std::allocator<int⤦
> >::_Tidy
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP
We see how the .at() method checks the bounds and throws an exception in case of error. The number that the last
printf() call prints is just taken from the memory, without any checks.
One may ask, why not use the variables like “size” and “capacity”, like it was done in std::string. I suppose that this
was done for faster bounds checking. But I’m not sure.
The code GCC generates is in general almost the same, but the .at() method is inlined:
Listing 51.34: GCC 4.8.1 -fno-inline-small-functions -O1
main proc near
push ebp
mov ebp, esp
push edi
push esi
push ebx
and esp, 0FFFFFFF0h
sub esp, 20h
mov dword ptr [esp+14h], 0
mov dword ptr [esp+18h], 0
mov dword ptr [esp+1Ch], 0
575
CHAPTER 51. C++ 51.4. STL
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 1
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 2
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 3
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 4
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov ebx, [esp+14h]
mov eax, [esp+1Ch]
sub eax, ebx
cmp eax, 17h
ja short loc_80001CF
mov edi, [esp+18h]
sub edi, ebx
sar edi, 2
mov dword ptr [esp], 18h
call _Znwj ; operator new(uint)
mov esi, eax
test edi, edi
jz short loc_80001AD
lea eax, ds:0[edi*4]
mov [esp+8], eax ; n
mov [esp+4], ebx ; src
mov [esp], esi ; dest
call memmove
loc_80001AD: ; CODE XREF: main+F8
mov eax, [esp+14h]
test eax, eax
jz short loc_80001BD
mov [esp], eax ; void *
call _ZdlPv ; operator delete(void *)
loc_80001BD: ; CODE XREF: main+117
576
CHAPTER 51. C++ 51.4. STL
mov [esp+14h], esi
lea eax, [esi+edi*4]
mov [esp+18h], eax
add esi, 18h
mov [esp+1Ch], esi
loc_80001CF: ; CODE XREF: main+DD
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 5
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov dword ptr [esp+10h], 6
lea eax, [esp+10h]
mov [esp+4], eax
lea eax, [esp+14h]
mov [esp], eax
call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦
int const&)
lea eax, [esp+14h]
mov [esp], eax
call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *)
mov eax, [esp+14h]
mov edx, [esp+18h]
sub edx, eax
cmp edx, 17h
ja short loc_8000246
mov dword ptr [esp], offset aVector_m_range ; "vector::_M_range_check"
call _ZSt20__throw_out_of_rangePKc ; std::__throw_out_of_range(char const*)
loc_8000246: ; CODE XREF: main+19C
mov eax, [eax+14h]
mov [esp+8], eax
mov dword ptr [esp+4], offset aD ; "%dn"
mov dword ptr [esp], 1
call __printf_chk
mov eax, [esp+14h]
mov eax, [eax+20h]
mov [esp+8], eax
mov dword ptr [esp+4], offset aD ; "%dn"
mov dword ptr [esp], 1
call __printf_chk
mov eax, [esp+14h]
test eax, eax
jz short loc_80002AC
mov [esp], eax ; void *
call _ZdlPv ; operator delete(void *)
jmp short loc_80002AC
mov ebx, eax
mov edx, [esp+14h]
test edx, edx
jz short loc_80002A4
mov [esp], edx ; void *
call _ZdlPv ; operator delete(void *)
loc_80002A4: ; CODE XREF: main+1FE
mov [esp], ebx
call _Unwind_Resume
loc_80002AC: ; CODE XREF: main+1EA
577
CHAPTER 51. C++ 51.4. STL
; main+1F4
mov eax, 0
lea esp, [ebp-0Ch]
pop ebx
pop esi
pop edi
pop ebp
locret_80002B8: ; DATA XREF: .eh_frame:08000510
; .eh_frame:080005BC
retn
main endp
.reserve() is inlined as well. It calls new() if the buffer is too small for the new size, calls memmove() to copy the
contents of the buffer, and calls delete() to free the old buffer.
Let’s also see what the compiled program outputs if compiled with GCC:
_Myfirst=0x(nil), _Mylast=0x(nil), _Myend=0x(nil)
size=0, capacity=0
_Myfirst=0x8257008, _Mylast=0x825700c, _Myend=0x825700c
size=1, capacity=1
element 0: 1
_Myfirst=0x8257018, _Mylast=0x8257020, _Myend=0x8257020
size=2, capacity=2
element 0: 1
element 1: 2
_Myfirst=0x8257028, _Mylast=0x8257034, _Myend=0x8257038
size=3, capacity=4
element 0: 1
element 1: 2
element 2: 3
_Myfirst=0x8257028, _Mylast=0x8257038, _Myend=0x8257038
size=4, capacity=4
element 0: 1
element 1: 2
element 2: 3
element 3: 4
_Myfirst=0x8257040, _Mylast=0x8257050, _Myend=0x8257058
size=4, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
_Myfirst=0x8257040, _Mylast=0x8257054, _Myend=0x8257058
size=5, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
element 4: 5
_Myfirst=0x8257040, _Mylast=0x8257058, _Myend=0x8257058
size=6, capacity=6
element 0: 1
element 1: 2
element 2: 3
element 3: 4
element 4: 5
element 5: 6
6
0
We can spot that the buffer size grows in a different way that in MSVC.
Simple experimentation shows that in MSVC’s implementation the buffer grows by ~50% each time it needs to be enlarged,
while GCC’s code enlarges it by 100% each time, i.e., doubles it.
51.4.4 std::map and std::set
The binary tree is another fundamental data structure. As its name states, this is a tree where each node has at most 2 links
to other nodes. Each node has key and/or value.
Binary trees are usually the structure used in the implementation of “dictionaries” of key-values (AKA “associative arrays”).
578
CHAPTER 51. C++ 51.4. STL
There are at least three important properties that a binary trees has:
• All keys are always stored in sorted form.
• Keys of any types can be stored easily. Binary tree algorithms are unaware of the key’s type, only a key comparison
function is required.
• Finding a specific key is relatively fast in comparison with lists and arrays.
Here is a very simple example: let’s store these numbers in a binary tree: 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 20, 99, 100, 101,
107, 1001, 1010.
..10.
1
.
0
.
5
.
3
.
2
..
6
..
9
.
100
.
20
.
12
.
11
..
99
.
107
.
101
.
1001
..
1010
All keys that are smaller than the node key’s value are stored on the left side. All keys that are bigger than the node
key’s value are stored on the right side.
Hence, the lookup algorithm is straightforward: if the value that you are looking for is smaller than the current node’s
key value: move left, if it is bigger: move right, stop if the value required is equal to the node key’s value. That is why the
searching algorithm may search for numbers, text strings, etc, as long as a key comparison function is provided.
All keys have unique values.
Having that, one needs ≈ log2 n steps in order to find a key in a balanced binary tree with n keys. This implies that ≈ 10
steps are needed ≈ 1000 keys, or ≈ 13 steps for ≈ 10000 keys. Not bad, but the tree has always to be balanced for this: i.e.,
the keys has to be distributed evenly on all levels. The insertion and removal operations do some maintenance to keep the
tree in a balanced state.
There are several popular balancing algorithms available, including the AVL tree and the red-black tree. The latter
extends each node with a “color” value to simplify the balancing process, hence, each node may be “red” or “black”.
Both GCC’s and MSVC’s std::map and std::set template implementations use red-black trees.
std::set contains only keys. std::map is the “extended” version of std::set: it also has a value at each node.
MSVC
#include <map>
#include <set>
#include <string>
#include <iostream>
// structure is not packed!
struct tree_node
{
struct tree_node *Left;
struct tree_node *Parent;
struct tree_node *Right;
char Color; // 0 - Red, 1 - Black
char Isnil;
//std::pair Myval;
unsigned int first; // called Myval in std::set
const char *second; // not present in std::set
};
struct tree_struct
{
struct tree_node *Myhead;
579
CHAPTER 51. C++ 51.4. STL
size_t Mysize;
};
void dump_tree_node (struct tree_node *n, bool is_set, bool traverse)
{
printf ("ptr=0x%p Left=0x%p Parent=0x%p Right=0x%p Color=%d Isnil=%dn",
n, n->Left, n->Parent, n->Right, n->Color, n->Isnil);
if (n->Isnil==0)
{
if (is_set)
printf ("first=%dn", n->first);
else
printf ("first=%d second=[%s]n", n->first, n->second);
}
if (traverse)
{
if (n->Isnil==1)
dump_tree_node (n->Parent, is_set, true);
else
{
if (n->Left->Isnil==0)
dump_tree_node (n->Left, is_set, true);
if (n->Right->Isnil==0)
dump_tree_node (n->Right, is_set, true);
};
};
};
const char* ALOT_OF_TABS="ttttttttttt";
void dump_as_tree (int tabs, struct tree_node *n, bool is_set)
{
if (is_set)
printf ("%dn", n->first);
else
printf ("%d [%s]n", n->first, n->second);
if (n->Left->Isnil==0)
{
printf ("%.*sL-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->Left, is_set);
};
if (n->Right->Isnil==0)
{
printf ("%.*sR-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->Right, is_set);
};
};
void dump_map_and_set(struct tree_struct *m, bool is_set)
{
printf ("ptr=0x%p, Myhead=0x%p, Mysize=%dn", m, m->Myhead, m->Mysize);
dump_tree_node (m->Myhead, is_set, true);
printf ("As a tree:n");
printf ("root----");
dump_as_tree (1, m->Myhead->Parent, is_set);
};
int main()
{
// map
std::map<int, const char*> m;
m[10]="ten";
m[20]="twenty";
m[3]="three";
m[101]="one hundred one";
m[100]="one hundred";
m[12]="twelve";
580
CHAPTER 51. C++ 51.4. STL
m[107]="one hundred seven";
m[0]="zero";
m[1]="one";
m[6]="six";
m[99]="ninety-nine";
m[5]="five";
m[11]="eleven";
m[1001]="one thousand one";
m[1010]="one thousand ten";
m[2]="two";
m[9]="nine";
printf ("dumping m as map:n");
dump_map_and_set ((struct tree_struct *)(void*)&m, false);
std::map<int, const char*>::iterator it1=m.begin();
printf ("m.begin():n");
dump_tree_node ((struct tree_node *)*(void**)&it1, false, false);
it1=m.end();
printf ("m.end():n");
dump_tree_node ((struct tree_node *)*(void**)&it1, false, false);
// set
std::set<int> s;
s.insert(123);
s.insert(456);
s.insert(11);
s.insert(12);
s.insert(100);
s.insert(1001);
printf ("dumping s as set:n");
dump_map_and_set ((struct tree_struct *)(void*)&s, true);
std::set<int>::iterator it2=s.begin();
printf ("s.begin():n");
dump_tree_node ((struct tree_node *)*(void**)&it2, true, false);
it2=s.end();
printf ("s.end():n");
dump_tree_node ((struct tree_node *)*(void**)&it2, true, false);
};
Listing 51.35: MSVC 2012
dumping m as map:
ptr=0x0020FE04, Myhead=0x005BB3A0, Mysize=17
ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1
ptr=0x005BB3C0 Left=0x005BB4C0 Parent=0x005BB3A0 Right=0x005BB440 Color=1 Isnil=0
first=10 second=[ten]
ptr=0x005BB4C0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB520 Color=1 Isnil=0
first=1 second=[one]
ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0
first=0 second=[zero]
ptr=0x005BB520 Left=0x005BB400 Parent=0x005BB4C0 Right=0x005BB4E0 Color=0 Isnil=0
first=5 second=[five]
ptr=0x005BB400 Left=0x005BB5A0 Parent=0x005BB520 Right=0x005BB3A0 Color=1 Isnil=0
first=3 second=[three]
ptr=0x005BB5A0 Left=0x005BB3A0 Parent=0x005BB400 Right=0x005BB3A0 Color=0 Isnil=0
first=2 second=[two]
ptr=0x005BB4E0 Left=0x005BB3A0 Parent=0x005BB520 Right=0x005BB5C0 Color=1 Isnil=0
first=6 second=[six]
ptr=0x005BB5C0 Left=0x005BB3A0 Parent=0x005BB4E0 Right=0x005BB3A0 Color=0 Isnil=0
first=9 second=[nine]
ptr=0x005BB440 Left=0x005BB3E0 Parent=0x005BB3C0 Right=0x005BB480 Color=1 Isnil=0
first=100 second=[one hundred]
ptr=0x005BB3E0 Left=0x005BB460 Parent=0x005BB440 Right=0x005BB500 Color=0 Isnil=0
first=20 second=[twenty]
ptr=0x005BB460 Left=0x005BB540 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0
first=12 second=[twelve]
ptr=0x005BB540 Left=0x005BB3A0 Parent=0x005BB460 Right=0x005BB3A0 Color=0 Isnil=0
first=11 second=[eleven]
ptr=0x005BB500 Left=0x005BB3A0 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0
581
CHAPTER 51. C++ 51.4. STL
first=99 second=[ninety-nine]
ptr=0x005BB480 Left=0x005BB420 Parent=0x005BB440 Right=0x005BB560 Color=0 Isnil=0
first=107 second=[one hundred seven]
ptr=0x005BB420 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB3A0 Color=1 Isnil=0
first=101 second=[one hundred one]
ptr=0x005BB560 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB580 Color=1 Isnil=0
first=1001 second=[one thousand one]
ptr=0x005BB580 Left=0x005BB3A0 Parent=0x005BB560 Right=0x005BB3A0 Color=0 Isnil=0
first=1010 second=[one thousand ten]
As a tree:
root----10 [ten]
L-------1 [one]
L-------0 [zero]
R-------5 [five]
L-------3 [three]
L-------2 [two]
R-------6 [six]
R-------9 [nine]
R-------100 [one hundred]
L-------20 [twenty]
L-------12 [twelve]
L-------11 [eleven]
R-------99 [ninety-nine]
R-------107 [one hundred seven]
L-------101 [one hundred one]
R-------1001 [one thousand one]
R-------1010 [one thousand ten]
m.begin():
ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0
first=0 second=[zero]
m.end():
ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1
dumping s as set:
ptr=0x0020FDFC, Myhead=0x005BB5E0, Mysize=6
ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1
ptr=0x005BB600 Left=0x005BB660 Parent=0x005BB5E0 Right=0x005BB620 Color=1 Isnil=0
first=123
ptr=0x005BB660 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB680 Color=1 Isnil=0
first=12
ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0
first=11
ptr=0x005BB680 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0
first=100
ptr=0x005BB620 Left=0x005BB5E0 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=0
first=456
ptr=0x005BB6A0 Left=0x005BB5E0 Parent=0x005BB620 Right=0x005BB5E0 Color=0 Isnil=0
first=1001
As a tree:
root----123
L-------12
L-------11
R-------100
R-------456
R-------1001
s.begin():
ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0
first=11
s.end():
ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1
The structure is not packed, so both char values occupy 4 bytes each.
As for std::map, first and second can be viewed as a single value of type std::pair. std::set has only one
value at this address in the structure instead.
The current size of the tree is always present, as in the case of the implementation of std::list in MSVC ( 51.4.2 on
page 568).
As in the case of std::list, the iterators are just pointers to nodes. The .begin() iterator points to the minimal
key. That pointer is not stored anywhere (as in lists), the minimal key of the tree is looked up every time. operator-- and
operator++ move the current node pointer to the predecessor or successor respectively, i.e., the nodes which have the
582
CHAPTER 51. C++ 51.4. STL
previous or next key. The algorithms for all these operations are explained in [Cor+09].
The .end() iterator points to the dummy node, it has 1 in Isnil, which implies that the node has no key and/or value.
It can be viewed as a “landing zone” in HDD10
. The “parent” field of the dummy node points to the root node, which serves
as a vertex of the tree and contains information.
GCC
#include <stdio.h>
#include <map>
#include <set>
#include <string>
#include <iostream>
struct map_pair
{
int key;
const char *value;
};
struct tree_node
{
int M_color; // 0 - Red, 1 - Black
struct tree_node *M_parent;
struct tree_node *M_left;
struct tree_node *M_right;
};
struct tree_struct
{
int M_key_compare;
struct tree_node M_header;
size_t M_node_count;
};
void dump_tree_node (struct tree_node *n, bool is_set, bool traverse, bool dump_keys_and_values⤦
)
{
printf ("ptr=0x%p M_left=0x%p M_parent=0x%p M_right=0x%p M_color=%dn",
n, n->M_left, n->M_parent, n->M_right, n->M_color);
void *point_after_struct=((char*)n)+sizeof(struct tree_node);
if (dump_keys_and_values)
{
if (is_set)
printf ("key=%dn", *(int*)point_after_struct);
else
{
struct map_pair *p=(struct map_pair *)point_after_struct;
printf ("key=%d value=[%s]n", p->key, p->value);
};
};
if (traverse==false)
return;
if (n->M_left)
dump_tree_node (n->M_left, is_set, traverse, dump_keys_and_values);
if (n->M_right)
dump_tree_node (n->M_right, is_set, traverse, dump_keys_and_values);
};
const char* ALOT_OF_TABS="ttttttttttt";
void dump_as_tree (int tabs, struct tree_node *n, bool is_set)
{
void *point_after_struct=((char*)n)+sizeof(struct tree_node);
10Hard disk drive
583
CHAPTER 51. C++ 51.4. STL
if (is_set)
printf ("%dn", *(int*)point_after_struct);
else
{
struct map_pair *p=(struct map_pair *)point_after_struct;
printf ("%d [%s]n", p->key, p->value);
}
if (n->M_left)
{
printf ("%.*sL-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->M_left, is_set);
};
if (n->M_right)
{
printf ("%.*sR-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->M_right, is_set);
};
};
void dump_map_and_set(struct tree_struct *m, bool is_set)
{
printf ("ptr=0x%p, M_key_compare=0x%x, M_header=0x%p, M_node_count=%dn",
m, m->M_key_compare, &m->M_header, m->M_node_count);
dump_tree_node (m->M_header.M_parent, is_set, true, true);
printf ("As a tree:n");
printf ("root----");
dump_as_tree (1, m->M_header.M_parent, is_set);
};
int main()
{
// map
std::map<int, const char*> m;
m[10]="ten";
m[20]="twenty";
m[3]="three";
m[101]="one hundred one";
m[100]="one hundred";
m[12]="twelve";
m[107]="one hundred seven";
m[0]="zero";
m[1]="one";
m[6]="six";
m[99]="ninety-nine";
m[5]="five";
m[11]="eleven";
m[1001]="one thousand one";
m[1010]="one thousand ten";
m[2]="two";
m[9]="nine";
printf ("dumping m as map:n");
dump_map_and_set ((struct tree_struct *)(void*)&m, false);
std::map<int, const char*>::iterator it1=m.begin();
printf ("m.begin():n");
dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, true);
it1=m.end();
printf ("m.end():n");
dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, false);
// set
std::set<int> s;
s.insert(123);
s.insert(456);
584
CHAPTER 51. C++ 51.4. STL
s.insert(11);
s.insert(12);
s.insert(100);
s.insert(1001);
printf ("dumping s as set:n");
dump_map_and_set ((struct tree_struct *)(void*)&s, true);
std::set<int>::iterator it2=s.begin();
printf ("s.begin():n");
dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, true);
it2=s.end();
printf ("s.end():n");
dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, false);
};
Listing 51.36: GCC 4.8.1
dumping m as map:
ptr=0x0028FE3C, M_key_compare=0x402b70, M_header=0x0028FE40, M_node_count=17
ptr=0x007A4988 M_left=0x007A4C00 M_parent=0x0028FE40 M_right=0x007A4B80 M_color=1
key=10 value=[ten]
ptr=0x007A4C00 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4C60 M_color=1
key=1 value=[one]
ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1
key=0 value=[zero]
ptr=0x007A4C60 M_left=0x007A4B40 M_parent=0x007A4C00 M_right=0x007A4C20 M_color=0
key=5 value=[five]
ptr=0x007A4B40 M_left=0x007A4CE0 M_parent=0x007A4C60 M_right=0x00000000 M_color=1
key=3 value=[three]
ptr=0x007A4CE0 M_left=0x00000000 M_parent=0x007A4B40 M_right=0x00000000 M_color=0
key=2 value=[two]
ptr=0x007A4C20 M_left=0x00000000 M_parent=0x007A4C60 M_right=0x007A4D00 M_color=1
key=6 value=[six]
ptr=0x007A4D00 M_left=0x00000000 M_parent=0x007A4C20 M_right=0x00000000 M_color=0
key=9 value=[nine]
ptr=0x007A4B80 M_left=0x007A49A8 M_parent=0x007A4988 M_right=0x007A4BC0 M_color=1
key=100 value=[one hundred]
ptr=0x007A49A8 M_left=0x007A4BA0 M_parent=0x007A4B80 M_right=0x007A4C40 M_color=0
key=20 value=[twenty]
ptr=0x007A4BA0 M_left=0x007A4C80 M_parent=0x007A49A8 M_right=0x00000000 M_color=1
key=12 value=[twelve]
ptr=0x007A4C80 M_left=0x00000000 M_parent=0x007A4BA0 M_right=0x00000000 M_color=0
key=11 value=[eleven]
ptr=0x007A4C40 M_left=0x00000000 M_parent=0x007A49A8 M_right=0x00000000 M_color=1
key=99 value=[ninety-nine]
ptr=0x007A4BC0 M_left=0x007A4B60 M_parent=0x007A4B80 M_right=0x007A4CA0 M_color=0
key=107 value=[one hundred seven]
ptr=0x007A4B60 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x00000000 M_color=1
key=101 value=[one hundred one]
ptr=0x007A4CA0 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x007A4CC0 M_color=1
key=1001 value=[one thousand one]
ptr=0x007A4CC0 M_left=0x00000000 M_parent=0x007A4CA0 M_right=0x00000000 M_color=0
key=1010 value=[one thousand ten]
As a tree:
root----10 [ten]
L-------1 [one]
L-------0 [zero]
R-------5 [five]
L-------3 [three]
L-------2 [two]
R-------6 [six]
R-------9 [nine]
R-------100 [one hundred]
L-------20 [twenty]
L-------12 [twelve]
L-------11 [eleven]
R-------99 [ninety-nine]
R-------107 [one hundred seven]
L-------101 [one hundred one]
R-------1001 [one thousand one]
R-------1010 [one thousand ten]
585
CHAPTER 51. C++ 51.4. STL
m.begin():
ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1
key=0 value=[zero]
m.end():
ptr=0x0028FE40 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4CC0 M_color=0
dumping s as set:
ptr=0x0028FE20, M_key_compare=0x8, M_header=0x0028FE24, M_node_count=6
ptr=0x007A1E80 M_left=0x01D5D890 M_parent=0x0028FE24 M_right=0x01D5D850 M_color=1
key=123
ptr=0x01D5D890 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8B0 M_color=1
key=12
ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0
key=11
ptr=0x01D5D8B0 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0
key=100
ptr=0x01D5D850 M_left=0x00000000 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=1
key=456
ptr=0x01D5D8D0 M_left=0x00000000 M_parent=0x01D5D850 M_right=0x00000000 M_color=0
key=1001
As a tree:
root----123
L-------12
L-------11
R-------100
R-------456
R-------1001
s.begin():
ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0
key=11
s.end():
ptr=0x0028FE24 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=0
GCC’s implementation is very similar 11
. The only difference is the absence of the Isnil field, so the structure occupies
slightly less space in memory than its implementation in MSVC. The dummy node is also used as a place to point the .end()
iterator also has no key and/or value.
Rebalancing demo (GCC)
Here is also a demo showing us how a tree is rebalanced after some insertions.
Listing 51.37: GCC
#include <stdio.h>
#include <map>
#include <set>
#include <string>
#include <iostream>
struct map_pair
{
int key;
const char *value;
};
struct tree_node
{
int M_color; // 0 - Red, 1 - Black
struct tree_node *M_parent;
struct tree_node *M_left;
struct tree_node *M_right;
};
struct tree_struct
{
int M_key_compare;
struct tree_node M_header;
size_t M_node_count;
};
11http://go.yurichev.com/17084
586
CHAPTER 51. C++ 51.4. STL
const char* ALOT_OF_TABS="ttttttttttt";
void dump_as_tree (int tabs, struct tree_node *n)
{
void *point_after_struct=((char*)n)+sizeof(struct tree_node);
printf ("%dn", *(int*)point_after_struct);
if (n->M_left)
{
printf ("%.*sL-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->M_left);
};
if (n->M_right)
{
printf ("%.*sR-------", tabs, ALOT_OF_TABS);
dump_as_tree (tabs+1, n->M_right);
};
};
void dump_map_and_set(struct tree_struct *m)
{
printf ("root----");
dump_as_tree (1, m->M_header.M_parent);
};
int main()
{
std::set<int> s;
s.insert(123);
s.insert(456);
printf ("123, 456 are insertedn");
dump_map_and_set ((struct tree_struct *)(void*)&s);
s.insert(11);
s.insert(12);
printf ("n");
printf ("11, 12 are insertedn");
dump_map_and_set ((struct tree_struct *)(void*)&s);
s.insert(100);
s.insert(1001);
printf ("n");
printf ("100, 1001 are insertedn");
dump_map_and_set ((struct tree_struct *)(void*)&s);
s.insert(667);
s.insert(1);
s.insert(4);
s.insert(7);
printf ("n");
printf ("667, 1, 4, 7 are insertedn");
dump_map_and_set ((struct tree_struct *)(void*)&s);
printf ("n");
};
Listing 51.38: GCC 4.8.1
123, 456 are inserted
root----123
R-------456
11, 12 are inserted
root----123
L-------11
R-------12
R-------456
100, 1001 are inserted
root----123
L-------12
L-------11
587
CHAPTER 51. C++ 51.4. STL
R-------100
R-------456
R-------1001
667, 1, 4, 7 are inserted
root----12
L-------4
L-------1
R-------11
L-------7
R-------123
L-------100
R-------667
L-------456
R-------1001
588
CHAPTER 52. NEGATIVE ARRAY INDICES
Chapter 52
Negative array indices
It’s possible to address the space before an array by supplying a negative index, e.g., array[−1].
It’s very hard to say why one should use it, I know probably only one practical application of this technique. C/C++ array
elements indices start at 0, but some PLs have a first index at 1 (at least FORTRAN). Programmers may still have this habit,
so using this little trick, it’s possible to address the first element in C/C++ using index 1:
#include <stdio.h>
int main()
{
int random_value=0x11223344;
unsigned char array[10];
int i;
unsigned char *fakearray=&array[-1];
for (i=0; i<10; i++)
array[i]=i;
printf ("first element %dn", fakearray[1]);
printf ("second element %dn", fakearray[2]);
printf ("last element %dn", fakearray[10]);
printf ("array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02Xn",
array[-1],
array[-2],
array[-3],
array[-4]);
};
Listing 52.1: Non-optimizing MSVC 2010
1 $SG2751 DB 'first element %d', 0aH, 00H
2 $SG2752 DB 'second element %d', 0aH, 00H
3 $SG2753 DB 'last element %d', 0aH, 00H
4 $SG2754 DB 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4'
5 DB ']=%02X', 0aH, 00H
6
7 _fakearray$ = -24 ; size = 4
8 _random_value$ = -20 ; size = 4
9 _array$ = -16 ; size = 10
10 _i$ = -4 ; size = 4
11 _main PROC
12 push ebp
13 mov ebp, esp
14 sub esp, 24
15 mov DWORD PTR _random_value$[ebp], 287454020 ; 11223344H
16 ; set fakearray[] one byte earlier before array[]
17 lea eax, DWORD PTR _array$[ebp]
18 add eax, -1 ; eax=eax-1
19 mov DWORD PTR _fakearray$[ebp], eax
20 mov DWORD PTR _i$[ebp], 0
21 jmp SHORT $LN3@main
22 ; fill array[] with 0..9
23 $LN2@main:
24 mov ecx, DWORD PTR _i$[ebp]
589
CHAPTER 52. NEGATIVE ARRAY INDICES
25 add ecx, 1
26 mov DWORD PTR _i$[ebp], ecx
27 $LN3@main:
28 cmp DWORD PTR _i$[ebp], 10
29 jge SHORT $LN1@main
30 mov edx, DWORD PTR _i$[ebp]
31 mov al, BYTE PTR _i$[ebp]
32 mov BYTE PTR _array$[ebp+edx], al
33 jmp SHORT $LN2@main
34 $LN1@main:
35 mov ecx, DWORD PTR _fakearray$[ebp]
36 ; ecx=address of fakearray[0], ecx+1 is fakearray[1] or array[0]
37 movzx edx, BYTE PTR [ecx+1]
38 push edx
39 push OFFSET $SG2751 ; 'first element %d'
40 call _printf
41 add esp, 8
42 mov eax, DWORD PTR _fakearray$[ebp]
43 ; eax=address of fakearray[0], eax+2 is fakearray[2] or array[1]
44 movzx ecx, BYTE PTR [eax+2]
45 push ecx
46 push OFFSET $SG2752 ; 'second element %d'
47 call _printf
48 add esp, 8
49 mov edx, DWORD PTR _fakearray$[ebp]
50 ; edx=address of fakearray[0], edx+10 is fakearray[10] or array[9]
51 movzx eax, BYTE PTR [edx+10]
52 push eax
53 push OFFSET $SG2753 ; 'last element %d'
54 call _printf
55 add esp, 8
56 ; subtract 4, 3, 2 and 1 from pointer to array[0] in order to find values before array[]
57 lea ecx, DWORD PTR _array$[ebp]
58 movzx edx, BYTE PTR [ecx-4]
59 push edx
60 lea eax, DWORD PTR _array$[ebp]
61 movzx ecx, BYTE PTR [eax-3]
62 push ecx
63 lea edx, DWORD PTR _array$[ebp]
64 movzx eax, BYTE PTR [edx-2]
65 push eax
66 lea ecx, DWORD PTR _array$[ebp]
67 movzx edx, BYTE PTR [ecx-1]
68 push edx
69 push OFFSET $SG2754 ; 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02⤦
X'
70 call _printf
71 add esp, 20
72 xor eax, eax
73 mov esp, ebp
74 pop ebp
75 ret 0
76 _main ENDP
So we have array[] of ten elements, filled with 0...9 bytes. Then we have the fakearray[] pointer, which points
one byte before array[]. fakearray[1] points exactly to array[0]. But we are still curious, what is there before
array[]? I added random_value before array[] and set it to 0x11223344. The non-optimizing compiler allocated
the variables in the order they were declared, so yes, the 32-bit random_value is right before the array.
I ran it, and:
first element 0
second element 1
last element 9
array[-1]=11, array[-2]=22, array[-3]=33, array[-4]=44
Here is the stack fragment I copypasted from OllyDbg’s stack window (with my comments):
Listing 52.2: Non-optimizing MSVC 2010
CPU Stack
Address Value
590
CHAPTER 52. NEGATIVE ARRAY INDICES
001DFBCC /001DFBD3 ; fakearray pointer
001DFBD0 |11223344 ; random_value
001DFBD4 |03020100 ; 4 bytes of array[]
001DFBD8 |07060504 ; 4 bytes of array[]
001DFBDC |00CB0908 ; random garbage + 2 last bytes of array[]
001DFBE0 |0000000A ; last i value after loop was finished
001DFBE4 |001DFC2C ; saved EBP value
001DFBE8 00CB129D ; Return Address
The pointer to the fakearray[] (0x001DFBD3) is indeed the address of array[] in the stack (0x001DFBD4), but
minus 1 byte.
It’s still very hackish and dubious trick, I doubt anyone should use it in production code, but as a demonstration, it fits
perfectly here.
591
CHAPTER 53. WINDOWS 16-BIT
Chapter 53
Windows 16-bit
16-bit Windows programs are rare nowadays, but in the cases of retrocomputing or dongle hacking ( 78 on page 744), I
sometimes dig into these.
16-bit Windows versions were up to 3.11. 96/98/ME also support 16-bit code, as well as the 32-bit versions of the
Windows NT line. The 64-bit versions of Windows NT line do not support 16-bit executable code at all.
The code resembles MS-DOS’s one.
Executable files are of type NE-type (so-called “new executable”).
All examples considered here were compiled by the OpenWatcom 1.9 compiler, using these switches:
wcl.exe -i=C:/WATCOM/h/win/ -s -os -bt=windows -bcl=windows example.c
53.1 Example#1
#include <windows.h>
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
MessageBeep(MB_ICONEXCLAMATION);
return 0;
};
WinMain proc near
push bp
mov bp, sp
mov ax, 30h ; '0' ; MB_ICONEXCLAMATION constant
push ax
call MESSAGEBEEP
xor ax, ax ; return 0
pop bp
retn 0Ah
WinMain endp
Seems to be easy, so far.
53.2 Example #2
#include <windows.h>
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL);
return 0;
};
592
CHAPTER 53. WINDOWS 16-BIT 53.3. EXAMPLE #3
WinMain proc near
push bp
mov bp, sp
xor ax, ax ; NULL
push ax
push ds
mov ax, offset aHelloWorld ; 0x18. "hello, world"
push ax
push ds
mov ax, offset aCaption ; 0x10. "caption"
push ax
mov ax, 3 ; MB_YESNOCANCEL
push ax
call MESSAGEBOX
xor ax, ax ; return 0
pop bp
retn 0Ah
WinMain endp
dseg02:0010 aCaption db 'caption',0
dseg02:0018 aHelloWorld db 'hello, world',0
Couple important things here: the PASCAL calling convention dictates passing the first argument first (MB_YESNOCANCEL),
and the last argument—last (NULL). This convention also tells the callee to restore the stack pointer: hence the RETN in-
struction has 0Ah as argument, which implies that the pointer has to be increased by 10 bytes when the function exits. It is
like stdcall ( 64.2 on page 663), but the arguments are passed in “natural” order.
The pointers are passed in pairs: first the data segment is passed, then the pointer inside the segment. There is only one
segment in this example, so DS always points to the data segment of the executable.
53.3 Example #3
#include <windows.h>
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
int result=MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL);
if (result==IDCANCEL)
MessageBox (NULL, "you pressed cancel", "caption", MB_OK);
else if (result==IDYES)
MessageBox (NULL, "you pressed yes", "caption", MB_OK);
else if (result==IDNO)
MessageBox (NULL, "you pressed no", "caption", MB_OK);
return 0;
};
WinMain proc near
push bp
mov bp, sp
xor ax, ax ; NULL
push ax
push ds
mov ax, offset aHelloWorld ; "hello, world"
push ax
push ds
mov ax, offset aCaption ; "caption"
push ax
mov ax, 3 ; MB_YESNOCANCEL
push ax
call MESSAGEBOX
cmp ax, 2 ; IDCANCEL
jnz short loc_2F
xor ax, ax
593
CHAPTER 53. WINDOWS 16-BIT 53.4. EXAMPLE #4
push ax
push ds
mov ax, offset aYouPressedCanc ; "you pressed cancel"
jmp short loc_49
loc_2F:
cmp ax, 6 ; IDYES
jnz short loc_3D
xor ax, ax
push ax
push ds
mov ax, offset aYouPressedYes ; "you pressed yes"
jmp short loc_49
loc_3D:
cmp ax, 7 ; IDNO
jnz short loc_57
xor ax, ax
push ax
push ds
mov ax, offset aYouPressedNo ; "you pressed no"
loc_49:
push ax
push ds
mov ax, offset aCaption ; "caption"
push ax
xor ax, ax
push ax
call MESSAGEBOX
loc_57:
xor ax, ax
pop bp
retn 0Ah
WinMain endp
Somewhat extended example from the previous section.
53.4 Example #4
#include <windows.h>
int PASCAL func1 (int a, int b, int c)
{
return a*b+c;
};
long PASCAL func2 (long a, long b, long c)
{
return a*b+c;
};
long PASCAL func3 (long a, long b, long c, int d)
{
return a*b+c-d;
};
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
func1 (123, 456, 789);
func2 (600000, 700000, 800000);
func3 (600000, 700000, 800000, 123);
return 0;
};
func1 proc near
c = word ptr 4
594
CHAPTER 53. WINDOWS 16-BIT 53.4. EXAMPLE #4
b = word ptr 6
a = word ptr 8
push bp
mov bp, sp
mov ax, [bp+a]
imul [bp+b]
add ax, [bp+c]
pop bp
retn 6
func1 endp
func2 proc near
arg_0 = word ptr 4
arg_2 = word ptr 6
arg_4 = word ptr 8
arg_6 = word ptr 0Ah
arg_8 = word ptr 0Ch
arg_A = word ptr 0Eh
push bp
mov bp, sp
mov ax, [bp+arg_8]
mov dx, [bp+arg_A]
mov bx, [bp+arg_4]
mov cx, [bp+arg_6]
call sub_B2 ; long 32-bit multiplication
add ax, [bp+arg_0]
adc dx, [bp+arg_2]
pop bp
retn 12
func2 endp
func3 proc near
arg_0 = word ptr 4
arg_2 = word ptr 6
arg_4 = word ptr 8
arg_6 = word ptr 0Ah
arg_8 = word ptr 0Ch
arg_A = word ptr 0Eh
arg_C = word ptr 10h
push bp
mov bp, sp
mov ax, [bp+arg_A]
mov dx, [bp+arg_C]
mov bx, [bp+arg_6]
mov cx, [bp+arg_8]
call sub_B2 ; long 32-bit multiplication
mov cx, [bp+arg_2]
add cx, ax
mov bx, [bp+arg_4]
adc bx, dx ; BX=high part, CX=low part
mov ax, [bp+arg_0]
cwd ; AX=low part d, DX=high part d
sub cx, ax
mov ax, cx
sbb bx, dx
mov dx, bx
pop bp
retn 14
func3 endp
WinMain proc near
push bp
mov bp, sp
mov ax, 123
push ax
595
CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5
mov ax, 456
push ax
mov ax, 789
push ax
call func1
mov ax, 9 ; high part of 600000
push ax
mov ax, 27C0h ; low part of 600000
push ax
mov ax, 0Ah ; high part of 700000
push ax
mov ax, 0AE60h ; low part of 700000
push ax
mov ax, 0Ch ; high part of 800000
push ax
mov ax, 3500h ; low part of 800000
push ax
call func2
mov ax, 9 ; high part of 600000
push ax
mov ax, 27C0h ; low part of 600000
push ax
mov ax, 0Ah ; high part of 700000
push ax
mov ax, 0AE60h ; low part of 700000
push ax
mov ax, 0Ch ; high part of 800000
push ax
mov ax, 3500h ; low part of 800000
push ax
mov ax, 7Bh ; 123
push ax
call func3
xor ax, ax ; return 0
pop bp
retn 0Ah
WinMain endp
32-bit values (the long data type implies 32 bits, while int is 16-bit) in 16-bit code (both MS-DOS and Win16) are passed
in pairs. It is just like when 64-bit values are used in a 32-bit environment ( 24 on page 403).
sub_B2 here is a library function written by the compiler’s developers that does “long multiplication”, i.e., multiplies
two 32-bit values. Other compiler functions that do the same are listed here: E on page 950, D on page 949.
The ADD/ADC instruction pair is used for addition of compound values: ADD may set/clear the CF flag, and ADC uses it
after.
The SUB/SBB instruction pair is used for subtraction: SUB may set/clear the CF flag, SBB uses it after.
32-bit values are returned from functions in the DX:AX register pair.
Constants are also passed in pairs in WinMain() here.
The int-typed 123 constant is first converted according to its sign into a 32-bit value using the CWD instruction.
53.5 Example #5
#include <windows.h>
int PASCAL string_compare (char *s1, char *s2)
{
while (1)
{
if (*s1!=*s2)
return 0;
if (*s1==0 || *s2==0)
return 1; // end of string
s1++;
s2++;
};
};
596
CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5
int PASCAL string_compare_far (char far *s1, char far *s2)
{
while (1)
{
if (*s1!=*s2)
return 0;
if (*s1==0 || *s2==0)
return 1; // end of string
s1++;
s2++;
};
};
void PASCAL remove_digits (char *s)
{
while (*s)
{
if (*s>='0' && *s<='9')
*s='-';
s++;
};
};
char str[]="hello 1234 world";
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
string_compare ("asd", "def");
string_compare_far ("asd", "def");
remove_digits (str);
MessageBox (NULL, str, "caption", MB_YESNOCANCEL);
return 0;
};
string_compare proc near
arg_0 = word ptr 4
arg_2 = word ptr 6
push bp
mov bp, sp
push si
mov si, [bp+arg_0]
mov bx, [bp+arg_2]
loc_12: ; CODE XREF: string_compare+21j
mov al, [bx]
cmp al, [si]
jz short loc_1C
xor ax, ax
jmp short loc_2B
loc_1C: ; CODE XREF: string_compare+Ej
test al, al
jz short loc_22
jnz short loc_27
loc_22: ; CODE XREF: string_compare+16j
mov ax, 1
jmp short loc_2B
loc_27: ; CODE XREF: string_compare+18j
inc bx
inc si
597
CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5
jmp short loc_12
loc_2B: ; CODE XREF: string_compare+12j
; string_compare+1Dj
pop si
pop bp
retn 4
string_compare endp
string_compare_far proc near ; CODE XREF: WinMain+18p
arg_0 = word ptr 4
arg_2 = word ptr 6
arg_4 = word ptr 8
arg_6 = word ptr 0Ah
push bp
mov bp, sp
push si
mov si, [bp+arg_0]
mov bx, [bp+arg_4]
loc_3A: ; CODE XREF: string_compare_far+35j
mov es, [bp+arg_6]
mov al, es:[bx]
mov es, [bp+arg_2]
cmp al, es:[si]
jz short loc_4C
xor ax, ax
jmp short loc_67
loc_4C: ; CODE XREF: string_compare_far+16j
mov es, [bp+arg_6]
cmp byte ptr es:[bx], 0
jz short loc_5E
mov es, [bp+arg_2]
cmp byte ptr es:[si], 0
jnz short loc_63
loc_5E: ; CODE XREF: string_compare_far+23j
mov ax, 1
jmp short loc_67
loc_63: ; CODE XREF: string_compare_far+2Cj
inc bx
inc si
jmp short loc_3A
loc_67: ; CODE XREF: string_compare_far+1Aj
; string_compare_far+31j
pop si
pop bp
retn 8
string_compare_far endp
remove_digits proc near ; CODE XREF: WinMain+1Fp
arg_0 = word ptr 4
push bp
mov bp, sp
mov bx, [bp+arg_0]
loc_72: ; CODE XREF: remove_digits+18j
mov al, [bx]
test al, al
598
CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5
jz short loc_86
cmp al, 30h ; '0'
jb short loc_83
cmp al, 39h ; '9'
ja short loc_83
mov byte ptr [bx], 2Dh ; '-'
loc_83: ; CODE XREF: remove_digits+Ej
; remove_digits+12j
inc bx
jmp short loc_72
loc_86: ; CODE XREF: remove_digits+Aj
pop bp
retn 2
remove_digits endp
WinMain proc near ; CODE XREF: start+EDp
push bp
mov bp, sp
mov ax, offset aAsd ; "asd"
push ax
mov ax, offset aDef ; "def"
push ax
call string_compare
push ds
mov ax, offset aAsd ; "asd"
push ax
push ds
mov ax, offset aDef ; "def"
push ax
call string_compare_far
mov ax, offset aHello1234World ; "hello 1234 world"
push ax
call remove_digits
xor ax, ax
push ax
push ds
mov ax, offset aHello1234World ; "hello 1234 world"
push ax
push ds
mov ax, offset aCaption ; "caption"
push ax
mov ax, 3 ; MB_YESNOCANCEL
push ax
call MESSAGEBOX
xor ax, ax
pop bp
retn 0Ah
WinMain endp
Here we see a difference between the so-called “near” pointers and the “far” pointers: another weird artefact of segmented
memory in 16-bit 8086.
You can read more about it here: 94 on page 880.
“near” pointers are those which point within the current data segment. Hence, the string_compare() function takes
only two 16-bit pointers, and accesses the data from the segment that DS points to (Themov al, [bx] instruction actually
works like mov al, ds:[bx]—DS is implicit here).
“far” pointers are those which may point to data in another memory segment. Hence string_compare_far() takes
the 16-bit pair as a pointer, loads the high part of it in the ES segment register and accesses the data through it (mov al,
es:[bx]). “far” pointers are also used in my MessageBox() win16 example: 53.2 on page 592. Indeed, the Windows
kernel is not aware which data segment to use when accessing text strings, so it need the complete information.
The reason for this distinction is that a compact program may use just one 64kb data segment, so it doesn’t need to pass
the high part of the address, which is always the same. A bigger program may use several 64kb data segments, so it needs
to specify the segment of the data each time.
It’s the same story for code segments. A compact program may have all executable code within one 64kb-segment, then
all functions in it will be called using the CALL NEAR instruction, and the code flow will be returned using RETN. But if
there are several code segments, then the address of the function is to be specified by a pair, it is to be called using the CALL
FAR instruction, and the code flow is to be returned using RETF.
599
CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6
This is what is set in the compiler by specifying “memory model”.
The compilers targeting MS-DOS and Win16 have specific libraries for each memory model: they differ by pointer types
for code and data.
53.6 Example #6
#include <windows.h>
#include <time.h>
#include <stdio.h>
char strbuf[256];
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
struct tm *t;
time_t unix_time;
unix_time=time(NULL);
t=localtime (&unix_time);
sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t->⤦
tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
MessageBox (NULL, strbuf, "caption", MB_OK);
return 0;
};
WinMain proc near
var_4 = word ptr -4
var_2 = word ptr -2
push bp
mov bp, sp
push ax
push ax
xor ax, ax
call time_
mov [bp+var_4], ax ; low part of UNIX time
mov [bp+var_2], dx ; high part of UNIX time
lea ax, [bp+var_4] ; take a pointer of high part
call localtime_
mov bx, ax ; t
push word ptr [bx] ; second
push word ptr [bx+2] ; minute
push word ptr [bx+4] ; hour
push word ptr [bx+6] ; day
push word ptr [bx+8] ; month
mov ax, [bx+0Ah] ; year
add ax, 1900
push ax
mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d"
push ax
mov ax, offset strbuf
push ax
call sprintf_
add sp, 10h
xor ax, ax ; NULL
push ax
push ds
mov ax, offset strbuf
push ax
600
CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6
push ds
mov ax, offset aCaption ; "caption"
push ax
xor ax, ax ; MB_OK
push ax
call MESSAGEBOX
xor ax, ax
mov sp, bp
pop bp
retn 0Ah
WinMain endp
UNIX time is a 32-bit value, so it is returned in the DX:AX register pair and stored in two local 16-bit variables. Then
a pointer to the pair is passed to the localtime() function. The localtime() function has a struct tm allocated
somewhere in the guts of the C library, so only a pointer to it is returned. By the way, this also implies that the function
cannot be called again until its results are used.
For the time() and localtime() functions, a Watcom calling convention is used here: the first four arguments are
passed in the AX, DX, BX and CX, registers, and the rest arguments are via the stack. The functions using this convention
are also marked by underscore at the end of their name.
sprintf() does not use the PASCAL calling convention, nor the Watcom one, so the arguments are passed in the
normal cdecl way ( 64.1 on page 663).
53.6.1 Global variables
This is the same example, but now these variables are global:
#include <windows.h>
#include <time.h>
#include <stdio.h>
char strbuf[256];
struct tm *t;
time_t unix_time;
int PASCAL WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
unix_time=time(NULL);
t=localtime (&unix_time);
sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t->⤦
tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
MessageBox (NULL, strbuf, "caption", MB_OK);
return 0;
};
unix_time_low dw 0
unix_time_high dw 0
t dw 0
WinMain proc near
push bp
mov bp, sp
xor ax, ax
call time_
mov unix_time_low, ax
mov unix_time_high, dx
mov ax, offset unix_time_low
call localtime_
mov bx, ax
mov t, ax ; will not be used in future...
push word ptr [bx] ; seconds
push word ptr [bx+2] ; minutes
601
CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6
push word ptr [bx+4] ; hour
push word ptr [bx+6] ; day
push word ptr [bx+8] ; month
mov ax, [bx+0Ah] ; year
add ax, 1900
push ax
mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d"
push ax
mov ax, offset strbuf
push ax
call sprintf_
add sp, 10h
xor ax, ax ; NULL
push ax
push ds
mov ax, offset strbuf
push ax
push ds
mov ax, offset aCaption ; "caption"
push ax
xor ax, ax ; MB_OK
push ax
call MESSAGEBOX
xor ax, ax ; return 0
pop bp
retn 0Ah
WinMain endp
t is not to be used, but the compiler emitted the code which stores the value. Because it is not sure, maybe that value
will eventually be used in some other module.
602
Part IV
Java
603
CHAPTER 54. JAVA
Chapter 54
Java
54.1 Introduction
There are some well-known decompilers for Java (or JVM bytecode in general) 1
.
The reason of this is because JVM-bytecode decompiling is somewhat easier than for lower level x86 code:
• There are much more information about data types.
• JVM memory model is much more rigorous and outlined.
• Java compiler don’t do any optimization job (JVM JIT2
does at runtime), so bytecode in class files is usually pretty
readable.
When JVM bytecode knowledge may be useful?
• Quick-and-dirty patching tasks of class files without need to recompile decompiler’s results.
• Analysing obfuscated code.
• Build your own obfuscator.
• Build compiler codegenerator (back-end) targetting JVM (like Scala, Clojure, etc 3
).
Let’s start with simple pieces of code. JDK 1.7 is used everywhere, unless mentioned otherwise.
This command to decompile class files was used everywhere : javap -c -verbose
This book was used by me while preparing all examples : [Jav13].
54.2 Returning a value
Probably the simplest Java function is one which returns some value. Oh, and we must keep in mind that there are no “free”
functions in Java in common sense, they are “methods”. Each method is related to some class, so it’s not possible to define
method outside of a class. But I’ll also call them “functions” anyway, because I used to.
public class ret
{
public static int main(String[] args)
{
return 0;
}
}
I’ll compile it:
javac ret.java
…and decompile it using standard Java utility:
javap -c -verbose ret.class
And what I’ve got:
1For example, JAD: http://varaneckas.com/jad/
2Just-in-time compilation
3Full list: http://en.wikipedia.org/wiki/List_of_JVM_languages
604
CHAPTER 54. JAVA 54.2. RETURNING A VALUE
Listing 54.1: JDK 1.7 (excerpt)
public static int main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: iconst_0
1: ireturn
Java developers decide that 0 is one of the busiest constants in programming, so there are separate short one-byte
iconst_0 instruction which pushes 0 4
. There are also iconst_1 (which pushes 1), iconst_2, etc, up to iconst_5.
There are also iconst_m1 which pushes -1.
Stack is used in JVM for data passing into functions to be called and also returning values. So iconst_0 pushed 0 into
stack. ireturn returns integer value (i in name mean integer) from the TOS5
.
Let’s rewrite our example slightly, now we return 1234:
public class ret
{
public static int main(String[] args)
{
return 1234;
}
}
…we got:
Listing 54.2: JDK 1.7 (excerpt)
public static int main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: sipush 1234
3: ireturn
sipush (short integer) pushes 1234 value into stack. short in name implies a 16-bit value is to be pushed. 1234 number
is indeed well fit in 16-bit value.
What about larger values?
public class ret
{
public static int main(String[] args)
{
return 12345678;
}
}
Listing 54.3: Constant pool
...
#2 = Integer 12345678
...
public static int main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: ldc #2 // int 12345678
2: ireturn
It’s not possible to encode a 32-bit number in a JVM instruction opcode, developers didn’t left such possibility. So 32-bit
number 12345678 is stored in so called “constant pool” which is, let’s say, library of most used constants (including strings,
objects, etc).
This way of passing constants is not unique to JVM. MIPS, ARM and other RISC CPUs also can’t encode 32-bit numbers
in 32-bit opcode, so RISC CPU code (including MIPS and ARM) has to construct values in several steps, or to keep them in
data segment: 28.3 on page 445, 29.1 on page 449.
MIPS code is also traditionally has constant pool, named “literal pool”, these are segments called “.lit4” (for 32-bit single
precision float point number constants storage) and “.lit8” (for 64-bit double precision float point number constants storage).
Let’s also try other data types!
Boolean:
4Just like in MIPS, where a separate register for zero constant exists : 3.5.2 on page 17.
5Top Of Stack
605
CHAPTER 54. JAVA 54.2. RETURNING A VALUE
public class ret
{
public static boolean main(String[] args)
{
return true;
}
}
public static boolean main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: iconst_1
1: ireturn
This JVM bytecode is no different from one returning integer 1. 32-bit data slots in stack are also used here for boolean
values, like in C/C++. But one could not use returned boolean value as integer or vice versa — type information is stored in
a class file and checked at runtime.
The same story about 16-bit short:
public class ret
{
public static short main(String[] args)
{
return 1234;
}
}
public static short main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: sipush 1234
3: ireturn
…and char!
public class ret
{
public static char main(String[] args)
{
return 'A';
}
}
public static char main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: bipush 65
2: ireturn
bipush mean “push byte”. Needless to say that char in Java is 16-bit UTF-16 character, and it’s equivalent to short, but
ASCII code of “A” character is 65, and it’s possible to use instruction for passing byte into stack.
Let’s also try byte:
public class retc
{
public static byte main(String[] args)
{
return 123;
}
}
public static byte main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: bipush 123
2: ireturn
606
CHAPTER 54. JAVA 54.2. RETURNING A VALUE
One may ask, why to bother with 16-bit short date type which is internally works as 32-bit integer? Why use char data
type if it is the same as short data type?
The answer is simple: for data type control and source code readability. char may essentially be the same as short but
we quickly grasp that it’s placeholder for UTF-16 character, and not for some other integer value. When using short we may
show to everyone that a variable range is limited by 16 bits. It’s a very good idea to use boolean type where it needs to,
instead of C-style int for the same purpose.
There are also 64-bit integer data type in Java:
public class ret3
{
public static long main(String[] args)
{
return 1234567890123456789L;
}
}
Listing 54.4: Constant pool
...
#2 = Long 1234567890123456789l
...
public static long main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: ldc2_w #2 // long 1234567890123456789l
3: lreturn
The 64-bit number is also stored in constant pool, ldc2_w loads it and lreturn (long return) returns it.
ldc2_w instruction is also used to load double precision floating point numbers (which also occupies 64 bits) from
constant pool:
public class ret
{
public static double main(String[] args)
{
return 123.456d;
}
}
Listing 54.5: Constant pool
...
#2 = Double 123.456d
...
public static double main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: ldc2_w #2 // double 123.456d
3: dreturn
dreturn stands for “return double”.
And finally, single precision floating point number:
public class ret
{
public static float main(String[] args)
{
return 123.456f;
}
}
Listing 54.6: Constant pool
...
#2 = Float 123.456f
...
607
CHAPTER 54. JAVA 54.3. SIMPLE CALCULATING FUNCTIONS
public static float main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=1, args_size=1
0: ldc #2 // float 123.456f
2: freturn
ldc instruction used here is the same as used for 32-bit integer numbers loading from constant pool. freturn stands
for “return float”.
Now what about function returning nothing?
public class ret
{
public static void main(String[] args)
{
return;
}
}
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=0, locals=1, args_size=1
0: return
This implies, return instruction is used to return control without returning actual value. Knowing all this, it’s very easy
to deduct function (or method) returning type from the last instruction.
54.3 Simple calculating functions
Let’s continue with simple calculating functions.
public class calc
{
public static int half(int a)
{
return a/2;
}
}
This is the case when iconst_2 instruction is used:
public static int half(int);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: iload_0
1: iconst_2
2: idiv
3: ireturn
iload_0 takes zeroth function argument and pushes it to stack. iconst_2 pushes 2 into stack. After these two
instructions execution, this is how stack looks like:
+---+
TOS ->| 2 |
+---+
| a |
+---+
idiv just takes two values at the TOS, divides one by another and leave result at TOS:
+--------+
TOS ->| result |
+--------+
ireturn takes it and returns.
Let’s proceed to double precision floating point numbers:
608
CHAPTER 54. JAVA 54.3. SIMPLE CALCULATING FUNCTIONS
public class calc
{
public static double half_double(double a)
{
return a/2.0;
}
}
Listing 54.7: Constant pool
...
#2 = Double 2.0d
...
public static double half_double(double);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=4, locals=2, args_size=1
0: dload_0
1: ldc2_w #2 // double 2.0d
4: ddiv
5: dreturn
It’s the very same, but ldc2_w instruction is used to load constant of 2.0 from constant pool. Also, all other three
instructions has d prefix, meaning they work with double data type values.
Let’s now use two arguments function:
public class calc
{
public static int sum(int a, int b)
{
return a+b;
}
}
public static int sum(int, int);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=2
0: iload_0
1: iload_1
2: iadd
3: ireturn
iload_0 loads first function argument (a), iload_2 — second (b). Here is a stack after both instruction executed:
+---+
TOS ->| b |
+---+
| a |
+---+
iadd adds two values and leave result at TOS:
+--------+
TOS ->| result |
+--------+
Let’s extend this example to long data type:
public static long lsum(long a, long b)
{
return a+b;
}
…we got:
public static long lsum(long, long);
flags: ACC_PUBLIC, ACC_STATIC
Code:
609
CHAPTER 54. JAVA 54.4. JVM MEMORY MODEL
stack=4, locals=4, args_size=2
0: lload_0
1: lload_2
2: ladd
3: lreturn
The second lload instruction takes second argument from 2nd slot. That’s because 64-bit long value occupies exactly
two 32-bit slots.
Slightly more complex example:
public class calc
{
public static int mult_add(int a, int b, int c)
{
return a*b+c;
}
}
public static int mult_add(int, int, int);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=3, args_size=3
0: iload_0
1: iload_1
2: imul
3: iload_2
4: iadd
5: ireturn
First step is multiplication. Product is left at the TOS:
+---------+
TOS ->| product |
+---------+
iload_2 loads third argument (c) into stack:
+---------+
TOS ->| c |
+---------+
| product |
+---------+
Now iadd instruction can add two values.
54.4 JVM memory model
x86 and other low-level environments uses stack for arguments passing and as local variables storage. JVM is slightly
different.
It has:
• Local variable array (LVA6
). It is used as storage for incoming function arguments and local variables. Instructions like
iload_0 loads values from it. istore stores values to it. First, function arguments are came: starting at 0 or at 1
(if zeroth argument is occupied by this pointer). Then local variables are allocated.
Each slot has size of 32-bit. Hence, values of long and double data types occupy two slots.
• Operand stack (or just “stack”). It’s used for computations and passing arguments while calling other functions. Unlike
low-level environments like x86, it’s not possible to access the stack without using instructions which explicitely pushes
or pops values to/from it.
• Heap. It is used as storage for objects and arrays.
These 3 areas are isolated from each other.
6(Java) Local Variable Array
610
CHAPTER 54. JAVA 54.5. SIMPLE FUNCTION CALLING
54.5 Simple function calling
Math.random() returns a pseudorandom number in range of [0.0 …1.0), but let’s say, by some reason, we need to devise
a function returning number in range of [0.0 …0.5):
public class HalfRandom
{
public static double f()
{
return Math.random()/2;
}
}
Listing 54.8: Constant pool
...
#2 = Methodref #18.#19 // java/lang/Math.random:()D
#3 = Double 2.0d
...
#12 = Utf8 ()D
...
#18 = Class #22 // java/lang/Math
#19 = NameAndType #23:#12 // random:()D
#22 = Utf8 java/lang/Math
#23 = Utf8 random
public static double f();
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=4, locals=0, args_size=0
0: invokestatic #2 // Method java/lang/Math.random:()D
3: ldc2_w #3 // double 2.0d
6: ddiv
7: dreturn
invokestatic calls for th
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en
Reverse engineering for_beginners-en

More Related Content

PDF
Bash
PDF
10.1.1.652.4894
PDF
Embedded linux barco-20121001
PDF
c programming
PDF
Advanced cardiovascular exercites
PDF
Bash reference manual
PDF
Electrónica digital: Logicsim
PDF
Mat power manual
Bash
10.1.1.652.4894
Embedded linux barco-20121001
c programming
Advanced cardiovascular exercites
Bash reference manual
Electrónica digital: Logicsim
Mat power manual

What's hot (17)

PDF
Circuitikzmanual
PDF
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
PDF
PDF
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
PDF
Snmp nagios
PDF
Analysis and control of an in situ hydrogen generation and fuel cell power sy...
PDF
Arduino: Realice proyectos básicos de Arduino 26 experimentos con microcontro...
PDF
AIX 5L Differences Guide Version 5.3 Edition
PDF
A practical introduction_to_python_programming_heinold
PDF
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
PDF
Openflow switch-v1.5.0.noipr
PDF
The C Preprocessor
PDF
Metasploit
PDF
2016.10.24 halvledere - pdf v.01 - DIODE TRANSISTOR SEMICONDUCTOR - Sven ...
PDF
Tinyos programming
PDF
Offshore structures
Circuitikzmanual
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Snmp nagios
Analysis and control of an in situ hydrogen generation and fuel cell power sy...
Arduino: Realice proyectos básicos de Arduino 26 experimentos con microcontro...
AIX 5L Differences Guide Version 5.3 Edition
A practical introduction_to_python_programming_heinold
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Openflow switch-v1.5.0.noipr
The C Preprocessor
Metasploit
2016.10.24 halvledere - pdf v.01 - DIODE TRANSISTOR SEMICONDUCTOR - Sven ...
Tinyos programming
Offshore structures
Ad

Viewers also liked (20)

PDF
Tackling the Management Challenges of Server Consolidation on Multi-core Systems
PDF
Kernel Recipes 2016 - Kernel documentation: what we have and where it’s going
PDF
BKK16-404A PCI Development Meeting
PDF
Dulloor xen-summit
PDF
Specification-Based Test Program Generation for ARM VMSAv8-64 MMUs
PDF
Virtualization overheads
PDF
Docker and friends at Linux Days 2014 in Prague
PDF
Linux numa evolution
PDF
BKK16-104 sched-freq
PPTX
Gc and-pagescan-attacks-by-linux
PDF
Cgroup resource mgmt_v1
PDF
Non-Uniform Memory Access ( NUMA)
PDF
Known basic of NFV Features
PDF
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
PDF
Linux NUMA & Databases: Perils and Opportunities
PDF
P4, EPBF, and Linux TC Offload
PPT
Cpu scheduling(suresh)
PPT
Process scheduling linux
PPT
NUMA overview
PDF
Notes on NUMA architecture
Tackling the Management Challenges of Server Consolidation on Multi-core Systems
Kernel Recipes 2016 - Kernel documentation: what we have and where it’s going
BKK16-404A PCI Development Meeting
Dulloor xen-summit
Specification-Based Test Program Generation for ARM VMSAv8-64 MMUs
Virtualization overheads
Docker and friends at Linux Days 2014 in Prague
Linux numa evolution
BKK16-104 sched-freq
Gc and-pagescan-attacks-by-linux
Cgroup resource mgmt_v1
Non-Uniform Memory Access ( NUMA)
Known basic of NFV Features
SFO15-TR9: PSCI, ACPI (and UEFI to boot)
Linux NUMA & Databases: Perils and Opportunities
P4, EPBF, and Linux TC Offload
Cpu scheduling(suresh)
Process scheduling linux
NUMA overview
Notes on NUMA architecture
Ad

Similar to Reverse engineering for_beginners-en (20)

PDF
Math for programmers
PDF
Pratical mpi programming
PDF
Assembly Language Programming Vincent Mahout
PDF
usersguide.pdf
PDF
Openstack InstallGuide.pdf
PDF
Postgresql database administration volume 1
PDF
Ns doc
PDF
Dm00046982
PDF
Manual programação stm 32 f4
PDF
Thats How We C
PDF
Xcos simulation
PDF
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
PDF
C++ For Quantitative Finance
PDF
Redp4469
PDF
St3300655 lw
PDF
devicetree-specification
PDF
Linux-Perf.pdf
PDF
R installation and administration
PDF
tutorial.pdf
PDF
IBM zEnterprise 114 Technical Guide
Math for programmers
Pratical mpi programming
Assembly Language Programming Vincent Mahout
usersguide.pdf
Openstack InstallGuide.pdf
Postgresql database administration volume 1
Ns doc
Dm00046982
Manual programação stm 32 f4
Thats How We C
Xcos simulation
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
C++ For Quantitative Finance
Redp4469
St3300655 lw
devicetree-specification
Linux-Perf.pdf
R installation and administration
tutorial.pdf
IBM zEnterprise 114 Technical Guide

Recently uploaded (20)

PPTX
Matchmaking for JVMs: How to Pick the Perfect GC Partner
PPTX
CNN LeNet5 Architecture: Neural Networks
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PDF
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
PPTX
Presentation by Samna Perveen And Subhan Afzal.pptx
PDF
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PPTX
Cybersecurity: Protecting the Digital World
PDF
AI Guide for Business Growth - Arna Softech
PPTX
HackYourBrain__UtrechtJUG__11092025.pptx
PDF
Internet Download Manager IDM Crack powerful download accelerator New Version...
PPTX
Computer Software - Technology and Livelihood Education
PPTX
Bista Solutions Advanced Accounting Package
DOC
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PDF
Practical Indispensable Project Management Tips for Delivering Successful Exp...
DOCX
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
PPTX
R-Studio Crack Free Download 2025 Latest
PPTX
Full-Stack Developer Courses That Actually Land You Jobs
PDF
CapCut PRO for PC Crack New Download (Fully Activated 2025)
Matchmaking for JVMs: How to Pick the Perfect GC Partner
CNN LeNet5 Architecture: Neural Networks
How Tridens DevSecOps Ensures Compliance, Security, and Agility
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
Presentation by Samna Perveen And Subhan Afzal.pptx
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Cybersecurity: Protecting the Digital World
AI Guide for Business Growth - Arna Softech
HackYourBrain__UtrechtJUG__11092025.pptx
Internet Download Manager IDM Crack powerful download accelerator New Version...
Computer Software - Technology and Livelihood Education
Bista Solutions Advanced Accounting Package
UTEP毕业证学历认证,宾夕法尼亚克拉里恩大学毕业证未毕业
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Practical Indispensable Project Management Tips for Delivering Successful Exp...
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
R-Studio Crack Free Download 2025 Latest
Full-Stack Developer Courses That Actually Land You Jobs
CapCut PRO for PC Crack New Download (Fully Activated 2025)

Reverse engineering for_beginners-en

  • 1. Reverse Engineering for Beginners Dennis Yurichev
  • 2. Reverse Engineering for Beginners Dennis Yurichev <dennis(a)yurichev.com> cbnd ©2013-2015, Dennis Yurichev. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/. Text version (April 14, 2015). There is probably a newer version of this text, and Russian language version also accessible at beginners.re. E-book reader version is also available on the page. There are also shortened LITE-version (introductory), intended to those who wants very quick introduction to reverse engineering basics: beginners.re You may also subscribe to my twitter, to get information about updates of this text, etc: @yurichev 1 or to subscribe to mailing list 2 . The cover was made by Andy Nechaevsky: facebook. 1twitter 2yurichev.com ii
  • 3. Please take a short survey! Feedback is extremely important to the author! http://beginners.re/survey.html. i
  • 4. SHORT CONTENTS SHORT CONTENTS Short contents I Code patterns 1 II Important fundamentals 450 III Slightly more advanced examples 458 IV Java 603 V Finding important/interesting stuff in the code 639 VI OS-specific 662 VII Tools 716 VIII More examples 722 IX Examples of reversing proprietary file formats 834 X Other things 865 XI Books/blogs worth reading 883 XII Exercises 887 Afterword 923 Appendix 925 Acronyms used 964 ii
  • 5. CONTENTS CONTENTS Contents 0.0.1 Donate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv I Code patterns 1 1 A short introduction to the CPU 3 1.1 A couple of words about different ISA3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 Simplest possible function 4 2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.3.1 Note about MIPS instruction/register names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3 Hello, world! 6 3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3.1.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3.1.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.1.3 GCC: AT&T syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.2 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.2.1 MSVC—x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.2.2 GCC—x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.3 GCC—one more thing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.4.1 Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.4.2 Non-optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.4.3 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.4.4 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.4.5 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.5.1 Word about “global pointer” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.5.2 Optimizing GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.5.3 Non-optimizing GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.5.4 Role of the stack frame in this example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.5.5 Optimizing GCC: load it into GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4 Function prologue and epilogue 21 4.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 5 Stack 22 5.1 Why does the stack grow backwards? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 5.2 What is the stack used for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.2.1 Save the function’s return address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.2.2 Passing function arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.2.3 Local variable storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.2.4 x86: alloca() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.2.5 (Windows) SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5.2.6 Buffer overflow protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5.3 Typical stack layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3Instruction Set Architecture iii
  • 6. CONTENTS 5.4 Noise in stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 5.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 5.5.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 6 printf() with several arguments 33 6.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 6.1.1 x86: 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 6.1.2 x64: 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 6.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 6.2.1 ARM: 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 6.2.2 ARM: 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 6.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 6.3.1 3 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 6.3.2 8 arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 6.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 6.5 By the way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 7 scanf() 56 7.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 7.1.1 About pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 7.1.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 7.1.3 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 7.1.4 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 7.1.5 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 7.1.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 7.2 Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 7.2.1 MSVC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 7.2.2 MSVC: x86 + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 7.2.3 GCC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 7.2.4 MSVC: x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 7.2.5 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 7.2.6 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 7.2.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 7.3 scanf() result checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 7.3.1 MSVC: x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 7.3.2 MSVC: x86: IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 7.3.3 MSVC: x86 + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 7.3.4 MSVC: x86 + Hiew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 7.3.5 MSVC: x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 7.3.6 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 7.3.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 7.3.8 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 8 Accessing passed arguments 86 8.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 8.1.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 8.1.2 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 8.1.3 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 8.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 8.2.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 8.2.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 8.2.3 GCC: uint64_t instead of int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 8.3 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 8.3.1 Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 8.3.2 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 8.3.3 Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 8.3.4 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 8.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 9 More about results returning 95 9.1 Attempt to use the result of a function returning void . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 9.2 What if we do not use the function result? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 9.3 Returning a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 iv
  • 7. CONTENTS 10 Pointers 98 10.1 Global variables example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 10.2 Local variables example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 10.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 11 GOTO 108 11.1 Dead code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 11.2 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 12 Conditional jumps 111 12.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 12.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 12.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 12.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 12.2 Calculating absolute value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 12.2.1 Optimizing MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 12.2.2 Optimizing Keil 6/2013: thumb mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 12.2.3 Optimizing Keil 6/2013: ARM mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 12.2.4 Non-optimizing GCC 4.9 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 12.2.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 12.2.6 Branchless version? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 12.3 Conditional operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 12.3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 12.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 12.3.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 12.3.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 12.3.5 Let’s rewrite it in an if/else way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 12.3.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 12.3.7 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 12.4 Getting minimal and maximal values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 12.4.1 32-bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 12.4.2 64-bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 12.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 12.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 12.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 12.5.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 12.5.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 12.5.4 Branchless . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 13 switch()/case/default 139 13.1 Small number of cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 13.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 13.1.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 13.1.5 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 13.1.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 13.1.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 13.2 A lot of cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 13.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 13.2.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 13.2.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 13.2.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 13.3 When there are several case statements in one block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 13.3.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 13.3.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 13.3.3 ARM64: Optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 13.4 Fall-through . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 13.4.1 MSVC x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 13.4.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 13.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 13.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 v
  • 8. CONTENTS 14 Loops 169 14.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 14.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 14.1.2 x86: OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 14.1.3 x86: tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 14.1.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 14.1.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 14.1.6 One more thing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 14.2 Memory blocks copying routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 14.2.1 Straight-forward implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 14.2.2 ARM in ARM mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 14.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 14.2.4 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 14.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 14.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 14.4.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 14.4.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 14.4.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 14.4.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 15 Simple C-strings processing 188 15.1 strlen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 15.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 15.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 15.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 15.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 15.2.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 16 Replacing arithmetic instructions to other ones 201 16.1 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 16.1.1 Multiplication using addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 16.1.2 Multiplication using shifting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 16.1.3 Multiplication using shifting/subtracting/adding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 16.2 Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 16.2.1 Division using shifts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 16.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 16.3.1 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 17 Floating-point unit 208 17.1 IEEE 754 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 17.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 17.3 ARM, MIPS, x86/x64 SIMD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 17.4 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 17.5 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 17.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 17.5.3 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 17.5.4 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 17.5.6 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 17.6 Passing floating point numbers via arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 17.6.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 17.6.5 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 17.7 Comparison example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 17.7.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 17.7.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 17.7.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 17.7.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 17.8 Stack, calculators and reverse Polish notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 17.9 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 17.10Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 17.10.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 vi
  • 9. CONTENTS 17.10.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 18 Arrays 257 18.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 18.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 18.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 18.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 18.2 Buffer overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 18.2.1 Reading outside array bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 18.2.2 Writing beyond array bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 18.3 Buffer overflow protection methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 18.3.1 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 18.4 One more word about arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 18.5 Array of pointers to strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 18.5.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 18.5.2 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 18.5.3 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 18.5.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 18.5.5 Array overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 18.6 Multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 18.6.1 Two-dimensional array example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 18.6.2 Access two-dimensional array as one-dimensional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 18.6.3 Three-dimensional array example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 18.6.4 More examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 18.7 Pack of strings as a two-dimensional array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 18.7.1 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 18.7.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 18.7.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 18.7.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 18.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 18.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 18.9.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 18.9.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 18.9.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 18.9.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 18.9.5 Exercise #5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 19 Manipulating specific bit(s) 305 19.1 Specific bit checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 19.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 19.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 19.2 Specific bit setting/clearing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 19.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 19.2.3 ARM + Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 19.2.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 19.2.5 ARM: more about the BIC instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 19.2.6 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 19.2.8 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 19.3 Shifts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 19.4 Specific bit setting/clearing: FPU4 example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 19.4.1 A word about the XOR operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 19.4.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 19.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 19.4.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 19.5 Counting bits set to 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 19.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 19.5.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 19.5.5 ARM64 + Optimizing GCC 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 19.5.6 ARM64 + Non-optimizing GCC 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 4Floating-point unit vii
  • 10. CONTENTS 19.5.7 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 19.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 19.6.1 Check for specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 19.6.2 Check for specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 19.6.3 Set specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 19.6.4 Set specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 19.6.5 Clear specific bit (known at compile stage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 19.6.6 Clear specific bit (specified at runtime) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 19.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 19.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 19.7.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 19.7.3 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 19.7.4 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 20 Linear congruential generator as pseudorandom number generator 344 20.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 20.2 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 20.3 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 20.4 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 20.4.1 MIPS relocations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 20.5 Thread-safe version of the example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 21 Structures 349 21.1 MSVC: SYSTEMTIME example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 21.1.1 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 21.1.2 Replacing the structure with array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 21.2 Let’s allocate space for a structure using malloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 21.3 UNIX: struct tm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 21.3.1 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 21.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 21.3.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 21.3.4 Structure as a set of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 21.3.5 Structure as an array of 32-bit words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 21.3.6 Structure as an array of bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 21.4 Fields packing in structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 21.4.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 21.4.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 21.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 21.4.4 One more word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 21.5 Nested structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 21.5.1 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 21.6 Bit fields in a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 21.6.1 CPUID example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 21.6.2 Working with the float type as with a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 21.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 21.7.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 21.7.2 Exercise #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 22 Unions 384 22.1 Pseudo-random number generator example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 22.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 22.1.2 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 22.1.3 ARM (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 22.2 Calculating machine epsilon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388 22.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 22.2.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 22.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 22.2.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 viii
  • 11. CONTENTS 23 Pointers to functions 391 23.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 23.1.1 MSVC + OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 23.1.2 MSVC + tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 23.1.3 MSVC + tracer (code coverage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 23.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 23.2.1 GCC + GDB (with source code) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 23.2.2 GCC + GDB (no source code) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 24 64-bit values in 32-bit environment 403 24.1 Returning of 64-bit value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 24.1.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 24.1.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 24.1.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 24.2 Arguments passing, addition, subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 24.2.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 24.2.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 24.2.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 24.3 Multiplication, division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 24.3.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 24.3.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 24.3.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 24.4 Shifting right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 24.4.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 24.4.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 24.4.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 24.5 Converting 32-bit value into 64-bit one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 24.5.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 24.5.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 24.5.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 25 SIMD 413 25.1 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 25.1.1 Addition example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 25.1.2 Memory copy example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 25.2 SIMD strlen() implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 26 64 bits 426 26.1 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 26.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432 26.3 Float point numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 27 Working with floating point numbers using SIMD 434 27.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 27.1.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 27.1.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 27.2 Passing floating point number via arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 27.3 Comparison example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 27.3.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 27.3.2 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 27.4 Calculating machine epsilon: x64 and SIMD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 27.5 Pseudo-random number generator example revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 27.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 28 More about ARM 445 28.1 Number sign (#) before number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 28.2 Addressing modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 28.3 Loading a constant into a register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 28.3.1 32-bit ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 28.3.2 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 28.4 Relocs in ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 29 More about MIPS 449 29.1 Loading constants into register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 29.2 Further reading about MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 ix
  • 12. CONTENTS II Important fundamentals 450 30 Signed number representations 451 31 Endianness 453 31.1 Big-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 31.2 Little-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 31.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 31.4 Bi-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 31.5 Converting data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 32 Memory 455 33 CPU 456 33.1 Branch predictors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 33.2 Data dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 34 Hash functions 457 34.1 How one-way function works? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 III Slightly more advanced examples 458 35 Temperature converting 459 35.1 Integer values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 35.1.1 Optimizing MSVC 2012 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 35.1.2 Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 35.2 Floating-point values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 36 Fibonacci numbers 464 36.1 Example #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464 36.2 Example #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 36.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 37 CRC32 calculation example 471 38 Network address calculation example 474 38.1 calc_network_address() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475 38.2 form_IP() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 38.3 print_as_IP() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 38.4 form_netmask() and set_bit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478 38.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 39 Loops: several iterators 480 39.1 Three iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 39.2 Two iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 39.3 Intel C++ 2011 case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 40 Duff’s device 485 41 Division by 9 488 41.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 41.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 41.2.1 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 41.2.2 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 41.2.3 Non-optimizing Xcode 4.6.3 (LLVM) and Keil 6/2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 41.3 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 41.4 How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 41.5 Getting the divisor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 41.5.1 Variant #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 41.5.2 Variant #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 41.6 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 x
  • 13. CONTENTS 42 String to number conversion (atoi()) 494 42.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 42.1.1 Optimizing MSVC 2013 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 42.1.2 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 42.1.3 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 42.1.4 Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 42.1.5 Optimizing GCC 4.9.1 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 42.2 A slightly advanced example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 42.2.1 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 42.2.2 Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 43 Inline functions 500 43.1 Strings and memory functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 43.1.1 strcmp() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 43.1.2 strlen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 43.1.3 strcpy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 43.1.4 memset() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 43.1.5 memcpy() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504 43.1.6 memcmp() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 43.1.7 IDA script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508 44 C99 restrict 509 45 Branchless abs() function 512 45.1 Optimizing GCC 4.9.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512 45.2 Optimizing GCC 4.9 ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512 46 Variadic functions 514 46.1 Computing arithmetic mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514 46.1.1 cdecl calling conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514 46.1.2 Register-based calling conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515 46.2 vprintf() function case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 47 Strings trimming 519 47.1 x64: Optimizing MSVC 2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520 47.2 x64: Non-optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 47.3 x64: Optimizing GCC 4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522 47.4 ARM64: Non-optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523 47.5 ARM64: Optimizing GCC (Linaro) 4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524 47.6 ARM: Optimizing Keil 6/2013 (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525 47.7 ARM: Optimizing Keil 6/2013 (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525 47.8 MIPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 48 toupper() function 528 48.1 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 48.1.1 Two comparison operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 48.1.2 One comparison operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529 48.2 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 48.2.1 GCC for ARM64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 48.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 49 Incorrectly disassembled code 532 49.1 Disassembling from an incorrect start (x86) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 49.2 How does random noise looks disassembled? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533 50 Obfuscation 537 50.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 50.2 Executable code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 50.2.1 Inserting garbage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 50.2.2 Replacing instructions with bloated equivalents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 50.2.3 Always executed/never executed code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 50.2.4 Making a lot of mess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 50.2.5 Using indirect pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 50.3 Virtual machine / pseudo-code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 50.4 Other things to mention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 xi
  • 14. CONTENTS 50.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 50.5.1 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 51 C++ 540 51.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 51.1.1 A simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 51.1.2 Class inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 51.1.3 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548 51.1.4 Multiple inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550 51.1.5 Virtual methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 51.2 ostream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 51.3 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 51.4 STL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 51.4.1 std::string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 51.4.2 std::list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 51.4.3 std::vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572 51.4.4 std::map and std::set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578 52 Negative array indices 589 53 Windows 16-bit 592 53.1 Example#1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 53.2 Example #2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 53.3 Example #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593 53.4 Example #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594 53.5 Example #5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 53.6 Example #6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600 53.6.1 Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 IV Java 603 54 Java 604 54.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604 54.2 Returning a value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604 54.3 Simple calculating functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 54.4 JVM5 memory model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610 54.5 Simple function calling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 54.6 Calling beep() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612 54.7 Linear congruential PRNG6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612 54.8 Conditional jumps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613 54.9 Passing arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615 54.10Bitfields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616 54.11Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617 54.12switch() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 54.13Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 54.13.1Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 54.13.2Summing elements of array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621 54.13.3main() function sole argument is array too . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622 54.13.4Pre-initialized array of strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622 54.13.5Variadic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624 54.13.6Two-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626 54.13.7Three-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626 54.13.8Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 54.14Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 54.14.1First example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 54.14.2Second example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628 54.15Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 54.16Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632 54.17Simple patching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634 54.17.1 First example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634 54.17.2 Second example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635 54.18Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638 5Java virtual machine 6Pseudorandom number generator xii
  • 15. CONTENTS V Finding important/interesting stuff in the code 639 55 Identification of executable files 641 55.1 Microsoft Visual C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.1.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.2.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.2.2 Cygwin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.2.3 MinGW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.3 Intel FORTRAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 55.4 Watcom, OpenWatcom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 55.4.1 Name mangling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 55.5 Borland . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 55.5.1 Delphi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 55.6 Other known DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 56 Communication with the outer world (win32) 644 56.1 Often used functions in the Windows API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644 56.2 tracer: Intercepting all functions in specific module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645 57 Strings 646 57.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 57.1.1 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 57.1.2 Borland Delphi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 57.1.3 Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 57.1.4 Base64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649 57.2 Error/debug messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649 57.3 Suspicious magic strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650 58 Calls to assert() 651 59 Constants 652 59.1 Magic numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 59.1.1 DHCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653 59.2 Searching for constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653 60 Finding the right instructions 654 61 Suspicious code patterns 656 61.1 XOR instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 61.2 Hand-written assembly code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 62 Using magic numbers while tracing 658 63 Other things 659 63.1 General idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 63.2 C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 63.3 Some binary file patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 63.4 Memory “snapshots” comparing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660 63.4.1 Windows registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 63.4.2 Blink-comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 VI OS-specific 662 64 Arguments passing methods (calling conventions) 663 64.1 cdecl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663 64.2 stdcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663 64.2.1 Functions with variable number of arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664 64.3 fastcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664 64.3.1 GCC regparm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 64.3.2 Watcom/OpenWatcom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 64.4 thiscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 64.5 x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 64.5.1 Windows x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 64.5.2 Linux x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 xiii
  • 16. CONTENTS 64.6 Return values of float and double type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 64.7 Modifying arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 64.8 Taking a pointer to function argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669 65 Thread Local Storage 671 65.1 Linear congruential generator revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 65.1.1 Win32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 65.1.2 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 66 System calls (syscall-s) 676 66.1 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676 66.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 67 Linux 678 67.1 Position-independent code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678 67.1.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 67.2 LD_PRELOAD hack in Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 68 Windows NT 683 68.1 CRT (win32) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683 68.2 Win32 PE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686 68.2.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686 68.2.2 Base address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 68.2.3 Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 68.2.4 OS version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 68.2.5 Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 68.2.6 Relocations (relocs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688 68.2.7 Exports and imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 68.2.8 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 68.2.9 .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 68.2.10TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 68.2.11Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 68.2.12Further reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 68.3 Windows SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 68.3.1 Let’s forget about MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 68.3.2 Now let’s get back to MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697 68.3.3 Windows x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710 68.3.4 Read more about SEH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714 68.4 Windows NT: Critical section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714 VII Tools 716 69 Disassembler 717 69.1 IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 70 Debugger 718 70.1 tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718 70.2 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718 70.3 GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718 71 System calls tracing 719 71.0.1 strace / dtruss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719 72 Decompilers 720 73 Other tools 721 VIII More examples 722 74 Task manager practical joke (Windows Vista) 723 74.1 Using LEA to load values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 75 Color Lines game practical joke 727 xiv
  • 17. CONTENTS 76 Minesweeper (Windows XP) 731 76.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 77 Hand decompiling + Z3 SMT solver 736 77.1 Hand decompiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736 77.2 Now let’s use the Z3 SMT solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739 78 Dongles 744 78.1 Example #1: MacOS Classic and PowerPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744 78.2 Example #2: SCO OpenServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750 78.2.1 Decrypting error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 78.3 Example #3: MS-DOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 79 “QR9”: Rubik’s cube inspired amateur crypto-algorithm 765 80 SAP 792 80.1 About SAP client network traffic compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792 80.2 SAP 6.0 password checking functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802 81 Oracle RDBMS 806 81.1 V$VERSION table in the Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806 81.2 X$KSMLRU table in Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813 81.3 V$TIMER table in Oracle RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814 82 Handwritten assembly code 819 82.1 EICAR test file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819 83 Demos 821 83.1 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821 83.1.1 Trixter’s 42 byte version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821 83.1.2 My attempt to reduce Trixter’s version: 27 bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822 83.1.3 Taking random memory garbage as a source of randomness . . . . . . . . . . . . . . . . . . . . . . . . . . . 822 83.1.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823 83.2 Mandelbrot set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824 83.2.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825 83.2.2 Let’s get back to the demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830 83.2.3 My “fixed” version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832 IX Examples of reversing proprietary file formats 834 84 Primitive XOR-encryption 835 84.1 Norton Guide: simplest possible 1-byte XOR encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836 84.1.1 Entropy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837 84.2 Simplest possible 4-byte XOR encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839 84.2.1 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842 85 Millenium game save file 843 86 Oracle RDBMS: .SYM-files 850 87 Oracle RDBMS: .MSB-files 859 87.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864 X Other things 865 88 npad 866 89 Executable files patching 868 89.1 Text strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868 89.2 x86 code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868 90 Compiler intrinsic 869 91 Compiler’s anomalies 870 xv
  • 18. CONTENTS 92 OpenMP 871 92.1 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 872 92.2 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874 93 Itanium 877 94 8086 memory model 880 95 Basic blocks reordering 881 95.1 Profile-guided optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881 XI Books/blogs worth reading 883 96 Books 884 96.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884 96.2 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884 96.3 x86 / x86-64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884 96.4 ARM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884 96.5 Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884 97 Blogs 885 97.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885 98 Other 886 XII Exercises 887 99 Level 1 889 99.1 Exercise 1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889 100Level 2 890 100.1Exercise 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890 100.1.1Optimizing MSVC 2010 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890 100.1.2Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891 100.2Exercise 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891 100.2.1Optimizing MSVC 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891 100.2.2GCC 4.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892 100.2.3Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893 100.2.4Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894 100.2.5Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894 100.2.6Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895 100.3Exercise 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896 100.3.1Optimizing MSVC 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896 100.3.2Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897 100.3.3Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897 100.3.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898 100.3.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899 100.4Exercise 2.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899 100.4.1Optimizing MSVC 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899 100.4.2Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899 100.4.3Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 100.4.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 100.4.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 100.5Exercise 2.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900 100.5.1MSVC 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901 100.5.2Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901 100.5.3GCC 4.6.3 for Raspberry Pi (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902 100.5.4Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903 100.5.5Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903 100.6Exercise 2.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905 100.6.1Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905 100.6.2Optimizing GCC 4.4.6 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907 100.6.3Optimizing GCC 4.8.1 x86 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908 100.6.4Keil (ARM mode): Cortex-R4F CPU as target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909 xvi
  • 19. CONTENTS 100.6.5Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910 100.6.6Optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911 100.7Exercise 2.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912 100.7.1 Optimizing MSVC 2012 x64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912 100.7.2 Optimizing Keil (ARM mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913 100.7.3 Optimizing Keil (thumb mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913 100.7.4 Non-optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913 100.7.5 Optimizing GCC 4.9.1 (ARM64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914 100.7.6 Non-optimizing GCC 4.4.5 (MIPS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916 100.8Exercise 2.17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917 100.9Exercise 2.18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918 100.10Exercise 2.19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918 100.11Exercise 2.20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918 101Level 3 919 101.1Exercise 3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919 101.2Exercise 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919 101.3Exercise 3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919 101.4Exercise 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919 101.5Exercise 3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920 101.6Exercise 3.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920 102crackme / keygenme 921 Afterword 923 103Questions? 923 Appendix 925 A x86 925 A.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925 A.2 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925 A.2.1 RAX/EAX/AX/AL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925 A.2.2 RBX/EBX/BX/BL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925 A.2.3 RCX/ECX/CX/CL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.4 RDX/EDX/DX/DL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.5 RSI/ESI/SI/SIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.6 RDI/EDI/DI/DIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.7 R8/R8D/R8W/R8L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.8 R9/R9D/R9W/R9L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.9 R10/R10D/R10W/R10L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926 A.2.10 R11/R11D/R11W/R11L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.11 R12/R12D/R12W/R12L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.12 R13/R13D/R13W/R13L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.13 R14/R14D/R14W/R14L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.14 R15/R15D/R15W/R15L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.15 RSP/ESP/SP/SPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.16 RBP/EBP/BP/BPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 A.2.17 RIP/EIP/IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928 A.2.18 CS/DS/ES/SS/FS/GS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928 A.2.19 Flags register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928 A.3 FPU registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929 A.3.1 Control Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929 A.3.2 Status Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929 A.3.3 Tag Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.4 SIMD registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.4.1 MMX registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.4.2 SSE and AVX registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.5 Debugging registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.5.1 DR6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930 A.5.2 DR7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931 A.6 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931 xvii
  • 20. CONTENTS A.6.1 Prefixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931 A.6.2 Most frequently used instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932 A.6.3 Less frequently used instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936 A.6.4 FPU instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940 A.6.5 Instructions having printable ASCII opcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 B ARM 944 B.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944 B.2 Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944 B.3 32-bit ARM (AArch32) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944 B.3.1 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 944 B.3.2 Current Program Status Register (CPSR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945 B.3.3 VFP (floating point) and NEON registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945 B.4 64-bit ARM (AArch64) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945 B.4.1 General purpose registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945 B.5 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946 B.5.1 Conditional codes table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946 C MIPS 947 C.1 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947 C.1.1 General purpose registers GPR7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947 C.1.2 Floating-point registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947 C.2 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947 C.2.1 Jump instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948 D Some GCC library functions 949 E Some MSVC library functions 950 F Cheatsheets 951 F.1 IDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951 F.2 OllyDbg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951 F.3 MSVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952 F.4 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952 F.5 GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952 G Exercise solutions 954 G.1 Per chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.1 “Stack” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.2 “switch()/case/default” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.3 Exercise #1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.4 “Loops” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.5 Exercise #3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954 G.1.6 Exercise #4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955 G.1.7 “Simple C-strings processing” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955 G.1.8 “Replacing arithmetic instructions to other ones” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955 G.1.9 “Floating-point unit” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955 G.1.10 “Arrays” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955 G.1.11 “Manipulating specific bit(s)” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956 G.1.12 “Structures” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958 G.1.13 “Obfuscation” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.1.14 “Division by 9” chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.2 Level 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.2.1 Exercise 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.2.2 Exercise 1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.3 Level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.3.1 Exercise 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.3.2 Exercise 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959 G.3.3 Exercise 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 G.3.4 Exercise 2.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 G.3.5 Exercise 2.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 G.3.6 Exercise 2.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 G.3.7 Exercise 2.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 G.3.8 Exercise 2.17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 7General Purpose Registers xviii
  • 21. CONTENTS G.3.9 Exercise 2.18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.3.10 Exercise 2.19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.3.11 Exercise 2.20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4 Level 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.1 Exercise 3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.2 Exercise 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.3 Exercise 3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.4 Exercise 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.5 Exercise 3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.4.6 Exercise 3.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 G.5 Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962 G.5.1 “Minesweeper (Windows XP)” example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962 Acronyms used 964 Glossary 968 Index 970 xix
  • 22. CONTENTS Preface There are several popular meanings of the term “reverse engineering”: 1) reverse engineering of software: researching compiled programs; 2) 3D model scanning and reworking in order to make a copy of it; 3) recreating DBMS8 structure. This book is related to the first meaning. Topics discussed x86/x64, ARM/ARM64, MIPS, Java/JVM. Topics touched Oracle RDBMS ( 81 on page 806), Itanium ( 93 on page 877), copy-protection dongles ( 78 on page 744), LD_PRELOAD ( 67.2 on page 680), stack overflow, ELF9 , win32 PE file format ( 68.2 on page 686), x86-64 ( 26.1 on page 426), critical sections ( 68.4 on page 714), syscalls ( 66 on page 676), TLS10 , position-independent code (PIC11 ) ( 67.1 on page 678), profile-guided optimization ( 95.1 on page 881), C++ STL ( 51.4 on page 556), OpenMP ( 92 on page 871), SEH ( 68.3 on page 692). About the author Dennis Yurichev is an experienced reverse engineer and programmer. He can be contacted by email: dennis(a)yurichev.com, or Skype: dennis.yurichev. Thanks For patiently answering all my questions: Andrey “herm1t” Baranovich, Slava ”Avid” Kazakov. For sending me notes about mistakes and inaccuracies: Stanislav ”Beaver” Bobrytskyy, Alexander Lysenko, Shell Rocket, Zhu Ruijin, Changmin Heo. For helping me in other ways: Andrew Zubinski, Arnaud Patard (rtp on #debian-arm IRC). For translating to Chinese simplified: Xian Chi. For translating to Korean: Byungho Min. For proofreading: Alexander ”Lstar” Chernenkiy, Vladimir Botov, Andrei Brazhuk, Mark “Logxen” Cooper, Yuan Jochen Kang, Mal Malakov. Vasil Kolev did a great amount of work in proofreading and correcting many mistakes. For illustrations and cover art: Andy Nechaevsky. Thanks also to all the folks on github.com who have contributed notes and corrections. Many LATEX packages were used: I would like to thank the authors as well. 0.0.1 Donate As it turns out, (technical) writing takes a lot of effort and work. This book is free, available freely and available in source code form 12 (LaTeX), and it will stay so forever. It is also ad-free. My current plan for this book is to add lots of information about: PLANS13 . If you want me to continue writing on all these topics, you may consider donating. Ways to donate are available on the page: beginners.re. Every donor’s name will be included in the book! Donors also have a right to ask me to rearrange items in my writing plan. 8Database management systems 9Executable file format widely used in *NIX system including Linux 10Thread Local Storage 11Position Independent Code: 67.1 on page 678 12GitHub 13GitHub xx
  • 23. CONTENTS Donors 23 * anonymous, 2 * Oleg Vygovsky (50+100 UAH), Daniel Bilar ($50), James Truscott ($4.5), Luis Rocha ($63), Joris van de Vis ($127), Richard S Shultz ($20), Jang Minchang ($20), Shade Atlas (5 AUD), Yao Xiao ($10), Pawel Szczur (40 CHF), Justin Simms ($20), Shawn the R0ck ($27), Ki Chan Ahn ($50), Triop AB (100 SEK), Ange Albertini (10+50 EUR), Sergey Lukianov (300 RUR), Ludvig Gislason (200 SEK), Gérard Labadie (40 EUR), Sergey Volchkov (10 AUD), Vankayala Vigneswararao ($50), Philippe Teuwen ($4), Martin Haeberli ($10), Victor Cazacov (5 EUR), Tobias Sturzenegger (10 CHF), Sonny Thai ($15), Bayna AlZaabi ($75), Redfive B.V. (25 EUR), Joona Oskari Heikkilä (5 EUR), Marshall Bishop ($50), Nicolas Werner (12 EUR), Jeremy Brown ($100), Alexandre Borges ($25), Vladimir Dikovski (50 EUR), Jiarui Hong (100.00 SEK), Jim_Di (500 RUR), Tan Vincent ($30), Sri Harsha Kandrakota (10 AUD), Pillay Harish (10 SGD), Timur Valiev (230 RUR), Carlos Garcia Prado (10 EUR), Salikov Alexander (500 RUR), Oliver Whitehouse (30 GBP), Katy Moe ($14), Maxim Dyakonov ($3). mini-FAQ Q: Why one should learn assembly language these days? A: Unless you are OS developer, you probably don’t need to write in assembly: modern compilers perform optimizations much better than humans do. 14 . Also, modern CPU15 s are very complex devices and assembly knowledge would not help you understand its internals. That said, there are at least two areas where a good understanding of assembly may help: first, security/malware research. Second, gaining a better understanding of your compiled code while debugging. Therefore, this book is intended for those who want to understand assembly language rather than to write in it, which is why there are many examples of compiler output. Q: I clicked on hyperlink inside of PDF-document, how to get back? A: (Adobe Acrobat Reader) Alt + LeftArrow Q: Your book is so huge! Is there anything shorter? A: There is shortened lite version: http://beginners.re/#lite. Q: May I print this book? Use it for teaching? A: Of course, that’s why book is licensed under Creative Commons terms. Someone may also want to build their own version of book, read here about it. Q: I want to translate your book to some other language. A: Read my note to translators. Q: How would one find a reverse engineering job? A: There are hiring threads that appear from time to time on reddit devoted to RE16 (2013 Q3, 2014). Try looking there. A somewhat related hiring thread can be found in the “netsec” subreddit: 2014 Q2. Q: I have a question... A: Write me it by email (dennis(a)yurichev.com) or ask your question at my forum: forum.yurichev.com. Praise for Reverse Engineering for Beginners • “It’s very well done .. and for free .. amazing.”17 Daniel Bilar, Siege Technologies, LLC. • “...excellent and free”18 Pete Finnigan, Oracle RDBMS security guru. • “... book is interesting, great job!” Michael Sikorski, author of Practical Malware Analysis: The Hands-On Guide to Dissecting Malicious Software. • “... my compliments for the very nice tutorial!” Herbert Bos, full professor at the Vrije Universiteit Amsterdam, co-author of Modern Operating Systems (4th Edition). • “... It is amazing and unbelievable.” Luis Rocha, CISSP / ISSAP, Technical Manager, Network & Information Security at Verizon Business. • “Thanks for the great work and your book.” Joris van de Vis, SAP Netweaver & Security specialist. • “... reasonable intro to some of the techniques.”19 (Mike Stay, teacher at the Federal Law Enforcement Training Center, Georgia, US.) 14A very good text about this topic: [Fog13b] 15Central processing unit 16reddit 17twitter 18twitter 19reddit xxi
  • 24. CONTENTS • “I love this book! I have several students reading it at the moment, plan to use it in graduate course.”20 (Sergey Bratus, Research Assistant Professor at the Computer Science Department at Dartmouth College) • “Dennis @Yurichev has published an impressive (and free!) book on reverse engineering”21 Tanel Poder, Oracle RDBMS performance tuning expert. About Korean translation In January 2015, Acorn publishing company (www.acornpub.co.kr) in South Korea did huge amount of work in translating and publishing my book (state which is it in August 2014) in Korean language. Now it’s available at their website. Translator is Byungho Min (twitter/tais9). Cover pictures was done by my artist friend Andy Nechaevsky : facebook/andydinka. They are also the Korean translation copyright holder. So if you want to have a real book on your shelf in Korean language and/or want to support my work, now you may buy it. 20twitter 21twitter xxii
  • 26. When I first started learning C and then C++, I used to write small pieces of code, compile them, and look at the assembly language output. This was much easy for me to understand 22 . I did it so many times that the relation between the C/C++ code and what the compiler produced was imprinted deeply in my mind. That is why when I look at assembly code I could instantly grasp what the original C code in general does and looks like. Perhaps this technique could be helpful for someone else and so I’m going to describe some examples here. Sometimes I use ancient compilers, in order to get the shortest (or simplest) possible code snippet. Exercises When I studied assembly language, I also often compiled small C-functions and then rewrote them gradually to assembly, trying to make their code as short as possible. This probably is not worth doing today in real-world scenarios (because it’s hard to compete with modern compilers on efficiency), but it’s a very good method to learn assembly better. Therefore, you can take any assembly code from this book and try to make it shorter. However, please also do not forget about testing your results! Difference between non-optimized (debug) and optimized (release) versions A non-optimizing compiler works faster and produces more understandable (verbose, though) code. An optimizing (release) compiler works slower and tries to produce faster (but not necessarily smaller) code. One important feature of the debugging code is that there might be debugging information showing connections between each line in source code and machine code addresses. Optimizing compilers tend to produce such output where whole source code lines may be optimized away and not present in the resulting machine code. Reverse engineer practitioner usually encounters either version because some developers turn on compiler’s optimization switches and others do not. That’s why I try to give examples of both versions of code. 22Frankly speaking, I still do so when I can’t understand what some code does. 2
  • 27. CHAPTER 1. A SHORT INTRODUCTION TO THE CPU Chapter 1 A short introduction to the CPU The CPU is the unit, which executes all of the programs. Short glossary: Instruction : a primitive CPU command. Simplest examples: moving data between registers, working with memory, arith- metic primitives. As a rule, each CPU has its own instruction set architecture (ISA). Machine code : code for the CPU. Each instruction is usually encoded by several bytes. Assembly language : mnemonic code and some extensions like macros which are intended to make a programmer’s life easier. CPU register : Each CPU has a fixed set of general purpose registers (GPR). ≈ 8 in x86, ≈ 16 in x86-64, ≈ 16 in ARM. The easiest way to understand a register is to think of it as an untyped temporary variable. Imagine you are working with a high-level PL1 and you have only 8 32-bit (or 64-bit) variables. Many things can be done using only these! What is the difference between machine code and a PL? It is much easier for humans to use a high-level PL like C/C++, Java, Python, etc., but it is easier for a CPU to use a much lower level of abstraction. Perhaps, it would be possible to invent a CPU which can execute high-level PL code, but it would be much more complex. On the contrary, it is very inconvenient for humans to use assembly language due to it being low-level. Besides, it is very hard to do it without making a huge amount of annoying mistakes. The program, which converts high-level PL code into assembly, is called a compiler. 1.1 A couple of words about different ISA x86 was always an ISA with variable-length opcodes, so when the 64-bit era came, the x64 extensions did not affect the ISA very much. x86 has a lot of instructions that appeared in 16-bit 8086 CPU and are still present in latest CPUs. ARM is a RISC2 CPU designed with constant opcode length in mind, which had some advantages in the past. At the very beginning, ARM had all instructions encoded in 4 bytes 3 . This is now referred as “ARM mode”. Then they thought it wasn’t very frugal. In fact, most used CPU instructions4 in real world applications can be encoded using less information. So they added another ISA called Thumb, where each instruction was encoded in just 2 bytes. This is now referred as “Thumb mode”. However, not all ARM instructions can be encoded in just 2 bytes, so Thumb instruction set is somewhat limited. Code compiled for ARM mode and Thumb mode may coexist in one program, of course. Then ARM creators thought Thumb could be extended: Thumb-2 appeared (in ARMv7). Thumb-2 is still 2-byte instruc- tions, but some new instructions have a size of 4 bytes. There is a common misconception that Thumb-2 is a mix of ARM and Thumb. This is incorrect. Rather, Thumb-2 was extended to fully support all processor features so it could compete with ARM mode. On instruction set richness, Thumb-2 now competes with the original ARM mode. The majority of iPod/iPhone/iPad applications are compiled for the Thumb-2 instruction set because Xcode does this by default. Later the 64-bit ARM came out. This ISA has 4-byte opcodes again, without any additional Thumb mode. But the 64- bit requirements affected ISA, so, summarizing, we now have 3 ARM instruction sets: ARM mode, Thumb mode (including Thumb-2) and ARM64. These ISAs intersect partially, but I would rather say they are different ISAs than variations of the same one. Therefore, I try to add fragments of code in all 3 ARM ISAs in this book. There are many other RISC ISAs with fixed length 32-bit opcodes, for example MIPS, PowerPC and Alpha AXP. 1Programming language 2Reduced instruction set computing 3By the way, fixed-length instructions are handy in a way that one can calculate the next (or previous) instruction’s address without effort. This feature will be discussed in switch() ( 13.2.2 on page 158) section. 4These are MOV/PUSH/CALL/Jcc 3
  • 28. CHAPTER 2. SIMPLEST POSSIBLE FUNCTION Chapter 2 Simplest possible function Probably the simplest possible function is that one which just returns some constant value. Here it is: int f() { return 123; }; 2.1 x86 And that’s what the optimizing GCC compiler produces: Listing 2.1: Optimizing GCC f: mov eax, 123 ret MSVC’s result is exactly the same. There are just two instructions: the first places the value 123 into the EAX register, which is used by convention for storing the return value and the second one is RET, which returns execution to the caller. The caller will take the result from the EAX register. 2.2 ARM What about ARM? Listing 2.2: Optimizing Keil 6/2013 (ARM mode) f PROC MOV r0,#0x7b ; 123 BX lr ENDP ARM uses register R0 for returning results, so 123 is stored into R0 here. The return address (RA1 ) is not saved on the local stack in ARM, but rather in the LR2 register. So the BX LR instruction is jumping to that address, effectively, returning execution to the caller. It has to be noted that MOV is a confusing name for the instruction in both x86 and ARM ISAs. In fact, data is not moved, it’s rather copied. 2.3 MIPS There are two ways of registers naming that are used in the MIPS world. By number (from $0 to $31) or by pseudoname ($V0, $A0, etc). Assembly listing generated by GCC shows registers by number: Listing 2.3: Optimizing GCC 4.4.5 (assembly output) j $31 li $2,123 # 0x7b 1Return Address 2Link Register 4
  • 29. CHAPTER 2. SIMPLEST POSSIBLE FUNCTION 2.3. MIPS …while IDA3 — by pseudoname: Listing 2.4: Optimizing GCC 4.4.5 (IDA) jr $ra li $v0, 0x7B So the $2 (or $V0) register is used to store the function result. LI is “Load Immediate”. The other instruction is jump instruction (J or JR) which returns execution flow to the caller, jumping to the address in $31 (or $RA) register. This is the register analogous to LR in ARM. But why the load instruction (LI) and the jump instruction (J or JR) are swapped? This is merely RISC feature called “branch delay slot”. We don’t need to get into details here. We just need to remember that: in MIPS, the instruction following jump or branch instruction is executed before the jump/brunch instruction itslef. Hence, branch instruction always swap place with the instruction, which must be executed beforehand. 2.3.1 Note about MIPS instruction/register names Register names and instruction names in MIPS world are traditionally written in lowercase. But I’ve decided to stick to uppercase, because the instruction and register names of other ISAs are all written in uppercase in this book. 3Interactive Disassembler and debugger developed by Hex-Rays 5
  • 30. CHAPTER 3. HELLO, WORLD! Chapter 3 Hello, world! Let’s continue with the famous example from the “The C programming Language”[Ker88] book: #include <stdio.h> int main() { printf("hello, worldn"); return 0; } 3.1 x86 3.1.1 MSVC Let’s compile it in MSVC 2010: cl 1.cpp /Fa1.asm (/Fa option instructs the compiler to generate assembly listing file) Listing 3.1: MSVC 2010 CONST SEGMENT $SG3830 DB 'hello, world', 0AH, 00H CONST ENDS PUBLIC _main EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _main PROC push ebp mov ebp, esp push OFFSET $SG3830 call _printf add esp, 4 xor eax, eax pop ebp ret 0 _main ENDP _TEXT ENDS MSVC produces assembly listings in Intel-syntax. The difference between Intel-syntax and AT&T-syntax will be discussed in 3.1.3 on the next page. The compiler generated 1.obj file, which is to be linked into 1.exe. In our case, the file contains two segments: CONST (for data constants) and _TEXT (for code). The string ``hello, world'' in C/C++ has type const char[] [Str13, p176, 7.3.2], however it does not have its own name. The compiler needs to deal with the string somehow so it defines the internal name $SG3830 for it. That is why the example may be rewritten as follows: #include <stdio.h> const char $SG3830[]="hello, worldn"; 6
  • 31. CHAPTER 3. HELLO, WORLD! 3.1. X86 int main() { printf($SG3830); return 0; } Let’s go back to the assembly listing. As we can see, the string is terminated by a zero byte, which is standard for C/C++ strings. More about C strings: 57.1.1 on page 646. In the code segment, _TEXT, there is only one function so far: main(). The function main() starts with prologue code and ends with epilogue code (like almost any function) 1 . After the function prologue we see the call to the printf() function: CALL _printf. Before the call the string address (or a pointer to it) containing our greeting is placed on the stack with the help of the PUSH instruction. When the printf() function returns the control to the main() function, the string address (or a pointer to it) is still on the stack. Since we do not need it anymore, the stack pointer (the ESP register) needs to be corrected. ADD ESP, 4 means add 4 to the ESP register value. Why 4? Since this is 32-bit program, we need exactly 4 bytes for address passing through the stack. If it was x64 code we would need 8 bytes. ``ADD ESP, 4'' is effectively equivalent to ``POP register'' but without using any register2 . Some compilers (like the Intel C++ Compiler) in the same situation may emit POP ECX instead of ADD (e.g., such a pattern can be observed in the Oracle RDBMS code as it is compiled with the Intel C++ compiler). This instruction has almost the same effect but the ECX register contents will be overwritten. The Intel C++ compiler probably uses POP ECX since this instruction’s opcode is shorter than ADD ESP, x (1 byte against 3). Here is an example: Listing 3.2: Oracle RDBMS 10.2 Linux (app.o file) .text:0800029A push ebx .text:0800029B call qksfroChild .text:080002A0 pop ecx Read more about the stack in section ( 5 on page 22). After calling printf(), the original C/C++ code contains the statement return 0 —return 0 as the result of the main() function. In the generated code this is implemented by the instruction XOR EAX, EAX XOR is in fact just “eXclusive OR” 3 but the compilers often use it instead of MOV EAX, 0 —again because it is a slightly shorter opcode (2 bytes against 5). Some compilers emit SUB EAX, EAX, which means SUBtract the value in the EAX from the value in EAX, which in any case resulting in zero. The last instruction RET returns the control to the caller. Usually, this is C/C++ CRT4 code, which in its turn returns the control to the OS5 . 3.1.2 GCC Now let’s try to compile the same C/C++ code in the GCC 4.4.1 compiler in Linux: gcc 1.c -o 1 Next, with the assistance of the IDA disassembler, let’s see how the main() function was created. (IDA, like MSVC, uses Intel-syntax) 6 . Listing 3.3: code in IDA main proc near var_10 = dword ptr -10h push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov eax, offset aHelloWorld ; "hello, worldn" mov [esp+10h+var_10], eax 1You can read more about it in section about function prolog and epilog ( 4 on page 21). 2CPU flags, however, are modified 3wikipedia 4C runtime library : 68.1 on page 683 5Operating System 6N.B. We could also have GCC produce assembly listings in Intel-syntax by applying the options -S -masm=intel. 7
  • 32. CHAPTER 3. HELLO, WORLD! 3.1. X86 call _printf mov eax, 0 leave retn main endp The result is almost the same. The address of the “hello, world” string (stored in the data segment) is loaded in the EAX register first and then it is saved onto the stack. In addition, the function prologue contains AND ESP, 0FFFFFFF0h —this instruction aligns the ESP register value on a 16-byte boundary. This results in all values in the stack being aligned the same way (The CPU performs better if the values it is dealing with are located in memory at addresses aligned on a 4- or 16-byte boundary)7 . SUB ESP, 10h allocates 16 bytes on the stack. Although, as we can see hereafter, only 4 are necessary here. This is because the size of the allocated stack is also aligned on a 16-byte boundary. The string address (or a pointer to the string) is then stored directly onto the stack without using the PUSH instruction. var_10 —is a local variable and is also an argument for printf(). Read about it below. Then the printf() function is called. Unlike MSVC, when GCC is compiling without optimization turned on, it emits MOV EAX, 0 instead of a shorter opcode. The last instruction, LEAVE —is the equivalent of the MOV ESP, EBP and POP EBP instruction pair —in other words, this instruction sets the stack pointer (ESP) back and restores the EBP register to its initial state. This is necessary since we modified these register values (ESP and EBP) at the beginning of the function (executing MOV EBP, ESP / AND ESP, ...). 3.1.3 GCC: AT&T syntax Let’s see how this can be represented in assembly language AT&T syntax. This syntax is much more popular in the UNIX- world. Listing 3.4: let’s compile in GCC 4.7.3 gcc -S 1_1.c We get this: Listing 3.5: GCC 4.7.3 .file "1_1.c" .section .rodata .LC0: .string "hello, worldn" .text .globl main .type main, @function main: .LFB0: .cfi_startproc pushl %ebp .cfi_def_cfa_offset 8 .cfi_offset 5, -8 movl %esp, %ebp .cfi_def_cfa_register 5 andl $-16, %esp subl $16, %esp movl $.LC0, (%esp) call printf movl $0, %eax leave .cfi_restore 5 .cfi_def_cfa 4, 4 ret .cfi_endproc .LFE0: .size main, .-main .ident "GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3" .section .note.GNU-stack,"",@progbits The listing contains many macros (beginning with dot). These are not interesting for us at the moment. For now, for the sake of simplification, we can ignore them (except the .string macro which encodes a null-terminated character sequence just like a C-string). Then we’ll see this 7Wikipedia: Data structure alignment 8
  • 33. CHAPTER 3. HELLO, WORLD! 3.2. X86-64 8 : Listing 3.6: GCC 4.7.3 .LC0: .string "hello, worldn" main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp movl $.LC0, (%esp) call printf movl $0, %eax leave ret Some of the major differences between Intel and AT&T syntax are: • Source and destination operands are written in opposite order. In Intel-syntax: <instruction> <destination operand> <source operand>. In AT&T syntax: <instruction> <source operand> <destination operand>. Here is a way to easy memorise the difference: when you deal with Intel-syntax, you can imagine that there is an equality sign (=) between operands and when you deal with AT&T-syntax imagine there is a right arrow (→) 9 . • AT&T: Before register names, a percent sign must be written (%) and before numbers a dollar sign ($). Parentheses are used instead of brackets. • AT&T: Suffix is added to instructions to define the operand size: – q — quad (64 bits) – l — long (32 bits) – w — word (16 bits) – b — byte (8 bits) Let’s go back to the compiled result: it is identical to what we saw in IDA. With one subtle difference: 0FFFFFFF0h is presented as $-16. It is the same thing: 16 in the decimal system is 0x10 in hexadecimal. -0x10 is equal to 0xFFFFFFF0 (for a 32-bit data type). One more thing: the return value is to be set to 0 by using usual MOV, not XOR. MOV just loads value to a register. Its name is misnomer (data is not moved but rather copied). In other architectures, this instruction is named “LOAD” and/or “STORE” or something similar. 3.2 x86-64 3.2.1 MSVC—x86-64 Let’s also try 64-bit MSVC: Listing 3.7: MSVC 2012 x64 $SG2989 DB 'hello, world', 0AH, 00H main PROC sub rsp, 40 lea rcx, OFFSET FLAT:$SG2989 call printf xor eax, eax add rsp, 40 ret 0 main ENDP 8This GCC option can be used to eliminate “unnecessary” macros: -fno-asynchronous-unwind-tables 9 By the way, in some C standard functions (e.g., memcpy(), strcpy()) the arguments are listed in the same way as in Intel-syntax: pointer to the destination memory block at the beginning and then pointer to the source memory block. 9
  • 34. CHAPTER 3. HELLO, WORLD! 3.2. X86-64 In x86-64, all registers were extended to 64-bit and now their names have an R- prefix. In order to use the stack less often (in other words, to access external memory/cache less often), there exists a popular way to pass function arguments via registers (fastcall : 64.3 on page 664 ). I.e., a part of the function arguments are passed in registers, the rest—via the stack. In Win64, 4 function arguments are passed in RCX, RDX, R8, R9 registers. That is what we see here: a pointer to the string for printf() is now passed not in stack, but in the RCX register. The pointers are 64-bit now, so they are passed in the 64-bit registers (which have the R- prefix). However, for backward compatibility, it is still possible to access the 32-bit parts, using the E- prefix. This is how RAX/EAX/AX/AL looks like in 64-bit x86-compatible CPUs: 7th (byte number) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL The main() function returns an int-typed value, which is, in the C/C++, for better backward compatibility and portability, still 32-bit, so that is why the EAX register is cleared at the function end (i.e., 32-bit part of register) instead of RAX. There are also 40 bytes allocated in the local stack. This is called “shadow space”, about which we are going to talk later: 8.2.1 on page 89. 3.2.2 GCC—x86-64 Let’s also try GCC in 64-bit Linux: Listing 3.8: GCC 4.4.6 x64 .string "hello, worldn" main: sub rsp, 8 mov edi, OFFSET FLAT:.LC0 ; "hello, worldn" xor eax, eax ; number of vector registers passed call printf xor eax, eax add rsp, 8 ret A method to pass function arguments in registers is also used in Linux, *BSD and Mac OS X [Mit13]. The first 6 arguments are passed in the RDI, RSI, RDX, RCX, R8, R9 registers, and the rest—via the stack. So the pointer to the string is passed in EDI (32-bit part of register). But why not use the 64-bit part, RDI? It is important to keep in mind that all MOV instructions in 64-bit mode that write something into the lower 32-bit register part, also clear the higher 32-bits[Int13]. I.e., the MOV EAX, 011223344h writes a value into RAX correctly, since the higher bits will be cleared. If we open the compiled object file (.o), we can also see all instruction’s opcodes 10 : Listing 3.9: GCC 4.4.6 x64 .text:00000000004004D0 main proc near .text:00000000004004D0 48 83 EC 08 sub rsp, 8 .text:00000000004004D4 BF E8 05 40 00 mov edi, offset format ; "hello, worldn" .text:00000000004004D9 31 C0 xor eax, eax .text:00000000004004DB E8 D8 FE FF FF call _printf .text:00000000004004E0 31 C0 xor eax, eax .text:00000000004004E2 48 83 C4 08 add rsp, 8 .text:00000000004004E6 C3 retn .text:00000000004004E6 main endp As we can see, the instruction that writes into EDI at 0x4004D4 occupies 5 bytes. The same instruction writing a 64-bit value into RDI occupies 7 bytes. Apparently, GCC is trying to save some space. Besides, it can be sure that the data segment containing the string will not be allocated at the addresses higher than 4GiB. We also see that the EAX register was cleared before the printf() function call. This is done because the number of used vector registers is passed in EAX by standard: “with variable arguments passes information about the number of vector registers used”[Mit13]. 10This must be enabled in Options → Disassembly → Number of opcode bytes 10
  • 35. CHAPTER 3. HELLO, WORLD! 3.3. GCC—ONE MORE THING 3.3 GCC—one more thing The fact that an anonymous C-string has const type ( 3.1.1 on page 6), and the fact that C-strings allocated in constants segment are guaranteed to be immutable, has an interesting consequence: the compiler may use a specific part of string. Let’s try this example: #include <stdio.h> int f1() { printf ("worldn"); } int f2() { printf ("hello worldn"); } int main() { f1(); f2(); } Common C/C++-compilers (including MSVC) allocates two strings, but let’s see what GCC 4.8.1 does: Listing 3.10: GCC 4.8.1 + IDA listing f1 proc near s = dword ptr -1Ch sub esp, 1Ch mov [esp+1Ch+s], offset s ; "worldn" call _puts add esp, 1Ch retn f1 endp f2 proc near s = dword ptr -1Ch sub esp, 1Ch mov [esp+1Ch+s], offset aHello ; "hello " call _puts add esp, 1Ch retn f2 endp aHello db 'hello ' s db 'world',0xa,0 Indeed: when we print the “hello world” string, these two words are positioned in memory adjacently and puts() called from f2() function is not aware this string is divided. It’s not divided in fact, it’s divided only “virtually”, in this listing. When puts() is called from f1(), it uses “world” string plus zero byte. puts() is not aware there is something before this string! This clever trick is often used by at least GCC and can save some memory. 3.4 ARM For my experiments with ARM processors, I used several compilers: • Popular in the embedded area Keil Release 6/2013. • Apple Xcode 4.6.3 IDE (with LLVM-GCC 4.2 compiler 11 ). • GCC 4.9 (Linaro) (for ARM64), available as win32-executables at http://go.yurichev.com/17325. 11It is indeed so: Apple Xcode 4.6.3 uses open-source GCC as front-end compiler and LLVM code generator 11
  • 36. CHAPTER 3. HELLO, WORLD! 3.4. ARM 32-bit ARM code is used in all cases in this book, if not mentioned otherwise. When we talk about 64-bit ARM here, it is called ARM64 here. 3.4.1 Non-optimizing Keil 6/2013 (ARM mode) Let’s start by compiling our example in Keil: armcc.exe --arm --c90 -O0 1.c The armcc compiler produces assembly listings in Intel-syntax but it has high-level ARM-processor related macros12 , but it is more important for us to see the instructions “as is” so let’s see the compiled result in IDA. Listing 3.11: Non-optimizing Keil 6/2013 (ARM mode) IDA .text:00000000 main .text:00000000 10 40 2D E9 STMFD SP!, {R4,LR} .text:00000004 1E 0E 8F E2 ADR R0, aHelloWorld ; "hello, world" .text:00000008 15 19 00 EB BL __2printf .text:0000000C 00 00 A0 E3 MOV R0, #0 .text:00000010 10 80 BD E8 LDMFD SP!, {R4,PC} .text:000001EC 68 65 6C 6C+aHelloWorld DCB "hello, world",0 ; DATA XREF: main+4 In the example, we can easily see each instruction has a size of 4 bytes. Indeed, we compiled our code for ARM mode, not for thumb. The very first instruction, ``STMFD SP!, {R4,LR}''13 , works as an x86 PUSH instruction, writing the values of two registers (R4 and LR) into the stack. Indeed, in the output listing from the armcc compiler, for the sake of simplification, actually shows the ``PUSH {r4,lr}'' instruction. But that is not quite precise. The PUSH instruction is only available in thumb mode. So, to make things less confusing, we’re doing this in IDA. This instruction decrements first the SP15 so it points to the place in the stack that is free for new entries, then it saves the values of the R4 and LR registers at the address stored in the modified SP. This instruction (like the PUSH instruction in thumb mode) is able to save several register values at once which can be very useful. By the way, this has no equivalent in x86. It can also be noted that the STMFD instruction is a generalization of the PUSH instruction (extending its features), since it can work with any register, not just with SP. In other words, STMFD may be used for storing pack of registers at the specified memory address. The ``ADR R0, aHelloWorld'' instruction adds or subtracts the value in the PC16 register to the offset where the “hello, world” string is located. How is the PC register used here, one might ask? This is so-called “position-independent code”. 17 Such code can be be executed at a non-fixed address in memory. In other words, this is PC-relative addressing. The ADR instruction takes into account the difference between the address of this instruction and the address where the string is located. This difference (offset) is always to be the same, no matter at what address our code is loaded by the OS. That’s why all we need is to add the address of the current instruction (from PC) in order to get the absolute memory address of our C-string. ``BL __2printf''18 instruction calls the printf() function. Here’s how this instruction works: • store the address following the BL instruction (0xC) into the LR; • then pass the control to the printf() by writing its address into the PC register. When printf() finishes its execution it must have information about where it needs to return the control to. That’s why each function passes control to the address stored in the LR register. That is a difference between “pure” RISC-processors like ARM and CISC19 -processors like x86, where the return address is usually stored on the stack20 . By the way, an absolute 32-bit address or offset cannot be encoded in the 32-bit BL instruction because it only has space for 24 bits. As we may remember, all ARM-mode instructions have a size of 4 bytes (32 bits). Hence, they can only be located on 4-byte boundary addresses. This implies that the last 2 bits of the instruction address (which are always zero bits) may be omitted. In summary, we have 26 bits for offset encoding. This is enough to encode current_PC ± ≈ 32M. Next, the ``MOV R0, #0''21 instruction just writes 0 into the R0 register. That’s because our C-function returns 0 and the return value is to be placed in the R0 register. 12e.g. ARM mode lacks PUSH/POP instructions 13STMFD14 15stack pointer. SP/ESP/RSP in x86/x64. SP in ARM. 16Program Counter. IP/EIP/RIP in x86/64. PC in ARM. 17Read more about it in relevant section ( 67.1 on page 678) 18Branch with Link 19Complex instruction set computing 20Read more about this in next section ( 5 on page 22) 21MOVe 12
  • 37. CHAPTER 3. HELLO, WORLD! 3.4. ARM The last instruction ``LDMFD SP!, R4,PC''22 is an inverse instruction of STMFD. It loads values from the stack (or any other memory place) in order to save them into R4 and PC, and increments the stack pointer SP. It works like POP here. N.B. The very first instruction STMFD saved the R4 and LR registers pair on the stack, but R4 and PC are restored during the LDMFD execution. As I mentioned before, the address of the place where each function must return control to is usually saved in the LR register. The very first instruction saves its value in the stack because the same register will be used by our main() function when calling printf(). In the function’s end, this value can be written directly to the PC register, thus passing control to where our function was called. Since main() is usually the primary function in C/C++, the control will be returned to the OS loader or to a point in a CRT, or something like that. DCB is an assembly language directive defining an array of bytes or ASCII strings, akin to the DB directive in x86-assembly language. 3.4.2 Non-optimizing Keil 6/2013 (thumb mode) Let’s compile the same example using Keil in thumb mode: armcc.exe --thumb --c90 -O0 1.c We are getting (in IDA): Listing 3.12: Non-optimizing Keil 6/2013 (thumb mode) + IDA .text:00000000 main .text:00000000 10 B5 PUSH {R4,LR} .text:00000002 C0 A0 ADR R0, aHelloWorld ; "hello, world" .text:00000004 06 F0 2E F9 BL __2printf .text:00000008 00 20 MOVS R0, #0 .text:0000000A 10 BD POP {R4,PC} .text:00000304 68 65 6C 6C+aHelloWorld DCB "hello, world",0 ; DATA XREF: main+2 We can easily spot the 2-byte (16-bit) opcodes. This is, as I mentioned, thumb. The BL instruction, however, consists of two 16-bit instructions. This is because it is impossible to load an offset for the printf() function into PC while using the small space in one 16-bit opcode. Therefore, the first 16-bit instruction loads the higher 10 bits of the offset and the second instruction loads the lower 11 bits of the offset. As I mentioned, all instructions in thumb mode have a size of 2 bytes (or 16 bits). This implies it is impossible for a thumb-instruction to be at an odd address whatsoever. Given the above, the last address bit may be omitted while encoding instructions. In summary, BL thumb-instruction can encode the address current_PC ± ≈ 2M. As for the other instructions in the function: PUSH and POP work here just like the described STMFD/LDMFD only the SP register is not mentioned explicitly here. ADR works just like in the previous example. MOVS writes 0 into the R0 register in order to return zero. 3.4.3 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) Xcode 4.6.3 without optimization turned on produces a lot of redundant code so we’ll study optimized output, where the instruction count is as small as possible, setting the compiler switch -O3. Listing 3.13: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) __text:000028C4 _hello_world __text:000028C4 80 40 2D E9 STMFD SP!, {R7,LR} __text:000028C8 86 06 01 E3 MOV R0, #0x1686 __text:000028CC 0D 70 A0 E1 MOV R7, SP __text:000028D0 00 00 40 E3 MOVT R0, #0 __text:000028D4 00 00 8F E0 ADD R0, PC, R0 __text:000028D8 C3 05 00 EB BL _puts __text:000028DC 00 00 A0 E3 MOV R0, #0 __text:000028E0 80 80 BD E8 LDMFD SP!, {R7,PC} __cstring:00003F62 48 65 6C 6C+aHelloWorld_0 DCB "Hello world!",0 The instructions STMFD and LDMFD are already familiar to us. The MOV instruction just writes the number 0x1686 into the R0 register. This is the offset pointing to the “Hello world!” string. The R7 register (as it is standardized in [App10]) is a frame pointer. More on that below. The MOVT R0, #0 (MOVe Top) instruction writes 0 into higher 16 bits of the register. The issue here is that the generic MOV instruction in ARM mode may write only the lower 16 bits of the register. Remember, all instruction opcodes in ARM 22LDMFD23 13
  • 38. CHAPTER 3. HELLO, WORLD! 3.4. ARM mode are limited in size to 32 bits. Of course, this limitation is not related to moving data between registers. That’s why an additional instruction MOVT exists for writing into the higher bits (from 16 to 31 inclusive). Its usage here, however, is redundant because the ``MOV R0, #0x1686'' instruction above cleared the higher part of the register. This is probably a shortcoming of the compiler. The ``ADD R0, PC, R0'' instruction adds the value in the PC to the value in the R0, to calculate absolute address of the “Hello world!” string. As we already know, it is “position-independent code” so this correction is essential here. The BL instruction calls the puts() function instead of printf(). GCC replaced the first printf() call with puts(). Indeed: printf() with a sole argument is almost analogous to puts(). Almost, because the two functions are producing the same result only in case the string does not contain printf format identifiers starting with %. In case it does, the effect of these two functions would be different 24 . Why did the compiler replace the printf() with puts()? Probably because puts() is faster 25 . puts() works faster because it just passes characters to stdout without comparing every one of them with the % symbol. Next, we see the familiar ``MOV R0, #0'' instruction intended to set the R0 register to 0. 3.4.4 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) By default Xcode 4.6.3 generates code for thumb-2 in this manner: Listing 3.14: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) __text:00002B6C _hello_world __text:00002B6C 80 B5 PUSH {R7,LR} __text:00002B6E 41 F2 D8 30 MOVW R0, #0x13D8 __text:00002B72 6F 46 MOV R7, SP __text:00002B74 C0 F2 00 00 MOVT.W R0, #0 __text:00002B78 78 44 ADD R0, PC __text:00002B7A 01 F0 38 EA BLX _puts __text:00002B7E 00 20 MOVS R0, #0 __text:00002B80 80 BD POP {R7,PC} ... __cstring:00003E70 48 65 6C 6C 6F 20+aHelloWorld DCB "Hello world!",0xA,0 The BL and BLX instructions in thumb mode, as we recall, are encoded as a pair of 16-bit instructions. In thumb-2 these surrogate opcodes are extended in such a way so that new instructions may be encoded here as 32-bit instructions. That is obvious considering that the opcodes of the thumb-2 instructions always begin with 0xFx or 0xEx. But in the IDA listing the opcode bytes are swapped because for ARM processor the instructions are encoded as follows: last byte comes first and after that comes the first one (for thumb and thumb-2 modes) or for instructions in ARM mode the fourth byte comes first, then the third, then the second and finally the first (due to different endianness). So as we can see, the MOVW, MOVT.W and BLX instructions begin with 0xFx. One of the thumb-2 instructions is ``MOVW R0, #0x13D8'' —it stores a 16-bit value into the lower part of the R0 register, clearing the higher bits. Also, ``MOVT.W R0, #0'' works just like MOVT from the previous example only it works in thumb-2. Among the other differences, the BLX instruction is used in this case instead of the BL. The difference is that, be- sides saving the RA in the LR register and passing control to the puts() function, the processor is also switching from thumb/thumb-2 mode to ARM mode (or back). This instruction is placed here since the instruction to which control is passed looks like (it is encoded in ARM mode): __symbolstub1:00003FEC _puts ; CODE XREF: _hello_world+E __symbolstub1:00003FEC 44 F0 9F E5 LDR PC, =__imp__puts This is essentially jump to place where puts() address is written in imports’ section. So, the observant reader may ask: why not call puts() right at the point in the code where it is needed? Because it is not very space-efficient. Almost any program uses external dynamic libraries (like DLL in Windows, .so in *NIX or .dylib in Mac OS X). The dynamic libraries contain frequently used library functions, including the standard C-function puts(). In an executable binary file (Windows PE .exe, ELF or Mach-O) an import section is present. This is a list of symbols (functions or global variables) imported from external modules along with the names of the modules themselves. The OS loader loads all modules it needs and, while enumerating import symbols in the primary module, determines the correct addresses of each symbol. In our case, __imp__puts is a 32-bit variable used by the OS loader to store the correct address of the function in an external library. Then the LDR instruction just reads the 32-bit value from this variable and writes it into the PC register, passing control to it. 24It has also to be noted the puts() does not require a ’n’ new line symbol at the end of a string, so we do not see it here. 25http://go.yurichev.com/17063 14
  • 39. CHAPTER 3. HELLO, WORLD! 3.4. ARM So, in order to reduce the time the OS loader needs for completing this procedure, it is good idea if it writes the address of each symbol only once, to a dedicated place. Besides, as we have already figured out, it is impossible to load a 32-bit value into a register while using only one instruction without a memory access. Therefore, the optimal solution is to allocate a separate function working in ARM mode with sole goal to pass control to the dynamic library and then to jump to this short one-instruction function (the so-called thunk function) from the thumb-code. By the way, in the previous example (compiled for ARM mode) the control is passed by the BL to the same thunk function. The processor mode, however, is not being switched (hence the absence of an “X” in the instruction mnemonic). 3.4.5 ARM64 GCC Let’s compile the example using GCC 4.8.1 in ARM64: Listing 3.15: Non-optimizing GCC 4.8.1 + objdump 1 0000000000400590 <main>: 2 400590: a9bf7bfd stp x29, x30, [sp,#-16]! 3 400594: 910003fd mov x29, sp 4 400598: 90000000 adrp x0, 400000 <_init-0x3b8> 5 40059c: 91192000 add x0, x0, #0x648 6 4005a0: 97ffffa0 bl 400420 <puts@plt> 7 4005a4: 52800000 mov w0, #0x0 // #0 8 4005a8: a8c17bfd ldp x29, x30, [sp],#16 9 4005ac: d65f03c0 ret 10 11 ... 12 13 Contents of section .rodata: 14 400640 01000200 00000000 48656c6c 6f210a00 ........Hello!.. There are no thumb and thumb-2 modes in ARM64, only ARM, so there are 32-bit instructions only. Registers count is doubled: B.4.1 on page 945. 64-bit registers has X- prefixes, while its 32-bit parts—W-. The STP instruction (Store Pair) saves two registers in the stack simultaneously: X29 in X30. Of course, this instruction is able to save this pair at a random place of memory, but the SP register is specified here, so the pair is saved in the stack. ARM64 registers are 64-bit ones, each has a size of 8 bytes, so one needs 16 bytes for saving two registers. Exclamation mark after operand mean that 16 is to be subtracted from SP first, and only then values from registers pair are to be written into the stack. This is also called pre-index. About the difference between post-index and pre-index, read here: 28.2 on page 445. Hence, in the terms of more familiar x86, the first instruction is just an analogue to pair of PUSH X29 and PUSH X30. X29 is used as FP26 in ARM64, and X30 as LR, so that’s why they are saved in the function prologue and restored in the function epilogue. The second instruction copies SP in X29 (or FP). This is done to set up the function stack frame. ADRP and ADD instructions are used to fill the string “Hello!” address into the X0 register, because the first function argument is passed in this register. There are no instructions, whatsoever, in ARM that can store a large number into a register (because the instruction length is limited to 4 bytes, read more about it here: 28.3.1 on page 445). So several instructions must be utilised. The first instruction (ADRP) writes address of 4Kb page where the string is located into X0, and the the second one (ADD) just adds reminder to the address. More about that in: 28.4 on page 447. 0x400000 + 0x648 = 0x400648, and we see our “Hello!” C-string in the .rodata data segment at this address. puts() is called afterwards using BL instruction. This was already discussed: 3.4.3 on page 14. MOV instruction writes 0 into W0. W0 is low 32 bits of 64-bit X0 register: High 32-bit part low 32-bit part X0 W0 The function result is returned via X0 and main() returns 0, so that’s how the return result is prepared. But why using the 32-bit part? Because int data type in ARM64, just like in x86-64, is still 32-bit, for better compatibility. So if a function returns 32-bit int, only the low 32 bits of X0 register has to be filled. In order to verify this, I changed my example slightly and recompiled it. Now main() returns 64-bit value: Listing 3.16: main() returning a value of uint64_t type #include <stdio.h> #include <stdint.h> 26Frame Pointer 15
  • 40. CHAPTER 3. HELLO, WORLD! 3.5. MIPS uint64_t main() { printf ("Hello!n"); return 0; } The result is the same, but that’s how MOV at that line looks like now: Listing 3.17: Non-optimizing GCC 4.8.1 + objdump 4005a4: d2800000 mov x0, #0x0 // #0 LDP (Load Pair) then restores X29 and X30 registers. There is no exclamation mark after the instruction: this implies that the value is first loaded from the stack, only then SP it is increased by 16. This is called post-index. New instruction appeared in ARM64: RET. It works just as BX LR, only a special hint bit is added, informing the CPU that this is a return from a function, not just another jump instruction, so it can execute it more optimally. Due to the simplicity of the function, optimizing GCC generates the very same code. 3.5 MIPS 3.5.1 Word about “global pointer” One important MIPS concept is “global pointer”. As we may already know, each MIPS instruction has size of 32 bits, so it’s impossible to embed 32-bit address into one instruction: a pair has to be used for this (like GCC did in our example for the text string address loading). It’s possible, however, to load data from the address in range of register − 32768...register + 32767 using one single instruction (because 16 bits of signed offset could be encoded in single instruction). So we can allocate some register for this purpose and also allocate 64KiB area of most used data. This allocated register is called “global pointer” and it points to the middle of the 64KiB area. This area usually contains global variables and addresses of imported functions like printf(), because GCC developers decided that getting address of some function must be as fast as single instruction execution instead of two. In an ELF file this 64KiB area is located partly in .sbss (“small BSS27 ”, for not initialized data) and .sdata (“small data”, for initialized data) sections. This implies that the programmer may choose what data he/she wants to be accessed fast and place it into .sdata/.sbss. Some old-school programmers may recall the MS-DOS memory model 94 on page 880 or the MS-DOS memory managers like XMS/EMS where all memory was divided in 64KiB blocks. This concept is not unique to MIPS. At least PowerPC uses this technique as well. 3.5.2 Optimizing GCC Listing 3.18: Optimizing GCC 4.4.5 (assembly output) 1 $LC0: 2 ; 000 is zero byte in octal base: 3 .ascii "Hello, world!012000" 4 main: 5 ; function prologue. 6 ; set GP: 7 lui $28,%hi(__gnu_local_gp) 8 addiu $sp,$sp,-32 9 addiu $28,$28,%lo(__gnu_local_gp) 10 ; save RA to the local stack: 11 sw $31,28($sp) 12 ; load address of puts() function from GP to $25: 13 lw $25,%call16(puts)($28) 14 ; load address of the text string to $4 ($a0): 15 lui $4,%hi($LC0) 16 ; jump to puts(), saving return address in link register: 17 jalr $25 18 addiu $4,$4,%lo($LC0) ; branch delay slot 19 ; restore RA: 20 lw $31,28($sp) 21 ; copy 0 from $zero to $v0: 22 move $2,$0 23 ; return by jumping to address in RA: 24 j $31 25 ; function epilogue: 27Block Started by Symbol 16
  • 41. CHAPTER 3. HELLO, WORLD! 3.5. MIPS 26 addiu $sp,$sp,32 ; branch delay slot The $GP register is set in the function prologue to point the middle of this area. The RA register is also saved in the local stack. puts() is also used here instead of printf(). The address of the puts() function is loaded into $25 using LW the instruction (“Load Word”). Then the address of the text string is loaded to $4 using LUI (“Load Upper Immediate”) and ADDIU (“Add Immediate Unsigned Word”) instruction pair. LUI sets the high 16 bits of the register (hence “upper” word in instruction name) and ADDIU adds the lower 16 bits of the address. ADDIU follows JALR (remember branch delay slots?). The register $4 is also called $A0, which is used for passing the first function argument 28 . JALR (“Jump and Link Register”) jumps to the address stored in the $25 register (address of puts()) while saving the address of the next instruction (LW) in RA. This is very similar to ARM. Oh, and one important thing is that the address saved in RA is not the address of the next instruction (because it’s in a delay slot and is executed before the jump instruction), but the address of the instruction after the next one (after the delay slot). Hence, PC + 8 is written to RA during the execution of JALR, in our case, this is the address of the LW instruction next to ADDIU. LW (“Load Word”) at line 19 restores RA from the local stack (this instruction is rather part of function epilogue). MOVE at line 22 copies the value from $0 ($ZERO) register to $2 ($V0). MIPS has a constant register, which always holds zero. Apparently, the MIPS developers came with the idea that zero is in fact the busiest constant in the computer programming, so let’s just use $0 register every time zero is needed. Another interesting fact is that MIPS lacks instruction which transfers data between registers. In fact, MOVE DST, SRC is ADD DST, SRC, $ZERO (DST = SRC + 0), which does the same. Apparently, MIPS developers wanted to have compact opcode table. This does not mean an actual addition happens at each MOVE instruction. Most likely, the CPU optimizes these pseudoinstructions and ALU29 is never used. J at line 24 jumps to the address in RA, which is effectively performing return from the function. ADDIU after J is in fact executed before J (remember branch delay slots?) and is part of function epilogue. Here is also a listing generated by IDA. Each register here has its own pseudoname: Listing 3.19: Optimizing GCC 4.4.5 (IDA) 1 .text:00000000 main: 2 .text:00000000 3 .text:00000000 var_10 = -0x10 4 .text:00000000 var_4 = -4 5 .text:00000000 6 ; function prologue. 7 ; set GP: 8 .text:00000000 lui $gp, (__gnu_local_gp >> 16) 9 .text:00000004 addiu $sp, -0x20 10 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) 11 ; save RA to the local stack: 12 .text:0000000C sw $ra, 0x20+var_4($sp) 13 ; save GP to the local stack: 14 ; by some reason, this instruction is missing in GCC assembly output: 15 .text:00000010 sw $gp, 0x20+var_10($sp) 16 ; load address of puts() function from GP to $t9: 17 .text:00000014 lw $t9, (puts & 0xFFFF)($gp) 18 ; form address of the text string in $a0: 19 .text:00000018 lui $a0, ($LC0 >> 16) # "Hello, world!" 20 ; jump to puts(), saving return address in link register: 21 .text:0000001C jalr $t9 22 .text:00000020 la $a0, ($LC0 & 0xFFFF) # "Hello, world!" 23 ; restore RA: 24 .text:00000024 lw $ra, 0x20+var_4($sp) 25 ; copy 0 from $zero to $v0: 26 .text:00000028 move $v0, $zero 27 ; return by jumping to address in RA: 28 .text:0000002C jr $ra 29 ; function epilogue: 30 .text:00000030 addiu $sp, 0x20 The instruction at line 15 saves GP value into the local stack, and this instruction is missing mysteriously from the GCC output listing, maybe by a GCC error30 . The GP value has to be saved indeed, because each function can use its own 64KiB data window. The register containing the puts() address is called $T9, because registers prefixed with T- are called “temporaries” and their contents may not be preserved. 3.5.3 Non-optimizing GCC 28The MIPS registers table is available in appendix C.1 on page 947 29Arithmetic logic unit 30Apparently, functions generating listings are not so critical to GCC users, so some unfixed errors may still exist. 17
  • 42. CHAPTER 3. HELLO, WORLD! 3.5. MIPS Listing 3.20: Non-optimizing GCC 4.4.5 (assembly output) 1 $LC0: 2 .ascii "Hello, world!012000" 3 main: 4 ; function prologue. 5 ; save GP and FP in the stack: 6 addiu $sp,$sp,-32 7 sw $31,28($sp) 8 sw $fp,24($sp) 9 ; set FP (stack frame pointer): 10 move $fp,$sp 11 ; set GP: 12 lui $28,%hi(__gnu_local_gp) 13 addiu $28,$28,%lo(__gnu_local_gp) 14 ; load address of the text string: 15 lui $2,%hi($LC0) 16 addiu $4,$2,%lo($LC0) 17 ; load address of puts() address using GP: 18 lw $2,%call16(puts)($28) 19 nop 20 ; call to puts(): 21 move $25,$2 22 jalr $25 23 nop ; branch delay slot 24 25 ; restore GP from local stack: 26 lw $28,16($fp) 27 ; set register $2 ($V0) to zero: 28 move $2,$0 29 ; function epilogue. 30 ; restore SP: 31 move $sp,$fp 32 ; restore RA: 33 lw $31,28($sp) 34 ; restore FP: 35 lw $fp,24($sp) 36 addiu $sp,$sp,32 37 ; jump to RA: 38 j $31 39 nop ; branch delay slot Non-optimizing GCC is more verbose. We see here that register FP is used as a pointer to the stack frame. We also see 3 NOP31 s. The second and third of which follow the branch instructions. I guess (not sure, though) that the GCC compiler always adds NOPs (because of branch delay slots) after branch instructions and then, if optimization is turned on, maybe eliminates them. So in this case they are left here. Here is also IDA listing: Listing 3.21: Non-optimizing GCC 4.4.5 (IDA) 1 .text:00000000 main: 2 .text:00000000 3 .text:00000000 var_10 = -0x10 4 .text:00000000 var_8 = -8 5 .text:00000000 var_4 = -4 6 .text:00000000 7 ; function prologue. 8 ; save GP and FP in the stack: 9 .text:00000000 addiu $sp, -0x20 10 .text:00000004 sw $ra, 0x20+var_4($sp) 11 .text:00000008 sw $fp, 0x20+var_8($sp) 12 ; set FP (stack frame pointer): 13 .text:0000000C move $fp, $sp 14 ; set GP: 15 .text:00000010 la $gp, __gnu_local_gp 16 .text:00000018 sw $gp, 0x20+var_10($sp) 17 ; load address of the text string: 18 .text:0000001C lui $v0, (aHelloWorld >> 16) # "Hello, world!" 19 .text:00000020 addiu $a0, $v0, (aHelloWorld & 0xFFFF) # "Hello, world!" 20 ; load address of puts() address using GP: 31No OPeration 18
  • 43. CHAPTER 3. HELLO, WORLD! 3.5. MIPS 21 .text:00000024 lw $v0, (puts & 0xFFFF)($gp) 22 .text:00000028 or $at, $zero ; NOP 23 ; call to puts(): 24 .text:0000002C move $t9, $v0 25 .text:00000030 jalr $t9 26 .text:00000034 or $at, $zero ; NOP 27 ; restore GP from local stack: 28 .text:00000038 lw $gp, 0x20+var_10($fp) 29 ; set register $2 ($V0) to zero: 30 .text:0000003C move $v0, $zero 31 ; function epilogue. 32 ; restore SP: 33 .text:00000040 move $sp, $fp 34 ; restore RA: 35 .text:00000044 lw $ra, 0x20+var_4($sp) 36 ; restore FP: 37 .text:00000048 lw $fp, 0x20+var_8($sp) 38 .text:0000004C addiu $sp, 0x20 39 ; jump to RA: 40 .text:00000050 jr $ra 41 .text:00000054 or $at, $zero ; NOP Interestingly, IDA recognized LUI/ADDIU instructions pair and coalesces them into one LA (“Load Address”) pseudoin- struction at line 15. We may also see that this pseudoinstruction has size of 8 bytes! This is a pseudoinstruction (or macro) because it’s not a real MIPS instruction, but rather handy name for an instruction pair. Another thing is that IDA doesn’t recognize NOP instructions, so here they are at lines 22, 26 and 41. It is OR $AT, $ZERO. Essentially, this instruction applies OR operation to contents of $AT register with zero, which is, of course, idle instruction. MIPS, like many other ISAs, doesn’t have a separate NOP instruction. 3.5.4 Role of the stack frame in this example The address of the text string is passed in register. Why setup local stack anyway? The reason for this lies in the fact that registers RA and GP’s values has to be saved somewhere (because printf() is called), and the local stack is used for this purpose. If this was a leaf function, it would have been possible to get rid of the function prologue and epilogue, for example: 2.3 on page 4. 3.5.5 Optimizing GCC: load it into GDB Listing 3.22: sample GDB session root@debian-mips:~# gcc hw.c -O3 -o hw root@debian-mips:~# gdb hw GNU gdb (GDB) 7.0.1-debian Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "mips-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /root/hw...(no debugging symbols found)...done. (gdb) b main Breakpoint 1 at 0x400654 (gdb) run Starting program: /root/hw Breakpoint 1, 0x00400654 in main () (gdb) set step-mode on (gdb) disas Dump of assembler code for function main: 0x00400640 <main+0>: lui gp,0x42 0x00400644 <main+4>: addiu sp,sp,-32 0x00400648 <main+8>: addiu gp,gp,-30624 0x0040064c <main+12>: sw ra,28(sp) 0x00400650 <main+16>: sw gp,16(sp) 0x00400654 <main+20>: lw t9,-32716(gp) 0x00400658 <main+24>: lui a0,0x40 19
  • 44. CHAPTER 3. HELLO, WORLD! 3.6. CONCLUSION 0x0040065c <main+28>: jalr t9 0x00400660 <main+32>: addiu a0,a0,2080 0x00400664 <main+36>: lw ra,28(sp) 0x00400668 <main+40>: move v0,zero 0x0040066c <main+44>: jr ra 0x00400670 <main+48>: addiu sp,sp,32 End of assembler dump. (gdb) s 0x00400658 in main () (gdb) s 0x0040065c in main () (gdb) s 0x2ab2de60 in printf () from /lib/libc.so.6 (gdb) x/s $a0 0x400820: "hello, world" (gdb) 3.6 Conclusion The main difference between x86/ARM and x64/ARM64 code is that pointer to the string is now 64-bit. Indeed, modern CPUs are 64-bit now because memory is cheaper nowadays. We can add much more memory to our computers and 32-bit pointers are not enough to address it. So all pointers are 64-bit now. 3.7 Exercises 3.7.1 Exercise #1 main: push 0xFFFFFFFF call MessageBeep xor eax,eax retn What does this win32-function do? 20
  • 45. CHAPTER 4. FUNCTION PROLOGUE AND EPILOGUE Chapter 4 Function prologue and epilogue A function prologue is a sequence of instructions at the start of a function. It often looks something like the following code fragment: push ebp mov ebp, esp sub esp, X What these instruction do: save the value in the EBP register, sets the value of the EBP register to the value of the ESP and then allocate space on the stack for local variables. The value in the EBP stays the same over the period of the function execution and is to be used for local variables and arguments access. For the same purpose one can use ESP, but since it changes over time this approach is not too convenient. The function epilogue frees allocated space in the stack, returns the value in the EBP register back to its initial state and returns the control flow to the callee: mov esp, ebp pop ebp ret 0 Function prologues and epilogues are usually detected in disassemblers for function delimitation. 4.1 Recursion Epilogues and prologues can negatively affect the recursion performance. More about recursion in this book: 36.3 on page 470. 21
  • 46. CHAPTER 5. STACK Chapter 5 Stack The stack is one of the most fundamental data structures in computer science 1 . Technically, it is just a block of memory in process memory along with the ESP or RSP register in x86 or x64, or the SP register in ARM, as a pointer within that block. The most frequently used stack access instructions are PUSH and POP (in both x86 and ARM thumb-mode). PUSH subtracts from ESP/RSP/SP 4 in 32-bit mode (or 8 in 64-bit mode) and then writes the contents of its sole operand to the memory address pointed by ESP/RSP/SP. POP is the reverse operation: retrieve the data from memory pointed by SP, loads it into the instruction operand (often a register) and then add 4 (or 8) to the stack pointer. After stack allocation, the stack pointer points at the bottom of the stack. PUSH decreases the stack pointer and POP increases it. The bottom of the stack is actually at the beginning of the memory allocated for the stack block. It seems strange, but that’s the way it is. ARM supports both descending and ascending stacks. For example the STMFD/LDMFD, STMED2 /LDMED3 instructions are intended to deal with a descending stack (grows downwards, starting with a high address and progressing to a lower one). The STMFA4 /LDMFA5 , STMEA6 /LDMEA7 instruc- tions are intended to deal with an ascending stack (grows upwards, starting from a low address and progressing to a higher one). 5.1 Why does the stack grow backwards? Intuitively, we might think that the stack grow upwards, i.e. towards higher addresses, like any other data structure. The reason that the stack grows backward is probably historical. When the computers were big and occupied a whole room, it was easy to divide memory into two parts, one for the heap and one for the stack. Of course, it was unknown how big the heap and the stack would be during program execution, so this solution was the simplest possible. ...Heap . Stack... Start of heap . Start of stack In [RT74] we can read: The user-core part of an image is divided into three logical segments. The program text segment begins at location 0 in the virtual address space. During execution, this segment is write-protected and a single copy of it is shared among all processes executing the same program. At the first 8K byte boundary above the program text segment in the virtual address space begins a nonshared, writable data segment, the size of which may be extended by a system call. Starting at the highest address in the virtual address space is a stack segment, which automatically grows downward as the hardware’s stack pointer fluctuates. 1wikipedia 2Store Multiple Empty Descending (ARM instruction) 3Load Multiple Empty Descending (ARM instruction) 4Store Multiple Full Ascending (ARM instruction) 5Load Multiple Full Ascending (ARM instruction) 6Store Multiple Empty Ascending (ARM instruction) 7Load Multiple Empty Ascending (ARM instruction) 22
  • 47. CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR? This reminds us how some students write two lecture notes using only one notebook: notes for the first lecture are written as usual, and notes for the second one are written from the end of notebook, by flipping it. Notes may meet each other somewhere in between, in case of lack of free space. 5.2 What is the stack used for? 5.2.1 Save the function’s return address x86 When calling another function with a CALL instruction the address of the point exactly after the CALL instruction is saved to the stack and then an unconditional jump to the address in the CALL operand is executed. The CALL instruction is equivalent to a PUSH address_after_call / JMP operand instruction pair. RET fetches a value from the stack and jumps to it —that is equivalent to a POP tmp / JMP tmp instruction pair. Overflowing the stack is straightforward. Just run eternal recursion: void f() { f(); }; MSVC 2008 reports the problem: c:tmp6>cl ss.cpp /Fass.asm Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. ss.cpp c:tmp6ss.cpp(4) : warning C4717: 'f' : recursive on all control paths, function will cause ⤦ runtime stack overflow …but generates the right code anyway: ?f@@YAXXZ PROC ; f ; File c:tmp6ss.cpp ; Line 2 push ebp mov ebp, esp ; Line 3 call ?f@@YAXXZ ; f ; Line 4 pop ebp ret 0 ?f@@YAXXZ ENDP ; f … Also if we turn on the compiler optimization (/Ox option) the optimized code will not overflow the stack and will work correctly8 instead: ?f@@YAXXZ PROC ; f ; File c:tmp6ss.cpp ; Line 2 $LL3@f: ; Line 3 jmp SHORT $LL3@f ?f@@YAXXZ ENDP ; f GCC 4.4.1 generates similar code in both cases without, however, issuing any warning about the problem. ARM ARM programs also use the stack for saving return addresses, but differently. As mentioned in “Hello, world!” ( 3.4 on page 11), the RA is saved to the LR (link register). If one needs, however, to call another function and use the LR register one more time its value has to be saved. Usually it is saved in the function prologue. Often, we see instructions like ``PUSH R4-R7,LR'' along with this instruction in epilogue ``POP R4-R7,PC'' —thus register values to be used in the function are saved in the stack, including LR. Nevertheless, if a function never calls any other function, in ARM terminology it is called a leaf function9 . As a conse- quence, leaf functions do not save the LR register (because they don’t modify it). If such function is small and uses a small 8irony here 9http://go.yurichev.com/17064 23
  • 48. CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR? number of registers, it may not use the stack at all. Thus, it is possible to call leaf functions without using the stack which can be faster than on older x86 because external RAM is not used for the stack 10 . This can be also useful for situations when memory for the stack is not yet allocated or not available. Some examples of leaf functions are: listing. 8.3.2 on page 91, 8.3.3 on page 92, 19.17 on page 315, 19.33 on page 332, 19.5.4 on page 333, 15.4 on page 196, 15.2 on page 195, 17.3 on page 216. 5.2.2 Passing function arguments The most popular way to pass parameters in x86 is called “cdecl”: push arg3 push arg2 push arg1 call f add esp, 4*3 Callee functions get their arguments via the stack pointer. Therefore, this is how the argument values are located in the stack before the execution of the f() function’s very first instruction: ESP return address ESP+4 argument#1, marked in IDA as arg_0 ESP+8 argument#2, marked in IDA as arg_4 ESP+0xC argument#3, marked in IDA as arg_8 … … For more information on other calling conventions see also section ( 64 on page 663). It is worth noting that nothing obliges programmers to pass arguments through the stack. It is not a requirement. One could implement any other method without using the stack at all. For example, it is possible to allocate a space for arguments in the heap, fill it and pass it to a function via a pointer to this block in the EAX register. This will work 11 . However, it is a convenient custom in x86 and ARM to use the stack for this purpose. By the way, the callee function does not have any information about how many arguments were passed. C functions with a variable number of arguments (like printf()) determine their number using format string specifiers (which begin with the % symbol). If we write something like printf("%d %d %d", 1234); printf() will print 1234, and then two random numbers, which were laying next to it in the stack. That’s why it is not very important how we declare the main() function: as main(), main(int argc, char *argv[]) or main(int argc, char *argv[], char *envp[]). In fact, the CRT-code is calling main() roughly as: push envp push argv push argc call main ... If you declare main() as main() without arguments, they are, nevertheless, still present in the stack, but are not used. If you declare main() as main(int argc, char *argv[]), you will be able to use first two arguments, and the third will remain “invisible” for your function. Even more, it is possible to declare main(int argc), and it will work. 5.2.3 Local variable storage A function could allocate space in the stack for its local variables just by shifting the stack pointer towards the stack bottom. Hence, it’s very fast, no matter how many local variables are defined. It is also not a requirement to store local variables in the stack. You could store local variables wherever you like, but traditionally this is how it’s done. 10Some time ago, on PDP-11 and VAX, the CALL instruction (calling other functions) was expensive; up to 50% of execution time might be spent on it, so it was considered that having a big number of small functions is an anti-pattern[Ray03, Chapter 4, Part II]. 11For example, in the “The Art of Computer Programming” book by Donald Knuth, in section 1.4.1 dedicated to subroutines[Knu98, section 1.4.1], we could read that one way to supply arguments to a subroutine is simply to list them after the JMP instruction passing control to subroutine. Knuth explains that this method was particularly convenient on IBM System/360. 24
  • 49. CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR? 5.2.4 x86: alloca() function It is worth noting the alloca() function.12 . This function works like malloc(), but allocates memory directly on the stack. The allocated memory chunk does not need to be freed via a free() function call, since the function epilogue ( 4 on page 21) returns ESP back to its initial state and the allocated memory is just dropped. It is worth noting how alloca() is implemented. In simple terms, this function just shifts ESP downwards toward the stack bottom by the number of bytes you need and sets ESP as a pointer to the allocated block. Let’s try: #ifdef __GNUC__ #include <alloca.h> // GCC #else #include <malloc.h> // MSVC #endif #include <stdio.h> void f() { char *buf=(char*)alloca (600); #ifdef __GNUC__ snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // GCC #else _snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // MSVC #endif puts (buf); }; (_snprintf() function works just like printf(), but instead of dumping the result into stdout (e.g., to terminal or console), it writes it to the buf buffer. puts() copies buf contents to stdout. Of course, these two function calls might be replaced by one printf() call, but I would like to illustrate small buffer usage.) MSVC Let’s compile (MSVC 2010): Listing 5.1: MSVC 2010 ... mov eax, 600 ; 00000258H call __alloca_probe_16 mov esi, esp push 3 push 2 push 1 push OFFSET $SG2672 push 600 ; 00000258H push esi call __snprintf push esi call _puts add esp, 28 ; 0000001cH ... The sole alloca() argument is passed via EAX (instead of pushing it into the stack) 13 . After the alloca() call, ESP points to the block of 600 bytes and we can use it as memory for the buf array. GCC + Intel syntax GCC 4.4.1 does the same without calling external functions: 12In MSVC, the function implementation can be found in alloca16.asm and chkstk.asm in C:Program Files (x86)Microsoft Visual Studio 10.0VCcrtsrcintel 13It is because alloca() is rather a compiler intrinsic ( 90 on page 869) than a normal function. One of the reasons we need a separate function instead of just a couple of instructions in the code, is because the MSVC14 alloca() implementation also has code which reads from the memory just allocated, in order to let the OS map physical memory to this VM15 region. 25
  • 50. CHAPTER 5. STACK 5.2. WHAT IS THE STACK USED FOR? Listing 5.2: GCC 4.7.3 .LC0: .string "hi! %d, %d, %dn" f: push ebp mov ebp, esp push ebx sub esp, 660 lea ebx, [esp+39] and ebx, -16 ; align pointer by 16-bit border mov DWORD PTR [esp], ebx ; s mov DWORD PTR [esp+20], 3 mov DWORD PTR [esp+16], 2 mov DWORD PTR [esp+12], 1 mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %dn" mov DWORD PTR [esp+4], 600 ; maxlen call _snprintf mov DWORD PTR [esp], ebx ; s call puts mov ebx, DWORD PTR [ebp-4] leave ret GCC + AT&T syntax Let’s see the same code, but in AT&T syntax: Listing 5.3: GCC 4.7.3 .LC0: .string "hi! %d, %d, %dn" f: pushl %ebp movl %esp, %ebp pushl %ebx subl $660, %esp leal 39(%esp), %ebx andl $-16, %ebx movl %ebx, (%esp) movl $3, 20(%esp) movl $2, 16(%esp) movl $1, 12(%esp) movl $.LC0, 8(%esp) movl $600, 4(%esp) call _snprintf movl %ebx, (%esp) call puts movl -4(%ebp), %ebx leave ret The code is the same as in the previous listing. By the way, movl $3, 20(%esp) corresponds to mov DWORD PTR [esp+20], 3 in Intel-syntax. In AT&T syntax when addressing memory using register+offset format, it is notated as offset(%register). 5.2.5 (Windows) SEH SEH16 records are also stored on the stack (if they present).. Read more about it: ( 68.3 on page 692). 5.2.6 Buffer overflow protection More about it here ( 18.2 on page 264). 16Structured Exception Handling : 68.3 on page 692 26
  • 51. CHAPTER 5. STACK 5.3. TYPICAL STACK LAYOUT 5.3 Typical stack layout A typical stack layout in a 32-bit environment at the start of a function, before the first instruction execution looks like this: … … ESP-0xC local variable #2, marked in IDA as var_8 ESP-8 local variable #1, marked in IDA as var_4 ESP-4 saved value of EBP ESP return address ESP+4 argument#1, marked in IDA as arg_0 ESP+8 argument#2, marked in IDA as arg_4 ESP+0xC argument#3, marked in IDA as arg_8 … … 5.4 Noise in stack Often in this book I write about “noise” or “garbage” values in stack or memory. Where do they come from? These are what was left in there after other functions’ executions. Short example: #include <stdio.h> void f1() { int a=1, b=2, c=3; }; void f2() { int a, b, c; printf ("%d, %d, %dn", a, b, c); }; int main() { f1(); f2(); }; Compiling… Listing 5.4: Non-optimizing MSVC 2010 $SG2752 DB '%d, %d, %d', 0aH, 00H _c$ = -12 ; size = 4 _b$ = -8 ; size = 4 _a$ = -4 ; size = 4 _f1 PROC push ebp mov ebp, esp sub esp, 12 mov DWORD PTR _a$[ebp], 1 mov DWORD PTR _b$[ebp], 2 mov DWORD PTR _c$[ebp], 3 mov esp, ebp pop ebp ret 0 _f1 ENDP _c$ = -12 ; size = 4 _b$ = -8 ; size = 4 _a$ = -4 ; size = 4 _f2 PROC push ebp mov ebp, esp sub esp, 12 mov eax, DWORD PTR _c$[ebp] push eax mov ecx, DWORD PTR _b$[ebp] 27
  • 52. CHAPTER 5. STACK 5.4. NOISE IN STACK push ecx mov edx, DWORD PTR _a$[ebp] push edx push OFFSET $SG2752 ; '%d, %d, %d' call DWORD PTR __imp__printf add esp, 16 mov esp, ebp pop ebp ret 0 _f2 ENDP _main PROC push ebp mov ebp, esp call _f1 call _f2 xor eax, eax pop ebp ret 0 _main ENDP The compiler will grumble a little bit… c:Polygonc>cl st.c /Fast.asm /MD Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. st.c c:polygoncst.c(11) : warning C4700: uninitialized local variable 'c' used c:polygoncst.c(11) : warning C4700: uninitialized local variable 'b' used c:polygoncst.c(11) : warning C4700: uninitialized local variable 'a' used Microsoft (R) Incremental Linker Version 10.00.40219.01 Copyright (C) Microsoft Corporation. All rights reserved. /out:st.exe st.obj But when I run the compiled program… c:Polygonc>st 1, 2, 3 Oh, what a weird thing! We did not set any variables in f2(). These are “ghosts” values, which are still in the stack. 28
  • 53. CHAPTER 5. STACK 5.4. NOISE IN STACK Let’s load the example into OllyDbg: Figure 5.1: OllyDbg: f1() When f1() assigns the variables a, b and c , their values are stored at the address 0x14F860 and so on. 29
  • 54. CHAPTER 5. STACK 5.5. EXERCISES And when f2() executes: Figure 5.2: OllyDbg: f2() ... a, b and c of f2() are located at the same addresses! No one has overwritten the values yet, so at that point they are still untouched. So, for this weird situation, several functions has to be called one after another and SP has to be the same at each function entry (i.e., they has same number of arguments). Then the local variables will be located at the same positions in the stack. Summarizing, all values in the stack (and memory cells in general) have values left there from previous function execu- tions. They are not random in the strict sense, but rather have unpredictable values. Is there other option? It probably would be possible to clear portions of the stack before each function execution, but that’s too much extra (and unnecessary) work. 5.5 Exercises 5.5.1 Exercise #1 If we compile this piece of code in MSVC and run it, three numbers are printed. Where do they come from? Where they come from if you compile it in MSVC with optimization (/Ox)? Why is the situation completely different if we compile with GCC? #include <stdio.h> int main() { printf ("%d, %d, %dn"); return 0; }; Answer: G.1.1 on page 954. 5.5.2 Exercise #2 What does this code do? Listing 5.5: Optimizing MSVC 2010 $SG3103 DB '%d', 0aH, 00H _main PROC push 0 call DWORD PTR __imp___time64 push edx push eax 30
  • 55. CHAPTER 5. STACK 5.5. EXERCISES push OFFSET $SG3103 ; '%d' call DWORD PTR __imp__printf add esp, 16 xor eax, eax ret 0 _main ENDP Listing 5.6: Optimizing Keil 6/2013 (ARM mode) main PROC PUSH {r4,lr} MOV r0,#0 BL time MOV r1,r0 ADR r0,|L0.32| BL __2printf MOV r0,#0 POP {r4,pc} ENDP |L0.32| DCB "%dn",0 Listing 5.7: Optimizing Keil 6/2013 (thumb mode) main PROC PUSH {r4,lr} MOVS r0,#0 BL time MOVS r1,r0 ADR r0,|L0.20| BL __2printf MOVS r0,#0 POP {r4,pc} ENDP |L0.20| DCB "%dn",0 Listing 5.8: Optimizing GCC 4.9 (ARM64) main: stp x29, x30, [sp, -16]! mov x0, 0 add x29, sp, 0 bl time mov x1, x0 ldp x29, x30, [sp], 16 adrp x0, .LC0 add x0, x0, :lo12:.LC0 b printf .LC0: .string "%dn" Listing 5.9: Optimizing GCC 4.4.5 (MIPS) (IDA) main: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (time & 0xFFFF)($gp) or $at, $zero jalr $t9 move $a0, $zero 31
  • 56. CHAPTER 5. STACK 5.5. EXERCISES lw $gp, 0x20+var_10($sp) lui $a0, ($LC0 >> 16) # "%dn" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) la $a0, ($LC0 & 0xFFFF) # "%dn" move $a1, $v0 jr $t9 addiu $sp, 0x20 $LC0: .ascii "%dn"<0> # DATA XREF: main+28 Answer: G.1.1 on page 954. 32
  • 57. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS Chapter 6 printf() with several arguments Now let’s extend the Hello, world! ( 3 on page 6) example, replacing printf() in the main() function body with this: #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d", 1, 2, 3); return 0; }; 6.1 x86 6.1.1 x86: 3 arguments MSVC When we compile it with MSVC 2010 Express we get: $SG3830 DB 'a=%d; b=%d; c=%d', 00H ... push 3 push 2 push 1 push OFFSET $SG3830 call _printf add esp, 16 ; 00000010H Almost the same, but now we can see the printf() arguments are pushed onto the stack in reverse order. The first argument is pushed last. By the way, variables of int type in 32-bit environment have 32-bit width, that is 4 bytes. So, we have 4 arguments here. 4 ∗ 4 = 16 —they occupy exactly 16 bytes in the stack: a 32-bit pointer to a string and 3 numbers of type int. When the stack pointer (ESP register) has changed back by the ADD ESP, X instruction after a function call, often, the number of function arguments could be deduced by simply dividing X by 4. Of course, this is specific to the cdecl calling convention, and only for 32-bit environment. See also the calling conventions section ( 64 on page 663). In certain cases where several functions return right after one another, the compiler could merge multiple ``ADD ESP, X'' instructions into one, after the last call: push a1 push a2 call ... ... push a1 call ... ... push a1 push a2 push a3 call ... 33
  • 58. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 add esp, 24 34
  • 59. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 MSVC and OllyDbg Now let’s try to load this example in OllyDbg. It is one of the most popular user-land win32 debuggers. We can compile our example in MSVC 2012 with /MD option, which means to link with MSVCR*.DLL, so we can see the imported functions clearly in the debugger. Then load the executable in OllyDbg. The very first breakpoint is in ntdll.dll, press F9 (run). The second breakpoint is in CRT-code. Now we have to find the main() function. Find this code by scrolling the code to the very top (MSVC allocates the main() function at the very beginning of the code section): Figure 6.1: OllyDbg: the very start of the main() function Click on the PUSH EBP instruction, press F2 (set breakpoint) and press F9 (run). We need to perform these actions in order to skip CRT-code, because we aren’t really interested in it yet. 35
  • 60. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 Press F8 (step over) 6 times, i.e., skip 6 instructions: Figure 6.2: OllyDbg: before printf() execution Now the PC points to the CALL printf instruction. OllyDbg, like other debuggers, highlights the value of the registers which were changed. So each time you press F8, EIP changes and its value is displayed in red. ESP changes as well, because the arguments values are pushed into the stack. Where are the values in the stack? Take a look at the right/bottom debugger window: Figure 6.3: OllyDbg: stack after the argument values have been pushed (The red rectangular border was added by me in a graphics editor) We can see 3 columns there: address in the stack, value in the stack and some additional OllyDbg comments. OllyDbg understands printf()-like strings, so it reports the string here and the 3 values attached to it. It is possible to right-click on the format string, click on “Follow in dump”, and the format string will appear in the debugger left-bottom window, which always displays some part of the memory. These memory values can be edited. It is possible to change the format string, in which case the result of our example would be different. It is not very useful in this particular case, but it could be good as an exercise so you start building a feel of how everything works here. 36
  • 61. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 Press F8 (step over). We see the following output in the console: Figure 6.4: printf() function executed Let’s see how the registers and stack state have changed: Figure 6.5: OllyDbg: after printf() execution Register EAX now contains 0xD (13). That is correct, since printf() returns the number of characters printed. The EIP value has changed: indeed, now it contains the address of the instruction coming after CALL printf. ECX and EDX values have changed as well. Apparently, the printf() function’s hidden machinery used them for its own needs. A very important fact is that neither the ESP value, nor the stack state have been changed! We clearly see that the format string and corresponding 3 values are still there. This is indeed the cdecl calling convention behaviour: callee does not return ESP back to its previous value. The caller is responsible to do so. 37
  • 62. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 Press F8 again to execute ADD ESP, 10 instruction: Figure 6.6: OllyDbg: after ADD ESP, 10 instruction execution ESP has changed, but the values are still in the stack! Yes, of course; no one needs to set these values to zeroes or something like that because everything above the stack pointer (SP) is noise or garbage, and has no meaning at all. It would be time consuming to clear the unused stack entries anyway, and no one really needs to. GCC Now let’s compile the same program in Linux using GCC 4.4.1 and take a look at what we have got in IDA: main proc near var_10 = dword ptr -10h var_C = dword ptr -0Ch var_8 = dword ptr -8 var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov eax, offset aADBDCD ; "a=%d; b=%d; c=%d" mov [esp+10h+var_4], 3 mov [esp+10h+var_8], 2 mov [esp+10h+var_C], 1 mov [esp+10h+var_10], eax call _printf mov eax, 0 leave retn main endp Its noticeable that the difference between the MSVC code and the GCC code is only in the way the arguments are stored on the stack. Here the GCC is working directly with the stack without the use of PUSH/POP. GCC and GDB Let’s try this example also in GDB1 in Linux. -g option instructs the compiler to include debug information in the executable file. $ gcc 1.c -g -o 1 $ gdb 1 GNU gdb (GDB) 7.6.1-ubuntu 1GNU debugger 38
  • 63. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/1...done. Listing 6.1: let’s set breakpoint on printf() (gdb) b printf Breakpoint 1 at 0x80482f0 Run. We don’t have the printf() function source code here, so GDB can’t show it, but may do so. (gdb) run Starting program: /home/dennis/polygon/1 Breakpoint 1, __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29 29 printf.c: No such file or directory. Print 10 stack elements. The most left column contains addresses on the stack. (gdb) x/10w $esp 0xbffff11c: 0x0804844a 0x080484f0 0x00000001 0x00000002 0xbffff12c: 0x00000003 0x08048460 0x00000000 0x00000000 0xbffff13c: 0xb7e29905 0x00000001 The very first element is the RA (0x0804844a). We can verify this by disassembling the memory at this address: (gdb) x/5i 0x0804844a 0x804844a <main+45>: mov $0x0,%eax 0x804844f <main+50>: leave 0x8048450 <main+51>: ret 0x8048451: xchg %ax,%ax 0x8048453: xchg %ax,%ax The two XCHG instructions are probably random garbage, which we can ignore for now. The second element (0x080484f0) is the format string address: (gdb) x/s 0x080484f0 0x80484f0: "a=%d; b=%d; c=%d" Next 3 elements (1, 2, 3) are the printf() arguments. The rest of the elements could be just “garbage” on the stack, but could also be values from other functions, their local variables, etc. We can ignore them for now. Run “finish”. The command instructs GDB to “execute all instructions until the end of the function”. In this case: execute till the end of printf(). (gdb) finish Run till exit from #0 __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29 main () at 1.c:6 6 return 0; Value returned is $2 = 13 GDB shows what printf() returned in EAX (13). This is the number of characters printed out, just like in the OllyDbg example. We also see “return 0;” and the information that this expression is in the 1.c file at the line 6. Indeed, the 1.c file is located in the current directory, and GDB finds the string there. How does GDB know which C-code line is being currently executed? This is due to the fact that the compiler, while generating debugging information, also saves a table of relations between source code line numbers and instruction addresses. GDB is a source-level debugger, after all. Let’s examine the registers. 13 in EAX: (gdb) info registers eax 0xd 13 ecx 0x0 0 edx 0x0 0 ebx 0xb7fc0000 -1208221696 esp 0xbffff120 0xbffff120 ebp 0xbffff138 0xbffff138 esi 0x0 0 39
  • 64. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 edi 0x0 0 eip 0x804844a 0x804844a <main+45> ... Let’s disassemble the current instructions. The arrow points to the instruction to be executed next. (gdb) disas Dump of assembler code for function main: 0x0804841d <+0>: push %ebp 0x0804841e <+1>: mov %esp,%ebp 0x08048420 <+3>: and $0xfffffff0,%esp 0x08048423 <+6>: sub $0x10,%esp 0x08048426 <+9>: movl $0x3,0xc(%esp) 0x0804842e <+17>: movl $0x2,0x8(%esp) 0x08048436 <+25>: movl $0x1,0x4(%esp) 0x0804843e <+33>: movl $0x80484f0,(%esp) 0x08048445 <+40>: call 0x80482f0 <printf@plt> => 0x0804844a <+45>: mov $0x0,%eax 0x0804844f <+50>: leave 0x08048450 <+51>: ret End of assembler dump. GDB uses AT&T syntax by default. It is possible to switch to Intel syntax: (gdb) set disassembly-flavor intel (gdb) disas Dump of assembler code for function main: 0x0804841d <+0>: push ebp 0x0804841e <+1>: mov ebp,esp 0x08048420 <+3>: and esp,0xfffffff0 0x08048423 <+6>: sub esp,0x10 0x08048426 <+9>: mov DWORD PTR [esp+0xc],0x3 0x0804842e <+17>: mov DWORD PTR [esp+0x8],0x2 0x08048436 <+25>: mov DWORD PTR [esp+0x4],0x1 0x0804843e <+33>: mov DWORD PTR [esp],0x80484f0 0x08048445 <+40>: call 0x80482f0 <printf@plt> => 0x0804844a <+45>: mov eax,0x0 0x0804844f <+50>: leave 0x08048450 <+51>: ret End of assembler dump. Execute next instruction. GDB shows ending bracket, meaning, this ends the block. (gdb) step 7 }; Let’s examine the registers after the MOV EAX, 0 instruction execution. Indeed EAX is zero at that point. (gdb) info registers eax 0x0 0 ecx 0x0 0 edx 0x0 0 ebx 0xb7fc0000 -1208221696 esp 0xbffff120 0xbffff120 ebp 0xbffff138 0xbffff138 esi 0x0 0 edi 0x0 0 eip 0x804844f 0x804844f <main+50> ... 6.1.2 x64: 8 arguments To see how other arguments are passed via the stack, let’s change our example again by increasing the number of arguments to 9 (printf() format string + 8 int variables): #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; 40
  • 65. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 MSVC As it was mentioned earlier, the first 4 arguments has to be passed through the RCX, RDX, R8, R9 registers in Win64, while all the rest—via the stack. That is exactly what we see here. However, the MOV instruction, instead of PUSH, is used for preparing the stack, so the values are stored to the stack in a straightforward manner. Listing 6.2: MSVC 2012 x64 $SG2923 DB 'a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d', 0aH, 00H main PROC sub rsp, 88 mov DWORD PTR [rsp+64], 8 mov DWORD PTR [rsp+56], 7 mov DWORD PTR [rsp+48], 6 mov DWORD PTR [rsp+40], 5 mov DWORD PTR [rsp+32], 4 mov r9d, 3 mov r8d, 2 mov edx, 1 lea rcx, OFFSET FLAT:$SG2923 call printf ; return 0 xor eax, eax add rsp, 88 ret 0 main ENDP _TEXT ENDS END The observant reader may ask why are 8 bytes allocated for int values, when 4 is enough? Yes, one has to remember: 8 bytes are allocated for any data type shorter than 64 bits. This is established for the convenience’s sake: it makes it easy to calculate the address of arbitrary argument. Besides, they are all located at aligned memory addresses. It is the same in the 32-bit environments: 4 bytes are reserved for all data types. GCC The picture is similar for x86-64 *NIX OS-es, except that the first 6 arguments are passed through the RDI, RSI, RDX, RCX, R8, R9 registers. All the rest—via the stack. GCC generates the code storing the string pointer into EDI instead of RDI—we noted that previously: 3.2.2 on page 10. We also noted earlier that the EAX register has been cleared before a printf() call: 3.2.2 on page 10. Listing 6.3: Optimizing GCC 4.4.6 x64 .LC0: .string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn" main: sub rsp, 40 mov r9d, 5 mov r8d, 4 mov ecx, 3 mov edx, 2 mov esi, 1 mov edi, OFFSET FLAT:.LC0 xor eax, eax ; number of vector registers passed mov DWORD PTR [rsp+16], 8 mov DWORD PTR [rsp+8], 7 mov DWORD PTR [rsp], 6 call printf ; return 0 xor eax, eax add rsp, 40 ret 41
  • 66. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.1. X86 GCC + GDB Let’s try this example in GDB. $ gcc -g 2.c -o 2 $ gdb 2 GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/2...done. Listing 6.4: let’s set the breakpoint to printf(), and run (gdb) b printf Breakpoint 1 at 0x400410 (gdb) run Starting program: /home/dennis/polygon/2 Breakpoint 1, __printf (format=0x400628 "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn") at ⤦ printf.c:29 29 printf.c: No such file or directory. Registers RSI/RDX/RCX/R8/R9 have the expected values. RIP has the address of the very first instruction of the printf() function. (gdb) info registers rax 0x0 0 rbx 0x0 0 rcx 0x3 3 rdx 0x2 2 rsi 0x1 1 rdi 0x400628 4195880 rbp 0x7fffffffdf60 0x7fffffffdf60 rsp 0x7fffffffdf38 0x7fffffffdf38 r8 0x4 4 r9 0x5 5 r10 0x7fffffffdce0 140737488346336 r11 0x7ffff7a65f60 140737348263776 r12 0x400440 4195392 r13 0x7fffffffe040 140737488347200 r14 0x0 0 r15 0x0 0 rip 0x7ffff7a65f60 0x7ffff7a65f60 <__printf> ... Listing 6.5: let’s inspect the format string (gdb) x/s $rdi 0x400628: "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn" Let’s dump the stack with the x/g command this time—g stands for giant words, i.e., 64-bit words. (gdb) x/10g $rsp 0x7fffffffdf38: 0x0000000000400576 0x0000000000000006 0x7fffffffdf48: 0x0000000000000007 0x00007fff00000008 0x7fffffffdf58: 0x0000000000000000 0x0000000000000000 0x7fffffffdf68: 0x00007ffff7a33de5 0x0000000000000000 0x7fffffffdf78: 0x00007fffffffe048 0x0000000100000000 The very first stack element, just like in the previous case, is the RA. 3 values are also passed through the stack: 6, 7, 8. We also see that 8 is passed with the high 32-bits not cleared: 0x00007fff00000008. That’s OK, because the values have int type, which is 32-bit. So, the high register or stack element part may contain “random garbage”. If you take a look at where the control will return after the printf() execution, GDB will show the entire main() function: 42
  • 67. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM (gdb) set disassembly-flavor intel (gdb) disas 0x0000000000400576 Dump of assembler code for function main: 0x000000000040052d <+0>: push rbp 0x000000000040052e <+1>: mov rbp,rsp 0x0000000000400531 <+4>: sub rsp,0x20 0x0000000000400535 <+8>: mov DWORD PTR [rsp+0x10],0x8 0x000000000040053d <+16>: mov DWORD PTR [rsp+0x8],0x7 0x0000000000400545 <+24>: mov DWORD PTR [rsp],0x6 0x000000000040054c <+31>: mov r9d,0x5 0x0000000000400552 <+37>: mov r8d,0x4 0x0000000000400558 <+43>: mov ecx,0x3 0x000000000040055d <+48>: mov edx,0x2 0x0000000000400562 <+53>: mov esi,0x1 0x0000000000400567 <+58>: mov edi,0x400628 0x000000000040056c <+63>: mov eax,0x0 0x0000000000400571 <+68>: call 0x400410 <printf@plt> 0x0000000000400576 <+73>: mov eax,0x0 0x000000000040057b <+78>: leave 0x000000000040057c <+79>: ret End of assembler dump. Let’s finish executing printf(), execute the instruction zeroing EAX, and note that the EAX register has a value of exactly zero. RIP now points to the LEAVE instruction, i.e., the penultimate one in the main() function. (gdb) finish Run till exit from #0 __printf (format=0x400628 "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%⤦ dn") at printf.c:29 a=1; b=2; c=3; d=4; e=5; f=6; g=7; h=8 main () at 2.c:6 6 return 0; Value returned is $1 = 39 (gdb) next 7 }; (gdb) info registers rax 0x0 0 rbx 0x0 0 rcx 0x26 38 rdx 0x7ffff7dd59f0 140737351866864 rsi 0x7fffffd9 2147483609 rdi 0x0 0 rbp 0x7fffffffdf60 0x7fffffffdf60 rsp 0x7fffffffdf40 0x7fffffffdf40 r8 0x7ffff7dd26a0 140737351853728 r9 0x7ffff7a60134 140737348239668 r10 0x7fffffffd5b0 140737488344496 r11 0x7ffff7a95900 140737348458752 r12 0x400440 4195392 r13 0x7fffffffe040 140737488347200 r14 0x0 0 r15 0x0 0 rip 0x40057b 0x40057b <main+78> ... 6.2 ARM 6.2.1 ARM: 3 arguments ARM’s traditional scheme for passing arguments (calling convention) behaves as follows: the first 4 arguments are passed through the R0-R3 registers; the remaining arguments via the stack. This resembles the arguments passing scheme in fastcall ( 64.3 on page 664) or win64 ( 64.5.1 on page 665). 32-bit ARM Non-optimizing Keil 6/2013 (ARM mode) 43
  • 68. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM Listing 6.6: Non-optimizing Keil 6/2013 (ARM mode) .text:00000000 main .text:00000000 10 40 2D E9 STMFD SP!, {R4,LR} .text:00000004 03 30 A0 E3 MOV R3, #3 .text:00000008 02 20 A0 E3 MOV R2, #2 .text:0000000C 01 10 A0 E3 MOV R1, #1 .text:00000010 08 00 8F E2 ADR R0, aADBDCD ; "a=%d; b=%d; c=%d" .text:00000014 06 00 00 EB BL __2printf .text:00000018 00 00 A0 E3 MOV R0, #0 ; return 0 .text:0000001C 10 80 BD E8 LDMFD SP!, {R4,PC} So, the first 4 arguments are passed via the R0-R3 registers in this order: a pointer to the printf() format string in R0, then 1 in R1, 2 in R2 and 3 in R3. The instruction at 0x18 writes 0 to R0 —this is return 0 C-statement. There is nothing unusual so far. Optimizing Keil 6/2013 generates the same code. Optimizing Keil 6/2013 (thumb mode) Listing 6.7: Optimizing Keil 6/2013 (thumb mode) .text:00000000 main .text:00000000 10 B5 PUSH {R4,LR} .text:00000002 03 23 MOVS R3, #3 .text:00000004 02 22 MOVS R2, #2 .text:00000006 01 21 MOVS R1, #1 .text:00000008 02 A0 ADR R0, aADBDCD ; "a=%d; b=%d; c=%d" .text:0000000A 00 F0 0D F8 BL __2printf .text:0000000E 00 20 MOVS R0, #0 .text:00000010 10 BD POP {R4,PC} There is no significant difference from the non-optimized code for ARM mode. Optimizing Keil 6/2013 (ARM mode) + let’s remove return Let’s rework example slightly by removing return 0: #include <stdio.h> void main() { printf("a=%d; b=%d; c=%d", 1, 2, 3); }; The result is somewhat unusual: Listing 6.8: Optimizing Keil 6/2013 (ARM mode) .text:00000014 main .text:00000014 03 30 A0 E3 MOV R3, #3 .text:00000018 02 20 A0 E3 MOV R2, #2 .text:0000001C 01 10 A0 E3 MOV R1, #1 .text:00000020 1E 0E 8F E2 ADR R0, aADBDCD ; "a=%d; b=%d; c=%dn" .text:00000024 CB 18 00 EA B __2printf This is the optimized (-O3) version for ARM mode and this time we see B as the last instruction instead of the familiar BL. Another difference between this optimized version and the previous one (compiled without optimization) is the lack of function prologue and epilogue (instructions preserving the R0 and LR registers values). The B instruction just jumps to another address, without any manipulation of the LR register, similar to JMP in x86. Why does it work? Because this code is, in fact, effectively equivalent to the previous. There are two main reasons: 1) neither the stack nor SP (the stack pointer) is modified; 2) the call to printf() is the last instruction, so there is nothing going on afterwards. On completion, the printf() function simply returns the control to the address stored in LR. Since the LR currently stores the address of the point from where our function was called then the control from printf() will be returned to that point. Therefore we do not need to save LR because we do not need to modify LR. And we do not need to modify LR because there are no other function calls except printf(). Furthermore, after this call we do not to do anything else! That is the reason such optimization is possible. This optimization is often used in functions where the last statement is a call to another function. A similar example is presented here: 13.1.1 on page 141. 44
  • 69. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM ARM64 Non-optimizing GCC (Linaro) 4.9 Listing 6.9: Non-optimizing GCC (Linaro) 4.9 .LC1: .string "a=%d; b=%d; c=%d" f2: ; save FP and LR in stack frame: stp x29, x30, [sp, -16]! ; set stack frame (FP=SP): add x29, sp, 0 adrp x0, .LC1 add x0, x0, :lo12:.LC1 mov w1, 1 mov w2, 2 mov w3, 3 bl printf mov w0, 0 ; restore FP and LR ldp x29, x30, [sp], 16 ret The first instruction STP (Store Pair) saves FP (X29) and LR (X30) in the stack. The second ADD X29, SP, 0 instruction forms the stack frame. It is just writing the value of SP into X29. Next, we see the familiar ADRP/ADD instruction pair, which forms a pointer to the string. %d in printf() string format is a 32-bit int, so the 1, 2 and 3 are loaded into 32-bit register parts. Optimizing GCC (Linaro) 4.9 generates the same code. 6.2.2 ARM: 8 arguments Let’s use again the example with 9 arguments from the previous section: 6.1.2 on page 40. #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; Optimizing Keil 6/2013: ARM mode .text:00000028 main .text:00000028 .text:00000028 var_18 = -0x18 .text:00000028 var_14 = -0x14 .text:00000028 var_4 = -4 .text:00000028 .text:00000028 04 E0 2D E5 STR LR, [SP,#var_4]! .text:0000002C 14 D0 4D E2 SUB SP, SP, #0x14 .text:00000030 08 30 A0 E3 MOV R3, #8 .text:00000034 07 20 A0 E3 MOV R2, #7 .text:00000038 06 10 A0 E3 MOV R1, #6 .text:0000003C 05 00 A0 E3 MOV R0, #5 .text:00000040 04 C0 8D E2 ADD R12, SP, #0x18+var_14 .text:00000044 0F 00 8C E8 STMIA R12, {R0-R3} .text:00000048 04 00 A0 E3 MOV R0, #4 .text:0000004C 00 00 8D E5 STR R0, [SP,#0x18+var_18] .text:00000050 03 30 A0 E3 MOV R3, #3 .text:00000054 02 20 A0 E3 MOV R2, #2 .text:00000058 01 10 A0 E3 MOV R1, #1 .text:0000005C 6E 0F 8F E2 ADR R0, aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g⤦ =%"... .text:00000060 BC 18 00 EB BL __2printf .text:00000064 14 D0 8D E2 ADD SP, SP, #0x14 .text:00000068 04 F0 9D E4 LDR PC, [SP+4+var_4],#4 45
  • 70. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM This code can be divided into several parts: • Function prologue: The very first ``STR LR, [SP,#var_4]!'' instruction saves LR on the stack, because we are going to use this register for the printf() call. Exclamation mark at the end indicates pre-index. This implies that SP is to be decreased by 4 first, and then LR will be saved at the address stored in SP. This is similar to PUSH in x86. Read more about it at: 28.2 on page 445. The second ``SUB SP, SP, #0x14'' instruction decreases SP (the stack pointer) in order to allocate 0x14 (20) bytes on the stack. Indeed, we need to pass 5 32-bit values via the stack to the printf() function, and each one occupies 4 bytes, which is exactly 5 ∗ 4 = 20. The other 4 32-bit values are to be passed through registers. • Passing 5, 6, 7 and 8 via the stack: they are stored in the R0, R1, R2 and R3 registers respectively. Then, the ``ADD R12, SP, #0x18+var_14'' instruction writes the stack address where these 4 variables are to be stored, into the R12 register. var_14 is an assembly macro, equal to −0x14, created by IDA to conveniently display the code accessing the stack. The var_? macros generated by IDA reflect local variables in the stack. So, SP + 4 is to be stored into the R12 register. The next ``STMIA R12, R0-R3'' instruction writes registers R0-R3 contents to the memory pointed by R12. STMIA abbreviates Store Multiple Increment After. “Increment After” implies that R12 is to be increased by 4 after each register value is written. • Passing 4 via the stack: 4 is stored in R0 and then this value, with the help of the ``STR R0, [SP,#0x18+var_18]'' instruction is saved on the stack. var_18 is −0x18, so the offset is to be 0, thus the value from the R0 register (4) is to be written to the address written in SP. • Passing 1, 2 and 3 via registers: The values of the first 3 numbers (a, b, c) (1, 2, 3 respectively) are passed through the R1, R2 and R3 registers right before the printf() call, and the other 5 values are passed via the stack: • printf() call. • Function epilogue: The ``ADD SP, SP, #0x14'' instruction restores the SP pointer back to its former value, thus cleaning the stack. Of course, what was stored on the stack will stay there, but it will all be rewritten during the execution of subsequent functions. The ``LDR PC, [SP+4+var_4],#4'' instruction loads the saved LR value from the stack into the PC register, thus causing the function to exit. There is no exclamation mark—indeed, PC is loaded first from the address stored in SP (4 + var_4 = 4 + (−4) = 0, so this instruction is analogous to LDR PC, [SP],#4), and then SP is increased by 4. This is referred as post-index2 . Why does IDA display the instruction like that? Because it wants to illustrate the stack layout and the fact that var_4 is allocated for saving the LR value in the local stack. This instruction is somewhat similar to POP PC in x863 . Optimizing Keil 6/2013: thumb mode .text:0000001C printf_main2 .text:0000001C .text:0000001C var_18 = -0x18 .text:0000001C var_14 = -0x14 .text:0000001C var_8 = -8 .text:0000001C .text:0000001C 00 B5 PUSH {LR} .text:0000001E 08 23 MOVS R3, #8 .text:00000020 85 B0 SUB SP, SP, #0x14 .text:00000022 04 93 STR R3, [SP,#0x18+var_8] .text:00000024 07 22 MOVS R2, #7 .text:00000026 06 21 MOVS R1, #6 .text:00000028 05 20 MOVS R0, #5 .text:0000002A 01 AB ADD R3, SP, #0x18+var_14 .text:0000002C 07 C3 STMIA R3!, {R0-R2} .text:0000002E 04 20 MOVS R0, #4 .text:00000030 00 90 STR R0, [SP,#0x18+var_18] .text:00000032 03 23 MOVS R3, #3 .text:00000034 02 22 MOVS R2, #2 .text:00000036 01 21 MOVS R1, #1 .text:00000038 A0 A0 ADR R0, aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; ⤦ g=%"... 2Read more about it: 28.2 on page 445. 3It is impossible to set IP/EIP/RIP value using POP in x86, but anyway, you get the idea, I hope. 46
  • 71. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.2. ARM .text:0000003A 06 F0 D9 F8 BL __2printf .text:0000003E .text:0000003E loc_3E ; CODE XREF: example13_f+16 .text:0000003E 05 B0 ADD SP, SP, #0x14 .text:00000040 00 BD POP {PC} The output is almost like in the previous example. However, this is thumb code and the values are packed into stack differently: 8 goes first, then 5, 6, 7, and 4 goes third. Optimizing Xcode 4.6.3 (LLVM): ARM mode __text:0000290C _printf_main2 __text:0000290C __text:0000290C var_1C = -0x1C __text:0000290C var_C = -0xC __text:0000290C __text:0000290C 80 40 2D E9 STMFD SP!, {R7,LR} __text:00002910 0D 70 A0 E1 MOV R7, SP __text:00002914 14 D0 4D E2 SUB SP, SP, #0x14 __text:00002918 70 05 01 E3 MOV R0, #0x1570 __text:0000291C 07 C0 A0 E3 MOV R12, #7 __text:00002920 00 00 40 E3 MOVT R0, #0 __text:00002924 04 20 A0 E3 MOV R2, #4 __text:00002928 00 00 8F E0 ADD R0, PC, R0 __text:0000292C 06 30 A0 E3 MOV R3, #6 __text:00002930 05 10 A0 E3 MOV R1, #5 __text:00002934 00 20 8D E5 STR R2, [SP,#0x1C+var_1C] __text:00002938 0A 10 8D E9 STMFA SP, {R1,R3,R12} __text:0000293C 08 90 A0 E3 MOV R9, #8 __text:00002940 01 10 A0 E3 MOV R1, #1 __text:00002944 02 20 A0 E3 MOV R2, #2 __text:00002948 03 30 A0 E3 MOV R3, #3 __text:0000294C 10 90 8D E5 STR R9, [SP,#0x1C+var_C] __text:00002950 A4 05 00 EB BL _printf __text:00002954 07 D0 A0 E1 MOV SP, R7 __text:00002958 80 80 BD E8 LDMFD SP!, {R7,PC} Almost the same as what we have already seen, with the exception of STMFA (Store Multiple Full Ascending) instruction, which is a synonym of STMIB (Store Multiple Increment Before) instruction. This instruction increases the value in the SP register and only then writes the next register value into the memory, rather than performing those two actions in the opposite order. Another thing that catches the eye is that the instructions are arranged seemingly random. For example, the value in the R0 register is manipulated in three places, at addresses 0x2918, 0x2920 and 0x2928, when it would be possible to do it in one point. However, the optimizing compiler may have its own reasons on how to order the instructions so to achieve higher efficiency during the execution. Usually, the processor attempts to simultaneously execute instructions located side-by-side. For example, instructions like ``MOVT R0, #0'' and ``ADD R0, PC, R0'' cannot be executed simultaneously since they both modify the R0 register. On the other hand, ``MOVT R0, #0'' and ``MOV R2, #4'' instructions can be executed simultaneously since the effects of their execution are not conflicting with each other. Presumably, the compiler tries to generate code in such a manner (wherever it is possible). Optimizing Xcode 4.6.3 (LLVM): thumb-2 mode __text:00002BA0 _printf_main2 __text:00002BA0 __text:00002BA0 var_1C = -0x1C __text:00002BA0 var_18 = -0x18 __text:00002BA0 var_C = -0xC __text:00002BA0 __text:00002BA0 80 B5 PUSH {R7,LR} __text:00002BA2 6F 46 MOV R7, SP __text:00002BA4 85 B0 SUB SP, SP, #0x14 __text:00002BA6 41 F2 D8 20 MOVW R0, #0x12D8 __text:00002BAA 4F F0 07 0C MOV.W R12, #7 __text:00002BAE C0 F2 00 00 MOVT.W R0, #0 __text:00002BB2 04 22 MOVS R2, #4 __text:00002BB4 78 44 ADD R0, PC ; char * __text:00002BB6 06 23 MOVS R3, #6 47
  • 72. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS __text:00002BB8 05 21 MOVS R1, #5 __text:00002BBA 0D F1 04 0E ADD.W LR, SP, #0x1C+var_18 __text:00002BBE 00 92 STR R2, [SP,#0x1C+var_1C] __text:00002BC0 4F F0 08 09 MOV.W R9, #8 __text:00002BC4 8E E8 0A 10 STMIA.W LR, {R1,R3,R12} __text:00002BC8 01 21 MOVS R1, #1 __text:00002BCA 02 22 MOVS R2, #2 __text:00002BCC 03 23 MOVS R3, #3 __text:00002BCE CD F8 10 90 STR.W R9, [SP,#0x1C+var_C] __text:00002BD2 01 F0 0A EA BLX _printf __text:00002BD6 05 B0 ADD SP, SP, #0x14 __text:00002BD8 80 BD POP {R7,PC} The output is almost the same as in the previous example, with the exception that thumb-instructions are used instead. ARM64 Non-optimizing GCC (Linaro) 4.9 Listing 6.10: Non-optimizing GCC (Linaro) 4.9 .LC2: .string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn" f3: ; grab more space in stack: sub sp, sp, #32 ; save FP and LR in stack frame: stp x29, x30, [sp,16] ; set stack frame (FP=SP): add x29, sp, 16 adrp x0, .LC2 ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn" add x0, x0, :lo12:.LC2 mov w1, 8 ; 9th argument str w1, [sp] ; store 9th argument in the stack mov w1, 1 mov w2, 2 mov w3, 3 mov w4, 4 mov w5, 5 mov w6, 6 mov w7, 7 bl printf sub sp, x29, #16 ; restore FP and LR ldp x29, x30, [sp,16] add sp, sp, 32 ret The first 8 arguments are passed in X- or W-registers: [ARM13c]. A string pointer requires a 64-bit register, so it’s passed in X0. All other values have a int 32-bit type, so they are stored in the 32-bit part of the registers (W-). The 9th argument (8) is passed via the stack. Indeed: it’s not possible to pass large number of arguments through registers, because the number of registers is limited. Optimizing GCC (Linaro) 4.9 generates the same code. 6.3 MIPS 6.3.1 3 arguments Optimizing GCC 4.4.5 The main difference with the “Hello, world!” example is that in this case printf() is called instead of puts() and 3 more arguments are passed through the registers $5 …$7 (or $A0 …$A2). That is why these registers are prefixed with A-, which implies they are used for function arguments passing. Listing 6.11: Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "a=%d; b=%d; c=%d000" main: 48
  • 73. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-32 addiu $28,$28,%lo(__gnu_local_gp) sw $31,28($sp) ; load address of printf(): lw $25,%call16(printf)($28) ; load address of the text string and set 1st argument of printf(): lui $4,%hi($LC0) addiu $4,$4,%lo($LC0) ; set 2nd argument of printf(): li $5,1 # 0x1 ; set 3rd argument of printf(): li $6,2 # 0x2 ; call printf(): jalr $25 ; set 4th argument of printf() (branch delay slot): li $7,3 # 0x3 ; function epilogue: lw $31,28($sp) ; set return value to 0: move $2,$0 ; return j $31 addiu $sp,$sp,32 ; branch delay slot Listing 6.12: Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x20 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x20+var_4($sp) .text:00000010 sw $gp, 0x20+var_10($sp) ; load address of printf(): .text:00000014 lw $t9, (printf & 0xFFFF)($gp) ; load address of the text string and set 1st argument of printf(): .text:00000018 la $a0, $LC0 # "a=%d; b=%d; c=%d" ; set 2nd argument of printf(): .text:00000020 li $a1, 1 ; set 3rd argument of printf(): .text:00000024 li $a2, 2 ; call printf(): .text:00000028 jalr $t9 ; set 4th argument of printf() (branch delay slot): .text:0000002C li $a3, 3 ; function epilogue: .text:00000030 lw $ra, 0x20+var_4($sp) ; set return value to 0: .text:00000034 move $v0, $zero ; return .text:00000038 jr $ra .text:0000003C addiu $sp, 0x20 ; branch delay slot Non-optimizing GCC 4.4.5 Non-optimizing GCC is more verbose: Listing 6.13: Non-optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "a=%d; b=%d; c=%d000" main: ; function prologue: 49
  • 74. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS addiu $sp,$sp,-32 sw $31,28($sp) sw $fp,24($sp) move $fp,$sp lui $28,%hi(__gnu_local_gp) addiu $28,$28,%lo(__gnu_local_gp) ; load address of the text string: lui $2,%hi($LC0) addiu $2,$2,%lo($LC0) ; set 1st argument of printf(): move $4,$2 ; set 2nd argument of printf(): li $5,1 # 0x1 ; set 3rd argument of printf(): li $6,2 # 0x2 ; set 4th argument of printf(): li $7,3 # 0x3 ; get address of printf(): lw $2,%call16(printf)($28) nop ; call printf(): move $25,$2 jalr $25 nop ; function epilogue: lw $28,16($fp) ; set return value to 0: move $2,$0 move $sp,$fp lw $31,28($sp) lw $fp,24($sp) addiu $sp,$sp,32 ; return j $31 nop Listing 6.14: Non-optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 addiu $sp, -0x20 .text:00000004 sw $ra, 0x20+var_4($sp) .text:00000008 sw $fp, 0x20+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x20+var_10($sp) ; load address of the text string: .text:0000001C la $v0, aADBDCD # "a=%d; b=%d; c=%d" ; set 1st argument of printf(): .text:00000024 move $a0, $v0 ; set 2nd argument of printf(): .text:00000028 li $a1, 1 ; set 3rd argument of printf(): .text:0000002C li $a2, 2 ; set 4th argument of printf(): .text:00000030 li $a3, 3 ; get address of printf(): .text:00000034 lw $v0, (printf & 0xFFFF)($gp) .text:00000038 or $at, $zero ; call printf(): .text:0000003C move $t9, $v0 .text:00000040 jalr $t9 .text:00000044 or $at, $zero ; NOP ; function epilogue: 50
  • 75. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS .text:00000048 lw $gp, 0x20+var_10($fp) ; set return value to 0: .text:0000004C move $v0, $zero .text:00000050 move $sp, $fp .text:00000054 lw $ra, 0x20+var_4($sp) .text:00000058 lw $fp, 0x20+var_8($sp) .text:0000005C addiu $sp, 0x20 ; return .text:00000060 jr $ra .text:00000064 or $at, $zero ; NOP 6.3.2 8 arguments Let’s use again the example with 9 arguments from the previous section: 6.1.2 on page 40. #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%dn", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; Optimizing GCC 4.4.5 Only the first 4 arguments are passed in the $A0 …$A3 registers, the rest are passed via the stack. This is the O32 calling convention (which is the most common one in the MIPS world). Other calling conventions (like N32) may use the registers for different purposes. SW abbreviates “Store Word” (from register to memory). MIPS lacks instructions for storing a value into memory, so an instruction pair has to be used instead (LI/SW). Listing 6.15: Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d012000" main: ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-56 addiu $28,$28,%lo(__gnu_local_gp) sw $31,52($sp) ; pass 5th argument in stack: li $2,4 # 0x4 sw $2,16($sp) ; pass 6th argument in stack: li $2,5 # 0x5 sw $2,20($sp) ; pass 7th argument in stack: li $2,6 # 0x6 sw $2,24($sp) ; pass 8th argument in stack: li $2,7 # 0x7 lw $25,%call16(printf)($28) sw $2,28($sp) ; pass 1st argument in $a0: lui $4,%hi($LC0) ; pass 9th argument in stack: li $2,8 # 0x8 sw $2,32($sp) addiu $4,$4,%lo($LC0) ; pass 2nd argument in $a1: li $5,1 # 0x1 ; pass 3rd argument in $a2: li $6,2 # 0x2 ; call printf(): jalr $25 ; pass 4th argument in $a3 (branch delay slot): li $7,3 # 0x3 51
  • 76. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS ; function epilogue: lw $31,52($sp) ; set return value to 0: move $2,$0 ; return j $31 addiu $sp,$sp,56 ; branch delay slot Listing 6.16: Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_28 = -0x28 .text:00000000 var_24 = -0x24 .text:00000000 var_20 = -0x20 .text:00000000 var_1C = -0x1C .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x38 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x38+var_4($sp) .text:00000010 sw $gp, 0x38+var_10($sp) ; pass 5th argument in stack: .text:00000014 li $v0, 4 .text:00000018 sw $v0, 0x38+var_28($sp) ; pass 6th argument in stack: .text:0000001C li $v0, 5 .text:00000020 sw $v0, 0x38+var_24($sp) ; pass 7th argument in stack: .text:00000024 li $v0, 6 .text:00000028 sw $v0, 0x38+var_20($sp) ; pass 8th argument in stack: .text:0000002C li $v0, 7 .text:00000030 lw $t9, (printf & 0xFFFF)($gp) .text:00000034 sw $v0, 0x38+var_1C($sp) ; prepare 1st argument in $a0: .text:00000038 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d⤦ ; g=%"... ; pass 9th argument in stack: .text:0000003C li $v0, 8 .text:00000040 sw $v0, 0x38+var_18($sp) ; pass 1st argument in $a1: .text:00000044 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%d; e=%d; f⤦ =%d; g=%"... ; pass 2nd argument in $a1: .text:00000048 li $a1, 1 ; pass 3rd argument in $a2: .text:0000004C li $a2, 2 ; call printf(): .text:00000050 jalr $t9 ; pass 4th argument in $a3 (branch delay slot): .text:00000054 li $a3, 3 ; function epilogue: .text:00000058 lw $ra, 0x38+var_4($sp) ; set return value to 0: .text:0000005C move $v0, $zero ; return .text:00000060 jr $ra .text:00000064 addiu $sp, 0x38 ; branch delay slot Non-optimizing GCC 4.4.5 Non-optimizing GCC is more verbose: 52
  • 77. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.3. MIPS Listing 6.17: Non-optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d012000" main: ; function prologue: addiu $sp,$sp,-56 sw $31,52($sp) sw $fp,48($sp) move $fp,$sp lui $28,%hi(__gnu_local_gp) addiu $28,$28,%lo(__gnu_local_gp) lui $2,%hi($LC0) addiu $2,$2,%lo($LC0) ; pass 5th argument in stack: li $3,4 # 0x4 sw $3,16($sp) ; pass 6th argument in stack: li $3,5 # 0x5 sw $3,20($sp) ; pass 7th argument in stack: li $3,6 # 0x6 sw $3,24($sp) ; pass 8th argument in stack: li $3,7 # 0x7 sw $3,28($sp) ; pass 9th argument in stack: li $3,8 # 0x8 sw $3,32($sp) ; pass 1st argument in $a0: move $4,$2 ; pass 2nd argument in $a1: li $5,1 # 0x1 ; pass 3rd argument in $a2: li $6,2 # 0x2 ; pass 4th argument in $a3: li $7,3 # 0x3 ; call printf(): lw $2,%call16(printf)($28) nop move $25,$2 jalr $25 nop ; function epilogue: lw $28,40($fp) ; set return value to 0: move $2,$0 move $sp,$fp lw $31,52($sp) lw $fp,48($sp) addiu $sp,$sp,56 ; return j $31 nop Listing 6.18: Non-optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_28 = -0x28 .text:00000000 var_24 = -0x24 .text:00000000 var_20 = -0x20 .text:00000000 var_1C = -0x1C .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 addiu $sp, -0x38 .text:00000004 sw $ra, 0x38+var_4($sp) 53
  • 78. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.4. CONCLUSION .text:00000008 sw $fp, 0x38+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x38+var_10($sp) .text:0000001C la $v0, aADBDCDDDEDFDGD # "a=%d; b=%d; c=%d; d=%d; e=%d; f⤦ =%d; g=%"... ; pass 5th argument in stack: .text:00000024 li $v1, 4 .text:00000028 sw $v1, 0x38+var_28($sp) ; pass 6th argument in stack: .text:0000002C li $v1, 5 .text:00000030 sw $v1, 0x38+var_24($sp) ; pass 7th argument in stack: .text:00000034 li $v1, 6 .text:00000038 sw $v1, 0x38+var_20($sp) ; pass 8th argument in stack: .text:0000003C li $v1, 7 .text:00000040 sw $v1, 0x38+var_1C($sp) ; pass 9th argument in stack: .text:00000044 li $v1, 8 .text:00000048 sw $v1, 0x38+var_18($sp) ; pass 1st argument in $a0: .text:0000004C move $a0, $v0 ; pass 2nd argument in $a1: .text:00000050 li $a1, 1 ; pass 3rd argument in $a2: .text:00000054 li $a2, 2 ; pass 4th argument in $a3: .text:00000058 li $a3, 3 ; call printf(): .text:0000005C lw $v0, (printf & 0xFFFF)($gp) .text:00000060 or $at, $zero .text:00000064 move $t9, $v0 .text:00000068 jalr $t9 .text:0000006C or $at, $zero ; NOP ; function epilogue: .text:00000070 lw $gp, 0x38+var_10($fp) ; set return value to 0: .text:00000074 move $v0, $zero .text:00000078 move $sp, $fp .text:0000007C lw $ra, 0x38+var_4($sp) .text:00000080 lw $fp, 0x38+var_8($sp) .text:00000084 addiu $sp, 0x38 ; return .text:00000088 jr $ra .text:0000008C or $at, $zero ; NOP 6.4 Conclusion Here is a rough skeleton of the function call: Listing 6.19: x86 ... PUSH 3rd argument PUSH 2nd argument PUSH 1st argument CALL function ; modify stack pointer (if needed) Listing 6.20: x64 (MSVC) MOV RCX, 1st argument MOV RDX, 2nd argument MOV R8, 3rd argument MOV R9, 4th argument ... PUSH 5th, 6th argument, etc (if needed) CALL function 54
  • 79. CHAPTER 6. PRINTF() WITH SEVERAL ARGUMENTS 6.5. BY THE WAY ; modify stack pointer (if needed) Listing 6.21: x64 (GCC) MOV RDI, 1st argument MOV RSI, 2nd argument MOV RDX, 3rd argument MOV RCX, 4th argument MOV R8, 5th argument MOV R9, 6th argument ... PUSH 7th, 8th argument, etc (if needed) CALL function ; modify stack pointer (if needed) Listing 6.22: ARM MOV R0, 1st argument MOV R1, 2nd argument MOV R2, 3rd argument MOV R3, 4th argument ; pass 5th, 6th argument, etc, in stack (if needed) BL function ; modify stack pointer (if needed) Listing 6.23: ARM64 MOV X0, 1st argument MOV X1, 2nd argument MOV X2, 3rd argument MOV X3, 4th argument MOV X4, 5th argument MOV X5, 6th argument MOV X6, 7th argument MOV X7, 8th argument ; pass 9th, 10th argument, etc, in stack (if needed) BL CALL function ; modify stack pointer (if needed) Listing 6.24: MIPS (O32 calling convention) LI $4, 1st argument ; AKA $A0 LI $5, 2nd argument ; AKA $A1 LI $6, 3rd argument ; AKA $A2 LI $7, 4th argument ; AKA $A3 ; pass 5th, 6th argument, etc, in stack (if needed) LW temp_reg, address of function JALR temp_reg 6.5 By the way By the way, this difference between the arguments passing in x86, x64, fastcall, ARM and MIPS is a good illustration of the fact that the CPU is oblivious to how the arguments are passed to functions. It is also possible to create a hypothetical compiler able to pass arguments via a special structure without using stack at all. MIPS $A0 …$A3 registers are labelled this way only for convenience (that is in the O32 calling convention). Programmers may use any other register (well, maybe except $ZERO) to pass data or use any other calling convention. The CPU is not aware of calling conventions whatsoever. We may also recall how newcoming assembly language programmers passing arguments into other functions: usually via registers, without any explicit order, or even via global variables. Of course, it works fine. 55
  • 80. CHAPTER 7. SCANF() Chapter 7 scanf() Now let’s use scanf(). 7.1 Simple example #include <stdio.h> int main() { int x; printf ("Enter X:n"); scanf ("%d", &x); printf ("You entered %d...n", x); return 0; }; OK, I agree, it is not clever to use scanf() for user interactions nowadays. I wanted, however, to illustrate passing a pointer to a variable of type int. 7.1.1 About pointers Pointers are one of the fundamental concepts in computer science. Often, passing a large array, structure or object as an argument to another function is too expensive, while passing their address is much cheaper. In addition if the callee function needs to modify something in the large array or structure received as a parameter and return back the entire structure then the situation is close to absurd. So the simplest thing to do is to pass the address of the array or structure to the callee function, and let it change what needs to be changed. A pointer in C/C++ is simply an address of some memory location. In x86, the address is represented as a 32-bit number (i.e., it is occupying 4 bytes), while in x86–64 it is a 64-bit num- ber(occupying 8 bytes). By the way, that is the reason behind some people’s indignation related to switching to x86-64 —all pointers in the x64-architecture require twice as much space. It is possible to work with untyped pointers only, given some effort; e.g. the standard C function memcpy(), that copies a block from one memory location to another, takes 2 pointers of type void* as arguments, since it is impossible to predict the type of the data you would like to copy. Data types are not important, only the block size matters. Pointers are also widely used when a function needs to return more than one value (we are going to get back to this later ( 10 on page 98) ). scanf() is such a case. Besides the fact that the function needs to indicate how many values were successfully read, it also needs to return all these values. In C/C++ the pointer type is only needed for compile-time type checking. Internally, in the compiled code there is no information about pointer types at all. 7.1.2 x86 MSVC Here is what we get after compiling with MSVC 2010: CONST SEGMENT $SG3831 DB 'Enter X:', 0aH, 00H $SG3832 DB '%d', 00H 56
  • 81. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE $SG3833 DB 'You entered %d...', 0aH, 00H CONST ENDS PUBLIC _main EXTRN _scanf:PROC EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _x$ = -4 ; size = 4 _main PROC push ebp mov ebp, esp push ecx push OFFSET $SG3831 ; 'Enter X:' call _printf add esp, 4 lea eax, DWORD PTR _x$[ebp] push eax push OFFSET $SG3832 ; '%d' call _scanf add esp, 8 mov ecx, DWORD PTR _x$[ebp] push ecx push OFFSET $SG3833 ; 'You entered %d...' call _printf add esp, 8 ; return 0 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS x is a local variable. According to the C/C++ standard it must be visible only in this function and not from any other external scope. Tradition- ally, local variables are stored on the stack. There are probably other ways to allocate them, but in x86 that is the way it is. The goal of the instruction following the function prologue, PUSH ECX, is not to save the ECX state (notice the absence of corresponding POP ECX at the function’s end). In fact it allocates 4 bytes on the stack for storing the x variable. x is to be accessed with the assistance of the _x$ macro (it equals to -4) and the EBP register pointing to the current frame. Over the span of the function’s execution, EBP is pointing to the current stack frame making it possible to access local variables and function arguments via EBP+offset. It is also possible to use ESP for the same purpose, although that is not very convenient since it changes frequently. The value of the EBP could be perceived as a frozen state of the value in ESP at the start of the function’s execution. Here is a typical stack frame layout in 32-bit environment: … … EBP-8 local variable #2, marked in IDA as var_8 EBP-4 local variable #1, marked in IDA as var_4 EBP saved value of EBP EBP+4 return address EBP+8 argument#1, marked in IDA as arg_0 EBP+0xC argument#2, marked in IDA as arg_4 EBP+0x10 argument#3, marked in IDA as arg_8 … … The scanf() function in our example has two arguments. The first one is a pointer to the string containing ``%d'' and the second is the address of the x variable. First, the x variable’s address is loaded into the EAX register by the lea eax, DWORD PTR _x$[ebp] instruction LEA stands for load effective address, and is often used for forming an address ( A.6.2 on page 933). We could say that in this case LEA simply stores the sum of the EBP register value and the _x$ macro in the EAX register. This is the same as lea eax, [ebp-4]. So, 4 is being subtracted from the EBP register value and the result is loaded in the EAX register. Next the EAX register value is pushed into the stack and scanf() is being called. 57
  • 82. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE printf() is being called after that with its first argument - a pointer to the string: ``You entered %d...n''. The second argument is prepared with: mov ecx, [ebp-4]. The instruction stores the x variable value and not its address, in the ECX register. Next the value in the ECX is stored on the stack and the last printf() is being called. 58
  • 83. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE 7.1.3 MSVC + OllyDbg Let’s try this example in OllyDbg. Let’s load it and keep pressing F8 (step over) until we reach our executable file instead of ntdll.dll. Scroll up until main() appears. Click on the first instruction (PUSH EBP), press F2 (set a breakpoint), then F9 (Run). The breakpoint will be triggered when main() begins. Let’s trace to the point where the address of the variable x is calculated: Figure 7.1: OllyDbg: The address of the local variable is calculated Right-click the EAX in the registers window and then select “Follow in stack”. This address will appear in the stack window. The red arrow, I have added, points to the variable in the local stack. At that moment this location contains some garbage (0x6E494714). Now with the help of PUSH instruction the address of this stack element is going to be stored to the same stack on the next position. Let’s trace with F8 until the scanf() execution completes. During the scanf() execution, we input, for example, 123, in the console window: Figure 7.2: User input in the console window 59
  • 84. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE scanf() completed its execution already: Figure 7.3: OllyDbg: scanf() executed scanf() returns 1 in EAX, which implies that it has read successfully one value. If we look again at the stack element corresponding to the local variable it now contains 0x7B (123). 60
  • 85. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE Further, this value is copied from the stack to the ECX register and passed to printf(): Figure 7.4: OllyDbg: preparing the value for passing to printf() GCC Let’s try to compile this code in GCC 4.4.1 under Linux: main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_20], offset aEnterX ; "Enter X:" call _puts mov eax, offset aD ; "%d" lea edx, [esp+20h+var_4] mov [esp+20h+var_1C], edx mov [esp+20h+var_20], eax call ___isoc99_scanf mov edx, [esp+20h+var_4] mov eax, offset aYouEnteredD___ ; "You entered %d...n" mov [esp+20h+var_1C], edx mov [esp+20h+var_20], eax call _printf mov eax, 0 leave retn main endp GCC replaced the printf() call with call to puts(). The reason for this was explained in ( 3.4.3 on page 14). As in the MSVC example —the arguments are placed on the stack using the MOV instruction. By the way By the way, this simple example is a demonstration of the fact that compiler translates list of expressions in C/C++-block into sequential list of instructions. There are nothing between expressions in C/C++, and so in resulting machine code, there are nothing between, control flow slips from one expression to another. 7.1.4 x64 The picture here is similar with the difference that the registers, rather than the stack, are used for arguments passing. 61
  • 86. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE MSVC Listing 7.1: MSVC 2012 x64 _DATA SEGMENT $SG1289 DB 'Enter X:', 0aH, 00H $SG1291 DB '%d', 00H $SG1292 DB 'You entered %d...', 0aH, 00H _DATA ENDS _TEXT SEGMENT x$ = 32 main PROC $LN3: sub rsp, 56 lea rcx, OFFSET FLAT:$SG1289 ; 'Enter X:' call printf lea rdx, QWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG1291 ; '%d' call scanf mov edx, DWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG1292 ; 'You entered %d...' call printf ; return 0 xor eax, eax add rsp, 56 ret 0 main ENDP _TEXT ENDS GCC Listing 7.2: Optimizing GCC 4.4.6 x64 .LC0: .string "Enter X:" .LC1: .string "%d" .LC2: .string "You entered %d...n" main: sub rsp, 24 mov edi, OFFSET FLAT:.LC0 ; "Enter X:" call puts lea rsi, [rsp+12] mov edi, OFFSET FLAT:.LC1 ; "%d" xor eax, eax call __isoc99_scanf mov esi, DWORD PTR [rsp+12] mov edi, OFFSET FLAT:.LC2 ; "You entered %d...n" xor eax, eax call printf ; return 0 xor eax, eax add rsp, 24 ret 7.1.5 ARM Optimizing Keil 6/2013 (thumb mode) .text:00000042 scanf_main .text:00000042 .text:00000042 var_8 = -8 62
  • 87. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE .text:00000042 .text:00000042 08 B5 PUSH {R3,LR} .text:00000044 A9 A0 ADR R0, aEnterX ; "Enter X:n" .text:00000046 06 F0 D3 F8 BL __2printf .text:0000004A 69 46 MOV R1, SP .text:0000004C AA A0 ADR R0, aD ; "%d" .text:0000004E 06 F0 CD F8 BL __0scanf .text:00000052 00 99 LDR R1, [SP,#8+var_8] .text:00000054 A9 A0 ADR R0, aYouEnteredD___ ; "You entered %d...n" .text:00000056 06 F0 CB F8 BL __2printf .text:0000005A 00 20 MOVS R0, #0 .text:0000005C 08 BD POP {R3,PC} In order for scanf() to be able to read item it needs a parameter—pointer to an int. int is 32-bit, so we need 4 bytes to store it somewhere in memory, and it fits exactly in a 32-bit register. A place for the local variable x is allocated in the stack and IDA has named it var_8. It is not necessary, however, to allocate a such since SP (stack pointer) is already pointing to that space and it can be used directly. So, SP’s value is copied to the R1 register and, together with the format-string, passed to scanf(). Later, with the help of the LDR instruction, this value is moved from the stack to the R1 register in order to be passed to printf(). ARM64 Listing 7.3: Non-optimizing GCC 4.9.1 ARM64 1 .LC0: 2 .string "Enter X:" 3 .LC1: 4 .string "%d" 5 .LC2: 6 .string "You entered %d...n" 7 f4: 8 ; save FP and LR in stack frame: 9 stp x29, x30, [sp, -32]! 10 ; set stack frame (FP=SP) 11 add x29, sp, 0 12 ; load pointer to the "Enter X:" string: 13 adrp x0, .LC0 14 add x0, x0, :lo12:.LC0 15 ; X0=pointer to the "Enter X:" string 16 ; print it: 17 bl puts 18 ; load pointer to the "%d" string: 19 adrp x0, .LC1 20 add x0, x0, :lo12:.LC1 21 ; find a space in stack frame for "x" variable (X1=FP+28): 22 add x1, x29, 28 23 ; X1=address of "x" variable 24 ; pass the address to scanf() and call it: 25 bl __isoc99_scanf 26 ; load 32-bit value from the variable in stack frame: 27 ldr w1, [x29,28] 28 ; W1=x 29 ; load pointer to the "You entered %d...n" string 30 ; printf() will take text string from X0 and "x" variable from X1 (or W1) 31 adrp x0, .LC2 32 add x0, x0, :lo12:.LC2 33 bl printf 34 ; return 0 35 mov w0, 0 36 ; restore FP and LR: 37 ldp x29, x30, [sp], 32 38 ret The most interesting part is finding space for the x variable in the stack frame (line 22). The address is passed to scanf(), which just stores the user input value in the memory at that address. This is 32-bit value of type int. The value is fetched at line 27 and then passed to printf(). 63
  • 88. CHAPTER 7. SCANF() 7.1. SIMPLE EXAMPLE 7.1.6 MIPS A place in the local stack is allocated for the x variable, and it is to be referred as $sp+24. Its address is passed to scanf(), and the user input values is loaded using the LW (“Load Word”) instruction and then passed to printf(). Listing 7.4: Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "Enter X:000" $LC1: .ascii "%d000" $LC2: .ascii "You entered %d...012000" main: ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-40 addiu $28,$28,%lo(__gnu_local_gp) sw $31,36($sp) ; call puts(): lw $25,%call16(puts)($28) lui $4,%hi($LC0) jalr $25 addiu $4,$4,%lo($LC0) ; branch delay slot ; call scanf(): lw $28,16($sp) lui $4,%hi($LC1) lw $25,%call16(__isoc99_scanf)($28) ; set 2nd argument of scanf(), $a1=$sp+24: addiu $5,$sp,24 jalr $25 addiu $4,$4,%lo($LC1) ; branch delay slot ; call printf(): lw $28,16($sp) ; set 2nd argument of printf(), ; load word at address $sp+24: lw $5,24($sp) lw $25,%call16(printf)($28) lui $4,%hi($LC2) jalr $25 addiu $4,$4,%lo($LC2) ; branch delay slot ; function epilogue: lw $31,36($sp) ; set return value to 0: move $2,$0 ; return: j $31 addiu $sp,$sp,40 ; branch delay slot IDA displays the stack layout as follows: Listing 7.5: Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x28 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x28+var_4($sp) .text:00000010 sw $gp, 0x28+var_18($sp) ; call puts(): .text:00000014 lw $t9, (puts & 0xFFFF)($gp) .text:00000018 lui $a0, ($LC0 >> 16) # "Enter X:" .text:0000001C jalr $t9 .text:00000020 la $a0, ($LC0 & 0xFFFF) # "Enter X:" ; branch delay slot 64
  • 89. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES ; call scanf(): .text:00000024 lw $gp, 0x28+var_18($sp) .text:00000028 lui $a0, ($LC1 >> 16) # "%d" .text:0000002C lw $t9, (__isoc99_scanf & 0xFFFF)($gp) ; set 2nd argument of scanf(), $a1=$sp+24: .text:00000030 addiu $a1, $sp, 0x28+var_10 .text:00000034 jalr $t9 ; branch delay slot .text:00000038 la $a0, ($LC1 & 0xFFFF) # "%d" ; call printf(): .text:0000003C lw $gp, 0x28+var_18($sp) ; set 2nd argument of printf(), ; load word at address $sp+24: .text:00000040 lw $a1, 0x28+var_10($sp) .text:00000044 lw $t9, (printf & 0xFFFF)($gp) .text:00000048 lui $a0, ($LC2 >> 16) # "You entered %d...n" .text:0000004C jalr $t9 .text:00000050 la $a0, ($LC2 & 0xFFFF) # "You entered %d...n" ; branch ⤦ delay slot ; function epilogue: .text:00000054 lw $ra, 0x28+var_4($sp) ; set return value to 0: .text:00000058 move $v0, $zero ; return: .text:0000005C jr $ra .text:00000060 addiu $sp, 0x28 ; branch delay slot 7.2 Global variables What if the x variable from the previous example was not local but a global one? Then it would have been accessible from any point, not only from the function body. Global variables are considered anti-pattern, but for the sake of the experiment, we could do this. #include <stdio.h> // now x is global variable int x; int main() { printf ("Enter X:n"); scanf ("%d", &x); printf ("You entered %d...n", x); return 0; }; 7.2.1 MSVC: x86 _DATA SEGMENT COMM _x:DWORD $SG2456 DB 'Enter X:', 0aH, 00H $SG2457 DB '%d', 00H $SG2458 DB 'You entered %d...', 0aH, 00H _DATA ENDS PUBLIC _main EXTRN _scanf:PROC EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _main PROC push ebp mov ebp, esp push OFFSET $SG2456 call _printf 65
  • 90. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES add esp, 4 push OFFSET _x push OFFSET $SG2457 call _scanf add esp, 8 mov eax, DWORD PTR _x push eax push OFFSET $SG2458 call _printf add esp, 8 xor eax, eax pop ebp ret 0 _main ENDP _TEXT ENDS In this case the x variable is defined in the _DATA segment and no memory is allocated in the local stack. It is accessed directly, not through the stack. Uninitialized global variables take no space in the executable file (indeed, why one needs to allocate space for variables initially set to zero?), but when someone accesses their address, the OS will allocate a block of zeroes there1 . Now let’s explicitly assign a value to the variable: int x=10; // default value We got: _DATA SEGMENT _x DD 0aH ... Here we see a value 0xA of DWORD type (DD stands for DWORD = 32 bit) for this variable. If you open the compiled .exe in IDA, you can see the x variable placed at the beginning of the _DATA segment, and after it you can see text strings. If you open the compiled .exe from the previous example in IDA, where the value of x was not set, you would see something like this: .data:0040FA80 _x dd ? ; DATA XREF: _main+10 .data:0040FA80 ; _main+22 .data:0040FA84 dword_40FA84 dd ? ; DATA XREF: _memset+1E .data:0040FA84 ; unknown_libname_1+28 .data:0040FA88 dword_40FA88 dd ? ; DATA XREF: ___sbh_find_block+5 .data:0040FA88 ; ___sbh_free_block+2BC .data:0040FA8C ; LPVOID lpMem .data:0040FA8C lpMem dd ? ; DATA XREF: ___sbh_find_block+B .data:0040FA8C ; ___sbh_free_block+2CA .data:0040FA90 dword_40FA90 dd ? ; DATA XREF: _V6_HeapAlloc+13 .data:0040FA90 ; __calloc_impl+72 .data:0040FA94 dword_40FA94 dd ? ; DATA XREF: ___sbh_free_block+2FE _x is marked with ? with the rest of the variables that do not need to be initialized. This implies that after loading the .exe to the memory, a space for all these variables is to be allocated and filled with zeroes [ISO07, 6.7.8p10]. But in the .exe file these uninitialized variables do not occupy anything. This is convenient for example when using large arrays. 1That is how a VM behaves 66
  • 91. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES 7.2.2 MSVC: x86 + OllyDbg Things are even simpler here: Figure 7.5: OllyDbg: after scanf() execution The variable is located in the data segment. After the PUSH instruction (pushing the address of x) gets executed, the address appears in the stack window. Right-click on that row and select “Follow in dump”. The variable will appear in the memory window on the left. After we have entered 123 in the console, 0x7B appears in the memory window (see the highlighted screenshot regions). But why is the first byte 7B? Thinking logically, 00 00 00 7B should be there. The cause for this is referred as endianness, and x86 uses little-endian. This implies that the lowest byte is written first, and the highest written last. Read more about it at: 31 on page 453. Back to the example, the 32-bit value is loaded from this memory address into EAX and passed to printf(). The memory address of x is 0x00C53394. 67
  • 92. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES In OllyDbg we can review the process memory map (Alt-M) and we can see that this address is inside the .data PE- segment of our program: Figure 7.6: OllyDbg: process memory map 7.2.3 GCC: x86 The picture in Linux is near the same, with the difference that the uninitialized variables are located in the _bss segment. In ELF file this segment has the following attributes: ; Segment type: Uninitialized ; Segment permissions: Read/Write If you, however, initialise the variable with some value e.g. 10, it is to be placed in the _data segment, which has the following attributes: ; Segment type: Pure data ; Segment permissions: Read/Write 7.2.4 MSVC: x64 Listing 7.6: MSVC 2012 x64 _DATA SEGMENT COMM x:DWORD $SG2924 DB 'Enter X:', 0aH, 00H $SG2925 DB '%d', 00H $SG2926 DB 'You entered %d...', 0aH, 00H _DATA ENDS _TEXT SEGMENT main PROC $LN3: sub rsp, 40 lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X:' call printf lea rdx, OFFSET FLAT:x 68
  • 93. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES lea rcx, OFFSET FLAT:$SG2925 ; '%d' call scanf mov edx, DWORD PTR x lea rcx, OFFSET FLAT:$SG2926 ; 'You entered %d...' call printf ; return 0 xor eax, eax add rsp, 40 ret 0 main ENDP _TEXT ENDS The code is almost the same as in x86. Please note that the address of the x variable is passed to scanf() using a LEA instruction, while the variable’s value is passed to the second printf() using a MOV instruction. ``DWORD PTR'' is a part of the assembly language (no relation to the machine code), indicating that the variable data size is 32-bit and the MOV instruction has to be encoded accordingly. 7.2.5 ARM: Optimizing Keil 6/2013 (thumb mode) .text:00000000 ; Segment type: Pure code .text:00000000 AREA .text, CODE ... .text:00000000 main .text:00000000 PUSH {R4,LR} .text:00000002 ADR R0, aEnterX ; "Enter X:n" .text:00000004 BL __2printf .text:00000008 LDR R1, =x .text:0000000A ADR R0, aD ; "%d" .text:0000000C BL __0scanf .text:00000010 LDR R0, =x .text:00000012 LDR R1, [R0] .text:00000014 ADR R0, aYouEnteredD___ ; "You entered %d...n" .text:00000016 BL __2printf .text:0000001A MOVS R0, #0 .text:0000001C POP {R4,PC} ... .text:00000020 aEnterX DCB "Enter X:",0xA,0 ; DATA XREF: main+2 .text:0000002A DCB 0 .text:0000002B DCB 0 .text:0000002C off_2C DCD x ; DATA XREF: main+8 .text:0000002C ; main+10 .text:00000030 aD DCB "%d",0 ; DATA XREF: main+A .text:00000033 DCB 0 .text:00000034 aYouEnteredD___ DCB "You entered %d...",0xA,0 ; DATA XREF: main+14 .text:00000047 DCB 0 .text:00000047 ; .text ends .text:00000047 ... .data:00000048 ; Segment type: Pure data .data:00000048 AREA .data, DATA .data:00000048 ; ORG 0x48 .data:00000048 EXPORT x .data:00000048 x DCD 0xA ; DATA XREF: main+8 .data:00000048 ; main+10 .data:00000048 ; .data ends So, the x variable is now global and for this reason located in another segment, namely the data segment (.data). One could ask, why are the text strings located in the code segment (.text) and x is located right here? Because it is a variable and by definition its value could change. Moreover it could possibly change often. The code segment might sometimes be located in a ROM2 chip (remember, we now deal with embedded microelectronics, and memory scarcity is common here), and changeable variables —in RAM3 . It is not very economical to store constant variables in RAM when you have ROM. Furthermore, constant variables in RAM must be initialized, because after powering on, the RAM, obviously, contains random information. 2Read-only memory 3Random-access memory 69
  • 94. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES Moving forward, we see a pointer to the x (off_2C) variable in the code segment, and that all operations with the variable occur via this pointer. That is because the x variable could be located somewhere far from this particular code fragment, so its address must be saved somewhere in close proximity to the code. The LDR instruction in thumb mode can only address variables in a range of 1020 bytes from its location, and in in ARM-mode —variables in range of ±4095 bytes. And so the address of the x variable must be located somewhere in close proximity, because there is no guarantee that the linker would be able to accommodate the variable somewhere nearby the code, it may well be even in an external memory chip! One more thing: if a variable is declared as const, the Keil compiler allocates it in the .constdata segment. Perhaps, thereafter, the linker could place this segment in ROM too, along with the code segment. 7.2.6 ARM64 Listing 7.7: Non-optimizing GCC 4.9.1 ARM64 1 .comm x,4,4 2 .LC0: 3 .string "Enter X:" 4 .LC1: 5 .string "%d" 6 .LC2: 7 .string "You entered %d...n" 8 f5: 9 ; save FP and LR in stack frame: 10 stp x29, x30, [sp, -16]! 11 ; set stack frame (FP=SP) 12 add x29, sp, 0 13 ; load pointer to the "Enter X:" string: 14 adrp x0, .LC0 15 add x0, x0, :lo12:.LC0 16 bl puts 17 ; load pointer to the "%d" string: 18 adrp x0, .LC1 19 add x0, x0, :lo12:.LC1 20 ; form address of x global variable: 21 adrp x1, x 22 add x1, x1, :lo12:x 23 bl __isoc99_scanf 24 ; form address of x global variable again: 25 adrp x0, x 26 add x0, x0, :lo12:x 27 ; load value from memory at this address: 28 ldr w1, [x0] 29 ; load pointer to the "You entered %d...n" string: 30 adrp x0, .LC2 31 add x0, x0, :lo12:.LC2 32 bl printf 33 ; return 0 34 mov w0, 0 35 ; restore FP and LR: 36 ldp x29, x30, [sp], 16 37 ret In this case the x variable is declared as global and its address is calculated using the ADRP/ADD instruction pair (lines 21 and 25). 7.2.7 MIPS Uninitialized global variable So now the x variable is global. I have compiled to executable file rather than object file and I have loaded it into IDA. IDA displays the x variable in the .sbss ELF section (remember the “Global Pointer”? 3.5.1 on page 16), since the variable is not initialized at the start. Listing 7.8: Optimizing GCC 4.4.5 (IDA) .text:004006C0 main: .text:004006C0 .text:004006C0 var_10 = -0x10 .text:004006C0 var_4 = -4 70
  • 95. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES .text:004006C0 ; function prologue: .text:004006C0 lui $gp, 0x42 .text:004006C4 addiu $sp, -0x20 .text:004006C8 li $gp, 0x418940 .text:004006CC sw $ra, 0x20+var_4($sp) .text:004006D0 sw $gp, 0x20+var_10($sp) ; call puts(): .text:004006D4 la $t9, puts .text:004006D8 lui $a0, 0x40 .text:004006DC jalr $t9 ; puts .text:004006E0 la $a0, aEnterX # "Enter X:" ; branch delay slot ; call scanf(): .text:004006E4 lw $gp, 0x20+var_10($sp) .text:004006E8 lui $a0, 0x40 .text:004006EC la $t9, __isoc99_scanf ; prepare address of x: .text:004006F0 la $a1, x .text:004006F4 jalr $t9 ; __isoc99_scanf .text:004006F8 la $a0, aD # "%d" ; branch delay slot ; call printf(): .text:004006FC lw $gp, 0x20+var_10($sp) .text:00400700 lui $a0, 0x40 ; get address of x: .text:00400704 la $v0, x .text:00400708 la $t9, printf ; load value from "x" variable and pass it to printf() in $a1: .text:0040070C lw $a1, (x - 0x41099C)($v0) .text:00400710 jalr $t9 ; printf .text:00400714 la $a0, aYouEnteredD___ # "You entered %d...n" ; branch ⤦ delay slot ; function epilogue: .text:00400718 lw $ra, 0x20+var_4($sp) .text:0040071C move $v0, $zero .text:00400720 jr $ra .text:00400724 addiu $sp, 0x20 ; branch delay slot ... .sbss:0041099C # Segment type: Uninitialized .sbss:0041099C .sbss .sbss:0041099C .globl x .sbss:0041099C x: .space 4 .sbss:0041099C IDA reduces the amount of information, so I also made a listing using objdump and commented it: Listing 7.9: Optimizing GCC 4.4.5 (objdump) 1 004006c0 <main>: 2 ; function prologue: 3 4006c0: 3c1c0042 lui gp,0x42 4 4006c4: 27bdffe0 addiu sp,sp,-32 5 4006c8: 279c8940 addiu gp,gp,-30400 6 4006cc: afbf001c sw ra,28(sp) 7 4006d0: afbc0010 sw gp,16(sp) 8 ; call puts(): 9 4006d4: 8f998034 lw t9,-32716(gp) 10 4006d8: 3c040040 lui a0,0x40 11 4006dc: 0320f809 jalr t9 12 4006e0: 248408f0 addiu a0,a0,2288 ; branch delay slot 13 ; call scanf(): 14 4006e4: 8fbc0010 lw gp,16(sp) 15 4006e8: 3c040040 lui a0,0x40 16 4006ec: 8f998038 lw t9,-32712(gp) 17 ; prepare address of x: 18 4006f0: 8f858044 lw a1,-32700(gp) 19 4006f4: 0320f809 jalr t9 20 4006f8: 248408fc addiu a0,a0,2300 ; branch delay slot 21 ; call printf(): 22 4006fc: 8fbc0010 lw gp,16(sp) 71
  • 96. CHAPTER 7. SCANF() 7.2. GLOBAL VARIABLES 23 400700: 3c040040 lui a0,0x40 24 ; get address of x: 25 400704: 8f828044 lw v0,-32700(gp) 26 400708: 8f99803c lw t9,-32708(gp) 27 ; load value from "x" variable and pass it to printf() in $a1: 28 40070c: 8c450000 lw a1,0(v0) 29 400710: 0320f809 jalr t9 30 400714: 24840900 addiu a0,a0,2304 ; branch delay slot 31 ; function epilogue: 32 400718: 8fbf001c lw ra,28(sp) 33 40071c: 00001021 move v0,zero 34 400720: 03e00008 jr ra 35 400724: 27bd0020 addiu sp,sp,32 ; branch delay slot 36 ; pack of NOPs used for aligning next function start on 16-byte boundary: 37 400728: 00200825 move at,at 38 40072c: 00200825 move at,at Now we see the x variable address is read from a 64KiB data buffer using GP and adding negative offset to it (line 18). More than that, the addresses of the three external functions which are used in our example (puts(), scanf(), printf()), are also read from the 64KiB global data buffer using GP (lines 9, 16 and 26). GP points to the middle of the buffer, and such offset suggests that all three function’s addresses, and also the address of the x variable, are all stored somewhere at the beginning of that buffer. That make sense, because our example is tiny. Another thing worth mentioning is that the function ends with two NOPs (MOVE $AT,$AT — an idle instruction), in order to align next function’s start on 16-byte boundary. Initialized global variable Let’s alter our example by giving the x variable a default value: int x=10; // default value Now IDA shows that the x variable is residing in the .data section: Listing 7.10: Optimizing GCC 4.4.5 (IDA) .text:004006A0 main: .text:004006A0 .text:004006A0 var_10 = -0x10 .text:004006A0 var_8 = -8 .text:004006A0 var_4 = -4 .text:004006A0 .text:004006A0 lui $gp, 0x42 .text:004006A4 addiu $sp, -0x20 .text:004006A8 li $gp, 0x418930 .text:004006AC sw $ra, 0x20+var_4($sp) .text:004006B0 sw $s0, 0x20+var_8($sp) .text:004006B4 sw $gp, 0x20+var_10($sp) .text:004006B8 la $t9, puts .text:004006BC lui $a0, 0x40 .text:004006C0 jalr $t9 ; puts .text:004006C4 la $a0, aEnterX # "Enter X:" .text:004006C8 lw $gp, 0x20+var_10($sp) ; prepare high part of x address: .text:004006CC lui $s0, 0x41 .text:004006D0 la $t9, __isoc99_scanf .text:004006D4 lui $a0, 0x40 ; add low part of x address: .text:004006D8 addiu $a1, $s0, (x - 0x410000) ; now address of x is in $a1. .text:004006DC jalr $t9 ; __isoc99_scanf .text:004006E0 la $a0, aD # "%d" .text:004006E4 lw $gp, 0x20+var_10($sp) ; get a word from memory: .text:004006E8 lw $a1, x ; value of x is now in $a1. .text:004006EC la $t9, printf .text:004006F0 lui $a0, 0x40 .text:004006F4 jalr $t9 ; printf .text:004006F8 la $a0, aYouEnteredD___ # "You entered %d...n" .text:004006FC lw $ra, 0x20+var_4($sp) .text:00400700 move $v0, $zero 72
  • 97. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING .text:00400704 lw $s0, 0x20+var_8($sp) .text:00400708 jr $ra .text:0040070C addiu $sp, 0x20 ... .data:00410920 .globl x .data:00410920 x: .word 0xA Why not .sdata? I do not know, its possible that this depends on some GCC option. Nevertheless, now x is in .data, which is a general memory area, and we can take a look how to work with variables there. The variable’s address must be formed using a pair of instructions. In our case those are LUI (“Load Upper Immediate”) and ADDIU (“Add Immediate Unsigned Word”). Here is also the objdump listing for close inspection: Listing 7.11: Optimizing GCC 4.4.5 (objdump) 004006a0 <main>: 4006a0: 3c1c0042 lui gp,0x42 4006a4: 27bdffe0 addiu sp,sp,-32 4006a8: 279c8930 addiu gp,gp,-30416 4006ac: afbf001c sw ra,28(sp) 4006b0: afb00018 sw s0,24(sp) 4006b4: afbc0010 sw gp,16(sp) 4006b8: 8f998034 lw t9,-32716(gp) 4006bc: 3c040040 lui a0,0x40 4006c0: 0320f809 jalr t9 4006c4: 248408d0 addiu a0,a0,2256 4006c8: 8fbc0010 lw gp,16(sp) ; prepare high part of x address: 4006cc: 3c100041 lui s0,0x41 4006d0: 8f998038 lw t9,-32712(gp) 4006d4: 3c040040 lui a0,0x40 ; add low part of x address: 4006d8: 26050920 addiu a1,s0,2336 ; now address of x is in $a1. 4006dc: 0320f809 jalr t9 4006e0: 248408dc addiu a0,a0,2268 4006e4: 8fbc0010 lw gp,16(sp) ; high part of x address is still in $s0. ; add low part to it and load a word from memory: 4006e8: 8e050920 lw a1,2336(s0) ; value of x is now in $a1. 4006ec: 8f99803c lw t9,-32708(gp) 4006f0: 3c040040 lui a0,0x40 4006f4: 0320f809 jalr t9 4006f8: 248408e0 addiu a0,a0,2272 4006fc: 8fbf001c lw ra,28(sp) 400700: 00001021 move v0,zero 400704: 8fb00018 lw s0,24(sp) 400708: 03e00008 jr ra 40070c: 27bd0020 addiu sp,sp,32 We see that the address is formed using LUI and ADDIU, but the high part of address is still in the $S0 register, and it is possible to encode the offset in a LW (“Load Word”) instruction, so one single LW is enough to load a value from the variable and pass it to printf(). Registers holding temporary data are prefixed with T-, but here we also see some prefixed with S-, the contents of which is need to be preserved before use in other functions (i.e., “saved”). That is why the value of $S0 was set at address 0x4006cc and was used again at address 0x4006e8, after the scanf() call. The scanf() function does not change its value. 7.3 scanf() result checking As I noted before, it is slightly old-fashioned to use scanf() today. But if we have to, we need to at least check if scanf() finishes correctly without an error. #include <stdio.h> int main() { 73
  • 98. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING int x; printf ("Enter X:n"); if (scanf ("%d", &x)==1) printf ("You entered %d...n", x); else printf ("What you entered? Huh?n"); return 0; }; By standard, the scanf()4 function returns the number of fields it has successfully read. In our case, if everything goes fine and the user enters a number scanf() returns 1, or in case of error (or EOF5 ) - 0. I have added some C code to check the scanf() return value and print error message in case of an error. This works as expected: C:...>ex3.exe Enter X: 123 You entered 123... C:...>ex3.exe Enter X: ouch What you entered? Huh? 7.3.1 MSVC: x86 Here is what we get in the assembly output (MSVC 2010): lea eax, DWORD PTR _x$[ebp] push eax push OFFSET $SG3833 ; '%d', 00H call _scanf add esp, 8 cmp eax, 1 jne SHORT $LN2@main mov ecx, DWORD PTR _x$[ebp] push ecx push OFFSET $SG3834 ; 'You entered %d...', 0aH, 00H call _printf add esp, 8 jmp SHORT $LN1@main $LN2@main: push OFFSET $SG3836 ; 'What you entered? Huh?', 0aH, 00H call _printf add esp, 4 $LN1@main: xor eax, eax The Caller function (main()) needs the callee function (scanf()) result, so the callee returns it in the EAX register. We check it with the help of the instruction CMP EAX, 1 (CoMPare). In other words, we compare the value in the EAX register with 1. A JNE conditional jump follows the CMP instruction. JNE stands for Jump if Not Equal. So, if the value in the EAX register is not equal to 1, the CPU will pass the execution to the address mentioned in the JNE operand, in our case $LN2@main. Passing the control to this address results in the CPU executing printf() with the argument ``What you entered? Huh?''. But if everything is fine, the conditional jump is not be be taken, and another printf() call is to be executed, with two arguments: 'You entered %d...' and the value of x. Since in this case the second printf() has not to be executed, there is a JMP preceding it (unconditional jump). It passes the control to the point after the second printf() and just before the XOR EAX, EAX instruction, which implements return 0. So, it could be said that comparing a value with another is usually implemented by CMP/Jcc instruction pair, where cc is condition code. CMP compares two values and sets processor flags6 . Jcc checks those flags and decides to either pass the control to the specified address or not. 4scanf, wscanf: MSDN 5End of file 6x86 flags, see also: wikipedia. 74
  • 99. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING This could sound paradoxical, but the CMP instruction is in fact SUB (subtract). All arithmetic instructions set processor flags, not just CMP. If we compare 1 and 1, 1 − 1 is 0 so the ZF flag would be set (meaning that the last result was 0). In no other circumstances ZF can be set, except when the operands are equal. JNE checks only the ZF flag and jumps only if it is not set. JNE is in fact a synonym for JNZ (Jump if Not Zero). Assembler translates both JNE and JNZ instructions into the same opcode. So, the CMP instruction can be replaced with a SUB instruction and almost everything will be fine, with the difference that SUB alters the value of the first operand. CMP is SUB without saving the result. 7.3.2 MSVC: x86: IDA It is time to run IDA and try to do something in it. By the way, for beginners it is good idea to use /MD option in MSVC, which means that all these standard functions are not be linked with the executable file, but are to be imported from the MSVCR*.DLL file instead. Thus it will be easier to see which standard function are used and where. While analysing code in IDA, it is very helpful to leave notes for oneself (and others). In instance, analysing this example, we see that JNZ is to be triggered in case of an error. So it is possible to move the cursor to the label, press “n” and rename it to “error”. Create another label—into “exit”. Here is my result: .text:00401000 _main proc near .text:00401000 .text:00401000 var_4 = dword ptr -4 .text:00401000 argc = dword ptr 8 .text:00401000 argv = dword ptr 0Ch .text:00401000 envp = dword ptr 10h .text:00401000 .text:00401000 push ebp .text:00401001 mov ebp, esp .text:00401003 push ecx .text:00401004 push offset Format ; "Enter X:n" .text:00401009 call ds:printf .text:0040100F add esp, 4 .text:00401012 lea eax, [ebp+var_4] .text:00401015 push eax .text:00401016 push offset aD ; "%d" .text:0040101B call ds:scanf .text:00401021 add esp, 8 .text:00401024 cmp eax, 1 .text:00401027 jnz short error .text:00401029 mov ecx, [ebp+var_4] .text:0040102C push ecx .text:0040102D push offset aYou ; "You entered %d...n" .text:00401032 call ds:printf .text:00401038 add esp, 8 .text:0040103B jmp short exit .text:0040103D .text:0040103D error: ; CODE XREF: _main+27 .text:0040103D push offset aWhat ; "What you entered? Huh?n" .text:00401042 call ds:printf .text:00401048 add esp, 4 .text:0040104B .text:0040104B exit: ; CODE XREF: _main+3B .text:0040104B xor eax, eax .text:0040104D mov esp, ebp .text:0040104F pop ebp .text:00401050 retn .text:00401050 _main endp Now it is slightly easier to understand the code. However, it is not a good idea to comment on every instruction. You could also hide(collapse) parts of a function in IDA. To do that mark the block, then press “–” on the numerical pad and enter the text to be displayed instead. I have hidden two blocks and given them names: .text:00401000 _text segment para public 'CODE' use32 .text:00401000 assume cs:_text .text:00401000 ;org 401000h .text:00401000 ; ask for X .text:00401012 ; get X .text:00401024 cmp eax, 1 .text:00401027 jnz short error .text:00401029 ; print result .text:0040103B jmp short exit 75
  • 100. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING .text:0040103D .text:0040103D error: ; CODE XREF: _main+27 .text:0040103D push offset aWhat ; "What you entered? Huh?n" .text:00401042 call ds:printf .text:00401048 add esp, 4 .text:0040104B .text:0040104B exit: ; CODE XREF: _main+3B .text:0040104B xor eax, eax .text:0040104D mov esp, ebp .text:0040104F pop ebp .text:00401050 retn .text:00401050 _main endp To expand previously collapsed parts of the code, use “+” on the numerical pad. 76
  • 101. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING By pressing “space”, we can see how IDA represents a function as a graph: Figure 7.7: Graph mode in IDA There are two arrows after each conditional jump: green and red. The green arrow points to the block which executes if the jump is triggered, and red if otherwise. 77
  • 102. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING It is possible to fold nodes in this mode and give them names as well (“group nodes”). I did it for 3 blocks: Figure 7.8: Graph mode in IDA with 3 nodes folded That is very useful. It could be said that a very important part of the reverse engineer’s job is to reduce the information he/she deals with. 78
  • 103. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING 7.3.3 MSVC: x86 + OllyDbg Let’s try to hack our program in OllyDbg, forcing it to think scanf() always works without error. When an address of a local variable is passed into scanf(), the variable initially contains some random garbage, in this case 0x6E494714: Figure 7.9: OllyDbg: passing variable address into scanf() 79
  • 104. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING While scanf() executes, in the console I enter something that is definitely not a number, like “asdasd”. scanf() finishes with 0 in EAX, which indicates that an error has occurred: Figure 7.10: OllyDbg: scanf() returning error We can also check the local variable in the stack and note that it has not changed. Indeed, what would scanf() write there? It simply did nothing except returning zero. Let’s try to “hack” our program. Right-click on EAX, Among the options there is “Set to 1”. This is what we need. We now have 1 in EAX, so the following check is to be executed as intended, and printf() will print the value of the variable in the stack. When we run the program (F9) we can see the following in the console window: Figure 7.11: console window Indeed, 1850296084 is a decimal representation of the number in the stack (0x6E494714)! 80
  • 105. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING 7.3.4 MSVC: x86 + Hiew This can also be used as a simple example of executable file patching. We may try to patch the executable so the program would always print the input, no matter what we enter. Assuming that the executable is compiled against external MSVCR*.DLL (i.e., with /MD option)7 , we see the main() function at the beginning of the .text section. Let’s open the executable in Hiew and find the beginning of the .text section (Enter, F8, F6, Enter, Enter). We can see this: Figure 7.12: Hiew: main() function Hiew finds ASCIIZ8 strings and displays them, as it does with the imported functions’ names. 7that’s what also called “dynamic linking” 8ASCII Zero (null-terminated ASCII string) 81
  • 106. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING Move the cursor to address .00401027 (where the JNZ instruction, we have to bypass, is located), press F3, and then type “9090”(, meaning two NOPs): Figure 7.13: Hiew: replacing JNZ with two NOPs Then press F9 (update). Now the executable is saved to the disk. It will behave as we wanted. Two NOPs are probably not the most æsthetic approach. Another way to patch this instruction is to write just 0 to the second opcode byte (jump offset), so that JNZ will always jump to the next instruction. We could also do the opposite: replace first byte with EB while not touching the second byte (jump offset). We would get an unconditional jump that is always triggered. In this case the error message would be printed every time, no matter the input. 7.3.5 MSVC: x64 Since we work here with int-typed variables, which are still 32-bit in x86-64, we see how the 32-bit part of the registers (prefixed with E-) are used here as well. While working with pointers, however, 64-bit register parts are used, prefixed with R-. Listing 7.12: MSVC 2012 x64 _DATA SEGMENT $SG2924 DB 'Enter X:', 0aH, 00H $SG2926 DB '%d', 00H $SG2927 DB 'You entered %d...', 0aH, 00H $SG2929 DB 'What you entered? Huh?', 0aH, 00H _DATA ENDS _TEXT SEGMENT x$ = 32 main PROC $LN5: sub rsp, 56 lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X:' 82
  • 107. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING call printf lea rdx, QWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG2926 ; '%d' call scanf cmp eax, 1 jne SHORT $LN2@main mov edx, DWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG2927 ; 'You entered %d...' call printf jmp SHORT $LN1@main $LN2@main: lea rcx, OFFSET FLAT:$SG2929 ; 'What you entered? Huh?' call printf $LN1@main: ; return 0 xor eax, eax add rsp, 56 ret 0 main ENDP _TEXT ENDS END 7.3.6 ARM ARM: Optimizing Keil 6/2013 (thumb mode) Listing 7.13: Optimizing Keil 6/2013 (thumb mode) var_8 = -8 PUSH {R3,LR} ADR R0, aEnterX ; "Enter X:n" BL __2printf MOV R1, SP ADR R0, aD ; "%d" BL __0scanf CMP R0, #1 BEQ loc_1E ADR R0, aWhatYouEntered ; "What you entered? Huh?n" BL __2printf loc_1A ; CODE XREF: main+26 MOVS R0, #0 POP {R3,PC} loc_1E ; CODE XREF: main+12 LDR R1, [SP,#8+var_8] ADR R0, aYouEnteredD___ ; "You entered %d...n" BL __2printf B loc_1A The new instructions here are CMP and BEQ9 . CMP is analogous to the x86 instruction with the same name, it subtracts one of the arguments from the other and updates the conditional flags if needed. BEQ jumps to another address if the operands were equal to each other, or, if the result of the last computation was 0, or if the Z flag is 1. It behaves as JZ in x86. Everything else is simple: the execution flow forks in two branches, then the branches converge at the point where 0 is written into the R0 as a function return value, and then the function ends. ARM64 Listing 7.14: Non-optimizing GCC 4.9.1 ARM64 1 .LC0: 2 .string "Enter X:" 3 .LC1: 9(PowerPC, ARM) Branch if Equal 83
  • 108. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING 4 .string "%d" 5 .LC2: 6 .string "You entered %d...n" 7 .LC3: 8 .string "What you entered? Huh?" 9 f6: 10 ; save FP and LR in stack frame: 11 stp x29, x30, [sp, -32]! 12 ; set stack frame (FP=SP) 13 add x29, sp, 0 14 ; load pointer to the "Enter X:" string: 15 adrp x0, .LC0 16 add x0, x0, :lo12:.LC0 17 bl puts 18 ; load pointer to the "%d" string: 19 adrp x0, .LC1 20 add x0, x0, :lo12:.LC1 21 ; calculate address of x variable in the local stack 22 add x1, x29, 28 23 bl __isoc99_scanf 24 ; scanf() returned result in W0. 25 ; check it: 26 cmp w0, 1 27 ; BNE is Branch if Not Equal 28 ; so if W0<>0, jump to L2 will be occurred 29 bne .L2 30 ; at this moment W0=1, meaning no error 31 ; load x value from the local stack 32 ldr w1, [x29,28] 33 ; load pointer to the "You entered %d...n" string: 34 adrp x0, .LC2 35 add x0, x0, :lo12:.LC2 36 bl printf 37 ; skip the code, which print the "What you entered? Huh?" string: 38 b .L3 39 .L2: 40 ; load pointer to the "What you entered? Huh?" string: 41 adrp x0, .LC3 42 add x0, x0, :lo12:.LC3 43 bl puts 44 .L3: 45 ; return 0 46 mov w0, 0 47 ; restore FP and LR: 48 ldp x29, x30, [sp], 32 49 ret Code flow in this case forks with the use of CMP/BNE (Branch if Not Equal) instructions pair. 7.3.7 MIPS Listing 7.15: Optimizing GCC 4.4.5 (IDA) .text:004006A0 main: .text:004006A0 .text:004006A0 var_18 = -0x18 .text:004006A0 var_10 = -0x10 .text:004006A0 var_4 = -4 .text:004006A0 .text:004006A0 lui $gp, 0x42 .text:004006A4 addiu $sp, -0x28 .text:004006A8 li $gp, 0x418960 .text:004006AC sw $ra, 0x28+var_4($sp) .text:004006B0 sw $gp, 0x28+var_18($sp) .text:004006B4 la $t9, puts .text:004006B8 lui $a0, 0x40 .text:004006BC jalr $t9 ; puts .text:004006C0 la $a0, aEnterX # "Enter X:" .text:004006C4 lw $gp, 0x28+var_18($sp) .text:004006C8 lui $a0, 0x40 84
  • 109. CHAPTER 7. SCANF() 7.3. SCANF() RESULT CHECKING .text:004006CC la $t9, __isoc99_scanf .text:004006D0 la $a0, aD # "%d" .text:004006D4 jalr $t9 ; __isoc99_scanf .text:004006D8 addiu $a1, $sp, 0x28+var_10 # branch delay slot .text:004006DC li $v1, 1 .text:004006E0 lw $gp, 0x28+var_18($sp) .text:004006E4 beq $v0, $v1, loc_40070C .text:004006E8 or $at, $zero # branch delay slot, NOP .text:004006EC la $t9, puts .text:004006F0 lui $a0, 0x40 .text:004006F4 jalr $t9 ; puts .text:004006F8 la $a0, aWhatYouEntered # "What you entered? Huh?" .text:004006FC lw $ra, 0x28+var_4($sp) .text:00400700 move $v0, $zero .text:00400704 jr $ra .text:00400708 addiu $sp, 0x28 .text:0040070C loc_40070C: .text:0040070C la $t9, printf .text:00400710 lw $a1, 0x28+var_10($sp) .text:00400714 lui $a0, 0x40 .text:00400718 jalr $t9 ; printf .text:0040071C la $a0, aYouEnteredD___ # "You entered %d...n" .text:00400720 lw $ra, 0x28+var_4($sp) .text:00400724 move $v0, $zero .text:00400728 jr $ra .text:0040072C addiu $sp, 0x28 scanf() returns the result of its work in register $V0. It is checked at address 0x004006E4 by comparing the values in $V0 with $V1 (1 was stored in $V1 earlier, at 0x004006DC). BEQ stands for “Branch Equal”. If the two values are equal (i.e., success), the execution jumps to address 0x0040070C. 7.3.8 Exercise As we can see, the JNE/JNZ instruction can be easily replaced by the JE/JZ and vice versa (or BNE by BEQ and vice versa). But then the basic blocks must also be swapped. Try to do this in some of the examples. 85
  • 110. CHAPTER 8. ACCESSING PASSED ARGUMENTS Chapter 8 Accessing passed arguments Now we figured out that the caller function is passing arguments to the callee via the stack. But how does the callee access them? Listing 8.1: simple example #include <stdio.h> int f (int a, int b, int c) { return a*b+c; }; int main() { printf ("%dn", f(1, 2, 3)); return 0; }; 8.1 x86 8.1.1 MSVC Here is what we get after compilation (MSVC 2010 Express): Listing 8.2: MSVC 2010 Express _TEXT SEGMENT _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] imul eax, DWORD PTR _b$[ebp] add eax, DWORD PTR _c$[ebp] pop ebp ret 0 _f ENDP _main PROC push ebp mov ebp, esp push 3 ; 3rd argument push 2 ; 2nd argument push 1 ; 1st argument call _f add esp, 12 push eax push OFFSET $SG2463 ; '%d', 0aH, 00H call _printf add esp, 8 ; return 0 86
  • 111. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.1. X86 xor eax, eax pop ebp ret 0 _main ENDP What we see is that the main() function pushes 3 numbers onto the stack and calls f(int,int,int). Argument access inside f() is organized with the help of macros like: _a$ = 8, in the same way as local variables, but with positive offsets (addressed with plus). So, we are addressing the outer side of the stack frame by adding the _a$ macro to the value in the EBP register. Then the value of a is stored into EAX. After IMUL instruction execution, the value in EAX is a product of the value in EAX and the content of _b. After that, ADD adds the value in _c to EAX. The value in EAX does not need to be moved: it is already where it must be. On returning to caller, it takes the EAX value and use it as an argument to printf(). 8.1.2 MSVC + OllyDbg Let’s illustrate this in OllyDbg. When we trace to the first instruction in f() that uses one of the arguments (first one), we see that EBP is pointing to the stack frame, which I marked with a red rectangle. The first element of the stack frame is the saved value of EBP, the second one is RA, the third is the first function argument, then the second and third ones. To access the first function argument, one needs to add exactly 8 (2 32-bit words) to EBP. OllyDbg is aware about this, so it has added comments to the stack elements like “RETURN from” and “Arg1 = …”, etc. N.B.: Function arguments are not members of the function’s stack frame, they are rather members of the stack frame of the caller function. Hence, OllyDbg marked “Arg” elements as members of another stack frame. Figure 8.1: OllyDbg: inside of f() function 8.1.3 GCC Let’s compile the same in GCC 4.4.1 and see the results in IDA: Listing 8.3: GCC 4.4.1 public f f proc near arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h push ebp mov ebp, esp mov eax, [ebp+arg_0] ; 1st argument imul eax, [ebp+arg_4] ; 2nd argument add eax, [ebp+arg_8] ; 3rd argument pop ebp retn f endp 87
  • 112. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64 public main main proc near var_10 = dword ptr -10h var_C = dword ptr -0Ch var_8 = dword ptr -8 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov [esp+10h+var_8], 3 ; 3rd argument mov [esp+10h+var_C], 2 ; 2nd argument mov [esp+10h+var_10], 1 ; 1st argument call f mov edx, offset aD ; "%dn" mov [esp+10h+var_C], eax mov [esp+10h+var_10], edx call _printf mov eax, 0 leave retn main endp The result is almost the same with some minor differences discussed earlier. The stack pointer is not set back after the two function calls(f and printf), because the penultimate LEAVE ( A.6.2 on page 933) instruction takes care of this at the end. 8.2 x64 The story is a bit different in x86-64, function arguments (first 4 or first 6 of them) are passed in registers i.e. the callee reads them from there instead of reading them from the stack. 8.2.1 MSVC Optimizing MSVC: Listing 8.4: Optimizing MSVC 2012 x64 $SG2997 DB '%d', 0aH, 00H main PROC sub rsp, 40 mov edx, 2 lea r8d, QWORD PTR [rdx+1] ; R8D=3 lea ecx, QWORD PTR [rdx-1] ; ECX=1 call f lea rcx, OFFSET FLAT:$SG2997 ; '%d' mov edx, eax call printf xor eax, eax add rsp, 40 ret 0 main ENDP f PROC ; ECX - 1st argument ; EDX - 2nd argument ; R8D - 3rd argument imul ecx, edx lea eax, DWORD PTR [r8+rcx] ret 0 f ENDP As we can see, the compact function f() takes all its arguments from the registers. The LEA instruction here is used for addition, apparently the compiler considered it faster than ADD. LEA is also used in the main() function to prepare the first and third f() arguments. The compiler must have decided that this would work faster than the usual way of loading values into a register — using MOV instruction. Let’s take a look at the non-optimizing MSVC output: 88
  • 113. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64 Listing 8.5: MSVC 2012 x64 f proc near ; shadow space: arg_0 = dword ptr 8 arg_8 = dword ptr 10h arg_10 = dword ptr 18h ; ECX - 1st argument ; EDX - 2nd argument ; R8D - 3rd argument mov [rsp+arg_10], r8d mov [rsp+arg_8], edx mov [rsp+arg_0], ecx mov eax, [rsp+arg_0] imul eax, [rsp+arg_8] add eax, [rsp+arg_10] retn f endp main proc near sub rsp, 28h mov r8d, 3 ; 3rd argument mov edx, 2 ; 2nd argument mov ecx, 1 ; 1st argument call f mov edx, eax lea rcx, $SG2931 ; "%dn" call printf ; return 0 xor eax, eax add rsp, 28h retn main endp It looks somewhat puzzling because all 3 arguments from the registers are saved to the stack for some reason. This is called “shadow space” 1 : every Win64 may (but is not required to) save all 4 register values there. This is done for two reasons: 1) it is too lavish to allocate a whole register (or even 4 registers) for an input argument, so it will be accessed via stack; 2) the debugger is always aware where to find the function arguments at a break 2 . So, some large functions can save their input arguments in the “shadows space” if they need to use them during execution, but some small functions (like ours) may not do this. It is a caller responsibility to allocate “shadow space” in the stack. 8.2.2 GCC Optimizing GCC generates more or less understandable code: Listing 8.6: Optimizing GCC 4.4.6 x64 f: ; EDI - 1st argument ; ESI - 2nd argument ; EDX - 3rd argument imul esi, edi lea eax, [rdx+rsi] ret main: sub rsp, 8 mov edx, 3 mov esi, 2 mov edi, 1 call f mov edi, OFFSET FLAT:.LC0 ; "%dn" mov esi, eax xor eax, eax ; number of vector registers passed 1MSDN 2MSDN 89
  • 114. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.2. X64 call printf xor eax, eax add rsp, 8 ret Non-optimizing GCC: Listing 8.7: GCC 4.4.6 x64 f: ; EDI - 1st argument ; ESI - 2nd argument ; EDX - 3rd argument push rbp mov rbp, rsp mov DWORD PTR [rbp-4], edi mov DWORD PTR [rbp-8], esi mov DWORD PTR [rbp-12], edx mov eax, DWORD PTR [rbp-4] imul eax, DWORD PTR [rbp-8] add eax, DWORD PTR [rbp-12] leave ret main: push rbp mov rbp, rsp mov edx, 3 mov esi, 2 mov edi, 1 call f mov edx, eax mov eax, OFFSET FLAT:.LC0 ; "%dn" mov esi, edx mov rdi, rax mov eax, 0 ; number of vector registers passed call printf mov eax, 0 leave ret There are no “shadow space” requirements in System V *NIX[Mit13], but the callee may need to save its arguments somewhere in case of registers shortage. 8.2.3 GCC: uint64_t instead of int Our example works with 32-bit int, that is why 32-bit register parts are used (prefixed by E-). It can be altered slightly in order to use 64-bit values: #include <stdio.h> #include <stdint.h> uint64_t f (uint64_t a, uint64_t b, uint64_t c) { return a*b+c; }; int main() { printf ("%lldn", f(0x1122334455667788, 0x1111111122222222, 0x3333333344444444)); return 0; }; Listing 8.8: Optimizing GCC 4.4.6 x64 f proc near imul rsi, rdi lea rax, [rdx+rsi] retn f endp 90
  • 115. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.3. ARM main proc near sub rsp, 8 mov rdx, 3333333344444444h ; 3rd argument mov rsi, 1111111122222222h ; 2nd argument mov rdi, 1122334455667788h ; 1st argument call f mov edi, offset format ; "%lldn" mov rsi, rax xor eax, eax ; number of vector registers passed call _printf xor eax, eax add rsp, 8 retn main endp The code is the same, but this time the full size registers (prefixed by R-) are used. 8.3 ARM 8.3.1 Non-optimizing Keil 6/2013 (ARM mode) .text:000000A4 00 30 A0 E1 MOV R3, R0 .text:000000A8 93 21 20 E0 MLA R0, R3, R1, R2 .text:000000AC 1E FF 2F E1 BX LR ... .text:000000B0 main .text:000000B0 10 40 2D E9 STMFD SP!, {R4,LR} .text:000000B4 03 20 A0 E3 MOV R2, #3 .text:000000B8 02 10 A0 E3 MOV R1, #2 .text:000000BC 01 00 A0 E3 MOV R0, #1 .text:000000C0 F7 FF FF EB BL f .text:000000C4 00 40 A0 E1 MOV R4, R0 .text:000000C8 04 10 A0 E1 MOV R1, R4 .text:000000CC 5A 0F 8F E2 ADR R0, aD_0 ; "%dn" .text:000000D0 E3 18 00 EB BL __2printf .text:000000D4 00 00 A0 E3 MOV R0, #0 .text:000000D8 10 80 BD E8 LDMFD SP!, {R4,PC} The main() function simply calls two other functions, with three values passed to the first one —(f()). As I mentioned before, in ARM the first 4 values are usually passed in the first 4 registers (R0-R3). The f() function, as it seems, uses the first 3 registers (R0-R2) as arguments. The MLA (Multiply Accumulate) instruction multiplies its first two operands (R3 and R1), adds the third operand (R2) to the product and stores the result into the zeroth register (R0), via which, by standard, functions return values. Multiplication and addition at once3 (Fused multiply–add) is a very useful operation. By the way, there was no such instruction in x86 before FMA-instructions appeared in SIMD 4 . The very first MOV R3, R0, instruction is, apparently, redundant (a single MLA instruction could be used here instead), the compiler has not optimized it, since this is non-optimizing compilation. The BX instruction returns the control to the address stored in the LR register and, if necessary, switches the processor mode from thumb to ARM or vice versa. This can be necessary since, as we can see, function f() is not aware from what kind of code it may be called, ARM or thumb. Thus, if it gets called from thumb code, BX is not only returns control to the calling function, but also switches the processor mode to thumb. Or not switch, if the function was called from ARM code [ARM12, A2.3.2]. 8.3.2 Optimizing Keil 6/2013 (ARM mode) .text:00000098 f .text:00000098 91 20 20 E0 MLA R0, R1, R0, R2 .text:0000009C 1E FF 2F E1 BX LR And here is the f() function compiled by the Keil compiler in full optimization mode (-O3). The MOV instruction was optimized out (or reduced) and now MLA uses all input registers and also places the result right into R0, exactly where the calling function will read and use it. 3wikipedia: Multiply–accumulate operation 4wikipedia 91
  • 116. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.3. ARM 8.3.3 Optimizing Keil 6/2013 (thumb mode) .text:0000005E 48 43 MULS R0, R1 .text:00000060 80 18 ADDS R0, R0, R2 .text:00000062 70 47 BX LR The MLA instruction is not available in thumb mode, so the compiler generates the code doing these two operations (multiplication and addition) separately. First the MULS instruction multiplies R0 by R1, leaving the result in register R1. The second instruction (ADDS) adds the result and R2 leaving the result in register R0. 8.3.4 ARM64 Optimizing GCC (Linaro) 4.9 Everything here is simple. MADD is just an instruction doing fused multiply/add (similar to the MLA we already saw). All 3 arguments are passed in the 32-bit parts of X-registers. Indeed, the argument types are 32-bit int’s. The result is returned in W0. Listing 8.9: Optimizing GCC (Linaro) 4.9 f: madd w0, w0, w1, w2 ret main: ; save FP and LR to stack frame: stp x29, x30, [sp, -16]! mov w2, 3 mov w1, 2 add x29, sp, 0 mov w0, 1 bl f mov w1, w0 adrp x0, .LC7 add x0, x0, :lo12:.LC7 bl printf ; return 0 mov w0, 0 ; restore FP and LR ldp x29, x30, [sp], 16 ret .LC7: .string "%dn" I also extended all data types to 64-bit uint64_t and tested: #include <stdio.h> #include <stdint.h> uint64_t f (uint64_t a, uint64_t b, uint64_t c) { return a*b+c; }; int main() { printf ("%lldn", f(0x1122334455667788, 0x1111111122222222, 0x3333333344444444)); return 0; }; f: madd x0, x0, x1, x2 ret main: mov x1, 13396 adrp x0, .LC8 stp x29, x30, [sp, -16]! 92
  • 117. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.4. MIPS movk x1, 0x27d0, lsl 16 add x0, x0, :lo12:.LC8 movk x1, 0x122, lsl 32 add x29, sp, 0 movk x1, 0x58be, lsl 48 bl printf mov w0, 0 ldp x29, x30, [sp], 16 ret .LC8: .string "%lldn" The f() function is the same, only the whole 64-bit X-registers are now used. Long 64-bit values are loaded into the registers by parts, I have described it also here: 28.3.1 on page 445. Non-optimizing GCC (Linaro) 4.9 The non-optimizing compiler is more redundant: f: sub sp, sp, #16 str w0, [sp,12] str w1, [sp,8] str w2, [sp,4] ldr w1, [sp,12] ldr w0, [sp,8] mul w1, w1, w0 ldr w0, [sp,4] add w0, w1, w0 add sp, sp, 16 ret The code saves its input arguments in the local stack, in case someone (or something) in this function needs using the W0...W2 registers. This prevents overwriting the original function arguments, which may be needed again in the future. This is called Register Save Area. [ARM13c] The callee, however, is not obliged to save them. This is somewhat similar to “Shadow Space”: 8.2.1 on page 89. Why did the optimizing GCC 4.9 drop this argument saving code? Because it did some additional optimizing work and concluded that the function arguments will not be needed in the future and also that the registers W0...W2 will not be used. We also see a MUL/ADD instruction pair instead of single a MADD. 8.4 MIPS Listing 8.10: Optimizing GCC 4.4.5 .text:00000000 f: ; $a0=a ; $a1=b ; $a2=c .text:00000000 mult $a1, $a0 .text:00000004 mflo $v0 .text:00000008 jr $ra .text:0000000C addu $v0, $a2, $v0 ; branch delay slot ; result in $v0 upon return .text:00000010 main: .text:00000010 .text:00000010 var_10 = -0x10 .text:00000010 var_4 = -4 .text:00000010 .text:00000010 lui $gp, (__gnu_local_gp >> 16) .text:00000014 addiu $sp, -0x20 .text:00000018 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000001C sw $ra, 0x20+var_4($sp) .text:00000020 sw $gp, 0x20+var_10($sp) ; set c: .text:00000024 li $a2, 3 93
  • 118. CHAPTER 8. ACCESSING PASSED ARGUMENTS 8.4. MIPS ; set a: .text:00000028 li $a0, 1 .text:0000002C jal f ; set b: .text:00000030 li $a1, 2 ; branch delay slot ; result in $v0 now .text:00000034 lw $gp, 0x20+var_10($sp) .text:00000038 lui $a0, ($LC0 >> 16) .text:0000003C lw $t9, (printf & 0xFFFF)($gp) .text:00000040 la $a0, ($LC0 & 0xFFFF) .text:00000044 jalr $t9 ; take result of f() function and pass it as a second argument to printf(): .text:00000048 move $a1, $v0 ; branch delay slot .text:0000004C lw $ra, 0x20+var_4($sp) .text:00000050 move $v0, $zero .text:00000054 jr $ra .text:00000058 addiu $sp, 0x20 ; branch delay slot The first four function arguments are passed in four registers prefixed by A-. There are two special registers in MIPS: HI and LO which are filled with the 64-bit result of the multiplication during the execution of the MULT instruction. These registers are accessible only by using the MFLO and MFHI instructions. MFLO here takes the low-part of the multiplication result and stores it into $V0. So the high 32-bit part of the multiplication result is dropped (the HI register content is not used). Indeed: we work with 32-bit int data types here. Finally, ADDU (“Add Unsigned”) adds the value of the third argument to the result. There are two different addition instructions in MIPS: ADD and ADDU. The difference between them is not related to signedness, but to exceptions. ADD can raise an exception on overflow, which is sometimes useful5 and supported in Ada PL, for instance. ADDU does not raise exceptions on overflow. Since C/C++ does not support this, in our example we see ADDU instead of ADD. The 32-bit result is left in $V0. There is a new instruction for us in main(): JAL (“Jump and Link”). The difference between JAL and JALR is that a relative offset is encoded in the first instruction, while JALR jumps to the absolute address stored in a register (“Jump and Link Register”). Both f() and main() functions are located in the same object file, so the relative address of f() is known and fixed. 5http://go.yurichev.com/17326 94
  • 119. CHAPTER 9. MORE ABOUT RESULTS RETURNING Chapter 9 More about results returning In x86, the result of function execution is usually returned 1 in the EAX register. If it is byte type or a character (char), then the lowest part of register EAX (AL) is used. If a function returns a float number, the FPU register ST(0) is used instead. In ARM, the result is usually returned in the R0 register. 9.1 Attempt to use the result of a function returning void So, what if the main() function return value was declared of type void and not int? The so-called startup-code is calling main() roughly as follows: push envp push argv push argc call main push eax call exit In other words: exit(main(argc,argv,envp)); If you declare main() as void, nothing is to be returned explicitly (using the return statement), then something random, that was stored in the EAX register at the end of main() becomes the sole argument of the exit() function. Most likely, there will be a random value, left from your function execution, so the exit code of program is pseudorandom. I can illustrate this fact. Please note that here the main() function has a void return type: #include <stdio.h> void main() { printf ("Hello, world!n"); }; Let’s compile it in Linux. GCC 4.8.1 replaced printf() with puts() (we have seen this before: 3.4.3 on page 14) , but that’s OK, since puts() returns the number of characters printed out, just like printf(). Please notice that EAX is not zeroed before main()’s end. This implies that the value of EAX at the end of main() contains what puts() has left there. Listing 9.1: GCC 4.8.1 .LC0: .string "Hello, world!" main: push ebp mov ebp, esp and esp, -16 sub esp, 16 mov DWORD PTR [esp], OFFSET FLAT:.LC0 call puts leave ret 1See also: MSDN: Return Values (C++): MSDN 95
  • 120. CHAPTER 9. MORE ABOUT RESULTS RETURNING 9.2. WHAT IF WE DO NOT USE THE FUNCTION RESULT? Let’ s write a bash script that shows the exit status: Listing 9.2: tst.sh #!/bin/sh ./hello_world echo $? And run it: $ tst.sh Hello, world! 14 14 is the number of characters printed. 9.2 What if we do not use the function result? printf() returns the count of characters successfully output, but the result of this function is rarely used in practice. It is also possible to call a function whose essence is in returning a value, and not use it: int f() { // skip first 3 random values rand(); rand(); rand(); // and use 4th return rand(); }; The result of the rand() function is left in EAX, in all four cases. But in the first 3 cases, the value in EAX is just thrown away. 9.3 Returning a structure Let’s go back to the fact that the return value is left in the EAX register. That is why old C compilers cannot create functions capable of returning something that does not fit in one register (usually int), but if one needs it, one have to return information via pointers passed as function’s arguments. So, usually, if a function needs to return several values, it returns only one, and all the rest—via pointers. Now it has become possible to return, let’s say, an entire structure, but that is still not very popular. If a function has to return a large structure, the caller must allocate it and pass a pointer to it via the first argument, transparently for the programmer. That is almost the same as to pass a pointer in the first argument manually, but the compiler hides it. Small example: struct s { int a; int b; int c; }; struct s get_some_values (int a) { struct s rt; rt.a=a+1; rt.b=a+2; rt.c=a+3; return rt; }; …what we got (MSVC 2010 /Ox): $T3853 = 8 ; size = 4 _a$ = 12 ; size = 4 ?get_some_values@@YA?AUs@@H@Z PROC ; get_some_values mov ecx, DWORD PTR _a$[esp-4] 96
  • 121. CHAPTER 9. MORE ABOUT RESULTS RETURNING 9.3. RETURNING A STRUCTURE mov eax, DWORD PTR $T3853[esp-4] lea edx, DWORD PTR [ecx+1] mov DWORD PTR [eax], edx lea edx, DWORD PTR [ecx+2] add ecx, 3 mov DWORD PTR [eax+4], edx mov DWORD PTR [eax+8], ecx ret 0 ?get_some_values@@YA?AUs@@H@Z ENDP ; get_some_values The macro name for internal passing of pointer to a structure her is $T3853. This example can be rewritten using the C99 language extensions: struct s { int a; int b; int c; }; struct s get_some_values (int a) { return (struct s){.a=a+1, .b=a+2, .c=a+3}; }; Listing 9.3: GCC 4.8.1 _get_some_values proc near ptr_to_struct = dword ptr 4 a = dword ptr 8 mov edx, [esp+a] mov eax, [esp+ptr_to_struct] lea ecx, [edx+1] mov [eax], ecx lea ecx, [edx+2] add edx, 3 mov [eax+4], ecx mov [eax+8], edx retn _get_some_values endp As we see, the function is just filling the structure’s fields allocated by the caller function, as if a pointer to the structure was passed. So there are no performance drawbacks. 97
  • 122. CHAPTER 10. POINTERS Chapter 10 Pointers Pointers are often used to return values from functions (recall scanf() case ( 7 on page 56)). For example, when a function needs to return two values. 10.1 Global variables example #include <stdio.h> void f1 (int x, int y, int *sum, int *product) { *sum=x+y; *product=x*y; }; int sum, product; void main() { f1(123, 456, &sum, &product); printf ("sum=%d, product=%dn", sum, product); }; This compiles to: Listing 10.1: Optimizing MSVC 2010 (/Ob0) COMM _product:DWORD COMM _sum:DWORD $SG2803 DB 'sum=%d, product=%d', 0aH, 00H _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 _sum$ = 16 ; size = 4 _product$ = 20 ; size = 4 _f1 PROC mov ecx, DWORD PTR _y$[esp-4] mov eax, DWORD PTR _x$[esp-4] lea edx, DWORD PTR [eax+ecx] imul eax, ecx mov ecx, DWORD PTR _product$[esp-4] push esi mov esi, DWORD PTR _sum$[esp] mov DWORD PTR [esi], edx mov DWORD PTR [ecx], eax pop esi ret 0 _f1 ENDP _main PROC push OFFSET _product push OFFSET _sum push 456 ; 000001c8H push 123 ; 0000007bH call _f1 98
  • 123. CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE mov eax, DWORD PTR _product mov ecx, DWORD PTR _sum push eax push ecx push OFFSET $SG2803 call DWORD PTR __imp__printf add esp, 28 ; 0000001cH xor eax, eax ret 0 _main ENDP 99
  • 124. CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE Let’s see this in OllyDbg: Figure 10.1: OllyDbg: global variables addresses are passed to f1() First, global variables’ addresses are passed to f1(). We can click “Follow in dump” on the stack element, and we can see the place in the data segment allocated for the two variables. 100
  • 125. CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE These variables are zeroed, because non-initialized data (from BSS) is cleared before the execution begins: [ISO07, 6.7.8p10]. They reside in the data segment, we can verify this by pressing Alt-M and reviewing the memory map: Figure 10.2: OllyDbg: memory map 101
  • 126. CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE Let’s trace (F7) to the start of f1(): Figure 10.3: OllyDbg: f1() starts Two values are visible in the stack 456 (0x1C8) and 123 (0x7B), and also the addresses of the two global variables. 102
  • 127. CHAPTER 10. POINTERS 10.1. GLOBAL VARIABLES EXAMPLE Let’s trace until the end of f1(). In the left bottom window we see how the results of the calculation appear in the global variables: Figure 10.4: OllyDbg: f1() execution completed 103
  • 128. CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE Now the global variables’ values are loaded into registers ready for passing to printf() (via the stack): Figure 10.5: OllyDbg: global variables’ addresses are passed into printf() 10.2 Local variables example Let’s rework our example slightly: Listing 10.2: now the sum and product variables are local void main() { int sum, product; // now variables are local in this function f1(123, 456, &sum, &product); printf ("sum=%d, product=%dn", sum, product); }; f1() code will not change. Only the code of main() will do: Listing 10.3: Optimizing MSVC 2010 (/Ob0) _product$ = -8 ; size = 4 _sum$ = -4 ; size = 4 _main PROC ; Line 10 sub esp, 8 ; Line 13 lea eax, DWORD PTR _product$[esp+8] push eax lea ecx, DWORD PTR _sum$[esp+12] push ecx push 456 ; 000001c8H push 123 ; 0000007bH call _f1 ; Line 14 mov edx, DWORD PTR _product$[esp+24] mov eax, DWORD PTR _sum$[esp+24] push edx push eax push OFFSET $SG2803 call DWORD PTR __imp__printf ; Line 15 xor eax, eax add esp, 36 ; 00000024H ret 0 104
  • 129. CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE Let’s look again with OllyDbg. The addresses of the local variables in the stack are 0x2EF854 and 0x2EF858. We see how these are pushed into the stack: Figure 10.6: OllyDbg: local variables’ addresses are pushed into the stack 105
  • 130. CHAPTER 10. POINTERS 10.2. LOCAL VARIABLES EXAMPLE f1() starts. So far there is only random garbage in the stack at 0x2EF854 and 0x2EF858: Figure 10.7: OllyDbg: f1() starting 106
  • 131. CHAPTER 10. POINTERS 10.3. CONCLUSION f1() completes: Figure 10.8: OllyDbg: f1() completes execution We now find 0xDB18 and 0x243 at addresses 0x2EF854 and 0x2EF858. These values are the f1() results. 10.3 Conclusion f1() could return pointers to any place in memory, located anywhere. This is in essence the usefulness of the pointers. By the way, C++ references work exactly the same way. Read more about them: ( 51.3 on page 556). 107
  • 132. CHAPTER 11. GOTO Chapter 11 GOTO The GOTO operator is considered harmful [Dij68], but nevertheless, it can be used reasonably [Knu74], [Yur13, p. 1.3.2]. Here is a very simple example: #include <stdio.h> int main() { printf ("beginn"); goto exit; printf ("skip me!n"); exit: printf ("endn"); }; Here is what we’ve get in MSVC 2012: Listing 11.1: MSVC 2012 $SG2934 DB 'begin', 0aH, 00H $SG2936 DB 'skip me!', 0aH, 00H $SG2937 DB 'end', 0aH, 00H _main PROC push ebp mov ebp, esp push OFFSET $SG2934 ; 'begin' call _printf add esp, 4 jmp SHORT $exit$3 push OFFSET $SG2936 ; 'skip me!' call _printf add esp, 4 $exit$3: push OFFSET $SG2937 ; 'end' call _printf add esp, 4 xor eax, eax pop ebp ret 0 _main ENDP The goto statement is just replaced by a JMP instruction, which has the same effect: unconditional jump to another place. The second printf() call can be executed only with human intervention, by using a debugger or patching. 108
  • 133. CHAPTER 11. GOTO This also could be a simple patching exercise. Let’s open the resulting executable in Hiew: Figure 11.1: Hiew 109
  • 134. CHAPTER 11. GOTO 11.1. DEAD CODE Place the cursor to address JMP (0x410), press F3 (edit), press zero twice, so the opcode becomes EB 00: Figure 11.2: Hiew The second byte of the JMP opcode is relative offset of jump, 0 implies the point right after the current instruction. So now JMP not skipping the second printf() call. Now press F9 (save) and exit. Now we run the executable and we see this: Figure 11.3: Result The same effect can be achieved by replacing the JMP instruction with 2 NOP instructions. NOP has an opcode of 0x90 and length of 1 byte, so we need 2 instructions as replacement. 11.1 Dead code The second printf() call is also called “dead code” in compiler terms. This mean, the code will never be executed. So when you compile this example with optimizations, the compiler removes “dead code”, leaving no trace of it: Listing 11.2: Optimizing MSVC 2012 $SG2981 DB 'begin', 0aH, 00H $SG2983 DB 'skip me!', 0aH, 00H $SG2984 DB 'end', 0aH, 00H _main PROC push OFFSET $SG2981 ; 'begin' call _printf push OFFSET $SG2984 ; 'end' $exit$4: call _printf add esp, 8 xor eax, eax ret 0 _main ENDP However, the compiler forgot to remove the “skip me!” string. 11.2 Exercise Try to achieve the same result using your favorite compiler and debugger. 110
  • 135. CHAPTER 12. CONDITIONAL JUMPS Chapter 12 Conditional jumps 12.1 Simple example #include <stdio.h> void f_signed (int a, int b) { if (a>b) printf ("a>bn"); if (a==b) printf ("a==bn"); if (a<b) printf ("a<bn"); }; void f_unsigned (unsigned int a, unsigned int b) { if (a>b) printf ("a>bn"); if (a==b) printf ("a==bn"); if (a<b) printf ("a<bn"); }; int main() { f_signed(1, 2); f_unsigned(1, 2); return 0; }; 12.1.1 x86 x86 + MSVC What we have in the f_signed() function: Listing 12.1: Non-optimizing MSVC 2010 _a$ = 8 _b$ = 12 _f_signed PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cmp eax, DWORD PTR _b$[ebp] jle SHORT $LN3@f_signed push OFFSET $SG737 ; 'a>b' call _printf add esp, 4 $LN3@f_signed: mov ecx, DWORD PTR _a$[ebp] 111
  • 136. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE cmp ecx, DWORD PTR _b$[ebp] jne SHORT $LN2@f_signed push OFFSET $SG739 ; 'a==b' call _printf add esp, 4 $LN2@f_signed: mov edx, DWORD PTR _a$[ebp] cmp edx, DWORD PTR _b$[ebp] jge SHORT $LN4@f_signed push OFFSET $SG741 ; 'a<b' call _printf add esp, 4 $LN4@f_signed: pop ebp ret 0 _f_signed ENDP The first instruction, JLE, stands for Jump if Less or Equal. In other words, if the second operand is larger than first or equal, control is to be passed to address or label mentioned in instruction. If this condition does not trigger (second operand smaller than first), the control flow is not to be altered and the first printf() is to be called. The second check is JNE: Jump if Not Equal. Control flow will not change if the operands are equal. The third check is JGE: Jump if Greater or Equal—jump if the first operand is larger than the second or if they are equal. So, if all three conditional jumps are triggered, no printf() to be called whatsoever. But it is impossible without special intervention. The f_unsigned() function is the same, with the exception that the JBE and JAE instructions are used here instead of JLE and JGE, see below: Now let’s take a look at the f_unsigned() function Listing 12.2: GCC _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _f_unsigned PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cmp eax, DWORD PTR _b$[ebp] jbe SHORT $LN3@f_unsigned push OFFSET $SG2761 ; 'a>b' call _printf add esp, 4 $LN3@f_unsigned: mov ecx, DWORD PTR _a$[ebp] cmp ecx, DWORD PTR _b$[ebp] jne SHORT $LN2@f_unsigned push OFFSET $SG2763 ; 'a==b' call _printf add esp, 4 $LN2@f_unsigned: mov edx, DWORD PTR _a$[ebp] cmp edx, DWORD PTR _b$[ebp] jae SHORT $LN4@f_unsigned push OFFSET $SG2765 ; 'a<b' call _printf add esp, 4 $LN4@f_unsigned: pop ebp ret 0 _f_unsigned ENDP Almost the same, with these different instructions: JBE—Jump if Below or Equal and JAE—Jump if Above or Equal. The difference in these instructions (JA/JAE/JBE/JBE) JG/JGE/JL/JLE is that they work with unsigned numbers. See also the section about signed number representations ( 30 on page 451). So, where we see JG/JL instead of JA/JBE or vice-versa, we can almost be sure that the variables are signed or unsigned, respectively. Here is also the main() function, where there is nothing much new to us: Listing 12.3: main() _main PROC push ebp mov ebp, esp push 2 112
  • 137. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE push 1 call _f_signed add esp, 8 push 2 push 1 call _f_unsigned add esp, 8 xor eax, eax pop ebp ret 0 _main ENDP 113
  • 138. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE x86 + MSVC + OllyDbg We can see how flags are set by running this example in OllyDbg. Let’s begin with f_unsigned() , which works with unsigned numbers. CMP is executed thrice here, but for the same arguments, so the flags are the same each time. Result of the first comparison: Figure 12.1: OllyDbg: f_unsigned(): first conditional jump So, the flags are: C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0. They are named with one character for brevity in OllyDbg. OllyDbg gives a hint that the (JBE) jump is to be triggered now. Indeed, if we take a look into [Int13], we can read there that JBE is triggering if CF=1 or ZF=1. The condition is true here, so the jump is triggered. 114
  • 139. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE The next conditional jump: Figure 12.2: OllyDbg: f_unsigned(): second conditional jump OllyDbg gives a hint that JNZ is to be triggered now. Indeed, JNZ triggering if ZF=0 (zero flag). 115
  • 140. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE The third conditional jump, JNB: Figure 12.3: OllyDbg: f_unsigned(): third conditional jump In [Int13] we can see that JNB triggers if CF=0 (carry flag). It’s not true in our case, so the third printf() executes. 116
  • 141. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE Now we can try in OllyDbg the f_signed() function, which works with signed values. Flags are set in the same way: C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0. The first conditional jump JLE is to be triggered: Figure 12.4: OllyDbg: f_unsigned(): first conditional jump In [Int13] we find that this instruction is triggered if ZF=1 or SF≠OF. SF≠OF in our case, so the jump triggers. 117
  • 142. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE The second JNZ conditional jump triggering: if ZF=0 (zero flag): Figure 12.5: OllyDbg: f_unsigned(): second conditional jump 118
  • 143. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE The third conditional jump JGE will not trigger because it will only if SF=OF, and that is not true in our case: Figure 12.6: OllyDbg: f_unsigned(): third conditional jump 119
  • 144. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE x86 + MSVC + Hiew We can try to patch the executable file in a way that the f_unsigned() function will always print “a==b”, for any input values. Here is how it looks in Hiew: Figure 12.7: Hiew: f_unsigned() function Essentially, we’ve got three tasks: • force the first jump to always trigger; • force the second jump to never trigger; • force the third jump to always trigger. Thus we can point the code flow to the second printf(), and it always print “a==b”. Three instructions (or bytes) has to be patched: • The first jump will now be JMP, but the jump offset is still the same. • The second jump may be triggered sometimes, but in any case it will jump to the next instruction, because, we set the jump offset to 0. Jump offset is just gets added to the address for the next instruction in these instructions. So if the offset is 0, the jump slips to the next instruction. • The third jump we convert into JMP just as the first one, so it is always triggering. 120
  • 145. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE That’s what we do: Figure 12.8: Hiew: let’s modify the f_unsigned() function If we forget about any of these jumps, then several printf() calls may execute, but we want just one. Non-optimizing GCC Non-optimizing GCC 4.4.1 produces almost the same code, but with puts() ( 3.4.3 on page 14) instead of printf(). Optimizing GCC An observant reader may ask, why execute CMP several times, if the flags are same after each execution? Perhaps optimizing MSVC can’t do this, but optimizing GCC 4.8.1 can go deeper: Listing 12.4: GCC 4.8.1 f_signed() f_signed: mov eax, DWORD PTR [esp+8] cmp DWORD PTR [esp+4], eax jg .L6 je .L7 jge .L1 mov DWORD PTR [esp+4], OFFSET FLAT:.LC2 ; "a<b" jmp puts .L6: mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 ; "a>b" jmp puts .L1: rep ret .L7: mov DWORD PTR [esp+4], OFFSET FLAT:.LC1 ; "a==b" jmp puts 121
  • 146. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE We also see JMP puts here instead of CALL puts / RETN. This kind of trick will have explained later: 13.1.1 on page 140. This type of x86 code is somewhat rare. MSVC 2012, as it seems, can’t generate such code. On the other hand, assembly language programmers are fully aware of the fact that Jcc instructions can be stacked. So if you see it somewhere, there is a good probability that the code was hand-written. The f_unsigned() function is not that æsthetically short: Listing 12.5: GCC 4.8.1 f_unsigned() f_unsigned: push esi push ebx sub esp, 20 mov esi, DWORD PTR [esp+32] mov ebx, DWORD PTR [esp+36] cmp esi, ebx ja .L13 cmp esi, ebx ; this instruction could be removed je .L14 .L10: jb .L15 add esp, 20 pop ebx pop esi ret .L15: mov DWORD PTR [esp+32], OFFSET FLAT:.LC2 ; "a<b" add esp, 20 pop ebx pop esi jmp puts .L13: mov DWORD PTR [esp], OFFSET FLAT:.LC0 ; "a>b" call puts cmp esi, ebx jne .L10 .L14: mov DWORD PTR [esp+32], OFFSET FLAT:.LC1 ; "a==b" add esp, 20 pop ebx pop esi jmp puts But nevertheless, there are two CMP instructions instead of three. So optimization algorithms of GCC 4.8.1 are probably not perfect yet. 12.1.2 ARM 32-bit ARM Optimizing Keil 6/2013 (ARM mode) Listing 12.6: Optimizing Keil 6/2013 (ARM mode) .text:000000B8 EXPORT f_signed .text:000000B8 f_signed ; CODE XREF: main+C .text:000000B8 70 40 2D E9 STMFD SP!, {R4-R6,LR} .text:000000BC 01 40 A0 E1 MOV R4, R1 .text:000000C0 04 00 50 E1 CMP R0, R4 .text:000000C4 00 50 A0 E1 MOV R5, R0 .text:000000C8 1A 0E 8F C2 ADRGT R0, aAB ; "a>bn" .text:000000CC A1 18 00 CB BLGT __2printf .text:000000D0 04 00 55 E1 CMP R5, R4 .text:000000D4 67 0F 8F 02 ADREQ R0, aAB_0 ; "a==bn" .text:000000D8 9E 18 00 0B BLEQ __2printf .text:000000DC 04 00 55 E1 CMP R5, R4 .text:000000E0 70 80 BD A8 LDMGEFD SP!, {R4-R6,PC} .text:000000E4 70 40 BD E8 LDMFD SP!, {R4-R6,LR} .text:000000E8 19 0E 8F E2 ADR R0, aAB_1 ; "a<bn" .text:000000EC 99 18 00 EA B __2printf 122
  • 147. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE .text:000000EC ; End of function f_signed A lot of instructions in ARM mode can be executed only when specific flags are set. E.g. this is often used when comparing numbers. For instance, the ADD instruction is in fact ADDAL internally, where AL stands for Always, i.e., execute always. The predicates are encoded in 4 high bits of the 32-bit ARM instructions (condition field). The B instruction for unconditional jumping is in fact conditional and encoded just like any other conditional jump, but has AL in the condition field, and it implies execute ALways, ignoring flags. The ADRGT instructions works just like ADR but executes only in the case when the previous CMP instruction found one number greater than another, while comparing the two. (Greater Than). The next BLGT instruction behaves exactly as BL and is triggered only if the result of the comparison was the same (Greater Than). ADRGT writes a pointer to the string ``a>bn'' into R0 and BLGT calls printf(). Consequently, these instructions with suffix -GT are executes only in the case when the value in R0 (a is there) is bigger than the value in R4 (b is there). Then we see the ADREQ and BLEQ instructions. They behave just like ADR and BL, but are to be executed only if operands were equal to each other during the last comparison. Another CMP is located before them (because the printf() call may tamper the flag state). Then we see LDMGEFD, this instruction works just like LDMFD1 , but is triggered only when one value was greater or equal to the other (Greater or Equal). The sense of ``LDMGEFD SP!, {R4-R6,PC}'' instruction is that is like a function epilogue, but it is triggered only if a >= b, only then the function execution finishes. But if it is not true, i.e., a < b, then the control flow continues to the next ``LDMFD SP!, {R4-R6,LR}'' instruction, which is one more function epilogue. This instruction restores the state of registers R4-R6, but also LR instead of PC, thus, it does not returns from the function. The last two instructions call printf() with the string «a<bn» as a sole argument. We already examined an unconditional jump to the printf() function instead of function return, in «printf() with several arguments» section, here ( 6.2.1 on page 44). f_unsigned is likewise, but the ADRHI, BLHI, and LDMCSFD instructions are used there, these predicates (HI = Unsigned higher, CS = Carry Set (greater than or equal)) are analogous to those examined before, but for unsigned values. There is not much new in the main() function for us: Listing 12.7: main() .text:00000128 EXPORT main .text:00000128 main .text:00000128 10 40 2D E9 STMFD SP!, {R4,LR} .text:0000012C 02 10 A0 E3 MOV R1, #2 .text:00000130 01 00 A0 E3 MOV R0, #1 .text:00000134 DF FF FF EB BL f_signed .text:00000138 02 10 A0 E3 MOV R1, #2 .text:0000013C 01 00 A0 E3 MOV R0, #1 .text:00000140 EA FF FF EB BL f_unsigned .text:00000144 00 00 A0 E3 MOV R0, #0 .text:00000148 10 80 BD E8 LDMFD SP!, {R4,PC} .text:00000148 ; End of function main That’s how you can get rid of conditional jumps in ARM mode. Why it is so good? Read here: 33.1 on page 456. There is no such feature in x86, except the CMOVcc instruction, it is the same as MOV, but triggered only when specific flags are set, usually set by CMP. Optimizing Keil 6/2013 (thumb mode) Listing 12.8: Optimizing Keil 6/2013 (thumb mode) .text:00000072 f_signed ; CODE XREF: main+6 .text:00000072 70 B5 PUSH {R4-R6,LR} .text:00000074 0C 00 MOVS R4, R1 .text:00000076 05 00 MOVS R5, R0 .text:00000078 A0 42 CMP R0, R4 .text:0000007A 02 DD BLE loc_82 .text:0000007C A4 A0 ADR R0, aAB ; "a>bn" .text:0000007E 06 F0 B7 F8 BL __2printf .text:00000082 .text:00000082 loc_82 ; CODE XREF: f_signed+8 .text:00000082 A5 42 CMP R5, R4 .text:00000084 02 D1 BNE loc_8C .text:00000086 A4 A0 ADR R0, aAB_0 ; "a==bn" 1LDMFD 123
  • 148. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE .text:00000088 06 F0 B2 F8 BL __2printf .text:0000008C .text:0000008C loc_8C ; CODE XREF: f_signed+12 .text:0000008C A5 42 CMP R5, R4 .text:0000008E 02 DA BGE locret_96 .text:00000090 A3 A0 ADR R0, aAB_1 ; "a<bn" .text:00000092 06 F0 AD F8 BL __2printf .text:00000096 .text:00000096 locret_96 ; CODE XREF: f_signed+1C .text:00000096 70 BD POP {R4-R6,PC} .text:00000096 ; End of function f_signed Only B instructions in thumb mode may be supplemented by condition codes, so the thumb code looks more ordinary. BLE is a normal conditional jump Less than or Equal, BNE—Not Equal, BGE—Greater than or Equal. f_unsigned is likewise, but other instructions are used while dealing with unsigned values: BLS (Unsigned lower or same) and BCS (Carry Set (Greater than or equal)). ARM64: Optimizing GCC (Linaro) 4.9 Listing 12.9: f_signed() f_signed: ; W0=a, W1=b cmp w0, w1 bgt .L19 ; Branch if Greater Than (a>b) beq .L20 ; Branch if Equal (a==b) bge .L15 ; Branch if Greater than or Equal (a>=b) (impossible here) ; a<b adrp x0, .LC11 ; "a<b" add x0, x0, :lo12:.LC11 b puts .L19: adrp x0, .LC9 ; "a>b" add x0, x0, :lo12:.LC9 b puts .L15: ; impossible here ret .L20: adrp x0, .LC10 ; "a==b" add x0, x0, :lo12:.LC10 b puts Listing 12.10: f_unsigned() f_unsigned: stp x29, x30, [sp, -48]! ; W0=a, W1=b cmp w0, w1 add x29, sp, 0 str x19, [sp,16] mov w19, w0 bhi .L25 ; Branch if HIgher (a>b) cmp w19, w1 beq .L26 ; Branch if Equal (a==b) .L23: bcc .L27 ; Branch if Carry Clear (if less than) (a<b) ; function epilogue, impossible to be here ldr x19, [sp,16] ldp x29, x30, [sp], 48 ret .L27: ldr x19, [sp,16] adrp x0, .LC11 ; "a<b" ldp x29, x30, [sp], 48 add x0, x0, :lo12:.LC11 b puts .L25: adrp x0, .LC9 ; "a>b" str x1, [x29,40] 124
  • 149. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE add x0, x0, :lo12:.LC9 bl puts ldr x1, [x29,40] cmp w19, w1 bne .L23 ; Branch if Not Equal .L26: ldr x19, [sp,16] adrp x0, .LC10 ; "a==b" ldp x29, x30, [sp], 48 add x0, x0, :lo12:.LC10 b puts I have added the comments. What is also striking is that compiler is not aware that some conditions are not possible at all, so there is dead code at some places, which will never be executed. Exercise Try to optimize these functions manually for size, removing redundant instructions, without adding new ones. 12.1.3 MIPS One distinctive MIPS feature is the absence of flags. Apparently, it was done to simplify the analysis of data dependencies. There are instructions similar to SETcc in x86: SLT (“Set on Less Than”: signed version) and SLTU (unsigned version). These instructions sets destination register value to 1 if the condition is true or to 0 if otherwise. The destination register is then checked using BEQ (“Branch on Equal”) or BNE (“Branch on Not Equal”) and a jump may occur. So, this instruction pair has to be used in MIPS for comparison and branch. Let’s first start with the signed version of our function: Listing 12.11: Non-optimizing GCC 4.4.5 (IDA) .text:00000000 f_signed: # CODE XREF: main+18 .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 arg_0 = 0 .text:00000000 arg_4 = 4 .text:00000000 .text:00000000 addiu $sp, -0x20 .text:00000004 sw $ra, 0x20+var_4($sp) .text:00000008 sw $fp, 0x20+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x20+var_10($sp) ; store input values into local stack: .text:0000001C sw $a0, 0x20+arg_0($fp) .text:00000020 sw $a1, 0x20+arg_4($fp) ; reload them. .text:00000024 lw $v1, 0x20+arg_0($fp) .text:00000028 lw $v0, 0x20+arg_4($fp) ; $v0=b ; $v1=a .text:0000002C or $at, $zero ; NOP ; this is pseudoinstruction. in fact, "slt $v0,$v0,$v1" is there. ; so $v0 will be set to 1 if $v0<$v1 (b<a) or to 0 if otherwise: .text:00000030 slt $v0, $v1 ; jump to loc_5c, if condition is not true. ; this is pseudoinstruction. in fact, "beq $v0,$zero,loc_5c" is there: .text:00000034 beqz $v0, loc_5C ; print "a>b" and finish .text:00000038 or $at, $zero ; branch delay slot, NOP .text:0000003C lui $v0, (unk_230 >> 16) # "a>b" .text:00000040 addiu $a0, $v0, (unk_230 & 0xFFFF) # "a>b" .text:00000044 lw $v0, (puts & 0xFFFF)($gp) .text:00000048 or $at, $zero ; NOP .text:0000004C move $t9, $v0 .text:00000050 jalr $t9 .text:00000054 or $at, $zero ; branch delay slot, NOP 125
  • 150. CHAPTER 12. CONDITIONAL JUMPS 12.1. SIMPLE EXAMPLE .text:00000058 lw $gp, 0x20+var_10($fp) .text:0000005C .text:0000005C loc_5C: # CODE XREF: f_signed+34 .text:0000005C lw $v1, 0x20+arg_0($fp) .text:00000060 lw $v0, 0x20+arg_4($fp) .text:00000064 or $at, $zero ; NOP ; check if a==b, jump to loc_90 if its not true': .text:00000068 bne $v1, $v0, loc_90 .text:0000006C or $at, $zero ; branch delay slot, NOP ; condition is true, so print "a==b" and finish: .text:00000070 lui $v0, (aAB >> 16) # "a==b" .text:00000074 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b" .text:00000078 lw $v0, (puts & 0xFFFF)($gp) .text:0000007C or $at, $zero ; NOP .text:00000080 move $t9, $v0 .text:00000084 jalr $t9 .text:00000088 or $at, $zero ; branch delay slot, NOP .text:0000008C lw $gp, 0x20+var_10($fp) .text:00000090 .text:00000090 loc_90: # CODE XREF: f_signed+68 .text:00000090 lw $v1, 0x20+arg_0($fp) .text:00000094 lw $v0, 0x20+arg_4($fp) .text:00000098 or $at, $zero ; NOP ; check if $v1<$v0 (a<b), set $v0 to 1 if condition is true: .text:0000009C slt $v0, $v1, $v0 ; if condition is not true (i.e., $v0==0), jump to loc_c8: .text:000000A0 beqz $v0, loc_C8 .text:000000A4 or $at, $zero ; branch delay slot, NOP ; condition is true, print "a<b" and finish .text:000000A8 lui $v0, (aAB_0 >> 16) # "a<b" .text:000000AC addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b" .text:000000B0 lw $v0, (puts & 0xFFFF)($gp) .text:000000B4 or $at, $zero ; NOP .text:000000B8 move $t9, $v0 .text:000000BC jalr $t9 .text:000000C0 or $at, $zero ; branch delay slot, NOP .text:000000C4 lw $gp, 0x20+var_10($fp) .text:000000C8 ; all 3 conditions were false, so just finish: .text:000000C8 loc_C8: # CODE XREF: f_signed+A0 .text:000000C8 move $sp, $fp .text:000000CC lw $ra, 0x20+var_4($sp) .text:000000D0 lw $fp, 0x20+var_8($sp) .text:000000D4 addiu $sp, 0x20 .text:000000D8 jr $ra .text:000000DC or $at, $zero ; branch delay slot, NOP .text:000000DC # End of function f_signed “SLT REG0, REG0, REG1” is reduced by IDA to its shorter form: “SLT REG0, REG1”. We also see there BEQZ pseudoinstruction (“Branch if Equal to Zero”), which are in fact “BEQ REG, $ZERO, LABEL”. The unsigned version is just the same, but SLTU (unsigned version, hence “U” in name) is used instead of SLT: Listing 12.12: Non-optimizing GCC 4.4.5 (IDA) .text:000000E0 f_unsigned: # CODE XREF: main+28 .text:000000E0 .text:000000E0 var_10 = -0x10 .text:000000E0 var_8 = -8 .text:000000E0 var_4 = -4 .text:000000E0 arg_0 = 0 .text:000000E0 arg_4 = 4 .text:000000E0 .text:000000E0 addiu $sp, -0x20 .text:000000E4 sw $ra, 0x20+var_4($sp) .text:000000E8 sw $fp, 0x20+var_8($sp) .text:000000EC move $fp, $sp .text:000000F0 la $gp, __gnu_local_gp .text:000000F8 sw $gp, 0x20+var_10($sp) .text:000000FC sw $a0, 0x20+arg_0($fp) .text:00000100 sw $a1, 0x20+arg_4($fp) .text:00000104 lw $v1, 0x20+arg_0($fp) 126
  • 151. CHAPTER 12. CONDITIONAL JUMPS 12.2. CALCULATING ABSOLUTE VALUE .text:00000108 lw $v0, 0x20+arg_4($fp) .text:0000010C or $at, $zero .text:00000110 sltu $v0, $v1 .text:00000114 beqz $v0, loc_13C .text:00000118 or $at, $zero .text:0000011C lui $v0, (unk_230 >> 16) .text:00000120 addiu $a0, $v0, (unk_230 & 0xFFFF) .text:00000124 lw $v0, (puts & 0xFFFF)($gp) .text:00000128 or $at, $zero .text:0000012C move $t9, $v0 .text:00000130 jalr $t9 .text:00000134 or $at, $zero .text:00000138 lw $gp, 0x20+var_10($fp) .text:0000013C .text:0000013C loc_13C: # CODE XREF: f_unsigned+34 .text:0000013C lw $v1, 0x20+arg_0($fp) .text:00000140 lw $v0, 0x20+arg_4($fp) .text:00000144 or $at, $zero .text:00000148 bne $v1, $v0, loc_170 .text:0000014C or $at, $zero .text:00000150 lui $v0, (aAB >> 16) # "a==b" .text:00000154 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b" .text:00000158 lw $v0, (puts & 0xFFFF)($gp) .text:0000015C or $at, $zero .text:00000160 move $t9, $v0 .text:00000164 jalr $t9 .text:00000168 or $at, $zero .text:0000016C lw $gp, 0x20+var_10($fp) .text:00000170 .text:00000170 loc_170: # CODE XREF: f_unsigned+68 .text:00000170 lw $v1, 0x20+arg_0($fp) .text:00000174 lw $v0, 0x20+arg_4($fp) .text:00000178 or $at, $zero .text:0000017C sltu $v0, $v1, $v0 .text:00000180 beqz $v0, loc_1A8 .text:00000184 or $at, $zero .text:00000188 lui $v0, (aAB_0 >> 16) # "a<b" .text:0000018C addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b" .text:00000190 lw $v0, (puts & 0xFFFF)($gp) .text:00000194 or $at, $zero .text:00000198 move $t9, $v0 .text:0000019C jalr $t9 .text:000001A0 or $at, $zero .text:000001A4 lw $gp, 0x20+var_10($fp) .text:000001A8 .text:000001A8 loc_1A8: # CODE XREF: f_unsigned+A0 .text:000001A8 move $sp, $fp .text:000001AC lw $ra, 0x20+var_4($sp) .text:000001B0 lw $fp, 0x20+var_8($sp) .text:000001B4 addiu $sp, 0x20 .text:000001B8 jr $ra .text:000001BC or $at, $zero .text:000001BC # End of function f_unsigned 12.2 Calculating absolute value A simple function: int my_abs (int i) { if (i<0) return -i; else return i; }; 127
  • 152. CHAPTER 12. CONDITIONAL JUMPS 12.2. CALCULATING ABSOLUTE VALUE 12.2.1 Optimizing MSVC This is the usual way to generate it: Listing 12.13: Optimizing MSVC 2012 x64 i$ = 8 my_abs PROC ; ECX = input test ecx, ecx ; check for sign of input value ; skip NEG instruction if sign is positive jns SHORT $LN2@my_abs ; negate value neg ecx $LN2@my_abs: ; prepare result in EAX: mov eax, ecx ret 0 my_abs ENDP GCC 4.9 does mostly the same. 12.2.2 Optimizing Keil 6/2013: thumb mode Listing 12.14: Optimizing Keil 6/2013: thumb mode my_abs PROC CMP r0,#0 ; is input value equal to zero or greater than zero? ; skip RSBS instruction then BGE |L0.6| ; subtract input value from 0: RSBS r0,r0,#0 |L0.6| BX lr ENDP ARM lacks a negate instruction, so the Keil compiler uses the “Reverse Subtract” instruction, which just subtract with reversed operands. 12.2.3 Optimizing Keil 6/2013: ARM mode It’s possible to add condition codes to some instructions in ARM mode, so that’s what the Keil compiler do: Listing 12.15: Optimizing Keil 6/2013: ARM mode my_abs PROC CMP r0,#0 ; execute "Reverse Subtract" instruction only if input value is less than 0: RSBLT r0,r0,#0 BX lr ENDP Now there are no conditional jumps and this is good: 33.1 on page 456. 12.2.4 Non-optimizing GCC 4.9 (ARM64) ARM64 has the instruction NEG for negating: Listing 12.16: Optimizing GCC 4.9 (ARM64) my_abs: sub sp, sp, #16 str w0, [sp,12] ldr w0, [sp,12] ; compare input value with contents of WZR register ; (which always holds zero) cmp w0, wzr bge .L2 ldr w0, [sp,12] 128
  • 153. CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR neg w0, w0 b .L3 .L2: ldr w0, [sp,12] .L3: add sp, sp, 16 ret 12.2.5 MIPS Listing 12.17: Optimizing GCC 4.4.5 (IDA) my_abs: ; jump if $a0<0: bltz $a0, locret_10 ; just return input value ($a0) in $v0: move $v0, $a0 jr $ra or $at, $zero ; branch delay slot, NOP locret_10: ; negate input value and store it in $v0: jr $ra ; this is pseudoinstruction. in fact, this is "subu $v0,$zero,$a0" ($v0=0-$a0) negu $v0, $a0 Here we see a new instruction: BLTZ (“Branch if Less Than Zero”). There is also the NEGU pseudoinstruction, which just does subtraction from zero. The “U” suffix in both SUBU and NEGU implies that no exception to be raised in case of integer overflow. 12.2.6 Branchless version? There are also could be branchless version, which we are going to see later: 45 on page 512. 12.3 Conditional operator The conditional operator in C/C++ is: expression ? expression : expression Here is an example: const char* f (int a) { return a==10 ? "it is ten" : "it is not ten"; }; 12.3.1 x86 Old and non-optimizing compilers generate the code just as if an if/else statement was used: Listing 12.18: Non-optimizing MSVC 2008 $SG746 DB 'it is ten', 00H $SG747 DB 'it is not ten', 00H tv65 = -4 ; this will be used as a temporary variable _a$ = 8 _f PROC push ebp mov ebp, esp push ecx ; compare input value with 10 cmp DWORD PTR _a$[ebp], 10 ; jump to $LN3@f if not equal jne SHORT $LN3@f ; store pointer to the string into temporary variable: mov DWORD PTR tv65[ebp], OFFSET $SG746 ; 'it is ten' 129
  • 154. CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR ; jump to exit jmp SHORT $LN4@f $LN3@f: ; store pointer to the string into temporary variable: mov DWORD PTR tv65[ebp], OFFSET $SG747 ; 'it is not ten' $LN4@f: ; this is exit. copy pointer to the string from temporary variable to EAX. mov eax, DWORD PTR tv65[ebp] mov esp, ebp pop ebp ret 0 _f ENDP Listing 12.19: Optimizing MSVC 2008 $SG792 DB 'it is ten', 00H $SG793 DB 'it is not ten', 00H _a$ = 8 ; size = 4 _f PROC ; compare input value with 10 cmp DWORD PTR _a$[esp-4], 10 mov eax, OFFSET $SG792 ; 'it is ten' ; jump to $LN4@f if equal je SHORT $LN4@f mov eax, OFFSET $SG793 ; 'it is not ten' $LN4@f: ret 0 _f ENDP Newer compilers are more concise: Listing 12.20: Optimizing MSVC 2012 x64 $SG1355 DB 'it is ten', 00H $SG1356 DB 'it is not ten', 00H a$ = 8 f PROC ; load pointers to the both strings lea rdx, OFFSET FLAT:$SG1355 ; 'it is ten' lea rax, OFFSET FLAT:$SG1356 ; 'it is not ten' ; compare input value with 10 cmp ecx, 10 ; if equal, copy value from RDX ("it is ten") ; if not, do nothing. pointer to the string "it is not ten" is still in RAX as for now. cmove rax, rdx ret 0 f ENDP Optimizing GCC 4.8 for x86 also uses the CMOVcc instruction, while the non-optimizing GCC 4.8 uses a conditional jumps. 12.3.2 ARM Optimizing Keil for ARM mode also uses the conditional instructions ADRcc: Listing 12.21: Optimizing Keil 6/2013 (ARM mode) f PROC ; compare input value with 10 CMP r0,#0xa ; if comparison result is EQual, copy pointer to the "it is ten" string into R0 ADREQ r0,|L0.16| ; "it is ten" ; if comparison result is Not Equal, copy pointer to the "it is not ten" string into R0 ADRNE r0,|L0.28| ; "it is not ten" BX lr ENDP |L0.16| DCB "it is ten",0 |L0.28| DCB "it is not ten",0 130
  • 155. CHAPTER 12. CONDITIONAL JUMPS 12.3. CONDITIONAL OPERATOR Without manual intervention, the two instructions ADREQ and ADRNE cannot be executed in the same run. Optimizing Keil for Thumb mode needs to use conditional jump instructions, since there are no load instructions that support conditional flags: Listing 12.22: Optimizing Keil 6/2013 (thumb mode) f PROC ; compare input value with 10 CMP r0,#0xa ; jump to |L0.8| if EQual BEQ |L0.8| ADR r0,|L0.12| ; "it is not ten" BX lr |L0.8| ADR r0,|L0.28| ; "it is ten" BX lr ENDP |L0.12| DCB "it is not ten",0 |L0.28| DCB "it is ten",0 12.3.3 ARM64 Optimizing GCC (Linaro) 4.9 for ARM64 also uses conditional jumps: Listing 12.23: Optimizing GCC (Linaro) 4.9 f: cmp x0, 10 beq .L3 ; branch if equal adrp x0, .LC1 ; "it is ten" add x0, x0, :lo12:.LC1 ret .L3: adrp x0, .LC0 ; "it is not ten" add x0, x0, :lo12:.LC0 ret .LC0: .string "it is ten" .LC1: .string "it is not ten" That’s because ARM64 doesn’t have a simple load instruction with conditional flags, like ADRcc in 32-bit ARM mode or CMOVcc in x86 [ARM13a, p390, C5.5]. It has, however, “Conditional SELect” instruction (CSEL), but GCC 4.9 doesn’t seem to be smart enough to use it in such piece of code. 12.3.4 MIPS Unfortunately, GCC 4.4.5 for MIPS is not very smart, either: Listing 12.24: Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "it is not ten000" $LC1: .ascii "it is ten000" f: li $2,10 # 0xa ; compare $a0 and 10, jump if equal: beq $4,$2,$L2 nop ; branch delay slot ; leave address of "it is not ten" string in $v0 and return: lui $2,%hi($LC0) j $31 addiu $2,$2,%lo($LC0) $L2: 131
  • 156. CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES ; leave address of "it is ten" string in $v0 and return: lui $2,%hi($LC1) j $31 addiu $2,$2,%lo($LC1) 12.3.5 Let’s rewrite it in an if/else way const char* f (int a) { if (a==10) return "it is ten"; else return "it is not ten"; }; Interestingly, optimizing GCC 4.8 for x86 was also able to use CMOVcc in this case: Listing 12.25: Optimizing GCC 4.8 .LC0: .string "it is ten" .LC1: .string "it is not ten" f: .LFB0: ; compare input value with 10 cmp DWORD PTR [esp+4], 10 mov edx, OFFSET FLAT:.LC1 ; "it is not ten" mov eax, OFFSET FLAT:.LC0 ; "it is ten" ; if comparison result is Not Equal, copy EDX value to EAX ; if not, do nothing cmovne eax, edx ret Optimizing Keil in ARM mode generates code identical to listing.12.21. But the optimizing MSVC 2012 is not that good (yet). 12.3.6 Conclusion Why optimizing compilers try to get rid of conditional jumps? Read here about it: 33.1 on page 456. 12.3.7 Exercise Try rewriting the code in listing.12.23 by removing all conditional jump instructions and using the CSEL instruction. 12.4 Getting minimal and maximal values 12.4.1 32-bit int my_max(int a, int b) { if (a>b) return a; else return b; }; int my_min(int a, int b) { if (a<b) return a; else return b; }; 132
  • 157. CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES Listing 12.26: Non-optimizing MSVC 2013 _a$ = 8 _b$ = 12 _my_min PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] ; compare A and B: cmp eax, DWORD PTR _b$[ebp] ; jump, if A is greater or equal to B: jge SHORT $LN2@my_min ; reload A to EAX if otherwise and jump to exit mov eax, DWORD PTR _a$[ebp] jmp SHORT $LN3@my_min jmp SHORT $LN3@my_min ; this is redundant JMP $LN2@my_min: ; return B mov eax, DWORD PTR _b$[ebp] $LN3@my_min: pop ebp ret 0 _my_min ENDP _a$ = 8 _b$ = 12 _my_max PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] ; compare A and B: cmp eax, DWORD PTR _b$[ebp] ; jump if A is less or equal to B: jle SHORT $LN2@my_max ; reload A to EAX if otherwise and jump to exit mov eax, DWORD PTR _a$[ebp] jmp SHORT $LN3@my_max jmp SHORT $LN3@my_max ; this is redundant JMP $LN2@my_max: ; return B mov eax, DWORD PTR _b$[ebp] $LN3@my_max: pop ebp ret 0 _my_max ENDP These two functions differ only in the conditional jump instruction: JGE (“Jump if Greater or Equal”) is used in the first one and JLE (“Jump if Less or Equal”) in the second. There is one unneeded JMP instruction in each function, which MSVC probably left by mistake. Branchless ARM for Thumb mode reminds us of x86 code: Listing 12.27: Optimizing Keil 6/2013 (thumb mode) my_max PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; branch if A is greater then B: BGT |L0.6| ; otherwise (A<=B) return R1 (B): MOVS r0,r1 |L0.6| ; return BX lr ENDP my_min PROC 133
  • 158. CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; branch if A is less then B: BLT |L0.14| ; otherwise (A>=B) return R1 (B): MOVS r0,r1 |L0.14| ; return BX lr ENDP The functions differ in the branching instruction: BGT and BLT. It’s possible to use conditional suffixes in ARM mode, so the code is shorter. MOVcc is to be executed only if the condition is met: Listing 12.28: Optimizing Keil 6/2013 (ARM mode) my_max PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; return B instead of A by placing B in R0 ; this instruction will trigger only if A<=B (hence, LE - Less or Equal) ; if instruction is not triggered (in case of A>B), A is still in R0 register MOVLE r0,r1 BX lr ENDP my_min PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; return B instead of A by placing B in R0 ; this instruction will trigger only if A>=B (hence, GE - Greater or Equal) ; if instruction is not triggered (in case of A<B), A value is still in R0 register MOVGE r0,r1 BX lr ENDP Optimizing GCC 4.8.1 and optimizing MSVC 2013 can use CMOVcc instruction, which is analogous to MOVcc in ARM: Listing 12.29: Optimizing MSVC 2013 my_max: mov edx, DWORD PTR [esp+4] mov eax, DWORD PTR [esp+8] ; EDX=A ; EAX=B ; compare A and B: cmp edx, eax ; if A>=B, load A value into EAX ; the instruction idle if otherwise (if A<B) cmovge eax, edx ret my_min: mov edx, DWORD PTR [esp+4] mov eax, DWORD PTR [esp+8] ; EDX=A ; EAX=B ; compare A and B: cmp edx, eax ; if A<=B, load A value into EAX ; the instruction idle if otherwise (if A>B) cmovle eax, edx ret 134
  • 159. CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES 12.4.2 64-bit #include <stdint.h> int64_t my_max(int64_t a, int64_t b) { if (a>b) return a; else return b; }; int64_t my_min(int64_t a, int64_t b) { if (a<b) return a; else return b; }; There is some unneeded value shuffling, but the code is comprehensible: Listing 12.30: Non-optimizing GCC 4.9.1 ARM64 my_max: sub sp, sp, #16 str x0, [sp,8] str x1, [sp] ldr x1, [sp,8] ldr x0, [sp] cmp x1, x0 ble .L2 ldr x0, [sp,8] b .L3 .L2: ldr x0, [sp] .L3: add sp, sp, 16 ret my_min: sub sp, sp, #16 str x0, [sp,8] str x1, [sp] ldr x1, [sp,8] ldr x0, [sp] cmp x1, x0 bge .L5 ldr x0, [sp,8] b .L6 .L5: ldr x0, [sp] .L6: add sp, sp, 16 ret Branchless No need to load function arguments from the stack, as they are already in the registers: Listing 12.31: Optimizing GCC 4.9.1 x64 my_max: ; RDI=A ; RSI=B ; compare A and B: cmp rdi, rsi ; prepare B in RAX for return: mov rax, rsi ; if A>=B, put A (RDI) in RAX for return. 135
  • 160. CHAPTER 12. CONDITIONAL JUMPS 12.4. GETTING MINIMAL AND MAXIMAL VALUES ; this instruction is idle if otherwise (if A<B) cmovge rax, rdi ret my_min: ; RDI=A ; RSI=B ; compare A and B: cmp rdi, rsi ; prepare B in RAX for return: mov rax, rsi ; if A<=B, put A (RDI) in RAX for return. ; this instruction is idle if otherwise (if A>B) cmovle rax, rdi ret MSVC 2013 does almost the same. ARM64 has the CSEL instruction, which works just as MOVcc in ARM or CMOVcc in x86, just the name is different: “Con- ditional SELect”. Listing 12.32: Optimizing GCC 4.9.1 ARM64 my_max: ; X0=A ; X1=B ; compare A and B: cmp x0, x1 ; select X0 (A) to X0 if X0>=X1 or A>=B (Greater or Equal) ; select X1 (B) to X0 if A<B csel x0, x0, x1, ge ret my_min: ; X0=A ; X1=B ; compare A and B: cmp x0, x1 ; select X0 (A) to X0 if X0<=X1 or A<=B (Less or Equal) ; select X1 (B) to X0 if A>B csel x0, x0, x1, le ret 12.4.3 MIPS Unfortunately, GCC 4.4.5 for MIPS is not that good: Listing 12.33: Optimizing GCC 4.4.5 (IDA) my_max: ; set $v1 $a1<$a0: slt $v1, $a1, $a0 ; jump, if $a1<$a0: beqz $v1, locret_10 ; this is branch delay slot ; prepare $a1 in $v0 in case of branch triggered: move $v0, $a1 ; no branch triggered, prepare $a0 in $v0: move $v0, $a0 locret_10: jr $ra or $at, $zero ; branch delay slot, NOP ; the min() function is same, but input operands in SLT instruction are swapped: my_min: slt $v1, $a0, $a1 beqz $v1, locret_28 move $v0, $a1 move $v0, $a0 136
  • 161. CHAPTER 12. CONDITIONAL JUMPS 12.5. CONCLUSION locret_28: jr $ra or $at, $zero ; branch delay slot, NOP Do not forget about the branch delay slots: the first MOVE is executed before BEQZ, the second MOVE is executed only if the branch wasn’t taken. 12.5 Conclusion 12.5.1 x86 Here’s the rough skeleton of a conditional jump: Listing 12.34: x86 CMP register, register/value Jcc true ; cc=condition code false: ... some code to be executed if comparison result is false ... JMP exit true: ... some code to be executed if comparison result is true ... exit: 12.5.2 ARM Listing 12.35: ARM CMP register, register/value Bcc true ; cc=condition code false: ... some code to be executed if comparison result is false ... JMP exit true: ... some code to be executed if comparison result is true ... exit: 12.5.3 MIPS Listing 12.36: Check for zero BEQZ REG, label ... Listing 12.37: Check for less than zero: BLTZ REG, label ... Listing 12.38: Check for equal values BEQ REG1, REG2, label ... Listing 12.39: Check for non-equal values BNE REG1, REG2, label ... Listing 12.40: Check for less than, greater than (signed) SLT REG1, REG2, REG3 BEQ REG1, label ... 137
  • 162. CHAPTER 12. CONDITIONAL JUMPS 12.5. CONCLUSION Listing 12.41: Check for less than, greater than (unsigned) SLTU REG1, REG2, REG3 BEQ REG1, label ... 12.5.4 Branchless If the body of a condition statement is very short, the conditional move instruction can be used: MOVcc in ARM (in ARM mode), CSEL in ARM64, CMOVcc in x86. ARM It’s possible to use conditional suffixes in ARM mode for some instructions: Listing 12.42: ARM (ARM mode) CMP register, register/value instr1_cc ; some instruction will be executed if condition code is true instr2_cc ; some other instruction will be executed if other condition code is true ... etc ... Of course, there is no limit for the number of instructions with conditional code suffixes, as long as the CPU flags are not modified by any of them. Thumb mode has the IT instruction, allowing to add conditional suffixes to the next four instructions. Read more about it: 17.7.2 on page 251. Listing 12.43: ARM (thumb mode) CMP register, register/value ITEEE EQ ; set these suffixes: if-then-else-else-else instr1 ; instruction will be executed if condition is true instr2 ; instruction will be executed if condition is false instr3 ; instruction will be executed if condition is false instr4 ; instruction will be executed if condition is false 138
  • 163. CHAPTER 13. SWITCH()/CASE/DEFAULT Chapter 13 switch()/case/default 13.1 Small number of cases #include <stdio.h> void f (int a) { switch (a) { case 0: printf ("zeron"); break; case 1: printf ("onen"); break; case 2: printf ("twon"); break; default: printf ("something unknownn"); break; }; }; int main() { f (2); // test }; 13.1.1 x86 Non-optimizing MSVC Result (MSVC 2010): Listing 13.1: MSVC 2010 tv64 = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] mov DWORD PTR tv64[ebp], eax cmp DWORD PTR tv64[ebp], 0 je SHORT $LN4@f cmp DWORD PTR tv64[ebp], 1 je SHORT $LN3@f cmp DWORD PTR tv64[ebp], 2 je SHORT $LN2@f jmp SHORT $LN1@f $LN4@f: push OFFSET $SG739 ; 'zero', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN7@f $LN3@f: push OFFSET $SG741 ; 'one', 0aH, 00H call _printf add esp, 4 139
  • 164. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES jmp SHORT $LN7@f $LN2@f: push OFFSET $SG743 ; 'two', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN7@f $LN1@f: push OFFSET $SG745 ; 'something unknown', 0aH, 00H call _printf add esp, 4 $LN7@f: mov esp, ebp pop ebp ret 0 _f ENDP Our function with a few cases in switch() is in fact analogous to this construction: void f (int a) { if (a==0) printf ("zeron"); else if (a==1) printf ("onen"); else if (a==2) printf ("twon"); else printf ("something unknownn"); }; If we work with switch() with a few cases it is impossible to be sure if it was a real switch() in the source code, or just a pack of if() statements. This implies that switch() is like syntactic sugar for a large number of nested if()s. There is nothing especially new to us in the generated code, with the exception of the compiler moving input variable a to a temporary local variable tv64 1 . If we compile this in GCC 4.4.1, we’ll get almost the same result, even with maximal optimization turned on (-O3 option). Optimizing MSVC Now let’s turn on optimization in MSVC (/Ox): cl 1.c /Fa1.asm /Ox Listing 13.2: MSVC _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] sub eax, 0 je SHORT $LN4@f sub eax, 1 je SHORT $LN3@f sub eax, 1 je SHORT $LN2@f mov DWORD PTR _a$[esp-4], OFFSET $SG791 ; 'something unknown', 0aH, 00H jmp _printf $LN2@f: mov DWORD PTR _a$[esp-4], OFFSET $SG789 ; 'two', 0aH, 00H jmp _printf $LN3@f: mov DWORD PTR _a$[esp-4], OFFSET $SG787 ; 'one', 0aH, 00H jmp _printf $LN4@f: mov DWORD PTR _a$[esp-4], OFFSET $SG785 ; 'zero', 0aH, 00H jmp _printf _f ENDP Here we can see some dirty hacks. First: the value of a is placed in EAX and 0 is subtracted from it. Sounds absurd, but it is done to check if the value in EAX was 0. If yes, the ZF flag is to be set (e.g. subtracting from 0 is 0) and the first conditional jump JE (Jump if Equal or synonym JZ —Jump if Zero) is to be triggered and control flow is to be passed to the $LN4@f label, where the 'zero' message is 1Local variables in stack are prefixed with tv — that’s how MSVC names internal variables for its needs 140
  • 165. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES being printed. If the first jump doesn’t get triggered, 1 is subtracted from the input value and if at some stage the result is 0, the corresponding jump is to be triggered. And if no jump gets triggered at all, the control flow passes to printf() with string argument 'something unknown'. Second: we see something unusual for us: a string pointer is placed into the a variable, and then printf() is called not via CALL, but via JMP. There is a simple explanation for that: the Caller pushes a value to the stack and calls our function via CALL. CALL itself pushes the return address (RA) to the stack and does an unconditional jump to our function address. Our function at any point of execution (since it do not contain any instruction that moves the stack pointer) has the following stack layout: • ESP—points to RA • ESP+4—points to the a variable On the other side, when we need to call printf() here we need exactly the same stack layout, except for the first printf() argument, which needs to point to the string. And that is what our code does. It replaces the function’s first argument with the address of the string and jumps to printf(), as if we didn’t call our function f(), but directly printf(). printf() prints a string to stdout and then executes the RET instruction, which POPs RA from the stack and control flow is returned not to f() but rather to f()’s callee, bypassing the end of the f() function. All this is possible because printf() is called right at the end of the f() function in all cases. In some way, it is similar to the longjmp()2 function. And of course, it is all done for the sake of speed. A similar case with the ARM compiler is described in “printf() with several arguments”, section, here ( 6.2.1 on page 44). 2wikipedia 141
  • 166. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES OllyDbg Since this example is tricky, let’s trace it in OllyDbg. OllyDbg can detect such switch() constructs, and it can add some useful comments. EAX is 2 in the beginning, that’s the function’s input value: Figure 13.1: OllyDbg: EAX now contain the first (and only) function argument 142
  • 167. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES 0 is subtracted from 2 in EAX. Of course, EAX still contains 2. But the ZF flag is now 0, indicating that the resulting value is non-zero: Figure 13.2: OllyDbg: SUB executed 143
  • 168. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES DEC is executed and EAX now contains 1. But 1 is non-zero, so the ZF flag is still 0: Figure 13.3: OllyDbg: first DEC executed 144
  • 169. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES Next DEC is executed. EAX is finally 0 and the ZF flag gets set, because the result is zero: Figure 13.4: OllyDbg: second DEC executed OllyDbg shows that this jump is to be taken now. 145
  • 170. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES A pointer to the string “two” is to be written into the stack now: Figure 13.5: OllyDbg: pointer to the string is to be written at the place of the first argument Please note: the current argument of the function is 2 and 2 is now in the stack at the address 0x0020FA44. 146
  • 171. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES MOV writes the pointer to the string at address 0x0020FA44 (see the stack window). Then, jump happens. This is the first instruction of the printf() function in MSVCR100.DLL (I compiled the example with /MD switch): Figure 13.6: OllyDbg: first instruction of printf() in MSVCR100.DLL Now printf() treats the string at 0x00FF3010 as its only argument and prints the string. 147
  • 172. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES This is the last instruction of printf(): Figure 13.7: OllyDbg: last instruction of printf() in MSVCR100.DLL The string “two” was just printed to the console window. 148
  • 173. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES Now let’s press F7 or F8 (step over) and return…not to f(), but rather to main(): Figure 13.8: OllyDbg: return to main() Yes, the jump was direct, from the guts of printf() to main(). Because RA in the stack points not to some place in f(), but rather to main(). And CALL 0x00FF1000 was the actual instruction which called f(). 13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode) .text:0000014C f1: .text:0000014C 00 00 50 E3 CMP R0, #0 .text:00000150 13 0E 8F 02 ADREQ R0, aZero ; "zeron" .text:00000154 05 00 00 0A BEQ loc_170 .text:00000158 01 00 50 E3 CMP R0, #1 .text:0000015C 4B 0F 8F 02 ADREQ R0, aOne ; "onen" .text:00000160 02 00 00 0A BEQ loc_170 .text:00000164 02 00 50 E3 CMP R0, #2 .text:00000168 4A 0F 8F 12 ADRNE R0, aSomethingUnkno ; "something unknownn" .text:0000016C 4E 0F 8F 02 ADREQ R0, aTwo ; "twon" .text:00000170 .text:00000170 loc_170: ; CODE XREF: f1+8 .text:00000170 ; f1+14 .text:00000170 78 18 00 EA B __2printf Again, by investigating this code we cannot say if it was a switch() in the original source code, or just a pack of if() statements. Anyway, we see here predicated instructions again (like ADREQ (Equal)) which is triggered only in case R0 = 0, and then loads the address of the string «zeron» into R0. The next instruction BEQ redirects control flow to loc_170, if R0 = 0. An astute reader may ask, will BEQ trigger correctly since ADREQ before it has already filled the R0 register with another value? Yes, it will since BEQ checks the flags set by the CMP instruction, and ADREQ does not modify any flags at all. The rest of the instructions are already familiar to us. There is only one call to printf(), at the end, and we have already examined this trick here ( 6.2.1 on page 44). In the end, there are three paths to printf(). The last instruction, ``CMP R0, #2'' , is needed to check if a = 2. If it is not true, then ADRNE loads a pointer to the string «something unknown n» into R0, since a was already checked to be equal to 0 or 1, and we can sure that the a variable is not equal to these numbers at this point. And if R0 = 2, a pointer to the string «twon» will be loaded by ADREQ into R0. 13.1.3 ARM: Optimizing Keil 6/2013 (thumb mode) 149
  • 174. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES .text:000000D4 f1: .text:000000D4 10 B5 PUSH {R4,LR} .text:000000D6 00 28 CMP R0, #0 .text:000000D8 05 D0 BEQ zero_case .text:000000DA 01 28 CMP R0, #1 .text:000000DC 05 D0 BEQ one_case .text:000000DE 02 28 CMP R0, #2 .text:000000E0 05 D0 BEQ two_case .text:000000E2 91 A0 ADR R0, aSomethingUnkno ; "something unknownn" .text:000000E4 04 E0 B default_case .text:000000E6 zero_case: ; CODE XREF: f1+4 .text:000000E6 95 A0 ADR R0, aZero ; "zeron" .text:000000E8 02 E0 B default_case .text:000000EA one_case: ; CODE XREF: f1+8 .text:000000EA 96 A0 ADR R0, aOne ; "onen" .text:000000EC 00 E0 B default_case .text:000000EE two_case: ; CODE XREF: f1+C .text:000000EE 97 A0 ADR R0, aTwo ; "twon" .text:000000F0 default_case ; CODE XREF: f1+10 .text:000000F0 ; f1+14 .text:000000F0 06 F0 7E F8 BL __2printf .text:000000F4 10 BD POP {R4,PC} As I already mentioned, it is not possible to add conditional predicates to most instructions in thumb mode, so the thumb-code here is somewhat similar to the easily understandable x86 CISC-style code. 13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9 .LC12: .string "zero" .LC13: .string "one" .LC14: .string "two" .LC15: .string "something unknown" f12: stp x29, x30, [sp, -32]! add x29, sp, 0 str w0, [x29,28] ldr w0, [x29,28] cmp w0, 1 beq .L34 cmp w0, 2 beq .L35 cmp w0, wzr bne .L38 ; jump to default label adrp x0, .LC12 ; "zero" add x0, x0, :lo12:.LC12 bl puts b .L32 .L34: adrp x0, .LC13 ; "one" add x0, x0, :lo12:.LC13 bl puts b .L32 .L35: adrp x0, .LC14 ; "two" add x0, x0, :lo12:.LC14 bl puts b .L32 .L38: adrp x0, .LC15 ; "something unknown" add x0, x0, :lo12:.LC15 bl puts 150
  • 175. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.1. SMALL NUMBER OF CASES nop .L32: ldp x29, x30, [sp], 32 ret The type of the input value is int, hence register W0 is used to hold it instead of the whole X0 register. The string pointers are passed to puts() using an ADRP/ADD instructions pair just like I demonstrated in the “Hello, world!” example: 3.4.5 on page 15. 13.1.5 ARM64: Optimizing GCC (Linaro) 4.9 f12: cmp w0, 1 beq .L31 cmp w0, 2 beq .L32 cbz w0, .L35 ; default case adrp x0, .LC15 ; "something unknown" add x0, x0, :lo12:.LC15 b puts .L35: adrp x0, .LC12 ; "zero" add x0, x0, :lo12:.LC12 b puts .L32: adrp x0, .LC14 ; "two" add x0, x0, :lo12:.LC14 b puts .L31: adrp x0, .LC13 ; "one" add x0, x0, :lo12:.LC13 b puts Better optimized piece of code. CBZ (Compare and Branch on Zero) instruction does jump if W0 is zero. There is also a direct jump to puts() instead of calling it, like I explained before: 13.1.1 on page 140. 13.1.6 MIPS Listing 13.3: Optimizing GCC 4.4.5 (IDA) f: lui $gp, (__gnu_local_gp >> 16) ; is it 1? li $v0, 1 beq $a0, $v0, loc_60 la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot ; is it 2? li $v0, 2 beq $a0, $v0, loc_4C or $at, $zero ; branch delay slot, NOP ; jump, if not equal to 0: bnez $a0, loc_38 or $at, $zero ; branch delay slot, NOP ; zero case: lui $a0, ($LC0 >> 16) # "zero" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 ; branch delay slot, NOP la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot # --------------------------------------------------------------------------- loc_38: # CODE XREF: f+1C lui $a0, ($LC3 >> 16) # "something unknown" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC3 & 0xFFFF) # "something unknown" ; branch delay slot 151
  • 176. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES # --------------------------------------------------------------------------- loc_4C: # CODE XREF: f+14 lui $a0, ($LC2 >> 16) # "two" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot # --------------------------------------------------------------------------- loc_60: # CODE XREF: f+8 lui $a0, ($LC1 >> 16) # "one" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot The function always ends with calling puts(), so here we see a jump to puts() (JR: “Jump Register”) instead of “jump and link”. We talked about this earlier: 13.1.1 on page 140. We also often see NOP instructions after LW ones. This is “load delay slot”: another delay slot in MIPS. An instruction next to LW may execute at the moment while LW loads value from memory. However, the next instruction must not use the result of LW. Modern MIPS CPUs have a feature to wait if the next instruction uses result of LW, so this is somewhat outdated, but GCC still adds NOPs for older MIPS CPUs. In general, it can be ignored. 13.1.7 Conclusion A switch() with few cases is indistinguishable from an if/else construction, for example: listing.13.1.1. 13.2 A lot of cases If a switch() statement contains a lot of cases, it is not very convenient for the compiler to emit too large code with a lot JE/JNE instructions. #include <stdio.h> void f (int a) { switch (a) { case 0: printf ("zeron"); break; case 1: printf ("onen"); break; case 2: printf ("twon"); break; case 3: printf ("threen"); break; case 4: printf ("fourn"); break; default: printf ("something unknownn"); break; }; }; int main() { f (2); // test }; 13.2.1 x86 Non-optimizing MSVC We get (MSVC 2010): Listing 13.4: MSVC 2010 tv64 = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] 152
  • 177. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES mov DWORD PTR tv64[ebp], eax cmp DWORD PTR tv64[ebp], 4 ja SHORT $LN1@f mov ecx, DWORD PTR tv64[ebp] jmp DWORD PTR $LN11@f[ecx*4] $LN6@f: push OFFSET $SG739 ; 'zero', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN5@f: push OFFSET $SG741 ; 'one', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN4@f: push OFFSET $SG743 ; 'two', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN3@f: push OFFSET $SG745 ; 'three', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN2@f: push OFFSET $SG747 ; 'four', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN1@f: push OFFSET $SG749 ; 'something unknown', 0aH, 00H call _printf add esp, 4 $LN9@f: mov esp, ebp pop ebp ret 0 npad 2 ; align next label $LN11@f: DD $LN6@f ; 0 DD $LN5@f ; 1 DD $LN4@f ; 2 DD $LN3@f ; 3 DD $LN2@f ; 4 _f ENDP What we see here is a set of printf() calls with various arguments. All they have not only addresses in the memory of the process, but also internal symbolic labels assigned by the compiler. All these labels are also mentioned in the $LN11@f internal table. At the function start, if a is greater than 4, control flow is passed to label $LN1@f, where printf() with argument 'something unknown' is called. But if the value of a is less or equals to 4, then it gets multiplied by 4 and added with the $LN11@f table address. That is how an address inside the table is constructed, pointing exactly to the element we need. For example, let’s say a is equal to 2. 2 ∗ 4 = 8 (all table elements are addresses in a 32-bit process and that is why all elements are 4 bytes wide). The address of the $LN11@f table + 8 is the table element where the $LN4@f label is stored. JMP fetches the $LN4@f address from the table and jumps to it. This table is sometimes called jumptable or branch table3 . Then the corresponding printf() is called with argument 'two'. Literally, the jmp DWORD PTR $LN11@f[ecx*4] instruction implies jump to the DWORD that is stored at address $LN11@f + ecx * 4. npad ( 88 on page 866) is assembly language macro that aligning the next label so that it is to be stored at an address aligned on a 4 byte (or 16 byte) boundary. This is very suitable for the processor since it is able to fetch 32-bit values from memory through the memory bus, cache memory, etc, in a more effective way if it is aligned. 3The whole method was once called computed GOTO in early versions of FORTRAN: wikipedia. Not quite relevant these days, but what a term! 153
  • 178. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES OllyDbg Let’s try this example in OllyDbg. The input value of the function (2) is loaded into EAX: Figure 13.9: OllyDbg: function’s input value is loaded in EAX 154
  • 179. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES The input value is checked, is it bigger than 4? If not, the “default” jump is not taken: Figure 13.10: OllyDbg: 2 is no bigger than 4: no jump is taken 155
  • 180. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES Here we see a jumptable: Figure 13.11: OllyDbg: calculating destination address using jumptable Here I’ve clicked “Follow in Dump” → “Address constant”, so now we see the jumptable in the data window. These are 5 32-bit values4 . ECX is now 2, so the second element (counting from zero) of the table is to be used. It’s also possible to click “Follow in Dump” → “Memory address” and OllyDbg will show the element addressed by the JMP instruction. That’s 0x010B103A. 4They are underlined by OllyDbg because these are also FIXUPs: 68.2.6 on page 688, we are going to come back to them later 156
  • 181. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES After the jump we are at 0x010B103A: the code printing “two” will now be executed: Figure 13.12: OllyDbg: now we at the case: label Non-optimizing GCC Let’s see what GCC 4.4.1 generates: Listing 13.5: GCC 4.4.1 public f f proc near ; CODE XREF: main+10 var_18 = dword ptr -18h arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 18h cmp [ebp+arg_0], 4 ja short loc_8048444 mov eax, [ebp+arg_0] shl eax, 2 mov eax, ds:off_804855C[eax] jmp eax loc_80483FE: ; DATA XREF: .rodata:off_804855C mov [esp+18h+var_18], offset aZero ; "zero" call _puts jmp short locret_8048450 loc_804840C: ; DATA XREF: .rodata:08048560 mov [esp+18h+var_18], offset aOne ; "one" call _puts jmp short locret_8048450 loc_804841A: ; DATA XREF: .rodata:08048564 mov [esp+18h+var_18], offset aTwo ; "two" call _puts jmp short locret_8048450 loc_8048428: ; DATA XREF: .rodata:08048568 mov [esp+18h+var_18], offset aThree ; "three" 157
  • 182. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES call _puts jmp short locret_8048450 loc_8048436: ; DATA XREF: .rodata:0804856C mov [esp+18h+var_18], offset aFour ; "four" call _puts jmp short locret_8048450 loc_8048444: ; CODE XREF: f+A mov [esp+18h+var_18], offset aSomethingUnkno ; "something unknown" call _puts locret_8048450: ; CODE XREF: f+26 ; f+34... leave retn f endp off_804855C dd offset loc_80483FE ; DATA XREF: f+12 dd offset loc_804840C dd offset loc_804841A dd offset loc_8048428 dd offset loc_8048436 It is almost the same, with a little nuance: argument arg_0 is multiplied by 4 by shifting it to left by 2 bits (it is almost the same as multiplication by 4) ( 16.2.1 on page 206). Then the address of the label is taken from the off_804855C array, stored in EAX, and then ``JMP EAX'' does the actual jump. 13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode) Listing 13.6: Optimizing Keil 6/2013 (ARM mode) 00000174 f2 00000174 05 00 50 E3 CMP R0, #5 ; switch 5 cases 00000178 00 F1 8F 30 ADDCC PC, PC, R0,LSL#2 ; switch jump 0000017C 0E 00 00 EA B default_case ; jumptable 00000178 default case 00000180 00000180 loc_180 ; CODE XREF: f2+4 00000180 03 00 00 EA B zero_case ; jumptable 00000178 case 0 00000184 00000184 loc_184 ; CODE XREF: f2+4 00000184 04 00 00 EA B one_case ; jumptable 00000178 case 1 00000188 00000188 loc_188 ; CODE XREF: f2+4 00000188 05 00 00 EA B two_case ; jumptable 00000178 case 2 0000018C 0000018C loc_18C ; CODE XREF: f2+4 0000018C 06 00 00 EA B three_case ; jumptable 00000178 case 3 00000190 00000190 loc_190 ; CODE XREF: f2+4 00000190 07 00 00 EA B four_case ; jumptable 00000178 case 4 00000194 00000194 zero_case ; CODE XREF: f2+4 00000194 ; f2:loc_180 00000194 EC 00 8F E2 ADR R0, aZero ; jumptable 00000178 case 0 00000198 06 00 00 EA B loc_1B8 0000019C 0000019C one_case ; CODE XREF: f2+4 0000019C ; f2:loc_184 0000019C EC 00 8F E2 ADR R0, aOne ; jumptable 00000178 case 1 000001A0 04 00 00 EA B loc_1B8 158
  • 183. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES 000001A4 000001A4 two_case ; CODE XREF: f2+4 000001A4 ; f2:loc_188 000001A4 01 0C 8F E2 ADR R0, aTwo ; jumptable 00000178 case 2 000001A8 02 00 00 EA B loc_1B8 000001AC 000001AC three_case ; CODE XREF: f2+4 000001AC ; f2:loc_18C 000001AC 01 0C 8F E2 ADR R0, aThree ; jumptable 00000178 case 3 000001B0 00 00 00 EA B loc_1B8 000001B4 000001B4 four_case ; CODE XREF: f2+4 000001B4 ; f2:loc_190 000001B4 01 0C 8F E2 ADR R0, aFour ; jumptable 00000178 case 4 000001B8 000001B8 loc_1B8 ; CODE XREF: f2+24 000001B8 ; f2+2C 000001B8 66 18 00 EA B __2printf 000001BC 000001BC default_case ; CODE XREF: f2+4 000001BC ; f2+8 000001BC D4 00 8F E2 ADR R0, aSomethingUnkno ; jumptable 00000178 default case 000001C0 FC FF FF EA B loc_1B8 This code makes use of the ARM mode feature in which all instructions have a fixed size of 4 bytes. Let’s keep in mind that the maximum value for a is 4 and any greater value will cause «something unknownn» string to be printed. The first ``CMP R0, #5'' instruction compares the input value of a with 5. The next ``ADDCC PC, PC, R0,LSL#2'' 5 instruction is being executed only if R0 < 5 (CC=Carry clear / Less than). Consequently, if ADDCC does not trigger (it is a R0 ≥ 5 case), a jump to default_case label will occur. But if R0 < 5 and ADDCC triggers, the following is to be happen: The value in R0 is multiplied by 4. In fact, LSL#2 at the instruction’s suffix stands for “shift left by 2 bits”. But as we will see later ( 16.2.1 on page 205) in section “Shifts”, shift left by 2 bits is equivalent to multiplying by 4. Then we add R0 ∗ 4 to the current value in PC, thus jumping to one of the B (Branch) instructions located below. At the moment of the execution of ADDCC, the value in PC is 8 bytes ahead (0x180) than the address at which the ADDCC instruction is located (0x178), or, in other words, 2 instructions ahead. This is how the pipeline in ARM processors works: when ADDCC is executed, the processor at the moment is beginning to process the instruction after the next one, so that is why PC points there. This has to be memorized. If a = 0, then is to be added to the value in PC, and the actual value of the PC will be written into PC (which is 8 bytes ahead) and a jump to the label loc_180 will happen, which is 8 bytes ahead of the point where the ADDCC instruction is. If a = 1, then PC + 8 + a ∗ 4 = PC + 8 + 1 ∗ 4 = PC + 12 = 0x184 will be written to PC, which is the address of the loc_184 label. With every 1 added to a, the resulting PC is increased by 4. 4 is the instruction length in ARM mode and also, the length of each B instruction, of which there are 5 in row. Each of these five B instructions passes control further, to what was programmed in the switch(). Pointer loading of the corresponding string occurs there, etc. 13.2.3 ARM: Optimizing Keil 6/2013 (thumb mode) Listing 13.7: Optimizing Keil 6/2013 (thumb mode) 000000F6 EXPORT f2 000000F6 f2 000000F6 10 B5 PUSH {R4,LR} 000000F8 03 00 MOVS R3, R0 000000FA 06 F0 69 F8 BL __ARM_common_switch8_thumb ; switch 6 cases 000000FE 05 DCB 5 000000FF 04 06 08 0A 0C 10 DCB 4, 6, 8, 0xA, 0xC, 0x10 ; jump table for switch statement 00000105 00 ALIGN 2 00000106 00000106 zero_case ; CODE XREF: f2+4 00000106 8D A0 ADR R0, aZero ; jumptable 000000FA case 0 5ADD—addition 159
  • 184. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES 00000108 06 E0 B loc_118 0000010A 0000010A one_case ; CODE XREF: f2+4 0000010A 8E A0 ADR R0, aOne ; jumptable 000000FA case 1 0000010C 04 E0 B loc_118 0000010E 0000010E two_case ; CODE XREF: f2+4 0000010E 8F A0 ADR R0, aTwo ; jumptable 000000FA case 2 00000110 02 E0 B loc_118 00000112 00000112 three_case ; CODE XREF: f2+4 00000112 90 A0 ADR R0, aThree ; jumptable 000000FA case 3 00000114 00 E0 B loc_118 00000116 00000116 four_case ; CODE XREF: f2+4 00000116 91 A0 ADR R0, aFour ; jumptable 000000FA case 4 00000118 00000118 loc_118 ; CODE XREF: f2+12 00000118 ; f2+16 00000118 06 F0 6A F8 BL __2printf 0000011C 10 BD POP {R4,PC} 0000011E 0000011E default_case ; CODE XREF: f2+4 0000011E 82 A0 ADR R0, aSomethingUnkno ; jumptable 000000FA default case 00000120 FA E7 B loc_118 000061D0 EXPORT __ARM_common_switch8_thumb 000061D0 __ARM_common_switch8_thumb ; CODE XREF: example6_f2+4 000061D0 78 47 BX PC 000061D2 00 00 ALIGN 4 000061D2 ; End of function __ARM_common_switch8_thumb 000061D2 000061D4 __32__ARM_common_switch8_thumb ; CODE XREF: ⤦ __ARM_common_switch8_thumb 000061D4 01 C0 5E E5 LDRB R12, [LR,#-1] 000061D8 0C 00 53 E1 CMP R3, R12 000061DC 0C 30 DE 27 LDRCSB R3, [LR,R12] 000061E0 03 30 DE 37 LDRCCB R3, [LR,R3] 000061E4 83 C0 8E E0 ADD R12, LR, R3,LSL#1 000061E8 1C FF 2F E1 BX R12 000061E8 ; End of function __32__ARM_common_switch8_thumb One cannot be sure that all instructions in thumb and thumb-2 modes has the same size. It can even be said that in these modes the instructions have variable lengths, just like in x86. So there is a special table added that contains information about how much cases are there (not including default-case), and an offset for each with a label to which control must be passed in the corresponding case. A special function is present here in order to deal with the table and pass control, named __ARM_common_switch8_thumb. It starts with ``BX PC'' , whose function is to switch the processor to ARM-mode. Then you see the function for table processing. It is too complex to describe it here now, so I’m omitting it. It is interesting to note that the function uses the LR register as a pointer to the table. Indeed, after calling of this function, LR contains the address after ``BL __ARM_common_switch8_thumb'' instruction, where the table starts. It is also worth noting that the code is generated as a separate function in order to reuse it, so the compiler not generates the same code for every switch() statement. IDA successfully perceived it as a service function and a table, and added comments to the labels like jumptable 000000FA case 0. 13.2.4 MIPS Listing 13.8: Optimizing GCC 4.4.5 (IDA) 160
  • 185. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.2. A LOT OF CASES f: lui $gp, (__gnu_local_gp >> 16) ; jump to loc_24 if input value is lesser than 5: sltiu $v0, $a0, 5 bnez $v0, loc_24 la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot ; input value is greater or equal to 5. ; print "something unknown" and finish: lui $a0, ($LC5 >> 16) # "something unknown" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC5 & 0xFFFF) # "something unknown" ; branch delay slot loc_24: # CODE XREF: f+8 ; load address of jumptable ; LA is pseudoinstruction, LUI and ADDIU pair are there in fact: la $v0, off_120 ; multiply input value by 4: sll $a0, 2 ; sum up multiplied value and jumptable address: addu $a0, $v0, $a0 ; load element from jumptable: lw $v0, 0($a0) or $at, $zero ; NOP ; jump to the address we got in jumptable: jr $v0 or $at, $zero ; branch delay slot, NOP sub_44: # DATA XREF: .rodata:0000012C ; print "three" and finish lui $a0, ($LC3 >> 16) # "three" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC3 & 0xFFFF) # "three" ; branch delay slot sub_58: # DATA XREF: .rodata:00000130 ; print "four" and finish lui $a0, ($LC4 >> 16) # "four" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC4 & 0xFFFF) # "four" ; branch delay slot sub_6C: # DATA XREF: .rodata:off_120 ; print "zero" and finish lui $a0, ($LC0 >> 16) # "zero" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot sub_80: # DATA XREF: .rodata:00000124 ; print "one" and finish lui $a0, ($LC1 >> 16) # "one" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot sub_94: # DATA XREF: .rodata:00000128 ; print "two" and finish lui $a0, ($LC2 >> 16) # "two" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot ; may be placed in .rodata section: 161
  • 186. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK off_120: .word sub_6C .word sub_80 .word sub_94 .word sub_44 .word sub_58 The new instruction for us is SLTIU (“Set on Less Than Immediate Unsigned”). This is the same as SLTU (“Set on Less Than Unsigned”), but “I” stands for “immediate”, i.e., a number has to be specified in the instruction itself. BNEZ is “Branch if Not Equal to Zero”. Code is very close to the other ISAs. SLL (“Shift Word Left Logical”) does multiplication by 4. MIPS is a 32-bit CPU after all, so all addresses in the jumptable are 32-bit ones. 13.2.5 Conclusion Rough skeleton of switch(): Listing 13.9: x86 MOV REG, input CMP REG, 4 ; maximal number of cases JA default SHL REG, 2 ; find element in table. shift for 3 bits in x64. MOV REG, jump_table[REG] JMP REG case1: ; do something JMP exit case2: ; do something JMP exit case3: ; do something JMP exit case4: ; do something JMP exit case5: ; do something JMP exit default: ... exit: .... jump_table dd case1 dd case2 dd case3 dd case4 dd case5 The jump to the address in the jump table may also be implemented using this instruction: JMP jump_table[REG*4]. Or JMP jump_table[REG*8] in x64. A jumptable is just array of pointers, like the one described later: 18.5 on page 275. 13.3 When there are several case statements in one block Here is a very widespread construction: several case statements for a single block: #include <stdio.h> void f(int a) { switch (a) { 162
  • 187. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK case 1: case 2: case 7: case 10: printf ("1, 2, 7, 10n"); break; case 3: case 4: case 5: case 6: printf ("3, 4, 5n"); break; case 8: case 9: case 20: case 21: printf ("8, 9, 21n"); break; case 22: printf ("22n"); break; default: printf ("defaultn"); break; }; }; int main() { f(4); }; It’s too wasteful to generate a block for each possible case, so what is usually done is to generate each block plus some kind of dispatcher. 13.3.1 MSVC Listing 13.10: Optimizing MSVC 2010 1 $SG2798 DB '1, 2, 7, 10', 0aH, 00H 2 $SG2800 DB '3, 4, 5', 0aH, 00H 3 $SG2802 DB '8, 9, 21', 0aH, 00H 4 $SG2804 DB '22', 0aH, 00H 5 $SG2806 DB 'default', 0aH, 00H 6 7 _a$ = 8 8 _f PROC 9 mov eax, DWORD PTR _a$[esp-4] 10 dec eax 11 cmp eax, 21 12 ja SHORT $LN1@f 13 movzx eax, BYTE PTR $LN10@f[eax] 14 jmp DWORD PTR $LN11@f[eax*4] 15 $LN5@f: 16 mov DWORD PTR _a$[esp-4], OFFSET $SG2798 ; '1, 2, 7, 10' 17 jmp DWORD PTR __imp__printf 18 $LN4@f: 19 mov DWORD PTR _a$[esp-4], OFFSET $SG2800 ; '3, 4, 5' 20 jmp DWORD PTR __imp__printf 21 $LN3@f: 22 mov DWORD PTR _a$[esp-4], OFFSET $SG2802 ; '8, 9, 21' 23 jmp DWORD PTR __imp__printf 24 $LN2@f: 25 mov DWORD PTR _a$[esp-4], OFFSET $SG2804 ; '22' 26 jmp DWORD PTR __imp__printf 27 $LN1@f: 28 mov DWORD PTR _a$[esp-4], OFFSET $SG2806 ; 'default' 29 jmp DWORD PTR __imp__printf 30 npad 2 ; align $LN11@f table on 16-byte boundary 163
  • 188. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK 31 $LN11@f: 32 DD $LN5@f ; print '1, 2, 7, 10' 33 DD $LN4@f ; print '3, 4, 5' 34 DD $LN3@f ; print '8, 9, 21' 35 DD $LN2@f ; print '22' 36 DD $LN1@f ; print 'default' 37 $LN10@f: 38 DB 0 ; a=1 39 DB 0 ; a=2 40 DB 1 ; a=3 41 DB 1 ; a=4 42 DB 1 ; a=5 43 DB 1 ; a=6 44 DB 0 ; a=7 45 DB 2 ; a=8 46 DB 2 ; a=9 47 DB 0 ; a=10 48 DB 4 ; a=11 49 DB 4 ; a=12 50 DB 4 ; a=13 51 DB 4 ; a=14 52 DB 4 ; a=15 53 DB 4 ; a=16 54 DB 4 ; a=17 55 DB 4 ; a=18 56 DB 4 ; a=19 57 DB 2 ; a=20 58 DB 2 ; a=21 59 DB 3 ; a=22 60 _f ENDP We see two tables here: the first table ($LN10@f) is an index table, and the second one ($LN11@f) is an array of pointers to blocks. First, the input value is used as an index in the index table (line 13). Here is a short legend for the values in the table: 0 is the first case block (for values 1, 2, 7, 10), 1 is the second one (for values 3, 4, 5), 2 is the third one (for values 8, 9, 21), 3 is the fourth one (for value 22), 4 is for the default block. There we get an index for the second table of code pointers and we jump to it (line 14). What is also worth noting is that there is no case for input value 0. That’s why we see the DEC instruction at line 10, and the table starts at a = 1, because there is no need to allocate a table element for a = 0. This is a very widespread pattern. So why is this economical? Why isn’t it possible to make it as before ( 13.2.1 on page 157), just with one table consisting of block pointers? The reason is that the elements in index table are 8-bit, hence it’s all more compact. 13.3.2 GCC GCC does the job in the way we already discussed ( 13.2.1 on page 157), using just one table of pointers. 13.3.3 ARM64: Optimizing GCC 4.9.1 There is no code to be triggered if the input value is 0, so GCC tries to make the jump table more compact and so it starts at 1 as an input value. GCC 4.9.1 for ARM64 uses an even cleverer trick. It’s able to encode all offsets as 8-bit bytes. Let’s recall that all ARM64 instructions have a size of 4 bytes. GCC is uses the fact that all offsets in my tiny example are in close proximity to each other. So the jump table consisting of single bytes. Listing 13.11: Optimizing GCC 4.9.1 ARM64 f14: ; input value in W0 sub w0, w0, #1 cmp w0, 21 ; branch if less or equal (unsigned): bls .L9 .L2: ; print "default": adrp x0, .LC4 add x0, x0, :lo12:.LC4 b puts .L9: 164
  • 189. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.3. WHEN THERE ARE SEVERAL CASE STATEMENTS IN ONE BLOCK ; load jumptable address to X1: adrp x1, .L4 add x1, x1, :lo12:.L4 ; W0=input_value-1 ; load byte from the table: ldrb w0, [x1,w0,uxtw] ; load address of the Lrtx label: adr x1, .Lrtx4 ; multiply table element by 4 (by shifting 2 bits left) and add (or subtract) to the address of Lrtx: add x0, x1, w0, sxtb #2 ; jump to the calculated address: br x0 ; this label is pointing in code (text) segment: .Lrtx4: .section .rodata ; everything after ".section" statement is allocated in the read-only data (rodata) segment: .L4: .byte (.L3 - .Lrtx4) / 4 ; case 1 .byte (.L3 - .Lrtx4) / 4 ; case 2 .byte (.L5 - .Lrtx4) / 4 ; case 3 .byte (.L5 - .Lrtx4) / 4 ; case 4 .byte (.L5 - .Lrtx4) / 4 ; case 5 .byte (.L5 - .Lrtx4) / 4 ; case 6 .byte (.L3 - .Lrtx4) / 4 ; case 7 .byte (.L6 - .Lrtx4) / 4 ; case 8 .byte (.L6 - .Lrtx4) / 4 ; case 9 .byte (.L3 - .Lrtx4) / 4 ; case 10 .byte (.L2 - .Lrtx4) / 4 ; case 11 .byte (.L2 - .Lrtx4) / 4 ; case 12 .byte (.L2 - .Lrtx4) / 4 ; case 13 .byte (.L2 - .Lrtx4) / 4 ; case 14 .byte (.L2 - .Lrtx4) / 4 ; case 15 .byte (.L2 - .Lrtx4) / 4 ; case 16 .byte (.L2 - .Lrtx4) / 4 ; case 17 .byte (.L2 - .Lrtx4) / 4 ; case 18 .byte (.L2 - .Lrtx4) / 4 ; case 19 .byte (.L6 - .Lrtx4) / 4 ; case 20 .byte (.L6 - .Lrtx4) / 4 ; case 21 .byte (.L7 - .Lrtx4) / 4 ; case 22 .text ; everything after ".text" statement is allocated in the code (text) segment: .L7: ; print "22" adrp x0, .LC3 add x0, x0, :lo12:.LC3 b puts .L6: ; print "8, 9, 21" adrp x0, .LC2 add x0, x0, :lo12:.LC2 b puts .L5: ; print "3, 4, 5" adrp x0, .LC1 add x0, x0, :lo12:.LC1 b puts .L3: ; print "1, 2, 7, 10" adrp x0, .LC0 add x0, x0, :lo12:.LC0 b puts .LC0: .string "1, 2, 7, 10" .LC1: .string "3, 4, 5" .LC2: .string "8, 9, 21" .LC3: .string "22" 165
  • 190. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.4. FALL-THROUGH .LC4: .string "default" I just compiled my example to object file and opened it in IDA. Here is the jump table: Listing 13.12: jumptable in IDA .rodata:0000000000000064 AREA .rodata, DATA, READONLY .rodata:0000000000000064 ; ORG 0x64 .rodata:0000000000000064 $d DCB 9 ; case 1 .rodata:0000000000000065 DCB 9 ; case 2 .rodata:0000000000000066 DCB 6 ; case 3 .rodata:0000000000000067 DCB 6 ; case 4 .rodata:0000000000000068 DCB 6 ; case 5 .rodata:0000000000000069 DCB 6 ; case 6 .rodata:000000000000006A DCB 9 ; case 7 .rodata:000000000000006B DCB 3 ; case 8 .rodata:000000000000006C DCB 3 ; case 9 .rodata:000000000000006D DCB 9 ; case 10 .rodata:000000000000006E DCB 0xF7 ; case 11 .rodata:000000000000006F DCB 0xF7 ; case 12 .rodata:0000000000000070 DCB 0xF7 ; case 13 .rodata:0000000000000071 DCB 0xF7 ; case 14 .rodata:0000000000000072 DCB 0xF7 ; case 15 .rodata:0000000000000073 DCB 0xF7 ; case 16 .rodata:0000000000000074 DCB 0xF7 ; case 17 .rodata:0000000000000075 DCB 0xF7 ; case 18 .rodata:0000000000000076 DCB 0xF7 ; case 19 .rodata:0000000000000077 DCB 3 ; case 20 .rodata:0000000000000078 DCB 3 ; case 21 .rodata:0000000000000079 DCB 0 ; case 22 .rodata:000000000000007B ; .rodata ends So in case of 1, 9 is to be multiplied by 4 and added to the address of Lrtx4 label. In case of 22, 0 is to be multiplied by 4, resulting in 0. Right after the Lrtx4 label is the L7 label, where you can find the code that prints “22”. There is no jump table in the code segment, it’s allocated in a separate .rodata section (there is no special need to place it in the code section). There are also negative bytes (0xF7), they are used for jumping back to the code that prints the “default” string (at .L2). 13.4 Fall-through Another very popular usage of switch() is the fall-through. Here is a small example: 1 #define R 1 2 #define W 2 3 #define RW 3 4 5 void f(int type) 6 { 7 int read=0, write=0; 8 9 switch (type) 10 { 11 case RW: 12 read=1; 13 case W: 14 write=1; 15 break; 16 case R: 17 read=1; 18 break; 19 default: 20 break; 21 }; 22 printf ("read=%d, write=%dn", read, write); 23 }; If type = 1 (R), read is to be set to 1, if type = 2 (W), write is to be set to 2. In case of type = 3 (RW), both read and write is to be set to 1. 166
  • 191. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.4. FALL-THROUGH The code at line 14 is executed in two cases: if type = RW or if type = W. There is no “break” for “case RW”x and that’s OK. 13.4.1 MSVC x86 Listing 13.13: MSVC 2012 $SG1305 DB 'read=%d, write=%d', 0aH, 00H _write$ = -12 ; size = 4 _read$ = -8 ; size = 4 tv64 = -4 ; size = 4 _type$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp sub esp, 12 mov DWORD PTR _read$[ebp], 0 mov DWORD PTR _write$[ebp], 0 mov eax, DWORD PTR _type$[ebp] mov DWORD PTR tv64[ebp], eax cmp DWORD PTR tv64[ebp], 1 ; R je SHORT $LN2@f cmp DWORD PTR tv64[ebp], 2 ; W je SHORT $LN3@f cmp DWORD PTR tv64[ebp], 3 ; RW je SHORT $LN4@f jmp SHORT $LN5@f $LN4@f: ; case RW: mov DWORD PTR _read$[ebp], 1 $LN3@f: ; case W: mov DWORD PTR _write$[ebp], 1 jmp SHORT $LN5@f $LN2@f: ; case R: mov DWORD PTR _read$[ebp], 1 $LN5@f: ; default mov ecx, DWORD PTR _write$[ebp] push ecx mov edx, DWORD PTR _read$[ebp] push edx push OFFSET $SG1305 ; 'read=%d, write=%d' call _printf add esp, 12 mov esp, ebp pop ebp ret 0 _f ENDP The code mostly resembles what is in the source. There are no jumps between labels $LN4@f and $LN3@f: so when code flow is at $LN4@f, read is first set to 1, then write. This is why it’s called fall-through: code flow falls through one piece of code (setting read) to another (setting write). If type = W, we land at $LN3@f, so no code setting read to 1 is executed. 13.4.2 ARM64 Listing 13.14: GCC (Linaro) 4.9 .LC0: .string "read=%d, write=%dn" f: stp x29, x30, [sp, -48]! add x29, sp, 0 str w0, [x29,28] str wzr, [x29,44] ; set "read" and "write" local variables to zero str wzr, [x29,40] ldr w0, [x29,28] ; load "type" argument cmp w0, 2 ; type=W? beq .L3 167
  • 192. CHAPTER 13. SWITCH()/CASE/DEFAULT 13.5. EXERCISES cmp w0, 3 ; type=RW? beq .L4 cmp w0, 1 ; type=R? beq .L5 b .L6 ; otherwise... .L4: ; case RW mov w0, 1 str w0, [x29,44] ; read=1 .L3: ; case W mov w0, 1 str w0, [x29,40] ; write=1 b .L6 .L5: ; case R mov w0, 1 str w0, [x29,44] ; read=1 nop .L6: ; default adrp x0, .LC0 ; "read=%d, write=%dn" add x0, x0, :lo12:.LC0 ldr w1, [x29,44] ; load "read" ldr w2, [x29,40] ; load "write" bl printf ldp x29, x30, [sp], 48 ret Merely the same thing. There are no jumps between labels .L4 and .L3. 13.5 Exercises 13.5.1 Exercise #1 It’s possible to rework the C example in 13.2 on page 152 in such way that the compiler can produce even smaller code, but will work just the same. Try to achieve it. Hint: G.1.3 on page 954. 168
  • 193. CHAPTER 14. LOOPS Chapter 14 Loops 14.1 Simple example 14.1.1 x86 There is a special LOOP instruction in x86 instruction set for checking the value in register ECX and if it is not 0, to decrement ECX and pass control flow to the label in the LOOP operand. Probably this instruction is not very convenient, as I never saw any modern compiler emit it automatically. So, if you see this instruction somewhere in code, it is most likely that this is a manually written piece of assembly code. In C/C++ loops are usually constructed using for(), while() or do/while() statements. Let’s start with for(). This statement defines loop initialization (set loop counter to initial value), loop condition (is the counter bigger than a limit?), what is done at each iteration (increment/decrement) and of course loop body. for (initialization; condition; at each iteration) { loop_body; } The generated code is consisting of four parts as well. Let’s start with a simple example: #include <stdio.h> void printing_function(int i) { printf ("f(%d)n", i); }; int main() { int i; for (i=2; i<10; i++) printing_function(i); return 0; }; Result (MSVC 2010): Listing 14.1: MSVC 2010 _i$ = -4 _main PROC push ebp mov ebp, esp push ecx mov DWORD PTR _i$[ebp], 2 ; loop initialization jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] ; here is what we do after each iteration: add eax, 1 ; add 1 to (i) value mov DWORD PTR _i$[ebp], eax 169
  • 194. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE $LN3@main: cmp DWORD PTR _i$[ebp], 10 ; this condition is checked *before* each iteration jge SHORT $LN1@main ; if (i) is biggest or equals to 10, lets finish loop' mov ecx, DWORD PTR _i$[ebp] ; loop body: call printing_function(i) push ecx call _printing_function add esp, 4 jmp SHORT $LN2@main ; jump to loop begin $LN1@main: ; loop end xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP As we see, nothing special. GCC 4.4.1 emits almost the same code, with one subtle difference: Listing 14.2: GCC 4.4.1 main proc near var_20 = dword ptr -20h var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_4], 2 ; (i) initializing jmp short loc_8048476 loc_8048465: mov eax, [esp+20h+var_4] mov [esp+20h+var_20], eax call printing_function add [esp+20h+var_4], 1 ; (i) increment loc_8048476: cmp [esp+20h+var_4], 9 jle short loc_8048465 ; if i<=9, continue loop mov eax, 0 leave retn main endp Now let’s see what we get with optimization turned on (/Ox): Listing 14.3: Optimizing MSVC _main PROC push esi mov esi, 2 $LL3@main: push esi call _printing_function inc esi add esp, 4 cmp esi, 10 ; 0000000aH jl SHORT $LL3@main xor eax, eax pop esi ret 0 _main ENDP What happens here is that space for the i variable is not allocated in the local stack anymore, but uses an individual register for it, ESI. This is possible in such small functions where there aren’t many local variables. One very important thing is that the f() function must not change the value in ESI. Our compiler is sure here. And if the compiler decides to use the ESI register in f() too, its value would have to be saved at the function’s prologue and restored at the function’s epilogue, almost like in our listing: please note PUSH ESI/POP ESI at the function start and end. Let’s try GCC 4.4.1 with maximal optimization turned on (-O3 option): 170
  • 195. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE Listing 14.4: Optimizing GCC 4.4.1 main proc near var_10 = dword ptr -10h push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov [esp+10h+var_10], 2 call printing_function mov [esp+10h+var_10], 3 call printing_function mov [esp+10h+var_10], 4 call printing_function mov [esp+10h+var_10], 5 call printing_function mov [esp+10h+var_10], 6 call printing_function mov [esp+10h+var_10], 7 call printing_function mov [esp+10h+var_10], 8 call printing_function mov [esp+10h+var_10], 9 call printing_function xor eax, eax leave retn main endp Huh, GCC just unwound our loop. Loop unwinding has an advantage in the cases when there aren’t much iterations and we could cut some execution time by removing all loop support instructions. On the other side, the resulting code is obviously larger. Big unrolled loops are not recommended in modern times, because bigger functions may require bigger cache footprint 1 . OK, let’s increase the maximum value of the i variable to 100 and try again. GCC does: Listing 14.5: GCC public main main proc near var_20 = dword ptr -20h push ebp mov ebp, esp and esp, 0FFFFFFF0h push ebx mov ebx, 2 ; i=2 sub esp, 1Ch ; aligning label loc_80484D0 (loop body begin) by 16-byte border: nop loc_80484D0: ; pass (i) as first argument to printing_function(): mov [esp+20h+var_20], ebx add ebx, 1 ; i++ call printing_function cmp ebx, 64h ; i==100? jnz short loc_80484D0 ; if not, continue add esp, 1Ch xor eax, eax ; return 0 pop ebx mov esp, ebp pop ebp retn main endp 1A very good article about it: [Dre07]. Another recommendations about loop unrolling from Intel are here : [Int14, p. 3.4.1.7]. 171
  • 196. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE It is quite similar to what MSVC 2010 with optimization (/Ox) produce, with the exception that the EBX register is allocated for the i variable. GCC is sure this register will not be modified inside of the f() function, and if it will, it will be saved at the function prologue and restored at epilogue, just like here in the main() function. 172
  • 197. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE 14.1.2 x86: OllyDbg Let’s compile our example in MSVC 2010 with /Ox and /Ob0 options and load it into OllyDbg. It seems that OllyDbg is able to detect simple loops and show them in square brackets, for convenience: Figure 14.1: OllyDbg: main() begin By tracing (F8 (step over)) we see ESI incrementing. Here, for instance, ESI = i = 6: Figure 14.2: OllyDbg: loop body just executed with i = 6 9 is the last loop value. That’s why JL is not triggering after the increment, and the function will finish: Figure 14.3: OllyDbg: ESI = 10, loop end 14.1.3 x86: tracer As we might see, it is not very convenient to trace manulally in the debugger. That’s one of the reasons I wrote a tracer for myself. We open compiled example in IDA, find the address of the instruction PUSH ESI (passing the sole argument to f()) which is 0x401026 for me and we run the tracer: tracer.exe -l:loops_2.exe bpx=loops_2.exe!0x00401026 BPX just sets a breakpoint at the address and tracer will then print the state of the registers. In the tracer.log This is what we see: PID=12884|New process loops_2.exe 173
  • 198. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE (0) loops_2.exe!0x401026 EAX=0x00a328c8 EBX=0x00000000 ECX=0x6f0f4714 EDX=0x00000000 ESI=0x00000002 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=PF ZF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000003 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000004 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000005 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000006 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000007 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000008 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000009 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF PID=12884|Process loops_2.exe exited. ExitCode=0 (0x0) We see how the value of ESI register changes from 2 to 9. Even more than that, the tracer can collect register values for all addresses within the function. This is called trace there. Every instruction gets traced, all interesting register values are recorded. Then, an IDA.idc-script is generated, that adds comments. So, in the IDA we’ve learned that the main() function address is 0x00401020 and we run: tracer.exe -l:loops_2.exe bpf=loops_2.exe!0x00401020,trace:cc BPF stands for set breakpoint on function. As a result, we get the loops_2.exe.idc and loops_2.exe_clear.idc scripts. 174
  • 199. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE We load loops_2.exe.idc into IDA and see: Figure 14.4: IDA with .idc-script loaded We see that ESI can be from 2 to 9 at the start of the loop body, but from 3 to 0xA (10) after the increment. We can also see that main() is finishing with 0 in EAX. tracer also generates loops_2.exe.txt, that contains information about how many times each instruction was exe- cuted and register values: Listing 14.6: loops_2.exe.txt 0x401020 (.text+0x20), e= 1 [PUSH ESI] ESI=1 0x401021 (.text+0x21), e= 1 [MOV ESI, 2] 0x401026 (.text+0x26), e= 8 [PUSH ESI] ESI=2..9 0x401027 (.text+0x27), e= 8 [CALL 8D1000h] tracing nested maximum level (1) reached, ⤦ skipping this CALL 8D1000h=0x8d1000 0x40102c (.text+0x2c), e= 8 [INC ESI] ESI=2..9 0x40102d (.text+0x2d), e= 8 [ADD ESP, 4] ESP=0x38fcbc 0x401030 (.text+0x30), e= 8 [CMP ESI, 0Ah] ESI=3..0xa 0x401033 (.text+0x33), e= 8 [JL 8D1026h] SF=false,true OF=false 0x401035 (.text+0x35), e= 1 [XOR EAX, EAX] 0x401037 (.text+0x37), e= 1 [POP ESI] 0x401038 (.text+0x38), e= 1 [RETN] EAX=0 We can use grep here. 14.1.4 ARM Non-optimizing Keil 6/2013 (ARM mode) main STMFD SP!, {R4,LR} MOV R4, #2 B loc_368 loc_35C ; CODE XREF: main+1C MOV R0, R4 BL printing_function ADD R4, R4, #1 loc_368 ; CODE XREF: main+8 CMP R4, #0xA BLT loc_35C MOV R0, #0 175
  • 200. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE LDMFD SP!, {R4,PC} Iteration counter i is to be stored in the R4 register. The ``MOV R4, #2'' instruction just initializes i. The ``MOV R0, R4'' and ``BL printing_function'' instructions compose the body of the loop, the first instruction preparing the argument for f() function and the second calling the function. The ``ADD R4, R4, #1'' instruction just adds 1 to the i variable at each iteration. ``CMP R4, #0xA'' compares i with 0xA (10). The next instruction BLT (Branch Less Than) jumps if i is less than 10. Otherwise, 0 is to be written into R0 (since our function returns 0) and function execution finishes. Optimizing Keil 6/2013 (thumb mode) _main PUSH {R4,LR} MOVS R4, #2 loc_132 ; CODE XREF: _main+E MOVS R0, R4 BL printing_function ADDS R4, R4, #1 CMP R4, #0xA BLT loc_132 MOVS R0, #0 POP {R4,PC} Practically the same. Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) _main PUSH {R4,R7,LR} MOVW R4, #0x1124 ; "%dn" MOVS R1, #2 MOVT.W R4, #0 ADD R7, SP, #4 ADD R4, PC MOV R0, R4 BLX _printf MOV R0, R4 MOVS R1, #3 BLX _printf MOV R0, R4 MOVS R1, #4 BLX _printf MOV R0, R4 MOVS R1, #5 BLX _printf MOV R0, R4 MOVS R1, #6 BLX _printf MOV R0, R4 MOVS R1, #7 BLX _printf MOV R0, R4 MOVS R1, #8 BLX _printf MOV R0, R4 MOVS R1, #9 BLX _printf MOVS R0, #0 POP {R4,R7,PC} In fact, this was in my f() function: void printing_function(int i) { printf ("%dn", i); }; 176
  • 201. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE So, LLVM not just unrolled the loop, but also inlined my very simple function f(), and inserted its body 8 times instead of calling it. This is possible when the function is so primitive (like mine) and when it is not called too much (like here). ARM64: Optimizing GCC 4.9.1 Listing 14.7: Optimizing GCC 4.9.1 printing_function: ; prepare second argument of printf(): mov w1, w0 ; load address of the "f(%d)n" string adrp x0, .LC0 add x0, x0, :lo12:.LC0 ; just branch here instead of branch with link and return: b printf main: ; save FP and LR in the local stack: stp x29, x30, [sp, -32]! ; set up stack frame: add x29, sp, 0 ; save contents of X19 register in the local stack: str x19, [sp,16] ; we will use W19 register as counter. ; set initial value of 2 to it: mov w19, 2 .L3: ; prepare first argument of printing_function(): mov w0, w19 ; increment counter register. add w19, w19, 1 ; W0 here still holds value of counter value before increment. bl printing_function ; is it end? cmp w19, 10 ; no, jump to the loop body begin: bne .L3 ; return 0 mov w0, 0 ; restore contents of X19 register: ldr x19, [sp,16] ; restore FP and LR values: ldp x29, x30, [sp], 32 ret .LC0: .string "f(%d)n" ARM64: Non-optimizing GCC 4.9.1 Listing 14.8: Non-optimizing GCC 4.9.1 -fno-inline printing_function: ; prepare second argument of printf(): mov w1, w0 ; load address of the "f(%d)n" string adrp x0, .LC0 add x0, x0, :lo12:.LC0 ; just branch here instead of branch with link and return: b printf main: ; save FP and LR in the local stack: stp x29, x30, [sp, -32]! ; set up stack frame: add x29, sp, 0 ; save contents of X19 register in the local stack: str x19, [sp,16] ; we will use W19 register as counter. ; set initial value of 2 to it: mov w19, 2 177
  • 202. CHAPTER 14. LOOPS 14.1. SIMPLE EXAMPLE .L3: ; prepare first argument of printing_function(): mov w0, w19 ; increment counter register. add w19, w19, 1 ; W0 here still holds value of counter value before increment. bl printing_function ; is it end? cmp w19, 10 ; no, jump to the loop body begin: bne .L3 ; return 0 mov w0, 0 ; restore contents of X19 register: ldr x19, [sp,16] ; restore FP and LR values: ldp x29, x30, [sp], 32 ret .LC0: .string "f(%d)n" 14.1.5 MIPS Listing 14.9: Non-optimizing GCC 4.4.5 (IDA) main: ; IDA is not aware of variable names in local stack ; I gave them names manually: i = -0x10 saved_FP = -8 saved_RA = -4 ; function prologue: addiu $sp, -0x28 sw $ra, 0x28+saved_RA($sp) sw $fp, 0x28+saved_FP($sp) move $fp, $sp ; initialize counter at 2 and store this value in local stack li $v0, 2 sw $v0, 0x28+i($fp) ; pseudoinstruction. "BEQ $ZERO, $ZERO, loc_9C" there in fact: b loc_9C or $at, $zero ; branch delay slot, NOP # --------------------------------------------------------------------------- loc_80: # CODE XREF: main+48 ; load counter value from local stack and call printing_function(): lw $a0, 0x28+i($fp) jal printing_function or $at, $zero ; branch delay slot, NOP ; load counter, increment it, store it back: lw $v0, 0x28+i($fp) or $at, $zero ; NOP addiu $v0, 1 sw $v0, 0x28+i($fp) loc_9C: # CODE XREF: main+18 ; check counter, is it 10? lw $v0, 0x28+i($fp) or $at, $zero ; NOP slti $v0, 0xA ; if it is less than 10, jump to loc_80 (loop body begin): bnez $v0, loc_80 or $at, $zero ; branch delay slot, NOP ; finishing, return 0: move $v0, $zero ; function epilogue: move $sp, $fp 178
  • 203. CHAPTER 14. LOOPS 14.2. MEMORY BLOCKS COPYING ROUTINE lw $ra, 0x28+saved_RA($sp) lw $fp, 0x28+saved_FP($sp) addiu $sp, 0x28 jr $ra or $at, $zero ; branch delay slot, NOP The instruction that’s new to us is “B”. It is actually the pseudoinstruction (BEQ). 14.1.6 One more thing In the generated code we can see: after initializing i , the body of the loop is not to be executed, as the condition for i is checked first, and only after that loop body can be executed. And that is correct. Because, if the loop condition is not met at the beginning, the body of the loop must not be executed. This is possible in the following case: for (i=0; i<total_entries_to_process; i++) loop_body; If total_entries_to_process is 0, the body of the loo must not be executed at all. This is why the condition checked before the execution. However, an optimizing compiler may swap the condition check and loop body, if it sure that the situation described here is not possible (like in the case of our very simple example and Keil, Xcode (LLVM), MSVC in optimization mode). 14.2 Memory blocks copying routine Real-world memory copy routines may copy 4 or 8 bytes at each iteration, use SIMD2 , vectorization, etc. But for the sake of simplicity, this example is the simplest possible. #include <stdio.h> void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt) { size_t i; for (i=0; i<cnt; i++) dst[i]=src[i]; }; 14.2.1 Straight-forward implementation Listing 14.10: GCC 4.9 x64 optimized for size (-Os) my_memcpy: ; RDI = destination address ; RSI = source address ; RDX = size of block ; initialize counter (i) at 0 xor eax, eax .L2: ; all bytes copied? exit then: cmp rax, rdx je .L5 ; load byte at RSI+i: mov cl, BYTE PTR [rsi+rax] ; store byte at RDI+i: mov BYTE PTR [rdi+rax], cl inc rax ; i++ jmp .L2 .L5: ret Listing 14.11: GCC 4.9 ARM64 optimized for size (-Os) my_memcpy: ; X0 = destination address ; X1 = source address 2Single instruction, multiple data 179
  • 204. CHAPTER 14. LOOPS 14.2. MEMORY BLOCKS COPYING ROUTINE ; X2 = size of block ; initialize counter (i) at 0 mov x3, 0 .L2: ; all bytes copied? exit then: cmp x3, x2 beq .L5 ; load byte at X1+i: ldrb w4, [x1,x3] ; store byte at X1+i: strb w4, [x0,x3] add x3, x3, 1 ; i++ b .L2 .L5: ret Listing 14.12: Optimizing Keil 6/2013 (thumb mode) my_memcpy PROC ; R0 = destination address ; R1 = source address ; R2 = size of block PUSH {r4,lr} ; initialize counter (i) at 0 MOVS r3,#0 ; condition checked at the end of function, so jump there: B |L0.12| |L0.6| ; load byte at R1+i: LDRB r4,[r1,r3] ; store byte at R1+i: STRB r4,[r0,r3] ; i++ ADDS r3,r3,#1 |L0.12| ; i<size? CMP r3,r2 ; jump to the loop begin if its so:' BCC |L0.6| POP {r4,pc} ENDP 14.2.2 ARM in ARM mode Keil in ARM mode takes full advantage of conditional suffixes: Listing 14.13: Optimizing Keil 6/2013 (ARM mode) my_memcpy PROC ; R0 = destination address ; R1 = source address ; R2 = size of block ; initialize counter (i) at 0 MOV r3,#0 |L0.4| ; all bytes copied? CMP r3,r2 ; the following block is executed only if "less than" condition, ; i.e., if R2<R3 or i<size. ; load byte at R1+i: LDRBCC r12,[r1,r3] ; store byte at R1+i: STRBCC r12,[r0,r3] ; i++ ADDCC r3,r3,#1 ; the last instruction of the "conditional block". 180
  • 205. CHAPTER 14. LOOPS 14.3. CONCLUSION ; jump to loop begin if i<size ; do nothing otherwise (i.e., if i>=size) BCC |L0.4| ; return BX lr ENDP That’s why there is only one branch instruction instead of 2. 14.2.3 MIPS Listing 14.14: GCC 4.4.5 optimized for size (-Os) (IDA) my_memcpy: ; jump to loop check part: b loc_14 ; initialize counter (i) at 0 ; it will always reside in $v0: move $v0, $zero ; branch delay slot loc_8: # CODE XREF: my_memcpy+1C ; load byte as unsigned at address in $t0 to $v1: lbu $v1, 0($t0) ; increment counter (i): addiu $v0, 1 ; store byte at $a3 sb $v1, 0($a3) loc_14: # CODE XREF: my_memcpy ; check if counter (i) in $v0 is still less then 3rd function argument ("cnt" in $a2): sltu $v1, $v0, $a2 ; form address of byte in source block: addu $t0, $a1, $v0 ; $t0 = $a1+$v0 = src+i ; jump to loop body if counter sill less then "cnt": bnez $v1, loc_8 ; form address of byte in destination block ($a3 = $a0+$v0 = dst+i): addu $a3, $a0, $v0 ; branch delay slot ; finish if BNEZ wasnt triggered:' jr $ra or $at, $zero ; branch delay slot, NOP Here we have two new instructions: LBU (“Load Byte Unsigned”) and SB (“Store Byte”). Just like in ARM, all MIPS registers are 32-bit wide, there are no byte-wide parts like in x86. So when dealing with single bytes, we have to allocate whole 32-bit registers for them. LBU loads a byte and clears all other bits (“Unsigned”). On the other hand, LB (“Load Byte”) instruction sign-extends the loaded byte to a 32-bit value. SB just writes a byte from lowest 8 bits of register to memory. 14.2.4 Vectorization Optimizing GCC can do much more on this example: 25.1.2 on page 419. 14.3 Conclusion Rough skeleton of loop from 2 to 9 inclusive: Listing 14.15: x86 mov [counter], 2 ; initialization jmp check body: ; loop body ; do something here ; use counter variable in local stack add [counter], 1 ; increment check: cmp [counter], 9 jle body 181
  • 206. CHAPTER 14. LOOPS 14.3. CONCLUSION The increment operation may be represented as 3 instructions in non-optimized code: Listing 14.16: x86 MOV [counter], 2 ; initialization JMP check body: ; loop body ; do something here ; use counter variable in local stack MOV REG, [counter] ; increment INC REG MOV [counter], REG check: CMP [counter], 9 JLE body If the body of the loop is short, a whole register can be dedicated to the counter variable: Listing 14.17: x86 MOV EBX, 2 ; initialization JMP check body: ; loop body ; do something here ; use counter in EBX, but do not modify it! INC EBX ; increment check: CMP EBX, 9 JLE body Some parts of the loop may be generated by compiler in different order: Listing 14.18: x86 MOV [counter], 2 ; initialization JMP label_check label_increment: ADD [counter], 1 ; increment label_check: CMP [counter], 10 JGE exit ; loop body ; do something here ; use counter variable in local stack JMP label_increment exit: Usually the condition is checked before loop body, but the compiler may rearrange it in a way that the condition is checked after loop body. This is done when the compiler is sure that the condition is always true on the first iteration, so the body of the loop is to be executed at least once: Listing 14.19: x86 MOV REG, 2 ; initialization body: ; loop body ; do something here ; use counter in REG, but do not modify it! INC REG ; increment CMP REG, 10 JL body Using the LOOP instruction. This is rare, compilers are not using it. When you see it, it’s a sign that this piece of code is hand-written: Listing 14.20: x86 ; count from 10 to 1 MOV ECX, 10 body: ; loop body ; do something here 182
  • 207. CHAPTER 14. LOOPS 14.4. EXERCISES ; use counter in ECX, but do not modify it! LOOP body ARM. The R4 register is dedicated to counter variable in this example: Listing 14.21: ARM MOV R4, 2 ; initialization B check body: ; loop body ; do something here ; use counter in R4, but do not modify it! ADD R4,R4, #1 ; increment check: CMP R4, #10 BLT body 14.4 Exercises 14.4.1 Exercise #1 Why isn’t the LOOP instruction used by modern compilers anymore? 14.4.2 Exercise #2 Take a loop example from this section ( 14.1.1 on page 169), compile it in your favorite OS and compiler and modify (patch) the executable file so the loop range will be [6..20]. 14.4.3 Exercise #3 What does this code do? Listing 14.22: Optimizing MSVC 2010 $SG2795 DB '%d', 0aH, 00H _main PROC push esi push edi mov edi, DWORD PTR __imp__printf mov esi, 100 npad 3 ; align next label $LL3@main: push esi push OFFSET $SG2795 ; '%d' call edi dec esi add esp, 8 test esi, esi jg SHORT $LL3@main pop edi xor eax, eax pop esi ret 0 _main ENDP Listing 14.23: Non-optimizing Keil 6/2013 (ARM mode) main PROC PUSH {r4,lr} MOV r4,#0x64 |L0.8| MOV r1,r4 ADR r0,|L0.40| BL __2printf SUB r4,r4,#1 CMP r4,#0 183
  • 208. CHAPTER 14. LOOPS 14.4. EXERCISES MOVLE r0,#0 BGT |L0.8| POP {r4,pc} ENDP |L0.40| DCB "%dn",0 Listing 14.24: Non-optimizing Keil 6/2013 (thumb mode) main PROC PUSH {r4,lr} MOVS r4,#0x64 |L0.4| MOVS r1,r4 ADR r0,|L0.24| BL __2printf SUBS r4,r4,#1 CMP r4,#0 BGT |L0.4| MOVS r0,#0 POP {r4,pc} ENDP DCW 0x0000 |L0.24| DCB "%dn",0 Listing 14.25: Optimizing GCC 4.9 (ARM64) main: stp x29, x30, [sp, -32]! add x29, sp, 0 stp x19, x20, [sp,16] adrp x20, .LC0 mov w19, 100 add x20, x20, :lo12:.LC0 .L2: mov w1, w19 mov x0, x20 bl printf subs w19, w19, #1 bne .L2 ldp x19, x20, [sp,16] ldp x29, x30, [sp], 32 ret .LC0: .string "%dn" Listing 14.26: Optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s1, 0x28+var_8($sp) sw $s0, 0x28+var_C($sp) sw $gp, 0x28+var_18($sp) la $s1, $LC0 # "%dn" li $s0, 0x64 # 'd' loc_28: # CODE XREF: main+40 lw $t9, (printf & 0xFFFF)($gp) 184
  • 209. CHAPTER 14. LOOPS 14.4. EXERCISES move $a1, $s0 move $a0, $s1 jalr $t9 addiu $s0, -1 lw $gp, 0x28+var_18($sp) bnez $s0, loc_28 or $at, $zero lw $ra, 0x28+var_4($sp) lw $s1, 0x28+var_8($sp) lw $s0, 0x28+var_C($sp) jr $ra addiu $sp, 0x28 $LC0: .ascii "%dn"<0> # DATA XREF: main+1C Answer: G.1.5 on page 954. 14.4.4 Exercise #4 What does this code do? Listing 14.27: Optimizing MSVC 2010 $SG2795 DB '%d', 0aH, 00H _main PROC push esi push edi mov edi, DWORD PTR __imp__printf mov esi, 1 npad 3 ; align next label $LL3@main: push esi push OFFSET $SG2795 ; '%d' call edi add esi, 3 add esp, 8 cmp esi, 100 jl SHORT $LL3@main pop edi xor eax, eax pop esi ret 0 _main ENDP Listing 14.28: Non-optimizing Keil 6/2013 (ARM mode) main PROC PUSH {r4,lr} MOV r4,#1 |L0.8| MOV r1,r4 ADR r0,|L0.40| BL __2printf ADD r4,r4,#3 CMP r4,#0x64 MOVGE r0,#0 BLT |L0.8| POP {r4,pc} ENDP |L0.40| DCB "%dn",0 Listing 14.29: Non-optimizing Keil 6/2013 (thumb mode) main PROC PUSH {r4,lr} MOVS r4,#1 |L0.4| 185
  • 210. CHAPTER 14. LOOPS 14.4. EXERCISES MOVS r1,r4 ADR r0,|L0.24| BL __2printf ADDS r4,r4,#3 CMP r4,#0x64 BLT |L0.4| MOVS r0,#0 POP {r4,pc} ENDP DCW 0x0000 |L0.24| DCB "%dn",0 Listing 14.30: Optimizing GCC 4.9 (ARM64) main: stp x29, x30, [sp, -32]! add x29, sp, 0 stp x19, x20, [sp,16] adrp x20, .LC0 mov w19, 1 add x20, x20, :lo12:.LC0 .L2: mov w1, w19 mov x0, x20 add w19, w19, 3 bl printf cmp w19, 100 bne .L2 ldp x19, x20, [sp,16] ldp x29, x30, [sp], 32 ret .LC0: .string "%dn" Listing 14.31: Optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s2, 0x28+var_8($sp) sw $s1, 0x28+var_C($sp) sw $s0, 0x28+var_10($sp) sw $gp, 0x28+var_18($sp) la $s2, $LC0 # "%dn" li $s0, 1 li $s1, 0x64 # 'd' loc_30: # CODE XREF: main+48 lw $t9, (printf & 0xFFFF)($gp) move $a1, $s0 move $a0, $s2 jalr $t9 addiu $s0, 3 lw $gp, 0x28+var_18($sp) bne $s0, $s1, loc_30 or $at, $zero lw $ra, 0x28+var_4($sp) lw $s2, 0x28+var_8($sp) lw $s1, 0x28+var_C($sp) 186
  • 211. CHAPTER 14. LOOPS 14.4. EXERCISES lw $s0, 0x28+var_10($sp) jr $ra addiu $sp, 0x28 $LC0: .ascii "%dn"<0> # DATA XREF: main+20 Answer: G.1.6 on page 955. 187
  • 212. CHAPTER 15. SIMPLE C-STRINGS PROCESSING Chapter 15 Simple C-strings processing 15.1 strlen() Let’s talk about loops one more time. Often, the strlen() function1 is implemented using a while() statement. Here is how it is done in the MSVC standard libraries: int my_strlen (const char * str) { const char *eos = str; while( *eos++ ) ; return( eos - str - 1 ); } int main() { // test return my_strlen("hello!"); }; 15.1.1 x86 Non-optimizing MSVC Let’s compile: _eos$ = -4 ; size = 4 _str$ = 8 ; size = 4 _strlen PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _str$[ebp] ; place pointer to string from "str" mov DWORD PTR _eos$[ebp], eax ; place it to local variable "eos" $LN2@strlen_: mov ecx, DWORD PTR _eos$[ebp] ; ECX=eos ; take 8-bit byte from address in ECX and place it as 32-bit value to EDX with sign extension movsx edx, BYTE PTR [ecx] mov eax, DWORD PTR _eos$[ebp] ; EAX=eos add eax, 1 ; increment EAX mov DWORD PTR _eos$[ebp], eax ; place EAX back to "eos" test edx, edx ; EDX is zero? je SHORT $LN1@strlen_ ; yes, then finish loop jmp SHORT $LN2@strlen_ ; continue loop $LN1@strlen_: ; here we calculate the difference between two pointers mov eax, DWORD PTR _eos$[ebp] 1counting the characters in a string in the C language 188
  • 213. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() sub eax, DWORD PTR _str$[ebp] sub eax, 1 ; subtract 1 and return result mov esp, ebp pop ebp ret 0 _strlen_ ENDP We get two new instructions here: MOVSX and TEST. The first one — MOVSX — takes a byte from an address in memory and stores the value in a 32-bit register. MOVSX stands for MOV with Sign-Extend. MOVSX sets the rest of the bits, from the 8th to the 31th, to 1 if the source byte is negative or to 0 if is positive. And here is why. By default, the char type is signed in MSVC and GCC. If we have two values of which one is char and the other is int, (int is signed too), and if the first value contain −2 (coded as 0xFE) and we just copy this byte into the int container, it makes 0x000000FE, and this from the point of signed int view is 254, but not −2. In signed int, −2 is coded as 0xFFFFFFFE. So if we need to transfer 0xFE from a variable of char type to int, we need to identify its sign and extend it. That is what MOVSX does. You can also read about it in “Signed number representations” section ( 30 on page 451). I’m not sure if the compiler needs to store a char variable in EDX, it could just take a 8-bit register part (for example DL). Apparently, the compiler’s register allocator works like that. Then we see TEST EDX, EDX. You can read more about the TEST instruction in the section about bit fields ( 19 on page 305). Here this instruction just checks if the value in EDX equals to 0. Non-optimizing GCC Let’s try GCC 4.4.1: public strlen strlen proc near eos = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 10h mov eax, [ebp+arg_0] mov [ebp+eos], eax loc_80483F0: mov eax, [ebp+eos] movzx eax, byte ptr [eax] test al, al setnz al add [ebp+eos], 1 test al, al jnz short loc_80483F0 mov edx, [ebp+eos] mov eax, [ebp+arg_0] mov ecx, edx sub ecx, eax mov eax, ecx sub eax, 1 leave retn strlen endp The result is almost the same as in MSVC, but here we see MOVZX instead of MOVSX. MOVZX stands for MOV with Zero- Extend. This instruction copies a 8-bit or 16-bit value into a 32-bit register and sets the rest of the bits to 0. In fact, this instruction is convenient only because it enable us to replace this instruction pair: xor eax, eax / mov al, [...]. On the other hand, it is obvious that the compiler could produce this code: mov al, byte ptr [eax] / test al, al —it is almost the same, however, the highest bits of the EAX register will contain random noise. But let’s think it is compiler’s drawback —it cannot produce more understandable code. Strictly speaking, the compiler is not obliged to emit understandable (to humans) code at all. The next new instruction for us is SETNZ. Here, if AL doesn’t contain zero, test al, al sets the ZF flag to 0, but SETNZ, if ZF==0 (NZ stands for not zero) sets AL to 1. Speaking in natural language, if AL is not zero, let’s jump to loc_80483F0. The compiler emits some redundant code, but let’s not forget that the optimizations are turned off. 189
  • 214. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() Optimizing MSVC Now let’s compile all this in MSVC 2012, with optimizations turned on (/Ox): Listing 15.1: Optimizing MSVC 2012 /Ob0 _str$ = 8 ; size = 4 _strlen PROC mov edx, DWORD PTR _str$[esp-4] ; EDX -> pointer to the string mov eax, edx ; move to EAX $LL2@strlen: mov cl, BYTE PTR [eax] ; CL = *EAX inc eax ; EAX++ test cl, cl ; CL==0? jne SHORT $LL2@strlen ; no, continue loop sub eax, edx ; calculate pointers difference dec eax ; decrement EAX ret 0 _strlen ENDP Now it is all simpler. Needless to say, the compiler could use registers with such efficiency only in small functions with a few local variables. INC/DEC— are increment/decrement instructions, in other words: add or substract 1 to/from a variable. 190
  • 215. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() Optimizing MSVC + OllyDbg We can try this (optimized) example in OllyDbg. Here is the first iteration: Figure 15.1: OllyDbg: first iteration start We see that OllyDbg found a loop and, for convenience, wrapped its instructions in brackets. By clicking the right button on EAX, we can choose “Follow in Dump” and the memory window scrolls to the right place. Here we can see the string “hello!” in memory. There is at least one zero byte after it and then random garbage. If OllyDbg sees a register with a valid address in it, that points to some string, it is shown as a string. 191
  • 216. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() Let’s press F8 (step over) a few times, to get to the start of the body of the loop: Figure 15.2: OllyDbg: second iteration start We see that EAX contains the address of the second character in the string. 192
  • 217. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() We have to press F8 enough number of times in order to escape from the loop: Figure 15.3: OllyDbg: pointers difference to be calculated now We see that EAX now contains the address of zero byte that’s right after the string. Meanwhile, EDX hasn’t changed, so it still pointing to the start of the string. The difference between these two addresses is being calculated now. 193
  • 218. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() The SUB instruction just got executed: Figure 15.4: OllyDbg: EAX to be decremented now The difference of pointers is in the EAX register now—7. Indeed, the length of the “hello!” string is 6, but with the zero byte included—7. But strlen() must return the number of non-zero characters in the string. So the decrement executes and then the function returns. Optimizing GCC Let’s check GCC 4.4.1 with optimizations turned on (-O3 key): public strlen strlen proc near arg_0 = dword ptr 8 push ebp mov ebp, esp mov ecx, [ebp+arg_0] mov eax, ecx loc_8048418: movzx edx, byte ptr [eax] add eax, 1 test dl, dl jnz short loc_8048418 not ecx add eax, ecx pop ebp retn strlen endp Here GCC is almost the same as MSVC, except for the presence of MOVZX. However, here MOVZX could be replaced with mov dl, byte ptr [eax]. Probably it is simpler for GCC’s code generator to remember the whole 32-bit EDX register is allocated for a char variable and it then can be sure that the highest bits has no any noise at any point. After that we also see a new instruction — NOT. This instruction inverts all bits in the operand. You can say that it is a synonym to the XOR ECX, 0ffffffffh instruction. NOT and the following ADD calculate the pointer difference and subtract 1, just in a different way. At the start ECX, where the pointer to str is stored, gets inverted and 1 is subtracted from it. See also: “Signed number representations” ( 30 on page 451). In other words, at the end of the function just after loop body, these operations are executed: 194
  • 219. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() ecx=str; eax=eos; ecx=(-ecx)-1; eax=eax+ecx return eax …and this is effectively equivalent to: ecx=str; eax=eos; eax=eax-ecx; eax=eax-1; return eax Why did GCC decide it would be better? I cannot be sure. But I’m sure the both variants are equivalent in efficiency. 15.1.2 ARM 32-bit ARM Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) Listing 15.2: Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) _strlen eos = -8 str = -4 SUB SP, SP, #8 ; allocate 8 bytes for local variables STR R0, [SP,#8+str] LDR R0, [SP,#8+str] STR R0, [SP,#8+eos] loc_2CB8 ; CODE XREF: _strlen+28 LDR R0, [SP,#8+eos] ADD R1, R0, #1 STR R1, [SP,#8+eos] LDRSB R0, [R0] CMP R0, #0 BEQ loc_2CD4 B loc_2CB8 loc_2CD4 ; CODE XREF: _strlen+24 LDR R0, [SP,#8+eos] LDR R1, [SP,#8+str] SUB R0, R0, R1 ; R0=eos-str SUB R0, R0, #1 ; R0=R0-1 ADD SP, SP, #8 ; free allocated 8 bytes BX LR Non-optimizing LLVM generates too much code, however, here we can see how the function works with local variables in the stack. There are only two local variables in our function, eos and str. In this listing, generated by IDA, I have manually renamed var_8 and var_4 to eos and str . The first instructions just saves the input values into both str and eos. The body of the loop starts at label loc_2CB8. The first three instruction in the loop body (LDR, ADD, STR) load the value of eos into R0, then the value is incremented and saved back into eos, which is located in the stack. The next instruction, ``LDRSB R0, [R0]'' (Load Register Signed Byte) , loads a byte from memory at the address stored in R0 and sign-extends it to 32-bit 2 . This is similar to the MOVSX instruction in x86. The compiler treats this byte as signed since the char type is signed according to the C standard. I already wrote about it ( 15.1.1 on page 189) in this section, in relation to x86. It has to be noted that it is impossible to use 8- or 16-bit part of a 32-bit register in ARM separately of the whole register, as it is in x86. Apparently, it is because x86 has a huge history of backwards compatibility with its ancestors up to the 16-bit 8086 and even 8-bit 8080, but ARM was developed from scratch as a 32-bit RISC-processor. Consequently, in order to process separate bytes in ARM, one has to use 32-bit registers anyway. 2The Keil compiler treats the char type as signed, just like MSVC and GCC. 195
  • 220. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() So, LDRSB loads bytes from the string into R0, one by one. The following CMP and BEQ instructions check if the loaded byte is 0. If it’s not 0, control passes to the start of the body of the loop. And if it’s 0, the loop ends. At the end of the function, the difference between eos and str is calculated, 1 is subtracted from it, and resulting value is returned via R0. N.B. Registers were not saved in this function. That’s because in the ARM calling convention registers R0-R3 are “scratch registers”, intended for arguments passing, and we’re not required to restore their value when the function exits, since the calling function will not use them anymore. Consequently, they may be used for anything we want. No other registers are used here, so that is why we have nothing to save on the stack. Thus, control may be returned back to calling function by a simple jump (BX), to the address in the LR register. Optimizing Xcode 4.6.3 (LLVM) (thumb mode) Listing 15.3: Optimizing Xcode 4.6.3 (LLVM) (thumb mode) _strlen MOV R1, R0 loc_2DF6 LDRB.W R2, [R1],#1 CMP R2, #0 BNE loc_2DF6 MVNS R0, R0 ADD R0, R1 BX LR As optimizing LLVM concludes, eos and str do not need space on the stack, and can always be stored in registers. Before the start of the loop body, str is always in R0, and eos—in R1. The ``LDRB.W R2, [R1],#1'' instruction loads a byte from the memory at the address stored in R1, to R2, sign- extending it to a 32-bit value, but not just that. #1 at the instruction’s end is implies “Post-indexed addressing”, which means that 1 is to be added to R1 after the byte is loaded. Read more about it: 28.2 on page 445. Then you can see CMP and BNE3 in the body of the loop, these instructions continue looping until 0 is found in the string. MVNS4 (inverts all bits, like NOT in x86) and ADD instructions compute eos − str − 1. In fact, these two instructions compute R0 = str+eos, which is effectively equivalent to what was in the source code, and why it is so, I already explained here ( 15.1.1 on page 194). Apparently, LLVM, just like GCC, concludes that this code can be shorter (or faster). Optimizing Keil 6/2013 (ARM mode) Listing 15.4: Optimizing Keil 6/2013 (ARM mode) _strlen MOV R1, R0 loc_2C8 LDRB R2, [R1],#1 CMP R2, #0 SUBEQ R0, R1, R0 SUBEQ R0, R0, #1 BNE loc_2C8 BX LR Almost the same as what we saw before, with the exception that the str − eos − 1 expression can be computed not at the function’s end, but right in the body of the loop. The -EQ suffix, as we may recall, implies that the instruction executes only if the operands in the CMP that was executed before were equal to each other. Thus, if R0 contains 0, both SUBEQ instructions executes and result is left in the R0 register. ARM64 Optimizing GCC (Linaro) 4.9 3(PowerPC, ARM) Branch if Not Equal 4MoVe Not 196
  • 221. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.1. STRLEN() my_strlen: mov x1, x0 ; X1 is now temporary pointer (eos), acting like cursor .L58: ; load byte from X1 to W2, increment X1 (post-index) ldrb w2, [x1],1 ; Compare and Branch if NonZero: compare W2 with 0, jump to .L58 if it is not cbnz w2, .L58 ; calculate difference between initial pointer in X0 and current address in X1 sub x0, x1, x0 ; decrement lowest 32-bit of result sub w0, w0, #1 ret The algorithm is the same as in 15.1.1 on page 190: find a zero byte, calculate the difference between the pointers and decrement the result by 1. I have added some comments. The only thing worth noting is that my example is somewhat wrong: my_strlen() returns 32-bit int, while it has to return size_t or another 64-bit type. The reason is that, theoretically, strlen() can be called for a huge blocks in memory that exceeds 4GB, so it must able to return a 64-bit value on 64-bit platforms. Because of my mistake, the last SUB instruction operates on a 32-bit part of register, while the penultimate SUB instruction works on full the 64-bit register (it calculates the difference between the pointers). It’s my mistake, but I have decided to leave it as is, as an example of how the code could look like in such case. Non-optimizing GCC (Linaro) 4.9 my_strlen: ; function prologue sub sp, sp, #32 ; first argument (str) will be stored in [sp,8] str x0, [sp,8] ldr x0, [sp,8] ; copy "str" to "eos" variable str x0, [sp,24] nop .L62: ; eos++ ldr x0, [sp,24] ; load "eos" to X0 add x1, x0, 1 ; increment X0 str x1, [sp,24] ; save X0 to "eos" ; load byte from memory at address in X0 to W0 ldrb w0, [x0] ; is it zero? (WZR is the 32-bit register always contain zero) cmp w0, wzr ; jump if not zero (Branch Not Equal) bne .L62 ; zero byte found. now calculate difference. ; load "eos" to X1 ldr x1, [sp,24] ; load "str" to X0 ldr x0, [sp,8] ; calculate difference sub x0, x1, x0 ; decrement result sub w0, w0, #1 ; function epilogue add sp, sp, 32 ret It’s more verbose. The variables are often tossed here to and from memory (local stack). The same mistake here: the decrement operation happens on a 32-bit register part. 15.1.3 MIPS Listing 15.5: Optimizing GCC 4.4.5 (IDA) my_strlen: ; "eos" variable will always reside in $v1: move $v1, $a0 197
  • 222. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES loc_4: ; load byte at address in "eos" into $a1: lb $a1, 0($v1) or $at, $zero ; load delay slot, NOP ; if loaded byte is not zero, jump to loc_4: bnez $a1, loc_4 ; increment "eos" anyway: addiu $v1, 1 ; branch delay slot ; loop finished. invert "str" variable: nor $v0, $zero, $a0 ; $v0=-str-1 jr $ra ; return value = $v1 + $v0 = eos + ( -str-1 ) = eos - str - 1 addu $v0, $v1, $v0 ; branch delay slot MIPS lacks a “NOT” instruction, but has “NOR” which is OR + NOT operation. This operation is widely used in digital electronics5 , but isn’t very popular in computer programming. So, the NOT operation is implemented here as “NOR DST, $ZERO, SRC”. From fundamentals 30 on page 451 we know that bitwise inverting a signed number is the same as changing its sign and subtracting 1 from the result. So what NOT does here is to take the value of str and transform it into −str − 1. The addition operation that follows prepares result. 15.2 Exercises 15.2.1 Exercise #1 What does this code do? Listing 15.6: Optimizing MSVC 2010 _s$ = 8 _f PROC mov edx, DWORD PTR _s$[esp-4] mov cl, BYTE PTR [edx] xor eax, eax test cl, cl je SHORT $LN2@f npad 4 ; align next label $LL4@f: cmp cl, 32 jne SHORT $LN3@f inc eax $LN3@f: mov cl, BYTE PTR [edx+1] inc edx test cl, cl jne SHORT $LL4@f $LN2@f: ret 0 _f ENDP Listing 15.7: GCC 4.8.1 -O3 f: .LFB24: push ebx mov ecx, DWORD PTR [esp+8] xor eax, eax movzx edx, BYTE PTR [ecx] test dl, dl je .L2 .L3: cmp dl, 32 lea ebx, [eax+1] cmove eax, ebx 5NOR is called “universal gate”. For example, the Apollo Guidance Computer used in the Apollo program, was built by only using 5600 NOR gates: [Eic11]. 198
  • 223. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES add ecx, 1 movzx edx, BYTE PTR [ecx] test dl, dl jne .L3 .L2: pop ebx ret Listing 15.8: Optimizing Keil 6/2013 (ARM mode) f PROC MOV r1,#0 |L0.4| LDRB r2,[r0,#0] CMP r2,#0 MOVEQ r0,r1 BXEQ lr CMP r2,#0x20 ADDEQ r1,r1,#1 ADD r0,r0,#1 B |L0.4| ENDP Listing 15.9: Optimizing Keil 6/2013 (thumb mode) f PROC MOVS r1,#0 B |L0.12| |L0.4| CMP r2,#0x20 BNE |L0.10| ADDS r1,r1,#1 |L0.10| ADDS r0,r0,#1 |L0.12| LDRB r2,[r0,#0] CMP r2,#0 BNE |L0.4| MOVS r0,r1 BX lr ENDP Listing 15.10: Optimizing GCC 4.9 (ARM64) f: ldrb w1, [x0] cbz w1, .L4 mov w2, 0 .L3: cmp w1, 32 ldrb w1, [x0,1]! csinc w2, w2, w2, ne cbnz w1, .L3 .L2: mov w0, w2 ret .L4: mov w2, w1 b .L2 Listing 15.11: Optimizing GCC 4.4.5 (MIPS) (IDA) f: lb $v1, 0($a0) or $at, $zero beqz $v1, locret_48 li $a1, 0x20 # ' ' b loc_28 move $v0, $zero loc_18: # CODE XREF: f:loc_28 199
  • 224. CHAPTER 15. SIMPLE C-STRINGS PROCESSING 15.2. EXERCISES lb $v1, 0($a0) or $at, $zero beqz $v1, locret_40 or $at, $zero loc_28: # CODE XREF: f+10 # f+38 bne $v1, $a1, loc_18 addiu $a0, 1 lb $v1, 0($a0) or $at, $zero bnez $v1, loc_28 addiu $v0, 1 locret_40: # CODE XREF: f+20 jr $ra or $at, $zero locret_48: # CODE XREF: f+8 jr $ra move $v0, $zero Answer G.1.7 on page 955. 200
  • 225. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES Chapter 16 Replacing arithmetic instructions to other ones In the pursuit of optimization, one instruction may be replaced by others, or even with a group of instructions. For example, the LEA instruction is often used for simple arithmetic calculations: A.6.2 on page 933. ADD and SUB can replace each other. For example, line 18 in listing.52.1. 16.1 Multiplication 16.1.1 Multiplication using addition Here is a simple example: Listing 16.1: Optimizing MSVC 2010 unsigned int f(unsigned int a) { return a*8; }; Multiplication by 8 is replaced by 3 addition instructions, which do the same. Apparently, MSVC’s optimizer decided that this code can be faster. _TEXT SEGMENT _a$ = 8 ; size = 4 _f PROC ; File c:polygonc2.c mov eax, DWORD PTR _a$[esp-4] add eax, eax add eax, eax add eax, eax ret 0 _f ENDP _TEXT ENDS END 16.1.2 Multiplication using shifting Multiplication and division instructions by a numbers that’s a power of 2 are often replaced by shift instructions. unsigned int f(unsigned int a) { return a*4; }; Listing 16.2: Non-optimizing MSVC 2010 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] shl eax, 2 pop ebp ret 0 _f ENDP 201
  • 226. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION Multiplication by 4 is just shifting the number to the left by 2 bits and inserting 2 zero bits at the right (as the last two bits). It is just like multiplying 3 by 100 —we need to just add two zeroes at the right. That’s how the shift left instruction works: ..7. 6. 5. 4. 3. 2. 1. 0.. 7 . 6 . 5 . 4 . 3 . 2 . 1 . 0 . CF . 0 The added bits at right are always zeroes. Multiplication by 4 in ARM: Listing 16.3: Non-optimizing Keil 6/2013 (ARM mode) f PROC LSL r0,r0,#2 BX lr ENDP Multiplication by 4 in MIPS: Listing 16.4: Optimizing GCC 4.4.5 (IDA) jr $ra sll $v0, $a0, 2 ; branch delay slot SLL is “Shift Left Logical” 16.1.3 Multiplication using shifting/subtracting/adding It’s still possible to get rid of the multiplication operation when you multiply by numbers like 7 or 17 again by using shifting. The mathematics used here is relatively easy. 32-bit #include <stdint.h> int f1(int a) { return a*7; }; int f2(int a) { return a*28; }; int f3(int a) { return a*17; }; x86 Listing 16.5: Optimizing MSVC 2012 ; a*7 _a$ = 8 _f1 PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=a lea eax, DWORD PTR [ecx*8] ; EAX=ECX*8 sub eax, ecx ; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7 ret 0 _f1 ENDP 202
  • 227. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION ; a*28 _a$ = 8 _f2 PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=a lea eax, DWORD PTR [ecx*8] ; EAX=ECX*8 sub eax, ecx ; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7 shl eax, 2 ; EAX=EAX<<2=(a*7)*4=a*28 ret 0 _f2 ENDP ; a*17 _a$ = 8 _f3 PROC mov eax, DWORD PTR _a$[esp-4] ; EAX=a shl eax, 4 ; EAX=EAX<<4=EAX*16=a*16 add eax, DWORD PTR _a$[esp-4] ; EAX=EAX+a=a*16+a=a*17 ret 0 _f3 ENDP ARM Keil for ARM mode takes advantage of the second operand’s shift modifiers: Listing 16.6: Optimizing Keil 6/2013 (ARM mode) ; a*7 ||f1|| PROC RSB r0,r0,r0,LSL #3 ; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7 BX lr ENDP ; a*28 ||f2|| PROC RSB r0,r0,r0,LSL #3 ; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7 LSL r0,r0,#2 ; R0=R0<<2=R0*4=a*7*4=a*28 BX lr ENDP ; a*17 ||f3|| PROC ADD r0,r0,r0,LSL #4 ; R0=R0+R0<<4=R0+R0*16=R0*17=a*17 BX lr ENDP But there are no such modifiers in Thumb mode. It also can’t optimize f2(): Listing 16.7: Optimizing Keil 6/2013 (thumb mode) ; a*7 ||f1|| PROC LSLS r1,r0,#3 ; R1=R0<<3=a<<3=a*8 SUBS r0,r1,r0 ; R0=R1-R0=a*8-a=a*7 BX lr ENDP ; a*28 203
  • 228. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.1. MULTIPLICATION ||f2|| PROC MOVS r1,#0x1c ; 28 ; R1=28 MULS r0,r1,r0 ; R0=R1*R0=28*a BX lr ENDP ; a*17 ||f3|| PROC LSLS r1,r0,#4 ; R1=R0<<4=R0*16=a*16 ADDS r0,r0,r1 ; R0=R0+R1=a+a*16=a*17 BX lr ENDP MIPS Listing 16.8: Optimizing GCC 4.4.5 (IDA) _f1: sll $v0, $a0, 3 ; $v0 = $a0<<3 = $a0*8 jr $ra subu $v0, $a0 ; branch delay slot ; $v0 = $v0-$a0 = $a0*8-$a0 = $a0*7 _f2: sll $v0, $a0, 5 ; $v0 = $a0<<5 = $a0*32 sll $a0, 2 ; $a0 = $a0<<2 = $a0*4 jr $ra subu $v0, $a0 ; branch delay slot ; $v0 = $a0*32-$a0*4 = $a0*28 _f3: sll $v0, $a0, 4 ; $v0 = $a0<<4 = $a0*16 jr $ra addu $v0, $a0 ; branch delay slot ; $v0 = $a0*16+$a0 = $a0*17 64-bit #include <stdint.h> int64_t f1(int64_t a) { return a*7; }; int64_t f2(int64_t a) { return a*28; }; int64_t f3(int64_t a) { return a*17; }; x64 204
  • 229. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.2. DIVISION Listing 16.9: Optimizing MSVC 2012 ; a*7 f1: lea rax, [0+rdi*8] ; RAX=RDI*8=a*8 sub rax, rdi ; RAX=RAX-RDI=a*8-a=a*7 ret ; a*28 f2: lea rax, [0+rdi*4] ; RAX=RDI*4=a*4 sal rdi, 5 ; RDI=RDI<<5=RDI*32=a*32 sub rdi, rax ; RDI=RDI-RAX=a*32-a*4=a*28 mov rax, rdi ret ; a*17 f3: mov rax, rdi sal rax, 4 ; RAX=RAX<<4=a*16 add rax, rdi ; RAX=a*16+a=a*17 ret ARM64 GCC 4.9 for ARM64 is also terse, thanks to the shift modifiers: Listing 16.10: Optimizing GCC (Linaro) 4.9 ARM64 ; a*7 f1: lsl x1, x0, 3 ; X1=X0<<3=X0*8=a*8 sub x0, x1, x0 ; X0=X1-X0=a*8-a=a*7 ret ; a*28 f2: lsl x1, x0, 5 ; X1=X0<<5=a*32 sub x0, x1, x0, lsl 2 ; X0=X1-X0<<2=a*32-a<<2=a*32-a*4=a*28 ret ; a*17 f3: add x0, x0, x0, lsl 4 ; X0=X0+X0<<4=a+a*16=a*17 ret 16.2 Division 16.2.1 Division using shifts Example: unsigned int f(unsigned int a) { return a/4; }; 205
  • 230. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.3. EXERCISES We get (MSVC 2010): Listing 16.11: MSVC 2010 _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] shr eax, 2 ret 0 _f ENDP The SHR (SHift Right) instruction in this example is shifting a number by 2 bits to the right. The two freed bits at left (e.g., two most significant bits) are set to zero. The two least significant bits are dropped. In fact, these two dropped bits are the division operation remainder. The SHR instruction works just like SHL, but in the other direction. ..7. 6. 5. 4. 3. 2. 1. 0.. 7 . 6 . 5 . 4 . 3 . 2 . 1 . 0 . 0 . CF It is easy to understand if you imagine the number 23 in the decimal numeral system. 23 can be easily divided by 10 just by dropping last digit (3 —is division remainder). 2 is left after the operation as a quotient. So the remainder is dropped, but that’s OK, we work on integer values anyway, these are not floating point numbers! Division by 4 in ARM: Listing 16.12: Non-optimizing Keil 6/2013 (ARM mode) f PROC LSR r0,r0,#2 BX lr ENDP Division by 4 in MIPS: Listing 16.13: Optimizing GCC 4.4.5 (IDA) jr $ra srl $v0, $a0, 2 ; branch delay slot The SRL instruction is “shift-right logical”. 16.3 Exercises 16.3.1 Exercise #2 What does this code do? Listing 16.14: Optimizing MSVC 2010 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] lea eax, DWORD PTR [ecx*8] sub eax, ecx ret 0 _f ENDP Listing 16.15: Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r0,r0,r0,LSL #3 BX lr ENDP 206
  • 231. CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES 16.3. EXERCISES Listing 16.16: Non-optimizing Keil 6/2013 (thumb mode) f PROC LSLS r1,r0,#3 SUBS r0,r1,r0 BX lr ENDP Listing 16.17: Optimizing GCC 4.9 (ARM64) f: lsl w1, w0, 3 sub w0, w1, w0 ret Listing 16.18: Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a0, 3 jr $ra subu $v0, $a0 Answer G.1.8 on page 955. 207
  • 232. CHAPTER 17. FLOATING-POINT UNIT Chapter 17 Floating-point unit The FPU is a device within the main CPU, specially designed to deal with floating point numbers. It was called “coprocessor” in the past and it stays somewhat aside of the main CPU. 17.1 IEEE 754 A number in the IEEE 754 format consists of a sign, a significand (also called fraction) and an exponent. 17.2 x86 It is worth looking into stack machines1 or learning the basics of the Forth language 2 , before studying the FPU in x86. It is interesting to know that in the past (before the 80486 CPU) the coprocessor was a separate chip and it was not always pre-installed on the motherboard. It was possible to buy it separately and install it 3 . Starting with the 80486 DX CPU, the FPU is integrated in the CPU. The FWAIT instruction reminds us of that fact—it switches the CPU to a waiting state, so it can wait until the FPU is done with its work. Another rudiment is the fact that the FPU instruction opcodes start with the so called “escape”-opcodes (D8..DF), i.e., opcodes passed to a separate coprocessor. The FPU has a stack capable to holding 8 80-bit registers, and each register can hold a number in the IEEE 7544 format. They are ST(0)..ST(7). For brevity, IDA and OllyDbg show ST(0) as ST, which is represented in some textbooks and manuals as “Stack Top”. 17.3 ARM, MIPS, x86/x64 SIMD In ARM and MIPS the FPU is not a stack, but a set of registers. The same ideology is used in the SIMD extensions of x86/x64 CPUs. 17.4 C/C++ The standard C/C++ languages offer at least two floating number types, float (single-precision5 , 32 bits) 6 and double (double- precision7 , 64 bits). GCC also supports the long double type (extended precision8 , 80 bit), which MSVC doesn’t. 1wikipedia 2wikipedia 3For example, John Carmack used fixed-point arithmetic (wikipedia) values in his Doom video game, stored in 32-bit GPR registers (16 bit for integral part and another 16 bit for fractional part), so Doom could work on 32-bit computers without FPU, i.e., 80386 and 80486 SX 4wikipedia 5wikipedia 6the single precision floating point number format is also addressed in the Working with the float type as with a structure ( 21.6.2 on page 376) section 7wikipedia 8wikipedia 208
  • 233. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE The float type requires the same number of bits as the int type in 32-bit environments, but the number representation is completely different. 17.5 Simple example Let’s consider this simple example: #include <stdio.h> double f (double a, double b) { return a/3.14 + b*4.1; }; int main() { printf ("%fn", f(1.2, 3.4)); }; 17.5.1 x86 MSVC Compile it in MSVC 2010: Listing 17.1: MSVC 2010: f() CONST SEGMENT __real@4010666666666666 DQ 04010666666666666r ; 4.1 CONST ENDS CONST SEGMENT __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 CONST ENDS _TEXT SEGMENT _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f PROC push ebp mov ebp, esp fld QWORD PTR _a$[ebp] ; current stack state: ST(0) = _a fdiv QWORD PTR __real@40091eb851eb851f ; current stack state: ST(0) = result of _a divided by 3.14 fld QWORD PTR _b$[ebp] ; current stack state: ST(0) = _b; ST(1) = result of _a divided by 3.14 fmul QWORD PTR __real@4010666666666666 ; current stack state: ; ST(0) = result of _b * 4.1; ; ST(1) = result of _a divided by 3.14 faddp ST(1), ST(0) ; current stack state: ST(0) = result of addition pop ebp ret 0 _f ENDP FLD takes 8 bytes from stack and loads the number into the ST(0) register, automatically converting it into the internal 80-bit format (extended precision). 209
  • 234. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE FDIV divides the value in ST(0) by the number stored at address __real@40091eb851eb851f —the value 3.14 is encoded there. The assembly syntax doesn’t support floating point numbers, so what we see here is the hexadecimal representation of 3.14 in 64-bit IEEE 754 format. After the execution of FDIV, ST(0) holds the quotient. By the way, there is also the FDIVP instruction, which divides ST(1) by ST(0), popping both these values from stack and then pushing the result. If you know the Forth language9 , you can quickly understand that this is a stack machine10 . The subsequent FLD instruction pushes the value of b into the stack. After that, the quotient is placed in ST(1), and ST(0) has the value of b. The next FMUL instruction does multiplication: b from ST(0) is multiplied by by value at __real@4010666666666666 (the numer 4.1 is there) and leaves the result in the ST(0) register. The last FADDP instruction adds the two values at top of stack, storing the result in ST(1) and then popping the value of ST(0), thereby leaving the result at the top of the stack, in ST(0). The function must return its result in the ST(0) register, so there are no any other instructions except the function epilogue after FADDP. 9wikipedia 10wikipedia 210
  • 235. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE MSVC + OllyDbg I have marked red 2 pairs of 32-bit words in the stack. Each pair is a double-number in IEEE 754 format and is passed from main(). We see how the first FLD loads a value (1.2) from the stack and puts it into ST(0): Figure 17.1: OllyDbg: first FLD executed Because of unavoidable conversion errors from 64-bit IEEE 754 float point to 80-bit (used internally in the FPU), here we see 1.999..., which is close to 1.2. EIP now points to the next instruction (FDIV), which loads a double-number (a constant) from memory. For convenience, OllyDbg shows its value: 3.14. 211
  • 236. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE Let’s trace further. FDIV was executed, now ST(0) contains 0.382... (quotient): Figure 17.2: OllyDbg: FDIV executed 212
  • 237. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE Third step: the next FLD was executed, loading 3.4 into ST(0) (here we see the approximate value, 3.39999...): Figure 17.3: OllyDbg: second FLD executed At the same time, quotient is pushed into ST(1). Right now, EIP points to the next instruction: FMUL. It loads the constant 4.1 from memory, which OllyDbg shows. 213
  • 238. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE Next: FMUL was executed, so now the product is in ST(0): Figure 17.4: OllyDbg: FMUL executed 214
  • 239. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE Next: FADDP was executed, now the result of the addition is in ST(0), and ST(1) is cleared: Figure 17.5: OllyDbg: FADDP executed The result is left in ST(0), because the function returns its value in ST(0). main() takes this value from the register later. We also see something unusual: the 13.93... value is now located in ST(7). Why? As I wrote before, the FPU registers are a stack: 17.2 on page 208. But this is a simplification. Imagine if it was implemented in hardware as it’s described, then all 7 register’s contents must be moved (or copied) to adjacent registers during pushing and popping, and that’s a lot of work. In reality, the FPU has just 8 registers and a pointer (called TOP) which contains a register number, which is the current “top of stack”. When a value is pushed to the stack, TOP is pointed to the next available register, and then a value is written to that register. The procedure is reversed if a value is popped, however, the register which was freed is not cleared (it could possibly be cleared, but this is more work which can degrade performance). So that’s what we see here. It can be said that FADDP saved the sum in the stack, and then popped one element. But in fact, this instruction saved the sum and then shifted TOP. More precisely, the registers of the FPU are a circular buffer. GCC GCC 4.4.1 (with -O3 option) emits the same code, just slightly different: Listing 17.2: Optimizing GCC 4.4.1 public f f proc near arg_0 = qword ptr 8 arg_8 = qword ptr 10h push ebp fld ds:dbl_8048608 ; 3.14 ; stack state now: ST(0) = 3.14 mov ebp, esp fdivr [ebp+arg_0] 215
  • 240. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE ; stack state now: ST(0) = result of division fld ds:dbl_8048610 ; 4.1 ; stack state now: ST(0) = 4.1, ST(1) = result of division fmul [ebp+arg_8] ; stack state now: ST(0) = result of multiplication, ST(1) = result of division pop ebp faddp st(1), st ; stack state now: ST(0) = result of addition retn f endp The difference is that, first of all, 3.14 is pushed to the stack (into ST(0)), and then the value in arg_0 is divided by the value in ST(0). FDIVR stands for Reverse Divide —to divide with divisor and dividend swapped with each other. There is no likewise instruction for multiplication since it is a commutative operation, so we just have FMUL without its -R counterpart. FADDP adds the two values but also pops one value from the stack. After that operation, ST(0) holds the sum. 17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) Until ARM got standardized floating point support, several processor manufacturers added their own instructions extensions. Then, VFP (Vector Floating Point) was standardized. One important difference from x86 is that in ARM, there is no stack, you work just with registers. Listing 17.3: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) f VLDR D16, =3.14 VMOV D17, R0, R1 ; load "a" VMOV D18, R2, R3 ; load "b" VDIV.F64 D16, D17, D16 ; a/3.14 VLDR D17, =4.1 VMUL.F64 D17, D18, D17 ; b*4.1 VADD.F64 D16, D17, D16 ; + VMOV R0, R1, D16 BX LR dbl_2C98 DCFD 3.14 ; DATA XREF: f dbl_2CA0 DCFD 4.1 ; DATA XREF: f+10 So, we see here new some registers used, with D prefix. These are 64-bit registers, there are 32 of them, and they can be used both for floating-point numbers (double) but also for SIMD (it is called NEON here in ARM). There are also 32 32-bit S-registers, intended to be used for single precision floating pointer numbers (float). It is easy to remember: D-registers are for double precision numbers, while S-registers —for single precision numbers. More about it: B.3.3 on page 945. Both (3.14 and 4.1) constants are stored in memory in IEEE 754 form. VLDR and VMOV , as it can be easily deduced, are analogous to the LDR and MOV instructions, but they work with D- registers. It has to be noted that these instructions, just like the D-registers, are intended not only for floating point numbers, but can be also used for SIMD (NEON) operations and this will also be shown soon. The arguments are passed to the function in a common way, via the R-registers, however each number that has double precision has a size of 64 bits, so two R-registers are needed to pass each one. ``VMOV D17, R0, R1'' at the start, composes two 32-bit values from R0 and R1 into one 64-bit value and saves it to D17. ``VMOV R0, R1, D16'' is the inverse operation, what was in D16 is split in two registers, R0 and R1, becase a double-precision number that needs 64 bits for storage, is returned in R0 and R1. VDIV, VMUL and VADD, are instruction for processing floating point numbers that compute quotient, product and sum, respectively. The code for thumb-2 is same. 17.5.3 ARM: Optimizing Keil 6/2013 (thumb mode) 216
  • 241. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE f PUSH {R3-R7,LR} MOVS R7, R2 MOVS R4, R3 MOVS R5, R0 MOVS R6, R1 LDR R2, =0x66666666 ; 4.1 LDR R3, =0x40106666 MOVS R0, R7 MOVS R1, R4 BL __aeabi_dmul MOVS R7, R0 MOVS R4, R1 LDR R2, =0x51EB851F ; 3.14 LDR R3, =0x40091EB8 MOVS R0, R5 MOVS R1, R6 BL __aeabi_ddiv MOVS R2, R7 MOVS R3, R4 BL __aeabi_dadd POP {R3-R7,PC} ; 4.1 in IEEE 754 form: dword_364 DCD 0x66666666 ; DATA XREF: f+A dword_368 DCD 0x40106666 ; DATA XREF: f+C ; 3.14 in IEEE 754 form: dword_36C DCD 0x51EB851F ; DATA XREF: f+1A dword_370 DCD 0x40091EB8 ; DATA XREF: f+1C Keil generated code for a processor without FPU or NEON support. The double-precision floating-point numbers are passed via generic R-registers, and instead of FPU-instructions, service library functions are called (like __aeabi_dmul, __aeabi_ddiv, __aeabi_dadd ) which emulate multiplication, division and addition for floating-point numbers. Of course, that is slower than FPU-coprocessor, but still better than nothing. By the way, similar FPU-emulating libraries were very popular in the x86 world when coprocessors were rare and expen- sive, and were installed only on expensive computers. The FPU-coprocessor emulation is called soft float or armel in the ARM world, while using the coprocessor’s FPU-instructions is called hard float or armhf. 17.5.4 ARM64: Optimizing GCC (Linaro) 4.9 Very compact code: Listing 17.4: Optimizing GCC (Linaro) 4.9 f: ; D0 = a, D1 = b ldr d2, .LC25 ; 3.14 ; D2 = 3.14 fdiv d0, d0, d2 ; D0 = D0/D2 = a/3.14 ldr d2, .LC26 ; 4.1 ; D2 = 4.1 fmadd d0, d1, d2, d0 ; D0 = D1*D2+D0 = b*4.1+a/3.14 ret ; constants in IEEE 754 format: .LC25: .word 1374389535 ; 3.14 .word 1074339512 .LC26: .word 1717986918 ; 4.1 .word 1074816614 17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9 217
  • 242. CHAPTER 17. FLOATING-POINT UNIT 17.5. SIMPLE EXAMPLE Listing 17.5: Non-optimizing GCC (Linaro) 4.9 f: sub sp, sp, #16 str d0, [sp,8] ; save "a" in Register Save Area str d1, [sp] ; save "b" in Register Save Area ldr x1, [sp,8] ; X1 = a ldr x0, .LC25 ; X0 = 3.14 fmov d0, x1 fmov d1, x0 ; D0 = a, D1 = 3.14 fdiv d0, d0, d1 ; D0 = D0/D1 = a/3.14 fmov x1, d0 ; X1 = a/3.14 ldr x2, [sp] ; X2 = b ldr x0, .LC26 ; X0 = 4.1 fmov d0, x2 ; D0 = b fmov d1, x0 ; D1 = 4.1 fmul d0, d0, d1 ; D0 = D0*D1 = b*4.1 fmov x0, d0 ; X0 = D0 = b*4.1 fmov d0, x1 ; D0 = a/3.14 fmov d1, x0 ; D1 = X0 = b*4.1 fadd d0, d0, d1 ; D0 = D0+D1 = a/3.14 + b*4.1 fmov x0, d0 ; redundant code fmov d0, x0 ; / add sp, sp, 16 ret .LC25: .word 1374389535 ; 3.14 .word 1074339512 .LC26: .word 1717986918 ; 4.1 .word 1074816614 Non-optimizing GCC is more verbose. There is a lot of unnecessary value shuffling, including some clearly redundant code (the last two FMOV instructions). Probably, GCC 4.9 is not yet good in generating ARM64 code. What is worth noting is that ARM64 has 64-bit registers, and the D-registers are 64-bit ones as well. So the compiler is free to save values of type double in GPRs instead of the local stack. This isn’t possible on 32-bit CPUs. And again, as an exercise, you can try to optimize this function manually, without introducing new instructions like FMADD. 17.5.6 MIPS MIPS can support several coprocessors (up to 4), the zeroth of which is a special control coprocessor, and first coprocessor is the FPU. As in ARM, the MIPS coprocessor is not a stack machine, it has 32 32-bit registers ($F0-$F31): C.1.2 on page 947. When one needs to work with 64-bit double values, a pair of 32-bit F-registers is used. Listing 17.6: Optimizing GCC 4.4.5 (IDA) f: ; $f12-$f13=A ; $f14-$f15=B lui $v0, (dword_C4 >> 16) ; ? ; load low 32-bit part of 3.14 constant to $f0: 218
  • 243. CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS lwc1 $f0, dword_BC or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 3.14 constant to $f1: lwc1 $f1, $LC0 lui $v0, ($LC1 >> 16) ; ? ; A in $f12-$f13, 3.14 constant in $f0-$f1, do division: div.d $f0, $f12, $f0 ; $f0-$f1=A/3.14 ; load low 32-bit part of 4.1 to $f2: lwc1 $f2, dword_C4 or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 4.1 to $f3: lwc1 $f3, $LC1 or $at, $zero ; load delay slot, NOP ; B in $f14-$f15, 4.1 constant in $f2-$f3, do multiplication: mul.d $f2, $f14, $f2 ; $f2-$f3=B*4.1 jr $ra ; sum 64-bit parts and leave result in $f0-$f1: add.d $f0, $f2 ; branch delay slot, NOP .rodata.cst8:000000B8 $LC0: .word 0x40091EB8 # DATA XREF: f+C .rodata.cst8:000000BC dword_BC: .word 0x51EB851F # DATA XREF: f+4 .rodata.cst8:000000C0 $LC1: .word 0x40106666 # DATA XREF: f+10 .rodata.cst8:000000C4 dword_C4: .word 0x66666666 # DATA XREF: f The new instructions here are: • LWC1 loads a 32-bit word into a register of the first coprocessor (hence “1” in instruction name). A pair of LWC1 instructions may be combined into a L.D pseudoinstruction. • DIV.D, MUL.D, ADD.D do division/multiplication/addition (“.D” in the suffix stands for double precision, “.S” would stands for single precision) There is also a weird compiler anomaly: the LUI instructions that I’ve marked with a question mark. It’s hard for me to understand why load a part of a 64-bit constant of double type into the $V0 register. These instruction have no effect. If someone knows more about it, please drop me an email11 . 17.6 Passing floating point numbers via arguments #include <math.h> #include <stdio.h> int main () { printf ("32.01 ^ 1.54 = %lfn", pow (32.01,1.54)); return 0; } 17.6.1 x86 Let’s see what we get in (MSVC 2010): Listing 17.7: MSVC 2010 CONST SEGMENT __real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01 __real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54 CONST ENDS _main PROC push ebp mov ebp, esp sub esp, 8 ; allocate space for the first variable 11dennis(a)yurichev.com 219
  • 244. CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS fld QWORD PTR __real@3ff8a3d70a3d70a4 fstp QWORD PTR [esp] sub esp, 8 ; allocate space for the second variable fld QWORD PTR __real@40400147ae147ae1 fstp QWORD PTR [esp] call _pow add esp, 8 ; "return back" place of one variable. ; in local stack here 8 bytes still reserved for us. ; result now in ST(0) fstp QWORD PTR [esp] ; move result from ST(0) to local stack for printf() push OFFSET $SG2651 call _printf add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP FLD and FSTP move variables between the data segment and the FPU stack. pow()12 takes both values from the stack of the FPU and returns its result in the ST(0) register. printf() takes 8 bytes from the local stack and interprets them as double type variable. By the way, a pair of MOV instructions could be used here for moving values from the memory into the stack, because the values in memory are stored in IEEE 754 format, and pow() also takes them in this format, so no conversion is necessary. That’s how it’s done in the next example, for ARM: 17.6.2 on page 220. 17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) _main var_C = -0xC PUSH {R7,LR} MOV R7, SP SUB SP, SP, #4 VLDR D16, =32.01 VMOV R0, R1, D16 VLDR D16, =1.54 VMOV R2, R3, D16 BLX _pow VMOV D16, R0, R1 MOV R0, 0xFC1 ; "32.01 ^ 1.54 = %lfn" ADD R0, PC VMOV R1, R2, D16 BLX _printf MOVS R1, 0 STR R0, [SP,#0xC+var_C] MOV R0, R1 ADD SP, SP, #4 POP {R7,PC} dbl_2F90 DCFD 32.01 ; DATA XREF: _main+6 dbl_2F98 DCFD 1.54 ; DATA XREF: _main+E As I wrote before, 64-bit floating pointer numbers are passed in R-registers pairs. This code is a bit redundant (certainly because optimization is turned off), since it is possible to load values into the R-registers directly without touching the D-registers. So, as we see, the _pow function receives its first argument in R0 and R1, and its second one in R2 and R3. The function leaves its result in R0 and R1. The result of _pow is moved into D16, then in the R1 and R2 pair, from where printf() takes the resulting number. 17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode) 12a standard C function, raises a number to the given power (exponentiation) 220
  • 245. CHAPTER 17. FLOATING-POINT UNIT 17.6. PASSING FLOATING POINT NUMBERS VIA ARGUMENTS _main STMFD SP!, {R4-R6,LR} LDR R2, =0xA3D70A4 ; y LDR R3, =0x3FF8A3D7 LDR R0, =0xAE147AE1 ; x LDR R1, =0x40400147 BL pow MOV R4, R0 MOV R2, R4 MOV R3, R1 ADR R0, a32_011_54Lf ; "32.01 ^ 1.54 = %lfn" BL __2printf MOV R0, #0 LDMFD SP!, {R4-R6,PC} y DCD 0xA3D70A4 ; DATA XREF: _main+4 dword_520 DCD 0x3FF8A3D7 ; DATA XREF: _main+8 ; double x x DCD 0xAE147AE1 ; DATA XREF: _main+C dword_528 DCD 0x40400147 ; DATA XREF: _main+10 a32_011_54Lf DCB "32.01 ^ 1.54 = %lf",0xA,0 ; DATA XREF: _main+24 D-registers are not used here, just R-register pairs. 17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9 Listing 17.8: Optimizing GCC (Linaro) 4.9 f: stp x29, x30, [sp, -16]! add x29, sp, 0 ldr d1, .LC1 ; load 1.54 into D1 ldr d0, .LC0 ; load 32.01 into D0 bl pow ; result of pow() in D0 adrp x0, .LC2 add x0, x0, :lo12:.LC2 bl printf mov w0, 0 ldp x29, x30, [sp], 16 ret .LC0: ; 32.01 in IEEE 754 format .word -1374389535 .word 1077936455 .LC1: ; 1.54 in IEEE 754 format .word 171798692 .word 1073259479 .LC2: .string "32.01 ^ 1.54 = %lfn" The constants are loaded into D0 and D1: pow() takes them from there. The result will be in D0 after the execution of pow(). It is to be passed to printf() without any modification and moving, because printf() takes arguments of integral types and pointers from X-registers, and floating point arguments from D-registers. 17.6.5 MIPS Listing 17.9: Optimizing GCC 4.4.5 (IDA) main: var_10 = -0x10 var_4 = -4 ; function prologue: lui $gp, (dword_9C >> 16) 221
  • 246. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lui $v0, (dword_A4 >> 16) ; ? ; load low 32-bit part of 32.01: lwc1 $f12, dword_9C ; load address of pow() function: lw $t9, (pow & 0xFFFF)($gp) ; load high 32-bit part of 32.01: lwc1 $f13, $LC0 lui $v0, ($LC1 >> 16) ; ? ; load low 32-bit part of 1.54: lwc1 $f14, dword_A4 or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 1.54: lwc1 $f15, $LC1 ; call pow(): jalr $t9 or $at, $zero ; branch delay slot, NOP lw $gp, 0x20+var_10($sp) ; copy result from $f0 and $f1 to $a3 and $a2: mfc1 $a3, $f0 lw $t9, (printf & 0xFFFF)($gp) mfc1 $a2, $f1 ; call printf(): lui $a0, ($LC2 >> 16) # "32.01 ^ 1.54 = %lfn" jalr $t9 la $a0, ($LC2 & 0xFFFF) # "32.01 ^ 1.54 = %lfn" ; function epilogue: lw $ra, 0x20+var_4($sp) ; return 0: move $v0, $zero jr $ra addiu $sp, 0x20 .rodata.str1.4:00000084 $LC2: .ascii "32.01 ^ 1.54 = %lfn"<0> ; 32.01: .rodata.cst8:00000098 $LC0: .word 0x40400147 # DATA XREF: main+20 .rodata.cst8:0000009C dword_9C: .word 0xAE147AE1 # DATA XREF: main .rodata.cst8:0000009C # main+18 ; 1.54: .rodata.cst8:000000A0 $LC1: .word 0x3FF8A3D7 # DATA XREF: main+24 .rodata.cst8:000000A0 # main+30 .rodata.cst8:000000A4 dword_A4: .word 0xA3D70A4 # DATA XREF: main+14 And again, we see here LUI loading a 32-bit part of a double number into $V0. And again, I honestly don’t know why. The new instruction for us here is MFC1 (“Move From Coprocessor 1”). The FPU is coprocessor number 1, hence “1” in the instruction name. This instruction transfers values from the coprocessor’s registers to the registers of the CPU (GPR). So in the end the result from pow() is moved to registers $A3 and $A2, and printf() takes a 64-bit double value from this register pair. 17.7 Comparison example Let’s try this: #include <stdio.h> double d_max (double a, double b) { if (a>b) return a; return b; }; int main() { 222
  • 247. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE printf ("%fn", d_max (1.2, 3.4)); printf ("%fn", d_max (5.6, -4)); }; Despite the simplicity of the function, it will be harder to understand how it works. 17.7.1 x86 Non-optimizing MSVC MSVC 2010 generates the following: Listing 17.10: Non-optimizing MSVC 2010 PUBLIC _d_max _TEXT SEGMENT _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _d_max PROC push ebp mov ebp, esp fld QWORD PTR _b$[ebp] ; current stack state: ST(0) = _b ; compare _b (ST(0)) and _a, and pop register fcomp QWORD PTR _a$[ebp] ; stack is empty here fnstsw ax test ah, 5 jp SHORT $LN1@d_max ; we are here only if a>b fld QWORD PTR _a$[ebp] jmp SHORT $LN2@d_max $LN1@d_max: fld QWORD PTR _b$[ebp] $LN2@d_max: pop ebp ret 0 _d_max ENDP So, FLD loads _b into ST(0). FCOMP compares the value in ST(0) with what is in _a and sets C3/C2/C0 bits in FPU status word register, accordingly. This is a 16-bit register that reflects the current state of the FPU. After the bits are set, the FCOMP instruction also pops one variable from the stack. This is what distinguishes it from FCOM, which is just compares values, leaving the stack in the same state. Unfortunately, CPUs before Intel P6 13 don’t have any conditional jumps instructions which check the C3/C2/C0 bits. Probably, it is a matter of history (remember: FPU was separate chip in past). Modern CPU starting at Intel P6 have FCOMI/FCOMIP/FUCOMI/FUCOMIP instructions —which do the same, but modify the ZF/PF/CF CPU flags. The FNSTSW instruction copies FPU the status word register to AX. C3/C2/C0 bits are placed at positions 14/10/8, they are at the same positions in the AX register and all they are placed in the high part of AX —AH. • If b > a in our example, then C3/C2/C0 bits are to be set as following: 0, 0, 0. • If a > b, then the bits are: 0, 0, 1. • If a = b, then the bits are: 1, 0, 0. • If the result is unordered (in case of error), then the set bits are: 1, 1, 1. This is how C3/C2/C0 bits are located in the AX register: 14 10 9 8 C3 C2 C1 C0 13Intel P6 is Pentium Pro, Pentium II, etc 223
  • 248. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE This is how C3/C2/C0 bits are located in the AH register: 6 2 1 0 C3 C2 C1 C0 After the execution of test ah, 514 , only C0 and C2 bits (on 0 and 2 position) are considered, all other bits are just ignored. Now let’s talk about the parity flag, another notable historical rudiment. This flag is set to 1 if the number of ones in the result of the last calculation is even, and to 0 if it is odd. Let’s look into Wikipedia 15 : One common reason to test the parity flag actually has nothing to do with parity. The FPU has four condition flags (C0 to C3), but they can not be tested directly, and must instead be first copied to the flags register. When this happens, C0 is placed in the carry flag, C2 in the parity flag and C3 in the zero flag. The C2 flag is set when e.g. incomparable floating point values (NaN or unsupported format) are compared with the FUCOM instructions. As noted in Wikipedia, the parity flag used sometimes in FPU code, let’s see how. The PF flag is to be set to 1 if both C0 and C2 are set to 0 or both are 1, in which case the subsequent JP (jump if PF==1) is triggering. If we recall the values of C3/C2/C0 for various cases, we can see that the conditional jump JP is triggering in two cases: if b > a or a = b (C3 bit is not considered here, since it was cleared by the test ah, 5 instruction). It is all simple after that. If the conditional jump was triggered, FLD loads the value of _b in ST(0), and if it was not triggered, the value of _a is loaded there. And what about checking C2? The C2 flag is set in case of error (NaN, etc), but our code doesn’t check it. If the programmer cares about FPU errors, he/she must add additional checks. 145=1001b 15wikipedia 224
  • 249. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE First OllyDbg example: a=1.2 and b=3.4 Let’s load the example into OllyDbg: Figure 17.6: OllyDbg: first FLD is executed Current arguments of the function: a = 1.2 and b = 3.4 (We can see them in the stack: two pairs of 32-bit values). b (3.4) is already loaded in ST(0). Now FCOMP is being executed. OllyDbg shows the second FCOMP argument, which is in stack right now. 225
  • 250. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FCOMP is executed: Figure 17.7: OllyDbg: FCOMP is executed We see the state of the FPU’s condition flags: all zeroes. The popped value is reflected as ST(7), I wrote earlier about reason for this: 17.5.1 on page 215. 226
  • 251. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FNSTSW is executed: Figure 17.8: OllyDbg: FNSTSW is executed We see that the AX register contain zeroes: indeed, all condition flags are zero. (OllyDbg disassembles the FNSTSW instruction as FSTSW — they are synonyms). 227
  • 252. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE TEST is executed: Figure 17.9: OllyDbg: TEST is executed The PF flag is set to 1. Indeed: the number of bits set in 0 is 0 and 0 is an even number. OllyDbg disassembles JP as JPE16 — they are synonyms. And it is about to trigger now. 16Jump Parity Even (x86 instruction) 228
  • 253. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE JPE triggered, FLD loads the value of b (3.4) in ST(0): Figure 17.10: OllyDbg: second FLD is executed The function finishes its work. 229
  • 254. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Second OllyDbg example: a=5.6 and b=-4 Let’s load example into OllyDbg: Figure 17.11: OllyDbg: first FLD executed Current function arguments: a = 5.6 and b = −4). b (−4) is already loaded in ST(0). FCOMP about to execute now. OllyDbg shows the second FCOMP argument, which is in stack right now. 230
  • 255. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FCOMP executed: Figure 17.12: OllyDbg: FCOMP executed We see the state of the FPU’s condition flags: all zeroes except C0. 231
  • 256. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FNSTSW executed: Figure 17.13: OllyDbg: FNSTSW executed We see that the AX register contains 0x100: the C0 flag is at the 16th bit. 232
  • 257. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE TEST executed: Figure 17.14: OllyDbg: TEST executed The PF flag is cleared. Indeed: the count of bits set in 0x100 is 1 and 1 is an odd number. JPE is being skipped now. 233
  • 258. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE JPE wasn’t triggered, so FLD loads the value of a (5.6) in ST(0): Figure 17.15: OllyDbg: second FLD executed The function finishes its work. Optimizing MSVC 2010 Listing 17.11: Optimizing MSVC 2010 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _d_max PROC fld QWORD PTR _b$[esp-4] fld QWORD PTR _a$[esp-4] ; current stack state: ST(0) = _a, ST(1) = _b fcom ST(1) ; compare _a and ST(1) = (_b) fnstsw ax test ah, 65 ; 00000041H jne SHORT $LN5@d_max ; copy ST(0) to ST(1) and pop register, ; leave (_a) on top fstp ST(1) ; current stack state: ST(0) = _a ret 0 $LN5@d_max: ; copy ST(0) to ST(0) and pop register, ; leave (_b) on top fstp ST(0) ; current stack state: ST(0) = _b ret 0 234
  • 259. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE _d_max ENDP FCOM differs from FCOMP in the sense that it just compares the values and doesn’t change the FPU stack. Unlike the previous example, here the operands are in reverse order, which is why the result of the comparison in C3/C2/C0 is different: • If a > b in our example, then C3/C2/C0 bits are to be set as: 0, 0, 0. • If b > a, then the bits are: 0, 0, 1. • If a = b, then the bits are: 1, 0, 0. The test ah, 65 instruction leaves just two bits —C3 and C0. Both will be zero if a > b: in that case the JNE jump will not be triggered. Then FSTP ST(1) follows —this instruction copies the value from ST(0) to the operand and pops one value from the FPU stack. In other words, the instruction copies ST(0) (where the value of _a is now) into ST(1). After that, two copies of _a are at the top of the stack. Then, one value is popped. After that, ST(0) contains _a and the function is finishes. The conditional jump JNE is triggering in two cases: if b > a or a = b. ST(0) is copied into ST(0), it is just like an idle (NOP) operation, then one value is popped from the stack and the top of the stack (ST(0)) is contain what was in ST(1) before (that is _b). Then the function finishes. The reason this instruction is used here probably is because the FPU has no other instruction to pop a value from the stack and discard it. 235
  • 260. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE First OllyDbg example: a=1.2 and b=3.4 Both FLD are executed: Figure 17.16: OllyDbg: both FLD are executed FCOM being executed: OllyDbg shows the contents of ST(0) and ST(1), for convenience. 236
  • 261. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FCOM is done: Figure 17.17: OllyDbg: FCOM is done C0 is set, all other condition flags are cleared. 237
  • 262. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FNSTSW is done, AX=0x3100: Figure 17.18: OllyDbg: FNSTSW is executed 238
  • 263. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE TEST is executed: Figure 17.19: OllyDbg: TEST is executed ZF=0, conditional jump is about to trigger now. 239
  • 264. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FSTP ST (or FSTP ST(0)) was executed: 1.2 was popped from the stack, and 3.4 was left on top: Figure 17.20: OllyDbg: FSTP is executed We see that the FSTP ST instruction works just like popping one value from the FPU stack. 240
  • 265. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Second OllyDbg example: a=5.6 and b=-4 Both FLD are executed: Figure 17.21: OllyDbg: both FLD are executed FCOM is about to execute. 241
  • 266. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FCOM is done: Figure 17.22: OllyDbg: FCOM is finished All conditional flags are cleared. 242
  • 267. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FNSTSW done, AX=0x3000: Figure 17.23: OllyDbg: FNSTSW was executed 243
  • 268. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE TEST is done: Figure 17.24: OllyDbg: TEST was executed ZF=1, jump will not happen now. 244
  • 269. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE FSTP ST(1) was executed: a value of 5.6 is now at the top of the FPU stack. Figure 17.25: OllyDbg: FSTP was executed We now see that the FSTP ST(1) instruction works as follows: it leaves what was at the top of the stack, but clears ST(1). GCC 4.4.1 Listing 17.12: GCC 4.4.1 d_max proc near b = qword ptr -10h a = qword ptr -8 a_first_half = dword ptr 8 a_second_half = dword ptr 0Ch b_first_half = dword ptr 10h b_second_half = dword ptr 14h push ebp mov ebp, esp sub esp, 10h ; put a and b to local stack: mov eax, [ebp+a_first_half] mov dword ptr [ebp+a], eax mov eax, [ebp+a_second_half] mov dword ptr [ebp+a+4], eax mov eax, [ebp+b_first_half] mov dword ptr [ebp+b], eax mov eax, [ebp+b_second_half] mov dword ptr [ebp+b+4], eax ; load a and b to FPU stack: 245
  • 270. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE fld [ebp+a] fld [ebp+b] ; current stack state: ST(0) - b; ST(1) - a fxch st(1) ; this instruction swapping ST(1) and ST(0) ; current stack state: ST(0) - a; ST(1) - b fucompp ; compare a and b and pop two values from stack, i.e., a and b fnstsw ax ; store FPU status to AX sahf ; load SF, ZF, AF, PF, and CF flags state from AH setnbe al ; store 1 to AL, if CF=0 and ZF=0 test al, al ; AL==0 ? jz short loc_8048453 ; yes fld [ebp+a] jmp short locret_8048456 loc_8048453: fld [ebp+b] locret_8048456: leave retn d_max endp FUCOMPP is almost like FCOM, but pops both values from the stack and handles “not-a-numbers” differently. A bit about not-a-numbers: The FPU is able to deal with special values which are not-a-numbers or NaNs 17 . These are infinity, result of division by 0, etc. Not-a-numbers can be “quiet” and “signaling”. It is possible to continue to work with “quiet” NaNs, but if one tries to do any operation with “signaling” NaNs, an exception is to be raised. FCOM raising an exception if any operand is NaN. FUCOM raising an exception only if any operand is a signaling NaN (SNaN). The next instruction is SAHF (Store AH into Flags) —this is a rare instruction in code not related to the FPU. 8 bits from AH are moved into the lower 8 bits of the CPU flags in the following order: 7 6 4 2 0 SF ZF AF PF CF Let’s recall that FNSTSW moves the bits that interest us (C3/C2/C0) into AH and they are in positions 6, 2, 0 of the AH register: 6 2 1 0 C3 C2 C1 C0 In other words, the fnstsw ax / sahf instruction pair moves C3/C2/C0 into ZF, PF and CF. Now let’s also recall the values of C3/C2/C0 in different conditions: • If a is greater than b in our example, then C3/C2/C0 are to be set to: 0, 0, 0. • if a is less than b, then the bits are to be set to: 0, 0, 1. • If a = b, then: 1, 0, 0. In other words, these states of the CPU flags are possible after three FUCOMPP/FNSTSW/SAHF instructions: • If a > b, the CPU flags are to be set as: ZF=0, PF=0, CF=0. • If a < b, then the flags are to be set as: ZF=0, PF=0, CF=1. • And if a = b, then: ZF=1, PF=0, CF=0. Depending on the CPU flags and conditions, SETNBE stores 1 or 0 to AL. It is almost the counterpart of JNBE, with the exception that SETcc18 stores 1 or 0 in AL, but Jcc does actually jump or not. SETNBE stores 1 only if CF=0 and ZF=0. If it is not true, 0 is to be stored into AL. Only in one case both CF and ZF are 0: if a > b. Then 1 is to be stored to AL, the subsequent JZ is not to be triggered and the function will return _a. In all other cases, _b is to be returned. 17wikipedia 18cc is condition code 246
  • 271. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Optimizing GCC 4.4.1 Listing 17.13: Optimizing GCC 4.4.1 public d_max d_max proc near arg_0 = qword ptr 8 arg_8 = qword ptr 10h push ebp mov ebp, esp fld [ebp+arg_0] ; _a fld [ebp+arg_8] ; _b ; stack state now: ST(0) = _b, ST(1) = _a fxch st(1) ; stack state now: ST(0) = _a, ST(1) = _b fucom st(1) ; compare _a and _b fnstsw ax sahf ja short loc_8048448 ; store ST(0) to ST(0) (idle operation), pop value at top of stack, ; leave _b at top fstp st jmp short loc_804844A loc_8048448: ; store _a to ST(0), pop value at top of stack, leave _a at top fstp st(1) loc_804844A: pop ebp retn d_max endp It is almost the same except that JA is used after SAHF. Actually, conditional jump instructions that check “larger”, “lesser” or “equal” for unsigned number comparison (these are JA, JAE, JBE, JBE, JE/JZ, JNA, JNAE, JNB, JNBE, JNE/JNZ) check only flags CF and ZF. Let’s recall where bits C3/C2/C0 are located in the AH register after the execution of FSTSW/FNSTSW: 6 2 1 0 C3 C2 C1 C0 Let’s also recall, how the bits from AH are stored into the CPU flags the execution of SAHF: 7 6 4 2 0 SF ZF AF PF CF After the comparison, the C3 and C0 bits are moved into ZF and CF, so the conditional jumps are able work after. JA is triggering if both CF are ZF zero. Thereby, the conditional jumps instructions listed here can be used after a FNSTSW/SAHF instruction pair. Apparently, the FPU C3/C2/C0 status bits were placed there intentionally, to easily map them to base CPU flags without additional permutations. But I’m not sure. GCC 4.8.1 with -O3 optimization turned on Some new FPU instructions were added in the P6 Intel family19 These are FUCOMI (compare operands and set flags of the main CPU) and FCMOVcc (works like CMOVcc, but on FPU registers). Apparently, the maintainers of GCC decided to drop support of pre-P6 Intel CPUs (early Pentiums, etc). And also, the FPU is no longer separate unit in P6 Intel family, so now it is possible to modify/check flags of the main CPU from the FPU. So what we get is: 19Starting at Pentium Pro, Pentium-II, etc. 247
  • 272. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Listing 17.14: Optimizing GCC 4.8.1 fld QWORD PTR [esp+4] ; load "a" fld QWORD PTR [esp+12] ; load "b" ; ST0=b, ST1=a fxch st(1) ; ST0=a, ST1=b ; compare "a" and "b" fucomi st, st(1) ; copy ST1 ("b" here) to ST0 if a<=b ; leave "a" in ST0 otherwise fcmovbe st, st(1) ; discard value in ST1 fstp st(1) ret I’m not sure why FXCH (swap operands) is here. It’s possible to get rid of it easily by swapping the first two FLD instructions or by replacing FCMOVBE (below or equal) by FCMOVA (above). Probably it’s a compiler inaccuracy. So FUCOMI compares ST(0) (a) and ST(1) (b) and then sets some flags in the main CPU. FCMOVBE checks the flags and copies ST(1) (b here at the moment) to ST(0) (a here) if ST0(a) <= ST1(b). Otherwise (a > b), it leaves a in ST(0). The last FSTP leaves ST(0) on top of the stack, discarding the contents of ST(1). Let’s trace this function in GDB: Listing 17.15: Optimizing GCC 4.8.1 and GDB 1 dennis@ubuntuvm:~/polygon$ gcc -O3 d_max.c -o d_max -fno-inline 2 dennis@ubuntuvm:~/polygon$ gdb d_max 3 GNU gdb (GDB) 7.6.1-ubuntu 4 Copyright (C) 2013 Free Software Foundation, Inc. 5 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> 6 This is free software: you are free to change and redistribute it. 7 There is NO WARRANTY, to the extent permitted by law. Type "show copying" 8 and "show warranty" for details. 9 This GDB was configured as "i686-linux-gnu". 10 For bug reporting instructions, please see: 11 <http://www.gnu.org/software/gdb/bugs/>... 12 Reading symbols from /home/dennis/polygon/d_max...(no debugging symbols found)...done. 13 (gdb) b d_max 14 Breakpoint 1 at 0x80484a0 15 (gdb) run 16 Starting program: /home/dennis/polygon/d_max 17 18 Breakpoint 1, 0x080484a0 in d_max () 19 (gdb) ni 20 0x080484a4 in d_max () 21 (gdb) disas $eip 22 Dump of assembler code for function d_max: 23 0x080484a0 <+0>: fldl 0x4(%esp) 24 => 0x080484a4 <+4>: fldl 0xc(%esp) 25 0x080484a8 <+8>: fxch %st(1) 26 0x080484aa <+10>: fucomi %st(1),%st 27 0x080484ac <+12>: fcmovbe %st(1),%st 28 0x080484ae <+14>: fstp %st(1) 29 0x080484b0 <+16>: ret 30 End of assembler dump. 31 (gdb) ni 32 0x080484a8 in d_max () 33 (gdb) info float 34 R7: Valid 0x3fff9999999999999800 +1.199999999999999956 35 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911 36 R5: Empty 0x00000000000000000000 37 R4: Empty 0x00000000000000000000 38 R3: Empty 0x00000000000000000000 39 R2: Empty 0x00000000000000000000 40 R1: Empty 0x00000000000000000000 41 R0: Empty 0x00000000000000000000 42 43 Status Word: 0x3000 44 TOP: 6 45 Control Word: 0x037f IM DM ZM OM UM PM 46 PC: Extended Precision (64-bits) 248
  • 273. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE 47 RC: Round to nearest 48 Tag Word: 0x0fff 49 Instruction Pointer: 0x73:0x080484a4 50 Operand Pointer: 0x7b:0xbffff118 51 Opcode: 0x0000 52 (gdb) ni 53 0x080484aa in d_max () 54 (gdb) info float 55 R7: Valid 0x4000d999999999999800 +3.399999999999999911 56 =>R6: Valid 0x3fff9999999999999800 +1.199999999999999956 57 R5: Empty 0x00000000000000000000 58 R4: Empty 0x00000000000000000000 59 R3: Empty 0x00000000000000000000 60 R2: Empty 0x00000000000000000000 61 R1: Empty 0x00000000000000000000 62 R0: Empty 0x00000000000000000000 63 64 Status Word: 0x3000 65 TOP: 6 66 Control Word: 0x037f IM DM ZM OM UM PM 67 PC: Extended Precision (64-bits) 68 RC: Round to nearest 69 Tag Word: 0x0fff 70 Instruction Pointer: 0x73:0x080484a8 71 Operand Pointer: 0x7b:0xbffff118 72 Opcode: 0x0000 73 (gdb) disas $eip 74 Dump of assembler code for function d_max: 75 0x080484a0 <+0>: fldl 0x4(%esp) 76 0x080484a4 <+4>: fldl 0xc(%esp) 77 0x080484a8 <+8>: fxch %st(1) 78 => 0x080484aa <+10>: fucomi %st(1),%st 79 0x080484ac <+12>: fcmovbe %st(1),%st 80 0x080484ae <+14>: fstp %st(1) 81 0x080484b0 <+16>: ret 82 End of assembler dump. 83 (gdb) ni 84 0x080484ac in d_max () 85 (gdb) info registers 86 eax 0x1 1 87 ecx 0xbffff1c4 -1073745468 88 edx 0x8048340 134513472 89 ebx 0xb7fbf000 -1208225792 90 esp 0xbffff10c 0xbffff10c 91 ebp 0xbffff128 0xbffff128 92 esi 0x0 0 93 edi 0x0 0 94 eip 0x80484ac 0x80484ac <d_max+12> 95 eflags 0x203 [ CF IF ] 96 cs 0x73 115 97 ss 0x7b 123 98 ds 0x7b 123 99 es 0x7b 123 100 fs 0x0 0 101 gs 0x33 51 102 (gdb) ni 103 0x080484ae in d_max () 104 (gdb) info float 105 R7: Valid 0x4000d999999999999800 +3.399999999999999911 106 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911 107 R5: Empty 0x00000000000000000000 108 R4: Empty 0x00000000000000000000 109 R3: Empty 0x00000000000000000000 110 R2: Empty 0x00000000000000000000 111 R1: Empty 0x00000000000000000000 112 R0: Empty 0x00000000000000000000 113 114 Status Word: 0x3000 115 TOP: 6 116 Control Word: 0x037f IM DM ZM OM UM PM 249
  • 274. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE 117 PC: Extended Precision (64-bits) 118 RC: Round to nearest 119 Tag Word: 0x0fff 120 Instruction Pointer: 0x73:0x080484ac 121 Operand Pointer: 0x7b:0xbffff118 122 Opcode: 0x0000 123 (gdb) disas $eip 124 Dump of assembler code for function d_max: 125 0x080484a0 <+0>: fldl 0x4(%esp) 126 0x080484a4 <+4>: fldl 0xc(%esp) 127 0x080484a8 <+8>: fxch %st(1) 128 0x080484aa <+10>: fucomi %st(1),%st 129 0x080484ac <+12>: fcmovbe %st(1),%st 130 => 0x080484ae <+14>: fstp %st(1) 131 0x080484b0 <+16>: ret 132 End of assembler dump. 133 (gdb) ni 134 0x080484b0 in d_max () 135 (gdb) info float 136 =>R7: Valid 0x4000d999999999999800 +3.399999999999999911 137 R6: Empty 0x4000d999999999999800 138 R5: Empty 0x00000000000000000000 139 R4: Empty 0x00000000000000000000 140 R3: Empty 0x00000000000000000000 141 R2: Empty 0x00000000000000000000 142 R1: Empty 0x00000000000000000000 143 R0: Empty 0x00000000000000000000 144 145 Status Word: 0x3800 146 TOP: 7 147 Control Word: 0x037f IM DM ZM OM UM PM 148 PC: Extended Precision (64-bits) 149 RC: Round to nearest 150 Tag Word: 0x3fff 151 Instruction Pointer: 0x73:0x080484ae 152 Operand Pointer: 0x7b:0xbffff118 153 Opcode: 0x0000 154 (gdb) quit 155 A debugging session is active. 156 157 Inferior 1 [process 30194] will be killed. 158 159 Quit anyway? (y or n) y 160 dennis@ubuntuvm:~/polygon$ Using “ni”, let’s execute the first two FLD instructions. Let’s examine the FPU registers (line 33). As I wrote before, the FPU registers set is a circular buffer rather than a stack ( 17.5.1 on page 215). And GDB doesn’t show STx registers, but internal the FPU registers (Rx). The arrow (at line 35) points to the current top of the stack. You can also see the TOP register contents in Status Word (line 44) — it is 6 now, so the stack top is now pointing to internal register 6. The values of a and b are swapped after FXCH is executed (line 54). FUCOMI is executed (line 83). Let’s see the flags: CF is set (line 95). FCMOVBE has copied the value of b (see line 104). FSTP leaves one value at the top of stack (line 136). The value of TOP is now 7, so the FPU stack top is pointing to internal register 7. 17.7.2 ARM Optimizing Xcode 4.6.3 (LLVM) (ARM mode) Listing 17.16: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) VMOV D16, R2, R3 ; b VMOV D17, R0, R1 ; a VCMPE.F64 D17, D16 VMRS APSR_nzcv, FPSCR VMOVGT.F64 D16, D17 ; copy "b" to D16 VMOV R0, R1, D16 250
  • 275. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE BX LR A very simple case. The input values are placed into the D17 and D16 registers and then compared using the VCMPE instruction. Just like in the x86 coprocessor, the ARM coprocessor has its own status and flags register, (FPSCR20 ), since there is a need to store coprocessor-specific flags. And just like in x86, there are no conditional jump instruction in ARM, that can check bits in the status register of the coprocessor, so there is VMRS , which copies 4 bits (N, Z, C, V) from the coprocessor status word into bits of the general status register (APSR21 ). VMOVGT is the analog of the MOVGT, instruction for D-registers, it executes if one operand is greater than the other while comparing (GT—Greater Than). If it gets executed, the value of b is to be written into D16 (that is currently stored in in D17 ). Otherwise, the value of a stays in the D16 register. The penultimate instruction VMOV prepares the value in the D16 register for returning it via the R0 and R1 register pair. Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) Listing 17.17: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) VMOV D16, R2, R3 ; b VMOV D17, R0, R1 ; a VCMPE.F64 D17, D16 VMRS APSR_nzcv, FPSCR IT GT VMOVGT.F64 D16, D17 VMOV R0, R1, D16 BX LR Almost the same as in the previous example, however slightly different. As we already know, many instructions in ARM mode can be supplemented by condition predicate. But there is no such thing in thumb mode. There is no space in the 16-bit instructions for 4 more bits in which conditions can be encoded. However, thumb-2 was extended to make it possible to specify predicates to old thumb instructions. Here, in the IDA-generated listing, we see the VMOVGT instruction, as in previous example. In fact, the usual VMOV is encoded there, but IDA adds the -GT suffix to it, since there is a ``IT GT'' instruction placed right before it. The IT instruction defines a so-called if-then block. After the instruction it is possible to place up to 4 instructions, each of them has a predicate suffix. In our example, ``IT GT'' implies that the next instruction is to be executed, if the GT (Greater Than) condition is true. Here is a more complex code fragment, by the way, from “Angry Birds” (for iOS): Listing 17.18: Angry Birds Classic ITE NE VMOVNE R2, R3, D16 VMOVEQ R2, R3, D17 ITE stands for if-then-else and it encodes suffixes for the next two instructions. The first instruction executes if the condition encoded in ITE (NE, not equal) is true at, and the second —if the condition is not true. (The inverse condition of NE is EQ (equal)). One more that’s slightly harder, which is also from “Angry Birds”: Listing 17.19: Angry Birds Classic ITTTT EQ MOVEQ R0, R4 ADDEQ SP, SP, #0x20 POPEQ.W {R8,R10} POPEQ {R4-R7,PC} Four “T” symbols in the instruction mnemonic mean that the four subsequent instructions are to be executed if the condition is true. That’s why IDA adds the -EQ suffix to each one of them. And if there was be, for example, ITEEE EQ (if-then-else-else-else), then the suffixes would have been set as follows: -EQ -NE -NE -NE 20(ARM) Floating-Point Status and Control Register 21(ARM) Application Program Status Register 251
  • 276. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Another fragment from “Angry Birds”: Listing 17.20: Angry Birds Classic CMP.W R0, #0xFFFFFFFF ITTE LE SUBLE.W R10, R0, #1 NEGLE R0, R0 MOVGT R10, R0 ITTE (if-then-then-else) implies that the 1st and 2nd instructions are to be executed if the LE (Less or Equal) condition is true, and the 3rd—if the inverse condition (GT—Greater Than) is true. Compilers usually don’t generate all possible combinations. For example, in the mentioned “Angry Birds” game (classic version for iOS) only these variants of the IT instruction are used: IT, ITE, ITT, ITTE, ITTT, ITTTT. How did I learn this? In IDA It is possible to produce listing files, so I created them with an option to show 4 bytes for each opcode . Then, knowing the high part of the 16-bit opcode (IT is 0xBF), I did the following using grep: cat AngryBirdsClassic.lst | grep " BF" | grep "IT" > results.lst By the way, if you program in ARM assembly language manually for thumb-2 mode, and you add conditional suffixes, the assembler will add the IT instructions automatically with the required flags where it is necessary. Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) Listing 17.21: Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) b = -0x20 a = -0x18 val_to_return = -0x10 saved_R7 = -4 STR R7, [SP,#saved_R7]! MOV R7, SP SUB SP, SP, #0x1C BIC SP, SP, #7 VMOV D16, R2, R3 VMOV D17, R0, R1 VSTR D17, [SP,#0x20+a] VSTR D16, [SP,#0x20+b] VLDR D16, [SP,#0x20+a] VLDR D17, [SP,#0x20+b] VCMPE.F64 D16, D17 VMRS APSR_nzcv, FPSCR BLE loc_2E08 VLDR D16, [SP,#0x20+a] VSTR D16, [SP,#0x20+val_to_return] B loc_2E10 loc_2E08 VLDR D16, [SP,#0x20+b] VSTR D16, [SP,#0x20+val_to_return] loc_2E10 VLDR D16, [SP,#0x20+val_to_return] VMOV R0, R1, D16 MOV SP, R7 LDR R7, [SP+0x20+b],#4 BX LR Almost the same as we already saw, but there is too much redundant code because the a and b variables are stored in the local stack, as well as the return value. Optimizing Keil 6/2013 (thumb mode) Listing 17.22: Optimizing Keil 6/2013 (thumb mode) PUSH {R3-R7,LR} MOVS R4, R2 MOVS R5, R3 252
  • 277. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE MOVS R6, R0 MOVS R7, R1 BL __aeabi_cdrcmple BCS loc_1C0 MOVS R0, R6 MOVS R1, R7 POP {R3-R7,PC} loc_1C0 MOVS R0, R4 MOVS R1, R5 POP {R3-R7,PC} Keil doesn’t generate FPU-instructions since it cannot rely on them being supported on the target CPU, and it can- not be done by straightforward bitwise comparing. So it calls an external library function to do the comparison: __ae- abi_cdrcmple. N.B. The result of the comparison is to be left in the flags by this function, so the following BCS (Carry set - Greater than or equal) instruction can work without any additional code. 17.7.3 ARM64 Optimizing GCC (Linaro) 4.9 d_max: ; D0 - a, D1 - b fcmpe d0, d1 fcsel d0, d0, d1, gt ; now result in D0 ret The ARM64 ISA has FPU-instructions which set APSR the CPU flags instead of FPSCR, for convenience. TheFPU is not a separate device here anymore (at least, logically). Here we see FCMPE, it compares the two values passed in D0 and D1 (which are the first and second arguments of the function) and sets APSR flags (N, Z, C, V). FCSEL (Floating Conditional Select) copies the value of D0 or D1 into D0 depending on the condition (GT (Greater Than) here), and again, it uses flags in APSR register instead of FPSCR. This is much more convenient, compared to the instruction set in older CPUs. If the condition is true (GT) then the value of D0 is copied into D0 (i.e., nothing happens). If the condition is not true, the value of D1 is copied into D0. Non-optimizing GCC (Linaro) 4.9 d_max: ; save input arguments in "Register Save Area" sub sp, sp, #16 str d0, [sp,8] str d1, [sp] ; reload values ldr x1, [sp,8] ldr x0, [sp] fmov d0, x1 fmov d1, x0 ; D0 - a, D1 - b fcmpe d0, d1 ble .L76 ; a>b; load D0 (a) into X0 ldr x0, [sp,8] b .L74 .L76: ; a<=b; load D1 (b) into X0 ldr x0, [sp] .L74: ; result in X0 fmov d0, x0 ; result in D0 add sp, sp, 16 ret 253
  • 278. CHAPTER 17. FLOATING-POINT UNIT 17.7. COMPARISON EXAMPLE Non-optimizing GCC is more verbose. First, the function saves its input argument values in the local stack (Register Save Area). Then the code reloads these values into registers X0/X1 and finally copies them to D0/D1 to be compared using FCMPE. A lot of redundant code, but that is how non-optimizing compilers work. FCMPE compares the values and sets the APSR flags. At this moment, the compiler is not thinking yet about the more convenient FCSEL instruction, so it proceed using old methods: using the BLE instruction (Branch if Less than or Equal). In the first case (a > b), the value of a gets loaded into X0. In the other case (a <= b), the value of b gets loadedin X0. Finally, the value from X0 gets copied into D0, because the return value needs to be in this register. Exercise As an exercise, you can try optimizing this piece of code manually by removing redundant instructions and not introducing new ones (including FCSEL). Optimizing GCC (Linaro) 4.9—float I also rewrote this example to use float instead of double. float f_max (float a, float b) { if (a>b) return a; return b; }; f_max: ; S0 - a, S1 - b fcmpe s0, s1 fcsel s0, s0, s1, gt ; now result in S0 ret It is the same code, but the S-registers are used instead of D- ones. It’s because numbers of type float are passed in 32-bit S-registers (which are in fact the lower parts of the 64-bit D-registers). 17.7.4 MIPS The co-processor of the most popular MIPS processor has only one condition bit which can be set in the FPU and checked in the CPU. Earlier MIPS-es have only one condition bit (called FCC0), later ones have 8 (called FCC7-FCC0). These bits are located in the register called FCCR. Listing 17.23: Optimizing GCC 4.4.5 (IDA) d_max: ; set FPU condition bit if $f14<$f12 (b<a): c.lt.d $f14, $f12 or $at, $zero ; NOP ; jump to locret_14 if condition bit is set bc1t locret_14 ; this instruction is always executed (set return value to "a"): mov.d $f0, $f12 ; branch delay slot ; this instruction is executed only if branch was not taken (i.e., if b>=a) ; set return value to "b": mov.d $f0, $f14 locret_14: jr $ra or $at, $zero ; branch delay slot, NOP “C.LT.D” compares two values. “LT” is the condition “Less Than”. “D” implies values of type double. Depending on the result of the comparison, the FCC0 condition bit is either set or cleared. “BC1T” checks the FCC0 bit and jumps if the bit is set. “T” mean that the jump is to be taken if the bit is set (“True”). There is also the instruction “BC1F” which jumps if the bit is cleared (“False”). Depending on the jump, one of function arguments is placed into $F0. 254
  • 279. CHAPTER 17. FLOATING-POINT UNIT 17.8. STACK, CALCULATORS AND REVERSE POLISH NOTATION 17.8 Stack, calculators and reverse Polish notation Now we undestand why some old calculators used reverse Polish notation 22 . For example, for addition of 12 and 34, one has to enter 12, then 34, then press “plus” sign. It’s because old calculators were just stack machine implementations, and this was much simpler than to handle complex expressions with parentheses. 17.9 x64 On how float point numbers are processed in x86-64, read more here: 27 on page 434. 17.10 Exercises 17.10.1 Exercise #1 Eliminate the FXCH instruction in the example 17.7.1 on page 247 and test it. 17.10.2 Exercise #2 What does this code do? Listing 17.24: Optimizing MSVC 2010 __real@4014000000000000 DQ 04014000000000000r ; 5 _a1$ = 8 ; size = 8 _a2$ = 16 ; size = 8 _a3$ = 24 ; size = 8 _a4$ = 32 ; size = 8 _a5$ = 40 ; size = 8 _f PROC fld QWORD PTR _a1$[esp-4] fadd QWORD PTR _a2$[esp-4] fadd QWORD PTR _a3$[esp-4] fadd QWORD PTR _a4$[esp-4] fadd QWORD PTR _a5$[esp-4] fdiv QWORD PTR __real@4014000000000000 ret 0 _f ENDP Listing 17.25: Non-optimizing Keil 6/2013 (thumb mode / compiled for Cortex-R4F CPU) f PROC VADD.F64 d0,d0,d1 VMOV.F64 d1,#5.00000000 VADD.F64 d0,d0,d2 VADD.F64 d0,d0,d3 VADD.F64 d2,d0,d4 VDIV.F64 d0,d2,d1 BX lr ENDP Listing 17.26: Optimizing GCC 4.9 (ARM64) f: fadd d0, d0, d1 fmov d1, 5.0e+0 fadd d2, d0, d2 fadd d3, d2, d3 fadd d0, d3, d4 fdiv d0, d0, d1 ret 22wikipedia 255
  • 280. CHAPTER 17. FLOATING-POINT UNIT 17.10. EXERCISES Listing 17.27: Optimizing GCC 4.4.5 (MIPS) (IDA) f: arg_10 = 0x10 arg_14 = 0x14 arg_18 = 0x18 arg_1C = 0x1C arg_20 = 0x20 arg_24 = 0x24 lwc1 $f0, arg_14($sp) add.d $f2, $f12, $f14 lwc1 $f1, arg_10($sp) lui $v0, ($LC0 >> 16) add.d $f0, $f2, $f0 lwc1 $f2, arg_1C($sp) or $at, $zero lwc1 $f3, arg_18($sp) or $at, $zero add.d $f0, $f2 lwc1 $f2, arg_24($sp) or $at, $zero lwc1 $f3, arg_20($sp) or $at, $zero add.d $f0, $f2 lwc1 $f2, dword_6C or $at, $zero lwc1 $f3, $LC0 jr $ra div.d $f0, $f2 $LC0: .word 0x40140000 # DATA XREF: f+C # f+44 dword_6C: .word 0 # DATA XREF: f+3C Answer G.1.9 on page 955. 256
  • 281. CHAPTER 18. ARRAYS Chapter 18 Arrays An array is just a set of variables in memory that lie next to each other and that have the same type 1 . 18.1 Simple example #include <stdio.h> int main() { int a[20]; int i; for (i=0; i<20; i++) a[i]=i*2; for (i=0; i<20; i++) printf ("a[%d]=%dn", i, a[i]); return 0; }; 18.1.1 x86 MSVC Let’s compile: Listing 18.1: MSVC 2008 _TEXT SEGMENT _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 ; 00000054H mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN6@main $LN5@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN6@main: cmp DWORD PTR _i$[ebp], 20 ; 00000014H jge SHORT $LN4@main mov ecx, DWORD PTR _i$[ebp] shl ecx, 1 mov edx, DWORD PTR _i$[ebp] mov DWORD PTR _a$[ebp+edx*4], ecx jmp SHORT $LN5@main $LN4@main: 1AKA2 “homogeneous container” 257
  • 282. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 20 ; 00000014H jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] mov edx, DWORD PTR _a$[ebp+ecx*4] push edx mov eax, DWORD PTR _i$[ebp] push eax push OFFSET $SG2463 call _printf add esp, 12 ; 0000000cH jmp SHORT $LN2@main $LN1@main: xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP Nothing very special, just two loops: the first is a filling loop and second is a printing loop. The shl ecx, 1 instruction is used for value multiplication by 2 in ECX, more about below 16.2.1 on page 206. 80 bytes are allocated on the stack for the array, 20 elements of 4 bytes. 258
  • 283. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE Let’s try this example in OllyDbg. We see how the array gets filled: each element is 32-bit word of int type and its value is the index multiplied by 2: Figure 18.1: OllyDbg: after array filling Since this array is located in the stack, we can see all its 20 elements there. GCC Here is what GCC 4.4.1 does: Listing 18.2: GCC 4.4.1 public main main proc near ; DATA XREF: _start+17 var_70 = dword ptr -70h var_6C = dword ptr -6Ch var_68 = dword ptr -68h i_2 = dword ptr -54h i = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 70h mov [esp+70h+i], 0 ; i=0 jmp short loc_804840A loc_80483F7: mov eax, [esp+70h+i] mov edx, [esp+70h+i] add edx, edx ; edx=i*2 mov [esp+eax*4+70h+i_2], edx add [esp+70h+i], 1 ; i++ 259
  • 284. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE loc_804840A: cmp [esp+70h+i], 13h jle short loc_80483F7 mov [esp+70h+i], 0 jmp short loc_8048441 loc_804841B: mov eax, [esp+70h+i] mov edx, [esp+eax*4+70h+i_2] mov eax, offset aADD ; "a[%d]=%dn" mov [esp+70h+var_68], edx mov edx, [esp+70h+i] mov [esp+70h+var_6C], edx mov [esp+70h+var_70], eax call _printf add [esp+70h+i], 1 loc_8048441: cmp [esp+70h+i], 13h jle short loc_804841B mov eax, 0 leave retn main endp By the way, variable a is of type int* (the pointer to int) —you can pass a pointer to an array to another function, but it’s more correct to say that a pointer to the first element of the array is passed (the addresses of rest of the elements are calculated in an obvious way). If you index this pointer as a[idx], idx is just to be added to the pointer and the element placed there (to which calculated pointer is pointing) is to be returned. An interesting example: a string of characters like “string” is an array of characters and it has a type of const char[]. An index can also be applied to this pointer. And that is why it is possible to write things like ``string''[i] —this is a correct C/C++ expression! 18.1.2 ARM Non-optimizing Keil 6/2013 (ARM mode) EXPORT _main _main STMFD SP!, {R4,LR} SUB SP, SP, #0x50 ; allocate place for 20 int variables ; first loop MOV R4, #0 ; i B loc_4A0 loc_494 MOV R0, R4,LSL#1 ; R0=R4*2 STR R0, [SP,R4,LSL#2] ; store R0 to SP+R4<<2 (same as SP+R4*4) ADD R4, R4, #1 ; i=i+1 loc_4A0 CMP R4, #20 ; i<20? BLT loc_494 ; yes, run loop body again ; second loop MOV R4, #0 ; i B loc_4C4 loc_4B0 LDR R2, [SP,R4,LSL#2] ; (second printf argument) R2=*(SP+R4<<4) (same as *(SP+R4*4)) MOV R1, R4 ; (first printf argument) R1=i ADR R0, aADD ; "a[%d]=%dn" BL __2printf ADD R4, R4, #1 ; i=i+1 loc_4C4 260
  • 285. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE CMP R4, #20 ; i<20? BLT loc_4B0 ; yes, run loop body again MOV R0, #0 ; value to return ADD SP, SP, #0x50 ; deallocate chunk, allocated for 20 int variables LDMFD SP!, {R4,PC} int type requires 32 bits for storage (or 4 bytes), so to store 20 int variables 80 (0x50) bytes are needed. So that is why the ``SUB SP, SP, #0x50'' instruction in the function’s prologie allocates exactly this amount of space in the stack. In both the first and second loops, the loop iterator i is placed in the R4 register. The number that is to be written into the array is calculated as i ∗ 2, which is effectively equivalent to shifting it left by one bit, so ``MOV R0, R4,LSL#1'' instruction does this. ``STR R0, [SP,R4,LSL#2]'' writes the contents of R0 into the array. Here is how a pointer to array element is calculated: SP points to the start of the array, R4 is i. So shifting i left by 2 bits is effectively equivalent to multiplication by 4 (since each array element has a size of 4 bytes) and then it’s added to the address of the start of the array. The second loop has an inverse ``LDR R2, [SP,R4,LSL#2]'' instruction, it loads the value we need from the array, and the pointer to it is calculated likewise. Optimizing Keil 6/2013 (thumb mode) _main PUSH {R4,R5,LR} ; allocate place for 20 int variables + one more variable SUB SP, SP, #0x54 ; first loop MOVS R0, #0 ; i MOV R5, SP ; pointer to first array element loc_1CE LSLS R1, R0, #1 ; R1=i<<1 (same as i*2) LSLS R2, R0, #2 ; R2=i<<2 (same as i*4) ADDS R0, R0, #1 ; i=i+1 CMP R0, #20 ; i<20? STR R1, [R5,R2] ; store R1 to *(R5+R2) (same R5+i*4) BLT loc_1CE ; yes, i<20, run loop body again ; second loop MOVS R4, #0 ; i=0 loc_1DC LSLS R0, R4, #2 ; R0=i<<2 (same as i*4) LDR R2, [R5,R0] ; load from *(R5+R0) (same as R5+i*4) MOVS R1, R4 ADR R0, aADD ; "a[%d]=%dn" BL __2printf ADDS R4, R4, #1 ; i=i+1 CMP R4, #20 ; i<20? BLT loc_1DC ; yes, i<20, run loop body again MOVS R0, #0 ; value to return ; deallocate chunk, allocated for 20 int variables + one more variable ADD SP, SP, #0x54 POP {R4,R5,PC} Thumb code is very similar. Thumb mode has special instructions for bit shifting (like LSLS), which calculates the value to be written into the array and the address of each element in the array as well. The compiler allocates slightly more space in the local stack, however, the last 4 bytes are not used. Non-optimizing GCC 4.9.1 (ARM64) Listing 18.3: Non-optimizing GCC 4.9.1 (ARM64) .LC0: .string "a[%d]=%dn" main: ; save FP and LR in stack frame: stp x29, x30, [sp, -112]! ; set stack frame (FP=SP) 261
  • 286. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE add x29, sp, 0 ; setting initial counter variable at 0 (WZR is the register always holding zero): str wzr, [x29,108] ; jump to loop condition checking code: b .L2 .L3: ; load value of "i" variable: ldr w0, [x29,108] ; multiplicate it by 2: lsl w2, w0, 1 ; find a place of an array in local stack: add x0, x29, 24 ; load 32-bit integer from local stack and sign extend it to 64-bit one: ldrsw x1, [x29,108] ; calculate address of element (X0+X1<<2=array address+i*4) and store W2 (i*2) there: str w2, [x0,x1,lsl 2] ; increment counter (i): ldr w0, [x29,108] add w0, w0, 1 str w0, [x29,108] .L2: ; check if we finished: ldr w0, [x29,108] cmp w0, 19 ; jump to L3 (loop body begin) if not: ble .L3 ; second part of the function begins here. ; setting initial counter variable at 0. ; by the way, the same place in the local stack was used for counter, ; because the same local variable (i) is being used as counter. str wzr, [x29,108] b .L4 .L5: ; calculate array address: add x0, x29, 24 ; load "i" value: ldrsw x1, [x29,108] ; load value from the array at the address (X0+X1<<2 = address of array + i*4) ldr w2, [x0,x1,lsl 2] ; load address of the "a[%d]=%dn" string: adrp x0, .LC0 add x0, x0, :lo12:.LC0 ; load "i" variable to W1 and pass it to printf() as second argument: ldr w1, [x29,108] ; W2 still contains the value of array element which was just loaded. ; call printf(): bl printf ; increment "i" variable: ldr w0, [x29,108] add w0, w0, 1 str w0, [x29,108] .L4: ; are we finished? ldr w0, [x29,108] cmp w0, 19 ; jump to the loop body begin if not: ble .L5 ; return 0 mov w0, 0 ; restore FP and LR: ldp x29, x30, [sp], 112 ret 18.1.3 MIPS The function uses a lot of S- registers which must be preserved, so that’s why its values are saved in the function prologue and restored in the epilogue. 262
  • 287. CHAPTER 18. ARRAYS 18.1. SIMPLE EXAMPLE Listing 18.4: Optimizing GCC 4.4.5 (IDA) main: var_70 = -0x70 var_68 = -0x68 var_14 = -0x14 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 = -4 ; function prologue: lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x80 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x80+var_4($sp) sw $s3, 0x80+var_8($sp) sw $s2, 0x80+var_C($sp) sw $s1, 0x80+var_10($sp) sw $s0, 0x80+var_14($sp) sw $gp, 0x80+var_70($sp) addiu $s1, $sp, 0x80+var_68 move $v1, $s1 move $v0, $zero ; that value will be used as a loop terminator. ; it was precalculated by GCC compiler at compile stage: li $a0, 0x28 # '(' loc_34: # CODE XREF: main+3C ; store value into memory: sw $v0, 0($v1) ; increase value to be stored by 2 at each iteration: addiu $v0, 2 ; loop terminator reached? bne $v0, $a0, loc_34 ; add 4 to address anyway: addiu $v1, 4 ; array filling loop is ended ; second loop begin la $s3, $LC0 # "a[%d]=%dn" ; "i" variable will reside in $s0: move $s0, $zero li $s2, 0x14 loc_54: # CODE XREF: main+70 ; call printf(): lw $t9, (printf & 0xFFFF)($gp) lw $a2, 0($s1) move $a1, $s0 move $a0, $s3 jalr $t9 ; increment "i": addiu $s0, 1 lw $gp, 0x80+var_70($sp) ; jump to loop body if end is not reached: bne $s0, $s2, loc_54 ; move memory pointer to the next 32-bit word: addiu $s1, 4 ; function epilogue lw $ra, 0x80+var_4($sp) move $v0, $zero lw $s3, 0x80+var_8($sp) lw $s2, 0x80+var_C($sp) lw $s1, 0x80+var_10($sp) lw $s0, 0x80+var_14($sp) jr $ra addiu $sp, 0x80 $LC0: .ascii "a[%d]=%dn"<0> # DATA XREF: main+44 263
  • 288. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW Something interesting: there are two loops and the first one doesn’t needs i, it needs only i ∗ 2 (increased by 2 at each iteration) and also the address in memory (increased by 4 at each iteration). So here we see two variables, one (in $V0) increasing by 2 each time, and another (in $V1) — by 4. The second loop is where printf() is called and it reports the value of i to the user, so there is a variable which is increased by 1 each time (in $S0) and also a memory address (in $S1) increased by 4 each time. That reminds us of loop optimizations we considered earlier: 39 on page 480. Their goal is to get rid of of multiplica- tions. 18.2 Buffer overflow 18.2.1 Reading outside array bounds So, array indexing is just array[index]. If you study the generated code closely, you’ll probably note the missing index bounds checking, which could check if it is less than 20. What if the index is 20 or greater? That’s the one C/C++ feature it is often blamed for. Here is a code that successfully compiles and works: #include <stdio.h> int main() { int a[20]; int i; for (i=0; i<20; i++) a[i]=i*2; printf ("a[20]=%dn", a[20]); return 0; }; Compilation results (MSVC 2008): Listing 18.5: Non-optimizing MSVC 2008 $SG2474 DB 'a[20]=%d', 0aH, 00H _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 20 jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] shl ecx, 1 mov edx, DWORD PTR _i$[ebp] mov DWORD PTR _a$[ebp+edx*4], ecx jmp SHORT $LN2@main $LN1@main: mov eax, DWORD PTR _a$[ebp+80] push eax push OFFSET $SG2474 ; 'a[20]=%d' call DWORD PTR __imp__printf add esp, 8 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 264
  • 289. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW _TEXT ENDS END When I run it, I get: Figure 18.2: OllyDbg: console output It is just something that was lying in the stack near to the array, 80 bytes away from its first element. 265
  • 290. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW Let’s try to find out where did this value come from, using OllyDbg. Let’s load and find the value located right after the last array element: Figure 18.3: OllyDbg: reading of the 20th element and execution of printf() What is this? Judging by the stack layout, this is the saved value of the EBP register. 266
  • 291. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW Let’s trace further and see how it gets restored: Figure 18.4: OllyDbg: restoring value of EBP Indeed, how it could be different? The compiler may generate some additional code to check the index value to be always in the array’s bounds (like in higher-level programming languages3 ) but this makes the code slower. 18.2.2 Writing beyond array bounds OK, we read some values from the stack illegally, but what if we could write something to it? Here is what we have got: #include <stdio.h> int main() { int a[20]; int i; for (i=0; i<30; i++) a[i]=i; return 0; }; MSVC And what we get: Listing 18.6: Non-optimizing MSVC 2008 _TEXT SEGMENT 3Java, Python, etc 267
  • 292. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 30 ; 0000001eH jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] mov edx, DWORD PTR _i$[ebp] ; that instruction is obviously redundant mov DWORD PTR _a$[ebp+ecx*4], edx ; ECX could be used as second operand here instead jmp SHORT $LN2@main $LN1@main: xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP The compiled program crashes after running. No wonder. Let’s see where exactly does it is crash. 268
  • 293. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW Let’s load it into OllyDbg, and trace until all 30 elements are written: Figure 18.5: OllyDbg: after restoring the value of EBP 269
  • 294. CHAPTER 18. ARRAYS 18.2. BUFFER OVERFLOW Trace until the function end: Figure 18.6: OllyDbg: EIP was restored, but OllyDbg can’t disassemble at 0x15 Now please keep your eyes on the registers. EIP is 0x15 now. It is not a legal address for code —at least for win32 code! We got there somehow against our will. It is also interesting that the EBP register contain 0x14, ECX and EDX —0x1D. Let’s study stack layout a bit more. After the control flow was passed to main(), the value in the EBP register was saved on the stack. Then, 84 bytes were allocated for the array and the i variable. That’s (20+1)*sizeof(int). ESP now points to the _i variable in the local stack and after the execution of the next PUSH something, something is appearing next to _i. That’s the stack layout while the control is in main(): ESP 4 bytes allocated for i variable ESP+4 80 bytes allocated for a[20] array ESP+84 saved EBP value ESP+88 return address a[19]=something statement writes the last int in the bounds of the array (in bounds so far!) a[20]=something statement writes something to the place where the value of EBP is saved. Please take a look at the register state at the moment of the crash. In our case, 20 was written in the 20th element. At the function end, the function epilogue restores the original EBP value. (20 in decimal is 0x14 in hexadecimal). Then RET gets executed, which is effectively equivalent to POP EIP instruction. The RET instruction takes the return address from the stack (that is the address in CRT), which was called main()), and 21 iss stored there (0x15 in hexadecimal). The CPU traps at address 0x15, but there is no executable code there, so exception gets raised. Welcome! It is called a buffer overflow4 . 4wikipedia 270
  • 295. CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS Replace the int array with a string (char array), create a long string deliberately and pass it to the program, to the function, which doesn’t check the length of the string and copies it in a short buffer, and you’ll able to point the program to an address to which it must jump. It’s not that simple in reality, but that is how it emerged 5 GCC Let’s try the same code in GCC 4.4.1. We get: public main main proc near a = dword ptr -54h i = dword ptr -4 push ebp mov ebp, esp sub esp, 60h ; 96 mov [ebp+i], 0 jmp short loc_80483D1 loc_80483C3: mov eax, [ebp+i] mov edx, [ebp+i] mov [ebp+eax*4+a], edx add [ebp+i], 1 loc_80483D1: cmp [ebp+i], 1Dh jle short loc_80483C3 mov eax, 0 leave retn main endp Running this in Linux will produce: Segmentation fault. If we run this in the GDB debugger, we get this: (gdb) r Starting program: /home/dennis/RE/1 Program received signal SIGSEGV, Segmentation fault. 0x00000016 in ?? () (gdb) info registers eax 0x0 0 ecx 0xd2f96388 -755407992 edx 0x1d 29 ebx 0x26eff4 2551796 esp 0xbffff4b0 0xbffff4b0 ebp 0x15 0x15 esi 0x0 0 edi 0x0 0 eip 0x16 0x16 eflags 0x10202 [ IF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) The register values are slightly different than in win32 example, since the stack layout is slightly different too. 18.3 Buffer overflow protection methods There are several methods to protect against this scourge, regardless of the C/C++ programmers’ negligence. MSVC has options like6 : 5Classic article about it: [One96]. 6Wikipedia: compiler-side buffer overflow protection methods: wikipedia 271
  • 296. CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS /RTCs Stack Frame runtime checking /GZ Enable stack checks (/RTCs) One of the methods is to write a random value between the local variables in stack at function prologue and to check it in function epilogue before the function exits. If value is not the same, do not execute the last instruction RET, but stop (or hang). The process will halt, but that is much better than a remote attack to your host. This random value is called a “canary” sometimes, it is related to the miners’ canary7 , they were used by miners in the past days in order to detect poisonous gases quickly. Canaries are very sensitive to mine gases, they become very agitated in case of danger, or even die. If we compile our very simple array example ( 18.1 on page 257) in MSVC with RTC1 and RTCs option, you can see a call to @_RTC_CheckStackVars@8 a function at the end of the function that checks if the “canary” is correct. Let’s see how GCC handles this. Let’s take an alloca() ( 5.2.4 on page 25) example: #ifdef __GNUC__ #include <alloca.h> // GCC #else #include <malloc.h> // MSVC #endif #include <stdio.h> void f() { char *buf=(char*)alloca (600); #ifdef __GNUC__ snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // GCC #else _snprintf (buf, 600, "hi! %d, %d, %dn", 1, 2, 3); // MSVC #endif puts (buf); }; By default, without any additional options, GCC 4.7.3 inserts a “canary” check into the code: Listing 18.7: GCC 4.7.3 .LC0: .string "hi! %d, %d, %dn" f: push ebp mov ebp, esp push ebx sub esp, 676 lea ebx, [esp+39] and ebx, -16 mov DWORD PTR [esp+20], 3 mov DWORD PTR [esp+16], 2 mov DWORD PTR [esp+12], 1 mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %dn" mov DWORD PTR [esp+4], 600 mov DWORD PTR [esp], ebx mov eax, DWORD PTR gs:20 ; canary mov DWORD PTR [ebp-12], eax xor eax, eax call _snprintf mov DWORD PTR [esp], ebx call puts mov eax, DWORD PTR [ebp-12] xor eax, DWORD PTR gs:20 ; check canary jne .L5 mov ebx, DWORD PTR [ebp-4] leave ret .L5: call __stack_chk_fail 7wikipedia 272
  • 297. CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS The random value is located in gs:20. It gets written on the stack and then at the end of the function the value in the stack is compared with the correct “canary” in gs:20. If the values are not equal, the __stack_chk_fail function is called and we can see in the console something like that (Ubuntu 13.04 x86): *** buffer overflow detected ***: ./2_1 terminated ======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x63)[0xb7699bc3] /lib/i386-linux-gnu/libc.so.6(+0x10593a)[0xb769893a] /lib/i386-linux-gnu/libc.so.6(+0x105008)[0xb7698008] /lib/i386-linux-gnu/libc.so.6(_IO_default_xsputn+0x8c)[0xb7606e5c] /lib/i386-linux-gnu/libc.so.6(_IO_vfprintf+0x165)[0xb75d7a45] /lib/i386-linux-gnu/libc.so.6(__vsprintf_chk+0xc9)[0xb76980d9] /lib/i386-linux-gnu/libc.so.6(__sprintf_chk+0x2f)[0xb7697fef] ./2_1[0x8048404] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0xb75ac935] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 08:01 2097586 /home/dennis/2_1 08049000-0804a000 r--p 00000000 08:01 2097586 /home/dennis/2_1 0804a000-0804b000 rw-p 00001000 08:01 2097586 /home/dennis/2_1 094d1000-094f2000 rw-p 00000000 00:00 0 [heap] b7560000-b757b000 r-xp 00000000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b757b000-b757c000 r--p 0001a000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b757c000-b757d000 rw-p 0001b000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b7592000-b7593000 rw-p 00000000 00:00 0 b7593000-b7740000 r-xp 00000000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7740000-b7742000 r--p 001ad000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7742000-b7743000 rw-p 001af000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7743000-b7746000 rw-p 00000000 00:00 0 b775a000-b775d000 rw-p 00000000 00:00 0 b775d000-b775e000 r-xp 00000000 00:00 0 [vdso] b775e000-b777e000 r-xp 00000000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so b777e000-b777f000 r--p 0001f000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so b777f000-b7780000 rw-p 00020000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so bff35000-bff56000 rw-p 00000000 00:00 0 [stack] Aborted (core dumped) gs—is the so-called segment register, these registers were used widely in MS-DOS and DOS-extenders times. Today, its function is different. To say it briefly, the gs register in Linux always points to the TLS ( 65 on page 671) —some information specific to thread is stored there (by the way, in win32 the fs register plays the same role, pointing to TIB8 9 ). More information can be found in the Linux kernel source code (at least in 3.11 version), in arch/x86/include/asm/stackprotector.h this variable is described in the comments. 18.3.1 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) Let’s get back to our simple array example ( 18.1 on page 257), again, now we can see how LLVM checks the correctness of the “canary”: _main var_64 = -0x64 var_60 = -0x60 var_5C = -0x5C var_58 = -0x58 var_54 = -0x54 var_50 = -0x50 var_4C = -0x4C var_48 = -0x48 var_44 = -0x44 var_40 = -0x40 var_3C = -0x3C var_38 = -0x38 var_34 = -0x34 var_30 = -0x30 var_2C = -0x2C var_28 = -0x28 var_24 = -0x24 var_20 = -0x20 8Thread Information Block 9wikipedia 273
  • 298. CHAPTER 18. ARRAYS 18.3. BUFFER OVERFLOW PROTECTION METHODS var_1C = -0x1C var_18 = -0x18 canary = -0x14 var_10 = -0x10 PUSH {R4-R7,LR} ADD R7, SP, #0xC STR.W R8, [SP,#0xC+var_10]! SUB SP, SP, #0x54 MOVW R0, #aObjc_methtype ; "objc_methtype" MOVS R2, #0 MOVT.W R0, #0 MOVS R5, #0 ADD R0, PC LDR.W R8, [R0] LDR.W R0, [R8] STR R0, [SP,#0x64+canary] MOVS R0, #2 STR R2, [SP,#0x64+var_64] STR R0, [SP,#0x64+var_60] MOVS R0, #4 STR R0, [SP,#0x64+var_5C] MOVS R0, #6 STR R0, [SP,#0x64+var_58] MOVS R0, #8 STR R0, [SP,#0x64+var_54] MOVS R0, #0xA STR R0, [SP,#0x64+var_50] MOVS R0, #0xC STR R0, [SP,#0x64+var_4C] MOVS R0, #0xE STR R0, [SP,#0x64+var_48] MOVS R0, #0x10 STR R0, [SP,#0x64+var_44] MOVS R0, #0x12 STR R0, [SP,#0x64+var_40] MOVS R0, #0x14 STR R0, [SP,#0x64+var_3C] MOVS R0, #0x16 STR R0, [SP,#0x64+var_38] MOVS R0, #0x18 STR R0, [SP,#0x64+var_34] MOVS R0, #0x1A STR R0, [SP,#0x64+var_30] MOVS R0, #0x1C STR R0, [SP,#0x64+var_2C] MOVS R0, #0x1E STR R0, [SP,#0x64+var_28] MOVS R0, #0x20 STR R0, [SP,#0x64+var_24] MOVS R0, #0x22 STR R0, [SP,#0x64+var_20] MOVS R0, #0x24 STR R0, [SP,#0x64+var_1C] MOVS R0, #0x26 STR R0, [SP,#0x64+var_18] MOV R4, 0xFDA ; "a[%d]=%dn" MOV R0, SP ADDS R6, R0, #4 ADD R4, PC B loc_2F1C ; second loop begin loc_2F14 ADDS R0, R5, #1 LDR.W R2, [R6,R5,LSL#2] MOV R5, R0 loc_2F1C 274
  • 299. CHAPTER 18. ARRAYS 18.4. ONE MORE WORD ABOUT ARRAYS MOV R0, R4 MOV R1, R5 BLX _printf CMP R5, #0x13 BNE loc_2F14 LDR.W R0, [R8] LDR R1, [SP,#0x64+canary] CMP R0, R1 ITTTT EQ ; canary still correct? MOVEQ R0, #0 ADDEQ SP, SP, #0x54 LDREQ.W R8, [SP+0x64+var_64],#4 POPEQ {R4-R7,PC} BLX ___stack_chk_fail First of all, as we see, LLVM “unrolled” the loop and all values were written into an array one-by-one, pre-calculated, as LLVM concluded it can work faster. By the way, instructions in ARM mode may help to do this even faster, and finding this could be your homework. At the function end we see the comparison of the “canaries” —the one in the local stack and the correct one, to which R8 points. If they are equal to each other, a 4-instruction block is triggered by ``ITTTT EQ'', which contains writ- ing 0 in R0, the function epilogue and exit. If the “canaries” are not equal, the block being skipped, and the jump to ___stack_chk_fail function will occur, which, as I suppose, will halt execution. 18.4 One more word about arrays Now we understand why it is impossible to write something like this in C/C++ code 10 : void f(int size) { int a[size]; ... }; That’s just because the compiler must know the exact array size to allocate space for it in the local stack layout on at the compiling stage. If you need an array of arbitrary size, allocate it by using malloc(), then access the allocated memory block as an array of variables of the type you need. Or use the C99 standard feature[ISO07, pp. 6.7.5/2], but it looks like alloca() ( 5.2.4 on page 25) internally. 18.5 Array of pointers to strings Here is an example for an array of pointers. Listing 18.8: Get month name #include <stdio.h> const char* month1[]= { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // in 0..11 range const char* get_month1 (int month) 10However, it is possible in C99 standard[ISO07, pp. 6.7.5/2]: GCC actually does this by allocating an array dynamically on the stack (like alloca() ( 5.2.4 on page 25)) 275
  • 300. CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS { return month1[month]; }; 18.5.1 x64 Listing 18.9: Optimizing MSVC 2013 x64 _DATA SEGMENT month1 DQ FLAT:$SG3122 DQ FLAT:$SG3123 DQ FLAT:$SG3124 DQ FLAT:$SG3125 DQ FLAT:$SG3126 DQ FLAT:$SG3127 DQ FLAT:$SG3128 DQ FLAT:$SG3129 DQ FLAT:$SG3130 DQ FLAT:$SG3131 DQ FLAT:$SG3132 DQ FLAT:$SG3133 $SG3122 DB 'January', 00H $SG3123 DB 'February', 00H $SG3124 DB 'March', 00H $SG3125 DB 'April', 00H $SG3126 DB 'May', 00H $SG3127 DB 'June', 00H $SG3128 DB 'July', 00H $SG3129 DB 'August', 00H $SG3130 DB 'September', 00H $SG3156 DB '%s', 0aH, 00H $SG3131 DB 'October', 00H $SG3132 DB 'November', 00H $SG3133 DB 'December', 00H _DATA ENDS month$ = 8 get_month1 PROC movsxd rax, ecx lea rcx, OFFSET FLAT:month1 mov rax, QWORD PTR [rcx+rax*8] ret 0 get_month1 ENDP The code is very simple: • The first MOVSXD instruction copies a 32-bit value from ECX (where month argument is passed) to RAX with sign- extension (because the month argument is of type int). The reason for the sign extension is that this 32-bit value is to be used in calculations with other 64-bit values. Hence, it has to be promoted to 64-bit 11 . • Then the address of the pointer table is loaded into RCX. • Finally, the input value (month) is multiplied by 8 and added to the address. Indeed: we are in a 64-bit environment and all address (or pointers) require exactly 64 bits (or 8 bytes) for storage. Hence, each table element is 8 bytes wide. And that’s why to pick a specific element, month ∗ 8 bytes has to be skipped from the start. That’s what MOV does. In addition, this instruction also loads the element at this address. For 1, an element would be a pointer to a string that contains “February”, etc. Optimizing GCC 4.9 can do the job even better 12 : Listing 18.10: Optimizing GCC 4.9 x64 movsx rdi, edi mov rax, QWORD PTR month1[0+rdi*8] ret 11It is somewhat weird, but negative array index could be passed here as month (negative array indices will have been explained later: 52 on page 589) . And if this happens, the negative input value of int type is sign-extended correctly and the corresponding element before table is picked. It is not going to work correctly without sign-extension. 12“0+” was left in the listing because GCC assembler output is not tidy enough to eliminate it. It’s displacement, and it’s zero here. 276
  • 301. CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS 32-bit MSVC Let’s also compile it in the 32-bit MSVC compiler: Listing 18.11: Optimizing MSVC 2013 x86 _month$ = 8 _get_month1 PROC mov eax, DWORD PTR _month$[esp-4] mov eax, DWORD PTR _month1[eax*4] ret 0 _get_month1 ENDP The input value does not need to be extended to 64-bit value, so it is used as is. And it’s multiplied by 4, because the table elements are 32-bit (or 4 bytes) wide. 18.5.2 32-bit ARM ARM in ARM mode Listing 18.12: Optimizing Keil 6/2013 (ARM mode) get_month1 PROC LDR r1,|L0.100| LDR r0,[r1,r0,LSL #2] BX lr ENDP |L0.100| DCD ||.data|| DCB "January",0 DCB "February",0 DCB "March",0 DCB "April",0 DCB "May",0 DCB "June",0 DCB "July",0 DCB "August",0 DCB "September",0 DCB "October",0 DCB "November",0 DCB "December",0 AREA ||.data||, DATA, ALIGN=2 month1 DCD ||.conststring|| DCD ||.conststring||+0x8 DCD ||.conststring||+0x11 DCD ||.conststring||+0x17 DCD ||.conststring||+0x1d DCD ||.conststring||+0x21 DCD ||.conststring||+0x26 DCD ||.conststring||+0x2b DCD ||.conststring||+0x32 DCD ||.conststring||+0x3c DCD ||.conststring||+0x44 DCD ||.conststring||+0x4d The address of the able is loaded in R1. All the rest is done using just one LDR instruction. Then input value month is shifted left by 2 (which is the same as multiplying by 4), then added to R1 (where the address of the table is) and then a table element is loaded from this address. The 32-bit table element is loaded into R0 from the table. ARM in Thumb mode The code is mostly the same, but less dense, because the LSL suffix cannot be specified in the LDR instruction here: get_month1 PROC LSLS r0,r0,#2 LDR r1,|L0.64| LDR r0,[r1,r0] 277
  • 302. CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS BX lr ENDP 18.5.3 ARM64 Listing 18.13: Optimizing GCC 4.9 ARM64 get_month1: adrp x1, .LANCHOR0 add x1, x1, :lo12:.LANCHOR0 ldr x0, [x1,w0,sxtw 3] ret .LANCHOR0 = . + 0 .type month1, %object .size month1, 96 month1: .xword .LC2 .xword .LC3 .xword .LC4 .xword .LC5 .xword .LC6 .xword .LC7 .xword .LC8 .xword .LC9 .xword .LC10 .xword .LC11 .xword .LC12 .xword .LC13 .LC2: .string "January" .LC3: .string "February" .LC4: .string "March" .LC5: .string "April" .LC6: .string "May" .LC7: .string "June" .LC8: .string "July" .LC9: .string "August" .LC10: .string "September" .LC11: .string "October" .LC12: .string "November" .LC13: .string "December" The address of the table is loaded in X1 using ADRP/ADD pair. Then corresponding element is picked using just one LDR, which takes W0 (the register where input argument month is), shifts it 3 bits to the left (which is the same as multiplying by 8), sign-extends it (this is what “sxtw” suffix implies) and adds to X0. Then the 64-bit value is loaded from the table into X0. 18.5.4 MIPS Listing 18.14: Optimizing GCC 4.4.5 (IDA) get_month1: ; load address of table into $v0: la $v0, month1 ; take input value and multiply it by 4: sll $a0, 2 ; sum up address of table and multiplied value: 278
  • 303. CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS addu $a0, $v0 ; load table element at this address into $v0: lw $v0, 0($a0) ; return jr $ra or $at, $zero ; branch delay slot, NOP .data # .data.rel.local .globl month1 month1: .word aJanuary # "January" .word aFebruary # "February" .word aMarch # "March" .word aApril # "April" .word aMay # "May" .word aJune # "June" .word aJuly # "July" .word aAugust # "August" .word aSeptember # "September" .word aOctober # "October" .word aNovember # "November" .word aDecember # "December" .data # .rodata.str1.4 aJanuary: .ascii "January"<0> aFebruary: .ascii "February"<0> aMarch: .ascii "March"<0> aApril: .ascii "April"<0> aMay: .ascii "May"<0> aJune: .ascii "June"<0> aJuly: .ascii "July"<0> aAugust: .ascii "August"<0> aSeptember: .ascii "September"<0> aOctober: .ascii "October"<0> aNovember: .ascii "November"<0> aDecember: .ascii "December"<0> 18.5.5 Array overflow Our function accepts values in the range of 0..11, but what if 12 is passed? There is no element in table at this place. So the function will load some value which happens to be there, and return it. Soon after, some other function can try to get a text string from this address and may crash. I have compiled the example in MSVC for win64 and opened it in IDA to see what the linker has placed after the table: Listing 18.15: Executable file in IDA off_140011000 dq offset aJanuary_1 ; DATA XREF: .text:0000000140001003 ; "January" dq offset aFebruary_1 ; "February" dq offset aMarch_1 ; "March" dq offset aApril_1 ; "April" dq offset aMay_1 ; "May" dq offset aJune_1 ; "June" dq offset aJuly_1 ; "July" dq offset aAugust_1 ; "August" dq offset aSeptember_1 ; "September" dq offset aOctober_1 ; "October" dq offset aNovember_1 ; "November" dq offset aDecember_1 ; "December" aJanuary_1 db 'January',0 ; DATA XREF: sub_140001020+4 ; .data:off_140011000 aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008 align 4 aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010 align 4 aApril_1 db 'April',0 ; DATA XREF: .data:0000000140011018 Month names are came right after. Our program is tiny, so there isn’t much data to pack in the data segment, so it just the month names. But I have to note that there might be really anything that linker has decided to put by chance. So what if 12 is passed to the function? The 13th element will be returned. Let’s see how the CPU treating the bytes there as a 64-bit value: 279
  • 304. CHAPTER 18. ARRAYS 18.5. ARRAY OF POINTERS TO STRINGS Listing 18.16: Executable file in IDA off_140011000 dq offset qword_140011060 ; DATA XREF: .text:0000000140001003 dq offset aFebruary_1 ; "February" dq offset aMarch_1 ; "March" dq offset aApril_1 ; "April" dq offset aMay_1 ; "May" dq offset aJune_1 ; "June" dq offset aJuly_1 ; "July" dq offset aAugust_1 ; "August" dq offset aSeptember_1 ; "September" dq offset aOctober_1 ; "October" dq offset aNovember_1 ; "November" dq offset aDecember_1 ; "December" qword_140011060 dq 797261756E614Ah ; DATA XREF: sub_140001020+4 ; .data:off_140011000 aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008 align 4 aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010 And this is 0x797261756E614A. Soon after, some other function (presumably, one that processes strings) may try to read bytes at this address, expecting a C-string there. Most likely it is about to crash, because this value does’t look like a valid address. Array overflow protection If something can go wrong, it will Murphy’s Law It’s a bit naïve to expect that every programmer who use your function or library will never pass an argument larger than 11. There exists the philosophy that says “fail early and fail loudly” or “fail-fast”, which teaches to report problems as early as possible and stop. One such method in C/C++ is assertions. We can modify our program to fail if an incorrect value is passed: Listing 18.17: assert() added const char* get_month1_checked (int month) { assert (month<12); return month1[month]; }; The assertion macro checks for valid values at every function start and fails if the expression is false. Listing 18.18: Optimizing MSVC 2013 x64 $SG3143 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '.', 00H DB 'c', 00H, 00H, 00H $SG3144 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '<', 00H DB '1', 00H, '2', 00H, 00H, 00H month$ = 48 get_month1_checked PROC $LN5: push rbx sub rsp, 32 movsxd rbx, ecx cmp ebx, 12 jl SHORT $LN3@get_month1 lea rdx, OFFSET FLAT:$SG3143 lea rcx, OFFSET FLAT:$SG3144 mov r8d, 29 call _wassert $LN3@get_month1: lea rcx, OFFSET FLAT:month1 mov rax, QWORD PTR [rcx+rbx*8] add rsp, 32 pop rbx 280
  • 305. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS ret 0 get_month1_checked ENDP In fact, assert() is not a function, but macro. It checks for a condition, then passes also the line number and file name to another function which reports this information to the user. Here we see that both file name and condition are encoded in UTF-16. The line number is also passed (it’s 29). This mechanism is probably the same in all compilers. Here is what GCC does: Listing 18.19: Optimizing GCC 4.9 x64 .LC1: .string "month.c" .LC2: .string "month<12" get_month1_checked: cmp edi, 11 jg .L6 movsx rdi, edi mov rax, QWORD PTR month1[0+rdi*8] ret .L6: push rax mov ecx, OFFSET FLAT:__PRETTY_FUNCTION__.2423 mov edx, 29 mov esi, OFFSET FLAT:.LC1 mov edi, OFFSET FLAT:.LC2 call __assert_fail __PRETTY_FUNCTION__.2423: .string "get_month1_checked" So the macro in GCC also passes the function name for convenience. Nothing is really free, and this is true for the sanitizing checks as well. They make your program slower, especially if the assert() macros used in small time-critical functions. So MSVC, for example, leaves the checks in Debug builds, but in Release builds they all disappear. Microsoft Windows NT kernels come in “checked” and “free” builds 13 . The first has validation checks (hence, “checked”), the second one doesn’t (hence, “free” of checks). 18.6 Multidimensional arrays Internally, a multidimensional array is essentially the same thing as a linear array. Since the computer memory is linear, it is an one-dimensional array. For convenience, this multi-dimensional array can be easily represented as one-dimensional. For example, thit is how the elements of the a[3][4] array are placed in one-dimensional array of 12 cells: [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] [1][2] [1][3] [2][0] [2][1] [2][2] [2][3] Table 18.1: Two-dimensional array represented in memory as one-dimensional Here is how each cell of 3*4 array are placed in memory: 13MSDN 281
  • 306. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS 0 1 2 3 4 5 6 7 8 9 10 11 Table 18.2: Memory addresses of each cell of two-dimensional array So, in order to calculate the address of the element we need, we first multiply the first index by 4 (matrix width) and then add the second index. That’s called row-major order, and this method of array and matrix representation is used in at least C/C++ and Python. The term row-major order in plain English language means: “first, write the elements of the first row, then the second row …and finally the elements of the last row”. Another method for representation is called column-major order (the array indices are used in reverse order) and it is used at least in FORTRAN, MATLAB and R. column-major order term in plain English language means: “first, write the elements of the first column, then the second column …and finally the elements of the last column”. Which method is better? In general, in terms of performance and cache memory, the best scheme for data organization is the one, in which the elements are accessed sequentially. So if your function accesses data per row, row-major order is better, and vice versa. 18.6.1 Two-dimensional array example We are going to work with an array of type char, which implies that each element requires only one byte in memory. Row filling example Let’s fill the second row with these values: 0...3: Listing 18.20: Row filling example #include <stdio.h> char a[3][4]; int main() { int x, y; // clear array for (x=0; x<3; x++) for (y=0; y<4; y++) a[x][y]=0; // fill second row by 0..3: for (y=0; y<4; y++) a[1][y]=y; }; I have marked all three rows with red. We see that second row now has values 0, 1, 2 and 3: Figure 18.7: OllyDbg: array is filled Column filling example Let’s fill the third column with values: 0...2. Listing 18.21: Column filling example #include <stdio.h> char a[3][4]; int main() 282
  • 307. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS { int x, y; // clear array for (x=0; x<3; x++) for (y=0; y<4; y++) a[x][y]=0; // fill third column by 0..2: for (x=0; x<3; x++) a[x][2]=x; }; I have also marked the three rows in red here. We see that in each row, at third position these values are written: 0, 1 and 2. Figure 18.8: OllyDbg: array is filled 18.6.2 Access two-dimensional array as one-dimensional I can easily show you how to access a two-dimensional array as one-dimensional array in at least two other ways: #include <stdio.h> char a[3][4]; char get_by_coordinates1 (char array[3][4], int a, int b) { return array[a][b]; }; char get_by_coordinates2 (char *array, int a, int b) { // treat input array as one-dimensional // 4 is array width here return array[a*4+b]; }; char get_by_coordinates3 (char *array, int a, int b) { // treat input array as pointer, // calculate address, get value at it // 4 is array width here return *(array+a*4+b); }; int main() { a[2][3]=123; printf ("%dn", get_by_coordinates1(a, 2, 3)); printf ("%dn", get_by_coordinates2(a, 2, 3)); printf ("%dn", get_by_coordinates3(a, 2, 3)); }; Compile and run it: it shows correct values. What MSVC 2013 did is fascinating, all three routines are just the same! Listing 18.22: Optimizing MSVC 2013 x64 array$ = 8 a$ = 16 b$ = 24 283
  • 308. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS get_by_coordinates3 PROC ; RCX=address of array ; RDX=a ; R8=b movsxd rax, r8d ; EAX=b movsxd r9, edx ; R9=a add rax, rcx ; RAX=b+address of array movzx eax, BYTE PTR [rax+r9*4] ; AL=load byte at address RAX+R9*4=b+address of array+a*4=address of array+a*4+b ret 0 get_by_coordinates3 ENDP array$ = 8 a$ = 16 b$ = 24 get_by_coordinates2 PROC movsxd rax, r8d movsxd r9, edx add rax, rcx movzx eax, BYTE PTR [rax+r9*4] ret 0 get_by_coordinates2 ENDP array$ = 8 a$ = 16 b$ = 24 get_by_coordinates1 PROC movsxd rax, r8d movsxd r9, edx add rax, rcx movzx eax, BYTE PTR [rax+r9*4] ret 0 get_by_coordinates1 ENDP GCC also generates equivalent routines, but slightly different: Listing 18.23: Optimizing GCC 4.9 x64 ; RDI=address of array ; RSI=a ; RDX=b get_by_coordinates1: ; sign-extend input 32-bit int values "a" and "b" to 64-bit ones movsx rsi, esi movsx rdx, edx lea rax, [rdi+rsi*4] ; RAX=RDI+RSI*4=address of array+a*4 movzx eax, BYTE PTR [rax+rdx] ; AL=load byte at address RAX+RDX=address of array+a*4+b ret get_by_coordinates2: lea eax, [rdx+rsi*4] ; RAX=RDX+RSI*4=b+a*4 cdqe movzx eax, BYTE PTR [rdi+rax] ; AL=load byte at address RDI+RAX=address of array+b+a*4 ret get_by_coordinates3: sal esi, 2 ; ESI=a<<2=a*4 ; sign-extend input 32-bit int values "a*4" and "b" to 64-bit ones movsx rdx, edx movsx rsi, esi add rdi, rsi ; RDI=RDI+RSI=address of array+a*4 284
  • 309. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS movzx eax, BYTE PTR [rdi+rdx] ; AL=load byte at address RDI+RDX=address of array+a*4+b ret 18.6.3 Three-dimensional array example It’s thing in multidimensional arrays. Now we are going to work with an array of type int: each element requires 4 bytes in memory. Let’s see: Listing 18.24: simple example #include <stdio.h> int a[10][20][30]; void insert(int x, int y, int z, int value) { a[x][y][z]=value; }; x86 We get (MSVC 2010): Listing 18.25: MSVC 2010 _DATA SEGMENT COMM _a:DWORD:01770H _DATA ENDS PUBLIC _insert _TEXT SEGMENT _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 _z$ = 16 ; size = 4 _value$ = 20 ; size = 4 _insert PROC push ebp mov ebp, esp mov eax, DWORD PTR _x$[ebp] imul eax, 2400 ; eax=600*4*x mov ecx, DWORD PTR _y$[ebp] imul ecx, 120 ; ecx=30*4*y lea edx, DWORD PTR _a[eax+ecx] ; edx=a + 600*4*x + 30*4*y mov eax, DWORD PTR _z$[ebp] mov ecx, DWORD PTR _value$[ebp] mov DWORD PTR [edx+eax*4], ecx ; *(edx+z*4)=value pop ebp ret 0 _insert ENDP _TEXT ENDS Nothing special. For index calculation, three input arguments are used in the formula address = 600⋅4⋅x+30⋅4⋅y +4z, to represent the array as multidimensional. Do not forget that the int type is 32-bit (4 bytes), so all coefficients must be multiplied by 4. Listing 18.26: GCC 4.4.1 public insert insert proc near x = dword ptr 8 y = dword ptr 0Ch z = dword ptr 10h value = dword ptr 14h push ebp mov ebp, esp push ebx mov ebx, [ebp+x] 285
  • 310. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS mov eax, [ebp+y] mov ecx, [ebp+z] lea edx, [eax+eax] ; edx=y*2 mov eax, edx ; eax=y*2 shl eax, 4 ; eax=(y*2)<<4 = y*2*16 = y*32 sub eax, edx ; eax=y*32 - y*2=y*30 imul edx, ebx, 600 ; edx=x*600 add eax, edx ; eax=eax+edx=y*30 + x*600 lea edx, [eax+ecx] ; edx=y*30 + x*600 + z mov eax, [ebp+value] mov dword ptr ds:a[edx*4], eax ; *(a+edx*4)=value pop ebx pop ebp retn insert endp The GCC compiler does it differently. For one of the operations in the calculation (30y), GCC produces code without multiplication instructions. This is how it done: (y + y) ≪ 4 − (y + y) = (2y) ≪ 4 − 2y = 2 ⋅ 16 ⋅ y − 2y = 32y − 2y = 30y. Thus, for the 30y calculation, only one addition operation, one bitwise shift operation and one subtraction operation are used. This works faster. ARM + Non-optimizing Xcode 4.6.3 (LLVM) (thumb mode) Listing 18.27: Non-optimizing Xcode 4.6.3 (LLVM) (thumb mode) _insert value = -0x10 z = -0xC y = -8 x = -4 ; allocate place in local stack for 4 values of int type SUB SP, SP, #0x10 MOV R9, 0xFC2 ; a ADD R9, PC LDR.W R9, [R9] STR R0, [SP,#0x10+x] STR R1, [SP,#0x10+y] STR R2, [SP,#0x10+z] STR R3, [SP,#0x10+value] LDR R0, [SP,#0x10+value] LDR R1, [SP,#0x10+z] LDR R2, [SP,#0x10+y] LDR R3, [SP,#0x10+x] MOV R12, 2400 MUL.W R3, R3, R12 ADD R3, R9 MOV R9, 120 MUL.W R2, R2, R9 ADD R2, R3 LSLS R1, R1, #2 ; R1=R1<<2 ADD R1, R2 STR R0, [R1] ; R1 - address of array element ; deallocate chunk in local stack, allocated for 4 values of int type ADD SP, SP, #0x10 BX LR Non-optimizing LLVM saves all variables in local stack, which is redundant. The address of the array element is calculated by the formula we already saw. ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb mode) Listing 18.28: Optimizing Xcode 4.6.3 (LLVM) (thumb mode) _insert MOVW R9, #0x10FC MOV.W R12, #2400 MOVT.W R9, #0 286
  • 311. CHAPTER 18. ARRAYS 18.6. MULTIDIMENSIONAL ARRAYS RSB.W R1, R1, R1,LSL#4 ; R1 - y. R1=y<<4 - y = y*16 - y = y*15 ADD R9, PC ; R9 = pointer to a array LDR.W R9, [R9] MLA.W R0, R0, R12, R9 ; R0 - x, R12 - 2400, R9 - pointer to a. R0=x*2400 + ptr to a ADD.W R0, R0, R1,LSL#3 ; R0 = R0+R1<<3 = R0+R1*8 = x*2400 + ptr to a + y*15*8 = ; ptr to a + y*30*4 + x*600*4 STR.W R3, [R0,R2,LSL#2] ; R2 - z, R3 - value. address=R0+z*4 = ; ptr to a + y*30*4 + x*600*4 + z*4 BX LR The tricks for replacing multiplication by shift, addition and subtraction which we already saw are also present here. Here we also see a new instruction for us: RSB (Reverse Subtract). It works just as SUB, but it swaps its operands with each other before execution. Why? SUB and RSB are instructions, to the second operand of which shift coefficient may be applied: (LSL#4). But this coefficient can be applied only to second operand. That’s fine for commutative operations like addition or multiplication (operands may be swapped there without changing the result). But subtraction is a non-commutative operation, so RSB exist for these cases. The ``LDR.W R9, [R9]'' instruction works like LEA ( A.6.2 on page 933) in x86, but it does nothing here, it is redundant. Apparently, the compiler did not optimize it out. MIPS My example is tiny, so the GCC compiler decided to put the a table into the 64KiB area addressable by the Global Pointer. Listing 18.29: Optimizing GCC 4.4.5 (IDA) insert: ; $a0=x ; $a1=y ; $a2=z ; $a3=value sll $v0, $a0, 5 ; $v0 = $a0<<5 = x*32 sll $a0, 3 ; $a0 = $a0<<3 = x*8 addu $a0, $v0 ; $a0 = $a0+$v0 = x*8+x*32 = x*40 sll $v1, $a1, 5 ; $v1 = $a1<<5 = y*32 sll $v0, $a0, 4 ; $v0 = $a0<<4 = x*40*16 = x*640 sll $a1, 1 ; $a1 = $a1<<1 = y*2 subu $a1, $v1, $a1 ; $a1 = $v1-$a1 = y*32-y*2 = y*30 subu $a0, $v0, $a0 ; $a0 = $v0-$a0 = x*640-x*40 = x*600 la $gp, __gnu_local_gp addu $a0, $a1, $a0 ; $a0 = $a1+$a0 = y*30+x*600 addu $a0, $a2 ; $a0 = $a0+$a2 = y*30+x*600+z ; load address of table: lw $v0, (a & 0xFFFF)($gp) ; multiply index by 4 to seek array element: sll $a0, 2 ; sum up multiplied index and table address: addu $a0, $v0, $a0 ; store value into table and return: jr $ra sw $a3, 0($a0) .comm a:0x1770 18.6.4 More examples The computer screen is represented as a 2D array, but the video-buffer is a linear 1D array. We talk about it here: 83.2 on page 824. 287
  • 312. CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY 18.7 Pack of strings as a two-dimensional array Let’s revisit the function that returns the name of a month: listing.18.8. As you see, at least one memory load operation is needed to prepare a pointer to the string that’s the month’s name. Is it possible to get rid of this memory load operation? In fact yes, if you represent the list of strings as a two-dimensional array: #include <stdio.h> #include <assert.h> const char month2[12][10]= { { 'J','a','n','u','a','r','y', 0, 0, 0 }, { 'F','e','b','r','u','a','r','y', 0, 0 }, { 'M','a','r','c','h', 0, 0, 0, 0, 0 }, { 'A','p','r','i','l', 0, 0, 0, 0, 0 }, { 'M','a','y', 0, 0, 0, 0, 0, 0, 0 }, { 'J','u','n','e', 0, 0, 0, 0, 0, 0 }, { 'J','u','l','y', 0, 0, 0, 0, 0, 0 }, { 'A','u','g','u','s','t', 0, 0, 0, 0 }, { 'S','e','p','t','e','m','b','e','r', 0 }, { 'O','c','t','o','b','e','r', 0, 0, 0 }, { 'N','o','v','e','m','b','e','r', 0, 0 }, { 'D','e','c','e','m','b','e','r', 0, 0 } }; // in 0..11 range const char* get_month2 (int month) { return &month2[month][0]; }; Here is what we’ve get: Listing 18.30: Optimizing MSVC 2013 x64 month2 DB 04aH DB 061H DB 06eH DB 075H DB 061H DB 072H DB 079H DB 00H DB 00H DB 00H ... get_month2 PROC ; sign-extend input argument and promote to 64-bit value movsxd rax, ecx lea rcx, QWORD PTR [rax+rax*4] ; RCX=month+month*4=month*5 lea rax, OFFSET FLAT:month2 ; RAX=pointer to table lea rax, QWORD PTR [rax+rcx*2] ; RAX=pointer to table + RCX*2=pointer to table + month*5*2=pointer to table + month*10 ret 0 get_month2 ENDP There are no memory accesses at all. All this function does is to calculate a point at which the first character of the name of the month is: pointer_to_the_table + month ∗ 10. There are also two LEA instructions, which effectively work as several MUL and MOV instructions. The width of the array is 10 bytes. Indeed, the longest string here — “September” — is 9 bytes, and plus the terminating zero is 10 bytes. The rest of the month names are padded by zero bytes, so they all occupy the same space (10 bytes). Thus, our function works even faster, because all string start at an address which can be calculated easily. Optimizing GCC 4.9 can do it even shorter: Listing 18.31: Optimizing GCC 4.9 x64 movsx rdi, edi lea rax, [rdi+rdi*4] 288
  • 313. CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY lea rax, month2[rax+rax] ret LEA is also used here for multiplication by 10. Non-optimizing compilers do multiplication differently. Listing 18.32: Non-optimizing GCC 4.9 x64 get_month2: push rbp mov rbp, rsp mov DWORD PTR [rbp-4], edi mov eax, DWORD PTR [rbp-4] movsx rdx, eax ; RDX = sign-extended input value mov rax, rdx ; RAX = month sal rax, 2 ; RAX = month<<2 = month*4 add rax, rdx ; RAX = RAX+RDX = month*4+month = month*5 add rax, rax ; RAX = RAX*2 = month*5*2 = month*10 add rax, OFFSET FLAT:month2 ; RAX = month*10 + pointer to the table pop rbp ret Non-optimizing MSVC just use IMUL instruction: Listing 18.33: Non-optimizing MSVC 2013 x64 month$ = 8 get_month2 PROC mov DWORD PTR [rsp+8], ecx movsxd rax, DWORD PTR month$[rsp] ; RAX = sign-extended input value into 64-bit one imul rax, rax, 10 ; RAX = RAX*10 lea rcx, OFFSET FLAT:month2 ; RCX = pointer to the table add rcx, rax ; RCX = RCX+RAX = pointer to the table+month*10 mov rax, rcx ; RAX = pointer to the table+month*10 mov ecx, 1 ; RCX = 1 imul rcx, rcx, 0 ; RCX = 1*0 = 0 add rax, rcx ; RAX = pointer to the table+month*10 + 0 = pointer to the table+month*10 ret 0 get_month2 ENDP … but one thing is weird here: why add multiplication by zero and adding zero to the final result? I don’t know, this looks like a compiler code generator quirk, which wasn’t caught by the compiler’s tests (the resulting code works correctly, after all). I intentionally add such pieces of code so the reader would understand, that sometimes one shouldn’t puzzle over such compiler artifacts. 18.7.1 32-bit ARM Optimizing Keil for Thumb mode uses the multiplication instruction MULS: Listing 18.34: Optimizing Keil 6/2013 (thumb mode) ; R0 = month MOVS r1,#0xa ; R1 = 10 MULS r0,r1,r0 ; R0 = R1*R0 = 10*month LDR r1,|L0.68| ; R1 = pointer to the table 289
  • 314. CHAPTER 18. ARRAYS 18.7. PACK OF STRINGS AS A TWO-DIMENSIONAL ARRAY ADDS r0,r0,r1 ; R0 = R0+R1 = 10*month + pointer to the table BX lr Optimizing Keil for ARM mode uses add and shift operations: Listing 18.35: Optimizing Keil 6/2013 (ARM mode) ; R0 = month LDR r1,|L0.104| ; R1 = pointer to the table ADD r0,r0,r0,LSL #2 ; R0 = R0+R0<<2 = R0+R0*4 = month*5 ADD r0,r1,r0,LSL #1 ; R0 = R1+R0<<2 = pointer to the table + month*5*2 = pointer to the table + month*10 BX lr 18.7.2 ARM64 Listing 18.36: Optimizing GCC 4.9 ARM64 ; W0 = month sxtw x0, w0 ; X0 = sign-extended input value adrp x1, .LANCHOR1 add x1, x1, :lo12:.LANCHOR1 ; X1 = pointer to the table add x0, x0, x0, lsl 2 ; X0 = X0+X0<<2 = X0+X0*4 = X0*5 add x0, x1, x0, lsl 1 ; X0 = X1+X0<<1 = X1+X0*2 = pointer to the table + X0*10 ret SXTW is used for sign-extension and promoting input 32-bit value into a 64-bit one and storing it in X0. ADRP/ADD pair is used for loading the address of the table. The ADD instructions also has a LSL suffix, which helps with multiplications. 18.7.3 MIPS Listing 18.37: Optimizing GCC 4.4.5 (IDA) .globl get_month2 get_month2: ; $a0=month sll $v0, $a0, 3 ; $v0 = $a0<<3 = month*8 sll $a0, 1 ; $a0 = $a0<<1 = month*2 addu $a0, $v0 ; $a0 = month*2+month*8 = month*10 ; load address of the table: la $v0, month2 ; sum up table address and index we calculated and return: jr $ra addu $v0, $a0 month2: .ascii "January"<0> .byte 0, 0 aFebruary: .ascii "February"<0> .byte 0 aMarch: .ascii "March"<0> .byte 0, 0, 0, 0 aApril: .ascii "April"<0> .byte 0, 0, 0, 0 aMay: .ascii "May"<0> .byte 0, 0, 0, 0, 0, 0 aJune: .ascii "June"<0> .byte 0, 0, 0, 0, 0 aJuly: .ascii "July"<0> .byte 0, 0, 0, 0, 0 290
  • 315. CHAPTER 18. ARRAYS 18.8. CONCLUSION aAugust: .ascii "August"<0> .byte 0, 0, 0 aSeptember: .ascii "September"<0> aOctober: .ascii "October"<0> .byte 0, 0 aNovember: .ascii "November"<0> .byte 0 aDecember: .ascii "December"<0> .byte 0, 0, 0, 0, 0, 0, 0, 0, 0 18.7.4 Conclusion This is a bit old-school technique to store text strings. You may find a lot of it in Oracle RDBMS, for example. But I don’t really know if it’s worth doing on modern computers. Nevertheless, it was a good example of arrays, so I added it to this book. 18.8 Conclusion An array is a pack of values in memory located adjacently. It’s true for any element type, including structures. Access to a specific array element is just a calculation of its address. 18.9 Exercises 18.9.1 Exercise #1 What does this code do? Listing 18.38: MSVC 2010 + /O1 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 ?s@@YAXPAN00@Z PROC ; s, COMDAT mov eax, DWORD PTR _b$[esp-4] mov ecx, DWORD PTR _a$[esp-4] mov edx, DWORD PTR _c$[esp-4] push esi push edi sub ecx, eax sub edx, eax mov edi, 200 ; 000000c8H $LL6@s: push 100 ; 00000064H pop esi $LL3@s: fld QWORD PTR [ecx+eax] fadd QWORD PTR [eax] fstp QWORD PTR [edx+eax] add eax, 8 dec esi jne SHORT $LL3@s dec edi jne SHORT $LL6@s pop edi pop esi ret 0 ?s@@YAXPAN00@Z ENDP ; s (/O1: minimize space). Listing 18.39: Optimizing Keil 6/2013 (ARM mode) PUSH {r4-r12,lr} MOV r9,r2 MOV r10,r1 MOV r11,r0 MOV r5,#0 291
  • 316. CHAPTER 18. ARRAYS 18.9. EXERCISES |L0.20| ADD r0,r5,r5,LSL #3 ADD r0,r0,r5,LSL #4 MOV r4,#0 ADD r8,r10,r0,LSL #5 ADD r7,r11,r0,LSL #5 ADD r6,r9,r0,LSL #5 |L0.44| ADD r0,r8,r4,LSL #3 LDM r0,{r2,r3} ADD r1,r7,r4,LSL #3 LDM r1,{r0,r1} BL __aeabi_dadd ADD r2,r6,r4,LSL #3 ADD r4,r4,#1 STM r2,{r0,r1} CMP r4,#0x64 BLT |L0.44| ADD r5,r5,#1 CMP r5,#0xc8 BLT |L0.20| POP {r4-r12,pc} Listing 18.40: Optimizing Keil 6/2013 (thumb mode) PUSH {r0-r2,r4-r7,lr} MOVS r4,#0 SUB sp,sp,#8 |L0.6| MOVS r1,#0x19 MOVS r0,r4 LSLS r1,r1,#5 MULS r0,r1,r0 LDR r2,[sp,#8] LDR r1,[sp,#0xc] ADDS r2,r0,r2 STR r2,[sp,#0] LDR r2,[sp,#0x10] MOVS r5,#0 ADDS r7,r0,r2 ADDS r0,r0,r1 STR r0,[sp,#4] |L0.32| LSLS r6,r5,#3 ADDS r0,r0,r6 LDM r0!,{r2,r3} LDR r0,[sp,#0] ADDS r1,r0,r6 LDM r1,{r0,r1} BL __aeabi_dadd ADDS r2,r7,r6 ADDS r5,r5,#1 STM r2!,{r0,r1} CMP r5,#0x64 BGE |L0.62| LDR r0,[sp,#4] B |L0.32| |L0.62| ADDS r4,r4,#1 CMP r4,#0xc8 BLT |L0.6| ADD sp,sp,#0x14 POP {r4-r7,pc} Listing 18.41: Non-optimizing GCC 4.9 (ARM64) s: sub sp, sp, #48 str x0, [sp,24] str x1, [sp,16] 292
  • 317. CHAPTER 18. ARRAYS 18.9. EXERCISES str x2, [sp,8] str wzr, [sp,44] b .L2 .L5: str wzr, [sp,40] b .L3 .L4: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] add x0, x1, x0 ldr w2, [sp,44] mov w1, 100 mul w1, w2, w1 sxtw x2, w1 ldrsw x1, [sp,40] add x1, x2, x1 lsl x1, x1, 3 ldr x2, [sp,24] add x1, x2, x1 ldr x2, [x1] ldr w3, [sp,44] mov w1, 100 mul w1, w3, w1 sxtw x3, w1 ldrsw x1, [sp,40] add x1, x3, x1 lsl x1, x1, 3 ldr x3, [sp,16] add x1, x3, x1 ldr x1, [x1] fmov d0, x2 fmov d1, x1 fadd d0, d0, d1 fmov x1, d0 str x1, [x0] ldr w0, [sp,40] add w0, w0, 1 str w0, [sp,40] .L3: ldr w0, [sp,40] cmp w0, 99 ble .L4 ldr w0, [sp,44] add w0, w0, 1 str w0, [sp,44] .L2: ldr w0, [sp,44] cmp w0, 199 ble .L5 add sp, sp, 48 ret Listing 18.42: Optimizing GCC 4.4.5 (MIPS) (IDA) sub_0: li $t3, 0x27100 move $t2, $zero li $t1, 0x64 # 'd' loc_10: # CODE XREF: sub_0+54 addu $t0, $a1, $t2 addu $a3, $a2, $t2 move $v1, $a0 move $v0, $zero 293
  • 318. CHAPTER 18. ARRAYS 18.9. EXERCISES loc_20: # CODE XREF: sub_0+48 lwc1 $f2, 4($v1) lwc1 $f0, 4($t0) lwc1 $f3, 0($v1) lwc1 $f1, 0($t0) addiu $v0, 1 add.d $f0, $f2, $f0 addiu $v1, 8 swc1 $f0, 4($a3) swc1 $f1, 0($a3) addiu $t0, 8 bne $v0, $t1, loc_20 addiu $a3, 8 addiu $t2, 0x320 bne $t2, $t3, loc_10 addiu $a0, 0x320 jr $ra or $at, $zero Answer G.1.10 on page 955. 18.9.2 Exercise #2 What does this code do? Listing 18.43: MSVC 2010 + /O1 tv315 = -8 ; size = 4 tv291 = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 ?m@@YAXPAN00@Z PROC ; m, COMDAT push ebp mov ebp, esp push ecx push ecx mov edx, DWORD PTR _a$[ebp] push ebx mov ebx, DWORD PTR _c$[ebp] push esi mov esi, DWORD PTR _b$[ebp] sub edx, esi push edi sub esi, ebx mov DWORD PTR tv315[ebp], 100 ; 00000064H $LL9@m: mov eax, ebx mov DWORD PTR tv291[ebp], 300 ; 0000012cH $LL6@m: fldz lea ecx, DWORD PTR [esi+eax] fstp QWORD PTR [eax] mov edi, 200 ; 000000c8H $LL3@m: dec edi fld QWORD PTR [ecx+edx] fmul QWORD PTR [ecx] fadd QWORD PTR [eax] fstp QWORD PTR [eax] jne HORT $LL3@m add eax, 8 dec DWORD PTR tv291[ebp] jne SHORT $LL6@m add ebx, 800 ; 00000320H dec DWORD PTR tv315[ebp] jne SHORT $LL9@m pop edi pop esi 294
  • 319. CHAPTER 18. ARRAYS 18.9. EXERCISES pop ebx leave ret 0 ?m@@YAXPAN00@Z ENDP ; m (/O1: minimize space). Listing 18.44: Optimizing Keil 6/2013 (ARM mode) PUSH {r0-r2,r4-r11,lr} SUB sp,sp,#8 MOV r5,#0 |L0.12| LDR r1,[sp,#0xc] ADD r0,r5,r5,LSL #3 ADD r0,r0,r5,LSL #4 ADD r1,r1,r0,LSL #5 STR r1,[sp,#0] LDR r1,[sp,#8] MOV r4,#0 ADD r11,r1,r0,LSL #5 LDR r1,[sp,#0x10] ADD r10,r1,r0,LSL #5 |L0.52| MOV r0,#0 MOV r1,r0 ADD r7,r10,r4,LSL #3 STM r7,{r0,r1} MOV r6,r0 LDR r0,[sp,#0] ADD r8,r11,r4,LSL #3 ADD r9,r0,r4,LSL #3 |L0.84| LDM r9,{r2,r3} LDM r8,{r0,r1} BL __aeabi_dmul LDM r7,{r2,r3} BL __aeabi_dadd ADD r6,r6,#1 STM r7,{r0,r1} CMP r6,#0xc8 BLT |L0.84| ADD r4,r4,#1 CMP r4,#0x12c BLT |L0.52| ADD r5,r5,#1 CMP r5,#0x64 BLT |L0.12| ADD sp,sp,#0x14 POP {r4-r11,pc} Listing 18.45: Optimizing Keil 6/2013 (thumb mode) PUSH {r0-r2,r4-r7,lr} MOVS r0,#0 SUB sp,sp,#0x10 STR r0,[sp,#0] |L0.8| MOVS r1,#0x19 LSLS r1,r1,#5 MULS r0,r1,r0 LDR r2,[sp,#0x10] LDR r1,[sp,#0x14] ADDS r2,r0,r2 STR r2,[sp,#4] LDR r2,[sp,#0x18] MOVS r5,#0 ADDS r7,r0,r2 ADDS r0,r0,r1 STR r0,[sp,#8] |L0.32| 295
  • 320. CHAPTER 18. ARRAYS 18.9. EXERCISES LSLS r4,r5,#3 MOVS r0,#0 ADDS r2,r7,r4 STR r0,[r2,#0] MOVS r6,r0 STR r0,[r2,#4] |L0.44| LDR r0,[sp,#8] ADDS r0,r0,r4 LDM r0!,{r2,r3} LDR r0,[sp,#4] ADDS r1,r0,r4 LDM r1,{r0,r1} BL __aeabi_dmul ADDS r3,r7,r4 LDM r3,{r2,r3} BL __aeabi_dadd ADDS r2,r7,r4 ADDS r6,r6,#1 STM r2!,{r0,r1} CMP r6,#0xc8 BLT |L0.44| MOVS r0,#0xff ADDS r5,r5,#1 ADDS r0,r0,#0x2d CMP r5,r0 BLT |L0.32| LDR r0,[sp,#0] ADDS r0,r0,#1 CMP r0,#0x64 STR r0,[sp,#0] BLT |L0.8| ADD sp,sp,#0x1c POP {r4-r7,pc} Listing 18.46: Non-optimizing GCC 4.9 (ARM64) m: sub sp, sp, #48 str x0, [sp,24] str x1, [sp,16] str x2, [sp,8] str wzr, [sp,44] b .L2 .L7: str wzr, [sp,40] b .L3 .L6: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] add x0, x1, x0 ldr x1, .LC0 str x1, [x0] str wzr, [sp,36] b .L4 .L5: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] 296
  • 321. CHAPTER 18. ARRAYS 18.9. EXERCISES add x0, x1, x0 ldr w2, [sp,44] mov w1, 100 mul w1, w2, w1 sxtw x2, w1 ldrsw x1, [sp,40] add x1, x2, x1 lsl x1, x1, 3 ldr x2, [sp,8] add x1, x2, x1 ldr x2, [x1] ldr w3, [sp,44] mov w1, 100 mul w1, w3, w1 sxtw x3, w1 ldrsw x1, [sp,40] add x1, x3, x1 lsl x1, x1, 3 ldr x3, [sp,24] add x1, x3, x1 ldr x3, [x1] ldr w4, [sp,44] mov w1, 100 mul w1, w4, w1 sxtw x4, w1 ldrsw x1, [sp,40] add x1, x4, x1 lsl x1, x1, 3 ldr x4, [sp,16] add x1, x4, x1 ldr x1, [x1] fmov d0, x3 fmov d1, x1 fmul d0, d0, d1 fmov x1, d0 fmov d0, x2 fmov d1, x1 fadd d0, d0, d1 fmov x1, d0 str x1, [x0] ldr w0, [sp,36] add w0, w0, 1 str w0, [sp,36] .L4: ldr w0, [sp,36] cmp w0, 199 ble .L5 ldr w0, [sp,40] add w0, w0, 1 str w0, [sp,40] .L3: ldr w0, [sp,40] cmp w0, 299 ble .L6 ldr w0, [sp,44] add w0, w0, 1 str w0, [sp,44] .L2: ldr w0, [sp,44] cmp w0, 99 ble .L7 add sp, sp, 48 ret Listing 18.47: Optimizing GCC 4.4.5 (MIPS) (IDA) m: li $t5, 0x13880 move $t4, $zero li $t1, 0xC8 297
  • 322. CHAPTER 18. ARRAYS 18.9. EXERCISES li $t3, 0x12C loc_14: # CODE XREF: m+7C addu $t0, $a0, $t4 addu $a3, $a1, $t4 move $v1, $a2 move $t2, $zero loc_24: # CODE XREF: m+70 mtc1 $zero, $f0 move $v0, $zero mtc1 $zero, $f1 or $at, $zero swc1 $f0, 4($v1) swc1 $f1, 0($v1) loc_3C: # CODE XREF: m+5C lwc1 $f4, 4($t0) lwc1 $f2, 4($a3) lwc1 $f5, 0($t0) lwc1 $f3, 0($a3) addiu $v0, 1 mul.d $f2, $f4, $f2 add.d $f0, $f2 swc1 $f0, 4($v1) bne $v0, $t1, loc_3C swc1 $f1, 0($v1) addiu $t2, 1 addiu $v1, 8 addiu $t0, 8 bne $t2, $t3, loc_24 addiu $a3, 8 addiu $t4, 0x320 bne $t4, $t5, loc_14 addiu $a2, 0x320 jr $ra or $at, $zero Answer G.1.10 on page 956. 18.9.3 Exercise #3 What does this code do? Try to determine the dimensions of the array, at least partially. Listing 18.48: Optimizing MSVC 2010 _array$ = 8 _x$ = 12 _y$ = 16 _f PROC mov eax, DWORD PTR _x$[esp-4] mov edx, DWORD PTR _y$[esp-4] mov ecx, eax shl ecx, 4 sub ecx, eax lea eax, DWORD PTR [edx+ecx*8] mov ecx, DWORD PTR _array$[esp-4] fld QWORD PTR [ecx+eax*8] ret 0 _f ENDP Listing 18.49: Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r1,r1,r1,LSL #4 ADD r0,r0,r1,LSL #6 ADD r1,r0,r2,LSL #3 LDM r1,{r0,r1} BX lr ENDP 298
  • 323. CHAPTER 18. ARRAYS 18.9. EXERCISES Listing 18.50: Non-optimizing Keil 6/2013 (thumb mode) f PROC MOVS r3,#0xf LSLS r3,r3,#6 MULS r1,r3,r1 ADDS r0,r1,r0 LSLS r1,r2,#3 ADDS r1,r0,r1 LDM r1,{r0,r1} BX lr ENDP Listing 18.51: Optimizing GCC 4.9 (ARM64) f: sxtw x1, w1 add x0, x0, x2, sxtw 3 lsl x2, x1, 10 sub x1, x2, x1, lsl 6 ldr d0, [x0,x1] ret Listing 18.52: Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a1, 10 sll $a1, 6 subu $a1, $v0, $a1 addu $a1, $a0, $a1 sll $a2, 3 addu $a1, $a2 lwc1 $f0, 4($a1) or $at, $zero lwc1 $f1, 0($a1) jr $ra or $at, $zero Answer G.1.10 on page 956 18.9.4 Exercise #4 What does this code do? Try to determine the dimensions of the array, at least partially. Listing 18.53: Optimizing MSVC 2010 _array$ = 8 _x$ = 12 _y$ = 16 _z$ = 20 _f PROC mov eax, DWORD PTR _x$[esp-4] mov edx, DWORD PTR _y$[esp-4] mov ecx, eax shl ecx, 4 sub ecx, eax lea eax, DWORD PTR [edx+ecx*4] mov ecx, DWORD PTR _array$[esp-4] lea eax, DWORD PTR [eax+eax*4] shl eax, 4 add eax, DWORD PTR _z$[esp-4] mov eax, DWORD PTR [ecx+eax*4] ret 0 _f ENDP Listing 18.54: Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r1,r1,r1,LSL #4 ADD r1,r1,r1,LSL #2 299
  • 324. CHAPTER 18. ARRAYS 18.9. EXERCISES ADD r0,r0,r1,LSL #8 ADD r1,r2,r2,LSL #2 ADD r0,r0,r1,LSL #6 LDR r0,[r0,r3,LSL #2] BX lr ENDP Listing 18.55: Non-optimizing Keil 6/2013 (thumb mode) f PROC PUSH {r4,lr} MOVS r4,#0x4b LSLS r4,r4,#8 MULS r1,r4,r1 ADDS r0,r1,r0 MOVS r1,#0xff ADDS r1,r1,#0x41 MULS r2,r1,r2 ADDS r0,r0,r2 LSLS r1,r3,#2 LDR r0,[r0,r1] POP {r4,pc} ENDP Listing 18.56: Optimizing GCC 4.9 (ARM64) f: sxtw x2, w2 mov w4, 19200 add x2, x2, x2, lsl 2 smull x1, w1, w4 lsl x2, x2, 4 add x3, x2, x3, sxtw add x0, x0, x3, lsl 2 ldr w0, [x0,x1] ret Listing 18.57: Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a1, 10 sll $a1, 8 addu $a1, $v0 sll $v0, $a2, 6 sll $a2, 4 addu $a2, $v0 sll $v0, $a1, 4 subu $a1, $v0, $a1 addu $a2, $a3 addu $a1, $a0, $a1 sll $a2, 2 addu $a1, $a2 lw $v0, 0($a1) jr $ra or $at, $zero Answer G.1.10 on page 956 18.9.5 Exercise #5 What does this code do? Listing 18.58: Optimizing MSVC 2012 /GS- COMM _tbl:DWORD:064H tv759 = -4 ; size = 4 _main PROC push ecx push ebx 300
  • 325. CHAPTER 18. ARRAYS 18.9. EXERCISES push ebp push esi xor edx, edx push edi xor esi, esi xor edi, edi xor ebx, ebx xor ebp, ebp mov DWORD PTR tv759[esp+20], edx mov eax, OFFSET _tbl+4 npad 8 ; align next label $LL6@main: lea ecx, DWORD PTR [edx+edx] mov DWORD PTR [eax+4], ecx mov ecx, DWORD PTR tv759[esp+20] add DWORD PTR tv759[esp+20], 3 mov DWORD PTR [eax+8], ecx lea ecx, DWORD PTR [edx*4] mov DWORD PTR [eax+12], ecx lea ecx, DWORD PTR [edx*8] mov DWORD PTR [eax], edx mov DWORD PTR [eax+16], ebp mov DWORD PTR [eax+20], ebx mov DWORD PTR [eax+24], edi mov DWORD PTR [eax+32], esi mov DWORD PTR [eax-4], 0 mov DWORD PTR [eax+28], ecx add eax, 40 inc edx add ebp, 5 add ebx, 6 add edi, 7 add esi, 9 cmp eax, OFFSET _tbl+404 jl SHORT $LL6@main pop edi pop esi pop ebp xor eax, eax pop ebx pop ecx ret 0 _main ENDP Listing 18.59: Non-optimizing Keil 6/2013 (ARM mode) main PROC LDR r12,|L0.60| MOV r1,#0 |L0.8| ADD r2,r1,r1,LSL #2 MOV r0,#0 ADD r2,r12,r2,LSL #3 |L0.20| MUL r3,r1,r0 STR r3,[r2,r0,LSL #2] ADD r0,r0,#1 CMP r0,#0xa BLT |L0.20| ADD r1,r1,#1 CMP r1,#0xa MOVGE r0,#0 BLT |L0.8| BX lr ENDP |L0.60| DCD ||.bss|| AREA ||.bss||, DATA, NOINIT, ALIGN=2 301
  • 326. CHAPTER 18. ARRAYS 18.9. EXERCISES tbl % 400 Listing 18.60: Non-optimizing Keil 6/2013 (thumb mode) main PROC PUSH {r4,r5,lr} LDR r4,|L0.40| MOVS r1,#0 |L0.6| MOVS r2,#0x28 MULS r2,r1,r2 MOVS r0,#0 ADDS r3,r2,r4 |L0.14| MOVS r2,r1 MULS r2,r0,r2 LSLS r5,r0,#2 ADDS r0,r0,#1 CMP r0,#0xa STR r2,[r3,r5] BLT |L0.14| ADDS r1,r1,#1 CMP r1,#0xa BLT |L0.6| MOVS r0,#0 POP {r4,r5,pc} ENDP DCW 0x0000 |L0.40| DCD ||.bss|| AREA ||.bss||, DATA, NOINIT, ALIGN=2 tbl % 400 Listing 18.61: Non-optimizing GCC 4.9 (ARM64) .comm tbl,400,8 main: sub sp, sp, #16 str wzr, [sp,12] b .L2 .L5: str wzr, [sp,8] b .L3 .L4: ldr w1, [sp,12] ldr w0, [sp,8] mul w3, w1, w0 adrp x0, tbl add x2, x0, :lo12:tbl ldrsw x4, [sp,8] ldrsw x1, [sp,12] mov x0, x1 lsl x0, x0, 2 add x0, x0, x1 lsl x0, x0, 1 add x0, x0, x4 str w3, [x2,x0,lsl 2] ldr w0, [sp,8] add w0, w0, 1 str w0, [sp,8] .L3: ldr w0, [sp,8] cmp w0, 9 ble .L4 302
  • 327. CHAPTER 18. ARRAYS 18.9. EXERCISES ldr w0, [sp,12] add w0, w0, 1 str w0, [sp,12] .L2: ldr w0, [sp,12] cmp w0, 9 ble .L5 mov w0, 0 add sp, sp, 16 ret Listing 18.62: Non-optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_4 = -4 addiu $sp, -0x18 sw $fp, 0x18+var_4($sp) move $fp, $sp la $gp, __gnu_local_gp sw $gp, 0x18+var_18($sp) sw $zero, 0x18+var_C($fp) b loc_A0 or $at, $zero loc_24: # CODE XREF: main+AC sw $zero, 0x18+var_10($fp) b loc_7C or $at, $zero loc_30: # CODE XREF: main+88 lw $v0, 0x18+var_C($fp) lw $a0, 0x18+var_10($fp) lw $a1, 0x18+var_C($fp) lw $v1, 0x18+var_10($fp) or $at, $zero mult $a1, $v1 mflo $a2 lw $v1, (tbl & 0xFFFF)($gp) sll $v0, 1 sll $a1, $v0, 2 addu $v0, $a1 addu $v0, $a0 sll $v0, 2 addu $v0, $v1, $v0 sw $a2, 0($v0) lw $v0, 0x18+var_10($fp) or $at, $zero addiu $v0, 1 sw $v0, 0x18+var_10($fp) loc_7C: # CODE XREF: main+28 lw $v0, 0x18+var_10($fp) or $at, $zero slti $v0, 0xA bnez $v0, loc_30 or $at, $zero lw $v0, 0x18+var_C($fp) or $at, $zero addiu $v0, 1 sw $v0, 0x18+var_C($fp) loc_A0: # CODE XREF: main+1C lw $v0, 0x18+var_C($fp) or $at, $zero slti $v0, 0xA 303
  • 328. CHAPTER 18. ARRAYS 18.9. EXERCISES bnez $v0, loc_24 or $at, $zero move $v0, $zero move $sp, $fp lw $fp, 0x18+var_4($sp) addiu $sp, 0x18 jr $ra or $at, $zero .comm tbl:0x64 # DATA XREF: main+4C Answer G.1.10 on page 956 304
  • 329. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) Chapter 19 Manipulating specific bit(s) A lot of functions define their input arguments as flags in bit fields. Of course, they could be substituted by a set of bool-typed variables, but it is not frugally. 19.1 Specific bit checking 19.1.1 x86 Win32 API example: HANDLE fh; fh=CreateFile ("file", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS⤦ , FILE_ATTRIBUTE_NORMAL, NULL); We get (MSVC 2010): Listing 19.1: MSVC 2010 push 0 push 128 ; 00000080H push 4 push 0 push 1 push -1073741824 ; c0000000H push OFFSET $SG78813 call DWORD PTR __imp__CreateFileA@28 mov DWORD PTR _fh$[ebp], eax Let’s take a look in WinNT.h: Listing 19.2: WinNT.h #define GENERIC_READ (0x80000000L) #define GENERIC_WRITE (0x40000000L) #define GENERIC_EXECUTE (0x20000000L) #define GENERIC_ALL (0x10000000L) Everything is clear, GENERIC_READ | GENERIC_WRITE = 0x80000000 | 0x40000000 = 0xC0000000, and that value is used as the second argument for the CreateFile()1 function. How would CreateFile() check these flags? If we look in KERNEL32.DLL in Windows XP SP3 x86, we’ll find this fragment of code in CreateFileW: Listing 19.3: KERNEL32.DLL (Windows XP SP3 x86) .text:7C83D429 test byte ptr [ebp+dwDesiredAccess+3], 40h .text:7C83D42D mov [ebp+var_8], 1 .text:7C83D434 jz short loc_7C83D417 .text:7C83D436 jmp loc_7C810817 Here we see the TEST instruction, however it doesn’t take the whole second argument, but only the most significant byte (ebp+dwDesiredAccess+3) and checks it for flag 0x40 (which implies the GENERIC_WRITE flag here) TEST is basically the same instruction as AND, but without saving the result (recall the fact CMP is merely the same as SUB, but without saving the result ( 7.3.1 on page 74)). The logic of this code fragment is as follows: 1MSDN: CreateFile function 305
  • 330. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.1. SPECIFIC BIT CHECKING if ((dwDesiredAccess&0x40000000) == 0) goto loc_7C83D417 If AND instruction leaves this bit, the ZF flag is to be cleared and the JZ conditional jump is not to be triggered. The conditional jump is triggered only if the 0x40000000 bit is absent in dwDesiredAccess variable —then the result of AND is 0, ZF is to be set and the conditional jump is to be triggered. Let’s try GCC 4.4.1 and Linux: #include <stdio.h> #include <fcntl.h> void main() { int handle; handle=open ("file", O_RDWR | O_CREAT); }; We get: Listing 19.4: GCC 4.4.1 public main main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_1C], 42h mov [esp+20h+var_20], offset aFile ; "file" call _open mov [esp+20h+var_4], eax leave retn main endp If we take a look in the open() function in the libc.so.6 library, it is only a syscall: Listing 19.5: open() (libc.so.6) .text:000BE69B mov edx, [esp+4+mode] ; mode .text:000BE69F mov ecx, [esp+4+flags] ; flags .text:000BE6A3 mov ebx, [esp+4+filename] ; filename .text:000BE6A7 mov eax, 5 .text:000BE6AC int 80h ; LINUX - sys_open So, the bit fields for open() are apparently checked somewhere in the Linux kernel. Of course, it is easy to download both Glibc and the Linux kernel source code, but we are interested in understanding the matter without it. So, as of Linux 2.6, when the sys_open syscall is called, control eventually passes to do_sys_open, and from there —to the do_filp_open() function (it’s located in the kernel source tree in fs/namei.c). N.B. Aside from passing arguments via the stack, there is also a method of passing some of them via registers. This is also called fastcall ( 64.3 on page 664). This works faster since CPU does not need to access the stack in memory to read argument values. GCC has the option regparm2 , through which it’s possible to set the number of arguments that can be passed via registers. The Linux 2.6 kernel is compiled with -mregparm=3 option 3 4 . What this means to us is that the first 3 arguments are to be passed via registers EAX, EDX and ECX, and the rest via the stack. Of course, if the number of arguments is less than 3, only part of registers set is to be used. So, let’s download Linux Kernel 2.6.31, compile it in Ubuntu: make vmlinux, open it in IDA, and find the do_filp_open() function. At the beginning, we see (the comments are mine): Listing 19.6: do_filp_open() (linux kernel 2.6.31) 2http://go.yurichev.com/17040 3http://go.yurichev.com/17066 4See also archx86includeasmcalling.h file in kernel tree 306
  • 331. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.1. SPECIFIC BIT CHECKING do_filp_open proc near ... push ebp mov ebp, esp push edi push esi push ebx mov ebx, ecx add ebx, 1 sub esp, 98h mov esi, [ebp+arg_4] ; acc_mode (5th arg) test bl, 3 mov [ebp+var_80], eax ; dfd (1th arg) mov [ebp+var_7C], edx ; pathname (2th arg) mov [ebp+var_78], ecx ; open_flag (3th arg) jnz short loc_C01EF684 mov ebx, ecx ; ebx <- open_flag GCC saves the values of the first 3 arguments in the local stack. If that wasn’t done, the compiler would not touch these registers, and that would be too tight environment for the compiler’s register allocator. Let’s find this fragment of code: Listing 19.7: do_filp_open() (linux kernel 2.6.31) loc_C01EF6B4: ; CODE XREF: do_filp_open+4F test bl, 40h ; O_CREAT jnz loc_C01EF810 mov edi, ebx shr edi, 11h xor edi, 1 and edi, 1 test ebx, 10000h jz short loc_C01EF6D3 or edi, 2 0x40 —is what the O_CREAT macro equals to. open_flag gets checked for the presence of the 0x40 bit, and if this bit is 1, the next JNZ instruction is triggered. 19.1.2 ARM The O_CREAT bit is checked differently in Linux kernel 3.8.0. Listing 19.8: linux kernel 3.8.0 struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) { ... filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU); ... } static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { ... error = do_last(nd, &path, file, op, &opened, pathname); ... } static int do_last(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, int *opened, struct filename *name) { ... if (!(open_flag & O_CREAT)) { ... error = lookup_fast(nd, path, &inode); ... } else { 307
  • 332. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING ... error = complete_walk(nd); } ... } Here is how the kernel compiled for ARM mode looks in IDA: Listing 19.9: do_last() (vmlinux) ... .text:C0169EA8 MOV R9, R3 ; R3 - (4th argument) open_flag ... .text:C0169ED4 LDR R6, [R9] ; R6 - open_flag ... .text:C0169F68 TST R6, #0x40 ; jumptable C0169F00 default case .text:C0169F6C BNE loc_C016A128 .text:C0169F70 LDR R2, [R4,#0x10] .text:C0169F74 ADD R12, R4, #8 .text:C0169F78 LDR R3, [R4,#0xC] .text:C0169F7C MOV R0, R4 .text:C0169F80 STR R12, [R11,#var_50] .text:C0169F84 LDRB R3, [R2,R3] .text:C0169F88 MOV R2, R8 .text:C0169F8C CMP R3, #0 .text:C0169F90 ORRNE R1, R1, #3 .text:C0169F94 STRNE R1, [R4,#0x24] .text:C0169F98 ANDS R3, R6, #0x200000 .text:C0169F9C MOV R1, R12 .text:C0169FA0 LDRNE R3, [R4,#0x24] .text:C0169FA4 ANDNE R3, R3, #1 .text:C0169FA8 EORNE R3, R3, #1 .text:C0169FAC STR R3, [R11,#var_54] .text:C0169FB0 SUB R3, R11, #-var_38 .text:C0169FB4 BL lookup_fast ... .text:C016A128 loc_C016A128 ; CODE XREF: do_last.isra.14+DC .text:C016A128 MOV R0, R4 .text:C016A12C BL complete_walk ... TST is analogous to the TEST instruction in x86. We can “spot” visually this code fragment by the fact the lookup_fast() is to be executed in one case and com- plete_walk() in the other. This corresponds to the source code of the do_last() function. The O_CREAT macro equals to 0x40 here too. 19.2 Specific bit setting/clearing For example: #include <stdio.h> #define IS_SET(flag, bit) ((flag) & (bit)) #define SET_BIT(var, bit) ((var) |= (bit)) #define REMOVE_BIT(var, bit) ((var) &= ~(bit)) int f(int a) { int rt=a; SET_BIT (rt, 0x4000); REMOVE_BIT (rt, 0x200); return rt; }; int main() { f(0x12340678); }; 308
  • 333. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING 19.2.1 x86 Non-optimizing MSVC We get (MSVC 2010): Listing 19.10: MSVC 2010 _rt$ = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] mov DWORD PTR _rt$[ebp], eax mov ecx, DWORD PTR _rt$[ebp] or ecx, 16384 ; 00004000H mov DWORD PTR _rt$[ebp], ecx mov edx, DWORD PTR _rt$[ebp] and edx, -513 ; fffffdffH mov DWORD PTR _rt$[ebp], edx mov eax, DWORD PTR _rt$[ebp] mov esp, ebp pop ebp ret 0 _f ENDP The OR instruction adds one more bit to value while ignoring the rest. AND resets one bit. It can be said that AND just copies all bits except one. Indeed, in the second AND operand only the bits that need to be saved are set, just the one do not want to copy is not (which is 0 in the bitmask). It is the easier way to memorize the logic. 309
  • 334. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING OllyDbg Let’s try this example in OllyDbg. First, let’s see the binary form of the constants we are going to use: 0x200 (00000000000000000001000000000) (i.e., the 10th bit (counting from 1st)). Inverted 0x200 is 0xFFFFFDFF (11111111111111111110111111111). 0x4000 (00000000000000100000000000000) (i.e., the 15th bit). The input value is: 0x12340678 (10010001101000000011001111000). We see how it’s loaded: Figure 19.1: OllyDbg: value is loaded into ECX 310
  • 335. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING OR got executed: Figure 19.2: OllyDbg: OR executed 15th bit is set: 0x12344678 (10010001101000100011001111000). 311
  • 336. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING The value is reloaded again (because the compiler is not in optimizing mode): Figure 19.3: OllyDbg: value was reloaded into EDX 312
  • 337. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING AND got executed: Figure 19.4: OllyDbg: AND executed The 10th bit was cleared (or, in other words, all bits were left except the 10th) and the final value now is 0x12344478 (10010001101000100010001111000). Optimizing MSVC If we compile it in MSVC with optimization turned on (/Ox), the code is even shorter: Listing 19.11: Optimizing MSVC _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] and eax, -513 ; fffffdffH or eax, 16384 ; 00004000H ret 0 _f ENDP Non-optimizing GCC Let’s try GCC 4.4.1 without optimization: Listing 19.12: Non-optimizing GCC public f f proc near var_4 = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 10h mov eax, [ebp+arg_0] mov [ebp+var_4], eax or [ebp+var_4], 4000h and [ebp+var_4], 0FFFFFDFFh mov eax, [ebp+var_4] leave retn f endp There is a redundant code present, however, it is shorter than the MSVC version without optimization. Now let’s try GCC with optimization turned on -O3: 313
  • 338. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING Optimizing GCC Listing 19.13: Optimizing GCC public f f proc near arg_0 = dword ptr 8 push ebp mov ebp, esp mov eax, [ebp+arg_0] pop ebp or ah, 40h and ah, 0FDh retn f endp That’s shorter. It is worth noting the compiler works with the EAX register part via the AH register —that is the EAX register part from the 8th to the 15th bits included. 7th (byte number) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL N.B. The 16-bit CPU 8086 accumulator was named AX and consisted of two 8-bit halves —AL (lower byte) and AH (higher byte). In 80386 almost all registers were extended to 32-bit, the accumulator was named EAX, but for the sake of compatibility, its older parts may be still accessed as AX/AH/AL. Since all x86 CPUs are successors of the 16-bit 8086 CPU, these older 16-bit opcodes are shorter than the newer 32-bit ones. That’s why the ``or ah, 40h'' instruction occupies only 3 bytes. It would be more logical way to emit here ``or eax, 04000h'' but that is 5 bytes, or even 6 (in case the register in the first operand is not EAX). Optimizing GCC and regparm It would be even shorter if to turn on the -O3 optimization flag and also set regparm=3. Listing 19.14: Optimizing GCC public f f proc near push ebp or ah, 40h mov ebp, esp and ah, 0FDh pop ebp retn f endp Indeed —the first argument is already loaded in EAX, so it is possible to work with it in-place. It is worth noting that both the function prologue (``push ebp / mov ebp,esp'') and epilogue (``pop ebp'') can easily be omitted here, but GCC probably is not good enough to do such code size optimizations. However, such short functions are better to be inlined functions ( 43 on page 500). 19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode) Listing 19.15: Optimizing Keil 6/2013 (ARM mode) 02 0C C0 E3 BIC R0, R0, #0x200 01 09 80 E3 ORR R0, R0, #0x4000 1E FF 2F E1 BX LR BIC (BItwise bit Clear) is an instruction for clearing specific bits. This is just like the AND instruction, but with inverted operand. I.e., it’s analogous to a NOT+AND instruction pair. ORR is “logical or”, analogous to OR in x86. So far it’s easy. 314
  • 339. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.2. SPECIFIC BIT SETTING/CLEARING 19.2.3 ARM + Optimizing Keil 6/2013 (thumb mode) Listing 19.16: Optimizing Keil 6/2013 (thumb mode) 01 21 89 03 MOVS R1, 0x4000 08 43 ORRS R0, R1 49 11 ASRS R1, R1, #5 ; generate 0x200 and place to R1 88 43 BICS R0, R1 70 47 BX LR Seems like Keil decided that the code in thumb mode, making 0x200 from 0x4000, is more compact than the code for writing 0x200 to an arbitrary register. So that is why, with the help of ASRS (arithmetic shift right), this value is calculated as 0x4000 ≫ 5. 19.2.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) Listing 19.17: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) 42 0C C0 E3 BIC R0, R0, #0x4200 01 09 80 E3 ORR R0, R0, #0x4000 1E FF 2F E1 BX LR The code that was generated by LLVM, in source code form could be something like this: REMOVE_BIT (rt, 0x4200); SET_BIT (rt, 0x4000); And it does exactly what we need. But why 0x4200? Perhaps, that an artifact from LLVM’s optimizer 5 . Probably a compiler’s optimizer error, but the generated code works correctly anyway. You can read more about compiler anomalies here ( 91 on page 870). Optimizing Xcode 4.6.3 (LLVM) for thumb mode generates the same code. 19.2.5 ARM: more about the BIC instruction Let’s rework the example slightly: int f(int a) { int rt=a; REMOVE_BIT (rt, 0x1234); return rt; }; Then the optimizing Keil 5.03 in ARM mode does: f PROC BIC r0,r0,#0x1000 BIC r0,r0,#0x234 BX lr ENDP There are two BIC instructions, i.e., bit 0x1234 are cleared in two passes. This is because it’s not possible to encode 0x1234 in a BIC instruction, but it’s possible to encode 0x1000 and 0x234. 19.2.6 ARM64: Optimizing GCC (Linaro) 4.9 Optimizing GCC compiling for ARM64 can use the AND instruction instead of BIC: Listing 19.18: Optimizing GCC (Linaro) 4.9 f: and w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF orr w0, w0, 16384 ; 0x4000 ret 5It was LLVM build 2410.2.00 bundled with Apple Xcode 4.6.3 315
  • 340. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.3. SHIFTS 19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9 Non-optimizing GCC generates more redundant code, but works just like optimized: Listing 19.19: Non-optimizing GCC (Linaro) 4.9 f: sub sp, sp, #32 str w0, [sp,12] ldr w0, [sp,12] str w0, [sp,28] ldr w0, [sp,28] orr w0, w0, 16384 ; 0x4000 str w0, [sp,28] ldr w0, [sp,28] and w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF str w0, [sp,28] ldr w0, [sp,28] add sp, sp, 32 ret 19.2.8 MIPS Listing 19.20: Optimizing GCC 4.4.5 (IDA) f: ; $a0=a ori $a0, 0x4000 ; $a0=a|0x4000 li $v0, 0xFFFFFDFF jr $ra and $v0, $a0, $v0 ; at finish: $v0 = $a0&$v0 = a|0x4000 & 0xFFFFFDFF ORI is,of course, the OR operation. “I” in the instruction name mean that the value is embedded in the machine code. But after that we have AND. There was no way to use ANDI because it’s not possible to embed the 0xFFFFFDFF number in a single instruction, so the compiler has to load 0xFFFFFDFF into register $V0 first and then generate AND which takes all its values from registers. 19.3 Shifts Bit shifts in C/C++ are implemented using ≪ and ≫ operators. The x86 ISA has the SHL (SHift Left) and SHR (SHift Right) instructions for this. Shift instructions are often used in division and multiplications by powers of two: 2n (e.g., 1, 2, 4, 8, etc): 16.1.2 on page 201, 16.2.1 on page 205. Shifting operations are also so important because they are often used for specific bit isolation or for constructing a value of several scattered bits. 19.4 Specific bit setting/clearing: FPU example Here is how bits are located in the float type in IEEE 754 form: 022233031 S exponent mantissa or fraction ( S—sign ) The sign of number is in the MSB6 . Will it be possible to change the sign of a floating point number without any FPU instructions? 6Most significant bit/byte 316
  • 341. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE #include <stdio.h> float my_abs (float i) { unsigned int tmp=(*(unsigned int*)&i) & 0x7FFFFFFF; return *(float*)&tmp; }; float set_sign (float i) { unsigned int tmp=(*(unsigned int*)&i) | 0x80000000; return *(float*)&tmp; }; float negate (float i) { unsigned int tmp=(*(unsigned int*)&i) ^ 0x80000000; return *(float*)&tmp; }; int main() { printf ("my_abs():n"); printf ("%fn", my_abs (123.456)); printf ("%fn", my_abs (-456.123)); printf ("set_sign():n"); printf ("%fn", set_sign (123.456)); printf ("%fn", set_sign (-456.123)); printf ("negate():n"); printf ("%fn", negate (123.456)); printf ("%fn", negate (-456.123)); }; We need this trickery in C/C++ to copy to/from float value without actual conversion. So there are three functions: my_abs() resets MSB; set_sign() sets MSB and negate() flips it. 19.4.1 A word about the XOR operation XOR is widely used when one need just to flip specific bit(s). Indeed, the XOR operation applied with 1 is effectively inverting a bit: input A input B output 0 0 0 0 1 1 1 0 1 1 1 0 And on the contrary, the XOR operation applied with 0 does nothing, i.e., it’s an idle operation. This is a very important property of the XOR operation and it’s highly recommended to memorize it. 19.4.2 x86 The code is pretty straightforward: Listing 19.21: Optimizing MSVC 2012 _tmp$ = 8 _i$ = 8 _my_abs PROC and DWORD PTR _i$[esp-4], 2147483647 ; 7fffffffH fld DWORD PTR _tmp$[esp-4] ret 0 _my_abs ENDP _tmp$ = 8 _i$ = 8 _set_sign PROC or DWORD PTR _i$[esp-4], -2147483648 ; 80000000H fld DWORD PTR _tmp$[esp-4] 317
  • 342. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE ret 0 _set_sign ENDP _tmp$ = 8 _i$ = 8 _negate PROC xor DWORD PTR _i$[esp-4], -2147483648 ; 80000000H fld DWORD PTR _tmp$[esp-4] ret 0 _negate ENDP An input value of type float is taken from the stack, but treated as an integer value. AND and OR reset and set the desired bit. XOR flips it. Finally, the modified value is loaded into ST0, because floating-point numbers are returned in this register. Now let’s try optimizing MSVC 2012 for x64: Listing 19.22: Optimizing MSVC 2012 x64 tmp$ = 8 i$ = 8 my_abs PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] btr eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 my_abs ENDP _TEXT ENDS tmp$ = 8 i$ = 8 set_sign PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] bts eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 set_sign ENDP tmp$ = 8 i$ = 8 negate PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] btc eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 negate ENDP The input value is passed in XMM0, then it is copied into the local stack and then we see some instructions that are new to us: BTR, BTS, BTC. These instructions are used for resetting (BTR), setting (BTS) and inverting (or complementing: BTC) specific bits. The 31st bit is MSB, counting from 0. Finally, the result is copied into XMM0, because floating point values are returned through XMM0 in Win64 environment. 19.4.3 MIPS GCC 4.4.5 for MIPS does mostly the same: Listing 19.23: Optimizing GCC 4.4.5 (IDA) my_abs: ; move from coprocessor 1: mfc1 $v1, $f12 li $v0, 0x7FFFFFFF ; $v0=0x7FFFFFFF ; do AND: and $v0, $v1 318
  • 343. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot set_sign: ; move from coprocessor 1: mfc1 $v0, $f12 lui $v1, 0x8000 ; $v1=0x80000000 ; do OR: or $v0, $v1, $v0 ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot negate: ; move from coprocessor 1: mfc1 $v0, $f12 lui $v1, 0x8000 ; $v1=0x80000000 ; do XOR: xor $v0, $v1, $v0 ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot One single LUI instruction is used to load 0x80000000 into a register, because LUI is clearing the low 16 bits and these are zeroes in the constant, so one LUI without subsequent ORI is enough. 19.4.4 ARM Optimizing Keil 6/2013 (ARM mode) Listing 19.24: Optimizing Keil 6/2013 (ARM mode) my_abs PROC ; clear bit: BIC r0,r0,#0x80000000 BX lr ENDP set_sign PROC ; do OR: ORR r0,r0,#0x80000000 BX lr ENDP negate PROC ; do XOR: EOR r0,r0,#0x80000000 BX lr ENDP So far so good. ARM has the BIC instruction, which explicitly clears specific bit(s). EOR is the ARM instruction name for XOR (“Exclusive OR”). Optimizing Keil 6/2013 (thumb mode) Listing 19.25: Optimizing Keil 6/2013 (thumb mode) my_abs PROC LSLS r0,r0,#1 ; r0=i<<1 319
  • 344. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.4. SPECIFIC BIT SETTING/CLEARING: FPU EXAMPLE LSRS r0,r0,#1 ; r0=(i<<1)>>1 BX lr ENDP set_sign PROC MOVS r1,#1 ; r1=1 LSLS r1,r1,#31 ; r1=1<<31=0x80000000 ORRS r0,r0,r1 ; r0=r0 | 0x80000000 BX lr ENDP negate PROC MOVS r1,#1 ; r1=1 LSLS r1,r1,#31 ; r1=1<<31=0x80000000 EORS r0,r0,r1 ; r0=r0 ^ 0x80000000 BX lr ENDP Thumb mode in ARM offers 16-bit instructions and not much data can be encoded in them, so here a MOVS/LSLS instruc- tion pair is used for forming the 0x80000000 constant. It works like this: 1 << 31 = 0x80000000. The code of my_abs is weird and it effectively works like this expression: (i << 1) >> 1. This statement looks meaningless. But nevertheless, when input << 1 is executed, the MSB (sign bit) is just dropped. When the subsequent result >> 1 statement is executed, all bits are now in their own places, but MSB is zero, because all “new” bits appearing from the shift operations are always zeroes. That is how the LSLS/LSRS instruction pair clears MSB. Optimizing GCC 4.6.3 (Raspberry Pi, ARM mode) Listing 19.26: Optimizing GCC 4.6.3 for Raspberry Pi (ARM mode) my_abs ; copy from S0 to R2: FMRS R2, S0 ; clear bit: BIC R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR set_sign ; copy from S0 to R2: FMRS R2, S0 ; do OR: ORR R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR negate ; copy from S0 to R2: FMRS R2, S0 ; do ADD: ADD R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR I run Raspberry Pi Linux in QEMU and it emulates an ARM FPU, so S-registers are used here for floating point numbers instead of R-registers. The FMRS instruction copies data from GPR to the FPU and back. my_abs() and set_sign() looks as expected, but negate()? Why is there ADD instead of XOR? It’s hard to believe, but the instruction “ADD register, 0x80000000” works just like “XOR register, 0x80000000”. First of all, what’s our goal? The goal is to flip the MSB, so let’s forget about the XOR operation. From school-level math- 320
  • 345. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 ematics we may remember that adding values like 1000 to other values never affects the last 3 digits. For example: 1234567 + 10000 = 1244567 ( last 4 digits are never affected). But here we operate in binary base and 0x80000000 is 100000000000000000000000000000000, i.e., only the highest bit is set. Adding 0x80000000 to any value never affects the lowest 31 bits, but affects only the MSB. Adding 1 to 0 is resulting in 1. Adding 1 to 1 is resulting in 10 in binary form, but the 32th bit (counting from zero) gets dropped, because our registers are 32 bit wide, so the result is 0. That’s why XOR can be replaced by ADD here. I’m not sure why GCC decided to do this, but it works correctly. 19.5 Counting bits set to 1 Here is a simple example of a function that calculates the number of bits set in the input value. This operation is also called “population count” 7 . #include <stdio.h> #define IS_SET(flag, bit) ((flag) & (bit)) int f(unsigned int a) { int i; int rt=0; for (i=0; i<32; i++) if (IS_SET (a, 1<<i)) rt++; return rt; }; int main() { f(0x12345678); // test }; In this loop, the iteration count value i is counting from 0 to 31, so the 1 ≪ i statement is counting from 1 to 0x80000000. Describing this operation in natural language, we would say shift 1 by n bits left. In other words, 1 ≪ i statement consequently produces all possible bit positions in a 32-bit number. The freed bit at right is always cleared. Here is a table of all possible 1 ≪ i for i = 0...31: 7modern x86 CPUs (supporting SSE4) even have a POPCNT instruction for it 321
  • 346. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 C/C++ expression Power of two Decimal form Hexadecimal form 1 ≪ 0 1 1 1 1 ≪ 1 21 2 2 1 ≪ 2 22 4 4 1 ≪ 3 23 8 8 1 ≪ 4 24 16 0x10 1 ≪ 5 25 32 0x20 1 ≪ 6 26 64 0x40 1 ≪ 7 27 128 0x80 1 ≪ 8 28 256 0x100 1 ≪ 9 29 512 0x200 1 ≪ 10 210 1024 0x400 1 ≪ 11 211 2048 0x800 1 ≪ 12 212 4096 0x1000 1 ≪ 13 213 8192 0x2000 1 ≪ 14 214 16384 0x4000 1 ≪ 15 215 32768 0x8000 1 ≪ 16 216 65536 0x10000 1 ≪ 17 217 131072 0x20000 1 ≪ 18 218 262144 0x40000 1 ≪ 19 219 524288 0x80000 1 ≪ 20 220 1048576 0x100000 1 ≪ 21 221 2097152 0x200000 1 ≪ 22 222 4194304 0x400000 1 ≪ 23 223 8388608 0x800000 1 ≪ 24 224 16777216 0x1000000 1 ≪ 25 225 33554432 0x2000000 1 ≪ 26 226 67108864 0x4000000 1 ≪ 27 227 134217728 0x8000000 1 ≪ 28 228 268435456 0x10000000 1 ≪ 29 229 536870912 0x20000000 1 ≪ 30 230 1073741824 0x40000000 1 ≪ 31 231 2147483648 0x80000000 These constant numbers (bit masks) very often appear in code and a practicing reverse engineer must be able to spot them quickly. You probably haven’t to memorize the decimal numbers, but the hexadecimal ones are very easy to remember. These constants are very often used for mapping flags to specific bits. For example, here is excerpt from ssl_private.h from Apache 2.4.6 source code: /** * Define the SSL options */ #define SSL_OPT_NONE (0) #define SSL_OPT_RELSET (1<<0) #define SSL_OPT_STDENVVARS (1<<1) #define SSL_OPT_EXPORTCERTDATA (1<<3) #define SSL_OPT_FAKEBASICAUTH (1<<4) #define SSL_OPT_STRICTREQUIRE (1<<5) #define SSL_OPT_OPTRENEGOTIATE (1<<6) #define SSL_OPT_LEGACYDNFORMAT (1<<7) Let’s get back to our example. The IS_SET macro checks bit presence in a. The IS_SET macro is in fact the logical AND operation (AND) and it returns 0 if the specific bit is absent there, or the bit mask, if the bit is present. The if() operator in C/C++ triggers if the expression in it is not zero, it might be even 123456, that is why it always works correctly. 19.5.1 x86 MSVC Let’s compile (MSVC 2010): Listing 19.27: MSVC 2010 _rt$ = -8 ; size = 4 322
  • 347. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 _i$ = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp sub esp, 8 mov DWORD PTR _rt$[ebp], 0 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN4@f $LN3@f: mov eax, DWORD PTR _i$[ebp] ; increment of i add eax, 1 mov DWORD PTR _i$[ebp], eax $LN4@f: cmp DWORD PTR _i$[ebp], 32 ; 00000020H jge SHORT $LN2@f ; loop finished? mov edx, 1 mov ecx, DWORD PTR _i$[ebp] shl edx, cl ; EDX=EDX<<CL and edx, DWORD PTR _a$[ebp] je SHORT $LN1@f ; result of AND instruction was 0? ; then skip next instructions mov eax, DWORD PTR _rt$[ebp] ; no, not zero add eax, 1 ; increment rt mov DWORD PTR _rt$[ebp], eax $LN1@f: jmp SHORT $LN3@f $LN2@f: mov eax, DWORD PTR _rt$[ebp] mov esp, ebp pop ebp ret 0 _f ENDP 323
  • 348. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 OllyDbg Let’s load this example into OllyDbg. Let the input value be 0x12345678. For i = 1, we see how i is loaded into ECX: Figure 19.5: OllyDbg: i = 1, i is loaded into ECX EDX is 1. SHL is to be executed now. 324
  • 349. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 SHL was executed: Figure 19.6: OllyDbg: i = 1, EDX =1 ≪ 1 = 2 EDX contain 1 ≪ 1 (or 2). This is a bit mask. 325
  • 350. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 AND sets ZF to 1, which implies that the input value (0x12345678) ANDed with 2 results in 0: Figure 19.7: OllyDbg: i = 1, is there that bit in the input value? No. (ZF =1) So, there is no corresponding bit in the input value. The piece of code, which increments the counter is not to be executed: the JZ instruction bypassing it. 326
  • 351. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 I traced a bit further and i is now 4. SHL is to be executed now: Figure 19.8: OllyDbg: i = 4, i is loaded into ECX 327
  • 352. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 EDX =1 ≪ 4 (or 0x10 or 16): Figure 19.9: OllyDbg: i = 4, EDX =1 ≪ 4 = 0x10 This is another bit mask. 328
  • 353. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 AND is executed: Figure 19.10: OllyDbg: i = 4, is there that bit in the input value? Yes. (ZF =0) ZF is 0 because this bit is present in the input value. Indeed, 0x12345678 & 0x10 = 0x10. This bit counts: the jump is not triggering and the bit counter incrementing. The function returns 13. This is total number of bits set in 0x12345678. GCC Let’s compile it in GCC 4.4.1: Listing 19.28: GCC 4.4.1 public f f proc near rt = dword ptr -0Ch i = dword ptr -8 arg_0 = dword ptr 8 push ebp mov ebp, esp push ebx sub esp, 10h mov [ebp+rt], 0 mov [ebp+i], 0 jmp short loc_80483EF loc_80483D0: mov eax, [ebp+i] mov edx, 1 mov ebx, edx mov ecx, eax shl ebx, cl mov eax, ebx and eax, [ebp+arg_0] test eax, eax jz short loc_80483EB add [ebp+rt], 1 loc_80483EB: add [ebp+i], 1 loc_80483EF: cmp [ebp+i], 1Fh jle short loc_80483D0 mov eax, [ebp+rt] add esp, 10h pop ebx pop ebp retn 329
  • 354. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 f endp 19.5.2 x64 I modified the example slightly to extend it to 64-bit: #include <stdio.h> #include <stdint.h> #define IS_SET(flag, bit) ((flag) & (bit)) int f(uint64_t a) { uint64_t i; int rt=0; for (i=0; i<64; i++) if (IS_SET (a, 1ULL<<i)) rt++; return rt; }; Non-optimizing GCC 4.8.2 So far so easy. Listing 19.29: Non-optimizing GCC 4.8.2 f: push rbp mov rbp, rsp mov QWORD PTR [rbp-24], rdi ; a mov DWORD PTR [rbp-12], 0 ; rt=0 mov QWORD PTR [rbp-8], 0 ; i=0 jmp .L2 .L4: mov rax, QWORD PTR [rbp-8] mov rdx, QWORD PTR [rbp-24] ; RAX = i, RDX = a mov ecx, eax ; ECX = i shr rdx, cl ; RDX = RDX>>CL = a>>i mov rax, rdx ; RAX = RDX = a>>i and eax, 1 ; EAX = EAX&1 = (a>>i)&1 test rax, rax ; the last bit is zero? ; skip the next ADD instruction, if it was so. je .L3 add DWORD PTR [rbp-12], 1 ; rt++ .L3: add QWORD PTR [rbp-8], 1 ; i++ .L2: cmp QWORD PTR [rbp-8], 63 ; i<63? jbe .L4 ; jump to the loop body begin, if so mov eax, DWORD PTR [rbp-12] ; return rt pop rbp ret Optimizing GCC 4.8.2 Listing 19.30: Optimizing GCC 4.8.2 1 f: 330
  • 355. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 2 xor eax, eax ; rt variable will be in EAX register 3 xor ecx, ecx ; i variable will be in ECX register 4 .L3: 5 mov rsi, rdi ; load input value 6 lea edx, [rax+1] ; EDX=EAX+1 7 ; EDX here is a "new version of rt", which will be written into rt variable, if the last bit is 1 8 shr rsi, cl ; RSI=RSI>>CL 9 and esi, 1 ; ESI=ESI&1 10 ; the last bit is 1? If so, write "new version of rt" into EAX 11 cmovne eax, edx 12 add rcx, 1 ; RCX++ 13 cmp rcx, 64 14 jne .L3 15 rep ret ; AKA fatret This code is terser, but has a quirk. In all examples that we see so far, we were incrementing the “rt” value after comparing a specific bit, but the code here increments “rt” before (line 6), writing the new value into register EDX. Thus, if the last bit is 1, the CMOVNE 8 instruction (which is a synonym for CMOVNZ 9 ) commits the new value of “rt” by moving EDX (“proposed rt value”) into EAX (“current rt” to be returned at the end). Hence, the incrementing is done at each step of loop, i.e., 64 times, without any relation to the input value. The advantage of this code is that it contain only one conditional jump (at the end of the loop) instead of two jumps (skipping the “rt” value increment and at the end of loop). And that might work faster on the modern CPUs with branch predictors: 33.1 on page 456. The last instruction is REP RET (opcode F3 C3) which is also called FATRET by MSVC. This is somewhat optimized version of RET, which is recommended by AMD to be placed at the end of function, if RET goes right after conditional jump: [AMD13b, p.15] 10 . Optimizing MSVC 2010 Listing 19.31: MSVC 2010 a$ = 8 f PROC ; RCX = input value xor eax, eax mov edx, 1 lea r8d, QWORD PTR [rax+64] ; R8D=64 npad 5 $LL4@f: test rdx, rcx ; there are no such bit in input value? ; skip the next INC instruction then. je SHORT $LN3@f inc eax ; rt++ $LN3@f: rol rdx, 1 ; RDX=RDX<<1 dec r8 ; R8-- jne SHORT $LL4@f fatret 0 f ENDP Here the ROL instruction is used instead of SHL, which is in fact “rotate left” instead of “shift left”, but in this example it works just as SHL. You can read more about the rotate instruction here: A.6.3 on page 939. R8 here is counting from 64 to 0. It’s just like an inverted i. Here is a table of some registers during the execution: 8Conditional MOVe if Not Equal 9Conditional MOVe if Not Zero 10More information on it: http://go.yurichev.com/17328 331
  • 356. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 RDX R8 0x0000000000000001 64 0x0000000000000002 63 0x0000000000000004 62 0x0000000000000008 61 ... ... 0x4000000000000000 2 0x8000000000000000 1 At the end we see the FATRET instruction, which was explained here: 19.5.2 on page 331. Optimizing MSVC 2012 Listing 19.32: MSVC 2012 a$ = 8 f PROC ; RCX = input value xor eax, eax mov edx, 1 lea r8d, QWORD PTR [rax+32] ; EDX = 1, R8D = 32 npad 5 $LL4@f: ; pass 1 ------------------------------------ test rdx, rcx je SHORT $LN3@f inc eax ; rt++ $LN3@f: rol rdx, 1 ; RDX=RDX<<1 ; ------------------------------------------- ; pass 2 ------------------------------------ test rdx, rcx je SHORT $LN11@f inc eax ; rt++ $LN11@f: rol rdx, 1 ; RDX=RDX<<1 ; ------------------------------------------- dec r8 ; R8-- jne SHORT $LL4@f fatret 0 f ENDP Optimizing MSVC 2012 does almost the same job as optimizing MSVC 2010, but somehow, it generates two identical loop bodies and the loop count is now 32 instead of 64. To be honest, I don’t know why. Some optimization trick? Maybe it’s better for the loop body to be slightly longer? Anyway, I have added the code here intentionally to show that sometimes the compiler output may be really weird and illogical, but perfectly working. 19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) (ARM mode) Listing 19.33: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) MOV R1, R0 MOV R0, #0 MOV R2, #1 MOV R3, R0 loc_2E54 TST R1, R2,LSL R3 ; set flags according to R1 & (R2<<R3) ADD R3, R3, #1 ; R3++ ADDNE R0, R0, #1 ; if ZF flag is cleared by TST, then R0++ CMP R3, #32 BNE loc_2E54 BX LR TST is the same things as TEST in x86. As I mentioned before ( 41.2.1 on page 489), there are no separate shifting instructions in ARM mode. However, there are modifiers LSL (Logical Shift Left), LSR (Logical Shift Right), ASR (Arithmetic Shift Right), ROR (Rotate Right) and RRX (Rotate Right with Extend) , which may be added to such instructions as MOV, TST, CMP, ADD, SUB, RSB11 . 11These instructions are also called “data processing instructions” 332
  • 357. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 These modificators define how to shift the second operand and by how many bits. Thus the ``TST R1, R2,LSL R3'' instruction works here as R1 ∧ (R2 ≪ R3). 19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) Almost the same, but here are two LSL.W/TST instructions are used instead of a single TST, because in thumb mode it is not possible to define LSL modifier directly in TST. MOV R1, R0 MOVS R0, #0 MOV.W R9, #1 MOVS R3, #0 loc_2F7A LSL.W R2, R9, R3 TST R2, R1 ADD.W R3, R3, #1 IT NE ADDNE R0, #1 CMP R3, #32 BNE loc_2F7A BX LR 19.5.5 ARM64 + Optimizing GCC 4.9 I took the 64-bit example I already used: 19.5.2 on page 330. Listing 19.34: Optimizing GCC (Linaro) 4.8 f: mov w2, 0 ; rt=0 mov x5, 1 mov w1, w2 .L2: lsl x4, x5, x1 ; w4 = w5<<w1 = 1<<i add w3, w2, 1 ; new_rt=rt+1 tst x4, x0 ; (1<<i) & a add w1, w1, 1 ; i++ ; result of TST was non-zero? ; then w2=w3 or rt=new_rt. ; otherwise: w2=w2 or rt=rt (idle operation) csel w2, w3, w2, ne cmp w1, 64 ; i<64? bne .L2 ; yes mov w0, w2 ; return rt ret The result is very similar to what GCC generates for x64: 19.30 on page 330. The CSEL instruction is “Conditional SELect”, it just choose one variable of two depending on the flags set by TST and copies the value into W2 , which holds the “rt” variable. 19.5.6 ARM64 + Non-optimizing GCC 4.9 And again, the 64-bit example I already used: 19.5.2 on page 330. The code is more verbose, as usual. Listing 19.35: Non-optimizing GCC (Linaro) 4.8 f: sub sp, sp, #32 str x0, [sp,8] ; store "a" value to Register Save Area str wzr, [sp,24] ; rt=0 str wzr, [sp,28] ; i=0 b .L2 .L4: ldr w0, [sp,28] mov x1, 1 lsl x0, x1, x0 ; X0 = X1<<X0 = 1<<i mov x1, x0 ; X1 = 1<<1 333
  • 358. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 ldr x0, [sp,8] ; X0 = a and x0, x1, x0 ; X0 = X1&X0 = (1<<i) & a ; X0 contain zero? then jump to .L3, skipping "rt" increment cmp x0, xzr beq .L3 ; rt++ ldr w0, [sp,24] add w0, w0, 1 str w0, [sp,24] .L3: ; i++ ldr w0, [sp,28] add w0, w0, 1 str w0, [sp,28] .L2: ; i<=63? then jump to .L4 ldr w0, [sp,28] cmp w0, 63 ble .L4 ; return rt ldr w0, [sp,24] add sp, sp, 32 ret 19.5.7 MIPS Non-optimizing GCC Listing 19.36: Non-optimizing GCC 4.4.5 (IDA) f: ; IDA is not aware of variable names, I gave them manually: rt = -0x10 i = -0xC var_4 = -4 a = 0 addiu $sp, -0x18 sw $fp, 0x18+var_4($sp) move $fp, $sp sw $a0, 0x18+a($fp) ; initialize rt and i variables to zero: sw $zero, 0x18+rt($fp) sw $zero, 0x18+i($fp) ; jump to loop check instructions: b loc_68 or $at, $zero ; branch delay slot, NOP loc_20: li $v1, 1 lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP sllv $v0, $v1, $v0 ; $v0 = 1<<i move $v1, $v0 lw $v0, 0x18+a($fp) or $at, $zero ; load delay slot, NOP and $v0, $v1, $v0 ; $v0 = a&(1<<i) ; is a&(1<<i) equals to zero? jump to loc_58 then: beqz $v0, loc_58 or $at, $zero ; no jump occurred, that means a&(1<<i)!=0, so increment "rt" then: lw $v0, 0x18+rt($fp) or $at, $zero ; load delay slot, NOP addiu $v0, 1 sw $v0, 0x18+rt($fp) 334
  • 359. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.5. COUNTING BITS SET TO 1 loc_58: ; increment i: lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP addiu $v0, 1 sw $v0, 0x18+i($fp) loc_68: ; load i and compare it with 0x20 (32). ; jump to loc_20 if it is less then 0x20 (32): lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP slti $v0, 0x20 # ' ' bnez $v0, loc_20 or $at, $zero ; branch delay slot, NOP ; function epilogue. return rt: lw $v0, 0x18+rt($fp) move $sp, $fp ; load delay slot lw $fp, 0x18+var_4($sp) addiu $sp, 0x18 ; load delay slot jr $ra or $at, $zero ; branch delay slot, NOP That is verbose: all local variables are located in the local stack and reloaded each time they’re needed. The SLLV instruction is “Shift Word Left Logical Variable”, it differs from SLL only in that the shift amount is encoded in the SLL instruction (and is fixed, as a consequence), but SLLV takes shift amount from a register. Optimizing GCC That is terser. There are two shift instructions instead of one. Why? It’s possible to replace the first SLLV instruction with an unconditional branch instruction that jumps right to the second SLLV. But this is another branching instruction in the function, and it’s always favorable to get rid of them: 33.1 on page 456. Listing 19.37: Optimizing GCC 4.4.5 (IDA) f: ; $a0=a ; rt variable will reside in $v0: move $v0, $zero ; i variable will reside in $v1: move $v1, $zero li $t0, 1 li $a3, 32 sllv $a1, $t0, $v1 ; $a1 = $t0<<$v1 = 1<<i loc_14: and $a1, $a0 ; $a1 = a&(1<<i) ; increment i: addiu $v1, 1 ; jump to loc_28 if a&(1<<i)==0 and increment rt: beqz $a1, loc_28 addiu $a2, $v0, 1 ; if BEQZ was not triggered, save updated rt into $v0: move $v0, $a2 loc_28: ; if i!=32, jump to loc_14 and also prepare next shifted value: bne $v1, $a3, loc_14 sllv $a1, $t0, $v1 ; return jr $ra or $at, $zero ; branch delay slot, NOP 335
  • 360. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.6. CONCLUSION 19.6 Conclusion Analogous to the C/C++ shifting operators ≪ and ≫, the shift instructions in x86 are SHR/SHL (for unsigned values) and SAR/SHL (for signed values). The shift instructions in ARM are LSR/LSL (for unsigned values) and ASR/LSL (for signed values). It’s also possible to add shift suffix to some instructions (which are called “data processing instructions”). 19.6.1 Check for specific bit (known at compile stage) Test if the 1000000 bit (0x40) is present in the register’s value: Listing 19.38: C/C++ if (input&0x40) ... Listing 19.39: x86 TEST REG, 40h JNZ is_set ; bit is not set Listing 19.40: x86 TEST REG, 40h JZ is_cleared ; bit is set Listing 19.41: ARM (ARM mode) TST REG, #0x40 BNE is_set ; bit is not set Sometimes, AND is used instead of TEST, but the flags that are set are the same. 19.6.2 Check for specific bit (specified at runtime) This is usually done by this C/C++ code snippet (shift value by n bits right, then cut off lowest bit): Listing 19.42: C/C++ if ((value>>n)&1) .... This is usually implemented in x86 code as: Listing 19.43: x86 ; REG=input_value ; CL=n SHR REG, CL AND REG, 1 Or (shift 1 bit n times left, isolate this bit in input value and check if it’s not zero): Listing 19.44: C/C++ if (value & (1<<n)) .... This is usually implemented in x86 code as: Listing 19.45: x86 ; CL=n MOV REG, 1 SHL REG, CL AND input_value, REG 336
  • 361. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.6. CONCLUSION 19.6.3 Set specific bit (known at compile stage) Listing 19.46: C/C++ value=value|0x40; Listing 19.47: x86 OR REG, 40h Listing 19.48: ARM (ARM mode) and ARM64 ORR R0, R0, #0x40 19.6.4 Set specific bit (specified at runtime) Listing 19.49: C/C++ value=value|(1<<n); This is usually implemented in x86 code as: Listing 19.50: x86 ; CL=n MOV REG, 1 SHL REG, CL OR input_value, REG 19.6.5 Clear specific bit (known at compile stage) Just apply AND operation with the inverted value: Listing 19.51: C/C++ value=value&(~0x40); Listing 19.52: x86 AND REG, 0FFFFFFBFh Listing 19.53: x64 AND REG, 0FFFFFFFFFFFFFFBFh This is actually leaving all bits set except one. ARM in ARM mode has BIC instruction, which works like the NOT+AND instruction pair: Listing 19.54: ARM (ARM mode) BIC R0, R0, #0x40 19.6.6 Clear specific bit (specified at runtime) Listing 19.55: C/C++ value=value&(~(1<<n)); Listing 19.56: x86 ; CL=n MOV REG, 1 SHL REG, CL NOT REG AND input_value, REG 337
  • 362. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES 19.7 Exercises 19.7.1 Exercise #1 What does this code do? Listing 19.57: Optimizing MSVC 2010 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, ecx mov edx, ecx shl edx, 16 ; 00000010H and eax, 65280 ; 0000ff00H or eax, edx mov edx, ecx and edx, 16711680 ; 00ff0000H shr ecx, 16 ; 00000010H or edx, ecx shl eax, 8 shr edx, 8 or eax, edx ret 0 _f ENDP Listing 19.58: Optimizing Keil 6/2013 (ARM mode) f PROC MOV r1,#0xff0000 AND r1,r1,r0,LSL #8 MOV r2,#0xff00 ORR r1,r1,r0,LSR #24 AND r2,r2,r0,LSR #8 ORR r1,r1,r2 ORR r0,r1,r0,LSL #24 BX lr ENDP Listing 19.59: Optimizing Keil 6/2013 (thumb mode) f PROC MOVS r3,#0xff LSLS r2,r0,#8 LSLS r3,r3,#16 ANDS r2,r2,r3 LSRS r1,r0,#24 ORRS r1,r1,r2 LSRS r2,r0,#8 ASRS r3,r3,#8 ANDS r2,r2,r3 ORRS r1,r1,r2 LSLS r0,r0,#24 ORRS r0,r0,r1 BX lr ENDP Listing 19.60: Optimizing GCC 4.9 (ARM64) f: rev w0, w0 ret Listing 19.61: Optimizing GCC 4.4.5 (MIPS) (IDA) f: srl $v0, $a0, 24 sll $v1, $a0, 24 sll $a1, $a0, 8 or $v1, $v0 338
  • 363. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES lui $v0, 0xFF and $v0, $a1, $v0 srl $a0, 8 or $v0, $v1, $v0 andi $a0, 0xFF00 jr $ra or $v0, $a0 Answer: G.1.11 on page 956. 19.7.2 Exercise #2 What does this code do? Listing 19.62: Optimizing MSVC 2010 _a$ = 8 ; size = 4 _f PROC push esi mov esi, DWORD PTR _a$[esp] xor ecx, ecx push edi lea edx, DWORD PTR [ecx+1] xor eax, eax npad 3 ; align next label $LL3@f: mov edi, esi shr edi, cl add ecx, 4 and edi, 15 imul edi, edx lea edx, DWORD PTR [edx+edx*4] add eax, edi add edx, edx cmp ecx, 28 jle SHORT $LL3@f pop edi pop esi ret 0 _f ENDP Listing 19.63: Optimizing Keil 6/2013 (ARM mode) f PROC MOV r3,r0 MOV r1,#0 MOV r2,#1 MOV r0,r1 |L0.16| LSR r12,r3,r1 AND r12,r12,#0xf MLA r0,r12,r2,r0 ADD r1,r1,#4 ADD r2,r2,r2,LSL #2 CMP r1,#0x1c LSL r2,r2,#1 BLE |L0.16| BX lr ENDP Listing 19.64: Optimizing Keil 6/2013 (thumb mode) f PROC PUSH {r4,lr} MOVS r3,r0 MOVS r1,#0 MOVS r2,#1 MOVS r0,r1 |L0.10| MOVS r4,r3 339
  • 364. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES LSRS r4,r4,r1 LSLS r4,r4,#28 LSRS r4,r4,#28 MULS r4,r2,r4 ADDS r0,r4,r0 MOVS r4,#0xa MULS r2,r4,r2 ADDS r1,r1,#4 CMP r1,#0x1c BLE |L0.10| POP {r4,pc} ENDP Listing 19.65: Non-optimizing GCC 4.9 (ARM64) f: sub sp, sp, #32 str w0, [sp,12] str wzr, [sp,28] mov w0, 1 str w0, [sp,24] str wzr, [sp,20] b .L2 .L3: ldr w0, [sp,28] ldr w1, [sp,12] lsr w0, w1, w0 and w1, w0, 15 ldr w0, [sp,24] mul w0, w1, w0 ldr w1, [sp,20] add w0, w1, w0 str w0, [sp,20] ldr w0, [sp,28] add w0, w0, 4 str w0, [sp,28] ldr w1, [sp,24] mov w0, w1 lsl w0, w0, 2 add w0, w0, w1 lsl w0, w0, 1 str w0, [sp,24] .L2: ldr w0, [sp,28] cmp w0, 28 ble .L3 ldr w0, [sp,20] add sp, sp, 32 ret Listing 19.66: Optimizing GCC 4.4.5 (MIPS) (IDA) f: srl $v0, $a0, 8 srl $a3, $a0, 20 andi $a3, 0xF andi $v0, 0xF srl $a1, $a0, 12 srl $a2, $a0, 16 andi $a1, 0xF andi $a2, 0xF sll $t2, $v0, 4 sll $v1, $a3, 2 sll $t0, $v0, 2 srl $t1, $a0, 4 sll $t5, $a3, 7 addu $t0, $t2 subu $t5, $v1 andi $t1, 0xF srl $v1, $a0, 28 340
  • 365. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES sll $t4, $a1, 7 sll $t2, $a2, 2 sll $t3, $a1, 2 sll $t7, $a2, 7 srl $v0, $a0, 24 addu $a3, $t5, $a3 subu $t3, $t4, $t3 subu $t7, $t2 andi $v0, 0xF sll $t5, $t1, 3 sll $t6, $v1, 8 sll $t2, $t0, 2 sll $t4, $t1, 1 sll $t1, $v1, 3 addu $a2, $t7, $a2 subu $t1, $t6, $t1 addu $t2, $t0, $t2 addu $t4, $t5 addu $a1, $t3, $a1 sll $t5, $a3, 2 sll $t3, $v0, 8 sll $t0, $v0, 3 addu $a3, $t5 subu $t0, $t3, $t0 addu $t4, $t2, $t4 sll $t3, $a2, 2 sll $t2, $t1, 6 sll $a1, 3 addu $a1, $t4, $a1 subu $t1, $t2, $t1 addu $a2, $t3 sll $t2, $t0, 6 sll $t3, $a3, 2 andi $a0, 0xF addu $v1, $t1, $v1 addu $a0, $a1 addu $a3, $t3 subu $t0, $t2, $t0 sll $a2, 4 addu $a2, $a0, $a2 addu $v0, $t0, $v0 sll $a1, $v1, 2 sll $a3, 5 addu $a3, $a2, $a3 addu $v1, $a1 sll $v0, 6 addu $v0, $a3, $v0 sll $v1, 7 jr $ra addu $v0, $v1, $v0 Answer: G.1.11 on page 957. 19.7.3 Exercise #3 Using the MSDN12 documentation, find out which flags were used in the MessageBox() win32 function call. Listing 19.67: Optimizing MSVC 2010 _main PROC push 278595 ; 00044043H push OFFSET $SG79792 ; 'caption' push OFFSET $SG79793 ; 'hello, world!' push 0 call DWORD PTR __imp__MessageBoxA@16 xor eax, eax ret 0 _main ENDP 12Microsoft Developer Network 341
  • 366. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES Answer: G.1.11 on page 957. 19.7.4 Exercise #4 What does this code do? Listing 19.68: Optimizing MSVC 2010 _m$ = 8 ; size = 4 _n$ = 12 ; size = 4 _f PROC mov ecx, DWORD PTR _n$[esp-4] xor eax, eax xor edx, edx test ecx, ecx je SHORT $LN2@f push esi mov esi, DWORD PTR _m$[esp] $LL3@f: test cl, 1 je SHORT $LN1@f add eax, esi adc edx, 0 $LN1@f: add esi, esi shr ecx, 1 jne SHORT $LL3@f pop esi $LN2@f: ret 0 _f ENDP Listing 19.69: Optimizing Keil 6/2013 (ARM mode) f PROC PUSH {r4,lr} MOV r3,r0 MOV r0,#0 MOV r2,r0 MOV r12,r0 B |L0.48| |L0.24| TST r1,#1 BEQ |L0.40| ADDS r0,r0,r3 ADC r2,r2,r12 |L0.40| LSL r3,r3,#1 LSR r1,r1,#1 |L0.48| CMP r1,#0 MOVEQ r1,r2 BNE |L0.24| POP {r4,pc} ENDP Listing 19.70: Optimizing Keil 6/2013 (thumb mode) f PROC PUSH {r4,r5,lr} MOVS r3,r0 MOVS r0,#0 MOVS r2,r0 MOVS r4,r0 B |L0.24| |L0.12| LSLS r5,r1,#31 BEQ |L0.20| ADDS r0,r0,r3 ADCS r2,r2,r4 342
  • 367. CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 19.7. EXERCISES |L0.20| LSLS r3,r3,#1 LSRS r1,r1,#1 |L0.24| CMP r1,#0 BNE |L0.12| MOVS r1,r2 POP {r4,r5,pc} ENDP Listing 19.71: Optimizing GCC 4.9 (ARM64) f: mov w2, w0 mov x0, 0 cbz w1, .L2 .L3: and w3, w1, 1 lsr w1, w1, 1 cmp w3, wzr add x3, x0, x2, uxtw lsl w2, w2, 1 csel x0, x3, x0, ne cbnz w1, .L3 .L2: ret Listing 19.72: Optimizing GCC 4.4.5 (MIPS) (IDA) mult: beqz $a1, loc_40 move $a3, $zero move $a2, $zero addu $t0, $a3, $a0 loc_10: # CODE XREF: mult+38 sltu $t1, $t0, $a3 move $v1, $t0 andi $t0, $a1, 1 addu $t1, $a2 beqz $t0, loc_30 srl $a1, 1 move $a3, $v1 move $a2, $t1 loc_30: # CODE XREF: mult+20 beqz $a1, loc_44 sll $a0, 1 b loc_10 addu $t0, $a3, $a0 loc_40: # CODE XREF: mult move $a2, $zero loc_44: # CODE XREF: mult:loc_30 move $v0, $a2 jr $ra move $v1, $a3 Answer: G.1.11 on page 957. 343
  • 368. CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR Chapter 20 Linear congruential generator as pseudorandom number generator The linear congruential generator is probably the simplest possible way to generate random numbers. It’s not in favour in modern times1 , but it’s so simple (just one multiplication, one addition and one AND operation), we can use it as an example. #include <stdint.h> // constants from the Numerical Recipes book #define RNG_a 1664525 #define RNG_c 1013904223 static uint32_t rand_state; void my_srand (uint32_t init) { rand_state=init; } int my_rand () { rand_state=rand_state*RNG_a; rand_state=rand_state+RNG_c; return rand_state & 0x7fff; } There are two functions: the first one is used to initialize the internal state, and the second one is called to generate pseudorandom numbers. We see that two constants are used in the algorithm. They are taken from [Pre+07]. I defined them using a #define C/C++ statement. It’s a macro. The difference between a C/C++ macro and a constant is that all macros are replaced with their value by C/C++ preprocessor, and they don’t take any memory, unlike variables. In contrast, a constant is a read-only variable. It’s possible to take a pointer (or address) of a constant variable, but impossible to do so with a macro. The last AND operation is needed because by C-standard, my_rand() has to return a value in the 0..32767 range. If you want to get 32-bit pseudorandom values, just omit the last AND operation. 20.1 x86 Listing 20.1: Optimizing MSVC 2013 _BSS SEGMENT _rand_state DD 01H DUP (?) _BSS ENDS _init$ = 8 _srand PROC mov eax, DWORD PTR _init$[esp-4] mov DWORD PTR _rand_state, eax ret 0 _srand ENDP _TEXT SEGMENT 1Mersenne twister is better 344
  • 369. CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.2. X64 _rand PROC imul eax, DWORD PTR _rand_state, 1664525 add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR _rand_state, eax and eax, 32767 ; 00007fffH ret 0 _rand ENDP _TEXT ENDS Here we see it: both constants are embedded into the code. There is no memory allocated for them. The my_srand() function just copies its input value into the internal rand_state variable. my_rand() takes it, calculates the next rand_state, cuts it and leaves it in the EAX register. The non-optimized version is more verbose: Listing 20.2: Non-optimizing MSVC 2013 _BSS SEGMENT _rand_state DD 01H DUP (?) _BSS ENDS _init$ = 8 _srand PROC push ebp mov ebp, esp mov eax, DWORD PTR _init$[ebp] mov DWORD PTR _rand_state, eax pop ebp ret 0 _srand ENDP _TEXT SEGMENT _rand PROC push ebp mov ebp, esp imul eax, DWORD PTR _rand_state, 1664525 mov DWORD PTR _rand_state, eax mov ecx, DWORD PTR _rand_state add ecx, 1013904223 ; 3c6ef35fH mov DWORD PTR _rand_state, ecx mov eax, DWORD PTR _rand_state and eax, 32767 ; 00007fffH pop ebp ret 0 _rand ENDP _TEXT ENDS 20.2 x64 The x64 version is mostly the same and uses 32-bit registers instead of 64-bit ones (because we are working with int values here). But my_srand() takes its input argument from the ECX register rather than from stack: Listing 20.3: Optimizing MSVC 2013 x64 _BSS SEGMENT rand_state DD 01H DUP (?) _BSS ENDS init$ = 8 my_srand PROC ; ECX = input argument mov DWORD PTR rand_state, ecx ret 0 my_srand ENDP _TEXT SEGMENT my_rand PROC imul eax, DWORD PTR rand_state, 1664525 ; 0019660dH 345
  • 370. CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.3. 32-BIT ARM add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR rand_state, eax and eax, 32767 ; 00007fffH ret 0 my_rand ENDP _TEXT ENDS GCC compiler generates mostly the same code. 20.3 32-bit ARM Listing 20.4: Optimizing Keil 6/2013 (ARM mode) my_srand PROC LDR r1,|L0.52| ; load pointer to rand_state STR r0,[r1,#0] ; save rand_state BX lr ENDP my_rand PROC LDR r0,|L0.52| ; load pointer to rand_state LDR r2,|L0.56| ; load RNG_a LDR r1,[r0,#0] ; load rand_state MUL r1,r2,r1 LDR r2,|L0.60| ; load RNG_c ADD r1,r1,r2 STR r1,[r0,#0] ; save rand_state ; AND with 0x7FFF: LSL r0,r1,#17 LSR r0,r0,#17 BX lr ENDP |L0.52| DCD ||.data|| |L0.56| DCD 0x0019660d |L0.60| DCD 0x3c6ef35f AREA ||.data||, DATA, ALIGN=2 rand_state DCD 0x00000000 It’s not possible to embed 32-bit constants into ARM instructions, so Keil has to place them externally and load them additionally. One interesting thing is that it’s not possible to embed the 0x7FFF constant as well. So what Keil does is shifting rand_state left by 17 bits and then shifting it right by 17 bits. This is analogous to the (rand_state ≪ 17) ≫ 17 state- ment in C/C++. It seems to be useless operation, but what it does is clearing the high 17 bits, leaving the low 15 bits intact, and that’s our goal after all. Optimizing Keil for Thumb mode generates mostly the same code. 20.4 MIPS Listing 20.5: Optimizing GCC 4.4.5 (IDA) my_srand: ; store $a0 to rand_state: lui $v0, (rand_state >> 16) jr $ra sw $a0, rand_state my_rand: ; load rand_state to $v0: lui $v1, (rand_state >> 16) 346
  • 371. CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.4. MIPS lw $v0, rand_state or $at, $zero ; load delay slot ; multiplicate rand_state in $v0 by 1664525 (RNG_a): sll $a1, $v0, 2 sll $a0, $v0, 4 addu $a0, $a1, $a0 sll $a1, $a0, 6 subu $a0, $a1, $a0 addu $a0, $v0 sll $a1, $a0, 5 addu $a0, $a1 sll $a0, 3 addu $v0, $a0, $v0 sll $a0, $v0, 2 addu $v0, $a0 ; add 1013904223 (RNG_c) ; the LI instruction is coalesced by IDA from LUI and ORI li $a0, 0x3C6EF35F addu $v0, $a0 ; store to rand_state: sw $v0, (rand_state & 0xFFFF)($v1) jr $ra andi $v0, 0x7FFF ; branch delay slot Wow, here we see only one constant (0x3C6EF35F or 1013904223). Where is the other one (1664525)? It seems that multiplication by 1664525 is done by just using shifts and additions! Let’s check this assumption: #define RNG_a 1664525 int f (int a) { return a*RNG_a; } Listing 20.6: Optimizing GCC 4.4.5 (IDA) f: sll $v1, $a0, 2 sll $v0, $a0, 4 addu $v0, $v1, $v0 sll $v1, $v0, 6 subu $v0, $v1, $v0 addu $v0, $a0 sll $v1, $v0, 5 addu $v0, $v1 sll $v0, 3 addu $a0, $v0, $a0 sll $v0, $a0, 2 jr $ra addu $v0, $a0, $v0 ; branch delay slot Indeed! 20.4.1 MIPS relocations I want also to focus on how such operations as load from memory and store to memory actually work. The listings here are produced by IDA, which hides some details. I’ll run objdump twice to get a disassembled listing and also relocations list: Listing 20.7: Optimizing GCC 4.4.5 (objdump) # objdump -D rand_O3.o ... 00000000 <my_srand>: 0: 3c020000 lui v0,0x0 4: 03e00008 jr ra 8: ac440000 sw a0,0(v0) 0000000c <my_rand>: 347
  • 372. CHAPTER 20. LINEAR CONGRUENTIAL GENERATOR AS PSEUDORANDOM NUMBER GENERATOR 20.5. THREAD-SAFE VERSION OF THE EXAMPLE c: 3c030000 lui v1,0x0 10: 8c620000 lw v0,0(v1) 14: 00200825 move at,at 18: 00022880 sll a1,v0,0x2 1c: 00022100 sll a0,v0,0x4 20: 00a42021 addu a0,a1,a0 24: 00042980 sll a1,a0,0x6 28: 00a42023 subu a0,a1,a0 2c: 00822021 addu a0,a0,v0 30: 00042940 sll a1,a0,0x5 34: 00852021 addu a0,a0,a1 38: 000420c0 sll a0,a0,0x3 3c: 00821021 addu v0,a0,v0 40: 00022080 sll a0,v0,0x2 44: 00441021 addu v0,v0,a0 48: 3c043c6e lui a0,0x3c6e 4c: 3484f35f ori a0,a0,0xf35f 50: 00441021 addu v0,v0,a0 54: ac620000 sw v0,0(v1) 58: 03e00008 jr ra 5c: 30427fff andi v0,v0,0x7fff ... # objdump -r rand_O3.o ... RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE 00000000 R_MIPS_HI16 .bss 00000008 R_MIPS_LO16 .bss 0000000c R_MIPS_HI16 .bss 00000010 R_MIPS_LO16 .bss 00000054 R_MIPS_LO16 .bss ... Let’s consider the two relocations for the my_srand() function. The first one, for address 0 has a type of R_MIPS_HI16 and the second one for address 8 has a type of R_MIPS_LO16. That implies that address of the beginning of the .bss segment is to be written into the instructions at address of 0 (high part of address) and 8 (low part of address). The rand_state variable is at the very start of the .bss segment. So we see zeroes in the operands of instructions LUI and SW, because nothing is there yet — the compiler don’t know what to write there. The linker will fix this, and the high part of the address will be written into the operand of LUI and the low part of the address — to the operand of SW. SW will sum up the low part of the address and what is in register $V0 (the high part is there). It’s the same story with the my_rand() function: R_MIPS_HI16 relocation instructs the linker to write the high part of the .bss segment address into instruction LUI. So the high part of the rand_state variable address is residing in register $V1. The LW instruction at address 0x10 sums up the high and low parts and loads the value of the rand_state variable into $V1. The SW instruction at address 0x54 do the summing again and then stores the new value to the rand_state global variable. IDA processes relocations while loading, thus hiding these details, but we ought to remember them. 20.5 Thread-safe version of the example The thread-safe version of the example is to be demonstrated later: 65.1 on page 671. 348
  • 373. CHAPTER 21. STRUCTURES Chapter 21 Structures A C/C++ structure, with some assumptions, is just a set of variables, always stored in memory together, not necessary of the same type 1 . 21.1 MSVC: SYSTEMTIME example Let’s take the SYSTEMTIME2 win32 structure that describes time. This is how it’s defined: Listing 21.1: WinBase.h typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME; Let’s write a C function to get the current time: #include <windows.h> #include <stdio.h> void main() { SYSTEMTIME t; GetSystemTime (&t); printf ("%04d-%02d-%02d %02d:%02d:%02dn", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); return; }; We get (MSVC 2010): Listing 21.2: MSVC 2010 /GS- _t$ = -16 ; size = 16 _main PROC push ebp mov ebp, esp sub esp, 16 lea eax, DWORD PTR _t$[ebp] push eax call DWORD PTR __imp__GetSystemTime@4 movzx ecx, WORD PTR _t$[ebp+12] ; wSecond push ecx 1AKA “heterogeneous container” 2MSDN: SYSTEMTIME structure 349
  • 374. CHAPTER 21. STRUCTURES 21.1. MSVC: SYSTEMTIME EXAMPLE movzx edx, WORD PTR _t$[ebp+10] ; wMinute push edx movzx eax, WORD PTR _t$[ebp+8] ; wHour push eax movzx ecx, WORD PTR _t$[ebp+6] ; wDay push ecx movzx edx, WORD PTR _t$[ebp+2] ; wMonth push edx movzx eax, WORD PTR _t$[ebp] ; wYear push eax push OFFSET $SG78811 ; '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H call _printf add esp, 28 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 16 bytes are allocated for this structure in the local stack —that is exactly sizeof(WORD)*8 (there are 8 WORD variables in the structure). Pay attention to the fact that the structure begins with the wYear field. It can be said that a pointer to the SYSTEMTIME structure is passed to the GetSystemTime()3 , but it is also can be said that a pointer to the wYear field is passed, and that is the same! GetSystemTime() writes the current year to the WORD pointer pointing to, then shifts 2 bytes ahead, writes current month, etc, etc. 3MSDN: SYSTEMTIME structure 350
  • 375. CHAPTER 21. STRUCTURES 21.1. MSVC: SYSTEMTIME EXAMPLE 21.1.1 OllyDbg Let’s compile this example in MSVC 2010 with /GS- /MD keys and run it in OllyDbg. Let’s open windows for data and stack at the address which is passed as the first argument of the GetSystemTime() function, and let’s wait until it’s executed. We see this: Figure 21.1: OllyDbg: GetSystemTime() just executed The system time of the function execution on my computer is 9 december 2014, 22:29:52: Figure 21.2: OllyDbg: printf() output So we see these 16 bytes in the data window: DE 07 0C 00 02 00 09 00 16 00 1D 00 34 00 D4 03 Each two bytes represent one field of the structure. Since the endianness is little endian, we see the low byte first and then the high one. Hence, these are the values currently stored in memory: Hexadecimal number decimal number field name 0x07DE 2014 wYear 0x000C 12 wMonth 0x0002 2 wDayOfWeek 0x0009 9 wDay 0x0016 22 wHour 0x001D 29 wMinute 0x0034 52 wSecond 0x03D4 980 wMilliseconds The same values are seen in the stack window, but they are grouped as 32-bit values. And then printf() just takes the values it needs and outputs them to the console. Some values aren’t output by printf() (wDayOfWeek and wMilliseconds), but they are in memory right now, available for use. 21.1.2 Replacing the structure with array The fact that the structure fields are just variables located side-by-side, I can demonstrate by doing the following. Keeping in mind the SYSTEMTIME structure description, I can rewrite this simple example like this: #include <windows.h> #include <stdio.h> 351
  • 376. CHAPTER 21. STRUCTURES 21.2. LET’S ALLOCATE SPACE FOR A STRUCTURE USING MALLOC() void main() { WORD array[8]; GetSystemTime (array); printf ("%04d-%02d-%02d %02d:%02d:%02dn", array[0] /* wYear */, array[1] /* wMonth */, array[3] /* wDay */, array[4] /* wHour */, array[5] /* wMinute */, array[6] /* wSecond */); return; }; The compiler grumbles a bit: systemtime2.c(7) : warning C4133: 'function' : incompatible types - from 'WORD [8]' to '⤦ LPSYSTEMTIME' But nevertheless, it produces this code: Listing 21.3: Non-optimizing MSVC 2010 $SG78573 DB '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H _array$ = -16 ; size = 16 _main PROC push ebp mov ebp, esp sub esp, 16 lea eax, DWORD PTR _array$[ebp] push eax call DWORD PTR __imp__GetSystemTime@4 movzx ecx, WORD PTR _array$[ebp+12] ; wSecond push ecx movzx edx, WORD PTR _array$[ebp+10] ; wMinute push edx movzx eax, WORD PTR _array$[ebp+8] ; wHoure push eax movzx ecx, WORD PTR _array$[ebp+6] ; wDay push ecx movzx edx, WORD PTR _array$[ebp+2] ; wMonth push edx movzx eax, WORD PTR _array$[ebp] ; wYear push eax push OFFSET $SG78573 call _printf add esp, 28 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP And it works just as the same! It is very interesting that the result in assembly form cannot be distinguished from the result of the previous compilation. So by looking at this code, one cannot say for sure if there was a structure declared, or an array. Nevertheless, no sane person would do it, as it is not convenient. Also the structure fields may be changed by developers, swapped, etc. I’m not adding OllyDbg example here, because it is just the same as in the case with the structure. 21.2 Let’s allocate space for a structure using malloc() Sometimes it is simpler to place structures not the in local stack, but in the heap: #include <windows.h> #include <stdio.h> void main() { SYSTEMTIME *t; 352
  • 377. CHAPTER 21. STRUCTURES 21.2. LET’S ALLOCATE SPACE FOR A STRUCTURE USING MALLOC() t=(SYSTEMTIME *)malloc (sizeof (SYSTEMTIME)); GetSystemTime (t); printf ("%04d-%02d-%02d %02d:%02d:%02dn", t->wYear, t->wMonth, t->wDay, t->wHour, t->wMinute, t->wSecond); free (t); return; }; Let’s compile it now with optimization (/Ox) so it would be easy see what we need. Listing 21.4: Optimizing MSVC _main PROC push esi push 16 call _malloc add esp, 4 mov esi, eax push esi call DWORD PTR __imp__GetSystemTime@4 movzx eax, WORD PTR [esi+12] ; wSecond movzx ecx, WORD PTR [esi+10] ; wMinute movzx edx, WORD PTR [esi+8] ; wHour push eax movzx eax, WORD PTR [esi+6] ; wDay push ecx movzx ecx, WORD PTR [esi+2] ; wMonth push edx movzx edx, WORD PTR [esi] ; wYear push eax push ecx push edx push OFFSET $SG78833 call _printf push esi call _free add esp, 32 xor eax, eax pop esi ret 0 _main ENDP So, sizeof(SYSTEMTIME) = 16 and that is exact number of bytes to be allocated by malloc(). It returns a pointer to a freshly allocated memory block in the EAX register, which is then moved into the ESI register. GetSystemTime() win32 function takes care of saving value in ESI, and that is why it is not saved here and continues to be used after the GetSystemTime() call. New instruction —MOVZX (Move with Zero eXtend). It may be used in most cases as MOVSX, but it sets the remaining bits to 0. That’s because printf() requires a 32-bit int, but we got a WORD in the structure —that is 16-bit unsigned type. That’s why by copying the value from a WORD into int, bits from 16 to 31 must be cleared, because a random noise may be there, which is left from the previous operations on the register(s). In this example, I again can represent the structure as an array of 8 WORDs: #include <windows.h> #include <stdio.h> void main() { WORD *t; t=(WORD *)malloc (16); GetSystemTime (t); printf ("%04d-%02d-%02d %02d:%02d:%02dn", t[0] /* wYear */, t[1] /* wMonth */, t[3] /* wDay */, 353
  • 378. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM t[4] /* wHour */, t[5] /* wMinute */, t[6] /* wSecond */); free (t); return; }; We get: Listing 21.5: Optimizing MSVC $SG78594 DB '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H _main PROC push esi push 16 call _malloc add esp, 4 mov esi, eax push esi call DWORD PTR __imp__GetSystemTime@4 movzx eax, WORD PTR [esi+12] movzx ecx, WORD PTR [esi+10] movzx edx, WORD PTR [esi+8] push eax movzx eax, WORD PTR [esi+6] push ecx movzx ecx, WORD PTR [esi+2] push edx movzx edx, WORD PTR [esi] push eax push ecx push edx push OFFSET $SG78594 call _printf push esi call _free add esp, 32 xor eax, eax pop esi ret 0 _main ENDP Again, we got the code cannot be distinguished from the previous one. And again I have to note, you haven’t to do this in practice, unless you really know what you are doing. 21.3 UNIX: struct tm 21.3.1 Linux Let’s take the tm structure from time.h in Linux for example: #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; unix_time=time(NULL); localtime_r (&unix_time, &t); printf ("Year: %dn", t.tm_year+1900); printf ("Month: %dn", t.tm_mon); printf ("Day: %dn", t.tm_mday); printf ("Hour: %dn", t.tm_hour); printf ("Minutes: %dn", t.tm_min); printf ("Seconds: %dn", t.tm_sec); 354
  • 379. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM }; Let’s compile it in GCC 4.4.1: Listing 21.6: GCC 4.4.1 main proc near push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; first argument for time() call time mov [esp+3Ch], eax lea eax, [esp+3Ch] ; take pointer to what time() returned lea edx, [esp+10h] ; at ESP+10h struct tm will begin mov [esp+4], edx ; pass pointer to the structure begin mov [esp], eax ; pass pointer to result of time() call localtime_r mov eax, [esp+24h] ; tm_year lea edx, [eax+76Ch] ; edx=eax+1900 mov eax, offset format ; "Year: %dn" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+20h] ; tm_mon mov eax, offset aMonthD ; "Month: %dn" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+1Ch] ; tm_mday mov eax, offset aDayD ; "Day: %dn" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+18h] ; tm_hour mov eax, offset aHourD ; "Hour: %dn" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+14h] ; tm_min mov eax, offset aMinutesD ; "Minutes: %dn" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+10h] mov eax, offset aSecondsD ; "Seconds: %dn" mov [esp+4], edx ; tm_sec mov [esp], eax call printf leave retn main endp Somehow, IDA did not write the local variables’ names in the local stack. But since we already are experienced reverse engineers :-) we may do it without this information in this simple example. Please also pay attention to the lea edx, [eax+76Ch] —this instruction just adds 0x76C (1900) to value in EAX, but doesn’t modify any flags. See also the relevant section about LEA ( A.6.2 on page 933). GDB Let’s try to load the example into GDB 4 : Listing 21.7: GDB dennis@ubuntuvm:~/polygon$ date Mon Jun 2 18:10:37 EEST 2014 dennis@ubuntuvm:~/polygon$ gcc GCC_tm.c -o GCC_tm dennis@ubuntuvm:~/polygon$ gdb GCC_tm 4I corrected the date result slightly for demonstration purposes. Of course, I wasn’t able to run GDB that quickly, in the same second. 355
  • 380. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/GCC_tm...(no debugging symbols found)...done. (gdb) b printf Breakpoint 1 at 0x8048330 (gdb) run Starting program: /home/dennis/polygon/GCC_tm Breakpoint 1, __printf (format=0x80485c0 "Year: %dn") at printf.c:29 29 printf.c: No such file or directory. (gdb) x/20x $esp 0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000 0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 0x0000000a 0xbffff0fc: 0x00000012 0x00000002 0x00000005 0x00000072 0xbffff10c: 0x00000001 0x00000098 0x00000001 0x00002a30 0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000 (gdb) We can easily find our structure in the stack. First, let’s see how it’s defined in time.h: Listing 21.8: time.h struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; Pay attention that 32-bit int is used here instead of WORD in SYSTEMTIME. So, each field occupies 32-bit. Here are the fields of our structure in the stack: 0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000 0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 sec 0x0000000a min 0xbffff0fc: 0x00000012 hour 0x00000002 mday 0x00000005 mon 0x00000072 year 0xbffff10c: 0x00000001 wday 0x00000098 yday 0x00000001 isdst0x00002a30 0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000 Or as a table: Hexadecimal number decimal number field name 0x00000025 37 tm_sec 0x0000000a 10 tm_min 0x00000012 18 tm_hour 0x00000002 2 tm_mday 0x00000005 5 tm_mon 0x00000072 114 tm_year 0x00000001 1 tm_wday 0x00000098 152 tm_yday 0x00000001 1 tm_isdst Just like SYSTEMTIME ( 21.1 on page 349), there are also other fields available that are not used, like tm_wday, tm_yday, tm_isdst. 21.3.2 ARM Optimizing Keil 6/2013 (thumb mode) Same example: 356
  • 381. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM Listing 21.9: Optimizing Keil 6/2013 (thumb mode) var_38 = -0x38 var_34 = -0x34 var_30 = -0x30 var_2C = -0x2C var_28 = -0x28 var_24 = -0x24 timer = -0xC PUSH {LR} MOVS R0, #0 ; timer SUB SP, SP, #0x34 BL time STR R0, [SP,#0x38+timer] MOV R1, SP ; tp ADD R0, SP, #0x38+timer ; timer BL localtime_r LDR R1, =0x76C LDR R0, [SP,#0x38+var_24] ADDS R1, R0, R1 ADR R0, aYearD ; "Year: %dn" BL __2printf LDR R1, [SP,#0x38+var_28] ADR R0, aMonthD ; "Month: %dn" BL __2printf LDR R1, [SP,#0x38+var_2C] ADR R0, aDayD ; "Day: %dn" BL __2printf LDR R1, [SP,#0x38+var_30] ADR R0, aHourD ; "Hour: %dn" BL __2printf LDR R1, [SP,#0x38+var_34] ADR R0, aMinutesD ; "Minutes: %dn" BL __2printf LDR R1, [SP,#0x38+var_38] ADR R0, aSecondsD ; "Seconds: %dn" BL __2printf ADD SP, SP, #0x34 POP {PC} Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) IDA “knows” the tm structure (because IDA “knows” the types of the arguments of library functions like localtime_r()), so it shows here structure elements accesses and their names. Listing 21.10: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) var_38 = -0x38 var_34 = -0x34 PUSH {R7,LR} MOV R7, SP SUB SP, SP, #0x30 MOVS R0, #0 ; time_t * BLX _time ADD R1, SP, #0x38+var_34 ; struct tm * STR R0, [SP,#0x38+var_38] MOV R0, SP ; time_t * BLX _localtime_r LDR R1, [SP,#0x38+var_34.tm_year] MOV R0, 0xF44 ; "Year: %dn" ADD R0, PC ; char * ADDW R1, R1, #0x76C BLX _printf LDR R1, [SP,#0x38+var_34.tm_mon] MOV R0, 0xF3A ; "Month: %dn" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34.tm_mday] 357
  • 382. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM MOV R0, 0xF35 ; "Day: %dn" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34.tm_hour] MOV R0, 0xF2E ; "Hour: %dn" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34.tm_min] MOV R0, 0xF28 ; "Minutes: %dn" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34] MOV R0, 0xF25 ; "Seconds: %dn" ADD R0, PC ; char * BLX _printf ADD SP, SP, #0x30 POP {R7,PC} ... 00000000 tm struc ; (sizeof=0x2C, standard type) 00000000 tm_sec DCD ? 00000004 tm_min DCD ? 00000008 tm_hour DCD ? 0000000C tm_mday DCD ? 00000010 tm_mon DCD ? 00000014 tm_year DCD ? 00000018 tm_wday DCD ? 0000001C tm_yday DCD ? 00000020 tm_isdst DCD ? 00000024 tm_gmtoff DCD ? 00000028 tm_zone DCD ? ; offset 0000002C tm ends 21.3.3 MIPS Listing 21.11: Optimizing GCC 4.4.5 (IDA) 1 main: 2 3 ; IDA is not aware of structure field names, I named them manually: 4 5 var_40 = -0x40 6 var_38 = -0x38 7 seconds = -0x34 8 minutes = -0x30 9 hour = -0x2C 10 day = -0x28 11 month = -0x24 12 year = -0x20 13 var_4 = -4 14 15 lui $gp, (__gnu_local_gp >> 16) 16 addiu $sp, -0x50 17 la $gp, (__gnu_local_gp & 0xFFFF) 18 sw $ra, 0x50+var_4($sp) 19 sw $gp, 0x50+var_40($sp) 20 lw $t9, (time & 0xFFFF)($gp) 21 or $at, $zero ; load delay slot, NOP 22 jalr $t9 23 move $a0, $zero ; branch delay slot, NOP 24 lw $gp, 0x50+var_40($sp) 25 addiu $a0, $sp, 0x50+var_38 26 lw $t9, (localtime_r & 0xFFFF)($gp) 27 addiu $a1, $sp, 0x50+seconds 28 jalr $t9 29 sw $v0, 0x50+var_38($sp) ; branch delay slot 30 lw $gp, 0x50+var_40($sp) 31 lw $a1, 0x50+year($sp) 358
  • 383. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM 32 lw $t9, (printf & 0xFFFF)($gp) 33 la $a0, $LC0 # "Year: %dn" 34 jalr $t9 35 addiu $a1, 1900 ; branch delay slot 36 lw $gp, 0x50+var_40($sp) 37 lw $a1, 0x50+month($sp) 38 lw $t9, (printf & 0xFFFF)($gp) 39 lui $a0, ($LC1 >> 16) # "Month: %dn" 40 jalr $t9 41 la $a0, ($LC1 & 0xFFFF) # "Month: %dn" ; branch delay slot 42 lw $gp, 0x50+var_40($sp) 43 lw $a1, 0x50+day($sp) 44 lw $t9, (printf & 0xFFFF)($gp) 45 lui $a0, ($LC2 >> 16) # "Day: %dn" 46 jalr $t9 47 la $a0, ($LC2 & 0xFFFF) # "Day: %dn" ; branch delay slot 48 lw $gp, 0x50+var_40($sp) 49 lw $a1, 0x50+hour($sp) 50 lw $t9, (printf & 0xFFFF)($gp) 51 lui $a0, ($LC3 >> 16) # "Hour: %dn" 52 jalr $t9 53 la $a0, ($LC3 & 0xFFFF) # "Hour: %dn" ; branch delay slot 54 lw $gp, 0x50+var_40($sp) 55 lw $a1, 0x50+minutes($sp) 56 lw $t9, (printf & 0xFFFF)($gp) 57 lui $a0, ($LC4 >> 16) # "Minutes: %dn" 58 jalr $t9 59 la $a0, ($LC4 & 0xFFFF) # "Minutes: %dn" ; branch delay slot 60 lw $gp, 0x50+var_40($sp) 61 lw $a1, 0x50+seconds($sp) 62 lw $t9, (printf & 0xFFFF)($gp) 63 lui $a0, ($LC5 >> 16) # "Seconds: %dn" 64 jalr $t9 65 la $a0, ($LC5 & 0xFFFF) # "Seconds: %dn" ; branch delay slot 66 lw $ra, 0x50+var_4($sp) 67 or $at, $zero ; load delay slot, NOP 68 jr $ra 69 addiu $sp, 0x50 70 71 $LC0: .ascii "Year: %dn"<0> 72 $LC1: .ascii "Month: %dn"<0> 73 $LC2: .ascii "Day: %dn"<0> 74 $LC3: .ascii "Hour: %dn"<0> 75 $LC4: .ascii "Minutes: %dn"<0> 76 $LC5: .ascii "Seconds: %dn"<0> This is an example where the branch delay slots can confuse us. For example, there is the instruction “addiu $a1, 1900” at line 35 which adds 1900 to the year number. It’s executed before the corresponding JALR at line 34, do not forget about it. 21.3.4 Structure as a set of values In order to illustrate that the structure is just variables laying side-by-side in one place, let’s rework our example while looking at the tm structure definition again: listing.21.8. #include <stdio.h> #include <time.h> void main() { int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, tm_yday, tm_isdst; time_t unix_time; unix_time=time(NULL); localtime_r (&unix_time, &tm_sec); printf ("Year: %dn", tm_year+1900); printf ("Month: %dn", tm_mon); printf ("Day: %dn", tm_mday); 359
  • 384. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM printf ("Hour: %dn", tm_hour); printf ("Minutes: %dn", tm_min); printf ("Seconds: %dn", tm_sec); }; N.B. The pointer to the tm_sec field is passed into localtime_r, i.e., to the first element of the “structure”. The compiler warns us: Listing 21.12: GCC 4.7.3 GCC_tm2.c: In function 'main': GCC_tm2.c:11:5: warning: passing argument 2 of 'localtime_r' from incompatible pointer type [⤦ enabled by default] In file included from GCC_tm2.c:2:0: /usr/include/time.h:59:12: note: expected 'struct tm *' but argument is of type 'int *' But nevertheless, it generates this: Listing 21.13: GCC 4.7.3 main proc near var_30 = dword ptr -30h var_2C = dword ptr -2Ch unix_time = dword ptr -1Ch tm_sec = dword ptr -18h tm_min = dword ptr -14h tm_hour = dword ptr -10h tm_mday = dword ptr -0Ch tm_mon = dword ptr -8 tm_year = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 30h call __main mov [esp+30h+var_30], 0 ; arg 0 call time mov [esp+30h+unix_time], eax lea eax, [esp+30h+tm_sec] mov [esp+30h+var_2C], eax lea eax, [esp+30h+unix_time] mov [esp+30h+var_30], eax call localtime_r mov eax, [esp+30h+tm_year] add eax, 1900 mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aYearD ; "Year: %dn" call printf mov eax, [esp+30h+tm_mon] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aMonthD ; "Month: %dn" call printf mov eax, [esp+30h+tm_mday] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aDayD ; "Day: %dn" call printf mov eax, [esp+30h+tm_hour] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aHourD ; "Hour: %dn" call printf mov eax, [esp+30h+tm_min] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aMinutesD ; "Minutes: %dn" call printf mov eax, [esp+30h+tm_sec] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aSecondsD ; "Seconds: %dn" call printf leave retn 360
  • 385. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM main endp This code is identical to what we saw previously and it is not possible to say, was it a structure in original source code or just a pack of variables. And this works. However, it is not recommended to do this in practice. Usually, non-optimizing compilers allocates variables in the local stack in the same order as they were declared in the function. Nevertheless, there is no guarantee. By the way, some other compiler may warn about the tm_year, tm_mon, tm_mday, tm_hour, tm_min variables, but not tm_sec are used without being initialized. Indeed, the compiler is not aware that these are to be filled by localtime_r() function. I chose this example, since all structure fields are of type int. This would not work if structure fields are 16-bit (WORD), like in the case of the SYSTEMTIME structure—GetSystemTime() will fill them incorrectly ( because the local variables are aligned on a 32-bit boundary). Read more about it in next section: “Fields packing in structure” ( 21.4 on the following page). So, a structure is just a pack of variables laying on one place, side-by-side. I could say that the structure is syntactic sugar, directing the compiler to hold them in one place. However, I’m not an expert on programming languages, so most likely I’m wrong with this term. By the way, in some very early C versions (before 1972), there were no structures at all [Rit93]. I’m not adding a debugger example here: it is just the same as you already saw. 21.3.5 Structure as an array of 32-bit words #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; int i; unix_time=time(NULL); localtime_r (&unix_time, &t); for (i=0; i<9; i++) { int tmp=((int*)&t)[i]; printf ("0x%08X (%d)n", tmp, tmp); }; }; I just cast a pointer to structure to an array of int’s. And that works! I ran the example at 23:51:45 26-July-2014. 0x0000002D (45) 0x00000033 (51) 0x00000017 (23) 0x0000001A (26) 0x00000006 (6) 0x00000072 (114) 0x00000006 (6) 0x000000CE (206) 0x00000001 (1) The variables here are in the same order as they are enumerated in the definition of the structure: 21.8 on page 356. Here is how it gets compiled: Listing 21.14: Optimizing GCC 4.8.1 main proc near push ebp mov ebp, esp push esi push ebx and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; timer lea ebx, [esp+14h] call _time lea esi, [esp+38h] 361
  • 386. CHAPTER 21. STRUCTURES 21.3. UNIX: STRUCT TM mov [esp+4], ebx ; tp mov [esp+10h], eax lea eax, [esp+10h] mov [esp], eax ; timer call _localtime_r nop lea esi, [esi+0] ; NOP loc_80483D8: ; EBX here is pointer to structure, ESI is the pointer to the end of it. mov eax, [ebx] ; get 32-bit word from array add ebx, 4 ; next field in structure mov dword ptr [esp+4], offset a0x08xD ; "0x%08X (%d)n" mov dword ptr [esp], 1 mov [esp+0Ch], eax ; pass value to printf() mov [esp+8], eax ; pass value to printf() call ___printf_chk cmp ebx, esi ; meet structure end? jnz short loc_80483D8 ; no - load next value then lea esp, [ebp-8] pop ebx pop esi pop ebp retn main endp Indeed: the space in the local stack is first treated as a structure, and then it’s treated as an array. It’s even possible to modify the fields of the structure through this pointer. And again, it’s dubiously hackish way to do things, not recommended for use in production code. Exercise As an exercise, try to modify (increase by 1) the current month number, treating the structure as an array. 21.3.6 Structure as an array of bytes I can do even more. Let’s cast the pointer to an array of bytes and dump it: #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; int i, j; unix_time=time(NULL); localtime_r (&unix_time, &t); for (i=0; i<9; i++) { for (j=0; j<4; j++) printf ("0x%02X ", ((unsigned char*)&t)[i*4+j]); printf ("n"); }; }; 0x2D 0x00 0x00 0x00 0x33 0x00 0x00 0x00 0x17 0x00 0x00 0x00 0x1A 0x00 0x00 0x00 0x06 0x00 0x00 0x00 0x72 0x00 0x00 0x00 0x06 0x00 0x00 0x00 0xCE 0x00 0x00 0x00 0x01 0x00 0x00 0x00 362
  • 387. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE I ran this example also at 23:51:45 26-July-2014. The values are just the same as in the previous dump ( 21.3.5 on page 361), and of course, the lowest byte goes first, because this is a little-endian architecture ( 31 on page 453). Listing 21.15: Optimizing GCC 4.8.1 main proc near push ebp mov ebp, esp push edi push esi push ebx and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; timer lea esi, [esp+14h] call _time lea edi, [esp+38h] ; struct end mov [esp+4], esi ; tp mov [esp+10h], eax lea eax, [esp+10h] mov [esp], eax ; timer call _localtime_r lea esi, [esi+0] ; NOP ; ESI here is the pointer to structure in local stack. EDI is the pointer to structure end. loc_8048408: xor ebx, ebx ; j=0 loc_804840A: movzx eax, byte ptr [esi+ebx] ; load byte add ebx, 1 ; j=j+1 mov dword ptr [esp+4], offset a0x02x ; "0x%02X " mov dword ptr [esp], 1 mov [esp+8], eax ; pass loaded byte to printf() call ___printf_chk cmp ebx, 4 jnz short loc_804840A ; print carriage return character (CR) mov dword ptr [esp], 0Ah ; c add esi, 4 call _putchar cmp esi, edi ; meet struct end? jnz short loc_8048408 ; j=0 lea esp, [ebp-0Ch] pop ebx pop esi pop edi pop ebp retn main endp 21.4 Fields packing in structure One important thing is fields packing in structures5 . Let’s take a simple example: #include <stdio.h> struct s { char a; int b; char c; int d; }; void f(struct s s) { 5See also: Wikipedia: Data structure alignment 363
  • 388. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE printf ("a=%d; b=%d; c=%d; d=%dn", s.a, s.b, s.c, s.d); }; int main() { struct s tmp; tmp.a=1; tmp.b=2; tmp.c=3; tmp.d=4; f(tmp); }; As we see, we have two char fields (each is exactly one byte) and two more —int (each - 4 bytes). 21.4.1 x86 This compiles to: Listing 21.16: MSVC 2012 /GS- /Ob0 1 _tmp$ = -16 2 _main PROC 3 push ebp 4 mov ebp, esp 5 sub esp, 16 6 mov BYTE PTR _tmp$[ebp], 1 ; set field a 7 mov DWORD PTR _tmp$[ebp+4], 2 ; set field b 8 mov BYTE PTR _tmp$[ebp+8], 3 ; set field c 9 mov DWORD PTR _tmp$[ebp+12], 4 ; set field d 10 sub esp, 16 ; allocate place for temporary structure 11 mov eax, esp 12 mov ecx, DWORD PTR _tmp$[ebp] ; copy our structure to the temporary one 13 mov DWORD PTR [eax], ecx 14 mov edx, DWORD PTR _tmp$[ebp+4] 15 mov DWORD PTR [eax+4], edx 16 mov ecx, DWORD PTR _tmp$[ebp+8] 17 mov DWORD PTR [eax+8], ecx 18 mov edx, DWORD PTR _tmp$[ebp+12] 19 mov DWORD PTR [eax+12], edx 20 call _f 21 add esp, 16 22 xor eax, eax 23 mov esp, ebp 24 pop ebp 25 ret 0 26 _main ENDP 27 28 _s$ = 8 ; size = 16 29 ?f@@YAXUs@@@Z PROC ; f 30 push ebp 31 mov ebp, esp 32 mov eax, DWORD PTR _s$[ebp+12] 33 push eax 34 movsx ecx, BYTE PTR _s$[ebp+8] 35 push ecx 36 mov edx, DWORD PTR _s$[ebp+4] 37 push edx 38 movsx eax, BYTE PTR _s$[ebp] 39 push eax 40 push OFFSET $SG3842 41 call _printf 42 add esp, 20 43 pop ebp 44 ret 0 45 ?f@@YAXUs@@@Z ENDP ; f 46 _TEXT ENDS We pass the structure as a whole, but in fact, as we can see, the structure is being copied to a temporary one (a place in stack is allocated in line 10 for it, and then all 4 fields, one by one, are copied in lines 12 … 19), and then its pointer (address) 364
  • 389. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE is to be passed. The structure is copied because it’s not know if the f() function going to modify the structure or not. If it gets changed, then the structure in main() has to remain as it was. We could use C/C++ pointers, and the resulting code will be almost the same, but without the copying. As we can see, each field’s address is aligned on a 4-byte boundary. That’s why each char occupies 4 bytes here (like int). Why? Because it is easier for the CPU to access memory at aligned addresses and to cache data from it. However, it is not very economical. Let’s try to compile it with option (/Zp1) (/Zp[n] pack structures on n-byte boundary). Listing 21.17: MSVC 2012 /GS- /Zp1 1 _main PROC 2 push ebp 3 mov ebp, esp 4 sub esp, 12 5 mov BYTE PTR _tmp$[ebp], 1 ; set field a 6 mov DWORD PTR _tmp$[ebp+1], 2 ; set field b 7 mov BYTE PTR _tmp$[ebp+5], 3 ; set field c 8 mov DWORD PTR _tmp$[ebp+6], 4 ; set field d 9 sub esp, 12 ; allocate place for temporary structure 10 mov eax, esp 11 mov ecx, DWORD PTR _tmp$[ebp] ; copy 10 bytes 12 mov DWORD PTR [eax], ecx 13 mov edx, DWORD PTR _tmp$[ebp+4] 14 mov DWORD PTR [eax+4], edx 15 mov cx, WORD PTR _tmp$[ebp+8] 16 mov WORD PTR [eax+8], cx 17 call _f 18 add esp, 12 19 xor eax, eax 20 mov esp, ebp 21 pop ebp 22 ret 0 23 _main ENDP 24 25 _TEXT SEGMENT 26 _s$ = 8 ; size = 10 27 ?f@@YAXUs@@@Z PROC ; f 28 push ebp 29 mov ebp, esp 30 mov eax, DWORD PTR _s$[ebp+6] 31 push eax 32 movsx ecx, BYTE PTR _s$[ebp+5] 33 push ecx 34 mov edx, DWORD PTR _s$[ebp+1] 35 push edx 36 movsx eax, BYTE PTR _s$[ebp] 37 push eax 38 push OFFSET $SG3842 39 call _printf 40 add esp, 20 41 pop ebp 42 ret 0 43 ?f@@YAXUs@@@Z ENDP ; f Now the structure takes only 10 bytes and each char value takes 1 byte. What does it give to us? Size economy. And as drawback —the CPU accessing these fields slower than it could. The structure is also copied in main(). Not field-by-field, but directly 10 bytes, using three pairs of MOV. Why not 4? The compiler decided that it’s better to copy 10 bytes using 3 MOV pairs than to copy two 32-bit words and two bytes using 4 MOV pairs. By the way, such copy implementation using MOV instead of calling the memcpy() function is widely used, because it’s faster than a call to memcpy()—for short blocks, of course: 43.1.5 on page 504. As it can be easily guessed, if the structure is used in many source and object files, all these must be compiled with the same convention about structures packing. Aside from MSVC /Zp option which sets how to align each structure field, there is also the #pragma pack compiler option, which can be defined right in the source code. It is available in both MSVC6 and GCC7 . Let’s get back to the SYSTEMTIME structure that consists of 16-bit fields. How does our compiler know to pack them on 1-byte alignment boundary? WinNT.h file has this: 6MSDN: Working with Packing Structures 7Structure-Packing Pragmas 365
  • 390. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE Listing 21.18: WinNT.h #include "pshpack1.h" And this: Listing 21.19: WinNT.h #include "pshpack4.h" // 4 byte packing is the default The file PshPack1.h looks like: Listing 21.20: PshPack1.h #if ! (defined(lint) || defined(RC_INVOKED)) #if ( _MSC_VER >= 800 && !defined(_M_I86)) || defined(_PUSHPOP_SUPPORTED) #pragma warning(disable:4103) #if !(defined( MIDL_PASS )) || defined( __midl ) #pragma pack(push,1) #else #pragma pack(1) #endif #else #pragma pack(1) #endif #endif /* ! (defined(lint) || defined(RC_INVOKED)) */ This tell the compiler how to pack the structures defined after #pragma pack. 366
  • 391. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE OllyDbg + fields are packed by default Let’s try our example (where the fields are aligned by default (4 bytes)) in OllyDbg: Figure 21.3: OllyDbg: Before printf() execution We see our 4 fields in the data window. But where do the random bytes (0x30, 0x37, 0x01) come from, that are next to the first (a) and third (c) fields? By looking at our listing 21.16 on page 364, we can see that the first and third fields are char, therefore only one byte is written, 1 and 3 respectively (lines 6 and 8). The remaining 3 bytes of the 32-bit words are not being modified in memory! Hence, random garbage is left there. This garbage doesn’t influence the printf() output in any way, because the values for it are prepared using the MOVSX instruction, which takes bytes, but not words: listing.21.16 (lines 34 and 38). By the way, the MOVSX (sign-extending) instruction is used here, because char is signed by default in MSVC and GCC. If the type unsigned char or uint8_t was used here, MOVZX instruction would have been used instead. 367
  • 392. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE OllyDbg + fields aligning on 1 byte boundary Things are much clearer here: 4 fields occupy 10 bytes and the values are stored side-by-side Figure 21.4: OllyDbg: Before printf() execution 21.4.2 ARM Optimizing Keil 6/2013 (thumb mode) Listing 21.21: Optimizing Keil 6/2013 (thumb mode) .text:0000003E exit ; CODE XREF: f+16 .text:0000003E 05 B0 ADD SP, SP, #0x14 .text:00000040 00 BD POP {PC} .text:00000280 f .text:00000280 .text:00000280 var_18 = -0x18 .text:00000280 a = -0x14 .text:00000280 b = -0x10 .text:00000280 c = -0xC .text:00000280 d = -8 .text:00000280 .text:00000280 0F B5 PUSH {R0-R3,LR} .text:00000282 81 B0 SUB SP, SP, #4 .text:00000284 04 98 LDR R0, [SP,#16] ; d .text:00000286 02 9A LDR R2, [SP,#8] ; b .text:00000288 00 90 STR R0, [SP] .text:0000028A 68 46 MOV R0, SP .text:0000028C 03 7B LDRB R3, [R0,#12] ; c .text:0000028E 01 79 LDRB R1, [R0,#4] ; a .text:00000290 59 A0 ADR R0, aADBDCDDD ; "a=%d; b=%d; c=%d; d=%dn" .text:00000292 05 F0 AD FF BL __2printf .text:00000296 D2 E6 B exit As we may recall, here a structure is passed instead of pointer to one, and since the first 4 function arguments in ARM are passed via registers, the structure’s fields are passed via R0-R3. LDRB loads one byte from memory and extends it to 32-bit, taking its sign into account. This is similar to MOVSX in x86. Here it is used to load fields a and c from the structure. One more thing we spot easily is that instead of function epilogue, there is jump to another function’s epilogue! Indeed, that was quite different function, not related in any way to ours, however, it has exactly the same epilogue (probably because, it hold 5 local variables too (5∗4 = 0x14)). Also it is located nearby (take a look at the addresses). Indeed, it doesn’t matter which epilogue gets executed, if it works just as we need. Apparently, Keil decides to reuse a part of another function to economize. The epilogue takes 4 bytes while jump —only 2. 368
  • 393. CHAPTER 21. STRUCTURES 21.4. FIELDS PACKING IN STRUCTURE ARM + Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) Listing 21.22: Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) var_C = -0xC PUSH {R7,LR} MOV R7, SP SUB SP, SP, #4 MOV R9, R1 ; b MOV R1, R0 ; a MOVW R0, #0xF10 ; "a=%d; b=%d; c=%d; d=%dn" SXTB R1, R1 ; prepare a MOVT.W R0, #0 STR R3, [SP,#0xC+var_C] ; place d to stack for printf() ADD R0, PC ; format-string SXTB R3, R2 ; prepare c MOV R2, R9 ; b BLX _printf ADD SP, SP, #4 POP {R7,PC} SXTB (Signed Extend Byte) is analogous to MOVSX in x86. All the rest —just the same. 21.4.3 MIPS Listing 21.23: Optimizing GCC 4.4.5 (IDA) 1 f: 2 3 var_18 = -0x18 4 var_10 = -0x10 5 var_4 = -4 6 arg_0 = 0 7 arg_4 = 4 8 arg_8 = 8 9 arg_C = 0xC 10 11 ; $a0=s.a 12 ; $a1=s.b 13 ; $a2=s.c 14 ; $a3=s.d 15 lui $gp, (__gnu_local_gp >> 16) 16 addiu $sp, -0x28 17 la $gp, (__gnu_local_gp & 0xFFFF) 18 sw $ra, 0x28+var_4($sp) 19 sw $gp, 0x28+var_10($sp) 20 ; prepare byte from 32-bit big-endian integer: 21 sra $t0, $a0, 24 22 move $v1, $a1 23 ; prepare byte from 32-bit big-endian integer: 24 sra $v0, $a2, 24 25 lw $t9, (printf & 0xFFFF)($gp) 26 sw $a0, 0x28+arg_0($sp) 27 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%dn" 28 sw $a3, 0x28+var_18($sp) 29 sw $a1, 0x28+arg_4($sp) 30 sw $a2, 0x28+arg_8($sp) 31 sw $a3, 0x28+arg_C($sp) 32 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%dn" 33 move $a1, $t0 34 move $a2, $v1 35 jalr $t9 36 move $a3, $v0 ; branch delay slot 37 lw $ra, 0x28+var_4($sp) 38 or $at, $zero ; load delay slot, NOP 39 jr $ra 40 addiu $sp, 0x28 ; branch delay slot 41 42 $LC0: .ascii "a=%d; b=%d; c=%d; d=%dn"<0> 369
  • 394. CHAPTER 21. STRUCTURES 21.5. NESTED STRUCTURES Structure fields come in registers $A0..$A3 and then get reshuffled into $A1..$A4 for printf(). But there are two SRA (“Shift Word Right Arithmetic”) instructions, which prepare char fields. Why? MIPS is a big-endian architecture by default 31 on page 453, and the Debian Linux I work in is big-endian too. So when byte variables are stored in 32-bit structure slots, they occupy the high 31..24 bits. And when a char variable needs to be extended into a 32-bit value, it must be shifted right by 24 bits. char is a signed type, so an arithmetical shift is used here instead of logical. 21.4.4 One more word Passing a structure as a function argument (instead of a passing pointer to structure) is the same as passing all structure fields one by one. If the structure fields are packed by default, the f() function can be rewritten as: void f(char a, int b, char c, int d) { printf ("a=%d; b=%d; c=%d; d=%dn", a, b, c, d); }; And that leads to the same code. 21.5 Nested structures Now what about situations when one structure is defined inside of another? #include <stdio.h> struct inner_struct { int a; int b; }; struct outer_struct { char a; int b; struct inner_struct c; char d; int e; }; void f(struct outer_struct s) { printf ("a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%dn", s.a, s.b, s.c.a, s.c.b, s.d, s.e); }; int main() { struct outer_struct s; s.a=1; s.b=2; s.c.a=100; s.c.b=101; s.d=3; s.e=4; f(s); }; … in this case, both inner_struct fields are to be placed between the a,b and d,e fields of the outer_struct. Let’s compile (MSVC 2010): Listing 21.24: Optimizing MSVC 2010 /Ob0 $SG2802 DB 'a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d', 0aH, 00H _TEXT SEGMENT _s$ = 8 _f PROC mov eax, DWORD PTR _s$[esp+16] movsx ecx, BYTE PTR _s$[esp+12] 370
  • 395. CHAPTER 21. STRUCTURES 21.5. NESTED STRUCTURES mov edx, DWORD PTR _s$[esp+8] push eax mov eax, DWORD PTR _s$[esp+8] push ecx mov ecx, DWORD PTR _s$[esp+8] push edx movsx edx, BYTE PTR _s$[esp+8] push eax push ecx push edx push OFFSET $SG2802 ; 'a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d' call _printf add esp, 28 ret 0 _f ENDP _s$ = -24 _main PROC sub esp, 24 push ebx push esi push edi mov ecx, 2 sub esp, 24 mov eax, esp mov BYTE PTR _s$[esp+60], 1 mov ebx, DWORD PTR _s$[esp+60] mov DWORD PTR [eax], ebx mov DWORD PTR [eax+4], ecx lea edx, DWORD PTR [ecx+98] lea esi, DWORD PTR [ecx+99] lea edi, DWORD PTR [ecx+2] mov DWORD PTR [eax+8], edx mov BYTE PTR _s$[esp+76], 3 mov ecx, DWORD PTR _s$[esp+76] mov DWORD PTR [eax+12], esi mov DWORD PTR [eax+16], ecx mov DWORD PTR [eax+20], edi call _f add esp, 24 pop edi pop esi xor eax, eax pop ebx add esp, 24 ret 0 _main ENDP One curious thing here is that by looking onto this assembly code, we do not even see that another structure was used inside of it! Thus, we would say, nested structures are unfolded into linear or one-dimensional structure. Of course, if we replace the struct inner_struct c; declaration with struct inner_struct *c; (thus making a pointer here) the situation will be quite different. 371
  • 396. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE 21.5.1 OllyDbg Let’s load the example into OllyDbg and take a look at outer_struct in memory: Figure 21.5: OllyDbg: Before printf() execution That’s how the values are located in memory: • (outer_struct.a) byte 1 + 3 bytes of random garbage; • (outer_struct.b) 32-bit word 2; • (inner_struct.a) 32-bit word 0x64 (100); • (inner_struct.b) 32-bit word 0x65 (101); • (outer_struct.d) byte 3 + 3 bytes of random garbage; • (outer_struct.e) 32-bit word 4. 21.6 Bit fields in a structure 21.6.1 CPUID example The C/C++ language allows to define the exact number of bits for each structure field. It is very useful if one needs to save memory space. For example, one bit is enough for a bool variable. But of course, it is not rational if speed is important. Let’s consider the CPUID8 instruction example. This instruction returns information about the current CPU and its features. If the EAX is set to 1 before the instruction’s execution, CPUID returning this information packed into the EAX register: 3:0 (4 bits) Stepping 7:4 (4 bits) Model 11:8 (4 bits) Family 13:12 (2 bits) Processor Type 19:16 (4 bits) Extended Model 27:20 (8 bits) Extended Family MSVC 2010 has CPUID macro, but GCC 4.4.1 does not. So let’s make this function by ourselves for GCC with the help of its built-in assembler9 . #include <stdio.h> #ifdef __GNUC__ static inline void cpuid(int code, int *a, int *b, int *c, int *d) { asm volatile("cpuid":"=a"(*a),"=b"(*b),"=c"(*c),"=d"(*d):"a"(code)); } #endif 8wikipedia 9More about internal GCC assembler 372
  • 397. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE #ifdef _MSC_VER #include <intrin.h> #endif struct CPUID_1_EAX { unsigned int stepping:4; unsigned int model:4; unsigned int family_id:4; unsigned int processor_type:2; unsigned int reserved1:2; unsigned int extended_model_id:4; unsigned int extended_family_id:8; unsigned int reserved2:4; }; int main() { struct CPUID_1_EAX *tmp; int b[4]; #ifdef _MSC_VER __cpuid(b,1); #endif #ifdef __GNUC__ cpuid (1, &b[0], &b[1], &b[2], &b[3]); #endif tmp=(struct CPUID_1_EAX *)&b[0]; printf ("stepping=%dn", tmp->stepping); printf ("model=%dn", tmp->model); printf ("family_id=%dn", tmp->family_id); printf ("processor_type=%dn", tmp->processor_type); printf ("extended_model_id=%dn", tmp->extended_model_id); printf ("extended_family_id=%dn", tmp->extended_family_id); return 0; }; After CPUID fills EAX/EBX/ECX/EDX, these registers are to be written in the b[] array. Then, we have a pointer to the CPUID_1_EAX structure and we point it to the value in EAX from the b[] array. In other words, we treat a 32-bit int value as a structure. Then we read from the structure. MSVC Let’s compile it in MSVC 2008 with /Ox option: Listing 21.25: Optimizing MSVC 2008 _b$ = -16 ; size = 16 _main PROC sub esp, 16 push ebx xor ecx, ecx mov eax, 1 cpuid push esi lea esi, DWORD PTR _b$[esp+24] mov DWORD PTR [esi], eax mov DWORD PTR [esi+4], ebx mov DWORD PTR [esi+8], ecx mov DWORD PTR [esi+12], edx mov esi, DWORD PTR _b$[esp+24] mov eax, esi and eax, 15 373
  • 398. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE push eax push OFFSET $SG15435 ; 'stepping=%d', 0aH, 00H call _printf mov ecx, esi shr ecx, 4 and ecx, 15 push ecx push OFFSET $SG15436 ; 'model=%d', 0aH, 00H call _printf mov edx, esi shr edx, 8 and edx, 15 push edx push OFFSET $SG15437 ; 'family_id=%d', 0aH, 00H call _printf mov eax, esi shr eax, 12 and eax, 3 push eax push OFFSET $SG15438 ; 'processor_type=%d', 0aH, 00H call _printf mov ecx, esi shr ecx, 16 and ecx, 15 push ecx push OFFSET $SG15439 ; 'extended_model_id=%d', 0aH, 00H call _printf shr esi, 20 and esi, 255 push esi push OFFSET $SG15440 ; 'extended_family_id=%d', 0aH, 00H call _printf add esp, 48 pop esi xor eax, eax pop ebx add esp, 16 ret 0 _main ENDP The SHR instruction shifting the value in EAX by the number of bits that must be skipped, e.g., we ignore some bits at the right side. The AND instruction clears the unneeded bits on the left, or, in other words, leaves only those bits in the EAX register we need. 374
  • 399. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE MSVC + OllyDbg Let’s load our example into OllyDbg and see, what values are set in EAX/EBX/ECX/EDX after the execution of CPUID: Figure 21.6: OllyDbg: After CPUID execution EAX has 0x000206A7 (my CPU is Intel Xeon E3-1220). This is 00000000000000100000011010100111 in binary form. Here is how the bits are distributed by fields: field in binary form in decimal form reserved2 0000 0 extended_family_id 00000000 0 extended_model_id 0010 2 reserved1 00 0 processor_id 00 0 family_id 0110 6 model 1010 10 stepping 0111 7 Figure 21.7: OllyDbg: Result GCC Let’s try GCC 4.4.1 with -O3 option. Listing 21.26: Optimizing GCC 4.4.1 main proc near ; DATA XREF: _start+17 push ebp mov ebp, esp and esp, 0FFFFFFF0h push esi mov esi, 1 375
  • 400. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE push ebx mov eax, esi sub esp, 18h cpuid mov esi, eax and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aSteppingD ; "stepping=%dn" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 4 and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aModelD ; "model=%dn" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 8 and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aFamily_idD ; "family_id=%dn" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 0Ch and eax, 3 mov [esp+8], eax mov dword ptr [esp+4], offset aProcessor_type ; "processor_type=%dn" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 10h shr esi, 14h and eax, 0Fh and esi, 0FFh mov [esp+8], eax mov dword ptr [esp+4], offset aExtended_model ; "extended_model_id=%dn" mov dword ptr [esp], 1 call ___printf_chk mov [esp+8], esi mov dword ptr [esp+4], offset unk_80486D0 mov dword ptr [esp], 1 call ___printf_chk add esp, 18h xor eax, eax pop ebx pop esi mov esp, ebp pop ebp retn main endp Almost the same. The only thing worth noting is that GCC somehow combines the calculation of extended_model_id and extended_family_id into one block, instead of calculating them separately before each printf() call. 21.6.2 Working with the float type as with a structure As we already noted in the section about FPU ( 17 on page 208), both float and double types consist of a sign, a significand (or fraction) and an exponent. But will we be able to work with these fields directly? Let’s try this with float. 022233031 S exponent mantissa or fraction ( S—sign ) #include <stdio.h> #include <assert.h> 376
  • 401. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE #include <stdlib.h> #include <memory.h> struct float_as_struct { unsigned int fraction : 23; // fractional part unsigned int exponent : 8; // exponent + 0x3FF unsigned int sign : 1; // sign bit }; float f(float in) { float f=in; struct float_as_struct t; assert (sizeof (struct float_as_struct) == sizeof (float)); memcpy (&t, &f, sizeof (float)); t.sign=1; // set negative sign t.exponent=t.exponent+2; // multiply d by 2n (n here is 2) memcpy (&f, &t, sizeof (float)); return f; }; int main() { printf ("%fn", f(1.234)); }; The float_as_struct structure occupies the same amount of memory as float, i.e., 4 bytes or 32 bits. Now we are setting the negative sign in the input value and also, by adding 2 to the exponent, we thereby multiply the whole number by 22 , i.e., by 4. Let’s compile in MSVC 2008 without optimization turned on: Listing 21.27: Non-optimizing MSVC 2008 _t$ = -8 ; size = 4 _f$ = -4 ; size = 4 __in$ = 8 ; size = 4 ?f@@YAMM@Z PROC ; f push ebp mov ebp, esp sub esp, 8 fld DWORD PTR __in$[ebp] fstp DWORD PTR _f$[ebp] push 4 lea eax, DWORD PTR _f$[ebp] push eax lea ecx, DWORD PTR _t$[ebp] push ecx call _memcpy add esp, 12 mov edx, DWORD PTR _t$[ebp] or edx, -2147483648 ; 80000000H - set minus sign mov DWORD PTR _t$[ebp], edx mov eax, DWORD PTR _t$[ebp] shr eax, 23 ; 00000017H - drop significand and eax, 255 ; 000000ffH - leave here only exponent add eax, 2 ; add 2 to it and eax, 255 ; 000000ffH shl eax, 23 ; 00000017H - shift result to place of bits 30:23 mov ecx, DWORD PTR _t$[ebp] and ecx, -2139095041 ; 807fffffH - drop exponent 377
  • 402. CHAPTER 21. STRUCTURES 21.6. BIT FIELDS IN A STRUCTURE ; add original value without exponent with new calculated exponent or ecx, eax mov DWORD PTR _t$[ebp], ecx push 4 lea edx, DWORD PTR _t$[ebp] push edx lea eax, DWORD PTR _f$[ebp] push eax call _memcpy add esp, 12 fld DWORD PTR _f$[ebp] mov esp, ebp pop ebp ret 0 ?f@@YAMM@Z ENDP ; f A bit redundant. If it was compiled with /Ox flag there would be no memcpy() call, the f variable is used directly. But it is easier to understand by looking at the unoptimized version. What would GCC 4.4.1 with -O3 do? Listing 21.28: Optimizing GCC 4.4.1 ; f(float) public _Z1ff _Z1ff proc near var_4 = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 4 mov eax, [ebp+arg_0] or eax, 80000000h ; set minus sig mov edx, eax and eax, 807FFFFFh ; leave only significand and exponent in EAX shr edx, 23 ; prepare exponent add edx, 2 ; add 2 movzx edx, dl ; clear all bits except 7:0 in EAX shl edx, 23 ; shift new calculated exponent to its place or eax, edx ; add new exponent and original value without exponent mov [ebp+var_4], eax fld [ebp+var_4] leave retn _Z1ff endp public main main proc near push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h fld ds:dword_8048614 ; -4.936 fstp qword ptr [esp+8] mov dword ptr [esp+4], offset asc_8048610 ; "%fn" mov dword ptr [esp], 1 call ___printf_chk xor eax, eax leave retn main endp The f() function is almost understandable. However, what is interesting is that GCC was able to calculate the result of f(1.234) during compilation despite all this hodge-podge with the structure fields and prepared this argument to printf() as precalculated at compile time! 378
  • 403. CHAPTER 21. STRUCTURES 21.7. EXERCISES 21.7 Exercises 21.7.1 Exercise #1 Linux x86 (beginners.re)10 Linux MIPS (beginners.re)11 This program for Linux x86 and Linux MIPS opens a file and prints a number. What is this number? Answer: G.1.12 on page 958. 21.7.2 Exercise #2 This function takes some structure on input and does something. Try to reverse engineer structure field types. Function contents may be ignored for the moment. Listing 21.29: Optimizing MSVC 2010 $SG2802 DB '%f', 0aH, 00H $SG2803 DB '%c, %d', 0aH, 00H $SG2805 DB 'error #2', 0aH, 00H $SG2807 DB 'error #1', 0aH, 00H __real@405ec00000000000 DQ 0405ec00000000000r ; 123 __real@407bc00000000000 DQ 0407bc00000000000r ; 444 _s$ = 8 _f PROC push esi mov esi, DWORD PTR _s$[esp] cmp DWORD PTR [esi], 1000 jle SHORT $LN4@f cmp DWORD PTR [esi+4], 10 jbe SHORT $LN3@f fld DWORD PTR [esi+8] sub esp, 8 fmul QWORD PTR __real@407bc00000000000 fld QWORD PTR [esi+16] fmul QWORD PTR __real@405ec00000000000 faddp ST(1), ST(0) fstp QWORD PTR [esp] push OFFSET $SG2802 ; '%f' call _printf movzx eax, BYTE PTR [esi+25] movsx ecx, BYTE PTR [esi+24] push eax push ecx push OFFSET $SG2803 ; '%c, %d' call _printf add esp, 24 pop esi ret 0 $LN3@f: pop esi mov DWORD PTR _s$[esp-4], OFFSET $SG2805 ; 'error #2' jmp _printf $LN4@f: pop esi mov DWORD PTR _s$[esp-4], OFFSET $SG2807 ; 'error #1' jmp _printf _f ENDP Listing 21.30: Non-optimizing Keil 6/2013 (ARM mode) f PROC PUSH {r4-r6,lr} MOV r4,r0 LDR r0,[r0,#0] CMP r0,#0x3e8 10GCC 4.8.1 -O3 11GCC 4.4.5 -O3 379
  • 404. CHAPTER 21. STRUCTURES 21.7. EXERCISES ADRLE r0,|L0.140| BLE |L0.132| LDR r0,[r4,#4] CMP r0,#0xa ADRLS r0,|L0.152| BLS |L0.132| ADD r0,r4,#0x10 LDM r0,{r0,r1} LDR r3,|L0.164| MOV r2,#0 BL __aeabi_dmul MOV r5,r0 MOV r6,r1 LDR r0,[r4,#8] LDR r1,|L0.168| BL __aeabi_fmul BL __aeabi_f2d MOV r2,r5 MOV r3,r6 BL __aeabi_dadd MOV r2,r0 MOV r3,r1 ADR r0,|L0.172| BL __2printf LDRB r2,[r4,#0x19] LDRB r1,[r4,#0x18] POP {r4-r6,lr} ADR r0,|L0.176| B __2printf |L0.132| POP {r4-r6,lr} B __2printf ENDP |L0.140| DCB "error #1n",0 DCB 0 DCB 0 |L0.152| DCB "error #2n",0 DCB 0 DCB 0 |L0.164| DCD 0x405ec000 |L0.168| DCD 0x43de0000 |L0.172| DCB "%fn",0 |L0.176| DCB "%c, %dn",0 Listing 21.31: Non-optimizing Keil 6/2013 (thumb mode) f PROC PUSH {r4-r6,lr} MOV r4,r0 LDR r0,[r0,#0] CMP r0,#0x3e8 ADRLE r0,|L0.140| BLE |L0.132| LDR r0,[r4,#4] CMP r0,#0xa ADRLS r0,|L0.152| BLS |L0.132| ADD r0,r4,#0x10 LDM r0,{r0,r1} LDR r3,|L0.164| MOV r2,#0 BL __aeabi_dmul MOV r5,r0 380
  • 405. CHAPTER 21. STRUCTURES 21.7. EXERCISES MOV r6,r1 LDR r0,[r4,#8] LDR r1,|L0.168| BL __aeabi_fmul BL __aeabi_f2d MOV r2,r5 MOV r3,r6 BL __aeabi_dadd MOV r2,r0 MOV r3,r1 ADR r0,|L0.172| BL __2printf LDRB r2,[r4,#0x19] LDRB r1,[r4,#0x18] POP {r4-r6,lr} ADR r0,|L0.176| B __2printf |L0.132| POP {r4-r6,lr} B __2printf ENDP |L0.140| DCB "error #1n",0 DCB 0 DCB 0 |L0.152| DCB "error #2n",0 DCB 0 DCB 0 |L0.164| DCD 0x405ec000 |L0.168| DCD 0x43de0000 |L0.172| DCB "%fn",0 |L0.176| DCB "%c, %dn",0 Listing 21.32: Optimizing GCC 4.9 (ARM64) f: stp x29, x30, [sp, -32]! add x29, sp, 0 ldr w1, [x0] str x19, [sp,16] cmp w1, 1000 ble .L2 ldr w1, [x0,4] cmp w1, 10 bls .L3 ldr s1, [x0,8] mov x19, x0 ldr s0, .LC1 adrp x0, .LC0 ldr d2, [x19,16] add x0, x0, :lo12:.LC0 fmul s1, s1, s0 ldr d0, .LC2 fmul d0, d2, d0 fcvt d1, s1 fadd d0, d1, d0 bl printf ldrb w1, [x19,24] adrp x0, .LC3 ldrb w2, [x19,25] add x0, x0, :lo12:.LC3 ldr x19, [sp,16] ldp x29, x30, [sp], 32 b printf 381
  • 406. CHAPTER 21. STRUCTURES 21.7. EXERCISES .L3: ldr x19, [sp,16] adrp x0, .LC4 ldp x29, x30, [sp], 32 add x0, x0, :lo12:.LC4 b puts .L2: ldr x19, [sp,16] adrp x0, .LC5 ldp x29, x30, [sp], 32 add x0, x0, :lo12:.LC5 b puts .size f, .-f .LC1: .word 1138622464 .LC2: .word 0 .word 1079951360 .LC0: .string "%fn" .LC3: .string "%c, %dn" .LC4: .string "error #2" .LC5: .string "error #1" Listing 21.33: Optimizing GCC 4.4.5 (MIPS) (IDA) f: var_10 = -0x10 var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $s0, 0x20+var_8($sp) sw $gp, 0x20+var_10($sp) lw $v0, 0($a0) or $at, $zero slti $v0, 0x3E9 bnez $v0, loc_C8 move $s0, $a0 lw $v0, 4($a0) or $at, $zero sltiu $v0, 0xB bnez $v0, loc_AC lui $v0, (dword_134 >> 16) lwc1 $f4, $LC1 lwc1 $f2, 8($a0) lui $v0, ($LC2 >> 16) lwc1 $f0, 0x14($a0) mul.s $f2, $f4, $f2 lwc1 $f4, dword_134 lwc1 $f1, 0x10($a0) lwc1 $f5, $LC2 cvt.d.s $f2, $f2 mul.d $f0, $f4, $f0 lw $t9, (printf & 0xFFFF)($gp) lui $a0, ($LC0 >> 16) # "%fn" add.d $f4, $f2, $f0 mfc1 $a2, $f5 mfc1 $a3, $f4 jalr $t9 la $a0, ($LC0 & 0xFFFF) # "%fn" lw $gp, 0x20+var_10($sp) lbu $a2, 0x19($s0) 382
  • 407. CHAPTER 21. STRUCTURES 21.7. EXERCISES lb $a1, 0x18($s0) lui $a0, ($LC3 >> 16) # "%c, %dn" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC3 & 0xFFFF) # "%c, %dn" jr $t9 addiu $sp, 0x20 loc_AC: # CODE XREF: f+38 lui $a0, ($LC4 >> 16) # "error #2" lw $t9, (puts & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC4 & 0xFFFF) # "error #2" jr $t9 addiu $sp, 0x20 loc_C8: # CODE XREF: f+24 lui $a0, ($LC5 >> 16) # "error #1" lw $t9, (puts & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC5 & 0xFFFF) # "error #1" jr $t9 addiu $sp, 0x20 $LC0: .ascii "%fn"<0> $LC3: .ascii "%c, %dn"<0> $LC4: .ascii "error #2"<0> $LC5: .ascii "error #1"<0> .data # .rodata.cst4 $LC1: .word 0x43DE0000 .data # .rodata.cst8 $LC2: .word 0x405EC000 dword_134: .word 0 Answer: G.1.12 on page 958. 383
  • 408. CHAPTER 22. UNIONS Chapter 22 Unions 22.1 Pseudo-random number generator example If we need float random numbers between 0 and 1, the simplest thing is to use a PRNG like the Mersenne twister. It produces random 32-bit values in DWORD form. Then we can transform this value to float and then divide it by RAND_MAX (0xFFFFFFFF in our case) — we getting a value in the 0..1 interval. But as we know, division is slow. Also, we would like to issue as few FPU operations as possible. Can we get rid of the division? Let’s recall what a floating point number consists of: sign bit, significand bits and exponent bits. We just need to store random bits in all significand bits to get a random float number! The exponent cannot be zero (the number is denormalized in this case), so we are storing 01111111 to exponent —this means that the exponent is 1. Then we filling the significand with random bits, set the sign bit to 0 (which means a positive number) and voilà. The generated numbers is to be between 1 and 2, so we must also subtract 1. A very simple linear congruential random numbers generator is used in my example1 , it produces 32-bit numbers. The PRNG is initialized with the current time in UNIX timestamp format. Here we represent the float type as an union —it is the C/C++ construction that enables us to interpret a piece of memory as different types. In our case, we are able to create a variable of type union and then access to it as it is float or as it is uint32_t. It can be said, it is just a hack. A dirty one. The integer PRNG code is the same as we already considered: 20 on page 344. So this code in compiled form is omitted. #include <stdio.h> #include <stdint.h> #include <time.h> // integer PRNG definitions, data and routines: // constants from the Numerical Recipes book const uint32_t RNG_a=1664525; const uint32_t RNG_c=1013904223; uint32_t RNG_state; // global variable void my_srand(uint32_t i) { RNG_state=i; }; uint32_t my_rand() { RNG_state=RNG_state*RNG_a+RNG_c; return RNG_state; }; // FPU PRNG definitions and routines: union uint32_t_float { uint32_t i; float f; }; float float_rand() { 1the idea was taken from: http://go.yurichev.com/17308 384
  • 409. CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE union uint32_t_float tmp; tmp.i=my_rand() & 0x007fffff | 0x3F800000; return tmp.f-1; }; // test int main() { my_srand(time(NULL)); // PRNG initialization for (int i=0; i<100; i++) printf ("%fn", float_rand()); return 0; }; 22.1.1 x86 Listing 22.1: Optimizing MSVC 2010 $SG4238 DB '%f', 0aH, 00H __real@3ff0000000000000 DQ 03ff0000000000000r ; 1 tv130 = -4 _tmp$ = -4 ?float_rand@@YAMXZ PROC push ecx call ?my_rand@@YAIXZ ; EAX=pseudorandom value and eax, 8388607 ; 007fffffH or eax, 1065353216 ; 3f800000H ; EAX=pseudorandom value & 0x007fffff | 0x3f800000 ; store it into local stack: mov DWORD PTR _tmp$[esp+4], eax ; reload it as float point number: fld DWORD PTR _tmp$[esp+4] ; subtract 1.0: fsub QWORD PTR __real@3ff0000000000000 ; store value we got into local stack and reload it: fstp DWORD PTR tv130[esp+4] ; these instructions are redundant fld DWORD PTR tv130[esp+4] ; / pop ecx ret 0 ?float_rand@@YAMXZ ENDP _main PROC push esi xor eax, eax call _time push eax call ?my_srand@@YAXI@Z add esp, 4 mov esi, 100 $LL3@main: call ?float_rand@@YAMXZ sub esp, 8 fstp QWORD PTR [esp] push OFFSET $SG4238 call _printf add esp, 12 dec esi jne SHORT $LL3@main xor eax, eax pop esi ret 0 _main ENDP 385
  • 410. CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE Function names are so strange here because I compiled this example as C++ and this is name mangling in C++, we will talk about it later: 51.1.1 on page 541. If we compile this in MSVC 2012, it uses the SIMD instructions for the FPU, read more about it here: 27.5 on page 444. 22.1.2 MIPS Listing 22.2: Optimizing GCC 4.4.5 float_rand: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) ; call my_rand(): jal my_rand or $at, $zero ; branch delay slot, NOP ; $v0=32-bit pseudorandom value li $v1, 0x7FFFFF ; $v1=0x7FFFFF and $v1, $v0, $v1 ; $v1=pseudorandom value & 0x7FFFFF lui $a0, 0x3F80 ; $a0=0x3F800000 or $v1, $a0 ; $v1=pseudorandom value & 0x7FFFFF | 0x3F800000 ; I still dont get matter of the following instruction:' lui $v0, ($LC0 >> 16) ; load 1.0 into $f0: lwc1 $f0, $LC0 ; move value from $v1 to coprocessor 1 (into register $f2) ; it behaves like bitwise copy, no conversion done: mtc1 $v1, $f2 lw $ra, 0x20+var_4($sp) ; subtract 1.0. leave result in $f0: sub.s $f0, $f2, $f0 jr $ra addiu $sp, 0x20 ; branch delay slot main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s2, 0x28+var_8($sp) sw $s1, 0x28+var_C($sp) sw $s0, 0x28+var_10($sp) sw $gp, 0x28+var_18($sp) lw $t9, (time & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jalr $t9 move $a0, $zero ; branch delay slot lui $s2, ($LC1 >> 16) # "%fn" move $a0, $v0 la $s2, ($LC1 & 0xFFFF) # "%fn" move $s0, $zero jal my_srand li $s1, 0x64 # 'd' ; branch delay slot 386
  • 411. CHAPTER 22. UNIONS 22.1. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE loc_104: jal float_rand addiu $s0, 1 lw $gp, 0x28+var_18($sp) ; convert value we got from float_rand() to double type (printf() need it): cvt.d.s $f2, $f0 lw $t9, (printf & 0xFFFF)($gp) mfc1 $a3, $f2 mfc1 $a2, $f3 jalr $t9 move $a0, $s2 bne $s0, $s1, loc_104 move $v0, $zero lw $ra, 0x28+var_4($sp) lw $s2, 0x28+var_8($sp) lw $s1, 0x28+var_C($sp) lw $s0, 0x28+var_10($sp) jr $ra addiu $sp, 0x28 ; branch delay slot $LC1: .ascii "%fn"<0> $LC0: .float 1.0 There is also an useless LUI instruction added for some weird reason. We considered this artifact earlier: 17.5.6 on page 219. 22.1.3 ARM (ARM mode) Listing 22.3: Optimizing GCC 4.6.3 (IDA) float_rand STMFD SP!, {R3,LR} BL my_rand ; R0=pseudorandom value FLDS S0, =1.0 ; S0=1.0 BIC R3, R0, #0xFF000000 BIC R3, R3, #0x800000 ORR R3, R3, #0x3F800000 ; R3=pseudorandom value & 0x007fffff | 0x3f800000 ; copy from R3 to FPU (register S15). ; it behaves like bitwise copy, no conversion done: FMSR S15, R3 ; subtract 1.0 and leave result in S0: FSUBS S0, S15, S0 LDMFD SP!, {R3,PC} flt_5C DCFS 1.0 main STMFD SP!, {R4,LR} MOV R0, #0 BL time BL my_srand MOV R4, #0x64 ; 'd' loc_78 BL float_rand ; S0=pseudorandom value LDR R0, =aF ; "%f" ; convert float type value into double type value (printf() will need it): FCVTDS D7, S0 ; bitwise copy from D7 into R2/R3 pair of registers (for printf()): FMRRD R2, R3, D7 BL printf SUBS R4, R4, #1 BNE loc_78 MOV R0, R4 387
  • 412. CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON LDMFD SP!, {R4,PC} aF DCB "%f",0xA,0 I also made a dump in objdump and I saw that the FPU instructions have different names than in IDA. Apparently, IDA and binutils developers used different manuals? I suppose, it would be good to know both instruction name variants. Listing 22.4: Optimizing GCC 4.6.3 (objdump) 00000038 <float_rand>: 38: e92d4008 push {r3, lr} 3c: ebfffffe bl 10 <my_rand> 40: ed9f0a05 vldr s0, [pc, #20] ; 5c <float_rand+0x24> 44: e3c034ff bic r3, r0, #-16777216 ; 0xff000000 48: e3c33502 bic r3, r3, #8388608 ; 0x800000 4c: e38335fe orr r3, r3, #1065353216 ; 0x3f800000 50: ee073a90 vmov s15, r3 54: ee370ac0 vsub.f32 s0, s15, s0 58: e8bd8008 pop {r3, pc} 5c: 3f800000 svccc 0x00800000 00000000 <main>: 0: e92d4010 push {r4, lr} 4: e3a00000 mov r0, #0 8: ebfffffe bl 0 <time> c: ebfffffe bl 0 <main> 10: e3a04064 mov r4, #100 ; 0x64 14: ebfffffe bl 38 <main+0x38> 18: e59f0018 ldr r0, [pc, #24] ; 38 <main+0x38> 1c: eeb77ac0 vcvt.f64.f32 d7, s0 20: ec532b17 vmov r2, r3, d7 24: ebfffffe bl 0 <printf> 28: e2544001 subs r4, r4, #1 2c: 1afffff8 bne 14 <main+0x14> 30: e1a00004 mov r0, r4 34: e8bd8010 pop {r4, pc} 38: 00000000 andeq r0, r0, r0 The instructions at 5c in float_rand() and at 38 in main() are random noise. 22.2 Calculating machine epsilon The machine epsilon is the smallest possible value the FPU can work with. The more bits allocated for floating point number, the smaller the machine epsilon. It is 2−23 = 1.19e − 07 for float and 2−52 = 2.22e − 16 for double. It’s interesting, how easy it’s to calculate the machine epsilon: #include <stdio.h> #include <stdint.h> union uint_float { uint32_t i; float f; }; float calculate_machine_epsilon(float start) { union uint_float v; v.f=start; v.i++; return v.f-start; } void main() { printf ("%gn", calculate_machine_epsilon(1.234567)); }; 388
  • 413. CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON What we do here is just treat the fraction part of the IEEE 754 number as integer and add 1 to it. The resulting floating number is equal to starting_value + machine_epsilon, so we just need to subtract the starting value (using floating point arithmetic) to measure, what difference one bit reflects in the single precision (float). The union serves here as a way to access IEEE 754 number as a regular integer. Adding 1 to it in fact adds 1 to the fraction part of the number, however, needless to say, overflow is possible, which will add another 1 to the exponent part. 22.2.1 x86 Listing 22.5: Optimizing MSVC 2010 tv130 = 8 _v$ = 8 _start$ = 8 _calculate_machine_epsilon PROC fld DWORD PTR _start$[esp-4] fst DWORD PTR _v$[esp-4] ; this instruction is redundant inc DWORD PTR _v$[esp-4] fsubr DWORD PTR _v$[esp-4] fstp DWORD PTR tv130[esp-4] ; this instruction pair is also redundant fld DWORD PTR tv130[esp-4] ; / ret 0 _calculate_machine_epsilon ENDP The second FST instruction is redundant: there is no need to store the input value in the same place (the compiler decided to allocate the v variable at the same point in the local stack as the input argument). Then it is incremented with INC, as it is a normal integer variable. Then it is loaded into the FPU as a 32-bit IEEE 754 number, FSUBR does the rest of job and the resulting value is stored in ST0. The last FSTP/FLD instruction pair is redundant, but the compiler didn’t optimize it out. 22.2.2 ARM64 Let’s extend our example to 64-bit: #include <stdio.h> #include <stdint.h> typedef union { uint64_t i; double d; } uint_double; double calculate_machine_epsilon(double start) { uint_double v; v.d=start; v.i++; return v.d-start; } void main() { printf ("%gn", calculate_machine_epsilon(1.234567)); }; ARM64 has no instruction that can add a number to a FPU D-register, so the input value (that came in D0) is first copied into GPR, incremented, copied to FPU register D1, and then subtraction occurs. Listing 22.6: Optimizing GCC 4.9 ARM64 calculate_machine_epsilon: fmov x0, d0 ; load input value of double type into X0 add x0, x0, 1 ; X0++ fmov d1, x0 ; move it to FPU register fsub d0, d1, d0 ; subtract ret See also this example compiled for x64 with SIMD instructions: 27.4 on page 443. 389
  • 414. CHAPTER 22. UNIONS 22.2. CALCULATING MACHINE EPSILON 22.2.3 MIPS The new instruction here is MTC1 (“Move To Coprocessor 1”), it just transfers data from GPR to the FPU’s registers. Listing 22.7: Optimizing GCC 4.4.5 (IDA) calculate_machine_epsilon: mfc1 $v0, $f12 or $at, $zero ; NOP addiu $v1, $v0, 1 mtc1 $v1, $f2 jr $ra sub.s $f0, $f2, $f12 ; branch delay slot 22.2.4 Conclusion It’s hard to say whether someone may need this trickery in real-world code, but as I write many times in this book, this example serves well for explaining the IEEE 754 format and unions in C/C++. 390
  • 415. CHAPTER 23. POINTERS TO FUNCTIONS Chapter 23 Pointers to functions A pointer to a function, as any other pointer, is just the address of the function’s start in its code segment. They are often used as callbacks 1 . Well-known examples are: • qsort()2 , atexit()3 from the standard C library; • *NIX OS signals4 ; • thread starting: CreateThread() (win32), pthread_create() (POSIX); • lots of win32 functions, like EnumChildWindows()5 . • lots of places in the Linux kernel, for example the filesystem driver functions are called via callbacks: http://go. yurichev.com/17076 • The GCC plugin functions are also called via callbacks: http://go.yurichev.com/17077 • Another example of function pointers is a table in the “dwm” Linux window manager that defines shortcuts. Each shortcut has a corresponding function to call if a specific key is pressed: GitHub As we can see, such table is easier to handle than a large switch() statement. So, the qsort() function is an implementation of quicksort in the C/C++ standard library. The functions is able to sort anything, any type of data, as long as you have a function to compare these two elements and qsort() is able to call it. The comparison function can be defined as: int (*compare)(const void *, const void *) Let’s use a slightly modified example I found here: 1 /* ex3 Sorting ints with qsort */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 int comp(const void * _a, const void * _b) 7 { 8 const int *a=(const int *)_a; 9 const int *b=(const int *)_b; 10 11 if (*a==*b) 12 return 0; 13 else 14 if (*a < *b) 15 return -1; 16 else 17 return 1; 18 } 19 20 int main(int argc, char* argv[]) 1wikipedia 2wikipedia 3http://go.yurichev.com/17073 4wikipedia 5MSDN 391
  • 416. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC 21 { 22 int numbers[10]={1892,45,200,-98,4087,5,-12345,1087,88,-100000}; 23 int i; 24 25 /* Sort the array */ 26 qsort(numbers,10,sizeof(int),comp) ; 27 for (i=0;i<9;i++) 28 printf("Number = %dn",numbers[ i ]) ; 29 return 0; 30 } 23.1 MSVC Let’s compile it in MSVC 2010 (I omitted some parts for the sake of brevity) with /Ox option: Listing 23.1: Optimizing MSVC 2010: /GS- /MD __a$ = 8 ; size = 4 __b$ = 12 ; size = 4 _comp PROC mov eax, DWORD PTR __a$[esp-4] mov ecx, DWORD PTR __b$[esp-4] mov eax, DWORD PTR [eax] mov ecx, DWORD PTR [ecx] cmp eax, ecx jne SHORT $LN4@comp xor eax, eax ret 0 $LN4@comp: xor edx, edx cmp eax, ecx setge dl lea eax, DWORD PTR [edx+edx-1] ret 0 _comp ENDP _numbers$ = -40 ; size = 40 _argc$ = 8 ; size = 4 _argv$ = 12 ; size = 4 _main PROC sub esp, 40 ; 00000028H push esi push OFFSET _comp push 4 lea eax, DWORD PTR _numbers$[esp+52] push 10 ; 0000000aH push eax mov DWORD PTR _numbers$[esp+60], 1892 ; 00000764H mov DWORD PTR _numbers$[esp+64], 45 ; 0000002dH mov DWORD PTR _numbers$[esp+68], 200 ; 000000c8H mov DWORD PTR _numbers$[esp+72], -98 ; ffffff9eH mov DWORD PTR _numbers$[esp+76], 4087 ; 00000ff7H mov DWORD PTR _numbers$[esp+80], 5 mov DWORD PTR _numbers$[esp+84], -12345 ; ffffcfc7H mov DWORD PTR _numbers$[esp+88], 1087 ; 0000043fH mov DWORD PTR _numbers$[esp+92], 88 ; 00000058H mov DWORD PTR _numbers$[esp+96], -100000 ; fffe7960H call _qsort add esp, 16 ; 00000010H ... Nothing surprising so far. As a fourth argument, the address of label _comp is passed, which is just a place where comp() is located, or, in other words, the address of the very first instruction of that function. How does qsort() call it? Let’s take a look at this function, located in MSVCR80.DLL (a MSVC DLL module with C standard library functions): 392
  • 417. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC Listing 23.2: MSVCR80.DLL .text:7816CBF0 ; void __cdecl qsort(void *, unsigned int, unsigned int, int (__cdecl *)(const ⤦ void *, const void *)) .text:7816CBF0 public _qsort .text:7816CBF0 _qsort proc near .text:7816CBF0 .text:7816CBF0 lo = dword ptr -104h .text:7816CBF0 hi = dword ptr -100h .text:7816CBF0 var_FC = dword ptr -0FCh .text:7816CBF0 stkptr = dword ptr -0F8h .text:7816CBF0 lostk = dword ptr -0F4h .text:7816CBF0 histk = dword ptr -7Ch .text:7816CBF0 base = dword ptr 4 .text:7816CBF0 num = dword ptr 8 .text:7816CBF0 width = dword ptr 0Ch .text:7816CBF0 comp = dword ptr 10h .text:7816CBF0 .text:7816CBF0 sub esp, 100h .... .text:7816CCE0 loc_7816CCE0: ; CODE XREF: _qsort+B1 .text:7816CCE0 shr eax, 1 .text:7816CCE2 imul eax, ebp .text:7816CCE5 add eax, ebx .text:7816CCE7 mov edi, eax .text:7816CCE9 push edi .text:7816CCEA push ebx .text:7816CCEB call [esp+118h+comp] .text:7816CCF2 add esp, 8 .text:7816CCF5 test eax, eax .text:7816CCF7 jle short loc_7816CD04 comp— is the fourth function argument. Here the control gets passed to the address in the comp argument. Before it, two arguments are prepared for comp(). Its result is checked after its execution. That’s why it is dangerous to use pointers to functions. First of all, if you call qsort() with an incorrect function pointer, qsort() may pass control flow to an incorrect point, the process may crash and this bug will be hard to find. The second reason is that the callback function types must comply strictly, calling the wrong function with wrong ar- guments of wrong types may lead to serious problems, however, the crashing of the process is not a problem here —the problem is how to determine the reason for the crash —because the compiler may be silent about the potential problems while compiling. 393
  • 418. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC 23.1.1 MSVC + OllyDbg Let’s load our example into OllyDbg and set a breakpoint on comp(). We can see how the values are compared at the first comp() call: Figure 23.1: OllyDbg: first call of comp() OllyDbg shows the compared values in the window under the code window, for convenience. We can also see that the SP points to RA , where the qsort() function is (located in MSVCR100.DLL). 394
  • 419. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC By tracing (F8) until the RETN instruction and pressing F8 one more time, we return to the qsort() function: Figure 23.2: OllyDbg: the code in qsort() right after comp() call That was a call to the comparison function. 395
  • 420. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC Here is also a screenshot of the moment of the second call of comp()— now values that have to be compared are different: Figure 23.3: OllyDbg: second call of comp() 23.1.2 MSVC + tracer Let’s also see which pairs are compared. These 10 numbers are being sorted: 1892, 45, 200, -98, 4087, 5, -12345, 1087, 88, -100000. I got the address of the first CMP instruction in comp(), it is 0x0040100C and I’ve set a breakpoint on it: tracer.exe -l:17_1.exe bpx=17_1.exe!0x0040100C Now I get some information about the registers at the breakpoint: PID=4336|New process 17_1.exe (0) 17_1.exe!0x40100c EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c FLAGS=IF (0) 17_1.exe!0x40100c EAX=0x00000005 EBX=0x0051f7c8 ECX=0xfffe7960 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c FLAGS=PF ZF IF (0) 17_1.exe!0x40100c EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c FLAGS=CF PF ZF IF ... I’ve filtered out EAX and ECX and gotten: EAX=0x00000764 ECX=0x00000005 EAX=0x00000005 ECX=0xfffe7960 EAX=0x00000764 ECX=0x00000005 EAX=0x0000002d ECX=0x00000005 EAX=0x00000058 ECX=0x00000005 EAX=0x0000043f ECX=0x00000005 EAX=0xffffcfc7 ECX=0x00000005 EAX=0x000000c8 ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0x00000ff7 ECX=0x00000005 EAX=0x00000ff7 ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0x00000005 ECX=0xffffcfc7 396
  • 421. CHAPTER 23. POINTERS TO FUNCTIONS 23.1. MSVC EAX=0xffffff9e ECX=0x00000005 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0xffffff9e ECX=0xffffcfc7 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0x000000c8 ECX=0x00000ff7 EAX=0x0000002d ECX=0x00000ff7 EAX=0x0000043f ECX=0x00000ff7 EAX=0x00000058 ECX=0x00000ff7 EAX=0x00000764 ECX=0x00000ff7 EAX=0x000000c8 ECX=0x00000764 EAX=0x0000002d ECX=0x00000764 EAX=0x0000043f ECX=0x00000764 EAX=0x00000058 ECX=0x00000764 EAX=0x000000c8 ECX=0x00000058 EAX=0x0000002d ECX=0x000000c8 EAX=0x0000043f ECX=0x000000c8 EAX=0x000000c8 ECX=0x00000058 EAX=0x0000002d ECX=0x000000c8 EAX=0x0000002d ECX=0x00000058 That’s 34 pairs. Therefore, the quick sort algorithm needs 34 comparison operations to sort these 10 numbers. 397
  • 422. CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC 23.1.3 MSVC + tracer (code coverage) We can also use the tracer’s feature to collect all possible register values and show them in IDA. Let’s trace all instructions in comp(): tracer.exe -l:17_1.exe bpf=17_1.exe!0x00401000,trace:cc We get an .idc-script for loading into IDA and load it: Figure 23.4: tracer and IDA. N.B.: some values are cut at right IDA gave the function a name (PtFuncCompare) — because IDA sees that the pointer to this function is passed to qsort(). We see that the a and b pointers are pointing to various places in the array, but the step between them is 4, as 32-bit values are stored in the array. We see that the instructions at 0x401010 and 0x401012 were never executed (so they left as white): indeed, comp() has never returned 0, because there no equal elements in the array. 23.2 GCC Not a big difference: Listing 23.3: GCC lea eax, [esp+40h+var_28] mov [esp+40h+var_40], eax mov [esp+40h+var_28], 764h mov [esp+40h+var_24], 2Dh mov [esp+40h+var_20], 0C8h mov [esp+40h+var_1C], 0FFFFFF9Eh mov [esp+40h+var_18], 0FF7h mov [esp+40h+var_14], 5 mov [esp+40h+var_10], 0FFFFCFC7h mov [esp+40h+var_C], 43Fh mov [esp+40h+var_8], 58h mov [esp+40h+var_4], 0FFFE7960h mov [esp+40h+var_34], offset comp mov [esp+40h+var_38], 4 mov [esp+40h+var_3C], 0Ah call _qsort comp() function: public comp comp proc near 398
  • 423. CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch push ebp mov ebp, esp mov eax, [ebp+arg_4] mov ecx, [ebp+arg_0] mov edx, [eax] xor eax, eax cmp [ecx], edx jnz short loc_8048458 pop ebp retn loc_8048458: setnl al movzx eax, al lea eax, [eax+eax-1] pop ebp retn comp endp The implementation of qsort() is located in libc.so.6 and it is in fact just a wrapper 6 for qsort_r(). In turn, it is calling quicksort(), where our defined function is called via a passed pointer: Listing 23.4: (file libc.so.6, glibc version—2.10.1) .text:0002DDF6 mov edx, [ebp+arg_10] .text:0002DDF9 mov [esp+4], esi .text:0002DDFD mov [esp], edi .text:0002DE00 mov [esp+8], edx .text:0002DE04 call [ebp+arg_C] ... 23.2.1 GCC + GDB (with source code) Obviously, we have the C-source code of our example ( 23 on page 391), so we can set a breakpoint (b) on line number (11—the line where the first comparison occurs). We also need to compile the example with debugging information included (-g), so the table with addresses and corresponding line numbers is present. We can also print values using variable names (p): the debugging information also has tells us which register and/or local stack element contains which variable. We can also see the stack (bt) and find out that there is some intermediate function msort_with_tmp() used in Glibc. Listing 23.5: GDB session dennis@ubuntuvm:~/polygon$ gcc 17_1.c -g dennis@ubuntuvm:~/polygon$ gdb ./a.out GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/a.out...done. (gdb) b 17_1.c:11 Breakpoint 1 at 0x804845f: file 17_1.c, line 11. (gdb) run Starting program: /home/dennis/polygon/./a.out Breakpoint 1, comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11 11 if (*a==*b) (gdb) p *a $1 = 1892 (gdb) p *b $2 = 45 6a concept like thunk function 399
  • 424. CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC (gdb) c Continuing. Breakpoint 1, comp (_a=0xbffff104, _b=_b@entry=0xbffff108) at 17_1.c:11 11 if (*a==*b) (gdb) p *a $3 = -98 (gdb) p *b $4 = 4087 (gdb) bt #0 comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11 #1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2) at msort.c:65 #2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53 #4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53 #6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d <⤦ comp>, arg=arg@entry=0x0) at msort.c:297 #8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307 #9 0x0804850d in main (argc=1, argv=0xbffff1c4) at 17_1.c:26 (gdb) 23.2.2 GCC + GDB (no source code) But often there is no source code at all, so we can disassemble the comp() function (disas), find the very first CMP instruction and set a breakpoint (b) at that address. At each breakpoint, we are going to dump all register contents (info registers). The stack information is also available (bt), but partially: there is no line number information for comp(). Listing 23.6: GDB session dennis@ubuntuvm:~/polygon$ gcc 17_1.c dennis@ubuntuvm:~/polygon$ gdb ./a.out GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/a.out...(no debugging symbols found)...done. (gdb) set disassembly-flavor intel (gdb) disas comp Dump of assembler code for function comp: 0x0804844d <+0>: push ebp 0x0804844e <+1>: mov ebp,esp 0x08048450 <+3>: sub esp,0x10 0x08048453 <+6>: mov eax,DWORD PTR [ebp+0x8] 0x08048456 <+9>: mov DWORD PTR [ebp-0x8],eax 0x08048459 <+12>: mov eax,DWORD PTR [ebp+0xc] 0x0804845c <+15>: mov DWORD PTR [ebp-0x4],eax 0x0804845f <+18>: mov eax,DWORD PTR [ebp-0x8] 0x08048462 <+21>: mov edx,DWORD PTR [eax] 0x08048464 <+23>: mov eax,DWORD PTR [ebp-0x4] 0x08048467 <+26>: mov eax,DWORD PTR [eax] 0x08048469 <+28>: cmp edx,eax 0x0804846b <+30>: jne 0x8048474 <comp+39> 0x0804846d <+32>: mov eax,0x0 0x08048472 <+37>: jmp 0x804848e <comp+65> 0x08048474 <+39>: mov eax,DWORD PTR [ebp-0x8] 0x08048477 <+42>: mov edx,DWORD PTR [eax] 0x08048479 <+44>: mov eax,DWORD PTR [ebp-0x4] 0x0804847c <+47>: mov eax,DWORD PTR [eax] 0x0804847e <+49>: cmp edx,eax 0x08048480 <+51>: jge 0x8048489 <comp+60> 400
  • 425. CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC 0x08048482 <+53>: mov eax,0xffffffff 0x08048487 <+58>: jmp 0x804848e <comp+65> 0x08048489 <+60>: mov eax,0x1 0x0804848e <+65>: leave 0x0804848f <+66>: ret End of assembler dump. (gdb) b *0x08048469 Breakpoint 1 at 0x8048469 (gdb) run Starting program: /home/dennis/polygon/./a.out Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0x2d 45 ecx 0xbffff0f8 -1073745672 edx 0x764 1892 ebx 0xb7fc0000 -1208221696 esp 0xbfffeeb8 0xbfffeeb8 ebp 0xbfffeec8 0xbfffeec8 esi 0xbffff0fc -1073745668 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x286 [ PF SF IF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) c Continuing. Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0xff7 4087 ecx 0xbffff104 -1073745660 edx 0xffffff9e -98 ebx 0xb7fc0000 -1208221696 esp 0xbfffee58 0xbfffee58 ebp 0xbfffee68 0xbfffee68 esi 0xbffff108 -1073745656 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x282 [ SF IF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) c Continuing. Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0xffffff9e -98 ecx 0xbffff100 -1073745664 edx 0xc8 200 ebx 0xb7fc0000 -1208221696 esp 0xbfffeeb8 0xbfffeeb8 ebp 0xbfffeec8 0xbfffeec8 esi 0xbffff104 -1073745660 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x286 [ PF SF IF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 401
  • 426. CHAPTER 23. POINTERS TO FUNCTIONS 23.2. GCC gs 0x33 51 (gdb) bt #0 0x08048469 in comp () #1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2) at msort.c:65 #2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53 #4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53 #6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d <⤦ comp>, arg=arg@entry=0x0) at msort.c:297 #8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307 #9 0x0804850d in main () 402
  • 427. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT Chapter 24 64-bit values in 32-bit environment In a 32-bit environment, GPR’s are 32-bit, so 64-bit values are stored and passed as 32-bit value pairs 1 . 24.1 Returning of 64-bit value #include <stdint.h> uint64_t f () { return 0x1234567890ABCDEF; }; 24.1.1 x86 In a 32-bit environment, 64-bit values are returned from functions in the EDX:EAX register pair. Listing 24.1: Optimizing MSVC 2010 _f PROC mov eax, -1867788817 ; 90abcdefH mov edx, 305419896 ; 12345678H ret 0 _f ENDP 24.1.2 ARM A 64-bit value is returned in the R0-R1 register pair (R1 is for the high part and R0 for the low part): Listing 24.2: Optimizing Keil 6/2013 (ARM mode) ||f|| PROC LDR r0,|L0.12| LDR r1,|L0.16| BX lr ENDP |L0.12| DCD 0x90abcdef |L0.16| DCD 0x12345678 24.1.3 MIPS A 64-bit value is returned in the V0-V1 ($2-$3) register pair (V0 ($2) is for the high part and V1 ($3) for the low part): Listing 24.3: Optimizing GCC 4.4.5 (assembly listing) li $3,-1867841536 # 0xffffffff90ab0000 li $2,305397760 # 0x12340000 ori $3,$3,0xcdef 1By the way, 32-bit values are passed as pairs in 16-bit environment in the same way: 53.4 on page 594 403
  • 428. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION j $31 ori $2,$2,0x5678 Listing 24.4: Optimizing GCC 4.4.5 (IDA) lui $v1, 0x90AB lui $v0, 0x1234 li $v1, 0x90ABCDEF jr $ra li $v0, 0x12345678 24.2 Arguments passing, addition, subtraction #include <stdint.h> uint64_t f_add (uint64_t a, uint64_t b) { return a+b; }; void f_add_test () { #ifdef __GNUC__ printf ("%lldn", f_add(12345678901234, 23456789012345)); #else printf ("%I64dn", f_add(12345678901234, 23456789012345)); #endif }; uint64_t f_sub (uint64_t a, uint64_t b) { return a-b; }; 24.2.1 x86 Listing 24.5: Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_add PROC mov eax, DWORD PTR _a$[esp-4] add eax, DWORD PTR _b$[esp-4] mov edx, DWORD PTR _a$[esp] adc edx, DWORD PTR _b$[esp] ret 0 _f_add ENDP _f_add_test PROC push 5461 ; 00001555H push 1972608889 ; 75939f79H push 2874 ; 00000b3aH push 1942892530 ; 73ce2ff_subH call _f_add push edx push eax push OFFSET $SG1436 ; '%I64d', 0aH, 00H call _printf add esp, 28 ret 0 _f_add_test ENDP _f_sub PROC mov eax, DWORD PTR _a$[esp-4] sub eax, DWORD PTR _b$[esp-4] mov edx, DWORD PTR _a$[esp] 404
  • 429. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION sbb edx, DWORD PTR _b$[esp] ret 0 _f_sub ENDP We can see in the f_add_test() function that each 64-bit value is passed using two 32-bit values, high part first, then low part. Addition and subtraction occur in pairs as well. In addition, the low 32-bit part are added first. If carry was occurred while adding, the CF flag is set. The following ADC instruction adds the high parts of the values, and also adds 1 if CF = 1. Subtraction also occurs in pairs. The first SUB may also turn on the CF flag, which is to be checked in the subsequent SBB instruction: if the carry flag is on, then 1 is also to be subtracted from the result. It is easy to see how the f_add() function result is then passed to printf(). Listing 24.6: GCC 4.8.1 -O1 -fno-inline _f_add: mov eax, DWORD PTR [esp+12] mov edx, DWORD PTR [esp+16] add eax, DWORD PTR [esp+4] adc edx, DWORD PTR [esp+8] ret _f_add_test: sub esp, 28 mov DWORD PTR [esp+8], 1972608889 ; 75939f79H mov DWORD PTR [esp+12], 5461 ; 00001555H mov DWORD PTR [esp], 1942892530 ; 73ce2ff_subH mov DWORD PTR [esp+4], 2874 ; 00000b3aH call _f_add mov DWORD PTR [esp+4], eax mov DWORD PTR [esp+8], edx mov DWORD PTR [esp], OFFSET FLAT:LC0 ; "%lld120" call _printf add esp, 28 ret _f_sub: mov eax, DWORD PTR [esp+4] mov edx, DWORD PTR [esp+8] sub eax, DWORD PTR [esp+12] sbb edx, DWORD PTR [esp+16] ret GCC code is the same. 24.2.2 ARM Listing 24.7: Optimizing Keil 6/2013 (ARM mode) f_add PROC ADDS r0,r0,r2 ADC r1,r1,r3 BX lr ENDP f_sub PROC SUBS r0,r0,r2 SBC r1,r1,r3 BX lr ENDP f_add_test PROC PUSH {r4,lr} LDR r2,|L0.68| ; 0x75939f79 LDR r3,|L0.72| ; 0x00001555 405
  • 430. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.2. ARGUMENTS PASSING, ADDITION, SUBTRACTION LDR r0,|L0.76| ; 0x73ce2ff2 LDR r1,|L0.80| ; 0x00000b3a BL f_add POP {r4,lr} MOV r2,r0 MOV r3,r1 ADR r0,|L0.84| ; "%I64dn" B __2printf ENDP |L0.68| DCD 0x75939f79 |L0.72| DCD 0x00001555 |L0.76| DCD 0x73ce2ff2 |L0.80| DCD 0x00000b3a |L0.84| DCB "%I64dn",0 The first 64-bit value is passed in R0 and R1 register pair, the second in R2 and R3 register pair. ARM has the ADC instruction as well (which counts carry flag) and SBC (“subtract with carry”). Important thing: when the low parts are added/subtracted, ADDS and SUBS instructions with -S suffix are used. The -S suffix stands for “set flags”, and flags (esp. carry flag) is what consequent ADC/SBC instructions definitely need. Otherwise, instructions without the -S suffix would do the job (ADD and SUB). 24.2.3 MIPS Listing 24.8: Optimizing GCC 4.4.5 (IDA) f_add: ; $a0 - high part of a ; $a1 - low part of a ; $a2 - high part of b ; $a3 - low part of b addu $v1, $a3, $a1 ; sum up low parts addu $a0, $a2, $a0 ; sum up high parts ; will carry generated while summing up low parts? ; if yes, set $v0 to 1 sltu $v0, $v1, $a3 jr $ra ; add 1 to high part of result if carry should be generated: addu $v0, $a0 ; branch delay slot ; $v0 - high part of result ; $v1 - low part of result f_sub: ; $a0 - high part of a ; $a1 - low part of a ; $a2 - high part of b ; $a3 - low part of b subu $v1, $a1, $a3 ; subtract low parts subu $v0, $a0, $a2 ; subtract high parts ; will carry generated while subtracting low parts? ; if yes, set $a0 to 1 sltu $a1, $v1 jr $ra ; subtract 1 from high part of result if carry should be generated: subu $v0, $a1 ; branch delay slot ; $v0 - high part of result ; $v1 - low part of result f_add_test: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) 406
  • 431. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lui $a1, 0x73CE lui $a3, 0x7593 li $a0, 0xB3A li $a3, 0x75939F79 li $a2, 0x1555 jal f_add li $a1, 0x73CE2FF2 lw $gp, 0x20+var_10($sp) lui $a0, ($LC0 >> 16) # "%lldn" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) la $a0, ($LC0 & 0xFFFF) # "%lldn" move $a3, $v1 move $a2, $v0 jr $t9 addiu $sp, 0x20 $LC0: .ascii "%lldn"<0> MIPS has no flags register, so there is no such information present after the execution of arithmetic operations. So there are no instructions like x86’s ADC and SBB. To know if the carry flag would be set, a comparison (using “SLTU” instruction) also occurs, which sets the destination register to 1 or 0. This 1 or 0 is then added or subtracted to/from the final result. 24.3 Multiplication, division #include <stdint.h> uint64_t f_mul (uint64_t a, uint64_t b) { return a*b; }; uint64_t f_div (uint64_t a, uint64_t b) { return a/b; }; uint64_t f_rem (uint64_t a, uint64_t b) { return a % b; }; 24.3.1 x86 Listing 24.9: Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_mul PROC push DWORD PTR _b$[esp] push DWORD PTR _b$[esp] push DWORD PTR _a$[esp+8] push DWORD PTR _a$[esp+8] call __allmul ; long long multiplication ret 0 _f_mul ENDP _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_div PROC push DWORD PTR _b$[esp] push DWORD PTR _b$[esp] push DWORD PTR _a$[esp+8] 407
  • 432. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION push DWORD PTR _a$[esp+8] call __aulldiv ; unsigned long long division ret 0 _f_div ENDP _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_rem PROC push DWORD PTR _b$[esp] push DWORD PTR _b$[esp] push DWORD PTR _a$[esp+8] push DWORD PTR _a$[esp+8] call __aullrem ; unsigned long long remainder ret 0 _f_rem ENDP Multiplication and division are more complex operations, so usually the compiler embeds calls to a library functions doing that. These functions are described here: E on page 950. Listing 24.10: Optimizing GCC 4.8.1 -fno-inline _f_mul: push ebx mov edx, DWORD PTR [esp+8] mov eax, DWORD PTR [esp+16] mov ebx, DWORD PTR [esp+12] mov ecx, DWORD PTR [esp+20] imul ebx, eax imul ecx, edx mul edx add ecx, ebx add edx, ecx pop ebx ret _f_div: sub esp, 28 mov eax, DWORD PTR [esp+40] mov edx, DWORD PTR [esp+44] mov DWORD PTR [esp+8], eax mov eax, DWORD PTR [esp+32] mov DWORD PTR [esp+12], edx mov edx, DWORD PTR [esp+36] mov DWORD PTR [esp], eax mov DWORD PTR [esp+4], edx call ___udivdi3 ; unsigned division add esp, 28 ret _f_rem: sub esp, 28 mov eax, DWORD PTR [esp+40] mov edx, DWORD PTR [esp+44] mov DWORD PTR [esp+8], eax mov eax, DWORD PTR [esp+32] mov DWORD PTR [esp+12], edx mov edx, DWORD PTR [esp+36] mov DWORD PTR [esp], eax mov DWORD PTR [esp+4], edx call ___umoddi3 ; unsigned modulo add esp, 28 ret GCC does the expected, but the multiplication code is inlined right in the function, thinking it could be more efficient. GCC has different library function names: D on page 949. 24.3.2 ARM Keil for thumb mode inserts library subroutine calls: 408
  • 433. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.3. MULTIPLICATION, DIVISION Listing 24.11: Optimizing Keil 6/2013 (thumb mode) ||f_mul|| PROC PUSH {r4,lr} BL __aeabi_lmul POP {r4,pc} ENDP ||f_div|| PROC PUSH {r4,lr} BL __aeabi_uldivmod POP {r4,pc} ENDP ||f_rem|| PROC PUSH {r4,lr} BL __aeabi_uldivmod MOVS r0,r2 MOVS r1,r3 POP {r4,pc} ENDP Keil for ARM mode, on the other hand, is able to produce 64-bit multiplication code: Listing 24.12: Optimizing Keil 6/2013 (ARM mode) ||f_mul|| PROC PUSH {r4,lr} UMULL r12,r4,r0,r2 MLA r1,r2,r1,r4 MLA r1,r0,r3,r1 MOV r0,r12 POP {r4,pc} ENDP ||f_div|| PROC PUSH {r4,lr} BL __aeabi_uldivmod POP {r4,pc} ENDP ||f_rem|| PROC PUSH {r4,lr} BL __aeabi_uldivmod MOV r0,r2 MOV r1,r3 POP {r4,pc} ENDP 24.3.3 MIPS Optimizing GCC for MIPS can generate 64-bit multiplication code, but has to call a library routine for 64-bit division: Listing 24.13: Optimizing GCC 4.4.5 (IDA) f_mul: mult $a2, $a1 mflo $v0 or $at, $zero ; NOP or $at, $zero ; NOP mult $a0, $a3 mflo $a0 addu $v0, $a0 or $at, $zero ; NOP multu $a3, $a1 mfhi $a2 mflo $v1 jr $ra addu $v0, $a2 f_div: 409
  • 434. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.4. SHIFTING RIGHT var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (__udivdi3 & 0xFFFF)($gp) or $at, $zero jalr $t9 or $at, $zero lw $ra, 0x20+var_4($sp) or $at, $zero jr $ra addiu $sp, 0x20 f_rem: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (__umoddi3 & 0xFFFF)($gp) or $at, $zero jalr $t9 or $at, $zero lw $ra, 0x20+var_4($sp) or $at, $zero jr $ra addiu $sp, 0x20 There are a lot of NOPs, probably delay slots filled after the multiplication instruction (it’s slower than other instructions, after all), but I’m not completely sure. 24.4 Shifting right #include <stdint.h> uint64_t f (uint64_t a) { return a>>7; }; 24.4.1 x86 Listing 24.14: Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _f PROC mov eax, DWORD PTR _a$[esp-4] mov edx, DWORD PTR _a$[esp] shrd eax, edx, 7 shr edx, 7 ret 0 _f ENDP Listing 24.15: Optimizing GCC 4.8.1 -fno-inline _f: mov edx, DWORD PTR [esp+8] mov eax, DWORD PTR [esp+4] 410
  • 435. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.5. CONVERTING 32-BIT VALUE INTO 64-BIT ONE shrd eax, edx, 7 shr edx, 7 ret Shifting also occurs in two passes: first the lower part is shifted, then the higher part. But the lower part is shifted with the help of the SHRD instruction, it shifts the value of EDX by 7 bits, but pulls new bits from EAX, i.e., from the higher part. The higher part is shifted using the more popular SHR instruction: indeed, the freed bits in the higher part must be filled with zeroes. 24.4.2 ARM ARM doesn’t have such instruction as SHRD in x86, so the Keil compiler ought to do this using simple shifts and OR operations: Listing 24.16: Optimizing Keil 6/2013 (ARM mode) ||f|| PROC LSR r0,r0,#7 ORR r0,r0,r1,LSL #25 LSR r1,r1,#7 BX lr ENDP Listing 24.17: Optimizing Keil 6/2013 (thumb mode) ||f|| PROC LSLS r2,r1,#25 LSRS r0,r0,#7 ORRS r0,r0,r2 LSRS r1,r1,#7 BX lr ENDP 24.4.3 MIPS GCC for MIPS follows the same algorithm as Keil does for thumb mode: Listing 24.18: Optimizing GCC 4.4.5 (IDA) f: sll $v0, $a0, 25 srl $v1, $a1, 7 or $v1, $v0, $v1 jr $ra srl $v0, $a0, 7 24.5 Converting 32-bit value into 64-bit one #include <stdint.h> int64_t f (int32_t a) { return a; }; 24.5.1 x86 Listing 24.19: Optimizing MSVC 2012 _a$ = 8 _f PROC mov eax, DWORD PTR _a$[esp-4] cdq ret 0 _f ENDP 411
  • 436. CHAPTER 24. 64-BIT VALUES IN 32-BIT ENVIRONMENT 24.5. CONVERTING 32-BIT VALUE INTO 64-BIT ONE Here we also run into necessity to extend a 32-bit signed value into a 64-bit signed one. Unsigned values are converted straightforwardly: all bits in the higher part must be set to 0. But this is not appropriate for signed data types: the sign has to be copied into the higher part of the resulting number. The CDQ instruction does that here, it takes its input value in EAX, extends it to 64-bit and leaves it in the EDX:EAX register pair. In other words, CDQ gets the number sign from EAX (by getting the most significant bit in EAX), and depending of it, sets all 32 bits in EDX to 0 or 1. Its operation is somewhat similar to the MOVSX instruction. 24.5.2 ARM Listing 24.20: Optimizing Keil 6/2013 (ARM mode) ||f|| PROC ASR r1,r0,#31 BX lr ENDP Keil for ARM is different: it just arithmetically shifts right the input value by 31 bits. As we know, the sign bit is MSB, and the arithmetical shift copies the sign bit into the “emerged” bits. So after “ASR r1,r0,#31”, R1 containing 0xFFFFFFFF if the input value was negative and 0 otherwise. R1 contains the high part of the resulting 64-bit value. In other words, this code just copies the MSB (sign bit) from the input value in R0 to all bits of the high 32-bit part of the resulting 64-bit value. 24.5.3 MIPS GCC for MIPS does the same as Keil did for ARM mode: Listing 24.21: Optimizing GCC 4.4.5 (IDA) f: sra $v0, $a0, 31 jr $ra move $v1, $a0 412
  • 437. CHAPTER 25. SIMD Chapter 25 SIMD SIMD is an acronym: Single Instruction, Multiple Data. As its name implies, it processes multiple data using only one instruction. Like the FPU, that CPU subsystem looks like a separate processor inside x86. SIMD began as MMX in x86. 8 new 64-bit registers appeared: MM0-MM7. Each MMX register can hold 2 32-bit values, 4 16-bit values or 8 bytes. For example, it is possible to add 8 8-bit values (bytes) simultaneously by adding two values in MMX registers. One simple example is a graphics editor that represents an image as a two dimensional array. When the user changes the brightness of the image, the editor must add or subtract a coefficient to/from each pixel value. For the sake of brevity if we say that the image is grayscale and each pixel is defined by one 8-bit byte, then it is possible to change the brightness of 8 pixels simultaneously. By the way, this is the reason why the saturation instructions are present in SIMD. When the user changes the brightness in the graphics editor, overflow and underflow is not desirable, so there are addition instructions in SIMD which are not adding anything if the maximum value is reached, etc. When MMX appeared, these registers were actually located in the FPU’s registers. It was possible to use either FPU or MMX at the same time. One might think that Intel saved on transistors, but in fact the reason of such symbiosis was simpler —older OSes that are not aware of the additional CPU registers would not save them at the context switch, but saving the FPU registers. Thus, MMX-enabled CPU + old OS + process utilizing MMX features will still work. SSE—is extension of the SIMD registers to 128 bits, now separate from the FPU. AVX—another extension, to 256 bits. Now about practical usage. Of course, memory copy routines (memcpy), memory comparing (memcmp) and so on. One more example: the DES encryption algorithm takes a 64-bit block and a 56-bit key, encrypt the block and produces a 64-bit result. The DES algorithm may be considered as a very large electronic circuit, with wires and AND/OR/NOT gates. Bitslice DES1 —is the idea of processing groups of blocks and keys simultaneously. Let’s say, variable of type unsigned int on x86 can hold up to 32 bits, so it is possible to store there intermediate results for 32 block-key pairs simultaneously, using 64+56 variables of type unsigned int. I wrote an utility to brute-force Oracle RDBMS passwords/hashes (ones based on DES), using slightly modified bitslice DES algorithm for SSE2 and AVX —now it is possible to encrypt 128 or 256 block-keys pairs simultaneously. http://go.yurichev.com/17313 25.1 Vectorization Vectorization2 is when, for example, you have a loop taking couple of arrays for input and producing one array. The loop body takes values from the input arrays, does something and puts the result into the output array. It is important that there is only a single operation applied to each element. Vectorization is to process several elements simultaneously. Vectorization is not very fresh technology: the author of this textbook saw it at least on the Cray Y-MP supercomputer line from 1988 when he played with its “lite” version Cray Y-MP EL 3 . For example: for (i = 0; i < 1024; i++) { C[i] = A[i]*B[i]; } This fragment of code takes elements from A and B, multiplies them and saves the result into C. If each array element we have is 32-bit int, then it is possible to load 4 elements from A into a 128-bit XMM-register, from B to another XMM-registers, and by executing PMULLD ( Multiply Packed Signed Dword Integers and Store Low Result) and PMULHW ( Multiply Packed Signed Integers and Store High Result), it is possible to get 4 64-bit products at once. 1http://go.yurichev.com/17329 2Wikipedia: vectorization 3Remotely. It is installed in the museum of supercomputers: http://go.yurichev.com/17081 413
  • 438. CHAPTER 25. SIMD 25.1. VECTORIZATION Thus, loop body execution count is 1024/4 instead of 1024, that is 4 times less and, of course, faster. 25.1.1 Addition example Some compilers can do vectorization automatically in simple cases, e.g., Intel C++4 . I wrote this tiny function: int f (int sz, int *ar1, int *ar2, int *ar3) { for (int i=0; i<sz; i++) ar3[i]=ar1[i]+ar2[i]; return 0; }; Intel C++ Let’s compile it with Intel C++ 11.1.051 win32: icl intel.cpp /QaxSSE2 /Faintel.asm /Ox We got (in IDA): ; int __cdecl f(int, int *, int *, int *) public ?f@@YAHHPAH00@Z ?f@@YAHHPAH00@Z proc near var_10 = dword ptr -10h sz = dword ptr 4 ar1 = dword ptr 8 ar2 = dword ptr 0Ch ar3 = dword ptr 10h push edi push esi push ebx push esi mov edx, [esp+10h+sz] test edx, edx jle loc_15B mov eax, [esp+10h+ar3] cmp edx, 6 jle loc_143 cmp eax, [esp+10h+ar2] jbe short loc_36 mov esi, [esp+10h+ar2] sub esi, eax lea ecx, ds:0[edx*4] neg esi cmp ecx, esi jbe short loc_55 loc_36: ; CODE XREF: f(int,int *,int *,int *)+21 cmp eax, [esp+10h+ar2] jnb loc_143 mov esi, [esp+10h+ar2] sub esi, eax lea ecx, ds:0[edx*4] cmp esi, ecx jb loc_143 loc_55: ; CODE XREF: f(int,int *,int *,int *)+34 cmp eax, [esp+10h+ar1] jbe short loc_67 mov esi, [esp+10h+ar1] sub esi, eax neg esi 4More about Intel C++ automatic vectorization: Excerpt: Effective Automatic Vectorization 414
  • 439. CHAPTER 25. SIMD 25.1. VECTORIZATION cmp ecx, esi jbe short loc_7F loc_67: ; CODE XREF: f(int,int *,int *,int *)+59 cmp eax, [esp+10h+ar1] jnb loc_143 mov esi, [esp+10h+ar1] sub esi, eax cmp esi, ecx jb loc_143 loc_7F: ; CODE XREF: f(int,int *,int *,int *)+65 mov edi, eax ; edi = ar1 and edi, 0Fh ; is ar1 16-byte aligned? jz short loc_9A ; yes test edi, 3 jnz loc_162 neg edi add edi, 10h shr edi, 2 loc_9A: ; CODE XREF: f(int,int *,int *,int *)+84 lea ecx, [edi+4] cmp edx, ecx jl loc_162 mov ecx, edx sub ecx, edi and ecx, 3 neg ecx add ecx, edx test edi, edi jbe short loc_D6 mov ebx, [esp+10h+ar2] mov [esp+10h+var_10], ecx mov ecx, [esp+10h+ar1] xor esi, esi loc_C1: ; CODE XREF: f(int,int *,int *,int *)+CD mov edx, [ecx+esi*4] add edx, [ebx+esi*4] mov [eax+esi*4], edx inc esi cmp esi, edi jb short loc_C1 mov ecx, [esp+10h+var_10] mov edx, [esp+10h+sz] loc_D6: ; CODE XREF: f(int,int *,int *,int *)+B2 mov esi, [esp+10h+ar2] lea esi, [esi+edi*4] ; is ar2+i*4 16-byte aligned? test esi, 0Fh jz short loc_109 ; yes! mov ebx, [esp+10h+ar1] mov esi, [esp+10h+ar2] loc_ED: ; CODE XREF: f(int,int *,int *,int *)+105 movdqu xmm1, xmmword ptr [ebx+edi*4] ; ar1+i*4 movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to XMM0 paddd xmm1, xmm0 movdqa xmmword ptr [eax+edi*4], xmm1 ; ar3+i*4 add edi, 4 cmp edi, ecx jb short loc_ED jmp short loc_127 loc_109: ; CODE XREF: f(int,int *,int *,int *)+E3 mov ebx, [esp+10h+ar1] mov esi, [esp+10h+ar2] loc_111: ; CODE XREF: f(int,int *,int *,int *)+125 415
  • 440. CHAPTER 25. SIMD 25.1. VECTORIZATION movdqu xmm0, xmmword ptr [ebx+edi*4] paddd xmm0, xmmword ptr [esi+edi*4] movdqa xmmword ptr [eax+edi*4], xmm0 add edi, 4 cmp edi, ecx jb short loc_111 loc_127: ; CODE XREF: f(int,int *,int *,int *)+107 ; f(int,int *,int *,int *)+164 cmp ecx, edx jnb short loc_15B mov esi, [esp+10h+ar1] mov edi, [esp+10h+ar2] loc_133: ; CODE XREF: f(int,int *,int *,int *)+13F mov ebx, [esi+ecx*4] add ebx, [edi+ecx*4] mov [eax+ecx*4], ebx inc ecx cmp ecx, edx jb short loc_133 jmp short loc_15B loc_143: ; CODE XREF: f(int,int *,int *,int *)+17 ; f(int,int *,int *,int *)+3A ... mov esi, [esp+10h+ar1] mov edi, [esp+10h+ar2] xor ecx, ecx loc_14D: ; CODE XREF: f(int,int *,int *,int *)+159 mov ebx, [esi+ecx*4] add ebx, [edi+ecx*4] mov [eax+ecx*4], ebx inc ecx cmp ecx, edx jb short loc_14D loc_15B: ; CODE XREF: f(int,int *,int *,int *)+A ; f(int,int *,int *,int *)+129 ... xor eax, eax pop ecx pop ebx pop esi pop edi retn loc_162: ; CODE XREF: f(int,int *,int *,int *)+8C ; f(int,int *,int *,int *)+9F xor ecx, ecx jmp short loc_127 ?f@@YAHHPAH00@Z endp The SSE2-related instructions are: • MOVDQU (Move Unaligned Double Quadword)— just loads 16 bytes from memory into a XMM-register. • PADDD (Add Packed Integers)— adds 4 pairs of 32-bit numbers and leaves the result in the first operand. By the way, no exception is raised in case of overflow and no flags are to be set, just the low 32 bits of the result are to be stored. If one of PADDD’s operands is the address of a value in memory, then the address must be aligned on a 16-byte boundary. If it is not aligned, an exception will be triggered 5 . • MOVDQA (Move Aligned Double Quadword) is the same as MOVDQU, but requires the address of the value in memory to be aligned on a 16-bit boundary. If it is not aligned, exception will be raised. MOVDQA works faster than MOVDQU, but requires aforesaid. So, these SSE2-instructions are to be executed only in case there are more than 4 pairs to work on and the pointer ar3 is aligned on a 16-byte boundary. Also, if ar2 is aligned on a 16-byte boundary as well, this fragment of code is to be executed: 5More about data alignment: Wikipedia: Data structure alignment 416
  • 441. CHAPTER 25. SIMD 25.1. VECTORIZATION movdqu xmm0, xmmword ptr [ebx+edi*4] ; ar1+i*4 paddd xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 movdqa xmmword ptr [eax+edi*4], xmm0 ; ar3+i*4 Otherwise, the value from ar2 is to be loaded into XMM0 using MOVDQU, which does not require aligned pointer, but may work slower: movdqu xmm1, xmmword ptr [ebx+edi*4] ; ar1+i*4 movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to XMM0 paddd xmm1, xmm0 movdqa xmmword ptr [eax+edi*4], xmm1 ; ar3+i*4 In all other cases, non-SSE2 code is to be executed. GCC GCC may also vectorize in simple cases6 , if the -O3 option is used and SSE2 support is turned on: -msse2. What we get (GCC 4.4.1): ; f(int, int *, int *, int *) public _Z1fiPiS_S_ _Z1fiPiS_S_ proc near var_18 = dword ptr -18h var_14 = dword ptr -14h var_10 = dword ptr -10h arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h arg_C = dword ptr 14h push ebp mov ebp, esp push edi push esi push ebx sub esp, 0Ch mov ecx, [ebp+arg_0] mov esi, [ebp+arg_4] mov edi, [ebp+arg_8] mov ebx, [ebp+arg_C] test ecx, ecx jle short loc_80484D8 cmp ecx, 6 lea eax, [ebx+10h] ja short loc_80484E8 loc_80484C1: ; CODE XREF: f(int,int *,int *,int *)+4B ; f(int,int *,int *,int *)+61 ... xor eax, eax nop lea esi, [esi+0] loc_80484C8: ; CODE XREF: f(int,int *,int *,int *)+36 mov edx, [edi+eax*4] add edx, [esi+eax*4] mov [ebx+eax*4], edx add eax, 1 cmp eax, ecx jnz short loc_80484C8 loc_80484D8: ; CODE XREF: f(int,int *,int *,int *)+17 ; f(int,int *,int *,int *)+A5 add esp, 0Ch xor eax, eax pop ebx pop esi pop edi 6More about GCC vectorization support: http://go.yurichev.com/17083 417
  • 442. CHAPTER 25. SIMD 25.1. VECTORIZATION pop ebp retn align 8 loc_80484E8: ; CODE XREF: f(int,int *,int *,int *)+1F test bl, 0Fh jnz short loc_80484C1 lea edx, [esi+10h] cmp ebx, edx jbe loc_8048578 loc_80484F8: ; CODE XREF: f(int,int *,int *,int *)+E0 lea edx, [edi+10h] cmp ebx, edx ja short loc_8048503 cmp edi, eax jbe short loc_80484C1 loc_8048503: ; CODE XREF: f(int,int *,int *,int *)+5D mov eax, ecx shr eax, 2 mov [ebp+var_14], eax shl eax, 2 test eax, eax mov [ebp+var_10], eax jz short loc_8048547 mov [ebp+var_18], ecx mov ecx, [ebp+var_14] xor eax, eax xor edx, edx nop loc_8048520: ; CODE XREF: f(int,int *,int *,int *)+9B movdqu xmm1, xmmword ptr [edi+eax] movdqu xmm0, xmmword ptr [esi+eax] add edx, 1 paddd xmm0, xmm1 movdqa xmmword ptr [ebx+eax], xmm0 add eax, 10h cmp edx, ecx jb short loc_8048520 mov ecx, [ebp+var_18] mov eax, [ebp+var_10] cmp ecx, eax jz short loc_80484D8 loc_8048547: ; CODE XREF: f(int,int *,int *,int *)+73 lea edx, ds:0[eax*4] add esi, edx add edi, edx add ebx, edx lea esi, [esi+0] loc_8048558: ; CODE XREF: f(int,int *,int *,int *)+CC mov edx, [edi] add eax, 1 add edi, 4 add edx, [esi] add esi, 4 mov [ebx], edx add ebx, 4 cmp ecx, eax jg short loc_8048558 add esp, 0Ch xor eax, eax pop ebx pop esi pop edi pop ebp 418
  • 443. CHAPTER 25. SIMD 25.1. VECTORIZATION retn loc_8048578: ; CODE XREF: f(int,int *,int *,int *)+52 cmp eax, esi jnb loc_80484C1 jmp loc_80484F8 _Z1fiPiS_S_ endp Almost the same, however, not as meticulously as Intel C++. 25.1.2 Memory copy example Let’s revisit the simple memcpy() example ( 14.2 on page 179): #include <stdio.h> void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt) { size_t i; for (i=0; i<cnt; i++) dst[i]=src[i]; }; And that’s what optimizations GCC 4.9.1 did: Listing 25.1: Optimizing GCC 4.9.1 x64 my_memcpy: ; RDI = destination address ; RSI = source address ; RDX = size of block test rdx, rdx je .L41 lea rax, [rdi+16] cmp rsi, rax lea rax, [rsi+16] setae cl cmp rdi, rax setae al or cl, al je .L13 cmp rdx, 22 jbe .L13 mov rcx, rsi push rbp push rbx neg rcx and ecx, 15 cmp rcx, rdx cmova rcx, rdx xor eax, eax test rcx, rcx je .L4 movzx eax, BYTE PTR [rsi] cmp rcx, 1 mov BYTE PTR [rdi], al je .L15 movzx eax, BYTE PTR [rsi+1] cmp rcx, 2 mov BYTE PTR [rdi+1], al je .L16 movzx eax, BYTE PTR [rsi+2] cmp rcx, 3 mov BYTE PTR [rdi+2], al je .L17 movzx eax, BYTE PTR [rsi+3] cmp rcx, 4 mov BYTE PTR [rdi+3], al je .L18 movzx eax, BYTE PTR [rsi+4] cmp rcx, 5 419
  • 444. CHAPTER 25. SIMD 25.1. VECTORIZATION mov BYTE PTR [rdi+4], al je .L19 movzx eax, BYTE PTR [rsi+5] cmp rcx, 6 mov BYTE PTR [rdi+5], al je .L20 movzx eax, BYTE PTR [rsi+6] cmp rcx, 7 mov BYTE PTR [rdi+6], al je .L21 movzx eax, BYTE PTR [rsi+7] cmp rcx, 8 mov BYTE PTR [rdi+7], al je .L22 movzx eax, BYTE PTR [rsi+8] cmp rcx, 9 mov BYTE PTR [rdi+8], al je .L23 movzx eax, BYTE PTR [rsi+9] cmp rcx, 10 mov BYTE PTR [rdi+9], al je .L24 movzx eax, BYTE PTR [rsi+10] cmp rcx, 11 mov BYTE PTR [rdi+10], al je .L25 movzx eax, BYTE PTR [rsi+11] cmp rcx, 12 mov BYTE PTR [rdi+11], al je .L26 movzx eax, BYTE PTR [rsi+12] cmp rcx, 13 mov BYTE PTR [rdi+12], al je .L27 movzx eax, BYTE PTR [rsi+13] cmp rcx, 15 mov BYTE PTR [rdi+13], al jne .L28 movzx eax, BYTE PTR [rsi+14] mov BYTE PTR [rdi+14], al mov eax, 15 .L4: mov r10, rdx lea r9, [rdx-1] sub r10, rcx lea r8, [r10-16] sub r9, rcx shr r8, 4 add r8, 1 mov r11, r8 sal r11, 4 cmp r9, 14 jbe .L6 lea rbp, [rsi+rcx] xor r9d, r9d add rcx, rdi xor ebx, ebx .L7: movdqa xmm0, XMMWORD PTR [rbp+0+r9] add rbx, 1 movups XMMWORD PTR [rcx+r9], xmm0 add r9, 16 cmp rbx, r8 jb .L7 add rax, r11 cmp r10, r11 je .L1 .L6: movzx ecx, BYTE PTR [rsi+rax] mov BYTE PTR [rdi+rax], cl 420
  • 445. CHAPTER 25. SIMD 25.1. VECTORIZATION lea rcx, [rax+1] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+1+rax] mov BYTE PTR [rdi+1+rax], cl lea rcx, [rax+2] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+2+rax] mov BYTE PTR [rdi+2+rax], cl lea rcx, [rax+3] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+3+rax] mov BYTE PTR [rdi+3+rax], cl lea rcx, [rax+4] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+4+rax] mov BYTE PTR [rdi+4+rax], cl lea rcx, [rax+5] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+5+rax] mov BYTE PTR [rdi+5+rax], cl lea rcx, [rax+6] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+6+rax] mov BYTE PTR [rdi+6+rax], cl lea rcx, [rax+7] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+7+rax] mov BYTE PTR [rdi+7+rax], cl lea rcx, [rax+8] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+8+rax] mov BYTE PTR [rdi+8+rax], cl lea rcx, [rax+9] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+9+rax] mov BYTE PTR [rdi+9+rax], cl lea rcx, [rax+10] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+10+rax] mov BYTE PTR [rdi+10+rax], cl lea rcx, [rax+11] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+11+rax] mov BYTE PTR [rdi+11+rax], cl lea rcx, [rax+12] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+12+rax] mov BYTE PTR [rdi+12+rax], cl lea rcx, [rax+13] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+13+rax] mov BYTE PTR [rdi+13+rax], cl lea rcx, [rax+14] cmp rdx, rcx jbe .L1 movzx edx, BYTE PTR [rsi+14+rax] mov BYTE PTR [rdi+14+rax], dl 421
  • 446. CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION .L1: pop rbx pop rbp .L41: rep ret .L13: xor eax, eax .L3: movzx ecx, BYTE PTR [rsi+rax] mov BYTE PTR [rdi+rax], cl add rax, 1 cmp rax, rdx jne .L3 rep ret .L28: mov eax, 14 jmp .L4 .L15: mov eax, 1 jmp .L4 .L16: mov eax, 2 jmp .L4 .L17: mov eax, 3 jmp .L4 .L18: mov eax, 4 jmp .L4 .L19: mov eax, 5 jmp .L4 .L20: mov eax, 6 jmp .L4 .L21: mov eax, 7 jmp .L4 .L22: mov eax, 8 jmp .L4 .L23: mov eax, 9 jmp .L4 .L24: mov eax, 10 jmp .L4 .L25: mov eax, 11 jmp .L4 .L26: mov eax, 12 jmp .L4 .L27: mov eax, 13 jmp .L4 25.2 SIMD strlen() implementation It has to be noted that the SIMD instructions can be inserted in C/C++ code via special macros7 . For MSVC, some of them are located in the intrin.h file. It is possible to implement the strlen() function8 using SIMD instructions that works 2-2.5 times faster than the common implementation. This function loads 16 characters into a XMM-register and check each against zero 9 . 7MSDN: MMX, SSE, and SSE2 Intrinsics 8strlen() —standard C library function for calculating string length 9The example is based on source code from: http://go.yurichev.com/17330. 422
  • 447. CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION size_t strlen_sse2(const char *str) { register size_t len = 0; const char *s=str; bool str_is_aligned=(((unsigned int)str)&0xFFFFFFF0) == (unsigned int)str; if (str_is_aligned==false) return strlen (str); __m128i xmm0 = _mm_setzero_si128(); __m128i xmm1; int mask = 0; for (;;) { xmm1 = _mm_load_si128((__m128i *)s); xmm1 = _mm_cmpeq_epi8(xmm1, xmm0); if ((mask = _mm_movemask_epi8(xmm1)) != 0) { unsigned long pos; _BitScanForward(&pos, mask); len += (size_t)pos; break; } s += sizeof(__m128i); len += sizeof(__m128i); }; return len; } Let’s compile it in MSVC 2010 with /Ox option: Listing 25.2: Optimizing MSVC 2010 _pos$75552 = -4 ; size = 4 _str$ = 8 ; size = 4 ?strlen_sse2@@YAIPBD@Z PROC ; strlen_sse2 push ebp mov ebp, esp and esp, -16 ; fffffff0H mov eax, DWORD PTR _str$[ebp] sub esp, 12 ; 0000000cH push esi mov esi, eax and esi, -16 ; fffffff0H xor edx, edx mov ecx, eax cmp esi, eax je SHORT $LN4@strlen_sse lea edx, DWORD PTR [eax+1] npad 3 ; align next label $LL11@strlen_sse: mov cl, BYTE PTR [eax] inc eax test cl, cl jne SHORT $LL11@strlen_sse sub eax, edx pop esi mov esp, ebp pop ebp ret 0 $LN4@strlen_sse: movdqa xmm1, XMMWORD PTR [eax] pxor xmm0, xmm0 pcmpeqb xmm1, xmm0 pmovmskb eax, xmm1 test eax, eax jne SHORT $LN9@strlen_sse 423
  • 448. CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION $LL3@strlen_sse: movdqa xmm1, XMMWORD PTR [ecx+16] add ecx, 16 ; 00000010H pcmpeqb xmm1, xmm0 add edx, 16 ; 00000010H pmovmskb eax, xmm1 test eax, eax je SHORT $LL3@strlen_sse $LN9@strlen_sse: bsf eax, eax mov ecx, eax mov DWORD PTR _pos$75552[esp+16], eax lea eax, DWORD PTR [ecx+edx] pop esi mov esp, ebp pop ebp ret 0 ?strlen_sse2@@YAIPBD@Z ENDP ; strlen_sse2 First, we check if the str pointer is aligned on a 16-byte boundary. If not, we call the generic strlen() implementation. Then, we load the next 16 bytes into the XMM1 register using MOVDQA. An observant reader might ask, why can’t MOVDQU be used here since it can load data from the memory regardless pointer alignment? Yes, it might be done in this way: if the pointer is aligned, load data using MOVDQA, if not —use the slower MOVDQU. But here we are may hit another caveat: In the Windows NT line of OS (but not limited to it), memory is allocated by pages of 4 KiB (4096 bytes). Each win32- process has 4 GiB available, but in fact, only some parts of the address space are connected to real physical memory. If the process is accessing an absent memory block, an exception is to be raised. That’s how VM works10 . So, a function loading 16 bytes at once may step over the border of an allocated memory block. Let’s say that the OS has allocated 8192 (0x2000) bytes at address 0x008c0000. Thus, the block is the bytes starting from address 0x008c0000 to 0x008c1fff inclusive. After the block, that is, starting from address 0x008c2000 there is nothing at all, e.g. the OS not allocated any memory there. Any attempt to access memory starting from that address will raise an exception. And let’s consider the example in which the program is holding a string that contains 5 characters almost at the end of a block, and that is not a crime. 0x008c1ff8 ’h’ 0x008c1ff9 ’e’ 0x008c1ffa ’l’ 0x008c1ffb ’l’ 0x008c1ffc ’o’ 0x008c1ffd ’x00’ 0x008c1ffe random noise 0x008c1fff random noise So, in normal conditions the program calls strlen(), passing it a pointer to the string 'hello' placed in memory at address 0x008c1ff8. strlen() reads one byte at a time until 0x008c1ffd, where there’s a zero byte, and then it stops. Now if we implement our own strlen() reading 16 byte at once, starting at any address, aligned or not, MOVDQU may attempt to load 16 bytes at once at address 0x008c1ff8 up to 0x008c2008, and then an exception will be raised. That situation is to be avoided, of course. So then we’ll work only with the addresses aligned on a 16 byte boundary, which in combination with the knowledge that the OS’ page size is usually aligned on a 16-byte boundary gives us some warranty that our function will not read from unallocated memory. Let’s get back to our function. _mm_setzero_si128()— is a macro generating pxor xmm0, xmm0 —it just clears the XMM0 register. _mm_load_si128()— is a macro for MOVDQA, it just loads 16 bytes from the address into the XMM1 register. _mm_cmpeq_epi8()— is a macro for PCMPEQB, an instruction that compares two XMM-registers bytewise. And if some byte was equals to the one in the other register, there will be 0xff at this point in the result or 0 if otherwise. For example. XMM1: 11223344556677880000000000000000 XMM0: 11ab3444007877881111111111111111 After the execution of pcmpeqb xmm1, xmm0, the XMM1 register contains: XMM1: ff0000ff0000ffff0000000000000000 10wikipedia 424
  • 449. CHAPTER 25. SIMD 25.2. SIMD STRLEN() IMPLEMENTATION In our case, this instruction compares each 16-byte block with a block of 16 zero-bytes, which was set in the XMM0 register by pxor xmm0, xmm0. The next macro is _mm_movemask_epi8() —that is the PMOVMSKB instruction. It is very useful with PCMPEQB. pmovmskb eax, xmm1 This instruction sets first EAX bit to 1 if the most significant bit of the first byte in XMM1 is 1. In other words, if the first byte of the XMM1 register is 0xff, then the first bit of EAX is to be 1, too. If the second byte in the XMM1 register is 0xff, then the second bit in EAX is to be set to 1. In other words, the instruction is answering the question “which bytes in XMM1 are 0xff?” and returns 16 bits in the EAX register. The other bits in the EAX register are to be cleared. By the way, do not forget about this quirk of our algorithm. There might be 16 bytes in the input like: 15 14 13 12 11 10 9 3 2 1 0 “h” “e” “l” “l” “o” 0 garbage 0 garbage It is the 'hello' string, terminating zero, and some random noise in memory. If we load these 16 bytes into XMM1 and compare them with the zeroed XMM0, we are getting something like 11 : XMM1: 0000ff00000000000000ff0000000000 This means that the instruction found two zero bytes, and it is not surprising. PMOVMSKB in our case will set EAX to (in binary representation): 0010000000100000b. Obviously, our function must take only the first zero bit and ignore the rest. The next instruction is BSF (Bit Scan Forward). This instruction finds the first bit set to 1 and stores its position into the first operand. EAX=0010000000100000b After the execution of bsf eax, eax, EAX contains 5, meaning 1 was found at the 5th bit position (starting from zero). MSVC has a macro for this instruction: _BitScanForward. Now it is simple. If a zero byte was found, its position is added to what we have already counted and now we have the return result. Almost all. By the way, it is also has to be noted that the MSVC compiler emitted two loop bodies side by side, for optimization. By the way, SSE 4.2 (that appeared in Intel Core i7) offers more instructions where these string manipulations might be even easier: http://go.yurichev.com/17331 11I use here order from MSB to LSB12 425
  • 450. CHAPTER 26. 64 BITS Chapter 26 64 bits 26.1 x86-64 It is a 64-bit extension to the x86 architecture. From the reverse engineer’s perspective, the most important changes are: • Almost all registers (except FPU and SIMD) were extended to 64 bits and got a R- prefix. 8 additional registers wer added. Now GPR’s are: RAX, RBX, RCX, RDX, RBP, RSP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15. It is still possible to access the older register parts as usual. For example, it is possible to access the lower 32-bit part of the RAX register using EAX: 7th (byte number) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL The new R8-R15 registers also have their lower parts: R8D-R15D (lower 32-bit parts), R8W-R15W (lower 16-bit parts), R8L-R15L (lower 8-bit parts). 7th (byte number) 6th 5th 4th 3rd 2nd 1st 0th R8 R8D R8W R8L The number of SIMD registers was doubled from 8 to 16: XMM0-XMM15. • In Win64, the function calling convention is slightly different, somewhat resembling fastcall ( 64.3 on page 664) . The first 4 arguments are stored in the RCX, RDX, R8, R9 registers, the rest —in the stack. The Caller function must also allocate 32 bytes so the callee may save there 4 first arguments and use these registers for its own needs. Short functions may use arguments just from registers, but larger ones may save their values on the stack. System V AMD64 ABI (Linux, *BSD, Mac OS X)[Mit13] also somewhat resembles fastcall, it uses 6 registers RDI, RSI, RDX, RCX, R8, R9 for the first 6 arguments. All the rest are passed via the stack. See also the section on calling conventions ( 64 on page 663). • The C/C++ int type is still 32-bit for compatibility. • All pointers are 64-bit now. This provokes irritation sometimes: now one needs twice as much memory for storing pointers, including cache mem- ory, despite the fact that x64 CPUs can address only 48 bits of external RAM. Since now the number of registers is doubled, the compilers have more space for maneuvering called register allocation. For us this implies that the emitted code containing less number of local variables. For example, the function that calculates the first S-box of the DES encryption algorithm processes 32/64/128/256 values at once (depending on DES_type type (uint32, uint64, SSE2 or AVX)) using the bitslice DES method (read more about this technique here ( 25 on page 413)): 426
  • 451. CHAPTER 26. 64 BITS 26.1. X86-64 /* * Generated S-box files. * * This software may be modified, redistributed, and used for any purpose, * so long as its origin is acknowledged. * * Produced by Matthew Kwan - March 1998 */ #ifdef _WIN64 #define DES_type unsigned __int64 #else #define DES_type unsigned int #endif void s1 ( DES_type a1, DES_type a2, DES_type a3, DES_type a4, DES_type a5, DES_type a6, DES_type *out1, DES_type *out2, DES_type *out3, DES_type *out4 ) { DES_type x1, x2, x3, x4, x5, x6, x7, x8; DES_type x9, x10, x11, x12, x13, x14, x15, x16; DES_type x17, x18, x19, x20, x21, x22, x23, x24; DES_type x25, x26, x27, x28, x29, x30, x31, x32; DES_type x33, x34, x35, x36, x37, x38, x39, x40; DES_type x41, x42, x43, x44, x45, x46, x47, x48; DES_type x49, x50, x51, x52, x53, x54, x55, x56; x1 = a3 & ~a5; x2 = x1 ^ a4; x3 = a3 & ~a4; x4 = x3 | a5; x5 = a6 & x4; x6 = x2 ^ x5; x7 = a4 & ~a5; x8 = a3 ^ a4; x9 = a6 & ~x8; x10 = x7 ^ x9; x11 = a2 | x10; x12 = x6 ^ x11; x13 = a5 ^ x5; x14 = x13 & x8; x15 = a5 & ~a4; x16 = x3 ^ x14; x17 = a6 | x16; x18 = x15 ^ x17; x19 = a2 | x18; x20 = x14 ^ x19; x21 = a1 & x20; x22 = x12 ^ ~x21; *out2 ^= x22; x23 = x1 | x5; x24 = x23 ^ x8; x25 = x18 & ~x2; x26 = a2 & ~x25; x27 = x24 ^ x26; x28 = x6 | x7; x29 = x28 ^ x25; x30 = x9 ^ x24; x31 = x18 & ~x30; x32 = a2 & x31; 427
  • 452. CHAPTER 26. 64 BITS 26.1. X86-64 x33 = x29 ^ x32; x34 = a1 & x33; x35 = x27 ^ x34; *out4 ^= x35; x36 = a3 & x28; x37 = x18 & ~x36; x38 = a2 | x3; x39 = x37 ^ x38; x40 = a3 | x31; x41 = x24 & ~x37; x42 = x41 | x3; x43 = x42 & ~a2; x44 = x40 ^ x43; x45 = a1 & ~x44; x46 = x39 ^ ~x45; *out1 ^= x46; x47 = x33 & ~x9; x48 = x47 ^ x39; x49 = x4 ^ x36; x50 = x49 & ~x5; x51 = x42 | x18; x52 = x51 ^ a5; x53 = a2 & ~x52; x54 = x50 ^ x53; x55 = a1 | x54; x56 = x48 ^ ~x55; *out3 ^= x56; } There are a lot of local variables. Of course, not all those going into the local stack. Let’s compile it with MSVC 2008 with /Ox option: Listing 26.1: Optimizing MSVC 2008 PUBLIC _s1 ; Function compile flags: /Ogtpy _TEXT SEGMENT _x6$ = -20 ; size = 4 _x3$ = -16 ; size = 4 _x1$ = -12 ; size = 4 _x8$ = -8 ; size = 4 _x4$ = -4 ; size = 4 _a1$ = 8 ; size = 4 _a2$ = 12 ; size = 4 _a3$ = 16 ; size = 4 _x33$ = 20 ; size = 4 _x7$ = 20 ; size = 4 _a4$ = 20 ; size = 4 _a5$ = 24 ; size = 4 tv326 = 28 ; size = 4 _x36$ = 28 ; size = 4 _x28$ = 28 ; size = 4 _a6$ = 28 ; size = 4 _out1$ = 32 ; size = 4 _x24$ = 36 ; size = 4 _out2$ = 36 ; size = 4 _out3$ = 40 ; size = 4 _out4$ = 44 ; size = 4 _s1 PROC sub esp, 20 ; 00000014H mov edx, DWORD PTR _a5$[esp+16] push ebx mov ebx, DWORD PTR _a4$[esp+20] push ebp push esi mov esi, DWORD PTR _a3$[esp+28] push edi mov edi, ebx not edi mov ebp, edi and edi, DWORD PTR _a5$[esp+32] 428
  • 453. CHAPTER 26. 64 BITS 26.1. X86-64 mov ecx, edx not ecx and ebp, esi mov eax, ecx and eax, esi and ecx, ebx mov DWORD PTR _x1$[esp+36], eax xor eax, ebx mov esi, ebp or esi, edx mov DWORD PTR _x4$[esp+36], esi and esi, DWORD PTR _a6$[esp+32] mov DWORD PTR _x7$[esp+32], ecx mov edx, esi xor edx, eax mov DWORD PTR _x6$[esp+36], edx mov edx, DWORD PTR _a3$[esp+32] xor edx, ebx mov ebx, esi xor ebx, DWORD PTR _a5$[esp+32] mov DWORD PTR _x8$[esp+36], edx and ebx, edx mov ecx, edx mov edx, ebx xor edx, ebp or edx, DWORD PTR _a6$[esp+32] not ecx and ecx, DWORD PTR _a6$[esp+32] xor edx, edi mov edi, edx or edi, DWORD PTR _a2$[esp+32] mov DWORD PTR _x3$[esp+36], ebp mov ebp, DWORD PTR _a2$[esp+32] xor edi, ebx and edi, DWORD PTR _a1$[esp+32] mov ebx, ecx xor ebx, DWORD PTR _x7$[esp+32] not edi or ebx, ebp xor edi, ebx mov ebx, edi mov edi, DWORD PTR _out2$[esp+32] xor ebx, DWORD PTR [edi] not eax xor ebx, DWORD PTR _x6$[esp+36] and eax, edx mov DWORD PTR [edi], ebx mov ebx, DWORD PTR _x7$[esp+32] or ebx, DWORD PTR _x6$[esp+36] mov edi, esi or edi, DWORD PTR _x1$[esp+36] mov DWORD PTR _x28$[esp+32], ebx xor edi, DWORD PTR _x8$[esp+36] mov DWORD PTR _x24$[esp+32], edi xor edi, ecx not edi and edi, edx mov ebx, edi and ebx, ebp xor ebx, DWORD PTR _x28$[esp+32] xor ebx, eax not eax mov DWORD PTR _x33$[esp+32], ebx and ebx, DWORD PTR _a1$[esp+32] and eax, ebp xor eax, ebx mov ebx, DWORD PTR _out4$[esp+32] xor eax, DWORD PTR [ebx] xor eax, DWORD PTR _x24$[esp+32] mov DWORD PTR [ebx], eax 429
  • 454. CHAPTER 26. 64 BITS 26.1. X86-64 mov eax, DWORD PTR _x28$[esp+32] and eax, DWORD PTR _a3$[esp+32] mov ebx, DWORD PTR _x3$[esp+36] or edi, DWORD PTR _a3$[esp+32] mov DWORD PTR _x36$[esp+32], eax not eax and eax, edx or ebx, ebp xor ebx, eax not eax and eax, DWORD PTR _x24$[esp+32] not ebp or eax, DWORD PTR _x3$[esp+36] not esi and ebp, eax or eax, edx xor eax, DWORD PTR _a5$[esp+32] mov edx, DWORD PTR _x36$[esp+32] xor edx, DWORD PTR _x4$[esp+36] xor ebp, edi mov edi, DWORD PTR _out1$[esp+32] not eax and eax, DWORD PTR _a2$[esp+32] not ebp and ebp, DWORD PTR _a1$[esp+32] and edx, esi xor eax, edx or eax, DWORD PTR _a1$[esp+32] not ebp xor ebp, DWORD PTR [edi] not ecx and ecx, DWORD PTR _x33$[esp+32] xor ebp, ebx not eax mov DWORD PTR [edi], ebp xor eax, ecx mov ecx, DWORD PTR _out3$[esp+32] xor eax, DWORD PTR [ecx] pop edi pop esi xor eax, ebx pop ebp mov DWORD PTR [ecx], eax pop ebx add esp, 20 ; 00000014H ret 0 _s1 ENDP 5 variables were allocated in the local stack by the compiler. Now let’s try the same thing in the 64-bit version of MSVC 2008: Listing 26.2: Optimizing MSVC 2008 a1$ = 56 a2$ = 64 a3$ = 72 a4$ = 80 x36$1$ = 88 a5$ = 88 a6$ = 96 out1$ = 104 out2$ = 112 out3$ = 120 out4$ = 128 s1 PROC $LN3: mov QWORD PTR [rsp+24], rbx mov QWORD PTR [rsp+32], rbp mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rsi 430
  • 455. CHAPTER 26. 64 BITS 26.1. X86-64 push rdi push r12 push r13 push r14 push r15 mov r15, QWORD PTR a5$[rsp] mov rcx, QWORD PTR a6$[rsp] mov rbp, r8 mov r10, r9 mov rax, r15 mov rdx, rbp not rax xor rdx, r9 not r10 mov r11, rax and rax, r9 mov rsi, r10 mov QWORD PTR x36$1$[rsp], rax and r11, r8 and rsi, r8 and r10, r15 mov r13, rdx mov rbx, r11 xor rbx, r9 mov r9, QWORD PTR a2$[rsp] mov r12, rsi or r12, r15 not r13 and r13, rcx mov r14, r12 and r14, rcx mov rax, r14 mov r8, r14 xor r8, rbx xor rax, r15 not rbx and rax, rdx mov rdi, rax xor rdi, rsi or rdi, rcx xor rdi, r10 and rbx, rdi mov rcx, rdi or rcx, r9 xor rcx, rax mov rax, r13 xor rax, QWORD PTR x36$1$[rsp] and rcx, QWORD PTR a1$[rsp] or rax, r9 not rcx xor rcx, rax mov rax, QWORD PTR out2$[rsp] xor rcx, QWORD PTR [rax] xor rcx, r8 mov QWORD PTR [rax], rcx mov rax, QWORD PTR x36$1$[rsp] mov rcx, r14 or rax, r8 or rcx, r11 mov r11, r9 xor rcx, rdx mov QWORD PTR x36$1$[rsp], rax mov r8, rsi mov rdx, rcx xor rdx, r13 not rdx and rdx, rdi mov r10, rdx and r10, r9 xor r10, rax 431
  • 456. CHAPTER 26. 64 BITS 26.2. ARM xor r10, rbx not rbx and rbx, r9 mov rax, r10 and rax, QWORD PTR a1$[rsp] xor rbx, rax mov rax, QWORD PTR out4$[rsp] xor rbx, QWORD PTR [rax] xor rbx, rcx mov QWORD PTR [rax], rbx mov rbx, QWORD PTR x36$1$[rsp] and rbx, rbp mov r9, rbx not r9 and r9, rdi or r8, r11 mov rax, QWORD PTR out1$[rsp] xor r8, r9 not r9 and r9, rcx or rdx, rbp mov rbp, QWORD PTR [rsp+80] or r9, rsi xor rbx, r12 mov rcx, r11 not rcx not r14 not r13 and rcx, r9 or r9, rdi and rbx, r14 xor r9, r15 xor rcx, rdx mov rdx, QWORD PTR a1$[rsp] not r9 not rcx and r13, r10 and r9, r11 and rcx, rdx xor r9, rbx mov rbx, QWORD PTR [rsp+72] not rcx xor rcx, QWORD PTR [rax] or r9, rdx not r9 xor rcx, r8 mov QWORD PTR [rax], rcx mov rax, QWORD PTR out3$[rsp] xor r9, r13 xor r9, QWORD PTR [rax] xor r9, r8 mov QWORD PTR [rax], r9 pop r15 pop r14 pop r13 pop r12 pop rdi pop rsi ret 0 s1 ENDP Nothing was allocated in the local stack by the compiler, x36 is synonym for a5. By the way, there are CPUs with much more GPR’s, e.g. Itanium (128 registers). 26.2 ARM 64-bit instructions appeared in ARMv8. 432
  • 457. CHAPTER 26. 64 BITS 26.3. FLOAT POINT NUMBERS 26.3 Float point numbers How float point numbers are processed in x86-64 is explained here: 27 on the previous page. 433
  • 458. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD Chapter 27 Working with floating point numbers using SIMD Of course, the FPU has remained in x86-compatible processors when the SIMD extensions were added. The SIMD extensions (SSE2) offer an easier way to work with floating-point numbers. The number format remains the same (IEEE 754). So, modern compilers (including those generating for x86-64) usually use SIMD instructions instead of FPU ones. It can be said that it’s good news, because it’s easier to work with them. We are going to reuse the examples from the FPU section here: 17 on page 208. 27.1 Simple example #include <stdio.h> double f (double a, double b) { return a/3.14 + b*4.1; }; int main() { printf ("%fn", f(1.2, 3.4)); }; 27.1.1 x64 Listing 27.1: Optimizing MSVC 2012 x64 __real@4010666666666666 DQ 04010666666666666r ; 4.1 __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 a$ = 8 b$ = 16 f PROC divsd xmm0, QWORD PTR __real@40091eb851eb851f mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 ret 0 f ENDP The input floating point values are passed in the XMM0-XMM3 registers, all the rest—via the stack 1 . a is passed in XMM0, b—via XMM1. The XMM-registers are 128-bit (as we know from the section about SIMD: 25 on page 413), but the double values are 64 bit, so only lower register half is used. DIVSD is an SSE-instruction that stands for “Divide Scalar Double-Precision Floating-Point Values”, it just divides one value of type double by another, stored in the lower halves of operands. The constants are encoded by compiler in IEEE 754 format. MULSD and ADDSD work just as the same, but do multiplication and addition. The result of the function’s execution in type double is left in the in XMM0 register. That is how non-optimizing MSVC works: 1MSDN: Parameter Passing 434
  • 459. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Listing 27.2: MSVC 2012 x64 __real@4010666666666666 DQ 04010666666666666r ; 4.1 __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 a$ = 8 b$ = 16 f PROC movsdx QWORD PTR [rsp+16], xmm1 movsdx QWORD PTR [rsp+8], xmm0 movsdx xmm0, QWORD PTR a$[rsp] divsd xmm0, QWORD PTR __real@40091eb851eb851f movsdx xmm1, QWORD PTR b$[rsp] mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 ret 0 f ENDP Slightly redundant. The input arguments are saved in the “shadow space” ( 8.2.1 on page 89), but only their lower register halves, i.e., only 64-bit values of type double. GCC produces the same code. 27.1.2 x86 I also compiled this example for x86. Despite the fact it’s generating for x86, MSVC 2012 uses SSE2 instructions: Listing 27.3: Non-optimizing MSVC 2012 x86 tv70 = -8 ; size = 8 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f PROC push ebp mov ebp, esp sub esp, 8 movsd xmm0, QWORD PTR _a$[ebp] divsd xmm0, QWORD PTR __real@40091eb851eb851f movsd xmm1, QWORD PTR _b$[ebp] mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 movsd QWORD PTR tv70[ebp], xmm0 fld QWORD PTR tv70[ebp] mov esp, ebp pop ebp ret 0 _f ENDP Listing 27.4: Optimizing MSVC 2012 x86 tv67 = 8 ; size = 8 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f PROC movsd xmm1, QWORD PTR _a$[esp-4] divsd xmm1, QWORD PTR __real@40091eb851eb851f movsd xmm0, QWORD PTR _b$[esp-4] mulsd xmm0, QWORD PTR __real@4010666666666666 addsd xmm1, xmm0 movsd QWORD PTR tv67[esp-4], xmm1 fld QWORD PTR tv67[esp-4] ret 0 _f ENDP It’s almost the same code, however, there are some differences related to calling conventions: 1) the arguments are passed not in XMM registers, but in the stack, like in the FPU examples ( 17 on page 208); 2) the result of the function is returned in ST(0) — in order to do so, it’s copied (through local variable tv) from one of the XMM registers to ST(0). 435
  • 460. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Let’s try the optimized example in OllyDbg: Figure 27.1: OllyDbg: MOVSD loads the value of a into XMM1 436
  • 461. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Figure 27.2: OllyDbg: DIVSD calculated quotient and stored it in XMM1 437
  • 462. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Figure 27.3: OllyDbg: MULSD calculated product and stored it in XMM0 438
  • 463. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Figure 27.4: OllyDbg: ADDSD adds value in XMM0 to XMM1 439
  • 464. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.1. SIMPLE EXAMPLE Figure 27.5: OllyDbg: FLD left function result in ST(0) We see that OllyDbg shows the XMM registers as pairs of double numbers, but only the lower part is used. Apparently, OllyDbg shows them in that format because the SSE2 instructions (suffixed with -SD) are executed right now. But of course, it’s possible to switch the register format and to see their contents as 4 float-numbers or just as 16 bytes. 440
  • 465. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.2. PASSING FLOATING POINT NUMBER VIA ARGUMENTS 27.2 Passing floating point number via arguments #include <math.h> #include <stdio.h> int main () { printf ("32.01 ^ 1.54 = %lfn", pow (32.01,1.54)); return 0; } They are passed in the lower halves of the XMM0-XMM3 registers. Listing 27.5: Optimizing MSVC 2012 x64 $SG1354 DB '32.01 ^ 1.54 = %lf', 0aH, 00H __real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01 __real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54 main PROC sub rsp, 40 ; 00000028H movsdx xmm1, QWORD PTR __real@3ff8a3d70a3d70a4 movsdx xmm0, QWORD PTR __real@40400147ae147ae1 call pow lea rcx, OFFSET FLAT:$SG1354 movaps xmm1, xmm0 movd rdx, xmm1 call printf xor eax, eax add rsp, 40 ; 00000028H ret 0 main ENDP There is no MOVSDX instruction in Intel [Int13] and AMD [AMD13a] manuals, there it is called just MOVSD. So there are two instructions sharing the same name in x86 (about the other see: A.6.2 on page 934). Apparently, Microsoft developers wanted to get rid of the mess, so they renamed it to MOVSDX. It just loads a value into the lower half of a XMM register. pow() takes arguments from XMM0 and XMM1, and returns result in XMM0. It is then moved to RDX for printf(). Why? Honestly speaking, I don’t know, maybe because printf()—is a variable arguments function? Listing 27.6: Optimizing GCC 4.4.6 x64 .LC2: .string "32.01 ^ 1.54 = %lfn" main: sub rsp, 8 movsd xmm1, QWORD PTR .LC0[rip] movsd xmm0, QWORD PTR .LC1[rip] call pow ; result is now in XMM0 mov edi, OFFSET FLAT:.LC2 mov eax, 1 ; number of vector registers passed call printf xor eax, eax add rsp, 8 ret .LC0: .long 171798692 .long 1073259479 .LC1: .long 2920577761 .long 1077936455 GCC generates clearer output. The value for printf() is passed in XMM0. By the way, here is a case when 1 is written into EAX for printf()—this implies that one argument will be passed in vector registers, just as the standard requires [Mit13]. 27.3 Comparison example 441
  • 466. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.3. COMPARISON EXAMPLE #include <stdio.h> double d_max (double a, double b) { if (a>b) return a; return b; }; int main() { printf ("%fn", d_max (1.2, 3.4)); printf ("%fn", d_max (5.6, -4)); }; 27.3.1 x64 Listing 27.7: Optimizing MSVC 2012 x64 a$ = 8 b$ = 16 d_max PROC comisd xmm0, xmm1 ja SHORT $LN2@d_max movaps xmm0, xmm1 $LN2@d_max: fatret 0 d_max ENDP Optimizing MSVC generates a code very easy to understand. COMISD is “Compare Scalar Ordered Double-Precision Floating-Point Values and Set EFLAGS”. Essentially, that is what it does. Non-optimizing MSVC generates more redundant code, but it is still not hard to understand: Listing 27.8: MSVC 2012 x64 a$ = 8 b$ = 16 d_max PROC movsdx QWORD PTR [rsp+16], xmm1 movsdx QWORD PTR [rsp+8], xmm0 movsdx xmm0, QWORD PTR a$[rsp] comisd xmm0, QWORD PTR b$[rsp] jbe SHORT $LN1@d_max movsdx xmm0, QWORD PTR a$[rsp] jmp SHORT $LN2@d_max $LN1@d_max: movsdx xmm0, QWORD PTR b$[rsp] $LN2@d_max: fatret 0 d_max ENDP However, GCC 4.4.6 did more optimizations and used the MAXSD (“Return Maximum Scalar Double-Precision Floating- Point Value”) instruction, which just choose the maximum value! Listing 27.9: Optimizing GCC 4.4.6 x64 d_max: maxsd xmm0, xmm1 ret 442
  • 467. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.4. CALCULATING MACHINE EPSILON: X64 AND SIMD 27.3.2 x86 Let’s compile this example in MSVC 2012 with optimization turned on: Listing 27.10: Optimizing MSVC 2012 x86 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _d_max PROC movsd xmm0, QWORD PTR _a$[esp-4] comisd xmm0, QWORD PTR _b$[esp-4] jbe SHORT $LN1@d_max fld QWORD PTR _a$[esp-4] ret 0 $LN1@d_max: fld QWORD PTR _b$[esp-4] ret 0 _d_max ENDP Almost the same, but the values of a and b are taken from the stack and the function result is left in ST(0). If we load this example in OllyDbg, we can see how the COMISD instruction compares values and sets/clears the CF and PF flags: Figure 27.6: OllyDbg: COMISD changed CF and PF flags 27.4 Calculating machine epsilon: x64 and SIMD Let’s revisit the “calculating machine epsilon” example for double listing.22.2.2. Now we compile it for x64: Listing 27.11: Optimizing MSVC 2012 x64 v$ = 8 calculate_machine_epsilon PROC movsdx QWORD PTR v$[rsp], xmm0 443
  • 468. CHAPTER 27. WORKING WITH FLOATING POINT NUMBERS USING SIMD 27.5. PSEUDO-RANDOM NUMBER GENERATOR EXAMPLE REVISITED movaps xmm1, xmm0 inc QWORD PTR v$[rsp] movsdx xmm0, QWORD PTR v$[rsp] subsd xmm0, xmm1 ret 0 calculate_machine_epsilon ENDP There is no way to add 1 to a value in 128-bit XMM register, so it must be placed into memory. There is, however, the ADDSD instruction (Add Scalar Double-Precision Floating-Point Values) which can add a value to the lowest 64-bit half of a XMM register while ignoring the higher one, but MSVC 2012 probably is not that good yet 2 . Nevertheless, the value is then reloaded to a XMM register and subtraction occurs. SUBSD is “Subtract Scalar Double- Precision Floating-Point Values”, i.e., it operates on the lower 64-bit part of 128-bit XMM register. The result is returned in the XMM0 register. 27.5 Pseudo-random number generator example revisited Let’s revisit “pseudo-random number generator example” example listing.22.1. If we compile this in MSVC 2012, it will use the SIMD instructions for the FPU. Listing 27.12: Optimizing MSVC 2012 __real@3f800000 DD 03f800000r ; 1 tv128 = -4 _tmp$ = -4 ?float_rand@@YAMXZ PROC push ecx call ?my_rand@@YAIXZ ; EAX=pseudorandom value and eax, 8388607 ; 007fffffH or eax, 1065353216 ; 3f800000H ; EAX=pseudorandom value & 0x007fffff | 0x3f800000 ; store it into local stack: mov DWORD PTR _tmp$[esp+4], eax ; reload it as float point number: movss xmm0, DWORD PTR _tmp$[esp+4] ; subtract 1.0: subss xmm0, DWORD PTR __real@3f800000 ; move value to ST0 by placing it in temporary variable... movss DWORD PTR tv128[esp+4], xmm0 ; ... and reloading it into ST0: fld DWORD PTR tv128[esp+4] pop ecx ret 0 ?float_rand@@YAMXZ ENDP All instructions have the -SS suffix, which stands for “Scalar Single”. “Scalar” implies that only one value is stored in the register. “Single” stands for float data type. 27.6 Summary Only the lower half of XMM registers is used in all examples here, to store number in IEEE 754 format. Essentially, all instructions prefixed by -SD (“Scalar Double-Precision”)—are instructions working with floating point numbers in IEEE 754 format, stored in the lower 64-bit half of a XMM register. And it is easier than in the FPU, probably because the SIMD extensions were evolved in a less chaotic way than the FPU ones in the past. The stack register model is not used. If you would try to replace double with float in these examples, the same instructions will be used, but prefixed with -SS (“Scalar Single-Precision”), for example, MOVSS, COMISS, ADDSS, etc. “Scalar” implies that the SIMD register containing only one value instead of several. Instructions working with several values in a register simultaneously have “Packed” in their name. Needless to say, the SSE2 instructions work with 64-bit IEEE 754 numbers (double), while the internal representation of the floating-point numbers in FPU is 80-bit numbers. Hence, the FPU may produce less round-off errors and as a consequence, FPU may give more precise calculation results. 2As an exercise, you may try to rework this code to eliminate the usage of the local stack. 444
  • 469. CHAPTER 28. MORE ABOUT ARM Chapter 28 More about ARM 28.1 Number sign (#) before number The Keil compiler, IDA and objdump precede all numbers with the “#” number sign, for example: listing.14.1.4. But when GCC 4.9 generates assembly language output, it doesn’t, for example: listing.39.3. The ARM listings in this book are somewhat mixed. I’m not sure which method is right. Supposedly, one has to obey the rules accepted in environment he/she works in. 28.2 Addressing modes This instruction is possible in ARM64: ldr x0, [x29,24] This means add 24 to the value in X29 and load the value from this address. Please note that 24 is inside the brackets. The meaning is different if the number is outside the brackets: ldr w4, [x1],28 This means load the value at the address in X1, then add 28 to X1. ARM allows you to add or subtract a constant to/from the address used for loading. And it’s possible to do that both before and after loading. There is no such addressing mode in x86, but it is present in some other processors, even on PDP-11. There is a legend that the pre-increment, post-increment, pre-decrement and post-decrement modes in PDP-11, were “guilty” for the appearance of such C language (which developed on PDP-11) constructs as *ptr++, *++ptr, *ptr--, *--ptr. By the way, this is one of the hard to memorize C features. This is how it is: C term ARM term C statement how it works Post-increment post-indexed addressing *ptr++ use *ptr value, then increment ptr pointer Post-decrement post-indexed addressing *ptr-- use *ptr value, then decrement ptr pointer Pre-increment pre-indexed addressing *++ptr increment ptr pointer, then use *ptr value Pre-decrement pre-indexed addressing *--ptr decrement ptr pointer, then use *ptr value Pre-indexing is marked with an exclamation mark in the ARM assembly language. For example, see line 2 in listing.3.15. Dennis Ritchie (one of the creators of the C language) mentioned that it probably was invented by Ken Thompson (another C creator) because this processor feature was present in PDP-7 [Rit86][Rit93]. Thus, C language compilers may use it, if it is present on the target processor. That’s very convenient for array processing. 28.3 Loading a constant into a register 28.3.1 32-bit ARM Aa we already know, all instructions have a length of 4 bytes in ARM mode and 2 bytes in Thumb mode. Then how can we load a 32-bit value into a register, if it’s not possible to encode it in one instruction? Let’s try: 445
  • 470. CHAPTER 28. MORE ABOUT ARM 28.3. LOADING A CONSTANT INTO A REGISTER unsigned int f() { return 0x12345678; }; Listing 28.1: GCC 4.6.3 -O3 ARM mode f: ldr r0, .L2 bx lr .L2: .word 305419896 ; 0x12345678 So, the 0x12345678 value is just stored aside in memory and loaded if needed. But it’s possible to get rid of the additional memory access. Listing 28.2: GCC 4.6.3 -O3 -march=armv7-a (ARM mode) movw r0, #22136 ; 0x5678 movt r0, #4660 ; 0x1234 bx lr We see that the value is loaded into the register by parts, the lower part first (using MOVW), then the higher (using MOVT). This implies that 2 instructions are necessary in ARM mode for loading a 32-bit value into a register. It’s not a real problem, because in fact there are not many constants in real code (except of 0 and 1). Does it mean that the two-instruction version is slower than one-instruction version? Doubtfully. Most likely, modern ARM processors are able to detect such sequences and execute them fast. On the other hand, IDA is able to detect such patterns in the code and disassembles this function as: MOV R0, 0x12345678 BX LR 28.3.2 ARM64 uint64_t f() { return 0x12345678ABCDEF01; }; Listing 28.3: GCC 4.9.1 -O3 mov x0, 61185 ; 0xef01 movk x0, 0xabcd, lsl 16 movk x0, 0x5678, lsl 32 movk x0, 0x1234, lsl 48 ret MOVK stands for “MOV Keep”, i.e., it writes a 16-bit value into the register, not touching the rest of the bits. The LSL suffix shifts left the value by 16, 32 and 48 bits at each step. The shifting is done before loading. This implies that 4 instructions are necessary to load a 64-bit value into a register. Storing floating-point number into register It’s possible to store a floating-point number into a D-register using only one instruction. For example: double a() { return 1.5; }; Listing 28.4: GCC 4.9.1 -O3 + objdump 0000000000000000 <a>: 0: 1e6f1000 fmov d0, #1.500000000000000000e+000 4: d65f03c0 ret 446
  • 471. CHAPTER 28. MORE ABOUT ARM 28.4. RELOCS IN ARM64 The number 1.5 was indeed encoded in a 32-bit instruction. But how? In ARM64, there are 8 bits in the FMOV instruction for encoding some floating-point numbers. The algorithm is called VFPExpandImm() in [ARM13a]. This is also called minifloat1 . I tried it with different values: the compiler is able to encode 30.0 and 31.0, but it couldn’t encode 32.0, as 8 bytes have to be allocated for this number in the IEEE 754 format: double a() { return 32; }; Listing 28.5: GCC 4.9.1 -O3 a: ldr d0, .LC0 ret .LC0: .word 0 .word 1077936128 28.4 Relocs in ARM64 As we know, there are 4-byte instructions in ARM64, so it is impossible to write a large number into a register using a single instruction. Nevertheless, an executable image can be loaded at any random address in memory, so that’s why relocs exists. Read more about them (in relation to Win32 PE): 68.2.6 on page 688. The address is formed using the ADRP and ADD instruction pair in ARM64. The first loads a 4Kb-page address and the second one adds the remainder. I compiled the example from “Hello, world!” (listing.6) in GCC (Linaro) 4.9 under win32: Listing 28.6: GCC (Linaro) 4.9 and objdump of object file ...>aarch64-linux-gnu-gcc.exe hw.c -c ...>aarch64-linux-gnu-objdump.exe -d hw.o ... 0000000000000000 <main>: 0: a9bf7bfd stp x29, x30, [sp,#-16]! 4: 910003fd mov x29, sp 8: 90000000 adrp x0, 0 <main> c: 91000000 add x0, x0, #0x0 10: 94000000 bl 0 <printf> 14: 52800000 mov w0, #0x0 // #0 18: a8c17bfd ldp x29, x30, [sp],#16 1c: d65f03c0 ret ...>aarch64-linux-gnu-objdump.exe -r hw.o ... RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE 0000000000000008 R_AARCH64_ADR_PREL_PG_HI21 .rodata 000000000000000c R_AARCH64_ADD_ABS_LO12_NC .rodata 0000000000000010 R_AARCH64_CALL26 printf So there are 3 relocs in this object file. • The first one takes the page address, cuts the lowest 12 bits and writes the remaining high 21 bits to the ADRP instruction’s bit fields. This is because we don’t need to encode the low 12 bits, and the ADRP instruction has space only for 21 bits. • The second one puts the 12 bits of the address relative to the page start into the ADD instruction’s bit fields. • The last, 26-bit one, is applied to the instruction at address 0x10 where the jump to the printf() function is. All ARM64 (and in ARM in ARM mode) instruction addresses have zeroes in the two lowest bits (because all instructions have a size of 4 bytes), so one need to encode only the highest 26 bits of 28-bit address space (±128MB). 1wikipedia 447
  • 472. CHAPTER 28. MORE ABOUT ARM 28.4. RELOCS IN ARM64 There are no such relocs in the executable file: because it’s known where the “Hello!” string is located, in which page, and the address of puts() is also known. So there are values set already in the ADRP, ADD and BL instructions (the linker has written them while linking): Listing 28.7: objdump of executable file 0000000000400590 <main>: 400590: a9bf7bfd stp x29, x30, [sp,#-16]! 400594: 910003fd mov x29, sp 400598: 90000000 adrp x0, 400000 <_init-0x3b8> 40059c: 91192000 add x0, x0, #0x648 4005a0: 97ffffa0 bl 400420 <puts@plt> 4005a4: 52800000 mov w0, #0x0 // #0 4005a8: a8c17bfd ldp x29, x30, [sp],#16 4005ac: d65f03c0 ret ... Contents of section .rodata: 400640 01000200 00000000 48656c6c 6f210000 ........Hello!.. As an example, let’s try to disassemble the BL instruction manually. 0x97ffffa0 is 10010111111111111111111110100000b. According to [ARM13a, p. C5.6.26], imm26 is the last 26 bits: imm26 = 11111111111111111110100000. It is 0x3FFFFA0, but the MSB is 1, so the number is negative, and in terms of modular arithmetic by modulo 232 , it is 0xFFFFFFA0. Again, by modulo 232 , 0xFFFFFFA0 * 4 = 0xFFFFFE80, and 0x4005a0 + FFFFFE80 = 0x400420 (please note: we consider the address of the BL instruction, not the current value of PC, which may be different! ). So the destination address is 0x400420. More about ARM64-related relocs: [ARM13b]. 448
  • 473. CHAPTER 29. MORE ABOUT MIPS Chapter 29 More about MIPS 29.1 Loading constants into register unsigned int f() { return 0x12345678; }; All instructions in MIPS, just like ARM, have a of 32-bit, so it’s not possible to embed a 32-bit constant into one instruction. So this translates to at least two instructions: the first loads the high part of the 32-bit number and the second one applies an OR operation, which effectively sets the low 16-bit part of the target register: Listing 29.1: GCC 4.4.5 -O3 (assembly output) li $2,305397760 # 0x12340000 j $31 ori $2,$2,0x5678 ; branch delay slot IDA is fully aware of such frequently encountered code patterns, so, for convenience it shows the last ORI instruction as the LI pseudoinstruction, which allegedly loads a full 32-bit number into the $V0 register. Listing 29.2: GCC 4.4.5 -O3 (IDA) lui $v0, 0x1234 jr $ra li $v0, 0x12345678 ; branch delay slot The GCC assembly output has the LI pseudoinstruction, but in fact, LUI (“Load Upper Imeddiate”) is there, which stores a 16-bit value into the high part of the register. 29.2 Further reading about MIPS [Swe10]. 449
  • 475. CHAPTER 30. SIGNED NUMBER REPRESENTATIONS Chapter 30 Signed number representations There are several methods for representing signed numbers1 , but “two’s complement” is the most popular one in computers. Here is a table for some byte values: binary hexadecimal unsigned signed (2’s complement) 01111111 0x7f 127 127 01111110 0x7e 126 126 ... 00000110 0x6 6 6 00000101 0x5 5 5 00000100 0x4 4 4 00000011 0x3 3 3 00000010 0x2 2 2 00000001 0x1 1 1 00000000 0x0 0 0 11111111 0xff 255 -1 11111110 0xfe 254 -2 11111101 0xfd 253 -3 11111100 0xfc 252 -4 11111011 0xfb 251 -5 11111010 0xfa 250 -6 ... 10000010 0x82 130 -126 10000001 0x81 129 -127 10000000 0x80 128 -128 The difference between signed and unsigned numbers is that if we represent 0xFFFFFFFE and 0x0000002 as unsigned, then the first number (4294967294) is bigger than the second one(2). If we represent them both as signed, the first one is to be −2, and it is smaller than the second (2). That is the reason why conditional jumps ( 12 on page 111) are present both for signed (e.g. JG, JL) and unsigned (JA, JBE) operations. For the sake of simplicity, that is what one need to know: • Number can be signed or unsigned. • C/C++ signed types: – int64_t (-9223372036854775806..9223372036854775807) or 0x8000000000000000..0x7FFFFFFFFFFFFFFF), – int (-2147483646..2147483647 or 0x80000000..0x7FFFFFFF), – char (-127..128 or 0x7F..0x80), – ssize_t. Unsigned: – uint64_t (0..18446744073709551615 or 0..0xFFFFFFFFFFFFFFFF), – unsigned int (0..4294967295 or 0..0xFFFFFFFF), – unsigned char (0..255 or 0..0xFF), 1wikipedia 451
  • 476. CHAPTER 30. SIGNED NUMBER REPRESENTATIONS – size_t. • Signed types have the sign in the most significant bit: 1 mean “minus”, 0 mean “plus”. • Promoting to a larger data types is simple: 24.5 on page 411. • Negation is simple: just invert all bits and add 1. We can remember that a number of inverse sign is located on the opposite side at the same proximity from zero. The addition of one is needed because zero is present in the middle. • The addition and subtraction operations work well for both signed and unsigned values. But for multiplication and division operations, x86 has different instructions: IDIV/IMUL for signed and DIV/MUL for unsigned. • Here are some more instructions that work with signed numbers: CBW/CWD/CWDE/CDQ/CDQE ( A.6.3 on page 936), MOVSX ( 15.1.1 on page 189), SAR ( A.6.3 on page 940). 452
  • 477. CHAPTER 31. ENDIANNESS Chapter 31 Endianness The endianness is a way of representing values in memory. 31.1 Big-endian The 0x12345678 value is represented in memory as: address in memory byte value +0 0x12 +1 0x34 +2 0x56 +3 0x78 Big-endian CPUs include Motorola 68k, IBM POWER. 31.2 Little-endian The 0x12345678 value is represented in memory as: address in memory byte value +0 0x78 +1 0x56 +2 0x34 +3 0x12 Little-endian CPUs include Intel x86. 31.3 Example I have big-endian MIPS Linux installed and ready in QEMU 1 . And I have compiled this simple example: #include <stdio.h> int main() { int v, i; v=123; printf ("%02X %02X %02X %02Xn", *(char*)&v, *(((char*)&v)+1), *(((char*)&v)+2), *(((char*)&v)+3)); }; And after running it I get: 1I’ve uploaded it here: http://go.yurichev.com/17008 453
  • 478. CHAPTER 31. ENDIANNESS 31.4. BI-ENDIAN root@debian-mips:~# ./a.out 00 00 00 7B That is it. 0x7B is 123 in decimal. In little-endian architectures, 7B is the first byte (you can check on x86 or x86-64), but here it is the last one, because the highest byte goes first. That’s why there are separate Linux distributions for MIPS (“mips” (big-endian) and “mipsel” (little-endian)). It is impos- sible for a binary compiled for one endianness to work on an OS with different endianness. There is another example of MIPS big-endiannes in this book: 21.4.3 on page 369. 31.4 Bi-endian CPUs that may switch between endianness are ARM, PowerPC, SPARC, MIPS, IA642 , etc. 31.5 Converting data The BSWAP instruction can be used for conversion. TCP/IP network data packets use the big-endian conventions, so that is why a program working on a little-endian archi- tecture has to convert the values. The htonl() and htons() functions are usually used. In TCP/IP, big-endian is also called “network byte order”, while byte order on the computer—“host byte order”. “host byte order” is little-endian on Intel x86 and other little-endian architectures, but it is big-endian on IBM POWER, so htonl() and htons() are not shuffle any bytes on latter. 2Intel Architecture 64 (Itanium): 93 on page 877 454
  • 479. CHAPTER 32. MEMORY Chapter 32 Memory There are 3 main types of memory: • Global memory. AKA “static memory allocation”. No need to allocate explicitly, the allocation is done just by declaring variables/arrays globally. These are global variables, residing in the data or constant segments. The are available globally (hence, considered as an anti-pattern). Not convenient for buffers/arrays, because they must have a fixed size. Buffer overflows that occur here usually overwrite variables or buffers reside next to them in memory. There’s an example in this book: 7.2 on page 65. • Stack. AKA “allocate on stack”. The allocation is done just by declaring variables/arrays locally in the function. These are usually local variables for the function. Sometimes these local variable are also available to descending functions (if one passes a pointer to a variable to the function to be executed). Allocation and deallocation are very fast, only SP needs to be shifted. But they’re also not convenient for buffers/arrays, because the buffer size has to be fixed, unless alloca() ( 5.2.4 on page 25) (or a variable-length array) is used. Buffer overflows usually overwrite important stack structures: 18.2 on page 264. • Heap. AKA “dynamic memory allocation”. Allocation is done by calling malloc()/free() or new/delete in C++. This is the most convenient method: the block size may be set at runtime. Resizing is possible (using realloc()), but can be slow. This is the slowest way to allocate memory: the memory allocator must support and update all control structures while allocating and deallocating. Buffer overflows usually overwrite these structures. Heap allocations are also source of memory leak problems: each memory block has to be deallocated explicitly, but one may forget about it, or do it incorrectly. Another problem is the “use after free”—using a memory block after free() was called on it, which is very dangerous. Example in this book: 21.2 on page 352. 455
  • 480. CHAPTER 33. CPU Chapter 33 CPU 33.1 Branch predictors Some modern compilers try to get rid of conditional jump instructions. Examples in this book are: 12.1.2 on page 122, 12.3 on page 129, 19.5.2 on page 330. This is because the branch predictor is not always perfect, so the compilers try to do without conditional jumps, if possible. Conditional instructions in ARM (like ADRcc) are one way, another one is the CMOVcc x86 instruction. 33.2 Data dependencies Modern CPUs are able to execute instructions simultaneously (OOE1 ), but in order to do so, the results of one instruction in a group must not influence the execution of others. Hence, the compiler endeavors to use instructions with minimal influence to the CPU state. That’s why the LEA instruction is so popular, because it does not modify CPU flags, while other arithmetic instructions do this. 1Out-of-order execution 456
  • 481. CHAPTER 34. HASH FUNCTIONS Chapter 34 Hash functions A very simple example is CRC32, an algorithm that provides “stronger” checksum for integrity checking purposes. it is impossible to restore the original text from the hash value, it has much less information: the input can be long, but CRC32’s result is always limited to 32 bits. But CRC32 is not cryptographically secure: it is known how to alter a text in a way that the resulting CRC32 hash value will be the one we need. Cryptographic hash functions are protected from this. Such functions are MD5, SHA1, etc., and they are widely used to hash user passwords in order to store them in a database. Indeed: an internet forum database may not contain user passwords (a stolen database can compromise all user’s passwords) but only hashes (a cracker can’t reveal passwords). Besides, an internet forum engine is not aware of your password, it has only to check if its hash is the same as the one in the database, and give you access if they match. One of the simplest password cracking methods is just to try hashing all possible passwords in order to see which is matching the resulting value that we need. Other methods are much more complex. 34.1 How one-way function works? One-way function is a function which is able to transform one value into another, while it is impossible (or very hard) to do reverse it back. Some people have difficulties while understanding how it’s possible at all. I’ll try to demonstrate it. We’ve got vector of 10 numbers in range 0..9, each encounters only once, for example: 4 6 0 1 3 5 7 8 9 2 Algorithm of simplest possible one-way function is: • take a number at zeroth position (4 in our case); • take a number at first position (6 in our case); • swap numbers at positions of 4 and 6. Let’s mark numbers on positions of 4 and 6: 4 6 0 1 3 5 7 8 9 2 ^ ^ Let’s swap them and we’ve got a result: 4 6 0 1 7 5 3 8 9 2 While looking at the result and even if we know algorithm, we can’t say unambiguously initial numbers set. Because first two numbers could be 0 and/or 1, and then they could be participate in swapping procedure. This is utterly simplified example for demonstration, real one-way functions may be much more complex. 457
  • 482. Part III Slightly more advanced examples 458
  • 483. CHAPTER 35. TEMPERATURE CONVERTING Chapter 35 Temperature converting Another very popular example in programming books for beginners is a small program that converts Fahrenheit temperature to Celsius or back. C = 5 ⋅ (F − 32) 9 I have also added simple error handling: 1) we must check if the user has entered a correct number; 2) we must check if the Celsius temperature is not below −273 (which is below absolute zero, as we may remember from school physics lessons). The exit() function terminates the program instantly, without returning to the caller function. 35.1 Integer values #include <stdio.h> #include <stdlib.h> int main() { int celsius, fahr; printf ("Enter temperature in Fahrenheit:n"); if (scanf ("%d", &fahr)!=1) { printf ("Error while parsing your inputn"); exit(0); }; celsius = 5 * (fahr-32) / 9; if (celsius<-273) { printf ("Error: incorrect temperature!n"); exit(0); }; printf ("Celsius: %dn", celsius); }; 35.1.1 Optimizing MSVC 2012 x86 Listing 35.1: Optimizing MSVC 2012 x86 $SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4230 DB '%d', 00H $SG4231 DB 'Error while parsing your input', 0aH, 00H $SG4233 DB 'Error: incorrect temperature!', 0aH, 00H $SG4234 DB 'Celsius: %d', 0aH, 00H _fahr$ = -4 ; size = 4 _main PROC push ecx push esi mov esi, DWORD PTR __imp__printf push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:' 459
  • 484. CHAPTER 35. TEMPERATURE CONVERTING 35.1. INTEGER VALUES call esi ; call printf() lea eax, DWORD PTR _fahr$[esp+12] push eax push OFFSET $SG4230 ; '%d' call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4231 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN9@main: $LN2@main: mov eax, DWORD PTR _fahr$[esp+8] add eax, -32 ; ffffffe0H lea ecx, DWORD PTR [eax+eax*4] mov eax, 954437177 ; 38e38e39H imul ecx sar edx, 1 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx cmp eax, -273 ; fffffeefH jge SHORT $LN1@main push OFFSET $SG4233 ; 'Error: incorrect temperature!' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN10@main: $LN1@main: push eax push OFFSET $SG4234 ; 'Celsius: %d' call esi ; call printf() add esp, 8 ; return 0 - by C99 standard xor eax, eax pop esi pop ecx ret 0 $LN8@main: _main ENDP What we can say about it: • The address of printf() is first loaded in the ESI register, so the subsequent printf() calls are done just by the CALL ESI instruction. It’s a very popular compiler technique, possible if several consequent calls to the same function are present in the code, and/or if there is a free register which can be used for this. • We see the ADD EAX, -32 instruction at the place where 32 has to be subtracted from the value. EAX = EAX + (−32) is equivalent to EAX = EAX − 32 and somehow, the compiler decided to use ADD instead of SUB. Maybe it’s worth it, but I’m not sure. • The LEA instruction is used when the value is to be multiplied by 5: lea ecx, DWORD PTR [eax+eax*4]. Yes, i + i ∗ 4 is equivalent to i ∗ 5 and LEA works faster then IMUL. By the way, the SHL EAX, 2 / ADD EAX, EAX instruction pair could be also used here instead— some compilers do it like. • The division by multiplication trick ( 41 on page 488) is also used here. • main() returns 0 if we don’t have return 0 at its end. The C99 standard tells us [ISO07, p. 5.1.2.2.3] that main() will return 0 in case the return statement is missing. This rule works only for the main() function. Though, MSVC doesn’t officially support C99, but maybe it support it partially? 35.1.2 Optimizing MSVC 2012 x64 The code is almost the same, but I’ve found INT 3 instructions after each exit() call: 460
  • 485. CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES xor ecx, ecx call QWORD PTR __imp_exit int 3 INT 3 is a debugger breakpoint. It is known that exit() is one of the functions which can never return 1 , so if it does, something really odd has happened and it’s time to load the debugger. 35.2 Floating-point values #include <stdio.h> #include <stdlib.h> int main() { double celsius, fahr; printf ("Enter temperature in Fahrenheit:n"); if (scanf ("%lf", &fahr)!=1) { printf ("Error while parsing your inputn"); exit(0); }; celsius = 5 * (fahr-32) / 9; if (celsius<-273) { printf ("Error: incorrect temperature!n"); exit(0); }; printf ("Celsius: %lfn", celsius); }; MSVC 2010 x86 uses FPU instructions… Listing 35.2: Optimizing MSVC 2010 x86 $SG4038 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4040 DB '%lf', 00H $SG4041 DB 'Error while parsing your input', 0aH, 00H $SG4043 DB 'Error: incorrect temperature!', 0aH, 00H $SG4044 DB 'Celsius: %lf', 0aH, 00H __real@c071100000000000 DQ 0c071100000000000r ; -273 __real@4022000000000000 DQ 04022000000000000r ; 9 __real@4014000000000000 DQ 04014000000000000r ; 5 __real@4040000000000000 DQ 04040000000000000r ; 32 _fahr$ = -8 ; size = 8 _main PROC sub esp, 8 push esi mov esi, DWORD PTR __imp__printf push OFFSET $SG4038 ; 'Enter temperature in Fahrenheit:' call esi ; call printf() lea eax, DWORD PTR _fahr$[esp+16] push eax push OFFSET $SG4040 ; '%lf' call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4041 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit 1another popular one is longjmp() 461
  • 486. CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES $LN2@main: fld QWORD PTR _fahr$[esp+12] fsub QWORD PTR __real@4040000000000000 ; 32 fmul QWORD PTR __real@4014000000000000 ; 5 fdiv QWORD PTR __real@4022000000000000 ; 9 fld QWORD PTR __real@c071100000000000 ; -273 fcomp ST(1) fnstsw ax test ah, 65 ; 00000041H jne SHORT $LN1@main push OFFSET $SG4043 ; 'Error: incorrect temperature!' fstp ST(0) call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN1@main: sub esp, 8 fstp QWORD PTR [esp] push OFFSET $SG4044 ; 'Celsius: %lf' call esi add esp, 12 ; 0000000cH ; return 0 - by C99 standard xor eax, eax pop esi add esp, 8 ret 0 $LN10@main: _main ENDP …but MSVC 2012 uses SIMD instructions instead: Listing 35.3: Optimizing MSVC 2010 x86 $SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4230 DB '%lf', 00H $SG4231 DB 'Error while parsing your input', 0aH, 00H $SG4233 DB 'Error: incorrect temperature!', 0aH, 00H $SG4234 DB 'Celsius: %lf', 0aH, 00H __real@c071100000000000 DQ 0c071100000000000r ; -273 __real@4040000000000000 DQ 04040000000000000r ; 32 __real@4022000000000000 DQ 04022000000000000r ; 9 __real@4014000000000000 DQ 04014000000000000r ; 5 _fahr$ = -8 ; size = 8 _main PROC sub esp, 8 push esi mov esi, DWORD PTR __imp__printf push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:' call esi ; call printf() lea eax, DWORD PTR _fahr$[esp+16] push eax push OFFSET $SG4230 ; '%lf' call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4231 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN9@main: $LN2@main: movsd xmm1, QWORD PTR _fahr$[esp+12] subsd xmm1, QWORD PTR __real@4040000000000000 ; 32 movsd xmm0, QWORD PTR __real@c071100000000000 ; -273 mulsd xmm1, QWORD PTR __real@4014000000000000 ; 5 divsd xmm1, QWORD PTR __real@4022000000000000 ; 9 comisd xmm0, xmm1 462
  • 487. CHAPTER 35. TEMPERATURE CONVERTING 35.2. FLOATING-POINT VALUES jbe SHORT $LN1@main push OFFSET $SG4233 ; 'Error: incorrect temperature!' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN10@main: $LN1@main: sub esp, 8 movsd QWORD PTR [esp], xmm1 push OFFSET $SG4234 ; 'Celsius: %lf' call esi ; call printf() add esp, 12 ; 0000000cH ; return 0 - by C99 standard xor eax, eax pop esi add esp, 8 ret 0 $LN8@main: _main ENDP Of course, SIMD instructions are available in x86 mode, including those working with floating point numbers. It’s somewhat easier to use them for calculations, so the new Microsoft compiler uses them. We can also see that the −273 value is loaded into XMM0 register too early. And that’s OK, because the compiler may emit instructions not in the order they are in the source code. 463
  • 488. CHAPTER 36. FIBONACCI NUMBERS Chapter 36 Fibonacci numbers Another widespread example used in programming textbooks is a recursive function that generates the Fibonacci numbers1 . The sequence is very simple: each consecutive number is the sum of the previous two. The first two numbers are 1’s or 0, 1 and 1. The sequence starts like this: 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181... 36.1 Example #1 The implementation is simple. This program generates the sequence until 21. #include <stdio.h> void fib (int a, int b, int limit) { printf ("%dn", a+b); if (a+b > limit) return; fib (b, a+b, limit); }; int main() { printf ("0n1n1n"); fib (1, 1, 20); }; Listing 36.1: MSVC 2010 x86 _TEXT SEGMENT _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _limit$ = 16 ; size = 4 _fib PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] push eax push OFFSET $SG2750 ; "%d" call DWORD PTR __imp__printf add esp, 8 mov ecx, DWORD PTR _limit$[ebp] push ecx mov edx, DWORD PTR _a$[ebp] add edx, DWORD PTR _b$[ebp] push edx mov eax, DWORD PTR _b$[ebp] push eax call _fib add esp, 12 1http://go.yurichev.com/17332 464
  • 489. CHAPTER 36. FIBONACCI NUMBERS 36.1. EXAMPLE #1 pop ebp ret 0 _fib ENDP _main PROC push ebp mov ebp, esp push OFFSET $SG2753 ; "0n1n1n" call DWORD PTR __imp__printf add esp, 4 push 20 push 1 push 1 call _fib add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP I want to illustrate the stack frames with this. 465
  • 490. CHAPTER 36. FIBONACCI NUMBERS 36.1. EXAMPLE #1 Let’s load the example in OllyDbg and trace to the last call of f(): Figure 36.1: OllyDbg: last call of f() 466
  • 491. CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2 Let’s investigate the stack more closely. I have added some comments to it 2 : 0035F940 00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F944 00000008 1st argument: a 0035F948 0000000D 2nd argument: b 0035F94C 00000014 3rd argument: limit 0035F950 /0035F964 saved EBP register 0035F954 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F958 |00000005 1st argument: a 0035F95C |00000008 2nd argument: b 0035F960 |00000014 3rd argument: limit 0035F964 ]0035F978 saved EBP register 0035F968 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F96C |00000003 1st argument: a 0035F970 |00000005 2nd argument: b 0035F974 |00000014 3rd argument: limit 0035F978 ]0035F98C saved EBP register 0035F97C |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F980 |00000002 1st argument: a 0035F984 |00000003 2nd argument: b 0035F988 |00000014 3rd argument: limit 0035F98C ]0035F9A0 saved EBP register 0035F990 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F994 |00000001 1st argument: a 0035F998 |00000002 2nd argument: b 0035F99C |00000014 3rd argument: limit 0035F9A0 ]0035F9B4 saved EBP register 0035F9A4 |00FD105C RETURN to fib.00FD105C from fib.00FD1000 0035F9A8 |00000001 1st argument: a 0035F9AC |00000001 2nd argument: b | prepared in main() for f1() 0035F9B0 |00000014 3rd argument: limit / 0035F9B4 ]0035F9F8 saved EBP register 0035F9B8 |00FD11D0 RETURN to fib.00FD11D0 from fib.00FD1040 0035F9BC |00000001 main() 1st argument: argc 0035F9C0 |006812C8 main() 2nd argument: argv | prepared in CRT for main() 0035F9C4 |00682940 main() 3rd argument: envp / The function is recursive 3 , hence stack looks like a “sandwich”. We see that the limit argument is always the same (0x14 or 20), but the a and b arguments are different for each call. There are also the RA-s and the saved EBP values. OllyDbg is able to determine the EBP-based frames, so it draws these brackets. The values inside each bracket make the stack frame, in other words, the stack area which each function incarnation uses as scratch space. We can also say that each function incarnation must not access stack elements beyond the boundaries of its frame (excluding function arguments), although it’s technically possible. It’s usually true, unless the function has bugs. Each saved EBP value is the address of the previous stack frame: this is the reason why some debuggers can easily divide the stack in frames and dump each function’s arguments. As we see here, each function incarnation prepares the arguments for the next function call. At the very end we see the 3 arguments for main(). argc is 1 (yes, indeed, I ran the program without command-line arguments). It’s easy to create a stack overflow: just remove (or comment) the limit check and it will crash with exception 0xC00000FD (stack overflow). 36.2 Example #2 My function has some redundancy, so let’s add a new local variable next and replace all “a+b” with it: #include <stdio.h> void fib (int a, int b, int limit) { int next=a+b; printf ("%dn", next); if (next > limit) return; fib (b, next, limit); }; 2By the way, it’s possible to select several entries in OllyDbg and copy them to the clipboard (Ctrl-C). That’s what I just did. 3i.e., it calls itself 467
  • 492. CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2 int main() { printf ("0n1n1n"); fib (1, 1, 20); }; This is the output of non-optimizing MSVC, so the next variable is actually allocated in the local stack: Listing 36.2: MSVC 2010 x86 _next$ = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _limit$ = 16 ; size = 4 _fib PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] mov DWORD PTR _next$[ebp], eax mov ecx, DWORD PTR _next$[ebp] push ecx push OFFSET $SG2751 ; '%d' call DWORD PTR __imp__printf add esp, 8 mov edx, DWORD PTR _next$[ebp] cmp edx, DWORD PTR _limit$[ebp] jle SHORT $LN1@fib jmp SHORT $LN2@fib $LN1@fib: mov eax, DWORD PTR _limit$[ebp] push eax mov ecx, DWORD PTR _next$[ebp] push ecx mov edx, DWORD PTR _b$[ebp] push edx call _fib add esp, 12 $LN2@fib: mov esp, ebp pop ebp ret 0 _fib ENDP _main PROC push ebp mov ebp, esp push OFFSET $SG2753 ; "0n1n1n" call DWORD PTR __imp__printf add esp, 4 push 20 push 1 push 1 call _fib add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP 468
  • 493. CHAPTER 36. FIBONACCI NUMBERS 36.2. EXAMPLE #2 Let’s load OllyDbg once again: Figure 36.2: OllyDbg: last call of f() Now the next variable is present in each frame. 469
  • 494. CHAPTER 36. FIBONACCI NUMBERS 36.3. SUMMARY Let’s investigate the stack more closely. I have added my comments again: 0029FC14 00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC18 00000008 1st argument: a 0029FC1C 0000000D 2nd argument: b 0029FC20 00000014 3rd argument: limit 0029FC24 0000000D "next" variable 0029FC28 /0029FC40 saved EBP register 0029FC2C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC30 |00000005 1st argument: a 0029FC34 |00000008 2nd argument: b 0029FC38 |00000014 3rd argument: limit 0029FC3C |00000008 "next" variable 0029FC40 ]0029FC58 saved EBP register 0029FC44 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC48 |00000003 1st argument: a 0029FC4C |00000005 2nd argument: b 0029FC50 |00000014 3rd argument: limit 0029FC54 |00000005 "next" variable 0029FC58 ]0029FC70 saved EBP register 0029FC5C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC60 |00000002 1st argument: a 0029FC64 |00000003 2nd argument: b 0029FC68 |00000014 3rd argument: limit 0029FC6C |00000003 "next" variable 0029FC70 ]0029FC88 saved EBP register 0029FC74 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC78 |00000001 1st argument: a 0029FC7C |00000002 2nd argument: b | prepared in f1() for next f1() 0029FC80 |00000014 3rd argument: limit / 0029FC84 |00000002 "next" variable 0029FC88 ]0029FC9C saved EBP register 0029FC8C |00E0106C RETURN to fib2.00E0106C from fib2.00E01000 0029FC90 |00000001 1st argument: a 0029FC94 |00000001 2nd argument: b | prepared in main() for f1() 0029FC98 |00000014 3rd argument: limit / 0029FC9C ]0029FCE0 saved EBP register 0029FCA0 |00E011E0 RETURN to fib2.00E011E0 from fib2.00E01050 0029FCA4 |00000001 main() 1st argument: argc 0029FCA8 |000812C8 main() 2nd argument: argv | prepared in CRT for main() 0029FCAC |00082940 main() 3rd argument: envp / Here we see it: the next value is calculated in each function incarnation, then passed as argument b to the next incarnation. 36.3 Summary Recursive functions are æsthetically nice, but technically may degrade performance because of their heavy stack usage. Everyone who writes performance critical code probably should should avoid recursion. For example, I once wrote a function to seek a particular node in a binary tree. As a recursive function it looked quite stylish but since additional time was to be spent at each function call for the prologue/epilogue, it was working a couple of times slower than an iterative (recursion-free) implementation. By the way, that is the reason compilers use tail call. 470
  • 495. CHAPTER 37. CRC32 CALCULATION EXAMPLE Chapter 37 CRC32 calculation example This is a very popular table-based CRC32 hash calculation technique1 . /* By Bob Jenkins, (c) 2006, Public Domain */ #include <stdio.h> #include <stddef.h> #include <string.h> typedef unsigned long ub4; typedef unsigned char ub1; static const ub4 crctab[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 1The source code was taken from here: http://go.yurichev.com/17327 471
  • 496. CHAPTER 37. CRC32 CALCULATION EXAMPLE 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; /* how to derive the values in crctab[] from polynomial 0xedb88320 */ void build_table() { ub4 i, j; for (i=0; i<256; ++i) { j = i; j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); printf("0x%.8lx, ", j); if (i%6 == 5) printf("n"); } } /* the hash function */ ub4 crc(const void *key, ub4 len, ub4 hash) { ub4 i; const ub1 *k = key; for (hash=len, i=0; i<len; ++i) hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ k[i]]; return hash; } /* To use, try "gcc -O crc.c -o crc; crc < crc.c" */ int main() { char s[1000]; while (gets(s)) printf("%.8lxn", crc(s, strlen(s), 0)); return 0; } We are interesting in the crc() function only. By the way, pay attention to the two loop initializers in the for() statement: hash=len, i=0. The C/C++ standard allows this, of course. The emitted code will contain two operations in the loop initialization part instead of one. Let’s compile it in MSVC with optimization (/Ox). For the sake of brevity, only the crc() function is listed here, with my comments. _key$ = 8 ; size = 4 _len$ = 12 ; size = 4 _hash$ = 16 ; size = 4 _crc PROC mov edx, DWORD PTR _len$[esp-4] xor ecx, ecx ; i will be stored in ECX mov eax, edx test edx, edx jbe SHORT $LN1@crc push ebx push esi mov esi, DWORD PTR _key$[esp+4] ; ESI = key push edi $LL3@crc: ; work with bytes using only 32-bit registers. byte from address key+i we store into EDI movzx edi, BYTE PTR [ecx+esi] mov ebx, eax ; EBX = (hash = len) and ebx, 255 ; EBX = hash & 0xff 472
  • 497. CHAPTER 37. CRC32 CALCULATION EXAMPLE ; XOR EDI, EBX (EDI=EDI^EBX) - this operation uses all 32 bits of each register ; but other bits (8-31) are cleared all time, so its OK' ; these are cleared because, as for EDI, it was done by MOVZX instruction above ; high bits of EBX was cleared by AND EBX, 255 instruction above (255 = 0xff) xor edi, ebx ; EAX=EAX>>8; bits 24-31 taken "from nowhere" will be cleared shr eax, 8 ; EAX=EAX^crctab[EDI*4] - choose EDI-th element from crctab[] table xor eax, DWORD PTR _crctab[edi*4] inc ecx ; i++ cmp ecx, edx ; i<len ? jb SHORT $LL3@crc ; yes pop edi pop esi pop ebx $LN1@crc: ret 0 _crc ENDP Let’s try the same in GCC 4.4.1 with -O3 option: public crc crc proc near key = dword ptr 8 hash = dword ptr 0Ch push ebp xor edx, edx mov ebp, esp push esi mov esi, [ebp+key] push ebx mov ebx, [ebp+hash] test ebx, ebx mov eax, ebx jz short loc_80484D3 nop ; padding lea esi, [esi+0] ; padding; works as NOP (ESI does not changing here) loc_80484B8: mov ecx, eax ; save previous state of hash to ECX xor al, [esi+edx] ; AL=*(key+i) add edx, 1 ; i++ shr ecx, 8 ; ECX=hash>>8 movzx eax, al ; EAX=*(key+i) mov eax, dword ptr ds:crctab[eax*4] ; EAX=crctab[EAX] xor eax, ecx ; hash=EAX^ECX cmp ebx, edx ja short loc_80484B8 loc_80484D3: pop ebx pop esi pop ebp retn crc endp GCC has aligned the loop start on a 8-byte boundary by adding NOP and lea esi, [esi+0] (that is an idle operation too). Read more about it in npad section ( 88 on page 866). 473
  • 498. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE Chapter 38 Network address calculation example As we know, a TCP/IP address (IPv4) consists of four numbers in the 0...255 range, i.e., four bytes. Four bytes can be fit in a 32-bit variable easily, so an IPv4 host address, network mask or network address can all be 32-bit integers. From the user’s point of view, the network mask is defined as four numbers and is formatted like 255.255.255.0 or so, but network engineers (sysadmins) use a more compact notation (CIDR1 ), like /8, /16 or similar. This notation just defines the number of bits the mask has, starting at the MSB. Mask Hosts Usable Netmask Hex mask /30 4 2 255.255.255.252 fffffffc /29 8 6 255.255.255.248 fffffff8 /28 16 14 255.255.255.240 fffffff0 /27 32 30 255.255.255.224 ffffffe0 /26 64 62 255.255.255.192 ffffffc0 /24 256 254 255.255.255.0 ffffff00 class C network /23 512 510 255.255.254.0 fffffe00 /22 1024 1022 255.255.252.0 fffffc00 /21 2048 2046 255.255.248.0 fffff800 /20 4096 4094 255.255.240.0 fffff000 /19 8192 8190 255.255.224.0 ffffe000 /18 16384 16382 255.255.192.0 ffffc000 /17 32768 32766 255.255.128.0 ffff8000 /16 65536 65534 255.255.0.0 ffff0000 class B network /8 16777216 16777214 255.0.0.0 ff000000 class A network Here is a small example, which calculates the network address by applying the network mask to the host address. #include <stdio.h> #include <stdint.h> uint32_t form_IP (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4) { return (ip1<<24) | (ip2<<16) | (ip3<<8) | ip4; }; void print_as_IP (uint32_t a) { printf ("%d.%d.%d.%dn", (a>>24)&0xFF, (a>>16)&0xFF, (a>>8)&0xFF, (a)&0xFF); }; // bit=31..0 uint32_t set_bit (uint32_t input, int bit) { return input=input|(1<<bit); }; uint32_t form_netmask (uint8_t netmask_bits) { 1Classless Inter-Domain Routing 474
  • 499. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.1. CALC_NETWORK_ADDRESS() uint32_t netmask=0; uint8_t i; for (i=0; i<netmask_bits; i++) netmask=set_bit(netmask, 31-i); return netmask; }; void calc_network_address (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint8_t ⤦ netmask_bits) { uint32_t netmask=form_netmask(netmask_bits); uint32_t ip=form_IP(ip1, ip2, ip3, ip4); uint32_t netw_adr; printf ("netmask="); print_as_IP (netmask); netw_adr=ip&netmask; printf ("network address="); print_as_IP (netw_adr); }; int main() { calc_network_address (10, 1, 2, 4, 24); // 10.1.2.4, /24 calc_network_address (10, 1, 2, 4, 8); // 10.1.2.4, /8 calc_network_address (10, 1, 2, 4, 25); // 10.1.2.4, /25 calc_network_address (10, 1, 2, 64, 26); // 10.1.2.4, /26 }; 38.1 calc_network_address() calc_network_address() function is simplest one: it just ANDs the host address with the network mask, resulting in the network address. Listing 38.1: Optimizing MSVC 2012 /Ob0 1 _ip1$ = 8 ; size = 1 2 _ip2$ = 12 ; size = 1 3 _ip3$ = 16 ; size = 1 4 _ip4$ = 20 ; size = 1 5 _netmask_bits$ = 24 ; size = 1 6 _calc_network_address PROC 7 push edi 8 push DWORD PTR _netmask_bits$[esp] 9 call _form_netmask 10 push OFFSET $SG3045 ; 'netmask=' 11 mov edi, eax 12 call DWORD PTR __imp__printf 13 push edi 14 call _print_as_IP 15 push OFFSET $SG3046 ; 'network address=' 16 call DWORD PTR __imp__printf 17 push DWORD PTR _ip4$[esp+16] 18 push DWORD PTR _ip3$[esp+20] 19 push DWORD PTR _ip2$[esp+24] 20 push DWORD PTR _ip1$[esp+28] 21 call _form_IP 22 and eax, edi ; network address = host address & netmask 23 push eax 24 call _print_as_IP 25 add esp, 36 26 pop edi 27 ret 0 28 _calc_network_address ENDP 475
  • 500. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.2. FORM_IP() At line 22 we see the most important AND— here the network address is calculated. 38.2 form_IP() The form_IP() function just puts all 4 bytes into a 32-bit value. Here is how it is usually done: • Allocate a variable for the return value. Set it to 0. • Take the fourth (lowest) byte, apply OR operation to this byte and return the value. The return value contain the 4th byte now. • Take the third byte, shift it left by 8 bits. You’ll get a value like 0x0000bb00 where bb is your third byte. Apply the OR operation to the resulting value and it. The return value has contained 0x000000aa so far, so ORing the values will produce a value like 0x0000bbaa. • Take the second byte, shift it left by 16 bits. You’ll get a value like 0x00cc0000, where cc is your second byte. Apply the OR operation to the resulting value and return it. The return value has contained 0x0000bbaa so far, so ORing the values will produce a value like 0x00ccbbaa. • Take the first byte, shift it left by 24 bits. You’ll get a value like 0xdd000000, where dd is your first byte. Apply the OR operation to the resulting value and return it. The return value contain 0x00ccbbaa so far, so ORing the values will produce a value like 0xddccbbaa. And this is how it’s done by non-optimizing MSVC 2012: Listing 38.2: Non-optimizing MSVC 2012 ; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa". _ip1$ = 8 ; size = 1 _ip2$ = 12 ; size = 1 _ip3$ = 16 ; size = 1 _ip4$ = 20 ; size = 1 _form_IP PROC push ebp mov ebp, esp movzx eax, BYTE PTR _ip1$[ebp] ; EAX=000000dd shl eax, 24 ; EAX=dd000000 movzx ecx, BYTE PTR _ip2$[ebp] ; ECX=000000cc shl ecx, 16 ; ECX=00cc0000 or eax, ecx ; EAX=ddcc0000 movzx edx, BYTE PTR _ip3$[ebp] ; EDX=000000bb shl edx, 8 ; EDX=0000bb00 or eax, edx ; EAX=ddccbb00 movzx ecx, BYTE PTR _ip4$[ebp] ; ECX=000000aa or eax, ecx ; EAX=ddccbbaa pop ebp ret 0 _form_IP ENDP Well, the order is different, but, of course, the order of the operations doesn’t matters. Optimizing MSVC 2012 does essentially the same, but in a different way: Listing 38.3: Optimizing MSVC 2012 /Ob0 ; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa". _ip1$ = 8 ; size = 1 _ip2$ = 12 ; size = 1 _ip3$ = 16 ; size = 1 _ip4$ = 20 ; size = 1 476
  • 501. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.3. PRINT_AS_IP() _form_IP PROC movzx eax, BYTE PTR _ip1$[esp-4] ; EAX=000000dd movzx ecx, BYTE PTR _ip2$[esp-4] ; ECX=000000cc shl eax, 8 ; EAX=0000dd00 or eax, ecx ; EAX=0000ddcc movzx ecx, BYTE PTR _ip3$[esp-4] ; ECX=000000bb shl eax, 8 ; EAX=00ddcc00 or eax, ecx ; EAX=00ddccbb movzx ecx, BYTE PTR _ip4$[esp-4] ; ECX=000000aa shl eax, 8 ; EAX=ddccbb00 or eax, ecx ; EAX=ddccbbaa ret 0 _form_IP ENDP We could say that each byte is written to the lowest 8 bits of the return value, and then the return value is shifted left by one byte at each step. Repeat 4 times for each input byte. That’s it! Unfortunately, there are probably no other ways to do it. I’ve never heard of a CPUs or ISAs which has instruction for composing a value from bits or bytes. It’s all usually done by bit shifting and ORing. 38.3 print_as_IP() print_as_IP() does the inverse: splitting a 32-bit value into 4 bytes. Slicing works somewhat simpler: just shift input value by 24, 16, 8 or 0 bits, take the bits from zeroth to seventh (lowest byte), and that’s it: Listing 38.4: Non-optimizing MSVC 2012 _a$ = 8 ; size = 4 _print_as_IP PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] ; EAX=ddccbbaa and eax, 255 ; EAX=000000aa push eax mov ecx, DWORD PTR _a$[ebp] ; ECX=ddccbbaa shr ecx, 8 ; ECX=00ddccbb and ecx, 255 ; ECX=000000bb push ecx mov edx, DWORD PTR _a$[ebp] ; EDX=ddccbbaa shr edx, 16 ; EDX=0000ddcc and edx, 255 ; EDX=000000cc push edx mov eax, DWORD PTR _a$[ebp] ; EAX=ddccbbaa shr eax, 24 ; EAX=000000dd and eax, 255 ; probably redundant instruction ; EAX=000000dd push eax push OFFSET $SG2973 ; '%d.%d.%d.%d' 477
  • 502. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.4. FORM_NETMASK() AND SET_BIT() call DWORD PTR __imp__printf add esp, 20 pop ebp ret 0 _print_as_IP ENDP Optimizing MSVC 2012 does almost the same, but without unnecessary reloading of the input value: Listing 38.5: Optimizing MSVC 2012 /Ob0 _a$ = 8 ; size = 4 _print_as_IP PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=ddccbbaa movzx eax, cl ; EAX=000000aa push eax mov eax, ecx ; EAX=ddccbbaa shr eax, 8 ; EAX=00ddccbb and eax, 255 ; EAX=000000bb push eax mov eax, ecx ; EAX=ddccbbaa shr eax, 16 ; EAX=0000ddcc and eax, 255 ; EAX=000000cc push eax ; ECX=ddccbbaa shr ecx, 24 ; ECX=000000dd push ecx push OFFSET $SG3020 ; '%d.%d.%d.%d' call DWORD PTR __imp__printf add esp, 20 ret 0 _print_as_IP ENDP 38.4 form_netmask() and set_bit() form_netmask() makes a network mask value from CIDR notation. Of course, it would be much effective to use here some kind of a precalculated table, but I wrote it in this way intentionally, to demonstrate bit shifts. I also wrote a separate function set_bit(). It’s a not very good idea to create a function for such primitive operation, but it would be easy to understand how it all works. Listing 38.6: Optimizing MSVC 2012 /Ob0 _input$ = 8 ; size = 4 _bit$ = 12 ; size = 4 _set_bit PROC mov ecx, DWORD PTR _bit$[esp-4] mov eax, 1 shl eax, cl or eax, DWORD PTR _input$[esp-4] ret 0 _set_bit ENDP _netmask_bits$ = 8 ; size = 1 _form_netmask PROC push ebx push esi movzx esi, BYTE PTR _netmask_bits$[esp+4] xor ecx, ecx xor bl, bl test esi, esi jle SHORT $LN9@form_netma 478
  • 503. CHAPTER 38. NETWORK ADDRESS CALCULATION EXAMPLE 38.5. SUMMARY xor edx, edx $LL3@form_netma: mov eax, 31 sub eax, edx push eax push ecx call _set_bit inc bl movzx edx, bl add esp, 8 mov ecx, eax cmp edx, esi jl SHORT $LL3@form_netma $LN9@form_netma: pop esi mov eax, ecx pop ebx ret 0 _form_netmask ENDP set_bit() is primitive: it just shift left 1 to number of bits we need and then ORs it with the “input” value. form_netmask() has a loop: it will set as many bits (starting from the MSB) as passed in the netmask_bits argument 38.5 Summary That’s it! I run it and get: netmask=255.255.255.0 network address=10.1.2.0 netmask=255.0.0.0 network address=10.0.0.0 netmask=255.255.255.128 network address=10.1.2.0 netmask=255.255.255.192 network address=10.1.2.64 479
  • 504. CHAPTER 39. LOOPS: SEVERAL ITERATORS Chapter 39 Loops: several iterators In most cases loops have only one iterator, but there could be several in the resulting code. Here is a very simple example: #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; // copy from one array to another in some weird scheme for (i=0; i<cnt; i++) a1[i*3]=a2[i*7]; }; There are two multiplications at each iteration and they are costly operations. Can we optimize it somehow? Yes, if we notice that both array indices are jumping on values that we can easily calculate without multiplication. 39.1 Three iterators Listing 39.1: Optimizing MSVC 2013 x64 f PROC ; RDX=a1 ; RCX=a2 ; R8=cnt test r8, r8 ; cnt==0? exit then je SHORT $LN1@f npad 11 $LL3@f: mov eax, DWORD PTR [rdx] lea rcx, QWORD PTR [rcx+12] lea rdx, QWORD PTR [rdx+28] mov DWORD PTR [rcx-12], eax dec r8 jne SHORT $LL3@f $LN1@f: ret 0 f ENDP Now there are 3 iterators: the cnt variable and two indices, which are increased by 12 and 28 at each iteration. We can rewrite this code in C/C++: #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; size_t idx1=0; idx2=0; // copy from one array to another in some weird scheme for (i=0; i<cnt; i++) { a1[idx1]=a2[idx2]; 480
  • 505. CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.2. TWO ITERATORS idx1+=3; idx2+=7; }; }; So, at the cost of updating 3 iterators at each iteration instead of one, we can remove two multiplication operations. 39.2 Two iterators GCC 4.9 does even more, leaving only 2 iterators: Listing 39.2: Optimizing GCC 4.9 x64 ; RDI=a1 ; RSI=a2 ; RDX=cnt f: test rdx, rdx ; cnt==0? exit then je .L1 ; calculate last element address in "a2" and leave it in RDX lea rax, [0+rdx*4] ; RAX=RDX*4=cnt*4 sal rdx, 5 ; RDX=RDX<<5=cnt*32 sub rdx, rax ; RDX=RDX-RAX=cnt*32-cnt*4=cnt*28 add rdx, rsi ; RDX=RDX+RSI=a2+cnt*28 .L3: mov eax, DWORD PTR [rsi] add rsi, 28 add rdi, 12 mov DWORD PTR [rdi-12], eax cmp rsi, rdx jne .L3 .L1: rep ret There is no counter variable any more: GCC concluded that it is not needed. The last element of the a2 array is calculated before the loop begins (which is easy: cnt ∗ 7) and that’s how the loop is to be stopped: just iterate until the second index has not reached this precalculated value. You can read more about multiplication using shifts/additions/subtractions here: 16.1.3 on page 202. This code can be rewritten into C/C++ like that: #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; size_t idx1=0; idx2=0; size_t last_idx2=cnt*7; // copy from one array to another in some weird scheme for (;;) { a1[idx1]=a2[idx2]; idx1+=3; idx2+=7; if (idx2==last_idx2) break; }; }; GCC (Linaro) 4.9 for ARM64 does the same, but it precalculates the last index of a1 instead of a2, which, of course has the same effect: Listing 39.3: Optimizing GCC (Linaro) 4.9 ARM64 ; X0=a1 ; X1=a2 481
  • 506. CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE ; X2=cnt f: cbz x2, .L1 ; cnt==0? exit then ; calculate last element of "a1" array add x2, x2, x2, lsl 1 ; X2=X2+X2<<1=X2+X2*2=X2*3 mov x3, 0 lsl x2, x2, 2 ; X2=X2<<2=X2*4=X2*3*4=X2*12 .L3: ldr w4, [x1],28 ; load at X1, add 28 to X1 (post-increment) str w4, [x0,x3] ; store at X0+X3=a1+X3 add x3, x3, 12 ; shift X3 cmp x3, x2 ; end? bne .L3 .L1: ret GCC 4.4.5 for MIPS does the same: Listing 39.4: Optimizing GCC 4.4.5 for MIPS (IDA) ; $a0=a1 ; $a1=a2 ; $a2=cnt f: ; jump to loop check code: beqz $a2, locret_24 ; initialize counter (i) at 0: move $v0, $zero ; branch delay slot, NOP loc_8: ; load 32-bit word at $a1 lw $a3, 0($a1) ; increment counter (i): addiu $v0, 1 ; check for finish (compare "i" in $v0 and "cnt" in $a2): sltu $v1, $v0, $a2 ; store 32-bit word at $a0: sw $a3, 0($a0) ; add 0x1C (28) to $a1 at each iteration: addiu $a1, 0x1C ; jump to loop body if i<cnt: bnez $v1, loc_8 ; add 0xC (12) to $a0 at each iteration: addiu $a0, 0xC ; branch delay slot locret_24: jr $ra or $at, $zero ; branch delay slot, NOP 39.3 Intel C++ 2011 case Compiler optimizations can also be weird, but nevertheless, still correct. Here is what the Intel C++ compiler 2011 does: Listing 39.5: Optimizing Intel C++ 2011 x64 f PROC ; parameter 1: rcx = a1 ; parameter 2: rdx = a2 ; parameter 3: r8 = cnt .B1.1:: ; Preds .B1.0 test r8, r8 ;8.14 jbe exit ; Prob 50% ;8.14 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.2:: ; Preds .B1.1 cmp r8, 6 ;8.2 jbe just_copy ; Prob 50% ;8.2 482
  • 507. CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.3:: ; Preds .B1.2 cmp rcx, rdx ;9.11 jbe .B1.5 ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.4:: ; Preds .B1.3 mov r10, r8 ;9.11 mov r9, rcx ;9.11 shl r10, 5 ;9.11 lea rax, QWORD PTR [r8*4] ;9.11 sub r9, rdx ;9.11 sub r10, rax ;9.11 cmp r9, r10 ;9.11 jge just_copy2 ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.5:: ; Preds .B1.3 .B1.4 cmp rdx, rcx ;9.11 jbe just_copy ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.6:: ; Preds .B1.5 mov r9, rdx ;9.11 lea rax, QWORD PTR [r8*8] ;9.11 sub r9, rcx ;9.11 lea r10, QWORD PTR [rax+r8*4] ;9.11 cmp r9, r10 ;9.11 jl just_copy ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8⤦ xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 just_copy2:: ; Preds .B1.4 .B1.6 ; R8 = cnt ; RDX = a2 ; RCX = a1 xor r10d, r10d ;8.2 xor r9d, r9d ; xor eax, eax ; ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦ xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.8:: ; Preds .B1.8 just_copy2 mov r11d, DWORD PTR [rax+rdx] ;3.6 inc r10 ;8.2 mov DWORD PTR [r9+rcx], r11d ;3.6 add r9, 12 ;8.2 add rax, 28 ;8.2 cmp r10, r8 ;8.2 jb .B1.8 ; Prob 82% ;8.2 jmp exit ; Prob 100% ;8.2 ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦ xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 just_copy:: ; Preds .B1.2 .B1.5 .B1.6 ; R8 = cnt ; RDX = a2 ; RCX = a1 xor r10d, r10d ;8.2 xor r9d, r9d ; xor eax, eax ; ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦ xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.11:: ; Preds .B1.11 just_copy mov r11d, DWORD PTR [rax+rdx] ;3.6 inc r10 ;8.2 mov DWORD PTR [r9+rcx], r11d ;3.6 add r9, 12 ;8.2 add rax, 28 ;8.2 cmp r10, r8 ;8.2 jb .B1.11 ; Prob 82% ;8.2 ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 ⤦ 483
  • 508. CHAPTER 39. LOOPS: SEVERAL ITERATORS 39.3. INTEL C++ 2011 CASE xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 exit:: ; Preds .B1.11 .B1.8 .B1.1 ret ;10.1 First, there are some decisions taken, then one of the routines is executed. Looks like it is a check if arrays intersect. This is very well known way of optimizing memory block copy routines. But copy routines are the same! This is probably an error of the Intel C++ optimizer, which still produces workable code, though. I’m adding such example code to my book so the reader would understand that compiler output is weird at times, but still correct, because when the compiler was tested, is passed the tests. 484
  • 509. CHAPTER 40. DUFF’S DEVICE Chapter 40 Duff’s device Duff’s device 1 is an unrolled loop with the possibility to jump inside it. The unrolled loop is implemented using a fallthrough switch() statement. I would use here a slightly simplified version of Tom Duff’s original code. Let’s say, we need to write a function that clears a region in memory. One can come with a simple loop, clearing byte by byte. It’s obviously slow, since all modern computers have much wider memory bus. So the better way is to clear the memory region using 4 or 8 byte blocks. Since we are going to work with a 64-bit example here, we are going to clear the memory in 8 byte blocks. So far so good. But what about the tail? Memory clearing routine can also be called for regions of size that’s not a multiple of 8. So here is the algorithm: • calculate the number of 8-byte blocks, clear them using 8-byte (64-bit) memory accesses; • calculate the size of the tail, clear it using 1-byte memory accesses. The second step can be implemented using a simple loop. But let’s implement it as an unrolled loop: #include <stdint.h> #include <stdio.h> void bzero(uint8_t* dst, size_t count) { int i; if (count&(~7)) // work out 8-byte blocks for (i=0; i<count>>3; i++) { *(uint64_t*)dst=0; dst=dst+8; }; // work out the tail switch(count & 7) { case 7: *dst++ = 0; case 6: *dst++ = 0; case 5: *dst++ = 0; case 4: *dst++ = 0; case 3: *dst++ = 0; case 2: *dst++ = 0; case 1: *dst++ = 0; case 0: // do nothing break; } } Let’s first understand how the calculation is done. The memory region size comes as a 64-bit value. And this value can be divided in two parts: 7 6 5 4 3 2 1 0 … B B B B B S S S 1wikipedia 485
  • 510. CHAPTER 40. DUFF’S DEVICE ( “B” is number of 8-byte blocks and “S” is length of the tail in bytes ). When we divide the input memory region size by 8, the value is just shifted right by 3 bits. But to calculate the remainder, we just need to isolate the lowest 3 bits! So the number of 8-byte blocks is calculated as count >> 3 and remainder as count&7. We also need to find out if we are going to execute the 8-byte procedure at all, so we need to check if the value of count is greater than 7. We do this by clearing the 3 lowest bits and comparing the resulting number with zero, because all we need here is to answer the question, is the high part of count non-zero. Of course, this works because 8 is 23 and division by numbers that are 2n is easy. It’s not possible for other numbers. It’s actually hard to say if these hacks are worth using, because they lead to hard-to-read code. However, these tricks are very popular and a practicing programmer, even if he/she is not using them, nevertheless has to understand them. So the first part is simple: get the number of 8-byte blocks and write 64-bit zero values to memory. The second part is an unrolled loop implemented as fallthrough switch() statement. First, let’s express in plain English what we have to do here. We have to “write as many zero bytes in memory, as count&7 value tells us”. If it’s 0, jump to the end, there is no work to do. If it’s 1, jump to the place inside switch() statement where only one storage operation is to be executed. If it’s 2, jump to another place, where two storage operation are to be executed, etc. 7 as input value leads to the execution of all 7 operations. There is no 8, because a memory region of 8 bytes is to be processed by the first part of our function. So we wrote an unrolled loop. It was definitely faster on older computers than normal loops (and conversely, modern CPUs works better for short loops than for unrolled ones). Maybe this is still meaningful on modern low-cost embedded MCU2 s. Let’s see what the optimizing MSVC 2012 does: dst$ = 8 count$ = 16 bzero PROC test rdx, -8 je SHORT $LN11@bzero ; work out 8-byte blocks xor r10d, r10d mov r9, rdx shr r9, 3 mov r8d, r10d test r9, r9 je SHORT $LN11@bzero npad 5 $LL19@bzero: inc r8d mov QWORD PTR [rcx], r10 add rcx, 8 movsxd rax, r8d cmp rax, r9 jb SHORT $LL19@bzero $LN11@bzero: ; work out the tail and edx, 7 dec rdx cmp rdx, 6 ja SHORT $LN9@bzero lea r8, OFFSET FLAT:__ImageBase mov eax, DWORD PTR $LN22@bzero[r8+rdx*4] add rax, r8 jmp rax $LN8@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN7@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN6@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN5@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN4@bzero: mov BYTE PTR [rcx], 0 inc rcx 2Microcontroller unit 486
  • 511. CHAPTER 40. DUFF’S DEVICE $LN3@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN2@bzero: mov BYTE PTR [rcx], 0 $LN9@bzero: fatret 0 npad 1 $LN22@bzero: DD $LN2@bzero DD $LN3@bzero DD $LN4@bzero DD $LN5@bzero DD $LN6@bzero DD $LN7@bzero DD $LN8@bzero bzero ENDP The first part of the function is predictable. The second part is just an unrolled loop and a jump passing control flow to the correct instruction inside it. There is no other code between the MOV/INC instruction pairs, so the execution is to fall until the very end, executing as many pairs as needed. By the way, we can observe that the MOV/INC pair consumes a fixed number of bytes (3+3). So the pair consumes 6 bytes. Knowing that, we can get rid of the switch() jumptable, we can just multiple the input value by 6 and jump to current_RIP + input_value ∗ 6. This can also be faster because we are not in need to fetch a value from the jumptable. It’s possible that 6 probably is not a very good constant for fast multiplication and maybe it’s not worth it, but you get the idea3 . That is what old-school demomakers did in the past with unrolled loops. 3As an exercise, you can try to rework the code to get rid of the jumptable. The instruction pair can be rewritten in a way that it will consume 4 bytes or maybe 8. 1 byte is also possible (using STOSB instruction). 487
  • 512. CHAPTER 41. DIVISION BY 9 Chapter 41 Division by 9 A very simple function: int f(int a) { return a/9; }; 41.1 x86 …is compiled in a very predictable way: Listing 41.1: MSVC _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cdq ; sign extend EAX to EDX:EAX mov ecx, 9 idiv ecx pop ebp ret 0 _f ENDP IDIV divides the 64-bit number stored in the EDX:EAX register pair by the value in the ECX. As a result, EAX will contain the quotient, and EDX —the remainder. The result is returned from the f() function in the EAX register, so the value is not moved after the division operation, it is in right place already. Since IDIV uses the value in the EDX:EAX register pair, the CDQ instruction (before IDIV) extends the value in EAX to a 64-bit value taking its sign into account, just as MOVSX does. If we turn optimization on (/Ox), we get: Listing 41.2: Optimizing MSVC _a$ = 8 ; size = 4 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, 954437177 ; 38e38e39H imul ecx sar edx, 1 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx ret 0 _f ENDP This is division by multiplication. Multiplication operations work much faster. And it is possible to use this trick 1 to produce code which is effectively equivalent and faster. This is also called “strength reduction” in compiler optimizations. GCC 4.4.1 generates almost the same code even without additional optimization flags, just like MSVC with optimization turned on: 1Read more about division by multiplication in [War02, pp. 10-3] 488
  • 513. CHAPTER 41. DIVISION BY 9 41.2. ARM Listing 41.3: Non-optimizing GCC 4.4.1 public f f proc near arg_0 = dword ptr 8 push ebp mov ebp, esp mov ecx, [ebp+arg_0] mov edx, 954437177 ; 38E38E39h mov eax, ecx imul edx sar edx, 1 mov eax, ecx sar eax, 1Fh mov ecx, edx sub ecx, eax mov eax, ecx pop ebp retn f endp 41.2 ARM The ARM processor, just like in any other ”pure” RISC processor lacks an instruction for division. It also lacks a single instruction for multiplication by a 32-bit constant (recall that a 32-bit constant cannot fit into a 32-bit opcode). By taking advantage of this clever trick (or hack), it is possible to do division using only three instructions: addition, subtraction and bit shifts ( 19 on page 305). Here is an example that divides a 32-bit number by 10, from [Ltd94, 3.3 Division by a Constant]. The output consists of the quotient and the remainder. ; takes argument in a1 ; returns quotient in a1, remainder in a2 ; cycles could be saved if only divide or remainder is required SUB a2, a1, #10 ; keep (x-10) for later SUB a1, a1, a1, lsr #2 ADD a1, a1, a1, lsr #4 ADD a1, a1, a1, lsr #8 ADD a1, a1, a1, lsr #16 MOV a1, a1, lsr #3 ADD a3, a1, a1, asl #2 SUBS a2, a2, a3, asl #1 ; calc (x-10) - (x/10)*10 ADDPL a1, a1, #1 ; fix-up quotient ADDMI a2, a2, #10 ; fix-up remainder MOV pc, lr 41.2.1 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) __text:00002C58 39 1E 08 E3 E3 18 43 E3 MOV R1, 0x38E38E39 __text:00002C60 10 F1 50 E7 SMMUL R0, R0, R1 __text:00002C64 C0 10 A0 E1 MOV R1, R0,ASR#1 __text:00002C68 A0 0F 81 E0 ADD R0, R1, R0,LSR#31 __text:00002C6C 1E FF 2F E1 BX LR This code is almost the same as the one generated by the optimizing MSVC and GCC. Apparently, LLVM uses the same algorithm for generating constants. The observant reader may ask, how does MOV writes a 32-bit value in a register, when this is not possible in ARM mode. it is impossible indeed, but, as we see, there are 8 bytes per instruction instead of the standard 4, in fact, there are two instructions. The first instruction loads 0x8E39 into the low 16 bits of register and the second instruction is MOVT, it loads 0x383E into the high 16 bits of the register. IDA is fully aware of such sequences, and for the the sake of compactness reduces them to one single “pseudo-instruction”. The SMMUL (Signed Most Significant Word Multiply) instruction two multiplies numbers, treating them as signed numbers and leaving the high 32-bit part of result in the R0 register, dropping the low 32-bit part of the result. The``MOV R1, R0,ASR#1'' instruction is an arithmetic shift right by one bit. ``ADD R0, R1, R0,LSR#31'' is R0 = R1 + R0 >> 31 489
  • 514. CHAPTER 41. DIVISION BY 9 41.3. MIPS There is no separate shifting instruction in ARM mode. Instead, an instructions like (MOV, ADD, SUB, RSB)2 can have a suffix added, that says if the second operand must be shifted, and if yes, by what value and how. ASR stands for Arithmetic Shift Right, LSR—Logical Shift Right. 41.2.2 Optimizing Xcode 4.6.3 (LLVM) (thumb-2 mode) MOV R1, 0x38E38E39 SMMUL.W R0, R0, R1 ASRS R1, R0, #1 ADD.W R0, R1, R0,LSR#31 BX LR There are separate instructions for shifting in thumb mode, and one of them is used here—ASRS (arithmetic shift right). 41.2.3 Non-optimizing Xcode 4.6.3 (LLVM) and Keil 6/2013 Non-optimizing LLVM does not generate the code we saw before in this section, but instead inserts a call to the library function ___divsi3. What about Keil: it inserts a call to the library function __aeabi_idivmod in all cases. 41.3 MIPS For some reason, optimizing GCC 4.4.5 generate just a division instruction: Listing 41.4: Optimizing GCC 4.4.5 (IDA) f: li $v0, 9 bnez $v0, loc_10 div $a0, $v0 ; branch delay slot break 0x1C00 ; "break 7" in assembly output and objdump loc_10: mflo $v0 jr $ra or $at, $zero ; branch delay slot, NOP Here we see here a new instruction: BREAK. It just raises an exception. In this case, an exception is raised if the divisor is zero (it’s not possible to divide by zero in conventional math). But GCC probably did not do very well the optimization job and did not see that $V0 is never zero. So the check is left here. So if $V0 is zero somehow, BREAK is to be executed, signaling to the OS about the exception. Otherwise, MFLO executes, which takes the result of the division from the LO register and copies it in $V0. By the way, as we may know, the MUL instruction leaves the high 32 bits of the result in register HI and the low 32 bits in register LO. DIV leaves the result in the LO register, and remainder in the HI register. If we alter the statement to “a % 9”, the MFHI instruction is to be used here instead of MFLO. 41.4 How it works That’s how division can be replaced by multiplication and division with 2n numbers: result = input divisor = input ⋅ 2n divisor 2n = input ⋅ M 2n Where M is a magic coefficient. This is how M can be computed: M = 2n divisor So these code snippets usually have this form: result = input ⋅ M 2n Division by 2n is usually done by simply shifting to the right. If n < 32, then the low part of the product is shifted (in EAX or RAX). If n ≥ 32, then the high part of the product is shifted (in EDX or RDX). 2These instructions are also called “data processing instructions” 490
  • 515. CHAPTER 41. DIVISION BY 9 41.5. GETTING THE DIVISOR n is chosen in order to minimize the error. When doing signed division, the sign of the multiplication result is also added to the output result. Take a look at the difference: int f3_32_signed(int a) { return a/3; }; unsigned int f3_32_unsigned(unsigned int a) { return a/3; }; In the unsigned version of the function, the magic coefficient is 0xAAAAAAAB and the multiplication result is divided by 233 . In the signed version of the function, the magic coefficient is 0x55555556 and the multiplication result is divided by 232 . There are no division instruction though: the result is just taken from EDX. The sign is also taken from the multiplication result: the high 32 bits of the result are shifted by 31 (leaving the sign in the least significant bit of EAX). 1 is added to the final result if the sign is negative, for result correction. Listing 41.5: Optimizing MSVC 2012 _f3_32_unsigned PROC mov eax, -1431655765 ; aaaaaaabH mul DWORD PTR _a$[esp-4] ; unsigned multiply ; EDX=(input*0xaaaaaaab)/2^32 shr edx, 1 ; EDX=(input*0xaaaaaaab)/2^33 mov eax, edx ret 0 _f3_32_unsigned ENDP _f3_32_signed PROC mov eax, 1431655766 ; 55555556H imul DWORD PTR _a$[esp-4] ; signed multiply ; take high part of product ; it is just the same as if to shift product by 32 bits right or to divide it by 2^32 mov eax, edx ; EAX=EDX=(input*0x55555556)/2^32 shr eax, 31 ; 0000001fH add eax, edx ; add 1 if sign is negative ret 0 _f3_32_signed ENDP Read more about it in [War02, pp. 10-3]. 41.5 Getting the divisor 41.5.1 Variant #1 Often, the code looks like this: mov eax, MAGICAL CONSTANT imul input value sar edx, SHIFTING COEFFICIENT ; signed division by 2x using arithmetic shift right mov eax, edx shr eax, 31 add eax, edx Let’s denote the 32-bit magic coefficient as M, the shifting coefficient as C and the divisor as D. The divisor we need to get is: D = 232+C M For example: Listing 41.6: Optimizing MSVC 2012 mov eax, 2021161081 ; 78787879H imul DWORD PTR _a$[esp-4] 491
  • 516. CHAPTER 41. DIVISION BY 9 41.5. GETTING THE DIVISOR sar edx, 3 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx This is: D = 232+3 2021161081 The numbers are larger than 32-bit, so I used Wolfram Mathematica for convenience: Listing 41.7: Wolfram Mathematica In[1]:=N[2^(32+3)/2021161081] Out[1]:=17. So the divisor from the code I used as example is 17. For x64 division, things are the same, but 264 has to be used instead of 232 : uint64_t f1234(uint64_t a) { return a/1234; }; Listing 41.8: Optimizing MSVC 2012 x64 f1234 PROC mov rax, 7653754429286296943 ; 6a37991a23aead6fH mul rcx shr rdx, 9 mov rax, rdx ret 0 f1234 ENDP Listing 41.9: Wolfram Mathematica In[1]:=N[2^(64+9)/16^^6a37991a23aead6f] Out[1]:=1234. 41.5.2 Variant #2 A variant with omitted arithmetic shift also exist: mov eax, 55555556h ; 1431655766 imul ecx mov eax, edx shr eax, 1Fh The method of getting divisor is simplified: D = 232 M As of my example, this is: D = 232 1431655766 And again I used Wolfram Mathematica: Listing 41.10: Wolfram Mathematica In[1]:=N[2^32/16^^55555556] Out[1]:=3. The divisor is 3. 492
  • 517. CHAPTER 41. DIVISION BY 9 41.6. EXERCISE #1 41.6 Exercise #1 What does this code do? Listing 41.11: Optimizing MSVC 2010 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, -968154503 ; c64b2279H imul ecx add edx, ecx sar edx, 9 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx ret 0 _f ENDP Listing 41.12: Optimizing GCC 4.9 (ARM64) f: mov w1, 8825 movk w1, 0xc64b, lsl 16 smull x1, w0, w1 lsr x1, x1, 32 add w1, w0, w1 asr w1, w1, 9 sub w0, w1, w0, asr 31 ret Answer G.1.14 on page 959. 493
  • 518. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) Chapter 42 String to number conversion (atoi()) Let’s try to reimplement the standard atoi() C function. 42.1 Simple example Here is the simplest possible way to read a number represented in ASCII1 encoding. It’s not error-prone: a character other than a digit leads to incorrect result. #include <stdio.h> int my_atoi (char *s) { int rt=0; while (*s) { rt=rt*10 + (*s-'0'); s++; }; return rt; }; int main() { printf ("%dn", my_atoi ("1234")); printf ("%dn", my_atoi ("1234567890")); }; So what the algorithm does is just reading digits from left to right. The zero ASCII character is subtracted from each digit. The digits from “0” to “9” are consecutive in the ASCII table, so we do not even need to know the exact value of the “0” character. All we need to know is that “0” minus “0” is 0, “9” minus “0”’is 9 and so on. Subtracting “0” from each character results in a number from 0 to 9 inclusive. Any other character leads to an incorrect result, of course! Each digit has to be added to the final result (in variable “rt”), but the final result is also multiplied by 10 at each digit. In other words, the result is shifted left by one position in decimal form on each iteration. The last digit is added, but there is no no shift. 42.1.1 Optimizing MSVC 2013 x64 Listing 42.1: Optimizing MSVC 2013 x64 s$ = 8 my_atoi PROC ; load first character movzx r8d, BYTE PTR [rcx] ; EAX is allocated for "rt" variable ; its 0 at start' xor eax, eax ; first character is zero-byte, i.e., string terminator? ; exit then. test r8b, r8b je SHORT $LN9@my_atoi 1American Standard Code for Information Interchange 494
  • 519. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.1. SIMPLE EXAMPLE $LL2@my_atoi: lea edx, DWORD PTR [rax+rax*4] ; EDX=RAX+RAX*4=rt+rt*4=rt*5 movsx eax, r8b ; EAX=input character ; load next character to R8D movzx r8d, BYTE PTR [rcx+1] ; shift pointer in RCX to the next character: lea rcx, QWORD PTR [rcx+1] lea eax, DWORD PTR [rax+rdx*2] ; EAX=RAX+RDX*2=input character + rt*5*2=input character + rt*10 ; correct digit by subtracting 48 (0x30 or '0') add eax, -48 ; ffffffffffffffd0H ; was last character zero? test r8b, r8b ; jump to loop begin, if not jne SHORT $LL2@my_atoi $LN9@my_atoi: ret 0 my_atoi ENDP A character can be loaded in two places: the first character and all subsequent characters. This is done for loop regrouping. There is no instruction for multiplication by 10, two LEA instruction do this instead. MSVC sometimes uses the ADD instruction with a negative constant instead of SUB. This is the case. I truly don’t know why this is better then SUB. But MSVC does this often. 42.1.2 Optimizing GCC 4.9.1 x64 Optimizing GCC 4.9.1 is more concise, but there is one redundant RET instruction at the end. One would be enough. Listing 42.2: Optimizing GCC 4.9.1 x64 my_atoi: ; load input character into EDX movsx edx, BYTE PTR [rdi] ; EAX is allocated for "rt" variable xor eax, eax ; exit, if loaded character is null byte test dl, dl je .L4 .L3: lea eax, [rax+rax*4] ; EAX=RAX*5=rt*5 ; shift pointer to the next character: add rdi, 1 lea eax, [rdx-48+rax*2] ; EAX=input character - 48 + RAX*2 = input character - '0' + rt*10 ; load next character: movsx edx, BYTE PTR [rdi] ; goto loop begin, if loaded character is not null byte test dl, dl jne .L3 rep ret .L4: rep ret 42.1.3 Optimizing Keil 6/2013 (ARM mode) Listing 42.3: Optimizing Keil 6/2013 (ARM mode) my_atoi PROC ; R1 will contain pointer to character MOV r1,r0 ; R0 will contain "rt" variable MOV r0,#0 B |L0.28| |L0.12| ADD r0,r0,r0,LSL #2 ; R0=R0+R0<<2=rt*5 495
  • 520. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.1. SIMPLE EXAMPLE ADD r0,r2,r0,LSL #1 ; R0=input character + rt*5<<1 = input character + rt*10 ; correct whole thing by subtracting '0' from rt: SUB r0,r0,#0x30 ; shift pointer to the next character: ADD r1,r1,#1 |L0.28| ; load input character to R2 LDRB r2,[r1,#0] ; is it null byte? if no, jump to loop body. CMP r2,#0 BNE |L0.12| ; exit if null byte. ; "rt" variable is still in R0 register, ready to be used in caller function BX lr ENDP 42.1.4 Optimizing Keil 6/2013 (thumb mode) Listing 42.4: Optimizing Keil 6/2013 (thumb mode) my_atoi PROC ; R1 will be pointer to the input character MOVS r1,r0 ; R0 is allocated to "rt" variable MOVS r0,#0 B |L0.16| |L0.6| MOVS r3,#0xa ; R3=10 MULS r0,r3,r0 ; R0=R3*R0=rt*10 ; shift pointer to the next character: ADDS r1,r1,#1 ; correct whole thing by subtracting 0' character from it': SUBS r0,r0,#0x30 ADDS r0,r2,r0 ; rt=R2+R0=input character + (rt*10 - '0') |L0.16| ; load input character to R2 LDRB r2,[r1,#0] ; is it zero? CMP r2,#0 ; jump to loop body if its not' BNE |L0.6| ; rt variable in R0 now, ready to be used in caller function BX lr ENDP Interestingly, from school mathematics we may remember that the order of addition and subtraction operations doesn’t matter. That’s our case: first, the rt ∗ 10 −′ 0′ expression is computed, then the input character value is added to it. Indeed, the result is the same, but the compiler did some regrouping. 42.1.5 Optimizing GCC 4.9.1 ARM64 The ARM64 compiler can use the pre-increment instruction suffix: Listing 42.5: Optimizing GCC 4.9.1 ARM64 my_atoi: ; load input character into W1 ldrb w1, [x0] mov x2, x0 ; X2=address of input string ; is loaded character zero? ; jump to exit if its so' ; W1 will contain 0 in this case. ; it will be reloaded into W0 at L4. cbz w1, .L4 496
  • 521. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE ; W0 will contain "rt" variable ; initialize it at zero: mov w0, 0 .L3: ; subtract 48 or '0' from input variable and put result into W3: sub w3, w1, #48 ; load next character at address X2+1 into W1 with pre-increment: ldrb w1, [x2,1]! add w0, w0, w0, lsl 2 ; W0=W0+W0<<2=W0+W0*4=rt*5 add w0, w3, w0, lsl 1 ; W0=input digit + W0<<1 = input digit + rt*5*2 = input digit + rt*10 ; if the character we just loaded is not null byte, jump to the loop begin cbnz w1, .L3 ; variable to be returned (rt) is in W0, ready to be used in caller function ret .L4: mov w0, w1 ret 42.2 A slightly advanced example My new code snippet is more advanced, now it checks for the “minus” sign at the first character and reports an error if a non-digit was found in the input string: #include <stdio.h> int my_atoi (char *s) { int negative=0; int rt=0; if (*s=='-') { negative=1; s++; }; while (*s) { if (*s<'0' || *s>'9') { printf ("Error! Unexpected char: '%c'n", *s); exit(0); }; rt=rt*10 + (*s-'0'); s++; }; if (negative) return -rt; return rt; }; int main() { printf ("%dn", my_atoi ("1234")); printf ("%dn", my_atoi ("1234567890")); printf ("%dn", my_atoi ("-1234")); printf ("%dn", my_atoi ("-1234567890")); printf ("%dn", my_atoi ("-a1234567890")); // error }; 42.2.1 Optimizing GCC 4.9.1 x64 Listing 42.6: Optimizing GCC 4.9.1 x64 497
  • 522. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE .LC0: .string "Error! Unexpected char: '%c'n" my_atoi: sub rsp, 8 movsx edx, BYTE PTR [rdi] ; check for minus sign cmp dl, 45 ; '-' je .L22 xor esi, esi test dl, dl je .L20 .L10: ; ESI=0 here if there was no minus sign and 1 if it was lea eax, [rdx-48] ; any character other than digit will result unsigned number greater than 9 after subtraction ; so if it is not digit, jump to L4, where error will be reported: cmp al, 9 ja .L4 xor eax, eax jmp .L6 .L7: lea ecx, [rdx-48] cmp cl, 9 ja .L4 .L6: lea eax, [rax+rax*4] add rdi, 1 lea eax, [rdx-48+rax*2] movsx edx, BYTE PTR [rdi] test dl, dl jne .L7 ; if there was no minus sign, skip NEG instruction ; if it was, execute it. test esi, esi je .L18 neg eax .L18: add rsp, 8 ret .L22: movsx edx, BYTE PTR [rdi+1] lea rax, [rdi+1] test dl, dl je .L20 mov rdi, rax mov esi, 1 jmp .L10 .L20: xor eax, eax jmp .L18 .L4: ; report error. character is in EDX mov edi, 1 mov esi, OFFSET FLAT:.LC0 ; "Error! Unexpected char: '%c'n" xor eax, eax call __printf_chk xor edi, edi call exit If the “minus” sign was encountered at the string start, the NEG instruction is to be executed at the end. It just negates the number. There is one more thing that needs mentioning. How would a common programmer check if the character is not a digit? Just how I wrote it in the source code: if (*s<'0' || *s>'9') ... There are two comparison operations. What is interesting is that we can replace both operations by single one: just subtract “0” from character value, treat result as unsigned value (this is important) and check if it’s greater than 9. 498
  • 523. CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) 42.2. A SLIGHTLY ADVANCED EXAMPLE For example, let’s say that the user input contains the dot character (“.”) which has ASCII code 46. 46−48 = −2 if we treat the result as a signed number. Indeed, the dot character is located two places earlier than the “0” character in the ASCII table. But it is 0xFFFFFFFE (4294967294) if we treat the result as an unsigned value, and that’s definitely bigger than 9! The compilers do this often, so it’s important to recognize these tricks. Another example of it in this book: 48.1.2 on page 529. Optimizing MSVC 2013 x64 does the same tricks. 42.2.2 Optimizing Keil 6/2013 (ARM mode) Listing 42.7: Optimizing Keil 6/2013 (ARM mode) 1 my_atoi PROC 2 PUSH {r4-r6,lr} 3 MOV r4,r0 4 LDRB r0,[r0,#0] 5 MOV r6,#0 6 MOV r5,r6 7 CMP r0,#0x2d '-' 8 ; R6 will contain 1 if minus was encountered, 0 if otherwise 9 MOVEQ r6,#1 10 ADDEQ r4,r4,#1 11 B |L0.80| 12 |L0.36| 13 SUB r0,r1,#0x30 14 CMP r0,#0xa 15 BCC |L0.64| 16 ADR r0,|L0.220| 17 BL __2printf 18 MOV r0,#0 19 BL exit 20 |L0.64| 21 LDRB r0,[r4],#1 22 ADD r1,r5,r5,LSL #2 23 ADD r0,r0,r1,LSL #1 24 SUB r5,r0,#0x30 25 |L0.80| 26 LDRB r1,[r4,#0] 27 CMP r1,#0 28 BNE |L0.36| 29 CMP r6,#0 30 ; negate result 31 RSBNE r0,r5,#0 32 MOVEQ r0,r5 33 POP {r4-r6,pc} 34 ENDP 35 36 |L0.220| 37 DCB "Error! Unexpected char: '%c'n",0 There is no NEG instruction in 32-bit ARM, so the “Reverse Subtraction” operation (line 31) is used here. It is triggered if the result of the CMP instruction (at line 29) was “Not Equal” (hence -NE suffix). So what RSBNE does is to subtract the resulting value from 0. It works just like the regular subtraction operation, but swaps operands. Subtracting any number from 0 results in negation: 0 − x = −x. Thumb mode code is mostly the same. GCC 4.9 for ARM64 can use the NEG instruction, which is available in ARM64. 499
  • 524. CHAPTER 43. INLINE FUNCTIONS Chapter 43 Inline functions Inlined code is when the compiler, instead of placing a call instruction to a small or tiny function, just places its body right in-place. Listing 43.1: A simple example #include <stdio.h> int celsius_to_fahrenheit (int celsius) { return celsius * 9 / 5 + 32; }; int main(int argc, char *argv[]) { int celsius=atol(argv[1]); printf ("%dn", celsius_to_fahrenheit (celsius)); }; … is compiled in very predictable way, however, if we turn on GCC optimizations (-O3), we’ll see: Listing 43.2: Optimizing GCC 4.8.1 _main: push ebp mov ebp, esp and esp, -16 sub esp, 16 call ___main mov eax, DWORD PTR [ebp+12] mov eax, DWORD PTR [eax+4] mov DWORD PTR [esp], eax call _atol mov edx, 1717986919 mov DWORD PTR [esp], OFFSET FLAT:LC2 ; "%d120" lea ecx, [eax+eax*8] mov eax, ecx imul edx sar ecx, 31 sar edx sub edx, ecx add edx, 32 mov DWORD PTR [esp+4], edx call _printf leave ret (Here the division is done by multiplication( 41 on page 488).) Yes, our small function celsius_to_fahrenheit() was just placed before the printf() call. Why? It can be faster than executing this function’s code plus the overhead of calling/returning. Modern optimizing compilers are choosing small functions for inlining automatically. But it’s possible to force compiler additionally to inline some function, if to mark it with the “inline” keyword in its declaration. 500
  • 525. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS 43.1 Strings and memory functions Another very common automatic optimization tactic is the inlining of string functions like strcpy(), strcmp(), strlen(), memset(), memcmp(), memcpy(), etc. Sometimes it’s faster than to call a separate function. These are very frequent patterns and it is highly advisable for reverse engineers to learn to detect automatically. 43.1.1 strcmp() Listing 43.3: strcmp() example bool is_bool (char *s) { if (strcmp (s, "true")==0) return true; if (strcmp (s, "false")==0) return false; assert(0); }; Listing 43.4: Optimizing GCC 4.8.1 .LC0: .string "true" .LC1: .string "false" is_bool: .LFB0: push edi mov ecx, 5 push esi mov edi, OFFSET FLAT:.LC0 sub esp, 20 mov esi, DWORD PTR [esp+32] repz cmpsb je .L3 mov esi, DWORD PTR [esp+32] mov ecx, 6 mov edi, OFFSET FLAT:.LC1 repz cmpsb seta cl setb dl xor eax, eax cmp cl, dl jne .L8 add esp, 20 pop esi pop edi ret .L8: mov DWORD PTR [esp], 0 call assert add esp, 20 pop esi pop edi ret .L3: add esp, 20 mov eax, 1 pop esi pop edi ret Listing 43.5: Optimizing MSVC 2010 $SG3454 DB 'true', 00H $SG3456 DB 'false', 00H 501
  • 526. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS _s$ = 8 ; size = 4 ?is_bool@@YA_NPAD@Z PROC ; is_bool push esi mov esi, DWORD PTR _s$[esp] mov ecx, OFFSET $SG3454 ; 'true' mov eax, esi npad 4 ; align next label $LL6@is_bool: mov dl, BYTE PTR [eax] cmp dl, BYTE PTR [ecx] jne SHORT $LN7@is_bool test dl, dl je SHORT $LN8@is_bool mov dl, BYTE PTR [eax+1] cmp dl, BYTE PTR [ecx+1] jne SHORT $LN7@is_bool add eax, 2 add ecx, 2 test dl, dl jne SHORT $LL6@is_bool $LN8@is_bool: xor eax, eax jmp SHORT $LN9@is_bool $LN7@is_bool: sbb eax, eax sbb eax, -1 $LN9@is_bool: test eax, eax jne SHORT $LN2@is_bool mov al, 1 pop esi ret 0 $LN2@is_bool: mov ecx, OFFSET $SG3456 ; 'false' mov eax, esi $LL10@is_bool: mov dl, BYTE PTR [eax] cmp dl, BYTE PTR [ecx] jne SHORT $LN11@is_bool test dl, dl je SHORT $LN12@is_bool mov dl, BYTE PTR [eax+1] cmp dl, BYTE PTR [ecx+1] jne SHORT $LN11@is_bool add eax, 2 add ecx, 2 test dl, dl jne SHORT $LL10@is_bool $LN12@is_bool: xor eax, eax jmp SHORT $LN13@is_bool $LN11@is_bool: sbb eax, eax sbb eax, -1 $LN13@is_bool: test eax, eax jne SHORT $LN1@is_bool xor al, al pop esi ret 0 $LN1@is_bool: push 11 push OFFSET $SG3458 push OFFSET $SG3459 502
  • 527. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS call DWORD PTR __imp___wassert add esp, 12 pop esi ret 0 ?is_bool@@YA_NPAD@Z ENDP ; is_bool 43.1.2 strlen() Listing 43.6: strlen() example int strlen_test(char *s1) { return strlen(s1); }; Listing 43.7: Optimizing MSVC 2010 _s1$ = 8 ; size = 4 _strlen_test PROC mov eax, DWORD PTR _s1$[esp-4] lea edx, DWORD PTR [eax+1] $LL3@strlen_tes: mov cl, BYTE PTR [eax] inc eax test cl, cl jne SHORT $LL3@strlen_tes sub eax, edx ret 0 _strlen_test ENDP 43.1.3 strcpy() Listing 43.8: strcpy() example void strcpy_test(char *s1, char *outbuf) { strcpy(outbuf, s1); }; Listing 43.9: Optimizing MSVC 2010 _s1$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _strcpy_test PROC mov eax, DWORD PTR _s1$[esp-4] mov edx, DWORD PTR _outbuf$[esp-4] sub edx, eax npad 6 ; align next label $LL3@strcpy_tes: mov cl, BYTE PTR [eax] mov BYTE PTR [edx+eax], cl inc eax test cl, cl jne SHORT $LL3@strcpy_tes ret 0 _strcpy_test ENDP 43.1.4 memset() Example#1 Listing 43.10: 32 bytes #include <stdio.h> 503
  • 528. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS void f(char *out) { memset(out, 0, 32); }; Many compilers don’t generate a call to memset() for short blocks, but rather insert a MOV: Listing 43.11: Optimizing GCC 4.9.1 x64 f: mov QWORD PTR [rdi], 0 mov QWORD PTR [rdi+8], 0 mov QWORD PTR [rdi+16], 0 mov QWORD PTR [rdi+24], 0 ret By the way, that remind us of unrolled loops: 14.1.4 on page 176. Example#2 Listing 43.12: 67 bytes #include <stdio.h> void f(char *out) { memset(out, 0, 67); }; When the block size is not a multiple of 4 or 8, the compilers can behave differently. For instance, MSVC 2012 continues to insert MOVs: Listing 43.13: Optimizing MSVC 2012 x64 out$ = 8 f PROC xor eax, eax mov QWORD PTR [rcx], rax mov QWORD PTR [rcx+8], rax mov QWORD PTR [rcx+16], rax mov QWORD PTR [rcx+24], rax mov QWORD PTR [rcx+32], rax mov QWORD PTR [rcx+40], rax mov QWORD PTR [rcx+48], rax mov QWORD PTR [rcx+56], rax mov WORD PTR [rcx+64], ax mov BYTE PTR [rcx+66], al ret 0 f ENDP …while GCC uses REP STOSQ, concluding that this would be shorter than a pack of MOVs: Listing 43.14: Optimizing GCC 4.9.1 x64 f: mov QWORD PTR [rdi], 0 mov QWORD PTR [rdi+59], 0 mov rcx, rdi lea rdi, [rdi+8] xor eax, eax and rdi, -8 sub rcx, rdi add ecx, 67 shr ecx, 3 rep stosq ret 43.1.5 memcpy() Short blocks The routine to copy short blocks is often implemented as a sequence of MOV instructions. 504
  • 529. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS Listing 43.15: memcpy() example void memcpy_7(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 7); }; Listing 43.16: Optimizing MSVC 2010 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_7 PROC mov ecx, DWORD PTR _inbuf$[esp-4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR _outbuf$[esp-4] mov DWORD PTR [eax+10], edx mov dx, WORD PTR [ecx+4] mov WORD PTR [eax+14], dx mov cl, BYTE PTR [ecx+6] mov BYTE PTR [eax+16], cl ret 0 _memcpy_7 ENDP Listing 43.17: Optimizing GCC 4.8.1 memcpy_7: push ebx mov eax, DWORD PTR [esp+8] mov ecx, DWORD PTR [esp+12] mov ebx, DWORD PTR [eax] lea edx, [ecx+10] mov DWORD PTR [ecx+10], ebx movzx ecx, WORD PTR [eax+4] mov WORD PTR [edx+4], cx movzx eax, BYTE PTR [eax+6] mov BYTE PTR [edx+6], al pop ebx ret That’s usually done as follows: 4-byte blocks are copied first, then a 16-bit word (if needed), then the last byte (if needed). Structures are also copied using MOV: 21.4.1 on page 365. Long blocks The compilers behave differently in this case. Listing 43.18: memcpy() example void memcpy_128(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 128); }; void memcpy_123(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 123); }; For copying 128 bytes, MSVC uses a single MOVSD instruction (because 128 divides evenly by 4): Listing 43.19: Optimizing MSVC 2010 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_128 PROC push esi mov esi, DWORD PTR _inbuf$[esp] push edi mov edi, DWORD PTR _outbuf$[esp+4] add edi, 10 mov ecx, 32 rep movsd 505
  • 530. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS pop edi pop esi ret 0 _memcpy_128 ENDP When copying 123 bytes, 30 32-byte words are copied first using MOVSD (that’s 120 bytes), then 2 bytes are copied using MOVSW, then one more byte using MOVSB. Listing 43.20: Optimizing MSVC 2010 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_123 PROC push esi mov esi, DWORD PTR _inbuf$[esp] push edi mov edi, DWORD PTR _outbuf$[esp+4] add edi, 10 mov ecx, 30 rep movsd movsw movsb pop edi pop esi ret 0 _memcpy_123 ENDP GCC uses one big universal functions, that works for any block size: Listing 43.21: Optimizing GCC 4.8.1 memcpy_123: .LFB3: push edi mov eax, 123 push esi mov edx, DWORD PTR [esp+16] mov esi, DWORD PTR [esp+12] lea edi, [edx+10] test edi, 1 jne .L24 test edi, 2 jne .L25 .L7: mov ecx, eax xor edx, edx shr ecx, 2 test al, 2 rep movsd je .L8 movzx edx, WORD PTR [esi] mov WORD PTR [edi], dx mov edx, 2 .L8: test al, 1 je .L5 movzx eax, BYTE PTR [esi+edx] mov BYTE PTR [edi+edx], al .L5: pop esi pop edi ret .L24: movzx eax, BYTE PTR [esi] lea edi, [edx+11] add esi, 1 test edi, 2 mov BYTE PTR [edx+10], al mov eax, 122 je .L7 .L25: movzx edx, WORD PTR [esi] 506
  • 531. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS add edi, 2 add esi, 2 sub eax, 2 mov WORD PTR [edi-2], dx jmp .L7 .LFE3: Universal memory copy functions usually work as follows: calculate how many 32-bit words can be copied, then copy them using MOVSD, then copy the remaining bytes. More complex copy functions use SIMD instructions and also take the memory alignment in consideration. 43.1.6 memcmp() Listing 43.22: memcmp() example void memcpy_1235(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 1235); }; For any block size, MSVC 2010 inserts the same universal function: Listing 43.23: Optimizing MSVC 2010 _buf1$ = 8 ; size = 4 _buf2$ = 12 ; size = 4 _memcmp_1235 PROC mov edx, DWORD PTR _buf2$[esp-4] mov ecx, DWORD PTR _buf1$[esp-4] push esi push edi mov esi, 1235 add edx, 10 $LL4@memcmp_123: mov eax, DWORD PTR [edx] cmp eax, DWORD PTR [ecx] jne SHORT $LN10@memcmp_123 sub esi, 4 add ecx, 4 add edx, 4 cmp esi, 4 jae SHORT $LL4@memcmp_123 $LN10@memcmp_123: movzx edi, BYTE PTR [ecx] movzx eax, BYTE PTR [edx] sub eax, edi jne SHORT $LN7@memcmp_123 movzx eax, BYTE PTR [edx+1] movzx edi, BYTE PTR [ecx+1] sub eax, edi jne SHORT $LN7@memcmp_123 movzx eax, BYTE PTR [edx+2] movzx edi, BYTE PTR [ecx+2] sub eax, edi jne SHORT $LN7@memcmp_123 cmp esi, 3 jbe SHORT $LN6@memcmp_123 movzx eax, BYTE PTR [edx+3] movzx ecx, BYTE PTR [ecx+3] sub eax, ecx $LN7@memcmp_123: sar eax, 31 pop edi or eax, 1 pop esi ret 0 $LN6@memcmp_123: pop edi xor eax, eax pop esi 507
  • 532. CHAPTER 43. INLINE FUNCTIONS 43.1. STRINGS AND MEMORY FUNCTIONS ret 0 _memcmp_1235 ENDP 43.1.7 IDA script I wrote a small IDA script for searching and folding such very frequently seen pieces of inline code: GitHub. 508
  • 533. CHAPTER 44. C99 RESTRICT Chapter 44 C99 restrict Here is a reason why FORTRAN programs, in some cases, work faster than C/C++ ones. void f1 (int* x, int* y, int* sum, int* product, int* sum_product, int* update_me, size_t s) { for (int i=0; i<s; i++) { sum[i]=x[i]+y[i]; product[i]=x[i]*y[i]; update_me[i]=i*123; // some dummy value sum_product[i]=sum[i]+product[i]; }; }; That’s very simple example with one specific thing in it: the pointer to the update_me array could be a pointer to the sum array, product array, or even the sum_product array—nothing forbids that, right? The compiler is fully aware of this, so it generates code with four stages in the loop body: • calculate next sum[i] • calculate next product[i] • calculate next update_me[i] • calculate next sum_product[i]— on this stage, we need to load from memory the already calculated sum[i] and product[i] Is it possible to optimize the last stage? Since we have already calculated sum[i] and product[i] it is not necessary to load them again from memory. Yes, but compiler is not sure that nothing was overwritten in the 3rd stage! This is called “pointer aliasing”, a situation when the compiler cannot be sure that a memory to which a pointer is pointing was not changed. restrict in the C99 standard[ISO07, pp. 6.7.3/1] is a promise, given by programmer to the compiler that the function arguments marked by this keyword always points to different memory locations and never intersects. To be more precise and describe this formally, restrict shows that only this pointer is to be used to access an object, and no other pointer will be used for it. It can be even said the object will be accessed only via one single pointer, if it is marked as restrict. Let’s add this keyword to each pointer argument: void f2 (int* restrict x, int* restrict y, int* restrict sum, int* restrict product, int* ⤦ restrict sum_product, int* restrict update_me, size_t s) { for (int i=0; i<s; i++) { sum[i]=x[i]+y[i]; product[i]=x[i]*y[i]; update_me[i]=i*123; // some dummy value sum_product[i]=sum[i]+product[i]; }; }; Let’s see results: Listing 44.1: GCC x64: f1() f1: push r15 r14 r13 r12 rbp rdi rsi rbx 509
  • 534. CHAPTER 44. C99 RESTRICT mov r13, QWORD PTR 120[rsp] mov rbp, QWORD PTR 104[rsp] mov r12, QWORD PTR 112[rsp] test r13, r13 je .L1 add r13, 1 xor ebx, ebx mov edi, 1 xor r11d, r11d jmp .L4 .L6: mov r11, rdi mov rdi, rax .L4: lea rax, 0[0+r11*4] lea r10, [rcx+rax] lea r14, [rdx+rax] lea rsi, [r8+rax] add rax, r9 mov r15d, DWORD PTR [r10] add r15d, DWORD PTR [r14] mov DWORD PTR [rsi], r15d ; store to sum[] mov r10d, DWORD PTR [r10] imul r10d, DWORD PTR [r14] mov DWORD PTR [rax], r10d ; store to product[] mov DWORD PTR [r12+r11*4], ebx ; store to update_me[] add ebx, 123 mov r10d, DWORD PTR [rsi] ; reload sum[i] add r10d, DWORD PTR [rax] ; reload product[i] lea rax, 1[rdi] cmp rax, r13 mov DWORD PTR 0[rbp+r11*4], r10d ; store to sum_product[] jne .L6 .L1: pop rbx rsi rdi rbp r12 r13 r14 r15 ret Listing 44.2: GCC x64: f2() f2: push r13 r12 rbp rdi rsi rbx mov r13, QWORD PTR 104[rsp] mov rbp, QWORD PTR 88[rsp] mov r12, QWORD PTR 96[rsp] test r13, r13 je .L7 add r13, 1 xor r10d, r10d mov edi, 1 xor eax, eax jmp .L10 .L11: mov rax, rdi mov rdi, r11 .L10: mov esi, DWORD PTR [rcx+rax*4] mov r11d, DWORD PTR [rdx+rax*4] mov DWORD PTR [r12+rax*4], r10d ; store to update_me[] add r10d, 123 lea ebx, [rsi+r11] imul r11d, esi mov DWORD PTR [r8+rax*4], ebx ; store to sum[] mov DWORD PTR [r9+rax*4], r11d ; store to product[] add r11d, ebx mov DWORD PTR 0[rbp+rax*4], r11d ; store to sum_product[] lea r11, 1[rdi] cmp r11, r13 jne .L11 .L7: pop rbx rsi rdi rbp r12 r13 510
  • 535. CHAPTER 44. C99 RESTRICT ret The difference between the compiled f1() and f2() functions is as follows: in f1(), sum[i] and product[i] are reloaded in the middle of the loop, and in f2() there is no such thing, the already calculated values are used, since we “promised” the compiler that no one and nothing will change the values in sum[i] and product[i] during the execution of the loop’s body, so it is “sure” that there is no need to load the value from memory again. Obviously, the second example works faster. But what if the pointers in the function’s arguments intersect somehow? This is on the programmer’s conscience, and the results will be incorrect. Let’s go back to FORTRAN. Compilers of this programming language treats all pointers as such, so when it was not possible to set restrict in C, FORTRAN can generate faster code in these cases. How practical is it? In the cases when the function works with several big blocks in memory. There are a lot of such in linear algebra, for instance. A lot of linear algebra is done on supercomputers/HPC1 , so probably that is why, traditionally, FORTRAN is still used there [Loh10]. But when the number of iterations is not very big, certainly, the speed boost may not to be significant. 1High-Performance Computing 511
  • 536. CHAPTER 45. BRANCHLESS ABS() FUNCTION Chapter 45 Branchless abs() function Let’s revisit an example I gave earlier 12.2 on page 127 and ask ourselves, is it possible to make a branchless version of the function in x86 code? int my_abs (int i) { if (i<0) return -i; else return i; }; And the answer is yes. 45.1 Optimizing GCC 4.9.1 x64 We could see it if we compile it using optimizing GCC 4.9: Listing 45.1: Optimizing GCC 4.9 x64 my_abs: mov edx, edi mov eax, edi sar edx, 31 ; EDX is 0xFFFFFFFF here if sign of input value is minus ; EDX is 0 if sign of input value is plus (including 0) ; the following two instructions have effect only if EDX is 0xFFFFFFFF ; or idle if EDX is 0 xor eax, edx sub eax, edx ret This is how it works: Arithmetically shift the input value left by 31. Arithmetical shift implies sign extension, so if the MSB is 1, all 32 bits are to be filled with 1, or with 0 if otherwise. In other words, the SAR REG, 31 instruction makes 0xFFFFFFFF if the sign was negative or 0 if positive. After the execution of SAR, we have this value in EDX. Then, if the value is 0xFFFFFFFF (i.e., the sign is negative), the input value is inverted (because XOR REG, 0xFFFFFFFF is effectively an inverse all bits operation). Then, again, if the value is 0xFFFFFFFF (i.e., the sign is negative), 1 is added to the final result (because subtracting −1 from some value resulting in incrementing it). Inversion of all bits and incrementing is exactly how two’s complement value is negated: 30 on page 451. We may observe that the last two instruction do something if the sign of the input value is negative. Otherwise (if the sign is positive) they do nothing at all, leaving the input value untouched. The algorithm is explained in [War02, pp. 2-4]. I’m not sure, how GCC did it, deduced it by itself or found a suitable pattern among known ones? 45.2 Optimizing GCC 4.9 ARM64 GCC 4.9 for ARM64 generates mostly the same, just decides to use the full 64-bit registers. There are less instructions, because the input value can be shifted using a suffixed instruction (“asr”) instead of using a separate instruction. Listing 45.2: Optimizing GCC 4.9 ARM64 my_abs: 512
  • 537. CHAPTER 45. BRANCHLESS ABS() FUNCTION 45.2. OPTIMIZING GCC 4.9 ARM64 ; sign-extend input 32-bit value to X0 64-bit register: sxtw x0, w0 eor x1, x0, x0, asr 63 ; X1=X0^(X0>>63) (shift is arithmetical) sub x0, x1, x0, asr 63 ; X0=X1-(X0>>63)=X0^(X0>>63)-(X0>>63) (all shifts are arithmetical) ret 513
  • 538. CHAPTER 46. VARIADIC FUNCTIONS Chapter 46 Variadic functions Functions like printf() and scanf() can have a variable number of arguments. How are these arguments accessed? 46.1 Computing arithmetic mean Let’s imagine that we need to calculate arithmetic mean, and for some weird reason we need to specify all the values as function arguments. But it’s impossible to get the number of arguments in a variadic function in C/C++, so I’ll denote the value of −1 as a terminator. There is the standard stdarg.h header file which define macros for dealing with such arguments. The printf() and scanf() functions use them as well. #include <stdio.h> #include <stdarg.h> int arith_mean(int v, ...) { va_list args; int sum=v, count=1, i; va_start(args, v); while(1) { i=va_arg(args, int); if (i==-1) // terminator break; sum=sum+i; count++; } va_end(args); return sum/count; }; int main() { printf ("%dn", arith_mean (1, 2, 7, 10, 15, -1 /* terminator */)); }; The first argument has to be treated just like a normal argument. All other arguments are loaded using the va_arg macro and then summed. So what is inside? 46.1.1 cdecl calling conventions Listing 46.1: Optimizing MSVC 6.0 _v$ = 8 _arith_mean PROC NEAR mov eax, DWORD PTR _v$[esp-4] ; load 1st argument into sum push esi mov esi, 1 ; count=1 lea edx, DWORD PTR _v$[esp] ; address of the 1st argument 514
  • 539. CHAPTER 46. VARIADIC FUNCTIONS 46.1. COMPUTING ARITHMETIC MEAN $L838: mov ecx, DWORD PTR [edx+4] ; load next argument add edx, 4 ; shift pointer to the next argument cmp ecx, -1 ; is it -1? je SHORT $L856 ; exit if so add eax, ecx ; sum = sum + loaded argument inc esi ; count++ jmp SHORT $L838 $L856: ; calculate quotient cdq idiv esi pop esi ret 0 _arith_mean ENDP $SG851 DB '%d', 0aH, 00H _main PROC NEAR push -1 push 15 push 10 push 7 push 2 push 1 call _arith_mean push eax push OFFSET FLAT:$SG851 ; '%d' call _printf add esp, 32 ret 0 _main ENDP The arguments, as we may see, are passed to main() one-by-one. The first argument is pushed into the local stack as first. The terminating value (−1) is pushed last. The arith_mean() function takes the value of the first argument and stores it in the sum variable. Then, it sets the EDX register to the address of the second argument, takes the value from it, adds it to sum, and does this in an infinite loop, until −1 is found. When it’s found, the sum is divided by the number of all values (excluding −1) and the quotient is returned. So, in other words, the function treats the stack fragment as an array of integer values of infinite length. Now we can understand why the cdecl calling convention forces us to push the first argument into the stack as last. Because otherwise, it would not be possible to find the first argument, or, for printf-like functions, it would not be possible to find the address of the format-string. 46.1.2 Register-based calling conventions The observant reader may ask, what about calling conventions where the first few arguments are passed in registers? Let’s see: Listing 46.2: Optimizing MSVC 2012 x64 $SG3013 DB '%d', 0aH, 00H v$ = 8 arith_mean PROC mov DWORD PTR [rsp+8], ecx ; 1st argument mov QWORD PTR [rsp+16], rdx ; 2nd argument mov QWORD PTR [rsp+24], r8 ; 3rd argument mov eax, ecx ; sum = 1st argument lea rcx, QWORD PTR v$[rsp+8] ; pointer to the 2nd argument mov QWORD PTR [rsp+32], r9 ; 4th argument mov edx, DWORD PTR [rcx] ; load 2nd argument mov r8d, 1 ; count=1 cmp edx, -1 ; 2nd argument is -1? je SHORT $LN8@arith_mean ; exit if so $LL3@arith_mean: add eax, edx ; sum = sum + loaded argument mov edx, DWORD PTR [rcx+8] ; load next argument 515
  • 540. CHAPTER 46. VARIADIC FUNCTIONS 46.1. COMPUTING ARITHMETIC MEAN lea rcx, QWORD PTR [rcx+8] ; shift pointer to point to the argument after next inc r8d ; count++ cmp edx, -1 ; is loaded argument -1? jne SHORT $LL3@arith_mean ; go to loop begin if its not' $LN8@arith_mean: ; calculate quotient cdq idiv r8d ret 0 arith_mean ENDP main PROC sub rsp, 56 mov edx, 2 mov DWORD PTR [rsp+40], -1 mov DWORD PTR [rsp+32], 15 lea r9d, QWORD PTR [rdx+8] lea r8d, QWORD PTR [rdx+5] lea ecx, QWORD PTR [rdx-1] call arith_mean lea rcx, OFFSET FLAT:$SG3013 mov edx, eax call printf xor eax, eax add rsp, 56 ret 0 main ENDP We see that the first 4 arguments are passed in the registers and two more — in the stack. The arith_mean() function first places these 4 arguments into the Shadow Space and then treats the Shadow Space and stack behind it as a single continuous array! What about GCC? Things are slightly clumsier here, because now the function is divided in two parts: the first part saves the registers into the “red zone”, processes that space, and the second part of the function processes the stack: Listing 46.3: Optimizing GCC 4.9.1 x64 arith_mean: lea rax, [rsp+8] ; save 6 input registers in "red zone" in the local stack mov QWORD PTR [rsp-40], rsi mov QWORD PTR [rsp-32], rdx mov QWORD PTR [rsp-16], r8 mov QWORD PTR [rsp-24], rcx mov esi, 8 mov QWORD PTR [rsp-64], rax lea rax, [rsp-48] mov QWORD PTR [rsp-8], r9 mov DWORD PTR [rsp-72], 8 lea rdx, [rsp+8] mov r8d, 1 mov QWORD PTR [rsp-56], rax jmp .L5 .L7: ; work out saved arguments lea rax, [rsp-48] mov ecx, esi add esi, 8 add rcx, rax mov ecx, DWORD PTR [rcx] cmp ecx, -1 je .L4 .L8: add edi, ecx add r8d, 1 .L5: ; decide, which part we will work out now. ; is current argument number less or equal 6? cmp esi, 47 jbe .L7 ; no, process saved arguments then ; work out arguments from stack mov rcx, rdx 516
  • 541. CHAPTER 46. VARIADIC FUNCTIONS 46.2. VPRINTF() FUNCTION CASE add rdx, 8 mov ecx, DWORD PTR [rcx] cmp ecx, -1 jne .L8 .L4: mov eax, edi cdq idiv r8d ret .LC1: .string "%dn" main: sub rsp, 8 mov edx, 7 mov esi, 2 mov edi, 1 mov r9d, -1 mov r8d, 15 mov ecx, 10 xor eax, eax call arith_mean mov esi, OFFSET FLAT:.LC1 mov edx, eax mov edi, 1 xor eax, eax add rsp, 8 jmp __printf_chk By the way, a similar usage of the Shadow Space is also considered here : 64.8 on page 669. 46.2 vprintf() function case Many programmers define their own logging functions which take a printf-like format string + a variable number of argu- ments. Another popular example is the die() function, which prints some message and exits. We need some way to pack input arguments of unknown number and pass them to the printf() function. But how? That’s why there are functions with “v” in name. One of them is vprintf(): it takes a format-string and a pointer to a variable of type va_list: #include <stdlib.h> #include <stdarg.h> void die (const char * fmt, ...) { va_list va; va_start (va, fmt); vprintf (fmt, va); exit(0); }; By closer examination, we can see that va_list is a pointer to an array. Let’s compile: Listing 46.4: Optimizing MSVC 2010 _fmt$ = 8 _die PROC ; load 1st argument (format-string) mov ecx, DWORD PTR _fmt$[esp-4] ; get pointer to the 2nd argument lea eax, DWORD PTR _fmt$[esp] push eax ; pass pointer push ecx call _vprintf add esp, 8 push 0 call _exit $LN3@die: int 3 _die ENDP 517
  • 542. CHAPTER 46. VARIADIC FUNCTIONS 46.2. VPRINTF() FUNCTION CASE We see that all our function does is just taking a pointer to the arguments and passing it to vprintf(), and that function is treating it like an infinite array of arguments! Listing 46.5: Optimizing MSVC 2012 x64 fmt$ = 48 die PROC ; save first 4 arguments in Shadow Space mov QWORD PTR [rsp+8], rcx mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+24], r8 mov QWORD PTR [rsp+32], r9 sub rsp, 40 lea rdx, QWORD PTR fmt$[rsp+8] ; pass pointer to the 1st argument ; RCX here is still points to the 1st argument (format-string) of die() ; so vprintf() will take it right from RCX call vprintf xor ecx, ecx call exit int 3 die ENDP 518
  • 543. CHAPTER 47. STRINGS TRIMMING Chapter 47 Strings trimming A very common string processing task is to remove some characters at the start and/or at the end. In this example, we are going to work with a function which removes all newline characters (CR1 /LF2 ) from the end of the input string: #include <stdio.h> #include <string.h> char* str_trim (char *s) { char c; size_t str_len; // work as long as r or n is at the end of string // stop if some other character there or its an empty string' // (at start or due to our operation) for (str_len=strlen(s); str_len>0 && (c=s[str_len-1]); str_len--) { if (c=='r' || c=='n') s[str_len-1]=0; else break; }; return s; }; int main() { // test // strdup() is used to copy text string into data segment, // because it will crash on Linux otherwise, // where text strings are allocated in constant data segment, // and not modifiable. printf ("[%s]n", str_trim (strdup(""))); printf ("[%s]n", str_trim (strdup("n"))); printf ("[%s]n", str_trim (strdup("r"))); printf ("[%s]n", str_trim (strdup("nr"))); printf ("[%s]n", str_trim (strdup("rn"))); printf ("[%s]n", str_trim (strdup("test1rn"))); printf ("[%s]n", str_trim (strdup("test2nr"))); printf ("[%s]n", str_trim (strdup("test3nrnr"))); printf ("[%s]n", str_trim (strdup("test4n"))); printf ("[%s]n", str_trim (strdup("test5r"))); printf ("[%s]n", str_trim (strdup("test6rrr"))); }; The input argument is always returned on exit, this is convenient when you need to chain string processing functions, like it was done here in the main() function. The second part of for() (str_len>0 && (c=s[str_len-1])) is the so called “short-circuit” in C/C++ and is very convenient [Yur13, p. 1.3.8]. The C/C++ compilers guarantee an evaluation sequence from left to right. So if the first clause 1Carriage return (13 or’r’ in C/C++) 2Line feed (10 or’n’ in C/C++) 519
  • 544. CHAPTER 47. STRINGS TRIMMING 47.1. X64: OPTIMIZING MSVC 2013 is false after evaluation, the second one is never to be evaluated. 47.1 x64: Optimizing MSVC 2013 Listing 47.1: Optimizing MSVC 2013 x64 s$ = 8 str_trim PROC ; RCX is the first function argument and it always holds pointer to the string ; this is strlen() function inlined right here: ; set RAX to 0xFFFFFFFFFFFFFFFF (-1) or rax, -1 $LL14@str_trim: inc rax cmp BYTE PTR [rcx+rax], 0 jne SHORT $LL14@str_trim ; is string length zero? exit then test eax, eax $LN18@str_trim: je SHORT $LN15@str_trim ; RAX holds string length ; here is probably disassembler (or assembler printing routine) error, ; LEA RDX... should be here instead of LEA EDX... lea edx, DWORD PTR [rax-1] ; idle instruction: EAX will be reset at the next instructions execution' mov eax, edx ; load character at address s[str_len-1] movzx eax, BYTE PTR [rdx+rcx] ; save also pointer to the last character to R8 lea r8, QWORD PTR [rdx+rcx] cmp al, 13 ; is it 'r'? je SHORT $LN2@str_trim cmp al, 10 ; is it 'n'? jne SHORT $LN15@str_trim $LN2@str_trim: ; store 0 to that place mov BYTE PTR [r8], 0 mov eax, edx ; check character for 0, but conditional jump is above... test edx, edx jmp SHORT $LN18@str_trim $LN15@str_trim: ; return "s" mov rax, rcx ret 0 str_trim ENDP First, MSVC inlined the strlen() function code, because it concluded this is to be faster than the usual strlen() work + the cost of calling it and returning from it. This is called inlining: 43 on page 500. The first instruction of the inlined strlen() is OR RAX, 0xFFFFFFFFFFFFFFFF. I don’t know why MSVC uses OR instead of MOV RAX, 0xFFFFFFFFFFFFFFFF, but it does this often. And of course, it is equivalent: all bits are set, and a number with all bits set is −1 in two’s complement arithmetic: 30 on page 451. Why would the −1 number be used in strlen(), one might ask. Due to optimizations, of course. Here is the code that MSVC generated: Listing 47.2: Inlined strlen() by MSVC 2013 x64 ; RCX = pointer to the input string ; RAX = current string length or rax, -1 label: inc rax cmp BYTE PTR [rcx+rax], 0 jne SHORT label ; RAX = string length Try to write shorter if you want to initialize the counter at 0! Here is my attempt: 520
  • 545. CHAPTER 47. STRINGS TRIMMING 47.2. X64: NON-OPTIMIZING GCC 4.9.1 Listing 47.3: My version of strlen() ; RCX = pointer to the input string ; RAX = current string length xor rax, rax label: cmp byte ptr [rcx+rax], 0 jz exit inc rax jmp label exit: ; RAX = string length I failed. We need to use additional JMP instruction! So what the MSVC 2013 compiler did is to move the INC instruction to the place before the actual character loading. If the first character is 0, that’s OK, RAX is 0 at this moment, so the resulting string length is 0. The rest in this function seems easy to understand. There is another trick at the end. If we do not count strlen()’s inlined code, there are only 3 conditional jumps in the function. There should be 4: the 4th has to be located at the function end, to check if the character is zero. But there is an unconditional jump to the “$LN18@str_trim” label, where we see JE, which was first used to check if the input string is empty, right after strlen() finishes. So the code uses the JE instruction at this place for two purposes! This may be overkill, but nevertheless, MSVC did it. You can read more on why it’s important to do the job without conditional jumps, if possible: 33.1 on page 456. 47.2 x64: Non-optimizing GCC 4.9.1 str_trim: push rbp mov rbp, rsp sub rsp, 32 mov QWORD PTR [rbp-24], rdi ; for() first part begins here mov rax, QWORD PTR [rbp-24] mov rdi, rax call strlen mov QWORD PTR [rbp-8], rax ; str_len ; for() first part ends here jmp .L2 ; for() body begins here .L5: cmp BYTE PTR [rbp-9], 13 ; c=='r'? je .L3 cmp BYTE PTR [rbp-9], 10 ; c=='n'? jne .L4 .L3: mov rax, QWORD PTR [rbp-8] ; str_len lea rdx, [rax-1] ; EDX=str_len-1 mov rax, QWORD PTR [rbp-24] ; s add rax, rdx ; RAX=s+str_len-1 mov BYTE PTR [rax], 0 ; s[str_len-1]=0 ; for() body ends here ; for() third part begins here sub QWORD PTR [rbp-8], 1 ; str_len-- ; for() third part ends here .L2: ; for() second part begins here cmp QWORD PTR [rbp-8], 0 ; str_len==0? je .L4 ; exit then ; check second clause, and load "c" mov rax, QWORD PTR [rbp-8] ; RAX=str_len lea rdx, [rax-1] ; RDX=str_len-1 mov rax, QWORD PTR [rbp-24] ; RAX=s add rax, rdx ; RAX=s+str_len-1 movzx eax, BYTE PTR [rax] ; AL=s[str_len-1] mov BYTE PTR [rbp-9], al ; store loaded char into "c" cmp BYTE PTR [rbp-9], 0 ; is it zero? jne .L5 ; yes? exit then ; for() second part ends here .L4: 521
  • 546. CHAPTER 47. STRINGS TRIMMING 47.3. X64: OPTIMIZING GCC 4.9.1 ; return "s" mov rax, QWORD PTR [rbp-24] leave ret I have added my comments. After the execution of strlen(), the control is passed to the L2 label, and there two clauses are checked, one after another. The second will never be checked, if the first one (str_len==0) is false (this is “short-circuit”). Now let’s see this function in short form: • First for() part (call to strlen()) • goto L2 • L5: • for() body. goto exit, if needed • for() third part (decrement of str_len) • L2: • for() second part: check first clause, then second. goto loop body begin or exit. • L4: • // exit • return s 47.3 x64: Optimizing GCC 4.9.1 str_trim: push rbx mov rbx, rdi ; RBX will always be "s" call strlen ; check for str_len==0 and exit if its so' test rax, rax je .L9 lea rdx, [rax-1] ; RDX will always contain str_len-1 value, not str_len ; so RDX is more like buffer index variable lea rsi, [rbx+rdx] ; RSI=s+str_len-1 movzx ecx, BYTE PTR [rsi] ; load character test cl, cl je .L9 ; exit if its zero' cmp cl, 10 je .L4 cmp cl, 13 ; exit if its not' 'n' and not 'r' jne .L9 .L4: ; this is weird instruction. we need RSI=s-1 here. ; its possible to get it by' MOV RSI, EBX / DEC RSI ; but this is two instructions instead of one sub rsi, rax ; RSI = s+str_len-1-str_len = s-1 ; main loop begin .L12: test rdx, rdx ; store zero at address s-1+str_len-1+1 = s-1+str_len = s+str_len-1 mov BYTE PTR [rsi+1+rdx], 0 ; check for str_len-1==0. exit if so. je .L9 sub rdx, 1 ; equivalent to str_len-- ; load next character at address s+str_len-1 movzx ecx, BYTE PTR [rbx+rdx] test cl, cl ; is it zero? exit then je .L9 cmp cl, 10 ; is it 'n'? je .L12 522
  • 547. CHAPTER 47. STRINGS TRIMMING 47.4. ARM64: NON-OPTIMIZING GCC (LINARO) 4.9 cmp cl, 13 ; is it 'r'? je .L12 .L9: ; return "s" mov rax, rbx pop rbx ret Now this is more complex. The code before the loop’s body start is executed only once, but it has the CR/LF characters check too! What is this code duplication for? The common way to implement the main loop is probably this: • (loop start) check for CR/LF characters, make decisions • store zero character But GCC has decided to reverse these two steps. Of course, store zero character cannot be first step, so another check is needed: • workout first character. match it to CR/LF, exit if character is not CR/LF • (loop begin) store zero character • check for CR/LF characters, make decisions Now the main loop is very short, which is good for modern CPUs. The code doesn’t use the str_len variable, but str_len-1. So this is more like an index in a buffer. Apparently, GCC notices that the str_len-1 statement is used twice. So it’s better to allocate a variable which always holds a value that’s smaller than the current string length by one, and decrement it (this is the same effect as decrementing the str_len variable). 47.4 ARM64: Non-optimizing GCC (Linaro) 4.9 This implementation is straightforward: Listing 47.4: Non-optimizing GCC (Linaro) 4.9 str_trim: stp x29, x30, [sp, -48]! add x29, sp, 0 str x0, [x29,24] ; copy input argument into local stack ldr x0, [x29,24] ; s bl strlen str x0, [x29,40] ; str_len variable in local stack b .L2 ; main loop begin .L5: ldrb w0, [x29,39] ; W0=c cmp w0, 13 ; is it 'r'? beq .L3 ldrb w0, [x29,39] ; W0=c cmp w0, 10 ; is it 'n'? bne .L4 ; goto exit if it is not .L3: ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 ldr x1, [x29,24] ; X1=s add x0, x1, x0 ; X0=s+str_len-1 strb wzr, [x0] ; write byte at s+str_len-1 ; decrement str_len: ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 str x0, [x29,40] 523
  • 548. CHAPTER 47. STRINGS TRIMMING 47.5. ARM64: OPTIMIZING GCC (LINARO) 4.9 ; save X0 (or str_len-1) to local stack .L2: ldr x0, [x29,40] ; str_len==0? cmp x0, xzr ; goto exit then beq .L4 ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 ldr x1, [x29,24] ; X1=s add x0, x1, x0 ; X0=s+str_len-1 ; load byte at address s+str_len-1 to W0 ldrb w0, [x0] strb w0, [x29,39] ; store loaded byte to "c" ldrb w0, [x29,39] ; reload it ; is it zero byte? cmp w0, wzr ; goto exit, if its zero or to L5 if its not'' bne .L5 .L4: ; return s ldr x0, [x29,24] ldp x29, x30, [sp], 48 ret 47.5 ARM64: Optimizing GCC (Linaro) 4.9 This is a more advanced optimization. The first character is loaded at the beginning, and compared against 10 (the LF character). Characters are also loaded in the main loop, for the characters after first one. This is somewhat similar to the 47.3 on page 522 example. Listing 47.5: Optimizing GCC (Linaro) 4.9 str_trim: stp x29, x30, [sp, -32]! add x29, sp, 0 str x19, [sp,16] mov x19, x0 ; X19 will always hold value of "s" bl strlen ; X0=str_len cbz x0, .L9 ; goto L9 (exit) if str_len==0 sub x1, x0, #1 ; X1=X0-1=str_len-1 add x3, x19, x1 ; X3=X19+X1=s+str_len-1 ldrb w2, [x19,x1] ; load byte at address X19+X1=s+str_len-1 ; W2=loaded character cbz w2, .L9 ; is it zero? jump to exit then cmp w2, 10 ; is it 'n'? bne .L15 .L12: ; main loop body. loaded character is always 10 or 13 at this moment! sub x2, x1, x0 ; X2=X1-X0=str_len-1-str_len=-1 add x2, x3, x2 ; X2=X3+X2=s+str_len-1+(-1)=s+str_len-2 strb wzr, [x2,1] ; store zero byte at address s+str_len-2+1=s+str_len-1 cbz x1, .L9 ; str_len-1==0? goto exit, if so sub x1, x1, #1 ; str_len-- ldrb w2, [x19,x1] ; load next character at address X19+X1=s+str_len-1 cmp w2, 10 ; is it 'n'? cbz w2, .L9 ; jump to exit, if its zero' beq .L12 ; jump to begin loop, if its' 'n' .L15: 524
  • 549. CHAPTER 47. STRINGS TRIMMING 47.6. ARM: OPTIMIZING KEIL 6/2013 (ARM MODE) cmp w2, 13 ; is it 'r'? beq .L12 ; yes, jump to the loop body begin .L9: ; return "s" mov x0, x19 ldr x19, [sp,16] ldp x29, x30, [sp], 32 ret 47.6 ARM: Optimizing Keil 6/2013 (ARM mode) And again, the compiler took advantage of ARM mode’s conditional instructions, so the code is much more compact. Listing 47.6: Optimizing Keil 6/2013 (ARM mode) str_trim PROC PUSH {r4,lr} ; R0=s MOV r4,r0 ; R4=s BL strlen ; strlen() takes "s" value from R0 ; R0=str_len MOV r3,#0 ; R3 will always hold 0 |L0.16| CMP r0,#0 ; str_len==0? ADDNE r2,r4,r0 ; (if str_len!=0) R2=R4+R0=s+str_len LDRBNE r1,[r2,#-1] ; (if str_len!=0) R1=load byte at address R2-1=s+str_len-1 CMPNE r1,#0 ; (if str_len!=0) compare loaded byte against 0 BEQ |L0.56| ; jump to exit if str_len==0 or loaded byte is 0 CMP r1,#0xd ; is loaded byte 'r'? CMPNE r1,#0xa ; (if loaded byte is not 'r') is loaded byte 'r'? SUBEQ r0,r0,#1 ; (if loaded byte is 'r' or 'n') R0-- or str_len-- STRBEQ r3,[r2,#-1] ; (if loaded byte is 'r' or 'n') store R3 (zero) at address R2-1=s+str_len-1 BEQ |L0.16| ; jump to loop begin if loaded byte was 'r' or 'n' |L0.56| ; return "s" MOV r0,r4 POP {r4,pc} ENDP 47.7 ARM: Optimizing Keil 6/2013 (thumb mode) There are less conditional instructions in Thumb mode, so the code is simpler. But there are is really weird thing with the 0x20 and 0x19 offsets. Why did the Keil compiler do so? Honestly, I have no idea. Probably, this is a quirk of Keil’s optimization process. Nevertheless, the code works correctly. Listing 47.7: Optimizing Keil 6/2013 (thumb mode) str_trim PROC PUSH {r4,lr} MOVS r4,r0 ; R4=s BL strlen ; strlen() takes "s" value from R0 ; R0=str_len MOVS r3,#0 ; R3 will always hold 0 B |L0.24| |L0.12| CMP r1,#0xd ; is loaded byte 'r'? BEQ |L0.20| CMP r1,#0xa ; is loaded byte 'n'? BNE |L0.38| ; jump to exit, if no |L0.20| SUBS r0,r0,#1 ; R0-- or str_len-- STRB r3,[r2,#0x1f] ; store 0 at address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1 525
  • 550. CHAPTER 47. STRINGS TRIMMING 47.8. MIPS |L0.24| CMP r0,#0 ; str_len==0? BEQ |L0.38| ; yes? jump to exit ADDS r2,r4,r0 ; R2=R4+R0=s+str_len SUBS r2,r2,#0x20 ; R2=R2-0x20=s+str_len-0x20 LDRB r1,[r2,#0x1f] ; load byte at address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1 to R1 CMP r1,#0 ; is loaded byte 0? BNE |L0.12| ; jump to loop begin, if its not 0' |L0.38| ; return "s" MOVS r0,r4 POP {r4,pc} ENDP 47.8 MIPS Listing 47.8: Optimizing GCC 4.4.5 (IDA) str_trim: ; IDA is not aware of local variable names, I gave them manually: saved_GP = -0x10 saved_S0 = -8 saved_RA = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+saved_RA($sp) sw $s0, 0x20+saved_S0($sp) sw $gp, 0x20+saved_GP($sp) ; call strlen(). input string address is still in $a0, strlen() will take it from there: lw $t9, (strlen & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jalr $t9 ; input string address is still in $a0, put it to $s0: move $s0, $a0 ; branch delay slot ; result of strlen() (i.e, length of string) is in $v0 now ; jump to exit if $v0==0 (i.e., if length of string is 0): beqz $v0, exit or $at, $zero ; branch delay slot, NOP addiu $a1, $v0, -1 ; $a1 = $v0-1 = str_len-1 addu $a1, $s0, $a1 ; $a1 = input string address + $a1 = s+strlen-1 ; load byte at address $a1: lb $a0, 0($a1) or $at, $zero ; load delay slot, NOP ; loaded byte is zero? jump to exit if its so': beqz $a0, exit or $at, $zero ; branch delay slot, NOP addiu $v1, $v0, -2 ; $v1 = str_len-2 addu $v1, $s0, $v1 ; $v1 = $s0+$v1 = s+str_len-2 li $a2, 0xD ; skip loop body: b loc_6C li $a3, 0xA ; branch delay slot loc_5C: ; load next byte from memory to $a0: lb $a0, 0($v1) move $a1, $v1 ; $a1=s+str_len-2 ; jump to exit if loaded byte is zero: beqz $a0, exit ; decrement str_len: addiu $v1, -1 ; branch delay slot 526
  • 551. CHAPTER 47. STRINGS TRIMMING 47.8. MIPS loc_6C: ; at this moment, $a0=loaded byte, $a2=0xD (CR symbol) and $a3=0xA (LF symbol) ; loaded byte is CR? jump to loc_7C then: beq $a0, $a2, loc_7C addiu $v0, -1 ; branch delay slot ; loaded byte is LF? jump to exit if its not LF': bne $a0, $a3, exit or $at, $zero ; branch delay slot, NOP loc_7C: ; loaded byte is CR at this moment ; jump to loc_5c (loop body begin) if str_len (in $v0) is not zero: bnez $v0, loc_5C ; simultaneously, store zero at that place in memory: sb $zero, 0($a1) ; branch delay slot ; "exit" label was named by me manually: exit: lw $ra, 0x20+saved_RA($sp) move $v0, $s0 lw $s0, 0x20+saved_S0($sp) jr $ra addiu $sp, 0x20 ; branch delay slot Registers prefixed with S- are also called “saved temporaries”, so $S0 value is saved in the local stack and restored upon finish. 527
  • 552. CHAPTER 48. TOUPPER() FUNCTION Chapter 48 toupper() function Another very popular function transforms symbol from lower case to upper case, if needed: char toupper (char c) { if(c>='a' && c<='z') return c-'a'+'A'; else return c; } 'a'+'A' expression is left in source code for better readability, it is to be optimized by compiler, of course 1 . The ASCII code of “a” symbol is 97 (or 0x61), and 65 (or 0x41) for “A” symbol. The difference (or distance) between them in ASCII table is 32 (or 0x20). For better understanding, reader may take a look at 7-bit standard ASCII table: Figure 48.1: 7-bit ASCII table in Emacs 48.1 x64 48.1.1 Two comparison operations Non-optimizing MSVC is straightforward: the code checks if input symbol is in [97..122] range (or in [‘a’..‘z’] range) and subtracts 32 in this case. There are also minor compiler artefact: Listing 48.1: Non-optimizing MSVC 2013 (x64) 1 c$ = 8 2 toupper PROC 3 mov BYTE PTR [rsp+8], cl 4 movsx eax, BYTE PTR c$[rsp] 5 cmp eax, 97 6 jl SHORT $LN2@toupper 7 movsx eax, BYTE PTR c$[rsp] 8 cmp eax, 122 9 jg SHORT $LN2@toupper 10 movsx eax, BYTE PTR c$[rsp] 11 sub eax, 32 12 jmp SHORT $LN3@toupper 1However, if to be meticulous, I think, there are still could be compilers which can’t optimize such expressions and leaving them right in the code. 528
  • 553. CHAPTER 48. TOUPPER() FUNCTION 48.1. X64 13 jmp SHORT $LN1@toupper ; compiler artefact 14 $LN2@toupper: 15 movzx eax, BYTE PTR c$[rsp] ; unnecessary casting 16 $LN1@toupper: 17 $LN3@toupper: ; compiler artefact 18 ret 0 19 toupper ENDP It’s important to notice that input byte is loaded into 64-bit local stack slot at line 3. All the rest bits ([8..63]) are untouched, i.e., contains some random noise (you’ll see it in debugger). All instructions operates only on byte-level, so it’s fine. The last MOVZX instruction at line 15 takes byte from local stack slot and zero-extends it into int 32-bit data type. Non-optimizing GCC does mostly the same: Listing 48.2: Non-optimizing GCC 4.9 (x64) toupper: push rbp mov rbp, rsp mov eax, edi mov BYTE PTR [rbp-4], al cmp BYTE PTR [rbp-4], 96 jle .L2 cmp BYTE PTR [rbp-4], 122 jg .L2 movzx eax, BYTE PTR [rbp-4] sub eax, 32 jmp .L3 .L2: movzx eax, BYTE PTR [rbp-4] .L3: pop rbp ret 48.1.2 One comparison operation Optimizing MSVC does its job better, it generates only one comparison operation: Listing 48.3: Optimizing MSVC 2013 (x64) toupper PROC lea eax, DWORD PTR [rcx-97] cmp al, 25 ja SHORT $LN2@toupper movsx eax, cl sub eax, 32 ret 0 $LN2@toupper: movzx eax, cl ret 0 toupper ENDP It was explained earlier, how to replace two comparison operations by one : 42.2.1 on page 498. I would rewrite this into C/C++: int tmp=c-97; if (tmp>25) return c; else return c-32; tmp variable should be signed. This makes two subtracting operations in case of transformation plus one comparison operation. While original algorithm uses two comparison operations plus one subtracting operation. Optimizing GCC is even better, it got rid of jumps (which is good: 33.1 on page 456) by using CMOVcc instruction: Listing 48.4: Optimizing GCC 4.9 (x64) 1 toupper: 2 lea edx, [rdi-97] ; 0x61 3 lea eax, [rdi-32] ; 0x20 4 cmp dl, 25 529
  • 554. CHAPTER 48. TOUPPER() FUNCTION 48.2. ARM 5 cmova eax, edi 6 ret At line 3 the code prepares the subtracted value in advance, as if conversion will happen always. At line 5 subtracted value in EAX is replaced by untouched input value if conversion is not needed. And then this value (of course incorrect) is dropped. Advance subtracting is a price compiler paying for the absence of conditional jumps. 48.2 ARM Optimizing Keil for ARM mode also generates only one comparison: Listing 48.5: Optimizing Keil 6/2013 (ARM mode) toupper PROC SUB r1,r0,#0x61 CMP r1,#0x19 SUBLS r0,r0,#0x20 ANDLS r0,r0,#0xff BX lr ENDP SUBLS and ANDLS instructions are executing only if R1 value is less than 0x19 (or equal). They do actual conversion. Optimizing Keil for thumb mode generates only one comparison operation as well: Listing 48.6: Optimizing Keil 6/2013 (thumb mode) toupper PROC MOVS r1,r0 SUBS r1,r1,#0x61 CMP r1,#0x19 BHI |L0.14| SUBS r0,r0,#0x20 LSLS r0,r0,#24 LSRS r0,r0,#24 |L0.14| BX lr ENDP Last two LSLS and LSRS instructions works like AND reg, 0xFF: they are analogous to C/C++-expression (i << 24) >> 24. Apparently, Keil for thumb mode deduced that two 2-byte instructions is shorter then the code loading 0xFF constant into register plus AND instruction. 48.2.1 GCC for ARM64 Listing 48.7: Non-optimizing GCC 4.9 (ARM64) toupper: sub sp, sp, #16 strb w0, [sp,15] ldrb w0, [sp,15] cmp w0, 96 bls .L2 ldrb w0, [sp,15] cmp w0, 122 bhi .L2 ldrb w0, [sp,15] sub w0, w0, #32 uxtb w0, w0 b .L3 .L2: ldrb w0, [sp,15] .L3: add sp, sp, 16 ret Listing 48.8: Optimizing GCC 4.9 (ARM64) toupper: uxtb w0, w0 530
  • 555. CHAPTER 48. TOUPPER() FUNCTION 48.3. SUMMARY sub w1, w0, #97 uxtb w1, w1 cmp w1, 25 bhi .L2 sub w0, w0, #32 uxtb w0, w0 .L2: ret 48.3 Summary All these compiler optimizations are very popular nowadays and practicing reverse engineer usually sees such code patterns often. 531
  • 556. CHAPTER 49. INCORRECTLY DISASSEMBLED CODE Chapter 49 Incorrectly disassembled code Practicing reverse engineers often have to deal with incorrectly disassembled code. 49.1 Disassembling from an incorrect start (x86) Unlike ARM and MIPS (where any instruction has a length of 2 or 4 bytes), x86 instructions have variable size, so any disassembler that starts in the middle of a x86 instruction may produce incorrect results. As an example: add [ebp-31F7Bh], cl dec dword ptr [ecx-3277Bh] dec dword ptr [ebp-2CF7Bh] inc dword ptr [ebx-7A76F33Ch] fdiv st(4), st db 0FFh dec dword ptr [ecx-21F7Bh] dec dword ptr [ecx-22373h] dec dword ptr [ecx-2276Bh] dec dword ptr [ecx-22B63h] dec dword ptr [ecx-22F4Bh] dec dword ptr [ecx-23343h] jmp dword ptr [esi-74h] xchg eax, ebp clc std db 0FFh db 0FFh mov word ptr [ebp-214h], cs ; <- disassembler finally found right track here mov word ptr [ebp-238h], ds mov word ptr [ebp-23Ch], es mov word ptr [ebp-240h], fs mov word ptr [ebp-244h], gs pushf pop dword ptr [ebp-210h] mov eax, [ebp+4] mov [ebp-218h], eax lea eax, [ebp+4] mov [ebp-20Ch], eax mov dword ptr [ebp-2D0h], 10001h mov eax, [eax-4] mov [ebp-21Ch], eax mov eax, [ebp+0Ch] mov [ebp-320h], eax mov eax, [ebp+10h] mov [ebp-31Ch], eax mov eax, [ebp+4] mov [ebp-314h], eax call ds:IsDebuggerPresent mov edi, eax lea eax, [ebp-328h] push eax call sub_407663 pop ecx test eax, eax 532
  • 557. CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED? jnz short loc_402D7B There are incorrectly disassembled instructions at the beginning, but eventually the disassembler gets on the right track. 49.2 How does random noise looks disassembled? Common properties that can be spotted easily are: • Unusually big instruction dispersion. The most frequent x86 instructions are PUSH, MOV, CALL, but here we see instructions from all instruction groups: FPU instructions, IN/OUT instructions, rare and system instructions, everything mixed up in one single place. • Big and random values, offsets and immediates. • Jumps having incorrect offsets, often jumping in the middle of another instructions. Listing 49.1: random noise (x86) mov bl, 0Ch mov ecx, 0D38558Dh mov eax, ds:2C869A86h db 67h mov dl, 0CCh insb movsb push eax xor [edx-53h], ah fcom qword ptr [edi-45A0EF72h] pop esp pop ss in eax, dx dec ebx push esp lds esp, [esi-41h] retf rcl dword ptr [eax], cl mov cl, 9Ch mov ch, 0DFh push cs insb mov esi, 0D9C65E4Dh imul ebp, [ecx], 66h pushf sal dword ptr [ebp-64h], cl sub eax, 0AC433D64h out 8Ch, eax pop ss sbb [eax], ebx aas xchg cl, [ebx+ebx*4+14B31Eh] jecxz short near ptr loc_58+1 xor al, 0C6h inc edx db 36h pusha stosb test [ebx], ebx sub al, 0D3h ; 'L' pop eax stosb loc_58: ; CODE XREF: seg000:0000004A test [esi], eax inc ebp das db 64h pop ecx das hlt 533
  • 558. CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED? pop edx out 0B0h, al lodsb push ebx cdq out dx, al sub al, 0Ah sti outsd add dword ptr [edx], 96FCBE4Bh and eax, 0E537EE4Fh inc esp stosd cdq push ecx in al, 0CBh mov ds:0D114C45Ch, al mov esi, 659D1985h Listing 49.2: random noise (x86-64) lea esi, [rax+rdx*4+43558D29h] loc_AF3: ; CODE XREF: seg000:0000000000000B46 rcl byte ptr [rsi+rax*8+29BB423Ah], 1 lea ecx, cs:0FFFFFFFFB2A6780Fh mov al, 96h mov ah, 0CEh push rsp lods byte ptr [esi] db 2Fh ; / pop rsp db 64h retf 0E993h cmp ah, [rax+4Ah] movzx rsi, dword ptr [rbp-25h] push 4Ah movzx rdi, dword ptr [rdi+rdx*8] db 9Ah rcr byte ptr [rax+1Dh], cl lodsd xor [rbp+6CF20173h], edx xor [rbp+66F8B593h], edx push rbx sbb ch, [rbx-0Fh] stosd int 87h db 46h, 4Ch out 33h, rax xchg eax, ebp test ecx, ebp movsd leave push rsp db 16h xchg eax, esi pop rdi loc_B3D: ; CODE XREF: seg000:0000000000000B5F mov ds:93CA685DF98A90F9h, eax jnz short near ptr loc_AF3+6 out dx, eax 534
  • 559. CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED? cwde mov bh, 5Dh ; ']' movsb pop rbp Listing 49.3: random noise (ARM (ARM mode)) BLNE 0xFE16A9D8 BGE 0x1634D0C SVCCS 0x450685 STRNVT R5, [PC],#-0x964 LDCGE p6, c14, [R0],#0x168 STCCSL p9, c9, [LR],#0x14C CMNHIP PC, R10,LSL#22 FLDMIADNV LR!, {D4} MCR p5, 2, R2,c15,c6, 4 BLGE 0x1139558 BLGT 0xFF9146E4 STRNEB R5, [R4],#0xCA2 STMNEIB R5, {R0,R4,R6,R7,R9-SP,PC} STMIA R8, {R0,R2-R4,R7,R8,R10,SP,LR}^ STRB SP, [R8],PC,ROR#18 LDCCS p9, c13, [R6,#0x1BC] LDRGE R8, [R9,#0x66E] STRNEB R5, [R8],#-0x8C3 STCCSL p15, c9, [R7,#-0x84] RSBLS LR, R2, R11,ASR LR SVCGT 0x9B0362 SVCGT 0xA73173 STMNEDB R11!, {R0,R1,R4-R6,R8,R10,R11,SP} STR R0, [R3],#-0xCE4 LDCGT p15, c8, [R1,#0x2CC] LDRCCB R1, [R11],-R7,ROR#30 BLLT 0xFED9D58C BL 0x13E60F4 LDMVSIB R3!, {R1,R4-R7}^ USATNE R10, #7, SP,LSL#11 LDRGEB LR, [R1],#0xE56 STRPLT R9, [LR],#0x567 LDRLT R11, [R1],#-0x29B SVCNV 0x12DB29 MVNNVS R5, SP,LSL#25 LDCL p8, c14, [R12,#-0x288] STCNEL p2, c6, [R6,#-0xBC]! SVCNV 0x2E5A2F BLX 0x1A8C97E TEQGE R3, #0x1100000 STMLSIA R6, {R3,R6,R10,R11,SP} BICPLS R12, R2, #0x5800 BNE 0x7CC408 TEQGE R2, R4,LSL#20 SUBS R1, R11, #0x28C BICVS R3, R12, R7,ASR R0 LDRMI R7, [LR],R3,LSL#21 BLMI 0x1A79234 STMVCDB R6, {R0-R3,R6,R7,R10,R11} EORMI R12, R6, #0xC5 MCRRCS p1, 0xF, R1,R3,c2 Listing 49.4: random noise (ARM (thumb mode)) LSRS R3, R6, #0x12 LDRH R1, [R7,#0x2C] SUBS R0, #0x55 ; 'U' ADR R1, loc_3C LDR R2, [SP,#0x218] CMP R4, #0x86 SXTB R7, R4 LDR R4, [R1,#0x4C] STR R4, [R4,R2] 535
  • 560. CHAPTER 49. INCORRECTLY DISASSEMBLED CODE 49.2. HOW DOES RANDOM NOISE LOOKS DISASSEMBLED? STR R0, [R6,#0x20] BGT 0xFFFFFF72 LDRH R7, [R2,#0x34] LDRSH R0, [R2,R4] LDRB R2, [R7,R2] DCB 0x17 DCB 0xED STRB R3, [R1,R1] STR R5, [R0,#0x6C] LDMIA R3, {R0-R5,R7} ASRS R3, R2, #3 LDR R4, [SP,#0x2C4] SVC 0xB5 LDR R6, [R1,#0x40] LDR R5, =0xB2C5CA32 STMIA R6, {R1-R4,R6} LDR R1, [R3,#0x3C] STR R1, [R5,#0x60] BCC 0xFFFFFF70 LDR R4, [SP,#0x1D4] STR R5, [R5,#0x40] ORRS R5, R7 loc_3C ; DATA XREF: ROM:00000006 B 0xFFFFFF98 Listing 49.5: random noise (MIPS little endian) lw $t9, 0xCB3($t5) sb $t5, 0x3855($t0) sltiu $a2, $a0, -0x657A ldr $t4, -0x4D99($a2) daddi $s0, $s1, 0x50A4 lw $s7, -0x2353($s4) bgtzl $a1, 0x17C5C .byte 0x17 .byte 0xED .byte 0x4B # K .byte 0x54 # T lwc2 $31, 0x66C5($sp) lwu $s1, 0x10D3($a1) ldr $t6, -0x204B($zero) lwc1 $f30, 0x4DBE($s2) daddiu $t1, $s1, 0x6BD9 lwu $s5, -0x2C64($v1) cop0 0x13D642D bne $gp, $t4, 0xFFFF9EF0 lh $ra, 0x1819($s1) sdl $fp, -0x6474($t8) jal 0x78C0050 ori $v0, $s2, 0xC634 blez $gp, 0xFFFEA9D4 swl $t8, -0x2CD4($s2) sltiu $a1, $k0, 0x685 sdc1 $f15, 0x5964($at) sw $s0, -0x19A6($a1) sltiu $t6, $a3, -0x66AD lb $t7, -0x4F6($t3) sd $fp, 0x4B02($a1) It is also important to keep in mind that cleverly constructed unpacking and decryption code (including self-modifying) may looks like noise as well, but still execute correctly. 536
  • 561. CHAPTER 50. OBFUSCATION Chapter 50 Obfuscation The obfuscation is an attempt to hide the code (or its meaning) from reverse engineers. 50.1 Text strings As I explained in ( 57 on page 646) , text strings may be really helpful. Programmers who are aware of this try to hide them, making it impossible to find the string in IDA or any hex editor. Here is the simplest method. This is how the string can be constructed: mov byte ptr [ebx], 'h' mov byte ptr [ebx+1], 'e' mov byte ptr [ebx+2], 'l' mov byte ptr [ebx+3], 'l' mov byte ptr [ebx+4], 'o' mov byte ptr [ebx+5], ' ' mov byte ptr [ebx+6], 'w' mov byte ptr [ebx+7], 'o' mov byte ptr [ebx+8], 'r' mov byte ptr [ebx+9], 'l' mov byte ptr [ebx+10], 'd' The string is also can be compared with another one like this: mov ebx, offset username cmp byte ptr [ebx], 'j' jnz fail cmp byte ptr [ebx+1], 'o' jnz fail cmp byte ptr [ebx+2], 'h' jnz fail cmp byte ptr [ebx+3], 'n' jnz fail jz it_is_john In both cases, it is impossible to find these strings straightforwardly in a hex editor. By the way, this is a way to work with the strings when it is impossible to allocate space for them in the data segment, for example in a PIC or in shellcode. Another method I once saw is to use sprintf() for the construction: sprintf(buf, "%s%c%s%c%s", "hel",'l',"o w",'o',"rld"); The code looks weird, but as a simple anti-reversing measure, it may be helpful. Text strings may also be present in encrypted form, then every string usage is to be preceded by a string decrypting routine. For example: 78.2 on page 750. 50.2 Executable code 50.2.1 Inserting garbage Executable code obfuscation implies inserting random garbage code between real one, which executes but does nothing useful. A simple example: 537
  • 562. CHAPTER 50. OBFUSCATION 50.2. EXECUTABLE CODE Listing 50.1: original code add eax, ebx mul ecx Listing 50.2: obfuscated code xor esi, 011223344h ; garbage add esi, eax ; garbage add eax, ebx mov edx, eax ; garbage shl edx, 4 ; garbage mul ecx xor esi, ecx ; garbage Here the garbage code uses registers which are not used in the real code (ESI and EDX). However, the intermediate results produced by the real code may be used by the garbage instructions for some extra mess—why not? 50.2.2 Replacing instructions with bloated equivalents • MOV op1, op2 can be replaced by the PUSH op2 / POP op1 pair. • JMP label can be replaced by the PUSH label / RET pair. IDA will not show the references to the label. • CALL label can be replaced by the PUSH label_after_CALL_instruction / PUSH label / RET triplet. • PUSH op can also be replaced with the SUB ESP, 4 (or 8) / MOV [ESP], op pair. 50.2.3 Always executed/never executed code If the developer is sure that ESI at always 0 at that point: mov esi, 1 ... ; some code not touching ESI dec esi ... ; some code not touching ESI cmp esi, 0 jz real_code ; fake luggage real_code: The reverse engineer needs some time to get into it. This is also called an opaque predicate. Another example ( and again, the developer is sure that ESI is always zero): add eax, ebx ; real code mul ecx ; real code add eax, esi ; opaque predicate. XOR, AND or SHL, etc, can be here instead of ADD. 50.2.4 Making a lot of mess instruction 1 instruction 2 instruction 3 Can be replaced with: begin: jmp ins1_label ins2_label: instruction 2 jmp ins3_label ins3_label: instruction 3 jmp exit: ins1_label: instruction 1 jmp ins2_label exit: 538
  • 563. CHAPTER 50. OBFUSCATION 50.3. VIRTUAL MACHINE / PSEUDO-CODE 50.2.5 Using indirect pointers dummy_data1 db 100h dup (0) message1 db 'hello world',0 dummy_data2 db 200h dup (0) message2 db 'another message',0 func proc ... mov eax, offset dummy_data1 ; PE or ELF reloc here add eax, 100h push eax call dump_string ... mov eax, offset dummy_data2 ; PE or ELF reloc here add eax, 200h push eax call dump_string ... func endp IDA will show references only to dummy_data1 and dummy_data2, but not to the text strings. Global variables and even functions may be accessed like that. 50.3 Virtual machine / pseudo-code A programmer can construct his/her own PL or ISA and interpreter for it. (Like the pre-5.0 Visual Basic, .NET or Java machines). The reverse engineer will have to spend some time to understand the meaning and details of all of the ISA’s instructions. Probably, he/she will also have to write a disassembler/decompiler of some sort. 50.4 Other things to mention My own (yet weak) attempt to patch the Tiny C compiler to produce obfuscated code: http://go.yurichev.com/17220. Using the MOV instruction for really complicated things: [Dol13]. 50.5 Exercises 50.5.1 Exercise #1 This is a very short program, compiled using the patched Tiny C compiler 1 . Try to find out what it does. beginners.re. Answer: G.1.13 on page 959. 1blog.yurichev.com 539
  • 564. CHAPTER 51. C++ Chapter 51 C++ 51.1 Classes 51.1.1 A simple example Internally, the representation of C++ classes is almost the same as the structures. Let’s try an example with two variables, two constructors and one method: #include <stdio.h> class c { private: int v1; int v2; public: c() // default ctor { v1=667; v2=999; }; c(int a, int b) // ctor { v1=a; v2=b; }; void dump() { printf ("%d; %dn", v1, v2); }; }; int main() { class c c1; class c c2(5,6); c1.dump(); c2.dump(); return 0; }; MSVC—x86 Here is how the main() function looks like, translated into assembly language: Listing 51.1: MSVC _c2$ = -16 ; size = 8 _c1$ = -8 ; size = 8 _main PROC 540
  • 565. CHAPTER 51. C++ 51.1. CLASSES push ebp mov ebp, esp sub esp, 16 lea ecx, DWORD PTR _c1$[ebp] call ??0c@@QAE@XZ ; c::c push 6 push 5 lea ecx, DWORD PTR _c2$[ebp] call ??0c@@QAE@HH@Z ; c::c lea ecx, DWORD PTR _c1$[ebp] call ?dump@c@@QAEXXZ ; c::dump lea ecx, DWORD PTR _c2$[ebp] call ?dump@c@@QAEXXZ ; c::dump xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP Here’s what’s going on. For each object (instance of class c) 8 bytes are allocated, exactly the size needed to store the 2 variables. For c1 a default argumentless constructor ??0c@@QAE@XZ is called. For c2 another constructor ??0c@@QAE@HH@Z is called and two numbers are passed as arguments. A pointer to the object (this in C++ terminology) is passed in the ECX register. This is called thiscall ( 51.1.1 on page 541) — the method for passing a pointer to the object. MSVC does it using the ECX register. Needless to say, it is not a standardized method, other compilers can do it differently, e.g., via the first function argument (like GCC). Why do these functions have such odd names? That’s name mangling. A C++ class may contain several methods sharing the same name but having different arguments —that is polymorphism. And of course, different classes may have their own methods with the same name. Name mangling enable us to encode the class name + method name + all method argument types in one ASCII string, which is then used as an internal function name. That’s all because neither the linker, nor the DLL OS loader (mangled names may be among the DLL exports as well) knows anything about C++ or OOP1 . The dump() function is called two times. Now let’s see the constructors’ code: Listing 51.2: MSVC _this$ = -4 ; size = 4 ??0c@@QAE@XZ PROC ; c::c, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov DWORD PTR [eax], 667 mov ecx, DWORD PTR _this$[ebp] mov DWORD PTR [ecx+4], 999 mov eax, DWORD PTR _this$[ebp] mov esp, ebp pop ebp ret 0 ??0c@@QAE@XZ ENDP ; c::c _this$ = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 ??0c@@QAE@HH@Z PROC ; c::c, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR _a$[ebp] mov DWORD PTR [eax], ecx mov edx, DWORD PTR _this$[ebp] 1Object-Oriented Programming 541
  • 566. CHAPTER 51. C++ 51.1. CLASSES mov eax, DWORD PTR _b$[ebp] mov DWORD PTR [edx+4], eax mov eax, DWORD PTR _this$[ebp] mov esp, ebp pop ebp ret 8 ??0c@@QAE@HH@Z ENDP ; c::c The constructors are just functions, they use a pointer to the structure in ECX, copying the pointer into their own local variable, however, it is not necessary. From the C++ standard [ISO13, p. 12.1] we know that constructors are not required to return any values. In fact, internally, the constructors return a pointer to the newly created object, i.e., this. Now the dump() method: Listing 51.3: MSVC _this$ = -4 ; size = 4 ?dump@c@@QAEXXZ PROC ; c::dump, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR [eax+4] push ecx mov edx, DWORD PTR _this$[ebp] mov eax, DWORD PTR [edx] push eax push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ call _printf add esp, 12 mov esp, ebp pop ebp ret 0 ?dump@c@@QAEXXZ ENDP ; c::dump Simple enough: dump() takes a pointer to the structure that contains the two int’s from ECX, takes both values from it and passes them to printf(). The code is much shorter if compiled with optimizations (/Ox): Listing 51.4: MSVC ??0c@@QAE@XZ PROC ; c::c, COMDAT ; _this$ = ecx mov eax, ecx mov DWORD PTR [eax], 667 mov DWORD PTR [eax+4], 999 ret 0 ??0c@@QAE@XZ ENDP ; c::c _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 ??0c@@QAE@HH@Z PROC ; c::c, COMDAT ; _this$ = ecx mov edx, DWORD PTR _b$[esp-4] mov eax, ecx mov ecx, DWORD PTR _a$[esp-4] mov DWORD PTR [eax], ecx mov DWORD PTR [eax+4], edx ret 8 ??0c@@QAE@HH@Z ENDP ; c::c ?dump@c@@QAEXXZ PROC ; c::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push eax push ecx push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ call _printf 542
  • 567. CHAPTER 51. C++ 51.1. CLASSES add esp, 12 ret 0 ?dump@c@@QAEXXZ ENDP ; c::dump That’s all. The other thing we need to note is that the stack pointer was not corrected with add esp, X after the constructor was called. At the same time, the constructor has ret 8 instead of RET at the end. This is all because the thiscall ( 51.1.1 on page 541) calling convention is used here, which together with the stdcall ( 64.2 on page 663) method offers the callee to correct the stack instead of the caller. The ret x instruction adds X to the value in ESP, then passes the control to the caller function. See also the section about calling conventions ( 64 on page 663). It also has to be noted that the compiler decides when to call the constructor and destructor —but we already know that from the C++ language basics. MSVC—x86-64 As we already know, the first 4 function arguments in x86-64 are passed in RCX, RDX, R8 and R9 registers, all the rest—via the stack. Nevertheless, the this pointer to the object is passed in RCX, the first argument of the method in RDX, etc. We can see this in the c(int a, int b) method internals: Listing 51.5: Optimizing MSVC 2012 x64 ; void dump() ?dump@c@@QEAAXXZ PROC ; c::dump mov r8d, DWORD PTR [rcx+4] mov edx, DWORD PTR [rcx] lea rcx, OFFSET FLAT:??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ ; '%d; %d' jmp printf ?dump@c@@QEAAXXZ ENDP ; c::dump ; c(int a, int b) ??0c@@QEAA@HH@Z PROC ; c::c mov DWORD PTR [rcx], edx ; 1st argument: a mov DWORD PTR [rcx+4], r8d ; 2nd argument: b mov rax, rcx ret 0 ??0c@@QEAA@HH@Z ENDP ; c::c ; default ctor ??0c@@QEAA@XZ PROC ; c::c mov DWORD PTR [rcx], 667 mov DWORD PTR [rcx+4], 999 mov rax, rcx ret 0 ??0c@@QEAA@XZ ENDP ; c::c The int data type is still 32-bit in x64 2 , so that is why 32-bit register parts are used here. We also see JMP printf instead of RET in the dump() method, that hack we already saw earlier: 13.1.1 on page 140. GCC—x86 It is almost the same story in GCC 4.4.1, with a few exceptions. Listing 51.6: GCC 4.4.1 public main main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_18 = dword ptr -18h var_10 = dword ptr -10h var_8 = dword ptr -8 push ebp mov ebp, esp 2Apparently, for easier porting of 32-bit C/C++ code to x64 543
  • 568. CHAPTER 51. C++ 51.1. CLASSES and esp, 0FFFFFFF0h sub esp, 20h lea eax, [esp+20h+var_8] mov [esp+20h+var_20], eax call _ZN1cC1Ev mov [esp+20h+var_18], 6 mov [esp+20h+var_1C], 5 lea eax, [esp+20h+var_10] mov [esp+20h+var_20], eax call _ZN1cC1Eii lea eax, [esp+20h+var_8] mov [esp+20h+var_20], eax call _ZN1c4dumpEv lea eax, [esp+20h+var_10] mov [esp+20h+var_20], eax call _ZN1c4dumpEv mov eax, 0 leave retn main endp Here we see another name mangling style, specific to GNU 3 It can also be noted that the pointer to the object is passed as the first function argument —invisible to programmer, of course. First constructor: public _ZN1cC1Ev ; weak _ZN1cC1Ev proc near ; CODE XREF: main+10 arg_0 = dword ptr 8 push ebp mov ebp, esp mov eax, [ebp+arg_0] mov dword ptr [eax], 667 mov eax, [ebp+arg_0] mov dword ptr [eax+4], 999 pop ebp retn _ZN1cC1Ev endp It just writes two numbers using the pointer passed in the first (and only) argument. Second constructor: public _ZN1cC1Eii _ZN1cC1Eii proc near arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h push ebp mov ebp, esp mov eax, [ebp+arg_0] mov edx, [ebp+arg_4] mov [eax], edx mov eax, [ebp+arg_0] mov edx, [ebp+arg_8] mov [eax+4], edx pop ebp retn _ZN1cC1Eii endp This is a function, the analog of which can look like this: void ZN1cC1Eii (int *obj, int a, int b) { *obj=a; *(obj+1)=b; }; 3There is a good document about the various name mangling conventions in different compilers: [Fog14]. 544
  • 569. CHAPTER 51. C++ 51.1. CLASSES …and that is completely predictable. Now the dump() function: public _ZN1c4dumpEv _ZN1c4dumpEv proc near var_18 = dword ptr -18h var_14 = dword ptr -14h var_10 = dword ptr -10h arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 18h mov eax, [ebp+arg_0] mov edx, [eax+4] mov eax, [ebp+arg_0] mov eax, [eax] mov [esp+18h+var_10], edx mov [esp+18h+var_14], eax mov [esp+18h+var_18], offset aDD ; "%d; %dn" call _printf leave retn _ZN1c4dumpEv endp This function in its internal representation has only one argument, used as pointer to the object (this). This function could be rewritten in C like this: void ZN1c4dumpEv (int *obj) { printf ("%d; %dn", *obj, *(obj+1)); }; Thus, if we base our judgment on these simple examples, the difference between MSVC and GCC is the style of the encoding of function names (name mangling) and the method for passing a pointer to the object (via the ECX register or via the first argument). GCC—x86-64 The first 6 arguments, as we already know, are passed in the RDI, RSI, RDX, RCX, R8 and R9 [Mit13] registers, and the pointer to this via the first one (RDI) and that is what we see here. The int data type is also 32-bit here. The JMP instead of RET hack is also used here. Listing 51.7: GCC 4.4.6 x64 ; default ctor _ZN1cC2Ev: mov DWORD PTR [rdi], 667 mov DWORD PTR [rdi+4], 999 ret ; c(int a, int b) _ZN1cC2Eii: mov DWORD PTR [rdi], esi mov DWORD PTR [rdi+4], edx ret ; dump() _ZN1c4dumpEv: mov edx, DWORD PTR [rdi+4] mov esi, DWORD PTR [rdi] xor eax, eax mov edi, OFFSET FLAT:.LC0 ; "%d; %dn" jmp printf 545
  • 570. CHAPTER 51. C++ 51.1. CLASSES 51.1.2 Class inheritance Inherited classes are similar to the simple structures we already discussed, but extended in inheritable classes. Let’s take this simple example: #include <stdio.h> class object { public: int color; object() { }; object (int color) { this->color=color; }; void print_color() { printf ("color=%dn", color); }; }; class box : public object { private: int width, height, depth; public: box(int color, int width, int height, int depth) { this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦ height, depth); }; }; class sphere : public object { private: int radius; public: sphere(int color, int radius) { this->color=color; this->radius=radius; }; void dump() { printf ("this is sphere. color=%d, radius=%dn", color, radius); }; }; int main() { box b(1, 10, 20, 30); sphere s(2, 40); b.print_color(); s.print_color(); b.dump(); s.dump(); return 0; }; Let’s investigate the generated code of the dump() functions/methods and also object::print_color(), and see the memory layout for the structures-objects (for 32-bit code). So, here are the dump() methods for several classes, generated by MSVC 2008 with /Ox and /Ob0 options 4 4The /Ob0 option stands for disabling inline expansion since function inlining can make our experiment harder 546
  • 571. CHAPTER 51. C++ 51.1. CLASSES Listing 51.8: Optimizing MSVC 2008 /Ob0 ??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@ DB 'color=%d', 0aH, 00H ; `string' ?print_color@object@@QAEXXZ PROC ; object::print_color, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx] push eax ; 'color=%d', 0aH, 00H push OFFSET ??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@ call _printf add esp, 8 ret 0 ?print_color@object@@QAEXXZ ENDP ; object::print_color Listing 51.9: Optimizing MSVC 2008 /Ob0 ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H ; `string' push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@ call _printf add esp, 20 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump Listing 51.10: Optimizing MSVC 2008 /Ob0 ?dump@sphere@@QAEXXZ PROC ; sphere::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push eax push ecx ; 'this is sphere. color=%d, radius=%d', 0aH, 00H push OFFSET ??_C@_0CF@EFEDJLDC@this?5is?5sphere?4?5color?$DN?$CFd?0?5radius@ call _printf add esp, 12 ret 0 ?dump@sphere@@QAEXXZ ENDP ; sphere::dump So, here is the memory layout: (base class object) offset description +0x0 int color (inherited classes) box: offset description +0x0 int color +0x4 int width +0x8 int height +0xC int depth sphere: offset description +0x0 int color +0x4 int radius 547
  • 572. CHAPTER 51. C++ 51.1. CLASSES Let’s see main() function body: Listing 51.11: Optimizing MSVC 2008 /Ob0 PUBLIC _main _TEXT SEGMENT _s$ = -24 ; size = 8 _b$ = -16 ; size = 16 _main PROC sub esp, 24 push 30 push 20 push 10 push 1 lea ecx, DWORD PTR _b$[esp+40] call ??0box@@QAE@HHHH@Z ; box::box push 40 push 2 lea ecx, DWORD PTR _s$[esp+32] call ??0sphere@@QAE@HH@Z ; sphere::sphere lea ecx, DWORD PTR _b$[esp+24] call ?print_color@object@@QAEXXZ ; object::print_color lea ecx, DWORD PTR _s$[esp+24] call ?print_color@object@@QAEXXZ ; object::print_color lea ecx, DWORD PTR _b$[esp+24] call ?dump@box@@QAEXXZ ; box::dump lea ecx, DWORD PTR _s$[esp+24] call ?dump@sphere@@QAEXXZ ; sphere::dump xor eax, eax add esp, 24 ret 0 _main ENDP The inherited classes must always add their fields after the base classes’ fields, to make it possible for the base class methods to work with their own fields. When the object::print_color() method is called, a pointers to both the box and sphere objects are passed as this, and it can work with these objects easily since the color field in these objects is always at the pinned address (at offset +0x0). It can be said that the object::print_color() method is agnostic in relation to the input object type as long as the fields are pinned at the same addresses, and this condition is always true. And if you create inherited class of the box class, the compiler will add the new fields after the depth field, leaving the box class fields at the pinned addresses. Thus, the box::dump() method will work fine for accessing the color/width/height/depths fields, which are always pinned at known addresses. The code generated by GCC is almost the same, with the sole exception of passing the this pointer (as it was explained above, it is passed as the first argument instead of using the ECX register. 51.1.3 Encapsulation Encapsulation is hiding the data in the private sections of the class, e.g. to allow access to them only from this class methods. However, are there any marks in code the about the fact that some field is private and some other —not? No, there are no such marks. Let’s try this simple example: #include <stdio.h> class box { private: int color, width, height, depth; public: box(int color, int width, int height, int depth) { this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() 548
  • 573. CHAPTER 51. C++ 51.1. CLASSES { printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦ height, depth); }; }; Let’s compile it again in MSVC 2008 with /Ox and /Ob0 options and see the box::dump() method code: ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@ call _printf add esp, 20 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump Here is a memory layout of the class: offset description +0x0 int color +0x4 int width +0x8 int height +0xC int depth All fields are private and not allowed to be accessed from any other function, but knowing this layout, can we create code that modifies these fields? To do this I’ve added the hack_oop_encapsulation() function, which is not going to compile if it looked like this: void hack_oop_encapsulation(class box * o) { o->width=1; // that code cant be compiled': // "error C2248: 'box::width' : cannot access private member declared in class ⤦ 'box'" }; Nevertheless, if we cast the box type to a pointer to an int array, and we modify the array of int-s that we have, we can succeed. void hack_oop_encapsulation(class box * o) { unsigned int *ptr_to_object=reinterpret_cast<unsigned int*>(o); ptr_to_object[1]=123; }; This function’s code is very simple —it can be said that the function takes a pointer to an array of int-s for input and writes 123 to the second int: ?hack_oop_encapsulation@@YAXPAVbox@@@Z PROC ; hack_oop_encapsulation mov eax, DWORD PTR _o$[esp-4] mov DWORD PTR [eax+4], 123 ret 0 ?hack_oop_encapsulation@@YAXPAVbox@@@Z ENDP ; hack_oop_encapsulation Let’s check how it works: int main() { box b(1, 10, 20, 30); b.dump(); hack_oop_encapsulation(&b); 549
  • 574. CHAPTER 51. C++ 51.1. CLASSES b.dump(); return 0; }; Let’s run: this is box. color=1, width=10, height=20, depth=30 this is box. color=1, width=123, height=20, depth=30 We see that the encapsulation is just protection of class fields only in the compilation stage. The C++ compiler is not allowing the generation of code that modifies protected fields straightforwardly, nevertheless, it is possible with the help of dirty hacks. 51.1.4 Multiple inheritance Multiple inheritance is creating a class which inherits fields and methods from two or more classes. Let’s write a simple example again: #include <stdio.h> class box { public: int width, height, depth; box() { }; box(int width, int height, int depth) { this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. width=%d, height=%d, depth=%dn", width, height, depth); }; int get_volume() { return width * height * depth; }; }; class solid_object { public: int density; solid_object() { }; solid_object(int density) { this->density=density; }; int get_density() { return density; }; void dump() { printf ("this is solid_object. density=%dn", density); }; }; class solid_box: box, solid_object { public: solid_box (int width, int height, int depth, int density) { this->width=width; this->height=height; this->depth=depth; this->density=density; 550
  • 575. CHAPTER 51. C++ 51.1. CLASSES }; void dump() { printf ("this is solid_box. width=%d, height=%d, depth=%d, density=%dn", width, ⤦ height, depth, density); }; int get_weight() { return get_volume() * get_density(); }; }; int main() { box b(10, 20, 30); solid_object so(100); solid_box sb(10, 20, 30, 3); b.dump(); so.dump(); sb.dump(); printf ("%dn", sb.get_weight()); return 0; }; Let’s compile it in MSVC 2008 with the /Ox and /Ob0 options and see the code of box::dump(), solid_object::dump() and solid_box::dump(): Listing 51.12: Optimizing MSVC 2008 /Ob0 ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+8] mov edx, DWORD PTR [ecx+4] push eax mov eax, DWORD PTR [ecx] push edx push eax ; 'this is box. width=%d, height=%d, depth=%d', 0aH, 00H push OFFSET ??_C@_0CM@DIKPHDFI@this?5is?5box?4?5width?$DN?$CFd?0?5height?$DN?$CFd@ call _printf add esp, 16 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump Listing 51.13: Optimizing MSVC 2008 /Ob0 ?dump@solid_object@@QAEXXZ PROC ; solid_object::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx] push eax ; 'this is solid_object. density=%d', 0aH push OFFSET ??_C@_0CC@KICFJINL@this?5is?5solid_object?4?5density?$DN?$CFd@ call _printf add esp, 8 ret 0 ?dump@solid_object@@QAEXXZ ENDP ; solid_object::dump Listing 51.14: Optimizing MSVC 2008 /Ob0 ?dump@solid_box@@QAEXXZ PROC ; solid_box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is solid_box. width=%d, height=%d, depth=%d, density=%d', 0aH push OFFSET ??_C@_0DO@HNCNIHNN@this?5is?5solid_box?4?5width?$DN?$CFd?0?5hei@ call _printf 551
  • 576. CHAPTER 51. C++ 51.1. CLASSES add esp, 20 ret 0 ?dump@solid_box@@QAEXXZ ENDP ; solid_box::dump So, the memory layout for all three classes is: box class: offset description +0x0 width +0x4 height +0x8 depth solid_object class: offset description +0x0 density It can be said that the solid_box class memory layout is united: solid_box class: offset description +0x0 width +0x4 height +0x8 depth +0xC density The code of the box::get_volume() and solid_object::get_density() methods is trivial: Listing 51.15: Optimizing MSVC 2008 /Ob0 ?get_volume@box@@QAEHXZ PROC ; box::get_volume, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+8] imul eax, DWORD PTR [ecx+4] imul eax, DWORD PTR [ecx] ret 0 ?get_volume@box@@QAEHXZ ENDP ; box::get_volume Listing 51.16: Optimizing MSVC 2008 /Ob0 ?get_density@solid_object@@QAEHXZ PROC ; solid_object::get_density, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx] ret 0 ?get_density@solid_object@@QAEHXZ ENDP ; solid_object::get_density But the code of the solid_box::get_weight() method is much more interesting: Listing 51.17: Optimizing MSVC 2008 /Ob0 ?get_weight@solid_box@@QAEHXZ PROC ; solid_box::get_weight, COMDAT ; _this$ = ecx push esi mov esi, ecx push edi lea ecx, DWORD PTR [esi+12] call ?get_density@solid_object@@QAEHXZ ; solid_object::get_density mov ecx, esi mov edi, eax call ?get_volume@box@@QAEHXZ ; box::get_volume imul eax, edi pop edi pop esi ret 0 ?get_weight@solid_box@@QAEHXZ ENDP ; solid_box::get_weight get_weight() just calls two methods, but for get_volume() it just passes pointer to this, and for get_density() it passes a pointer to this incremented by 12 (or 0xC) bytes, and there, in the solid_box class memory layout, the fields of the solid_object class start. Thus, the solid_object::get_density() method will believe like it is dealing with the usual solid_object class, and the box::get_volume() method will work with its three fields, believing this is just the usual object of class box. Thus, we can say, an object of a class, that inherits from several other classes, is representing in memory as a united class, that contains all inherited fields. And each inherited method is called with a pointer to the corresponding structure’s part. 552
  • 577. CHAPTER 51. C++ 51.1. CLASSES 51.1.5 Virtual methods Yet another simple example: #include <stdio.h> class object { public: int color; object() { }; object (int color) { this->color=color; }; virtual void dump() { printf ("color=%dn", color); }; }; class box : public object { private: int width, height, depth; public: box(int color, int width, int height, int depth) { this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. color=%d, width=%d, height=%d, depth=%dn", color, width, ⤦ height, depth); }; }; class sphere : public object { private: int radius; public: sphere(int color, int radius) { this->color=color; this->radius=radius; }; void dump() { printf ("this is sphere. color=%d, radius=%dn", color, radius); }; }; int main() { box b(1, 10, 20, 30); sphere s(2, 40); object *o1=&b; object *o2=&s; o1->dump(); o2->dump(); return 0; }; Class object has a virtual method dump() that is being replaced in the inheriting box and sphere classes. If we are in an environment where it is not known the type of an object, as in the main() function in example, where the virtual method dump() is called, the information about its type must be stored somewhere, to be able to call the relevant virtual method. 553
  • 578. CHAPTER 51. C++ 51.1. CLASSES Let’s compile it in MSVC 2008 with the /Ox and /Ob0 options and see the code of main(): _s$ = -32 ; size = 12 _b$ = -20 ; size = 20 _main PROC sub esp, 32 push 30 push 20 push 10 push 1 lea ecx, DWORD PTR _b$[esp+48] call ??0box@@QAE@HHHH@Z ; box::box push 40 push 2 lea ecx, DWORD PTR _s$[esp+40] call ??0sphere@@QAE@HH@Z ; sphere::sphere mov eax, DWORD PTR _b$[esp+32] mov edx, DWORD PTR [eax] lea ecx, DWORD PTR _b$[esp+32] call edx mov eax, DWORD PTR _s$[esp+32] mov edx, DWORD PTR [eax] lea ecx, DWORD PTR _s$[esp+32] call edx xor eax, eax add esp, 32 ret 0 _main ENDP A pointer to the dump() function is taken somewhere from the object. Where could we store the address of the new method? Only somewhere in the constructors: there is no other place since nothing else is called in the main() function. 5 Let’s see the code of the constructor of the box class: ??_R0?AVbox@@@8 DD FLAT:??_7type_info@@6B@ ; box `RTTI Type Descriptor' DD 00H DB '.?AVbox@@', 00H ??_R1A@?0A@EA@box@@8 DD FLAT:??_R0?AVbox@@@8 ; box::`RTTI Base Class Descriptor at (0,-1,0,64)' DD 01H DD 00H DD 0ffffffffH DD 00H DD 040H DD FLAT:??_R3box@@8 ??_R2box@@8 DD FLAT:??_R1A@?0A@EA@box@@8 ; box::`RTTI Base Class Array' DD FLAT:??_R1A@?0A@EA@object@@8 ??_R3box@@8 DD 00H ; box::`RTTI Class Hierarchy Descriptor' DD 00H DD 02H DD FLAT:??_R2box@@8 ??_R4box@@6B@ DD 00H ; box::`RTTI Complete Object Locator' DD 00H DD 00H DD FLAT:??_R0?AVbox@@@8 DD FLAT:??_R3box@@8 ??_7box@@6B@ DD FLAT:??_R4box@@6B@ ; box::`vftable' DD FLAT:?dump@box@@UAEXXZ _color$ = 8 ; size = 4 _width$ = 12 ; size = 4 _height$ = 16 ; size = 4 _depth$ = 20 ; size = 4 ??0box@@QAE@HHHH@Z PROC ; box::box, COMDAT ; _this$ = ecx push esi 5You can read more about pointers to functions in the relevant section:( 23 on page 391) 554
  • 579. CHAPTER 51. C++ 51.2. OSTREAM mov esi, ecx call ??0object@@QAE@XZ ; object::object mov eax, DWORD PTR _color$[esp] mov ecx, DWORD PTR _width$[esp] mov edx, DWORD PTR _height$[esp] mov DWORD PTR [esi+4], eax mov eax, DWORD PTR _depth$[esp] mov DWORD PTR [esi+16], eax mov DWORD PTR [esi], OFFSET ??_7box@@6B@ mov DWORD PTR [esi+8], ecx mov DWORD PTR [esi+12], edx mov eax, esi pop esi ret 16 ??0box@@QAE@HHHH@Z ENDP ; box::box Here we see a slightly different memory layout: the first field is a pointer to some table box::`vftable' (the name was set by the MSVC compiler). In this table we see a link to a table named box::`RTTI Complete Object Locator' and also a link to the box::dump() method. These are called virtual methods table and RTTI6 . The table of virtual methods contains the addresses of methods and the RTTI table contains information about types. By the way, the RTTI tables are used while calling dynamic_cast and typeid in C++. You can also see here the class name as a plain text string. Thus, a method of the base object class may call the virtual method object::dump(), which in turn will call a method of an inherited class, since that information is present right in the object’s structure. Some additional CPU time is needed for doing look-ups in these tables and finding the right virtual method address, thus virtual methods are widely considered as slightly slower than common methods. In GCC-generated code the RTTI tables are constructed slightly differently. 51.2 ostream Let’s start again with a “hello world” example, but now we are going to use ostream: #include <iostream> int main() { std::cout << "Hello, world!n"; } Almost any C++ textbook tells us that the << operation can be replaced (overloaded) for other types. That is what is done in ostream. We see that operator<< is called for ostream: Listing 51.18: MSVC 2012 (reduced listing) $SG37112 DB 'Hello, world!', 0aH, 00H _main PROC push OFFSET $SG37112 push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦ $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 xor eax, eax ret 0 _main ENDP Let’s modify the example: #include <iostream> int main() { std::cout << "Hello, " << "world!n"; } And again, from many C++ textbooks we know that the result of each operator<< in ostream is forwarded to the next one. Indeed: 6Run-time type information 555
  • 580. CHAPTER 51. C++ 51.3. REFERENCES Listing 51.19: MSVC 2012 $SG37112 DB 'world!', 0aH, 00H $SG37113 DB 'Hello, ', 00H _main PROC push OFFSET $SG37113 ; 'Hello, ' push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦ $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 push OFFSET $SG37112 ; 'world!' push eax ; result of previous function execution call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?⤦ $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 xor eax, eax ret 0 _main ENDP If we replace operator<< by f(), that code can be rewritten as: f(f(std::cout, "Hello, "), "world!") GCC generates almost the same code as MSVC. 51.3 References In C++, references are pointers ( 10 on page 98) as well, but they are called safe, because it is harder to make a mistake while dealing with them [ISO13, p. 8.3.2]. For example, reference must always be pointing to an object of the corresponding type and cannot be NULL [Cli, p. 8.6]. Even more than that, references cannot be changed, it is impossible to point them to another object (reseat) [Cli, p. 8.5]. If we are going to try to change the example with pointers ( 10 on page 98) to use references instead … void f2 (int x, int y, int & sum, int & product) { sum=x+y; product=x*y; }; …then we can see that the compiled code is just the same as in the pointers example ( 10 on page 98): Listing 51.20: Optimizing MSVC 2010 _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 _sum$ = 16 ; size = 4 _product$ = 20 ; size = 4 ?f2@@YAXHHAAH0@Z PROC ; f2 mov ecx, DWORD PTR _y$[esp-4] mov eax, DWORD PTR _x$[esp-4] lea edx, DWORD PTR [eax+ecx] imul eax, ecx mov ecx, DWORD PTR _product$[esp-4] push esi mov esi, DWORD PTR _sum$[esp] mov DWORD PTR [esi], edx mov DWORD PTR [ecx], eax pop esi ret 0 ?f2@@YAXHHAAH0@Z ENDP ; f2 ( The reason why C++ functions has such strange names is explained here: 51.1.1 on page 541.) 51.4 STL N.B.: all examples here were checked only in 32-bit environment. x64 wasn’t checked. 556
  • 581. CHAPTER 51. C++ 51.4. STL 51.4.1 std::string Internals Many string libraries [Yur13, p. 2.2] implement a structure that contains a pointer to a string buffer, a variable that always contains the current string length (which is very convenient for many functions: [Yur13, p. 2.2.1]) and a variable containing the current buffer size. The string in the buffer is usually terminated with zero, in order to be able to pass a pointer to the buffer into the functions that take usual C ASCIIZ strings. It is not specified in the C++ standard [ISO13] how std::string has to be implemented, however, it is usually implemented as explained above. The C++ string is not a class (as QString in Qt, for instance) but a template (basic_string), this is done in order to support various character types: at least char and wchar_t. So, std::string is a class with char as its base type. And std::wstring is a class with wchar_t as its base type. MSVC The MSVC implementation may store the buffer in place instead of using a pointer to a buffer (if the string is shorter than 16 symbols). This implies that a short string is to occupy at least 16+4+4 = 24 bytes in 32-bit environment or at least 16+8+8 = 32 bytes in 64-bit one, and if the string is longer than 16 characters, we also have to add the length of the string itself. Listing 51.21: example for MSVC #include <string> #include <stdio.h> struct std_string { union { char buf[16]; char* ptr; } u; size_t size; // AKA 'Mysize' in MSVC size_t capacity; // AKA 'Myres' in MSVC }; void dump_std_string(std::string s) { struct std_string *p=(struct std_string*)&s; printf ("[%s] size:%d capacity:%dn", p->size>16 ? p->u.ptr : p->u.buf, p->size, p->⤦ capacity); }; int main() { std::string s1="short string"; std::string s2="string longer that 16 bytes"; dump_std_string(s1); dump_std_string(s2); // that works without using c_str() printf ("%sn", &s1); printf ("%sn", s2); }; Almost everything is clear from the source code. A couple of notes: If the string is shorter than 16 symbols, a buffer for the string is not to be allocated in the heap. This is convenient because in practice, a lot of strings are short indeed. Looks like that Microsoft’s developers chose 16 characters as a good balance. One very important thing here can be seen at the end of main(): I’m not using the c_str() method, nevertheless, if we compile and run this code, both strings will appear in the console! This is why it works. In the first case the string is shorter than 16 characters and the buffer with the string is located in the beginning of the std::string object (it can be treated as a structure). printf() treats the pointer as a pointer to the null-terminated array of characters, hence it works. 557
  • 582. CHAPTER 51. C++ 51.4. STL Printing the second string (longer than 16 characters) is even more dangerous: it is a typical programmer’s mistake (or typo) to forget to write c_str(). This works because at the moment a pointer to buffer is located at the start of structure. This may stay unnoticed for a long time, until a longer string appears there at some time, then the process will crash. GCC GCC’s implementation of this structure has one more variable—reference count. One interesting fact is that in GCC a pointer an instance of std::string instance points not to the beginning of the structure, but to the buffer pointer. In libstdc++-v3includebitsbasic_string.h we can read that it was done for more convenient debugging: * The reason you want _M_data pointing to the character %array and * not the _Rep is so that the debugger can see the string * contents. (Probably we should add a non-inline member to get * the _Rep for the debugger to use, so users can check the actual * string length.) basic_string.h source code I consider this in my example: Listing 51.22: example for GCC #include <string> #include <stdio.h> struct std_string { size_t length; size_t capacity; size_t refcount; }; void dump_std_string(std::string s) { char *p1=*(char**)&s; // GCC type checking workaround struct std_string *p2=(struct std_string*)(p1-sizeof(struct std_string)); printf ("[%s] size:%d capacity:%dn", p1, p2->length, p2->capacity); }; int main() { std::string s1="short string"; std::string s2="string longer that 16 bytes"; dump_std_string(s1); dump_std_string(s2); // GCC type checking workaround: printf ("%sn", *(char**)&s1); printf ("%sn", *(char**)&s2); }; A trickery has to be used to imitate the mistake I already wrote above because GCC has stronger type checking, never- theless, printf() works here without c_str() as well. A more complex example #include <string> #include <stdio.h> int main() { std::string s1="Hello, "; std::string s2="world!n"; std::string s3=s1+s2; printf ("%sn", s3.c_str()); } 558
  • 583. CHAPTER 51. C++ 51.4. STL Listing 51.23: MSVC 2012 $SG39512 DB 'Hello, ', 00H $SG39514 DB 'world!', 0aH, 00H $SG39581 DB '%s', 0aH, 00H _s2$ = -72 ; size = 24 _s3$ = -48 ; size = 24 _s1$ = -24 ; size = 24 _main PROC sub esp, 72 push 7 push OFFSET $SG39512 lea ecx, DWORD PTR _s1$[esp+80] mov DWORD PTR _s1$[esp+100], 15 mov DWORD PTR _s1$[esp+96], 0 mov BYTE PTR _s1$[esp+80], 0 call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦ std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign push 7 push OFFSET $SG39514 lea ecx, DWORD PTR _s2$[esp+80] mov DWORD PTR _s2$[esp+100], 15 mov DWORD PTR _s2$[esp+96], 0 mov BYTE PTR _s2$[esp+80], 0 call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦ std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign lea eax, DWORD PTR _s2$[esp+72] push eax lea eax, DWORD PTR _s1$[esp+76] push eax lea eax, DWORD PTR _s3$[esp+80] push eax call ??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?⤦ $char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z ; std::operator+<char,std::char_traits<⤦ char>,std::allocator<char> > ; inlined c_str() method: cmp DWORD PTR _s3$[esp+104], 16 lea eax, DWORD PTR _s3$[esp+84] cmovae eax, DWORD PTR _s3$[esp+84] push eax push OFFSET $SG39581 call _printf add esp, 20 cmp DWORD PTR _s3$[esp+92], 16 jb SHORT $LN119@main push DWORD PTR _s3$[esp+72] call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN119@main: cmp DWORD PTR _s2$[esp+92], 16 mov DWORD PTR _s3$[esp+92], 15 mov DWORD PTR _s3$[esp+88], 0 mov BYTE PTR _s3$[esp+72], 0 jb SHORT $LN151@main push DWORD PTR _s2$[esp+72] call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN151@main: cmp DWORD PTR _s1$[esp+92], 16 mov DWORD PTR _s2$[esp+92], 15 mov DWORD PTR _s2$[esp+88], 0 mov BYTE PTR _s2$[esp+72], 0 jb SHORT $LN195@main push DWORD PTR _s1$[esp+72] 559
  • 584. CHAPTER 51. C++ 51.4. STL call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN195@main: xor eax, eax add esp, 72 ret 0 _main ENDP The compiler does not construct strings statically: it would not be possible anyway if the buffer needs to be located in the heap. Instead, the ASCIIZ strings are stored in the data segment, and later, at runtime, with the help of the “assign” method, the s1 and s2 strings are constructed. And with the help of operator+, the s3 string is constructed. Please note that there is no call to the c_str() method, because its code is tiny enough so the compiler inlined it right there: if the string is shorter than 16 characters, a pointer to buffer is left in EAX, otherwise the address of the string buffer located in the heap is fetched. Next, we see calls to the 3 destructors, they are called if the string is longer than 16 characters: then the buffers in the heap have to be freed. Otherwise, since all three std::string objects are stored in the stack, they are freed automatically, when the function ends. As a consequence, processing short strings is faster, because of less heap accesses. GCC code is even simpler (because the GCC way, as I mentioned above, is to not store shorter strings right in the structure): Listing 51.24: GCC 4.8.1 .LC0: .string "Hello, " .LC1: .string "world!n" main: push ebp mov ebp, esp push edi push esi push ebx and esp, -16 sub esp, 32 lea ebx, [esp+28] lea edi, [esp+20] mov DWORD PTR [esp+8], ebx lea esi, [esp+24] mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 mov DWORD PTR [esp], edi call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+8], ebx mov DWORD PTR [esp+4], OFFSET FLAT:.LC1 mov DWORD PTR [esp], esi call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+4], edi mov DWORD PTR [esp], ebx call _ZNSsC1ERKSs mov DWORD PTR [esp+4], esi mov DWORD PTR [esp], ebx call _ZNSs6appendERKSs ; inlined c_str(): mov eax, DWORD PTR [esp+28] mov DWORD PTR [esp], eax call puts mov eax, DWORD PTR [esp+28] lea ebx, [esp+19] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax 560
  • 585. CHAPTER 51. C++ 51.4. STL call _ZNSs4_Rep10_M_disposeERKSaIcE mov eax, DWORD PTR [esp+24] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax call _ZNSs4_Rep10_M_disposeERKSaIcE mov eax, DWORD PTR [esp+20] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax call _ZNSs4_Rep10_M_disposeERKSaIcE lea esp, [ebp-12] xor eax, eax pop ebx pop esi pop edi pop ebp ret It can be seen that it’s not a pointer to the object that is passed to destructors, but rather an address 12 bytes (or 3 words) before, i.e., a pointer to the real start of the structure. std::string as a global variable Experienced C++ programmers may not agree, but a global variables with an STL7 type can be defined. Yes, indeed: #include <stdio.h> #include <string> std::string s="a string"; int main() { printf ("%sn", s.c_str()); }; In fact, this variable is to be initialized even before main() start. Listing 51.25: MSVC 2012: here is how a global variable is constructed and also its destructor is registered ??__Es@@YAXXZ PROC push 8 push OFFSET $SG39512 ; 'a string' mov ecx, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦ std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign push OFFSET ??__Fs@@YAXXZ ; `dynamic atexit destructor for 's'' call _atexit pop ecx ret 0 ??__Es@@YAXXZ ENDP Listing 51.26: MSVC 2012: here a global variable is used in main() $SG39512 DB 'a string', 00H $SG39519 DB '%s', 0aH, 00H _main PROC cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16 mov eax, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s cmovae eax, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A push eax push OFFSET $SG39519 ; '%s' call _printf add esp, 8 xor eax, eax ret 0 _main ENDP 7(C++) Standard Template Library: 51.4 on page 556 561
  • 586. CHAPTER 51. C++ 51.4. STL Listing 51.27: MSVC 2012: this destructor function is called before exit ??__Fs@@YAXXZ PROC push ecx cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16 jb SHORT $LN23@dynamic push esi mov esi, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A lea ecx, DWORD PTR $T2[esp+8] call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ push OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s lea ecx, DWORD PTR $T2[esp+12] call ??$destroy@PAD@?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAEXPAPAD@Z lea ecx, DWORD PTR $T1[esp+8] call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ push esi call ??3@YAXPAX@Z ; operator delete add esp, 4 pop esi $LN23@dynamic: mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 15 mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+16, 0 mov BYTE PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A, 0 pop ecx ret 0 ??__Fs@@YAXXZ ENDP In fact, a special function with all constructors of global variables is called from CRT, before main(). More than that: with the help of atexit() another function is registered, which contain calls to all destructors of such global variables. GCC works likewise: Listing 51.28: GCC 4.8.1 main: push ebp mov ebp, esp and esp, -16 sub esp, 16 mov eax, DWORD PTR s mov DWORD PTR [esp], eax call puts xor eax, eax leave ret .LC0: .string "a string" _GLOBAL__sub_I_s: sub esp, 44 lea eax, [esp+31] mov DWORD PTR [esp+8], eax mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 mov DWORD PTR [esp], OFFSET FLAT:s call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+8], OFFSET FLAT:__dso_handle mov DWORD PTR [esp+4], OFFSET FLAT:s mov DWORD PTR [esp], OFFSET FLAT:_ZNSsD1Ev call __cxa_atexit add esp, 44 ret .LFE645: .size _GLOBAL__sub_I_s, .-_GLOBAL__sub_I_s .section .init_array,"aw" .align 4 .long _GLOBAL__sub_I_s .globl s .bss .align 4 .type s, @object .size s, 4 s: .zero 4 .hidden __dso_handle 562
  • 587. CHAPTER 51. C++ 51.4. STL But it does not create a separate function for this, each destructor is passed to atexit(), one by one. 51.4.2 std::list This is the well-known doubly-linked list: each element has two pointers, to the previous and next elements. This implies that the memory footprint is enlarged by 2 words for each element (8 bytes in 32-bit environment or 16 bytes in 64-bit). C++ STL just adds the “next” and “previous” pointers to the existing structure of the type that you want to unite in a list. Let’s work out an example with a simple 2-variable structure that we want to store in a list. Although the C++ standard [ISO13] does not say how to implement it, both MSVC’s and GCC’s implementations are straight- forward and similar, so here is only one source code for both: #include <stdio.h> #include <list> #include <iostream> struct a { int x; int y; }; struct List_node { struct List_node* _Next; struct List_node* _Prev; int x; int y; }; void dump_List_node (struct List_node *n) { printf ("ptr=0x%p _Next=0x%p _Prev=0x%p x=%d y=%dn", n, n->_Next, n->_Prev, n->x, n->y); }; void dump_List_vals (struct List_node* n) { struct List_node* current=n; for (;;) { dump_List_node (current); current=current->_Next; if (current==n) // end break; }; }; void dump_List_val (unsigned int *a) { #ifdef _MSC_VER // GCC implementation does not have "size" field printf ("_Myhead=0x%p, _Mysize=%dn", a[0], a[1]); #endif dump_List_vals ((struct List_node*)a[0]); }; int main() { std::list<struct a> l; printf ("* empty list:n"); dump_List_val((unsigned int*)(void*)&l); struct a t1; t1.x=1; t1.y=2; 563
  • 588. CHAPTER 51. C++ 51.4. STL l.push_front (t1); t1.x=3; t1.y=4; l.push_front (t1); t1.x=5; t1.y=6; l.push_back (t1); printf ("* 3-elements list:n"); dump_List_val((unsigned int*)(void*)&l); std::list<struct a>::iterator tmp; printf ("node at .begin:n"); tmp=l.begin(); dump_List_node ((struct List_node *)*(void**)&tmp); printf ("node at .end:n"); tmp=l.end(); dump_List_node ((struct List_node *)*(void**)&tmp); printf ("* let's count from the begin:n"); std::list<struct a>::iterator it=l.begin(); printf ("1st element: %d %dn", (*it).x, (*it).y); it++; printf ("2nd element: %d %dn", (*it).x, (*it).y); it++; printf ("3rd element: %d %dn", (*it).x, (*it).y); it++; printf ("element at .end(): %d %dn", (*it).x, (*it).y); printf ("* let's count from the end:n"); std::list<struct a>::iterator it2=l.end(); printf ("element at .end(): %d %dn", (*it2).x, (*it2).y); it2--; printf ("3rd element: %d %dn", (*it2).x, (*it2).y); it2--; printf ("2nd element: %d %dn", (*it2).x, (*it2).y); it2--; printf ("1st element: %d %dn", (*it2).x, (*it2).y); printf ("removing last element...n"); l.pop_back(); dump_List_val((unsigned int*)(void*)&l); }; GCC Let’s start with GCC. When we run the example, we’ll see a long dump, let’s work with it in pieces. * empty list: ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0 Here we see an empty list. Despite the fact it is empty, it has one element with garbage (AKA dummy node) in x and y. Both the “next” and “prev” pointers are pointing to the self node: ..Next . Prev . X=garbage . Y=garbage . Variable std::list . list.begin() . list.end() ........ 564
  • 589. CHAPTER 51. C++ 51.4. STL At this moment, the .begin and .end iterators are equal to each other. If we push 3 elements, the list internally will be: * 3-elements list: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2 ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 The last element is still at 0x0028fe90, it not to be moved until the list’s disposal. It still contain random garbage in x and y (5 and 6). By coincidence, these values are the same as in the last element, but it doesn’t mean that they are meaningful. Here is how these 3 elements are stored in memory: ..Next . Prev . X=1st element . Y=1st element . Next. Prev . X=2nd element . Y=2nd element . Next. Prev . X=3rd element . Y=3rd element . Next. Prev . X=garbage . Y=garbage . Variable std::list . list.begin() . list.end() ........ The l variable always points to the first node. The .begin() and .end() iterators are not variables, but functions, which when called return pointers to the corresponding nodes. Having a dummy element (AKA sentinel node) is a very popular practice in implementing doubly-linked lists. Without it, a lot of operations may become slightly more complex and, hence, slower. The iterator is in fact just a pointer to a node. list.begin() and list.end() just return pointers. node at .begin: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 node at .end: ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 The fact that the last element has a pointer to the first and the first element has a pointer to the last one remind us circular list. This is very helpful here: having a pointer to the first list element, i.e., that is in the l variable, it is easy to get a pointer to the last one quickly, without the need to traverse the whole list. Inserting an element at the list end is also quick, thanks to this feature. operator-- and operator++ just set the current iterator’s value to the current_node->prev or current_node->next values. The reverse iterators (.rbegin, .rend) work just as the same, but in reverse. operator* just returns a pointer to the point in the node structure, where the user’s structure starts, i.e., a pointer to the first element of the structure (x). The list insertion and deletion are trivial: just allocate a new node (or deallocate) and update all pointers to be valid. That’s why an iterator may become invalid after element deletion: it may still point to the node that was already deal- located. This is also called a dangling pointer. And of course, the information from the freed node (to which iterator still points) cannot be used anymore. The GCC implementation (as of 4.8.1) doesn’t store the current size of the list: this implies a slow .size() method: it has to traverse the whole list to count the elements, because it doesn’t have any other way to get the information. This mean that this operation is O(n), i.e., it gets slower steadily as the list grows. Listing 51.29: Optimizing GCC 4.8.1 -fno-inline-small-functions main proc near push ebp mov ebp, esp push esi push ebx 565
  • 590. CHAPTER 51. C++ 51.4. STL and esp, 0FFFFFFF0h sub esp, 20h lea ebx, [esp+10h] mov dword ptr [esp], offset s ; "* empty list:" mov [esp+10h], ebx mov [esp+14h], ebx call puts mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) lea esi, [esp+18h] mov [esp+4], esi mov [esp], ebx mov dword ptr [esp+18h], 1 ; X for new element mov dword ptr [esp+1Ch], 2 ; Y for new element call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a⤦ const&) mov [esp+4], esi mov [esp], ebx mov dword ptr [esp+18h], 3 ; X for new element mov dword ptr [esp+1Ch], 4 ; Y for new element call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a⤦ const&) mov dword ptr [esp], 10h mov dword ptr [esp+18h], 5 ; X for new element mov dword ptr [esp+1Ch], 6 ; Y for new element call _Znwj ; operator new(uint) cmp eax, 0FFFFFFF8h jz short loc_80002A6 mov ecx, [esp+1Ch] mov edx, [esp+18h] mov [eax+0Ch], ecx mov [eax+8], edx loc_80002A6: ; CODE XREF: main+86 mov [esp+4], ebx mov [esp], eax call _ZNSt8__detail15_List_node_base7_M_hookEPS0_ ; std::__detail::_List_node_base::_M_hook⤦ (std::__detail::_List_node_base*) mov dword ptr [esp], offset a3ElementsList ; "* 3-elements list:" call puts mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) mov dword ptr [esp], offset aNodeAt_begin ; "node at .begin:" call puts mov eax, [esp+10h] mov [esp], eax call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *) mov dword ptr [esp], offset aNodeAt_end ; "node at .end:" call puts mov [esp], ebx call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *) mov dword ptr [esp], offset aLetSCountFromT ; "* let's count from the begin:" call puts mov esi, [esp+10h] mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi] ; operator++: get ->next pointer mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi] ; operator++: get ->next pointer 566
  • 591. CHAPTER 51. C++ 51.4. STL mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov eax, [esi] ; operator++: get ->next pointer mov edx, [eax+0Ch] mov [esp+0Ch], edx mov eax, [eax+8] mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov dword ptr [esp], offset aLetSCountFro_0 ; "* let's count from the end:" call puts mov eax, [esp+1Ch] mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %dn" mov dword ptr [esp], 1 mov [esp+0Ch], eax mov eax, [esp+18h] mov [esp+8], eax call __printf_chk mov esi, [esp+14h] mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi+4] ; operator--: get ->prev pointer mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov eax, [esi+4] ; operator--: get ->prev pointer mov edx, [eax+0Ch] mov [esp+0Ch], edx mov eax, [eax+8] mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %dn" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov dword ptr [esp], offset aRemovingLastEl ; "removing last element..." call puts mov esi, [esp+14h] mov [esp], esi call _ZNSt8__detail15_List_node_base9_M_unhookEv ; std::__detail::_List_node_base::⤦ _M_unhook(void) mov [esp], esi ; void * call _ZdlPv ; operator delete(void *) mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) mov [esp], ebx call _ZNSt10_List_baseI1aSaIS0_EE8_M_clearEv ; std::_List_base<a,std::allocator<a>>::⤦ _M_clear(void) lea esp, [ebp-8] xor eax, eax pop ebx pop esi pop ebp retn main endp 567
  • 592. CHAPTER 51. C++ 51.4. STL Listing 51.30: The whole output * empty list: ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0 * 3-elements list: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2 ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 node at .begin: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 node at .end: ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 * let's count from the begin: 1st element: 3 4 2nd element: 1 2 3rd element: 5 6 element at .end(): 5 6 * let's count from the end: element at .end(): 5 6 3rd element: 5 6 2nd element: 1 2 1st element: 3 4 removing last element... ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x0028fe90 _Prev=0x000349a0 x=1 y=2 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034988 x=5 y=6 MSVC MSVC’s implementation (2012) is just the same, but it also stores the current size of the list. This implies that the .size() method is very fast (O(1)): it just reads one value from memory. On the other hand, the size variable must be updated at each insertion/deletion. MSVC’s implementation is also slightly different in the way it arranges the nodes: ..Next . Prev . X=garbage . Y=garbage . Next. Prev . X=1st element . Y=1st element . Next. Prev . X=2nd element . Y=2nd element . Next. Prev . X=3rd element . Y=3rd element . Variable std::list . list.end() . list.begin() ........ GCC has its dummy element at the end of the list, while MSVC’s is at the beginning. Listing 51.31: Optimizing MSVC 2012 /Fa2.asm /GS- /Ob1 _l$ = -16 ; size = 8 _t1$ = -8 ; size = 8 _main PROC sub esp, 16 push ebx push esi push edi push 0 push 0 lea ecx, DWORD PTR _l$[esp+36] mov DWORD PTR _l$[esp+40], 0 568
  • 593. CHAPTER 51. C++ 51.4. STL ; allocate first "garbage" element call ?_Buynode0@?$_List_alloc@$0A@U?$_List_base_types@Ua@@V?⤦ $allocator@Ua@@@std@@@std@@@std@@QAEPAU?$_List_node@Ua@@PAX@2@PAU32@0@Z ; std::⤦ _List_alloc<0,std::_List_base_types<a,std::allocator<a> > >::_Buynode0 mov edi, DWORD PTR __imp__printf mov ebx, eax push OFFSET $SG40685 ; '* empty list:' mov DWORD PTR _l$[esp+32], ebx call edi ; printf lea eax, DWORD PTR _l$[esp+32] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val mov esi, DWORD PTR [ebx] add esp, 8 lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [esi+4] lea ecx, DWORD PTR _l$[esp+36] push esi mov DWORD PTR _t1$[esp+40], 1 ; data for a new node mov DWORD PTR _t1$[esp+44], 2 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦ $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦ const &> mov DWORD PTR [esi+4], eax mov ecx, DWORD PTR [eax+4] mov DWORD PTR _t1$[esp+28], 3 ; data for a new node mov DWORD PTR [ecx], eax mov esi, DWORD PTR [ebx] lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [esi+4] lea ecx, DWORD PTR _l$[esp+36] push esi mov DWORD PTR _t1$[esp+44], 4 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦ $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦ const &> mov DWORD PTR [esi+4], eax mov ecx, DWORD PTR [eax+4] mov DWORD PTR _t1$[esp+28], 5 ; data for a new node mov DWORD PTR [ecx], eax lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [ebx+4] lea ecx, DWORD PTR _l$[esp+36] push ebx mov DWORD PTR _t1$[esp+44], 6 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU?⤦ $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a ⤦ const &> mov DWORD PTR [ebx+4], eax mov ecx, DWORD PTR [eax+4] push OFFSET $SG40689 ; '* 3-elements list:' mov DWORD PTR _l$[esp+36], 3 mov DWORD PTR [ecx], eax call edi ; printf lea eax, DWORD PTR _l$[esp+32] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val push OFFSET $SG40831 ; 'node at .begin:' call edi ; printf push DWORD PTR [ebx] ; get next field of node l variable points to call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node push OFFSET $SG40835 ; 'node at .end:' call edi ; printf push ebx ; pointer to the node $l$ variable points to! 569
  • 594. CHAPTER 51. C++ 51.4. STL call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node push OFFSET $SG40839 ; '* let''s count from the begin:' call edi ; printf mov esi, DWORD PTR [ebx] ; operator++: get ->next pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40846 ; '1st element: %d %d' call edi ; printf mov esi, DWORD PTR [esi] ; operator++: get ->next pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40848 ; '2nd element: %d %d' call edi ; printf mov esi, DWORD PTR [esi] ; operator++: get ->next pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40850 ; '3rd element: %d %d' call edi ; printf mov eax, DWORD PTR [esi] ; operator++: get ->next pointer add esp, 64 push DWORD PTR [eax+12] push DWORD PTR [eax+8] push OFFSET $SG40852 ; 'element at .end(): %d %d' call edi ; printf push OFFSET $SG40853 ; '* let''s count from the end:' call edi ; printf push DWORD PTR [ebx+12] ; use x and y fields from the node l variable points to push DWORD PTR [ebx+8] push OFFSET $SG40860 ; 'element at .end(): %d %d' call edi ; printf mov esi, DWORD PTR [ebx+4] ; operator--: get ->prev pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40862 ; '3rd element: %d %d' call edi ; printf mov esi, DWORD PTR [esi+4] ; operator--: get ->prev pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40864 ; '2nd element: %d %d' call edi ; printf mov eax, DWORD PTR [esi+4] ; operator--: get ->prev pointer push DWORD PTR [eax+12] push DWORD PTR [eax+8] push OFFSET $SG40866 ; '1st element: %d %d' call edi ; printf add esp, 64 push OFFSET $SG40867 ; 'removing last element...' call edi ; printf mov edx, DWORD PTR [ebx+4] add esp, 4 ; prev=next? ; it is the only element, "garbage one"? ; if yes, do not delete it! cmp edx, ebx je SHORT $LN349@main mov ecx, DWORD PTR [edx+4] mov eax, DWORD PTR [edx] mov DWORD PTR [ecx], eax mov ecx, DWORD PTR [edx] mov eax, DWORD PTR [edx+4] push edx mov DWORD PTR [ecx+4], eax call ??3@YAXPAX@Z ; operator delete add esp, 4 mov DWORD PTR _l$[esp+32], 2 $LN349@main: lea eax, DWORD PTR _l$[esp+28] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val 570
  • 595. CHAPTER 51. C++ 51.4. STL mov eax, DWORD PTR [ebx] add esp, 4 mov DWORD PTR [ebx], ebx mov DWORD PTR [ebx+4], ebx cmp eax, ebx je SHORT $LN412@main $LL414@main: mov esi, DWORD PTR [eax] push eax call ??3@YAXPAX@Z ; operator delete add esp, 4 mov eax, esi cmp esi, ebx jne SHORT $LL414@main $LN412@main: push ebx call ??3@YAXPAX@Z ; operator delete add esp, 4 xor eax, eax pop edi pop esi pop ebx add esp, 16 ret 0 _main ENDP Unlike GCC, MSVC’s code allocates the dummy element at the start of the function with the help of the “Buynode” function, it is also used to allocate the rest of the nodes ( GCC’s code allocates the first element in the local stack). Listing 51.32: The whole output * empty list: _Myhead=0x003CC258, _Mysize=0 ptr=0x003CC258 _Next=0x003CC258 _Prev=0x003CC258 x=6226002 y=4522072 * 3-elements list: _Myhead=0x003CC258, _Mysize=3 ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072 ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 ptr=0x003CC270 _Next=0x003CC2A0 _Prev=0x003CC288 x=1 y=2 ptr=0x003CC2A0 _Next=0x003CC258 _Prev=0x003CC270 x=5 y=6 node at .begin: ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 node at .end: ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072 * let's count from the begin: 1st element: 3 4 2nd element: 1 2 3rd element: 5 6 element at .end(): 6226002 4522072 * let's count from the end: element at .end(): 6226002 4522072 3rd element: 5 6 2nd element: 1 2 1st element: 3 4 removing last element... _Myhead=0x003CC258, _Mysize=2 ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC270 x=6226002 y=4522072 ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 ptr=0x003CC270 _Next=0x003CC258 _Prev=0x003CC288 x=1 y=2 C++11 std::forward_list The same thing as std::list, but singly-linked one, i.e., having only the “next” field at each node. It has a smaller memory footprint, but also don’t offer the ability to traverse list backwards. 571
  • 596. CHAPTER 51. C++ 51.4. STL 51.4.3 std::vector I would call std::vector a “safe wrapper” of thePODT8 C array. Internally it is somewhat similar to std::string ( 51.4.1 on page 557): it has a pointer to the allocated buffer, a pointer to the end of the array, and a pointer to the end of the allocated buffer. The array’s elements lie in memory adjacently to each other, just like in a normal array ( 18 on page 257). In C++11 there is a new method called .data() , that returns a pointer to the buffer, like .c_str() in std::string. The buffer allocated in the heap can be larger than the array itself. Both MSVC’s and GCC’s implementations are similar, just the names of the structure’s fields are slightly different9 , so here is one source code that works for both compilers. Here is again the C-like code for dumping the structure of std::vector: #include <stdio.h> #include <vector> #include <algorithm> #include <functional> struct vector_of_ints { // MSVC names: int *Myfirst; int *Mylast; int *Myend; // GCC structure is the same, but names are: _M_start, _M_finish, _M_end_of_storage }; void dump(struct vector_of_ints *in) { printf ("_Myfirst=%p, _Mylast=%p, _Myend=%pn", in->Myfirst, in->Mylast, in->Myend); size_t size=(in->Mylast-in->Myfirst); size_t capacity=(in->Myend-in->Myfirst); printf ("size=%d, capacity=%dn", size, capacity); for (size_t i=0; i<size; i++) printf ("element %d: %dn", i, in->Myfirst[i]); }; int main() { std::vector<int> c; dump ((struct vector_of_ints*)(void*)&c); c.push_back(1); dump ((struct vector_of_ints*)(void*)&c); c.push_back(2); dump ((struct vector_of_ints*)(void*)&c); c.push_back(3); dump ((struct vector_of_ints*)(void*)&c); c.push_back(4); dump ((struct vector_of_ints*)(void*)&c); c.reserve (6); dump ((struct vector_of_ints*)(void*)&c); c.push_back(5); dump ((struct vector_of_ints*)(void*)&c); c.push_back(6); dump ((struct vector_of_ints*)(void*)&c); printf ("%dn", c.at(5)); // with bounds checking printf ("%dn", c[8]); // operator[], without bounds checking }; Here is the output of this program when compiled in MSVC: _Myfirst=00000000, _Mylast=00000000, _Myend=00000000 size=0, capacity=0 _Myfirst=0051CF48, _Mylast=0051CF4C, _Myend=0051CF4C size=1, capacity=1 element 0: 1 _Myfirst=0051CF58, _Mylast=0051CF60, _Myend=0051CF60 size=2, capacity=2 element 0: 1 8(C++) Plain Old Data Type 9GCC internals: http://go.yurichev.com/17086 572
  • 597. CHAPTER 51. C++ 51.4. STL element 1: 2 _Myfirst=0051C278, _Mylast=0051C284, _Myend=0051C284 size=3, capacity=3 element 0: 1 element 1: 2 element 2: 3 _Myfirst=0051C290, _Mylast=0051C2A0, _Myend=0051C2A0 size=4, capacity=4 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0051B180, _Mylast=0051B190, _Myend=0051B198 size=4, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0051B180, _Mylast=0051B194, _Myend=0051B198 size=5, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 _Myfirst=0051B180, _Mylast=0051B198, _Myend=0051B198 size=6, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 element 5: 6 6 6619158 As it can be seen, there is no allocated buffer when main() starts. After the first push_back() call, a buffer is allocated. And then, after each push_back() call, both array size and buffer size (capacity) are increased. But the buffer address changes as well, because push_back() reallocates the buffer in the heap each time. It is costly operation, that’s why it is very important to predict the size of the array in the future and reserve enough space for it with the .reserve() method. The last number is garbage: there are no array elements at this point, so a random number is printed. This illustrates the fact that operator[] of std::vector does not check of the index is in the array’s bounds. The slower .at() method, however, does this checking and throws an std::out_of_range exception in case of error. Let’s see the code: Listing 51.33: MSVC 2012 /GS- /Ob1 $SG52650 DB '%d', 0aH, 00H $SG52651 DB '%d', 0aH, 00H _this$ = -4 ; size = 4 __Pos$ = 8 ; size = 4 ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z PROC ; std::vector<int,std::allocator<int> ⤦ >::at, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR _this$[ebp] mov edx, DWORD PTR [eax+4] sub edx, DWORD PTR [ecx] sar edx, 2 cmp edx, DWORD PTR __Pos$[ebp] ja SHORT $LN1@at push OFFSET ??_C@_0BM@NMJKDPPO@invalid?5vector?$DMT?$DO?5subscript?$AA@ call DWORD PTR __imp_?_Xout_of_range@std@@YAXPBD@Z $LN1@at: mov eax, DWORD PTR _this$[ebp] 573
  • 598. CHAPTER 51. C++ 51.4. STL mov ecx, DWORD PTR [eax] mov edx, DWORD PTR __Pos$[ebp] lea eax, DWORD PTR [ecx+edx*4] $LN3@at: mov esp, ebp pop ebp ret 4 ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ENDP ; std::vector<int,std::allocator<int> ⤦ >::at _c$ = -36 ; size = 12 $T1 = -24 ; size = 4 $T2 = -20 ; size = 4 $T3 = -16 ; size = 4 $T4 = -12 ; size = 4 $T5 = -8 ; size = 4 $T6 = -4 ; size = 4 _main PROC push ebp mov ebp, esp sub esp, 36 mov DWORD PTR _c$[ebp], 0 ; Myfirst mov DWORD PTR _c$[ebp+4], 0 ; Mylast mov DWORD PTR _c$[ebp+8], 0 ; Myend lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T6[ebp], 1 lea ecx, DWORD PTR $T6[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T5[ebp], 2 lea eax, DWORD PTR $T5[ebp] push eax lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea ecx, DWORD PTR _c$[ebp] push ecx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T4[ebp], 3 lea edx, DWORD PTR $T4[ebp] push edx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T3[ebp], 4 lea ecx, DWORD PTR $T3[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 push 6 lea ecx, DWORD PTR _c$[ebp] 574
  • 599. CHAPTER 51. C++ 51.4. STL call ?reserve@?$vector@HV?$allocator@H@std@@@std@@QAEXI@Z ; std::vector<int,std::allocator<⤦ int> >::reserve lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T2[ebp], 5 lea ecx, DWORD PTR $T2[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T1[ebp], 6 lea eax, DWORD PTR $T1[ebp] push eax lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std::⤦ allocator<int> >::push_back lea ecx, DWORD PTR _c$[ebp] push ecx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 push 5 lea ecx, DWORD PTR _c$[ebp] call ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ; std::vector<int,std::allocator<int⤦ > >::at mov edx, DWORD PTR [eax] push edx push OFFSET $SG52650 ; '%d' call DWORD PTR __imp__printf add esp, 8 mov eax, 8 shl eax, 2 mov ecx, DWORD PTR _c$[ebp] mov edx, DWORD PTR [ecx+eax] push edx push OFFSET $SG52651 ; '%d' call DWORD PTR __imp__printf add esp, 8 lea ecx, DWORD PTR _c$[ebp] call ?_Tidy@?$vector@HV?$allocator@H@std@@@std@@IAEXXZ ; std::vector<int,std::allocator<int⤦ > >::_Tidy xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP We see how the .at() method checks the bounds and throws an exception in case of error. The number that the last printf() call prints is just taken from the memory, without any checks. One may ask, why not use the variables like “size” and “capacity”, like it was done in std::string. I suppose that this was done for faster bounds checking. But I’m not sure. The code GCC generates is in general almost the same, but the .at() method is inlined: Listing 51.34: GCC 4.8.1 -fno-inline-small-functions -O1 main proc near push ebp mov ebp, esp push edi push esi push ebx and esp, 0FFFFFFF0h sub esp, 20h mov dword ptr [esp+14h], 0 mov dword ptr [esp+18h], 0 mov dword ptr [esp+1Ch], 0 575
  • 600. CHAPTER 51. C++ 51.4. STL lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 1 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 2 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 3 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 4 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov ebx, [esp+14h] mov eax, [esp+1Ch] sub eax, ebx cmp eax, 17h ja short loc_80001CF mov edi, [esp+18h] sub edi, ebx sar edi, 2 mov dword ptr [esp], 18h call _Znwj ; operator new(uint) mov esi, eax test edi, edi jz short loc_80001AD lea eax, ds:0[edi*4] mov [esp+8], eax ; n mov [esp+4], ebx ; src mov [esp], esi ; dest call memmove loc_80001AD: ; CODE XREF: main+F8 mov eax, [esp+14h] test eax, eax jz short loc_80001BD mov [esp], eax ; void * call _ZdlPv ; operator delete(void *) loc_80001BD: ; CODE XREF: main+117 576
  • 601. CHAPTER 51. C++ 51.4. STL mov [esp+14h], esi lea eax, [esi+edi*4] mov [esp+18h], eax add esi, 18h mov [esp+1Ch], esi loc_80001CF: ; CODE XREF: main+DD lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 5 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 6 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back(⤦ int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov eax, [esp+14h] mov edx, [esp+18h] sub edx, eax cmp edx, 17h ja short loc_8000246 mov dword ptr [esp], offset aVector_m_range ; "vector::_M_range_check" call _ZSt20__throw_out_of_rangePKc ; std::__throw_out_of_range(char const*) loc_8000246: ; CODE XREF: main+19C mov eax, [eax+14h] mov [esp+8], eax mov dword ptr [esp+4], offset aD ; "%dn" mov dword ptr [esp], 1 call __printf_chk mov eax, [esp+14h] mov eax, [eax+20h] mov [esp+8], eax mov dword ptr [esp+4], offset aD ; "%dn" mov dword ptr [esp], 1 call __printf_chk mov eax, [esp+14h] test eax, eax jz short loc_80002AC mov [esp], eax ; void * call _ZdlPv ; operator delete(void *) jmp short loc_80002AC mov ebx, eax mov edx, [esp+14h] test edx, edx jz short loc_80002A4 mov [esp], edx ; void * call _ZdlPv ; operator delete(void *) loc_80002A4: ; CODE XREF: main+1FE mov [esp], ebx call _Unwind_Resume loc_80002AC: ; CODE XREF: main+1EA 577
  • 602. CHAPTER 51. C++ 51.4. STL ; main+1F4 mov eax, 0 lea esp, [ebp-0Ch] pop ebx pop esi pop edi pop ebp locret_80002B8: ; DATA XREF: .eh_frame:08000510 ; .eh_frame:080005BC retn main endp .reserve() is inlined as well. It calls new() if the buffer is too small for the new size, calls memmove() to copy the contents of the buffer, and calls delete() to free the old buffer. Let’s also see what the compiled program outputs if compiled with GCC: _Myfirst=0x(nil), _Mylast=0x(nil), _Myend=0x(nil) size=0, capacity=0 _Myfirst=0x8257008, _Mylast=0x825700c, _Myend=0x825700c size=1, capacity=1 element 0: 1 _Myfirst=0x8257018, _Mylast=0x8257020, _Myend=0x8257020 size=2, capacity=2 element 0: 1 element 1: 2 _Myfirst=0x8257028, _Mylast=0x8257034, _Myend=0x8257038 size=3, capacity=4 element 0: 1 element 1: 2 element 2: 3 _Myfirst=0x8257028, _Mylast=0x8257038, _Myend=0x8257038 size=4, capacity=4 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0x8257040, _Mylast=0x8257050, _Myend=0x8257058 size=4, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0x8257040, _Mylast=0x8257054, _Myend=0x8257058 size=5, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 _Myfirst=0x8257040, _Mylast=0x8257058, _Myend=0x8257058 size=6, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 element 5: 6 6 0 We can spot that the buffer size grows in a different way that in MSVC. Simple experimentation shows that in MSVC’s implementation the buffer grows by ~50% each time it needs to be enlarged, while GCC’s code enlarges it by 100% each time, i.e., doubles it. 51.4.4 std::map and std::set The binary tree is another fundamental data structure. As its name states, this is a tree where each node has at most 2 links to other nodes. Each node has key and/or value. Binary trees are usually the structure used in the implementation of “dictionaries” of key-values (AKA “associative arrays”). 578
  • 603. CHAPTER 51. C++ 51.4. STL There are at least three important properties that a binary trees has: • All keys are always stored in sorted form. • Keys of any types can be stored easily. Binary tree algorithms are unaware of the key’s type, only a key comparison function is required. • Finding a specific key is relatively fast in comparison with lists and arrays. Here is a very simple example: let’s store these numbers in a binary tree: 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 20, 99, 100, 101, 107, 1001, 1010. ..10. 1 . 0 . 5 . 3 . 2 .. 6 .. 9 . 100 . 20 . 12 . 11 .. 99 . 107 . 101 . 1001 .. 1010 All keys that are smaller than the node key’s value are stored on the left side. All keys that are bigger than the node key’s value are stored on the right side. Hence, the lookup algorithm is straightforward: if the value that you are looking for is smaller than the current node’s key value: move left, if it is bigger: move right, stop if the value required is equal to the node key’s value. That is why the searching algorithm may search for numbers, text strings, etc, as long as a key comparison function is provided. All keys have unique values. Having that, one needs ≈ log2 n steps in order to find a key in a balanced binary tree with n keys. This implies that ≈ 10 steps are needed ≈ 1000 keys, or ≈ 13 steps for ≈ 10000 keys. Not bad, but the tree has always to be balanced for this: i.e., the keys has to be distributed evenly on all levels. The insertion and removal operations do some maintenance to keep the tree in a balanced state. There are several popular balancing algorithms available, including the AVL tree and the red-black tree. The latter extends each node with a “color” value to simplify the balancing process, hence, each node may be “red” or “black”. Both GCC’s and MSVC’s std::map and std::set template implementations use red-black trees. std::set contains only keys. std::map is the “extended” version of std::set: it also has a value at each node. MSVC #include <map> #include <set> #include <string> #include <iostream> // structure is not packed! struct tree_node { struct tree_node *Left; struct tree_node *Parent; struct tree_node *Right; char Color; // 0 - Red, 1 - Black char Isnil; //std::pair Myval; unsigned int first; // called Myval in std::set const char *second; // not present in std::set }; struct tree_struct { struct tree_node *Myhead; 579
  • 604. CHAPTER 51. C++ 51.4. STL size_t Mysize; }; void dump_tree_node (struct tree_node *n, bool is_set, bool traverse) { printf ("ptr=0x%p Left=0x%p Parent=0x%p Right=0x%p Color=%d Isnil=%dn", n, n->Left, n->Parent, n->Right, n->Color, n->Isnil); if (n->Isnil==0) { if (is_set) printf ("first=%dn", n->first); else printf ("first=%d second=[%s]n", n->first, n->second); } if (traverse) { if (n->Isnil==1) dump_tree_node (n->Parent, is_set, true); else { if (n->Left->Isnil==0) dump_tree_node (n->Left, is_set, true); if (n->Right->Isnil==0) dump_tree_node (n->Right, is_set, true); }; }; }; const char* ALOT_OF_TABS="ttttttttttt"; void dump_as_tree (int tabs, struct tree_node *n, bool is_set) { if (is_set) printf ("%dn", n->first); else printf ("%d [%s]n", n->first, n->second); if (n->Left->Isnil==0) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->Left, is_set); }; if (n->Right->Isnil==0) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->Right, is_set); }; }; void dump_map_and_set(struct tree_struct *m, bool is_set) { printf ("ptr=0x%p, Myhead=0x%p, Mysize=%dn", m, m->Myhead, m->Mysize); dump_tree_node (m->Myhead, is_set, true); printf ("As a tree:n"); printf ("root----"); dump_as_tree (1, m->Myhead->Parent, is_set); }; int main() { // map std::map<int, const char*> m; m[10]="ten"; m[20]="twenty"; m[3]="three"; m[101]="one hundred one"; m[100]="one hundred"; m[12]="twelve"; 580
  • 605. CHAPTER 51. C++ 51.4. STL m[107]="one hundred seven"; m[0]="zero"; m[1]="one"; m[6]="six"; m[99]="ninety-nine"; m[5]="five"; m[11]="eleven"; m[1001]="one thousand one"; m[1010]="one thousand ten"; m[2]="two"; m[9]="nine"; printf ("dumping m as map:n"); dump_map_and_set ((struct tree_struct *)(void*)&m, false); std::map<int, const char*>::iterator it1=m.begin(); printf ("m.begin():n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false); it1=m.end(); printf ("m.end():n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false); // set std::set<int> s; s.insert(123); s.insert(456); s.insert(11); s.insert(12); s.insert(100); s.insert(1001); printf ("dumping s as set:n"); dump_map_and_set ((struct tree_struct *)(void*)&s, true); std::set<int>::iterator it2=s.begin(); printf ("s.begin():n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false); it2=s.end(); printf ("s.end():n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false); }; Listing 51.35: MSVC 2012 dumping m as map: ptr=0x0020FE04, Myhead=0x005BB3A0, Mysize=17 ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1 ptr=0x005BB3C0 Left=0x005BB4C0 Parent=0x005BB3A0 Right=0x005BB440 Color=1 Isnil=0 first=10 second=[ten] ptr=0x005BB4C0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB520 Color=1 Isnil=0 first=1 second=[one] ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0 first=0 second=[zero] ptr=0x005BB520 Left=0x005BB400 Parent=0x005BB4C0 Right=0x005BB4E0 Color=0 Isnil=0 first=5 second=[five] ptr=0x005BB400 Left=0x005BB5A0 Parent=0x005BB520 Right=0x005BB3A0 Color=1 Isnil=0 first=3 second=[three] ptr=0x005BB5A0 Left=0x005BB3A0 Parent=0x005BB400 Right=0x005BB3A0 Color=0 Isnil=0 first=2 second=[two] ptr=0x005BB4E0 Left=0x005BB3A0 Parent=0x005BB520 Right=0x005BB5C0 Color=1 Isnil=0 first=6 second=[six] ptr=0x005BB5C0 Left=0x005BB3A0 Parent=0x005BB4E0 Right=0x005BB3A0 Color=0 Isnil=0 first=9 second=[nine] ptr=0x005BB440 Left=0x005BB3E0 Parent=0x005BB3C0 Right=0x005BB480 Color=1 Isnil=0 first=100 second=[one hundred] ptr=0x005BB3E0 Left=0x005BB460 Parent=0x005BB440 Right=0x005BB500 Color=0 Isnil=0 first=20 second=[twenty] ptr=0x005BB460 Left=0x005BB540 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0 first=12 second=[twelve] ptr=0x005BB540 Left=0x005BB3A0 Parent=0x005BB460 Right=0x005BB3A0 Color=0 Isnil=0 first=11 second=[eleven] ptr=0x005BB500 Left=0x005BB3A0 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0 581
  • 606. CHAPTER 51. C++ 51.4. STL first=99 second=[ninety-nine] ptr=0x005BB480 Left=0x005BB420 Parent=0x005BB440 Right=0x005BB560 Color=0 Isnil=0 first=107 second=[one hundred seven] ptr=0x005BB420 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB3A0 Color=1 Isnil=0 first=101 second=[one hundred one] ptr=0x005BB560 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB580 Color=1 Isnil=0 first=1001 second=[one thousand one] ptr=0x005BB580 Left=0x005BB3A0 Parent=0x005BB560 Right=0x005BB3A0 Color=0 Isnil=0 first=1010 second=[one thousand ten] As a tree: root----10 [ten] L-------1 [one] L-------0 [zero] R-------5 [five] L-------3 [three] L-------2 [two] R-------6 [six] R-------9 [nine] R-------100 [one hundred] L-------20 [twenty] L-------12 [twelve] L-------11 [eleven] R-------99 [ninety-nine] R-------107 [one hundred seven] L-------101 [one hundred one] R-------1001 [one thousand one] R-------1010 [one thousand ten] m.begin(): ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0 first=0 second=[zero] m.end(): ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1 dumping s as set: ptr=0x0020FDFC, Myhead=0x005BB5E0, Mysize=6 ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1 ptr=0x005BB600 Left=0x005BB660 Parent=0x005BB5E0 Right=0x005BB620 Color=1 Isnil=0 first=123 ptr=0x005BB660 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB680 Color=1 Isnil=0 first=12 ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=11 ptr=0x005BB680 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=100 ptr=0x005BB620 Left=0x005BB5E0 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=0 first=456 ptr=0x005BB6A0 Left=0x005BB5E0 Parent=0x005BB620 Right=0x005BB5E0 Color=0 Isnil=0 first=1001 As a tree: root----123 L-------12 L-------11 R-------100 R-------456 R-------1001 s.begin(): ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=11 s.end(): ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1 The structure is not packed, so both char values occupy 4 bytes each. As for std::map, first and second can be viewed as a single value of type std::pair. std::set has only one value at this address in the structure instead. The current size of the tree is always present, as in the case of the implementation of std::list in MSVC ( 51.4.2 on page 568). As in the case of std::list, the iterators are just pointers to nodes. The .begin() iterator points to the minimal key. That pointer is not stored anywhere (as in lists), the minimal key of the tree is looked up every time. operator-- and operator++ move the current node pointer to the predecessor or successor respectively, i.e., the nodes which have the 582
  • 607. CHAPTER 51. C++ 51.4. STL previous or next key. The algorithms for all these operations are explained in [Cor+09]. The .end() iterator points to the dummy node, it has 1 in Isnil, which implies that the node has no key and/or value. It can be viewed as a “landing zone” in HDD10 . The “parent” field of the dummy node points to the root node, which serves as a vertex of the tree and contains information. GCC #include <stdio.h> #include <map> #include <set> #include <string> #include <iostream> struct map_pair { int key; const char *value; }; struct tree_node { int M_color; // 0 - Red, 1 - Black struct tree_node *M_parent; struct tree_node *M_left; struct tree_node *M_right; }; struct tree_struct { int M_key_compare; struct tree_node M_header; size_t M_node_count; }; void dump_tree_node (struct tree_node *n, bool is_set, bool traverse, bool dump_keys_and_values⤦ ) { printf ("ptr=0x%p M_left=0x%p M_parent=0x%p M_right=0x%p M_color=%dn", n, n->M_left, n->M_parent, n->M_right, n->M_color); void *point_after_struct=((char*)n)+sizeof(struct tree_node); if (dump_keys_and_values) { if (is_set) printf ("key=%dn", *(int*)point_after_struct); else { struct map_pair *p=(struct map_pair *)point_after_struct; printf ("key=%d value=[%s]n", p->key, p->value); }; }; if (traverse==false) return; if (n->M_left) dump_tree_node (n->M_left, is_set, traverse, dump_keys_and_values); if (n->M_right) dump_tree_node (n->M_right, is_set, traverse, dump_keys_and_values); }; const char* ALOT_OF_TABS="ttttttttttt"; void dump_as_tree (int tabs, struct tree_node *n, bool is_set) { void *point_after_struct=((char*)n)+sizeof(struct tree_node); 10Hard disk drive 583
  • 608. CHAPTER 51. C++ 51.4. STL if (is_set) printf ("%dn", *(int*)point_after_struct); else { struct map_pair *p=(struct map_pair *)point_after_struct; printf ("%d [%s]n", p->key, p->value); } if (n->M_left) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_left, is_set); }; if (n->M_right) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_right, is_set); }; }; void dump_map_and_set(struct tree_struct *m, bool is_set) { printf ("ptr=0x%p, M_key_compare=0x%x, M_header=0x%p, M_node_count=%dn", m, m->M_key_compare, &m->M_header, m->M_node_count); dump_tree_node (m->M_header.M_parent, is_set, true, true); printf ("As a tree:n"); printf ("root----"); dump_as_tree (1, m->M_header.M_parent, is_set); }; int main() { // map std::map<int, const char*> m; m[10]="ten"; m[20]="twenty"; m[3]="three"; m[101]="one hundred one"; m[100]="one hundred"; m[12]="twelve"; m[107]="one hundred seven"; m[0]="zero"; m[1]="one"; m[6]="six"; m[99]="ninety-nine"; m[5]="five"; m[11]="eleven"; m[1001]="one thousand one"; m[1010]="one thousand ten"; m[2]="two"; m[9]="nine"; printf ("dumping m as map:n"); dump_map_and_set ((struct tree_struct *)(void*)&m, false); std::map<int, const char*>::iterator it1=m.begin(); printf ("m.begin():n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, true); it1=m.end(); printf ("m.end():n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, false); // set std::set<int> s; s.insert(123); s.insert(456); 584
  • 609. CHAPTER 51. C++ 51.4. STL s.insert(11); s.insert(12); s.insert(100); s.insert(1001); printf ("dumping s as set:n"); dump_map_and_set ((struct tree_struct *)(void*)&s, true); std::set<int>::iterator it2=s.begin(); printf ("s.begin():n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, true); it2=s.end(); printf ("s.end():n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, false); }; Listing 51.36: GCC 4.8.1 dumping m as map: ptr=0x0028FE3C, M_key_compare=0x402b70, M_header=0x0028FE40, M_node_count=17 ptr=0x007A4988 M_left=0x007A4C00 M_parent=0x0028FE40 M_right=0x007A4B80 M_color=1 key=10 value=[ten] ptr=0x007A4C00 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4C60 M_color=1 key=1 value=[one] ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1 key=0 value=[zero] ptr=0x007A4C60 M_left=0x007A4B40 M_parent=0x007A4C00 M_right=0x007A4C20 M_color=0 key=5 value=[five] ptr=0x007A4B40 M_left=0x007A4CE0 M_parent=0x007A4C60 M_right=0x00000000 M_color=1 key=3 value=[three] ptr=0x007A4CE0 M_left=0x00000000 M_parent=0x007A4B40 M_right=0x00000000 M_color=0 key=2 value=[two] ptr=0x007A4C20 M_left=0x00000000 M_parent=0x007A4C60 M_right=0x007A4D00 M_color=1 key=6 value=[six] ptr=0x007A4D00 M_left=0x00000000 M_parent=0x007A4C20 M_right=0x00000000 M_color=0 key=9 value=[nine] ptr=0x007A4B80 M_left=0x007A49A8 M_parent=0x007A4988 M_right=0x007A4BC0 M_color=1 key=100 value=[one hundred] ptr=0x007A49A8 M_left=0x007A4BA0 M_parent=0x007A4B80 M_right=0x007A4C40 M_color=0 key=20 value=[twenty] ptr=0x007A4BA0 M_left=0x007A4C80 M_parent=0x007A49A8 M_right=0x00000000 M_color=1 key=12 value=[twelve] ptr=0x007A4C80 M_left=0x00000000 M_parent=0x007A4BA0 M_right=0x00000000 M_color=0 key=11 value=[eleven] ptr=0x007A4C40 M_left=0x00000000 M_parent=0x007A49A8 M_right=0x00000000 M_color=1 key=99 value=[ninety-nine] ptr=0x007A4BC0 M_left=0x007A4B60 M_parent=0x007A4B80 M_right=0x007A4CA0 M_color=0 key=107 value=[one hundred seven] ptr=0x007A4B60 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x00000000 M_color=1 key=101 value=[one hundred one] ptr=0x007A4CA0 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x007A4CC0 M_color=1 key=1001 value=[one thousand one] ptr=0x007A4CC0 M_left=0x00000000 M_parent=0x007A4CA0 M_right=0x00000000 M_color=0 key=1010 value=[one thousand ten] As a tree: root----10 [ten] L-------1 [one] L-------0 [zero] R-------5 [five] L-------3 [three] L-------2 [two] R-------6 [six] R-------9 [nine] R-------100 [one hundred] L-------20 [twenty] L-------12 [twelve] L-------11 [eleven] R-------99 [ninety-nine] R-------107 [one hundred seven] L-------101 [one hundred one] R-------1001 [one thousand one] R-------1010 [one thousand ten] 585
  • 610. CHAPTER 51. C++ 51.4. STL m.begin(): ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1 key=0 value=[zero] m.end(): ptr=0x0028FE40 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4CC0 M_color=0 dumping s as set: ptr=0x0028FE20, M_key_compare=0x8, M_header=0x0028FE24, M_node_count=6 ptr=0x007A1E80 M_left=0x01D5D890 M_parent=0x0028FE24 M_right=0x01D5D850 M_color=1 key=123 ptr=0x01D5D890 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8B0 M_color=1 key=12 ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=11 ptr=0x01D5D8B0 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=100 ptr=0x01D5D850 M_left=0x00000000 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=1 key=456 ptr=0x01D5D8D0 M_left=0x00000000 M_parent=0x01D5D850 M_right=0x00000000 M_color=0 key=1001 As a tree: root----123 L-------12 L-------11 R-------100 R-------456 R-------1001 s.begin(): ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=11 s.end(): ptr=0x0028FE24 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=0 GCC’s implementation is very similar 11 . The only difference is the absence of the Isnil field, so the structure occupies slightly less space in memory than its implementation in MSVC. The dummy node is also used as a place to point the .end() iterator also has no key and/or value. Rebalancing demo (GCC) Here is also a demo showing us how a tree is rebalanced after some insertions. Listing 51.37: GCC #include <stdio.h> #include <map> #include <set> #include <string> #include <iostream> struct map_pair { int key; const char *value; }; struct tree_node { int M_color; // 0 - Red, 1 - Black struct tree_node *M_parent; struct tree_node *M_left; struct tree_node *M_right; }; struct tree_struct { int M_key_compare; struct tree_node M_header; size_t M_node_count; }; 11http://go.yurichev.com/17084 586
  • 611. CHAPTER 51. C++ 51.4. STL const char* ALOT_OF_TABS="ttttttttttt"; void dump_as_tree (int tabs, struct tree_node *n) { void *point_after_struct=((char*)n)+sizeof(struct tree_node); printf ("%dn", *(int*)point_after_struct); if (n->M_left) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_left); }; if (n->M_right) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_right); }; }; void dump_map_and_set(struct tree_struct *m) { printf ("root----"); dump_as_tree (1, m->M_header.M_parent); }; int main() { std::set<int> s; s.insert(123); s.insert(456); printf ("123, 456 are insertedn"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(11); s.insert(12); printf ("n"); printf ("11, 12 are insertedn"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(100); s.insert(1001); printf ("n"); printf ("100, 1001 are insertedn"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(667); s.insert(1); s.insert(4); s.insert(7); printf ("n"); printf ("667, 1, 4, 7 are insertedn"); dump_map_and_set ((struct tree_struct *)(void*)&s); printf ("n"); }; Listing 51.38: GCC 4.8.1 123, 456 are inserted root----123 R-------456 11, 12 are inserted root----123 L-------11 R-------12 R-------456 100, 1001 are inserted root----123 L-------12 L-------11 587
  • 612. CHAPTER 51. C++ 51.4. STL R-------100 R-------456 R-------1001 667, 1, 4, 7 are inserted root----12 L-------4 L-------1 R-------11 L-------7 R-------123 L-------100 R-------667 L-------456 R-------1001 588
  • 613. CHAPTER 52. NEGATIVE ARRAY INDICES Chapter 52 Negative array indices It’s possible to address the space before an array by supplying a negative index, e.g., array[−1]. It’s very hard to say why one should use it, I know probably only one practical application of this technique. C/C++ array elements indices start at 0, but some PLs have a first index at 1 (at least FORTRAN). Programmers may still have this habit, so using this little trick, it’s possible to address the first element in C/C++ using index 1: #include <stdio.h> int main() { int random_value=0x11223344; unsigned char array[10]; int i; unsigned char *fakearray=&array[-1]; for (i=0; i<10; i++) array[i]=i; printf ("first element %dn", fakearray[1]); printf ("second element %dn", fakearray[2]); printf ("last element %dn", fakearray[10]); printf ("array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02Xn", array[-1], array[-2], array[-3], array[-4]); }; Listing 52.1: Non-optimizing MSVC 2010 1 $SG2751 DB 'first element %d', 0aH, 00H 2 $SG2752 DB 'second element %d', 0aH, 00H 3 $SG2753 DB 'last element %d', 0aH, 00H 4 $SG2754 DB 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4' 5 DB ']=%02X', 0aH, 00H 6 7 _fakearray$ = -24 ; size = 4 8 _random_value$ = -20 ; size = 4 9 _array$ = -16 ; size = 10 10 _i$ = -4 ; size = 4 11 _main PROC 12 push ebp 13 mov ebp, esp 14 sub esp, 24 15 mov DWORD PTR _random_value$[ebp], 287454020 ; 11223344H 16 ; set fakearray[] one byte earlier before array[] 17 lea eax, DWORD PTR _array$[ebp] 18 add eax, -1 ; eax=eax-1 19 mov DWORD PTR _fakearray$[ebp], eax 20 mov DWORD PTR _i$[ebp], 0 21 jmp SHORT $LN3@main 22 ; fill array[] with 0..9 23 $LN2@main: 24 mov ecx, DWORD PTR _i$[ebp] 589
  • 614. CHAPTER 52. NEGATIVE ARRAY INDICES 25 add ecx, 1 26 mov DWORD PTR _i$[ebp], ecx 27 $LN3@main: 28 cmp DWORD PTR _i$[ebp], 10 29 jge SHORT $LN1@main 30 mov edx, DWORD PTR _i$[ebp] 31 mov al, BYTE PTR _i$[ebp] 32 mov BYTE PTR _array$[ebp+edx], al 33 jmp SHORT $LN2@main 34 $LN1@main: 35 mov ecx, DWORD PTR _fakearray$[ebp] 36 ; ecx=address of fakearray[0], ecx+1 is fakearray[1] or array[0] 37 movzx edx, BYTE PTR [ecx+1] 38 push edx 39 push OFFSET $SG2751 ; 'first element %d' 40 call _printf 41 add esp, 8 42 mov eax, DWORD PTR _fakearray$[ebp] 43 ; eax=address of fakearray[0], eax+2 is fakearray[2] or array[1] 44 movzx ecx, BYTE PTR [eax+2] 45 push ecx 46 push OFFSET $SG2752 ; 'second element %d' 47 call _printf 48 add esp, 8 49 mov edx, DWORD PTR _fakearray$[ebp] 50 ; edx=address of fakearray[0], edx+10 is fakearray[10] or array[9] 51 movzx eax, BYTE PTR [edx+10] 52 push eax 53 push OFFSET $SG2753 ; 'last element %d' 54 call _printf 55 add esp, 8 56 ; subtract 4, 3, 2 and 1 from pointer to array[0] in order to find values before array[] 57 lea ecx, DWORD PTR _array$[ebp] 58 movzx edx, BYTE PTR [ecx-4] 59 push edx 60 lea eax, DWORD PTR _array$[ebp] 61 movzx ecx, BYTE PTR [eax-3] 62 push ecx 63 lea edx, DWORD PTR _array$[ebp] 64 movzx eax, BYTE PTR [edx-2] 65 push eax 66 lea ecx, DWORD PTR _array$[ebp] 67 movzx edx, BYTE PTR [ecx-1] 68 push edx 69 push OFFSET $SG2754 ; 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02⤦ X' 70 call _printf 71 add esp, 20 72 xor eax, eax 73 mov esp, ebp 74 pop ebp 75 ret 0 76 _main ENDP So we have array[] of ten elements, filled with 0...9 bytes. Then we have the fakearray[] pointer, which points one byte before array[]. fakearray[1] points exactly to array[0]. But we are still curious, what is there before array[]? I added random_value before array[] and set it to 0x11223344. The non-optimizing compiler allocated the variables in the order they were declared, so yes, the 32-bit random_value is right before the array. I ran it, and: first element 0 second element 1 last element 9 array[-1]=11, array[-2]=22, array[-3]=33, array[-4]=44 Here is the stack fragment I copypasted from OllyDbg’s stack window (with my comments): Listing 52.2: Non-optimizing MSVC 2010 CPU Stack Address Value 590
  • 615. CHAPTER 52. NEGATIVE ARRAY INDICES 001DFBCC /001DFBD3 ; fakearray pointer 001DFBD0 |11223344 ; random_value 001DFBD4 |03020100 ; 4 bytes of array[] 001DFBD8 |07060504 ; 4 bytes of array[] 001DFBDC |00CB0908 ; random garbage + 2 last bytes of array[] 001DFBE0 |0000000A ; last i value after loop was finished 001DFBE4 |001DFC2C ; saved EBP value 001DFBE8 00CB129D ; Return Address The pointer to the fakearray[] (0x001DFBD3) is indeed the address of array[] in the stack (0x001DFBD4), but minus 1 byte. It’s still very hackish and dubious trick, I doubt anyone should use it in production code, but as a demonstration, it fits perfectly here. 591
  • 616. CHAPTER 53. WINDOWS 16-BIT Chapter 53 Windows 16-bit 16-bit Windows programs are rare nowadays, but in the cases of retrocomputing or dongle hacking ( 78 on page 744), I sometimes dig into these. 16-bit Windows versions were up to 3.11. 96/98/ME also support 16-bit code, as well as the 32-bit versions of the Windows NT line. The 64-bit versions of Windows NT line do not support 16-bit executable code at all. The code resembles MS-DOS’s one. Executable files are of type NE-type (so-called “new executable”). All examples considered here were compiled by the OpenWatcom 1.9 compiler, using these switches: wcl.exe -i=C:/WATCOM/h/win/ -s -os -bt=windows -bcl=windows example.c 53.1 Example#1 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MessageBeep(MB_ICONEXCLAMATION); return 0; }; WinMain proc near push bp mov bp, sp mov ax, 30h ; '0' ; MB_ICONEXCLAMATION constant push ax call MESSAGEBEEP xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp Seems to be easy, so far. 53.2 Example #2 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL); return 0; }; 592
  • 617. CHAPTER 53. WINDOWS 16-BIT 53.3. EXAMPLE #3 WinMain proc near push bp mov bp, sp xor ax, ax ; NULL push ax push ds mov ax, offset aHelloWorld ; 0x18. "hello, world" push ax push ds mov ax, offset aCaption ; 0x10. "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp dseg02:0010 aCaption db 'caption',0 dseg02:0018 aHelloWorld db 'hello, world',0 Couple important things here: the PASCAL calling convention dictates passing the first argument first (MB_YESNOCANCEL), and the last argument—last (NULL). This convention also tells the callee to restore the stack pointer: hence the RETN in- struction has 0Ah as argument, which implies that the pointer has to be increased by 10 bytes when the function exits. It is like stdcall ( 64.2 on page 663), but the arguments are passed in “natural” order. The pointers are passed in pairs: first the data segment is passed, then the pointer inside the segment. There is only one segment in this example, so DS always points to the data segment of the executable. 53.3 Example #3 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { int result=MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL); if (result==IDCANCEL) MessageBox (NULL, "you pressed cancel", "caption", MB_OK); else if (result==IDYES) MessageBox (NULL, "you pressed yes", "caption", MB_OK); else if (result==IDNO) MessageBox (NULL, "you pressed no", "caption", MB_OK); return 0; }; WinMain proc near push bp mov bp, sp xor ax, ax ; NULL push ax push ds mov ax, offset aHelloWorld ; "hello, world" push ax push ds mov ax, offset aCaption ; "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX cmp ax, 2 ; IDCANCEL jnz short loc_2F xor ax, ax 593
  • 618. CHAPTER 53. WINDOWS 16-BIT 53.4. EXAMPLE #4 push ax push ds mov ax, offset aYouPressedCanc ; "you pressed cancel" jmp short loc_49 loc_2F: cmp ax, 6 ; IDYES jnz short loc_3D xor ax, ax push ax push ds mov ax, offset aYouPressedYes ; "you pressed yes" jmp short loc_49 loc_3D: cmp ax, 7 ; IDNO jnz short loc_57 xor ax, ax push ax push ds mov ax, offset aYouPressedNo ; "you pressed no" loc_49: push ax push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax push ax call MESSAGEBOX loc_57: xor ax, ax pop bp retn 0Ah WinMain endp Somewhat extended example from the previous section. 53.4 Example #4 #include <windows.h> int PASCAL func1 (int a, int b, int c) { return a*b+c; }; long PASCAL func2 (long a, long b, long c) { return a*b+c; }; long PASCAL func3 (long a, long b, long c, int d) { return a*b+c-d; }; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { func1 (123, 456, 789); func2 (600000, 700000, 800000); func3 (600000, 700000, 800000, 123); return 0; }; func1 proc near c = word ptr 4 594
  • 619. CHAPTER 53. WINDOWS 16-BIT 53.4. EXAMPLE #4 b = word ptr 6 a = word ptr 8 push bp mov bp, sp mov ax, [bp+a] imul [bp+b] add ax, [bp+c] pop bp retn 6 func1 endp func2 proc near arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah arg_8 = word ptr 0Ch arg_A = word ptr 0Eh push bp mov bp, sp mov ax, [bp+arg_8] mov dx, [bp+arg_A] mov bx, [bp+arg_4] mov cx, [bp+arg_6] call sub_B2 ; long 32-bit multiplication add ax, [bp+arg_0] adc dx, [bp+arg_2] pop bp retn 12 func2 endp func3 proc near arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah arg_8 = word ptr 0Ch arg_A = word ptr 0Eh arg_C = word ptr 10h push bp mov bp, sp mov ax, [bp+arg_A] mov dx, [bp+arg_C] mov bx, [bp+arg_6] mov cx, [bp+arg_8] call sub_B2 ; long 32-bit multiplication mov cx, [bp+arg_2] add cx, ax mov bx, [bp+arg_4] adc bx, dx ; BX=high part, CX=low part mov ax, [bp+arg_0] cwd ; AX=low part d, DX=high part d sub cx, ax mov ax, cx sbb bx, dx mov dx, bx pop bp retn 14 func3 endp WinMain proc near push bp mov bp, sp mov ax, 123 push ax 595
  • 620. CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5 mov ax, 456 push ax mov ax, 789 push ax call func1 mov ax, 9 ; high part of 600000 push ax mov ax, 27C0h ; low part of 600000 push ax mov ax, 0Ah ; high part of 700000 push ax mov ax, 0AE60h ; low part of 700000 push ax mov ax, 0Ch ; high part of 800000 push ax mov ax, 3500h ; low part of 800000 push ax call func2 mov ax, 9 ; high part of 600000 push ax mov ax, 27C0h ; low part of 600000 push ax mov ax, 0Ah ; high part of 700000 push ax mov ax, 0AE60h ; low part of 700000 push ax mov ax, 0Ch ; high part of 800000 push ax mov ax, 3500h ; low part of 800000 push ax mov ax, 7Bh ; 123 push ax call func3 xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp 32-bit values (the long data type implies 32 bits, while int is 16-bit) in 16-bit code (both MS-DOS and Win16) are passed in pairs. It is just like when 64-bit values are used in a 32-bit environment ( 24 on page 403). sub_B2 here is a library function written by the compiler’s developers that does “long multiplication”, i.e., multiplies two 32-bit values. Other compiler functions that do the same are listed here: E on page 950, D on page 949. The ADD/ADC instruction pair is used for addition of compound values: ADD may set/clear the CF flag, and ADC uses it after. The SUB/SBB instruction pair is used for subtraction: SUB may set/clear the CF flag, SBB uses it after. 32-bit values are returned from functions in the DX:AX register pair. Constants are also passed in pairs in WinMain() here. The int-typed 123 constant is first converted according to its sign into a 32-bit value using the CWD instruction. 53.5 Example #5 #include <windows.h> int PASCAL string_compare (char *s1, char *s2) { while (1) { if (*s1!=*s2) return 0; if (*s1==0 || *s2==0) return 1; // end of string s1++; s2++; }; }; 596
  • 621. CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5 int PASCAL string_compare_far (char far *s1, char far *s2) { while (1) { if (*s1!=*s2) return 0; if (*s1==0 || *s2==0) return 1; // end of string s1++; s2++; }; }; void PASCAL remove_digits (char *s) { while (*s) { if (*s>='0' && *s<='9') *s='-'; s++; }; }; char str[]="hello 1234 world"; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { string_compare ("asd", "def"); string_compare_far ("asd", "def"); remove_digits (str); MessageBox (NULL, str, "caption", MB_YESNOCANCEL); return 0; }; string_compare proc near arg_0 = word ptr 4 arg_2 = word ptr 6 push bp mov bp, sp push si mov si, [bp+arg_0] mov bx, [bp+arg_2] loc_12: ; CODE XREF: string_compare+21j mov al, [bx] cmp al, [si] jz short loc_1C xor ax, ax jmp short loc_2B loc_1C: ; CODE XREF: string_compare+Ej test al, al jz short loc_22 jnz short loc_27 loc_22: ; CODE XREF: string_compare+16j mov ax, 1 jmp short loc_2B loc_27: ; CODE XREF: string_compare+18j inc bx inc si 597
  • 622. CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5 jmp short loc_12 loc_2B: ; CODE XREF: string_compare+12j ; string_compare+1Dj pop si pop bp retn 4 string_compare endp string_compare_far proc near ; CODE XREF: WinMain+18p arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah push bp mov bp, sp push si mov si, [bp+arg_0] mov bx, [bp+arg_4] loc_3A: ; CODE XREF: string_compare_far+35j mov es, [bp+arg_6] mov al, es:[bx] mov es, [bp+arg_2] cmp al, es:[si] jz short loc_4C xor ax, ax jmp short loc_67 loc_4C: ; CODE XREF: string_compare_far+16j mov es, [bp+arg_6] cmp byte ptr es:[bx], 0 jz short loc_5E mov es, [bp+arg_2] cmp byte ptr es:[si], 0 jnz short loc_63 loc_5E: ; CODE XREF: string_compare_far+23j mov ax, 1 jmp short loc_67 loc_63: ; CODE XREF: string_compare_far+2Cj inc bx inc si jmp short loc_3A loc_67: ; CODE XREF: string_compare_far+1Aj ; string_compare_far+31j pop si pop bp retn 8 string_compare_far endp remove_digits proc near ; CODE XREF: WinMain+1Fp arg_0 = word ptr 4 push bp mov bp, sp mov bx, [bp+arg_0] loc_72: ; CODE XREF: remove_digits+18j mov al, [bx] test al, al 598
  • 623. CHAPTER 53. WINDOWS 16-BIT 53.5. EXAMPLE #5 jz short loc_86 cmp al, 30h ; '0' jb short loc_83 cmp al, 39h ; '9' ja short loc_83 mov byte ptr [bx], 2Dh ; '-' loc_83: ; CODE XREF: remove_digits+Ej ; remove_digits+12j inc bx jmp short loc_72 loc_86: ; CODE XREF: remove_digits+Aj pop bp retn 2 remove_digits endp WinMain proc near ; CODE XREF: start+EDp push bp mov bp, sp mov ax, offset aAsd ; "asd" push ax mov ax, offset aDef ; "def" push ax call string_compare push ds mov ax, offset aAsd ; "asd" push ax push ds mov ax, offset aDef ; "def" push ax call string_compare_far mov ax, offset aHello1234World ; "hello 1234 world" push ax call remove_digits xor ax, ax push ax push ds mov ax, offset aHello1234World ; "hello 1234 world" push ax push ds mov ax, offset aCaption ; "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX xor ax, ax pop bp retn 0Ah WinMain endp Here we see a difference between the so-called “near” pointers and the “far” pointers: another weird artefact of segmented memory in 16-bit 8086. You can read more about it here: 94 on page 880. “near” pointers are those which point within the current data segment. Hence, the string_compare() function takes only two 16-bit pointers, and accesses the data from the segment that DS points to (Themov al, [bx] instruction actually works like mov al, ds:[bx]—DS is implicit here). “far” pointers are those which may point to data in another memory segment. Hence string_compare_far() takes the 16-bit pair as a pointer, loads the high part of it in the ES segment register and accesses the data through it (mov al, es:[bx]). “far” pointers are also used in my MessageBox() win16 example: 53.2 on page 592. Indeed, the Windows kernel is not aware which data segment to use when accessing text strings, so it need the complete information. The reason for this distinction is that a compact program may use just one 64kb data segment, so it doesn’t need to pass the high part of the address, which is always the same. A bigger program may use several 64kb data segments, so it needs to specify the segment of the data each time. It’s the same story for code segments. A compact program may have all executable code within one 64kb-segment, then all functions in it will be called using the CALL NEAR instruction, and the code flow will be returned using RETN. But if there are several code segments, then the address of the function is to be specified by a pair, it is to be called using the CALL FAR instruction, and the code flow is to be returned using RETF. 599
  • 624. CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6 This is what is set in the compiler by specifying “memory model”. The compilers targeting MS-DOS and Win16 have specific libraries for each memory model: they differ by pointer types for code and data. 53.6 Example #6 #include <windows.h> #include <time.h> #include <stdio.h> char strbuf[256]; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { struct tm *t; time_t unix_time; unix_time=time(NULL); t=localtime (&unix_time); sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t->⤦ tm_mday, t->tm_hour, t->tm_min, t->tm_sec); MessageBox (NULL, strbuf, "caption", MB_OK); return 0; }; WinMain proc near var_4 = word ptr -4 var_2 = word ptr -2 push bp mov bp, sp push ax push ax xor ax, ax call time_ mov [bp+var_4], ax ; low part of UNIX time mov [bp+var_2], dx ; high part of UNIX time lea ax, [bp+var_4] ; take a pointer of high part call localtime_ mov bx, ax ; t push word ptr [bx] ; second push word ptr [bx+2] ; minute push word ptr [bx+4] ; hour push word ptr [bx+6] ; day push word ptr [bx+8] ; month mov ax, [bx+0Ah] ; year add ax, 1900 push ax mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d" push ax mov ax, offset strbuf push ax call sprintf_ add sp, 10h xor ax, ax ; NULL push ax push ds mov ax, offset strbuf push ax 600
  • 625. CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6 push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax ; MB_OK push ax call MESSAGEBOX xor ax, ax mov sp, bp pop bp retn 0Ah WinMain endp UNIX time is a 32-bit value, so it is returned in the DX:AX register pair and stored in two local 16-bit variables. Then a pointer to the pair is passed to the localtime() function. The localtime() function has a struct tm allocated somewhere in the guts of the C library, so only a pointer to it is returned. By the way, this also implies that the function cannot be called again until its results are used. For the time() and localtime() functions, a Watcom calling convention is used here: the first four arguments are passed in the AX, DX, BX and CX, registers, and the rest arguments are via the stack. The functions using this convention are also marked by underscore at the end of their name. sprintf() does not use the PASCAL calling convention, nor the Watcom one, so the arguments are passed in the normal cdecl way ( 64.1 on page 663). 53.6.1 Global variables This is the same example, but now these variables are global: #include <windows.h> #include <time.h> #include <stdio.h> char strbuf[256]; struct tm *t; time_t unix_time; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { unix_time=time(NULL); t=localtime (&unix_time); sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t->⤦ tm_mday, t->tm_hour, t->tm_min, t->tm_sec); MessageBox (NULL, strbuf, "caption", MB_OK); return 0; }; unix_time_low dw 0 unix_time_high dw 0 t dw 0 WinMain proc near push bp mov bp, sp xor ax, ax call time_ mov unix_time_low, ax mov unix_time_high, dx mov ax, offset unix_time_low call localtime_ mov bx, ax mov t, ax ; will not be used in future... push word ptr [bx] ; seconds push word ptr [bx+2] ; minutes 601
  • 626. CHAPTER 53. WINDOWS 16-BIT 53.6. EXAMPLE #6 push word ptr [bx+4] ; hour push word ptr [bx+6] ; day push word ptr [bx+8] ; month mov ax, [bx+0Ah] ; year add ax, 1900 push ax mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d" push ax mov ax, offset strbuf push ax call sprintf_ add sp, 10h xor ax, ax ; NULL push ax push ds mov ax, offset strbuf push ax push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax ; MB_OK push ax call MESSAGEBOX xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp t is not to be used, but the compiler emitted the code which stores the value. Because it is not sure, maybe that value will eventually be used in some other module. 602
  • 628. CHAPTER 54. JAVA Chapter 54 Java 54.1 Introduction There are some well-known decompilers for Java (or JVM bytecode in general) 1 . The reason of this is because JVM-bytecode decompiling is somewhat easier than for lower level x86 code: • There are much more information about data types. • JVM memory model is much more rigorous and outlined. • Java compiler don’t do any optimization job (JVM JIT2 does at runtime), so bytecode in class files is usually pretty readable. When JVM bytecode knowledge may be useful? • Quick-and-dirty patching tasks of class files without need to recompile decompiler’s results. • Analysing obfuscated code. • Build your own obfuscator. • Build compiler codegenerator (back-end) targetting JVM (like Scala, Clojure, etc 3 ). Let’s start with simple pieces of code. JDK 1.7 is used everywhere, unless mentioned otherwise. This command to decompile class files was used everywhere : javap -c -verbose This book was used by me while preparing all examples : [Jav13]. 54.2 Returning a value Probably the simplest Java function is one which returns some value. Oh, and we must keep in mind that there are no “free” functions in Java in common sense, they are “methods”. Each method is related to some class, so it’s not possible to define method outside of a class. But I’ll also call them “functions” anyway, because I used to. public class ret { public static int main(String[] args) { return 0; } } I’ll compile it: javac ret.java …and decompile it using standard Java utility: javap -c -verbose ret.class And what I’ve got: 1For example, JAD: http://varaneckas.com/jad/ 2Just-in-time compilation 3Full list: http://en.wikipedia.org/wiki/List_of_JVM_languages 604
  • 629. CHAPTER 54. JAVA 54.2. RETURNING A VALUE Listing 54.1: JDK 1.7 (excerpt) public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iconst_0 1: ireturn Java developers decide that 0 is one of the busiest constants in programming, so there are separate short one-byte iconst_0 instruction which pushes 0 4 . There are also iconst_1 (which pushes 1), iconst_2, etc, up to iconst_5. There are also iconst_m1 which pushes -1. Stack is used in JVM for data passing into functions to be called and also returning values. So iconst_0 pushed 0 into stack. ireturn returns integer value (i in name mean integer) from the TOS5 . Let’s rewrite our example slightly, now we return 1234: public class ret { public static int main(String[] args) { return 1234; } } …we got: Listing 54.2: JDK 1.7 (excerpt) public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: sipush 1234 3: ireturn sipush (short integer) pushes 1234 value into stack. short in name implies a 16-bit value is to be pushed. 1234 number is indeed well fit in 16-bit value. What about larger values? public class ret { public static int main(String[] args) { return 12345678; } } Listing 54.3: Constant pool ... #2 = Integer 12345678 ... public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: ldc #2 // int 12345678 2: ireturn It’s not possible to encode a 32-bit number in a JVM instruction opcode, developers didn’t left such possibility. So 32-bit number 12345678 is stored in so called “constant pool” which is, let’s say, library of most used constants (including strings, objects, etc). This way of passing constants is not unique to JVM. MIPS, ARM and other RISC CPUs also can’t encode 32-bit numbers in 32-bit opcode, so RISC CPU code (including MIPS and ARM) has to construct values in several steps, or to keep them in data segment: 28.3 on page 445, 29.1 on page 449. MIPS code is also traditionally has constant pool, named “literal pool”, these are segments called “.lit4” (for 32-bit single precision float point number constants storage) and “.lit8” (for 64-bit double precision float point number constants storage). Let’s also try other data types! Boolean: 4Just like in MIPS, where a separate register for zero constant exists : 3.5.2 on page 17. 5Top Of Stack 605
  • 630. CHAPTER 54. JAVA 54.2. RETURNING A VALUE public class ret { public static boolean main(String[] args) { return true; } } public static boolean main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iconst_1 1: ireturn This JVM bytecode is no different from one returning integer 1. 32-bit data slots in stack are also used here for boolean values, like in C/C++. But one could not use returned boolean value as integer or vice versa — type information is stored in a class file and checked at runtime. The same story about 16-bit short: public class ret { public static short main(String[] args) { return 1234; } } public static short main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: sipush 1234 3: ireturn …and char! public class ret { public static char main(String[] args) { return 'A'; } } public static char main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: bipush 65 2: ireturn bipush mean “push byte”. Needless to say that char in Java is 16-bit UTF-16 character, and it’s equivalent to short, but ASCII code of “A” character is 65, and it’s possible to use instruction for passing byte into stack. Let’s also try byte: public class retc { public static byte main(String[] args) { return 123; } } public static byte main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: bipush 123 2: ireturn 606
  • 631. CHAPTER 54. JAVA 54.2. RETURNING A VALUE One may ask, why to bother with 16-bit short date type which is internally works as 32-bit integer? Why use char data type if it is the same as short data type? The answer is simple: for data type control and source code readability. char may essentially be the same as short but we quickly grasp that it’s placeholder for UTF-16 character, and not for some other integer value. When using short we may show to everyone that a variable range is limited by 16 bits. It’s a very good idea to use boolean type where it needs to, instead of C-style int for the same purpose. There are also 64-bit integer data type in Java: public class ret3 { public static long main(String[] args) { return 1234567890123456789L; } } Listing 54.4: Constant pool ... #2 = Long 1234567890123456789l ... public static long main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: ldc2_w #2 // long 1234567890123456789l 3: lreturn The 64-bit number is also stored in constant pool, ldc2_w loads it and lreturn (long return) returns it. ldc2_w instruction is also used to load double precision floating point numbers (which also occupies 64 bits) from constant pool: public class ret { public static double main(String[] args) { return 123.456d; } } Listing 54.5: Constant pool ... #2 = Double 123.456d ... public static double main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: ldc2_w #2 // double 123.456d 3: dreturn dreturn stands for “return double”. And finally, single precision floating point number: public class ret { public static float main(String[] args) { return 123.456f; } } Listing 54.6: Constant pool ... #2 = Float 123.456f ... 607
  • 632. CHAPTER 54. JAVA 54.3. SIMPLE CALCULATING FUNCTIONS public static float main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: ldc #2 // float 123.456f 2: freturn ldc instruction used here is the same as used for 32-bit integer numbers loading from constant pool. freturn stands for “return float”. Now what about function returning nothing? public class ret { public static void main(String[] args) { return; } } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=0, locals=1, args_size=1 0: return This implies, return instruction is used to return control without returning actual value. Knowing all this, it’s very easy to deduct function (or method) returning type from the last instruction. 54.3 Simple calculating functions Let’s continue with simple calculating functions. public class calc { public static int half(int a) { return a/2; } } This is the case when iconst_2 instruction is used: public static int half(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: iload_0 1: iconst_2 2: idiv 3: ireturn iload_0 takes zeroth function argument and pushes it to stack. iconst_2 pushes 2 into stack. After these two instructions execution, this is how stack looks like: +---+ TOS ->| 2 | +---+ | a | +---+ idiv just takes two values at the TOS, divides one by another and leave result at TOS: +--------+ TOS ->| result | +--------+ ireturn takes it and returns. Let’s proceed to double precision floating point numbers: 608
  • 633. CHAPTER 54. JAVA 54.3. SIMPLE CALCULATING FUNCTIONS public class calc { public static double half_double(double a) { return a/2.0; } } Listing 54.7: Constant pool ... #2 = Double 2.0d ... public static double half_double(double); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=2, args_size=1 0: dload_0 1: ldc2_w #2 // double 2.0d 4: ddiv 5: dreturn It’s the very same, but ldc2_w instruction is used to load constant of 2.0 from constant pool. Also, all other three instructions has d prefix, meaning they work with double data type values. Let’s now use two arguments function: public class calc { public static int sum(int a, int b) { return a+b; } } public static int sum(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=2 0: iload_0 1: iload_1 2: iadd 3: ireturn iload_0 loads first function argument (a), iload_2 — second (b). Here is a stack after both instruction executed: +---+ TOS ->| b | +---+ | a | +---+ iadd adds two values and leave result at TOS: +--------+ TOS ->| result | +--------+ Let’s extend this example to long data type: public static long lsum(long a, long b) { return a+b; } …we got: public static long lsum(long, long); flags: ACC_PUBLIC, ACC_STATIC Code: 609
  • 634. CHAPTER 54. JAVA 54.4. JVM MEMORY MODEL stack=4, locals=4, args_size=2 0: lload_0 1: lload_2 2: ladd 3: lreturn The second lload instruction takes second argument from 2nd slot. That’s because 64-bit long value occupies exactly two 32-bit slots. Slightly more complex example: public class calc { public static int mult_add(int a, int b, int c) { return a*b+c; } } public static int mult_add(int, int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=3, args_size=3 0: iload_0 1: iload_1 2: imul 3: iload_2 4: iadd 5: ireturn First step is multiplication. Product is left at the TOS: +---------+ TOS ->| product | +---------+ iload_2 loads third argument (c) into stack: +---------+ TOS ->| c | +---------+ | product | +---------+ Now iadd instruction can add two values. 54.4 JVM memory model x86 and other low-level environments uses stack for arguments passing and as local variables storage. JVM is slightly different. It has: • Local variable array (LVA6 ). It is used as storage for incoming function arguments and local variables. Instructions like iload_0 loads values from it. istore stores values to it. First, function arguments are came: starting at 0 or at 1 (if zeroth argument is occupied by this pointer). Then local variables are allocated. Each slot has size of 32-bit. Hence, values of long and double data types occupy two slots. • Operand stack (or just “stack”). It’s used for computations and passing arguments while calling other functions. Unlike low-level environments like x86, it’s not possible to access the stack without using instructions which explicitely pushes or pops values to/from it. • Heap. It is used as storage for objects and arrays. These 3 areas are isolated from each other. 6(Java) Local Variable Array 610
  • 635. CHAPTER 54. JAVA 54.5. SIMPLE FUNCTION CALLING 54.5 Simple function calling Math.random() returns a pseudorandom number in range of [0.0 …1.0), but let’s say, by some reason, we need to devise a function returning number in range of [0.0 …0.5): public class HalfRandom { public static double f() { return Math.random()/2; } } Listing 54.8: Constant pool ... #2 = Methodref #18.#19 // java/lang/Math.random:()D #3 = Double 2.0d ... #12 = Utf8 ()D ... #18 = Class #22 // java/lang/Math #19 = NameAndType #23:#12 // random:()D #22 = Utf8 java/lang/Math #23 = Utf8 random public static double f(); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=0, args_size=0 0: invokestatic #2 // Method java/lang/Math.random:()D 3: ldc2_w #3 // double 2.0d 6: ddiv 7: dreturn invokestatic calls for th