SlideShare a Scribd company logo
Linux Binary Exploitation
C++ Exploitation
angelboy@chroot.org
1
Outline
• Name Mangling
• Virtual function table
• Vtable Hijacking
• Vector & String
• New & delete
• Copy constructor & assignment operator
2
Outline
• Name Mangling
• Virtual function table
• Vtable Hijacking
• Vector & String
• New & delete
• Copy constructor & assignment operator
3
Name Mangling
• C++ 為了了 Overloading 時,可以讓 compiler 和
linker 可以辨別出相同 function 名稱,參參數不同的
function 引⽤用的機制
• 使 programer 在不同的 namespace 底下可以有
著多個相同名稱的 function
4
Name Mangling
• ⽽而在 compiler 和 linker 處理理 symbol 時,就會使
⽤用該機制讓每個 function 名對應到⼀一個修飾過後
的名稱
• C++ 中全域變數和靜態變數也有相同的機制
5
Name Mangling
• 在 gdb 中可以使⽤用下列列指令讓 function 好看⼀一點
• set print asm-demangle on
6
Outline
• Name Mangling
• Virtual function table
• Vector & String
• New & delete
• Copy constructor & assignment operator
7
Virtual function table
• Virtual function is a key mechanism to support
polymorphism in C++
• For each class with virtual functions, depending
on the class inheritance hierarchy, the compiler
will create one or more associated virtual
function table
8
Virtual function table
9
writable section
(heap)
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
compiler generates
the table for all class
Virtual function table
10
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
new a Person and
a Stu object
Virtual function table
11
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
ddaa->speak()
Virtual function table
12
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
vfptr == *ddaa
取 vfptr
Virtual function table
13
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
call *vfptr
(Person::speak(ddaa))
Virtual function table
14
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
meh->speak()
Virtual function table
15
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
vfptr == *meh
取 vfptr
Virtual function table
16
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
call *vfptr
(Stu::speak(meh))
Virtual function table
17
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
meh->pwn()
Virtual function table
18
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
vfptr == *meh
取 vfptr
Virtual function table
19
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
call *(vfptr+0x10)
(Stu::pwn(meh))
Vtable Hijacking
• Need other vulnerabilities
• Use-after-free, Heap overflow ….
• Force the table and Hijack the vfptr
• Because the vfptr is writable
20
Vtable Hijacking
21
writable section
(heap)
ddaa
meh
vfptr
a
vfptr
b
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
Vtable Hijacking
22
writable section
(heap)
meh
&shellcode
0xddaa
ddaa
0xdead
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
heap overflow
forces a vtabe in ddaa
and hijack the vfptr of meh
ddaa
Vtable Hijacking
23
writable section
(heap)
meh
&shellcode
0xddaa
ddaa
0xdead
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
meh->speak()
ddaa
Vtable Hijacking
24
writable section
(heap)
meh
&shellcode
0xddaa
ddaa
0xdead
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
vfptr = *meh
取 vfptr
ddaa
Vtable Hijacking
25
writable section
(heap)
meh
&shellcode
0xddaa
ddaa
0xdead
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
ddaa
call *(vfptr)
(call shellcode(meh))
Vtable Hijacking
26
writable section
(heap)
meh
&shellcode
0xddaa
ddaa
0xdead
0xbeef
typeinfo
Person::speak()
Person::phd()
typeinfo
Stu::speak()
Person::phd()
Stu::pwn()
read-only section
vtable for Person
vtable for Stu
ddaa
call *(vfptr)
(call shellcode(meh))
PWN !!
但通常會有 DEP/NX 保護,可能要跳 libc 中的 one-gadget
或是其他可利利⽤用的地⽅方
Outline
• Name Mangling
• Virtual function table
• Vector & String
• New & delete
• Copy constructor & assignment operator
27
Vector & String
• Vector
• A dynamic array
• 分配在 heap 段
• 比⼀一般 c 中的陣列列更更有彈性,當空間不夠⼤大時
會重新兩兩倍⼤大的的⼩小來來放置新的 vector ,再把
原本的空間還給系統
28
Vector & String
• Vector
• member
• _M_start : vector 起始位置
• vector::begin()
• _M_finish : vector 結尾位置
• vector::end()
• _M_end_of_storage :容器最後位置
• if _M_finish == _M_end_of_storage in push_back
• It will alloca a new space for the vector
• 以這個來來判斷空間是否⾜足夠放元素
29
Vector & String
• Vector
• member function
• push_back : 在 vector 最後加入新元素
• pop_back : 移除 vector 最後⼀一個元素
• insert :插入元素到 vector 第 n 個位置
• erase :移除 vector 中第 n 個元素
• ……
30
Vector & String
• Vector layout
31
vector <string> vec
_M_start
_M_finish
_M_end_of_storage
Vector & String
• Vector layout
32
vec.push_back(“meh”)
_M_start
_M_finish
_M_end_of_storage
address of meh string
Vector & String
• Vector layout
33
vec.push_back(“meheap”)
_M_start
_M_finish
_M_end_of_storage
address of meh string
因為 _M_finish == _ M_end_of_storage
所以會先從新 new ⼀一塊新的 vector
並把舊的值複製過去
再將藍藍⾊色那塊 delete 掉
Vector & String
• Vector layout
34
vec.push_back(“meheap”)
_M_start
_M_finish
_M_end_of_storage
address of meh string
address of meh string
address of meheap string
Vector & String
• Vector layout
35
vec.push_back(“meh.py”)
_M_start
_M_finish
_M_end_of_storage
address of meh string
address of meh string
address of meheap string
address of meh string
address of meheap string
address of meh.py string
Vector & String
• Vector layout
36
vec.push_back(“pwn”)
_M_start
_M_finish
_M_end_of_storage
address of meh string
address of meh string
address of meheap string
address of meh string
address of meheap string
address of meh.py string
address of pwn string
Vector & String
• Vector layout
37
vec.pop_back()
_M_start
_M_finish
_M_end_of_storage
address of meh string
address of meh string
address of meheap string
address of meh string
address of meheap string
address of meh.py string
address of pwn string
call destructor of pwn string
Vector & String
• Vector layout
38
vec.pop_back()
_M_start
_M_finish
_M_end_of_storage
address of meh string
address of meh string
address of meheap string
address of meh string
address of meheap string
address of meh.py string
address of pwn string
Vector & String
• String
• a dynamic char array
• 比起以往的字串串陣列列更更加安全,全部動態配置記憶體空間,
減少⼀一般 buffer overflow 的發⽣生
• 在給定 input 時,會不斷重新分配空間給 user 直到結束後,
就會回傳適當的⼤大⼩小給 user
• 有許多種實作⽅方式,這邊介紹最常⾒見見的⼀一種
• g++ < 5
39
Vector & String
• String
• member
• size :字串串的長度
• Capacity : 該 string 空間的容量量
• reference count : 引⽤用計數
• 只要有其他元素引⽤用該字串串就會增加
• 如果其他元素不引⽤用了了,也會減少
• 當 reference == 0 時就會,將空間 delete 掉
• value : 存放字串串內容
40
Vector & String
• String
• member function
• length() : string ⼤大⼩小
• capacity() : ⽬目前 string 空間容量量
• c_str() : Get C string equivalent
• ……
41
Vector & String
• String layout
42
str
string str
cin >> str
Vector & String
• String layout
43
str
string str
cin >> str
input : aa
size = 2
capacity = 2
refcnt = 0
aa
Vector & String
• String layout
44
str
string str
cin >> str
input : aaa
size = 2
capacity = 2
refcnt = -1
aa
size = 3
capacity = 4
refcnt = 0
aaa
Vector & String
• String layout
45
str
string str
cin >> str
input : aaaaa
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 5
capacity = 8
refcnt = 0
aaaaa
Vector & String
• String layout
46
str
string str
cin >> str
input : a*125
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = 0
a*125
依此類推 capacity 會
不斷以⼆二的指數倍增長
直到 input 結束 .
.
.
Vector & String
• String layout
47
str
vector<string> vec
vec.push_back(str)
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = 1
a*125
_M_start
_M_finish
_M_end_of_storage
str
.
.
.
Vector & String
• String layout
48
str
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = 2
a*125
_M_start
_M_finish
_M_end_of_storage
str
str
str
vector<string> vec
vec.push_back(str)
vec.push_back(str)
.
.
.
Vector & String
• String layout
49
str
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = 1
a*125
_M_start
_M_finish
_M_end_of_storage
str
str
str
vec.pop_back()
這邊會 call str destuctor
但不會 delete 空間
.
.
.
Vector & String
• String layout
50
str
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = 0
a*125
_M_start
_M_finish
_M_end_of_storage
str
str
str
vec.pop_back()
這邊會 call str destuctor
但不會 delete 空間
.
.
.
Vector & String
• String layout
51
size = 2
capacity = 2
refcnt = -1
aa
size = 4
capacity = 4
refcnt = -1
aaaa
size = 8
capacity = 8
refcnt = -1
aaaaaaaa
size = 125
capacity = 128
refcnt = -1
a*125
_M_start
_M_finish
_M_end_of_storage
str
str
str
end of scope
這邊會 call str destuctor
因 refcnt < 0
會做 delete
.
.
.
Vector & String
• String
• g++ > 5 之後取消了了 Copy-on-Write 機制
• 所以少掉了了 reference count 這個欄欄位
• 在 data length
• <= 15 時會⽤用 local buffer
• > 15 時則會在 heap allocate 空間給 data 使⽤用
52
Vector & String
• String
• data pointer : 指向 data 位置
• size : 分配出去 string 的長度
• union
• local buffer : 在 size <= 15 時會直接把這欄欄位拿來來存
data
• allocated capacity : size > 15 時會拿來來紀錄 capcity
53
Vector & String
• String
• size < 15
54
data pointer
size = 15
aaaaaaaa
aaaaaaaa
Vector & String
• String
• size > 15
55
data pointer
size = 17
capacity = 30
0
aaaaaaaa
aaaaaaaa
a
heap
Outline
• Name Mangling
• Virtual function table
• Vector & String
• New & delete
• Copy constructor & assignment operator
56
New & Delete
• 在 c++ 預設的情況下 ,new/delete 的最底層實作依舊是靠
malloc/free 去處理理記憶體管理理
• 在 c++ 中,記憶體配置池稱為 free store ,但預設情況下
free store 位置是在 heap
• 不過事實上 new/delete 是可以 overloading 的,也就是⾃自⾏行行去
做記憶體管理理,另外最⼤大差別就是new/delete 實際上會去 call
constructor/destructor ⽽而 malloc/free 只做單純的記憶體配置
• 因此盡量量不要讓 malloc/free 與 new/delete 混⽤用,不然可能會
出現⼀一些不可預期的狀狀況
57
New & Delete
• new ⼤大致上流程
• operator new
• 與 malloc 類似,單純配置記憶體空間,但配置失敗會進入 exception
⽽而 malloc 則是返回 null ,有點像在 malloc 上⼀一層 wrapper
• constructor
• delete ⼤大致上流程
• destructor
• operator delete
• 與 free 類似,釋放⼀一塊記憶體空間,有點像是在 free 上⼀一層 wrapper
58
New & Delete
• 因此 new/delete 及 operator new / operator
delete 也應該成對配對
• 記憶體函式配對
59
配置函式 解除函式
new delete
new [] delete []
operator new operator delete
operator new[] operator delete[]
malloc free
Outline
• Name Mangling
• Virtual function table
• Vector & String
• New & delete
• Copy constructor & assignment operator
60
What’s wrong in this code
61
What’s wrong in this code
62
Copy constructor &
assignment operator
• shallow copy
• 只做單純 pointer (value) 的複製,複製完後內
容與原本的相同
• deep copy
• 會在配置更更多記憶體空間,包含 pointer 所指向
的內容也都⼀一併複製
63
Copy constructor &
assignment operator
• shallow copy
64
name
orange
StuA
Copy constructor &
assignment operator
• shallow copy
65
name
orange
name
StuA
StuB
Copy constructor &
assignment operator
• deep copy
66
name
orange
StuA
Copy constructor &
assignment operator
• deep copy
67
name
orange
name
StuA
StuB orange
Copy constructor &
assignment operator
• Copy constructor
• c++ 在進⾏行行複製 object 會使⽤用 copy constructor
• 通常 class 的 member 有指標時,就需要⾃自⾏行行
去實作
• 若若未特別定義則會使⽤用 default copy constructor
• 只做 shallow copy
68
Copy constructor &
assignment operator
• Assignment operator
• c++ 在進⾏行行 “=“ 這個 operator 時 object 會使⽤用
assignment operator 這個 function 去 assign object 的
值
• 通常 class 的 member 有指標時,就需要⾃自⾏行行去實作
• 若若未特別定義則會使⽤用 default assignment operator
• 只做 shallow copy
69
Copy constructor &
assignment operator
• 何時會使⽤用 copy constructor
• func(Stu stu)
• return stu
• vector 等 STL 容器
• ….
70
Copy constructor &
assignment operator
• 何時會使⽤用 assignment operator
• stuA = stuB
• vector 等 STL 容器
• e.g. vector.erase()
• …
71
Copy constructor &
assignment operator
72
call constructor
id
name
vector
Copy constructor &
assignment operator
73
new char [str.length() + 1]
id = 1337
name orange
vector
Copy constructor &
assignment operator
74
push_back(student)
id = 1337
name orange
vector
id = 1337
name copy the value
to vector
using
shadow copy
Copy constructor &
assignment operator
75
~Stu()
id = 1337
name orange
vector
id = 1337
name 因 student 的
life time 結束
所以
call destructor
Copy constructor &
assignment operator
76
delete [] name
id = 1337
name orange
vector
id = 1337
name
Copy constructor &
assignment operator
77
~vector()
id = 1337
name orange
vector
id = 1337
name 因 stulist 的
life time 結束
所以
call destructor
Copy constructor &
assignment operator
78
~Stu()
id = 1337
name orange
vector
id = 1337
name vector 會去
依次去呼叫
內容的
destructor
Copy constructor &
assignment operator
79
delete [] name
id = 1337
name orange
vector
id = 1337
name
Copy constructor &
assignment operator
80
delete [] name
id = 1337
name orange
vector
id = 1337
name
double free
Copy constructor &
assignment operator
• 總結
• 基本上 c++ 在只要做任何複製的動作時通常都
會去使⽤用 copy constructor 或者是 assignment
operator
• 所以基本上物件只要有 pointer 都盡量量養成習慣
去定義 copy constructor 跟 assignment
opeator
81
Lab 15
• zoo
82
Q & A
Ad

More Related Content

What's hot (20)

ROP 輕鬆談
ROP 輕鬆談ROP 輕鬆談
ROP 輕鬆談
hackstuff
 
Linux Binary Exploitation - Stack buffer overflow
Linux Binary Exploitation - Stack buffer overflowLinux Binary Exploitation - Stack buffer overflow
Linux Binary Exploitation - Stack buffer overflow
Angel Boy
 
Linux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledgeLinux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledge
Angel Boy
 
Advanced heap exploitaion
Advanced heap exploitaionAdvanced heap exploitaion
Advanced heap exploitaion
Angel Boy
 
Sigreturn Oriented Programming
Sigreturn Oriented ProgrammingSigreturn Oriented Programming
Sigreturn Oriented Programming
Angel Boy
 
Linux Binary Exploitation - Heap Exploitation
Linux Binary Exploitation - Heap Exploitation Linux Binary Exploitation - Heap Exploitation
Linux Binary Exploitation - Heap Exploitation
Angel Boy
 
Return to dlresolve
Return to dlresolveReturn to dlresolve
Return to dlresolve
Angel Boy
 
台科逆向簡報
台科逆向簡報台科逆向簡報
台科逆向簡報
耀德 蔡
 
TDOH x 台科 pwn課程
TDOH x 台科 pwn課程TDOH x 台科 pwn課程
TDOH x 台科 pwn課程
Weber Tsai
 
Linux Binary Exploitation - Return-oritend Programing
Linux Binary Exploitation - Return-oritend ProgramingLinux Binary Exploitation - Return-oritend Programing
Linux Binary Exploitation - Return-oritend Programing
Angel Boy
 
twlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsotwlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdso
Viller Hsiao
 
Physical Memory Models.pdf
Physical Memory Models.pdfPhysical Memory Models.pdf
Physical Memory Models.pdf
Adrian Huang
 
MacOS memory allocator (libmalloc) Exploitation - Chinese Version
MacOS memory allocator (libmalloc) Exploitation - Chinese VersionMacOS memory allocator (libmalloc) Exploitation - Chinese Version
MacOS memory allocator (libmalloc) Exploitation - Chinese Version
Angel Boy
 
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
Adrian Huang
 
Memory Mapping Implementation (mmap) in Linux Kernel
Memory Mapping Implementation (mmap) in Linux KernelMemory Mapping Implementation (mmap) in Linux Kernel
Memory Mapping Implementation (mmap) in Linux Kernel
Adrian Huang
 
Glibc malloc internal
Glibc malloc internalGlibc malloc internal
Glibc malloc internal
Motohiro KOSAKI
 
semaphore & mutex.pdf
semaphore & mutex.pdfsemaphore & mutex.pdf
semaphore & mutex.pdf
Adrian Huang
 
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
CODE BLUE
 
Slab Allocator in Linux Kernel
Slab Allocator in Linux KernelSlab Allocator in Linux Kernel
Slab Allocator in Linux Kernel
Adrian Huang
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in Linux
Adrian Huang
 
ROP 輕鬆談
ROP 輕鬆談ROP 輕鬆談
ROP 輕鬆談
hackstuff
 
Linux Binary Exploitation - Stack buffer overflow
Linux Binary Exploitation - Stack buffer overflowLinux Binary Exploitation - Stack buffer overflow
Linux Binary Exploitation - Stack buffer overflow
Angel Boy
 
Linux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledgeLinux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledge
Angel Boy
 
Advanced heap exploitaion
Advanced heap exploitaionAdvanced heap exploitaion
Advanced heap exploitaion
Angel Boy
 
Sigreturn Oriented Programming
Sigreturn Oriented ProgrammingSigreturn Oriented Programming
Sigreturn Oriented Programming
Angel Boy
 
Linux Binary Exploitation - Heap Exploitation
Linux Binary Exploitation - Heap Exploitation Linux Binary Exploitation - Heap Exploitation
Linux Binary Exploitation - Heap Exploitation
Angel Boy
 
Return to dlresolve
Return to dlresolveReturn to dlresolve
Return to dlresolve
Angel Boy
 
台科逆向簡報
台科逆向簡報台科逆向簡報
台科逆向簡報
耀德 蔡
 
TDOH x 台科 pwn課程
TDOH x 台科 pwn課程TDOH x 台科 pwn課程
TDOH x 台科 pwn課程
Weber Tsai
 
Linux Binary Exploitation - Return-oritend Programing
Linux Binary Exploitation - Return-oritend ProgramingLinux Binary Exploitation - Return-oritend Programing
Linux Binary Exploitation - Return-oritend Programing
Angel Boy
 
twlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsotwlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdso
Viller Hsiao
 
Physical Memory Models.pdf
Physical Memory Models.pdfPhysical Memory Models.pdf
Physical Memory Models.pdf
Adrian Huang
 
MacOS memory allocator (libmalloc) Exploitation - Chinese Version
MacOS memory allocator (libmalloc) Exploitation - Chinese VersionMacOS memory allocator (libmalloc) Exploitation - Chinese Version
MacOS memory allocator (libmalloc) Exploitation - Chinese Version
Angel Boy
 
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
qemu + gdb: The efficient way to understand/debug Linux kernel code/data stru...
Adrian Huang
 
Memory Mapping Implementation (mmap) in Linux Kernel
Memory Mapping Implementation (mmap) in Linux KernelMemory Mapping Implementation (mmap) in Linux Kernel
Memory Mapping Implementation (mmap) in Linux Kernel
Adrian Huang
 
semaphore & mutex.pdf
semaphore & mutex.pdfsemaphore & mutex.pdf
semaphore & mutex.pdf
Adrian Huang
 
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
CODE BLUE
 
Slab Allocator in Linux Kernel
Slab Allocator in Linux KernelSlab Allocator in Linux Kernel
Slab Allocator in Linux Kernel
Adrian Huang
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in Linux
Adrian Huang
 

Similar to Pwning in c++ (basic) (20)

Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
corehard_by
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
Anton Bikineev
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PVS-Studio
 
lldb – Debugger auf Abwegen
lldb – Debugger auf Abwegenlldb – Debugger auf Abwegen
lldb – Debugger auf Abwegen
inovex GmbH
 
Format String Vulnerability
Format String VulnerabilityFormat String Vulnerability
Format String Vulnerability
Jian-Yu Li
 
Python
PythonPython
Python
Wei-Bo Chen
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
Web-Scale Graph Analytics with Apache® Spark™
Web-Scale Graph Analytics with Apache® Spark™Web-Scale Graph Analytics with Apache® Spark™
Web-Scale Graph Analytics with Apache® Spark™
Databricks
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable types
arvidn
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in Python
OSCON Byrum
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in space
Faizan Shabbir
 
R and cpp
R and cppR and cpp
R and cpp
Romain Francois
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
Satish Gummadi
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
Sergey Platonov
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
JVM performance options. How it works
JVM performance options. How it worksJVM performance options. How it works
JVM performance options. How it works
Dmitriy Dumanskiy
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
corehard_by
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
Anton Bikineev
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PVS-Studio
 
lldb – Debugger auf Abwegen
lldb – Debugger auf Abwegenlldb – Debugger auf Abwegen
lldb – Debugger auf Abwegen
inovex GmbH
 
Format String Vulnerability
Format String VulnerabilityFormat String Vulnerability
Format String Vulnerability
Jian-Yu Li
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
Web-Scale Graph Analytics with Apache® Spark™
Web-Scale Graph Analytics with Apache® Spark™Web-Scale Graph Analytics with Apache® Spark™
Web-Scale Graph Analytics with Apache® Spark™
Databricks
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable types
arvidn
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in Python
OSCON Byrum
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in space
Faizan Shabbir
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
Sergey Platonov
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
JVM performance options. How it works
JVM performance options. How it worksJVM performance options. How it works
JVM performance options. How it works
Dmitriy Dumanskiy
 
Ad

Recently uploaded (20)

Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Ad

Pwning in c++ (basic)

  • 1. Linux Binary Exploitation C++ Exploitation angelboy@chroot.org 1
  • 2. Outline • Name Mangling • Virtual function table • Vtable Hijacking • Vector & String • New & delete • Copy constructor & assignment operator 2
  • 3. Outline • Name Mangling • Virtual function table • Vtable Hijacking • Vector & String • New & delete • Copy constructor & assignment operator 3
  • 4. Name Mangling • C++ 為了了 Overloading 時,可以讓 compiler 和 linker 可以辨別出相同 function 名稱,參參數不同的 function 引⽤用的機制 • 使 programer 在不同的 namespace 底下可以有 著多個相同名稱的 function 4
  • 5. Name Mangling • ⽽而在 compiler 和 linker 處理理 symbol 時,就會使 ⽤用該機制讓每個 function 名對應到⼀一個修飾過後 的名稱 • C++ 中全域變數和靜態變數也有相同的機制 5
  • 6. Name Mangling • 在 gdb 中可以使⽤用下列列指令讓 function 好看⼀一點 • set print asm-demangle on 6
  • 7. Outline • Name Mangling • Virtual function table • Vector & String • New & delete • Copy constructor & assignment operator 7
  • 8. Virtual function table • Virtual function is a key mechanism to support polymorphism in C++ • For each class with virtual functions, depending on the class inheritance hierarchy, the compiler will create one or more associated virtual function table 8
  • 9. Virtual function table 9 writable section (heap) typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu compiler generates the table for all class
  • 10. Virtual function table 10 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu new a Person and a Stu object
  • 11. Virtual function table 11 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu ddaa->speak()
  • 12. Virtual function table 12 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu vfptr == *ddaa 取 vfptr
  • 13. Virtual function table 13 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu call *vfptr (Person::speak(ddaa))
  • 14. Virtual function table 14 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu meh->speak()
  • 15. Virtual function table 15 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu vfptr == *meh 取 vfptr
  • 16. Virtual function table 16 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu call *vfptr (Stu::speak(meh))
  • 17. Virtual function table 17 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu meh->pwn()
  • 18. Virtual function table 18 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu vfptr == *meh 取 vfptr
  • 19. Virtual function table 19 writable section (heap) ddaa meh vfptr a vfptr b typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu call *(vfptr+0x10) (Stu::pwn(meh))
  • 20. Vtable Hijacking • Need other vulnerabilities • Use-after-free, Heap overflow …. • Force the table and Hijack the vfptr • Because the vfptr is writable 20
  • 22. Vtable Hijacking 22 writable section (heap) meh &shellcode 0xddaa ddaa 0xdead typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu heap overflow forces a vtabe in ddaa and hijack the vfptr of meh ddaa
  • 26. Vtable Hijacking 26 writable section (heap) meh &shellcode 0xddaa ddaa 0xdead 0xbeef typeinfo Person::speak() Person::phd() typeinfo Stu::speak() Person::phd() Stu::pwn() read-only section vtable for Person vtable for Stu ddaa call *(vfptr) (call shellcode(meh)) PWN !! 但通常會有 DEP/NX 保護,可能要跳 libc 中的 one-gadget 或是其他可利利⽤用的地⽅方
  • 27. Outline • Name Mangling • Virtual function table • Vector & String • New & delete • Copy constructor & assignment operator 27
  • 28. Vector & String • Vector • A dynamic array • 分配在 heap 段 • 比⼀一般 c 中的陣列列更更有彈性,當空間不夠⼤大時 會重新兩兩倍⼤大的的⼩小來來放置新的 vector ,再把 原本的空間還給系統 28
  • 29. Vector & String • Vector • member • _M_start : vector 起始位置 • vector::begin() • _M_finish : vector 結尾位置 • vector::end() • _M_end_of_storage :容器最後位置 • if _M_finish == _M_end_of_storage in push_back • It will alloca a new space for the vector • 以這個來來判斷空間是否⾜足夠放元素 29
  • 30. Vector & String • Vector • member function • push_back : 在 vector 最後加入新元素 • pop_back : 移除 vector 最後⼀一個元素 • insert :插入元素到 vector 第 n 個位置 • erase :移除 vector 中第 n 個元素 • …… 30
  • 31. Vector & String • Vector layout 31 vector <string> vec _M_start _M_finish _M_end_of_storage
  • 32. Vector & String • Vector layout 32 vec.push_back(“meh”) _M_start _M_finish _M_end_of_storage address of meh string
  • 33. Vector & String • Vector layout 33 vec.push_back(“meheap”) _M_start _M_finish _M_end_of_storage address of meh string 因為 _M_finish == _ M_end_of_storage 所以會先從新 new ⼀一塊新的 vector 並把舊的值複製過去 再將藍藍⾊色那塊 delete 掉
  • 34. Vector & String • Vector layout 34 vec.push_back(“meheap”) _M_start _M_finish _M_end_of_storage address of meh string address of meh string address of meheap string
  • 35. Vector & String • Vector layout 35 vec.push_back(“meh.py”) _M_start _M_finish _M_end_of_storage address of meh string address of meh string address of meheap string address of meh string address of meheap string address of meh.py string
  • 36. Vector & String • Vector layout 36 vec.push_back(“pwn”) _M_start _M_finish _M_end_of_storage address of meh string address of meh string address of meheap string address of meh string address of meheap string address of meh.py string address of pwn string
  • 37. Vector & String • Vector layout 37 vec.pop_back() _M_start _M_finish _M_end_of_storage address of meh string address of meh string address of meheap string address of meh string address of meheap string address of meh.py string address of pwn string call destructor of pwn string
  • 38. Vector & String • Vector layout 38 vec.pop_back() _M_start _M_finish _M_end_of_storage address of meh string address of meh string address of meheap string address of meh string address of meheap string address of meh.py string address of pwn string
  • 39. Vector & String • String • a dynamic char array • 比起以往的字串串陣列列更更加安全,全部動態配置記憶體空間, 減少⼀一般 buffer overflow 的發⽣生 • 在給定 input 時,會不斷重新分配空間給 user 直到結束後, 就會回傳適當的⼤大⼩小給 user • 有許多種實作⽅方式,這邊介紹最常⾒見見的⼀一種 • g++ < 5 39
  • 40. Vector & String • String • member • size :字串串的長度 • Capacity : 該 string 空間的容量量 • reference count : 引⽤用計數 • 只要有其他元素引⽤用該字串串就會增加 • 如果其他元素不引⽤用了了,也會減少 • 當 reference == 0 時就會,將空間 delete 掉 • value : 存放字串串內容 40
  • 41. Vector & String • String • member function • length() : string ⼤大⼩小 • capacity() : ⽬目前 string 空間容量量 • c_str() : Get C string equivalent • …… 41
  • 42. Vector & String • String layout 42 str string str cin >> str
  • 43. Vector & String • String layout 43 str string str cin >> str input : aa size = 2 capacity = 2 refcnt = 0 aa
  • 44. Vector & String • String layout 44 str string str cin >> str input : aaa size = 2 capacity = 2 refcnt = -1 aa size = 3 capacity = 4 refcnt = 0 aaa
  • 45. Vector & String • String layout 45 str string str cin >> str input : aaaaa size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 5 capacity = 8 refcnt = 0 aaaaa
  • 46. Vector & String • String layout 46 str string str cin >> str input : a*125 size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = 0 a*125 依此類推 capacity 會 不斷以⼆二的指數倍增長 直到 input 結束 . . .
  • 47. Vector & String • String layout 47 str vector<string> vec vec.push_back(str) size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = 1 a*125 _M_start _M_finish _M_end_of_storage str . . .
  • 48. Vector & String • String layout 48 str size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = 2 a*125 _M_start _M_finish _M_end_of_storage str str str vector<string> vec vec.push_back(str) vec.push_back(str) . . .
  • 49. Vector & String • String layout 49 str size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = 1 a*125 _M_start _M_finish _M_end_of_storage str str str vec.pop_back() 這邊會 call str destuctor 但不會 delete 空間 . . .
  • 50. Vector & String • String layout 50 str size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = 0 a*125 _M_start _M_finish _M_end_of_storage str str str vec.pop_back() 這邊會 call str destuctor 但不會 delete 空間 . . .
  • 51. Vector & String • String layout 51 size = 2 capacity = 2 refcnt = -1 aa size = 4 capacity = 4 refcnt = -1 aaaa size = 8 capacity = 8 refcnt = -1 aaaaaaaa size = 125 capacity = 128 refcnt = -1 a*125 _M_start _M_finish _M_end_of_storage str str str end of scope 這邊會 call str destuctor 因 refcnt < 0 會做 delete . . .
  • 52. Vector & String • String • g++ > 5 之後取消了了 Copy-on-Write 機制 • 所以少掉了了 reference count 這個欄欄位 • 在 data length • <= 15 時會⽤用 local buffer • > 15 時則會在 heap allocate 空間給 data 使⽤用 52
  • 53. Vector & String • String • data pointer : 指向 data 位置 • size : 分配出去 string 的長度 • union • local buffer : 在 size <= 15 時會直接把這欄欄位拿來來存 data • allocated capacity : size > 15 時會拿來來紀錄 capcity 53
  • 54. Vector & String • String • size < 15 54 data pointer size = 15 aaaaaaaa aaaaaaaa
  • 55. Vector & String • String • size > 15 55 data pointer size = 17 capacity = 30 0 aaaaaaaa aaaaaaaa a heap
  • 56. Outline • Name Mangling • Virtual function table • Vector & String • New & delete • Copy constructor & assignment operator 56
  • 57. New & Delete • 在 c++ 預設的情況下 ,new/delete 的最底層實作依舊是靠 malloc/free 去處理理記憶體管理理 • 在 c++ 中,記憶體配置池稱為 free store ,但預設情況下 free store 位置是在 heap • 不過事實上 new/delete 是可以 overloading 的,也就是⾃自⾏行行去 做記憶體管理理,另外最⼤大差別就是new/delete 實際上會去 call constructor/destructor ⽽而 malloc/free 只做單純的記憶體配置 • 因此盡量量不要讓 malloc/free 與 new/delete 混⽤用,不然可能會 出現⼀一些不可預期的狀狀況 57
  • 58. New & Delete • new ⼤大致上流程 • operator new • 與 malloc 類似,單純配置記憶體空間,但配置失敗會進入 exception ⽽而 malloc 則是返回 null ,有點像在 malloc 上⼀一層 wrapper • constructor • delete ⼤大致上流程 • destructor • operator delete • 與 free 類似,釋放⼀一塊記憶體空間,有點像是在 free 上⼀一層 wrapper 58
  • 59. New & Delete • 因此 new/delete 及 operator new / operator delete 也應該成對配對 • 記憶體函式配對 59 配置函式 解除函式 new delete new [] delete [] operator new operator delete operator new[] operator delete[] malloc free
  • 60. Outline • Name Mangling • Virtual function table • Vector & String • New & delete • Copy constructor & assignment operator 60
  • 61. What’s wrong in this code 61
  • 62. What’s wrong in this code 62
  • 63. Copy constructor & assignment operator • shallow copy • 只做單純 pointer (value) 的複製,複製完後內 容與原本的相同 • deep copy • 會在配置更更多記憶體空間,包含 pointer 所指向 的內容也都⼀一併複製 63
  • 64. Copy constructor & assignment operator • shallow copy 64 name orange StuA
  • 65. Copy constructor & assignment operator • shallow copy 65 name orange name StuA StuB
  • 66. Copy constructor & assignment operator • deep copy 66 name orange StuA
  • 67. Copy constructor & assignment operator • deep copy 67 name orange name StuA StuB orange
  • 68. Copy constructor & assignment operator • Copy constructor • c++ 在進⾏行行複製 object 會使⽤用 copy constructor • 通常 class 的 member 有指標時,就需要⾃自⾏行行 去實作 • 若若未特別定義則會使⽤用 default copy constructor • 只做 shallow copy 68
  • 69. Copy constructor & assignment operator • Assignment operator • c++ 在進⾏行行 “=“ 這個 operator 時 object 會使⽤用 assignment operator 這個 function 去 assign object 的 值 • 通常 class 的 member 有指標時,就需要⾃自⾏行行去實作 • 若若未特別定義則會使⽤用 default assignment operator • 只做 shallow copy 69
  • 70. Copy constructor & assignment operator • 何時會使⽤用 copy constructor • func(Stu stu) • return stu • vector 等 STL 容器 • …. 70
  • 71. Copy constructor & assignment operator • 何時會使⽤用 assignment operator • stuA = stuB • vector 等 STL 容器 • e.g. vector.erase() • … 71
  • 72. Copy constructor & assignment operator 72 call constructor id name vector
  • 73. Copy constructor & assignment operator 73 new char [str.length() + 1] id = 1337 name orange vector
  • 74. Copy constructor & assignment operator 74 push_back(student) id = 1337 name orange vector id = 1337 name copy the value to vector using shadow copy
  • 75. Copy constructor & assignment operator 75 ~Stu() id = 1337 name orange vector id = 1337 name 因 student 的 life time 結束 所以 call destructor
  • 76. Copy constructor & assignment operator 76 delete [] name id = 1337 name orange vector id = 1337 name
  • 77. Copy constructor & assignment operator 77 ~vector() id = 1337 name orange vector id = 1337 name 因 stulist 的 life time 結束 所以 call destructor
  • 78. Copy constructor & assignment operator 78 ~Stu() id = 1337 name orange vector id = 1337 name vector 會去 依次去呼叫 內容的 destructor
  • 79. Copy constructor & assignment operator 79 delete [] name id = 1337 name orange vector id = 1337 name
  • 80. Copy constructor & assignment operator 80 delete [] name id = 1337 name orange vector id = 1337 name double free
  • 81. Copy constructor & assignment operator • 總結 • 基本上 c++ 在只要做任何複製的動作時通常都 會去使⽤用 copy constructor 或者是 assignment operator • 所以基本上物件只要有 pointer 都盡量量養成習慣 去定義 copy constructor 跟 assignment opeator 81
  • 83. Q & A
  翻译: