C言語やC++の欠点の一つは,バッファオーバーフローやオーバーランが起こりやすいことです.
それは欠点であると同時にC/C++の利点であると言う人もいます.つまり,メモリ関連のチェックを省略することで,省略した分C/C++はオーバヘッドが少ない高速なプログラムが生成できるというものです.しかしバッファオーバーフローやオーバーランはプログラムのクラッシュやセキュリティホールを招く危険な「バグ」であることには変わりありません.
そこで最近のC/C++のコンパイラはコンパイル時のオプションでオーバーフローのチェックをOn/Offできるようになっています.
オプションは大雑把に分類すると
- コンパイル時に,静的に,オーバーフローのチェックするもの
- 実行時に,動的に,オーバーフローのチェックするもの
に大別できます.
これらオプションのデメリットは
となります.
実際の開発では,メリットとデメリットのトレードオフを理解した上で,デバッグビルドではOn リリースビルドではOffする,といった使い方をすることになります.
使用例
昨日書いたコードにあえてバグを混入させます.
#include <string> #include <cstdio> #include <vector> template <typename ... Args> std::string format(const std::string& fmt, Args ... args ) { // 意図的にバグを混入しています.正しいコードは // http://pyopyopyo.hatenablog.com/entry/2019/02/08/102456 をみてください size_t len = std::snprintf( nullptr, 0, fmt.c_str(), args ... ); std::vector<char> buf(len); std::snprintf(&buf[0], len+1, fmt.c_str(), args ... ); return std::string(&buf[0], &buf[0] + len); } #include <iostream> int main() { // 意図的にバグを混入しています.正しいコードは // http://pyopyopyo.hatenablog.com/entry/2019/02/08/102456 をみてください std::cout << format("%e", 1./3) << std::endl; return 0; }
どこにバグがあるか判るでしょうか?
試しにコンパイルして実行してみます.mac OSで,clangを使ってコンパイルしてみました.
$ clang++ -std=c++11 -Wall -Wextra -Og -g bug1.cpp -o bug1 $ ./bug1 3.333333e-0
特に問題なく実行できます.しかしこれは「偶々」動作しただけです.
AddressSanitizer を使う
コンパライのオプションに " -fsanitize=address "を追加します.これでオーバーフローの実行時チェックが有効になります.
$ clang++ -std=c++11 -fsanitize=address -Wall -Wextra -Og -g bug1.cpp -o bug1
バイナリを実行すると,AddressSanitizerがバッファオーバーフロー(厳密には heap-buffer-overflow)を検出します.
$ ./bug1 len: 1 ================================================================= ==1038==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000f1 at pc 0x000101fe6c39 bp 0x7ffeedc4e570 sp 0x7ffeedc4dcf8 WRITE of size 2 at 0x6020000000f1 thread T0 #0 0x101fe6c38 in wrap_vsnprintf (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x26c38) #1 0x101fe7945 in wrap_snprintf (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x27945) #2 0x101fb23b8 in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > format<int>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) bug1.cpp:13 #3 0x101fb1e42 in main bug1.cpp:20 #4 0x7fff585f308c in start (libdyld.dylib:x86_64+0x1708c) 0x6020000000f1 is located 0 bytes to the right of 1-byte region [0x6020000000f0,0x6020000000f1) allocated by thread T0 here: #0 0x102022fa2 in wrap__Znwm (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x62fa2) #1 0x101fb305b in std::__1::vector<char, std::__1::allocator<char> >::allocate(unsigned long) vector:937 #2 0x101fb3008 in std::__1::vector<char, std::__1::allocator<char> >::vector(unsigned long) vector:1080 #3 0x101fb234b in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > format<int>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int) bug1.cpp:12 #4 0x101fb1e42 in main bug1.cpp:20 #5 0x7fff585f308c in start (libdyld.dylib:x86_64+0x1708c) SUMMARY: AddressSanitizer: heap-buffer-overflow (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x26c38) in wrap_vsnprintf Shadow bytes around the buggy address: 0x1c03ffffffc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x1c03ffffffd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x1c03ffffffe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x1c03fffffff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x1c0400000000: fa fa fd fd fa fa fd fd fa fa 00 00 fa fa 00 00 =>0x1c0400000010: fa fa 00 04 fa fa 00 00 fa fa 00 06 fa fa[01]fa 0x1c0400000020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x1c0400000030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x1c0400000040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x1c0400000050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x1c0400000060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb ==1038==ABORTING Abort trap: 6
AddressSanitizerのログの読み方
冒頭の3行
AddressSanitizer: heap-buffer-overflow on address 0x6020000000f1 at pc 0x000101fe6c39 bp 0x7ffeedc4e570 sp 0x7ffeedc4dcf8 WRITE of size 2 at 0x6020000000f1 thread T0 #0 0x101fe6c38 in wrap_vsnprintf (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x26c38)
これは先頭から順に
- バッファオーバーフローが発生した
- 場所は 2BYTE メモリに書き込む処理(メモリのアドレスは 0x6020000000f1 )
- それは wrap_vsnprintf の内部の処理
と読みます.
次の4行は
0x6020000000f1 is located 0 bytes to the right of 1-byte region [0x6020000000f0,0x6020000000f1) allocated by thread T0 here: #0 0x102022fa2 in wrap__Znwm (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x62fa2) #1 0x101fb305b in std::__1::vector<char, std::__1::allocator<char> >::allocate(unsigned long) vector:937
- 0x6020000000f1 のメモリは,メモリ領域 [0x6020000000f0,0x6020000000f1)の1バイト右側(後ろ側)のアドレス
- それが割り当てられたのは wrap__Znwm () という関数で
- std::__1::vector
の内部からコールされている
と読みます
まとめると, vsnprintf で std::vector
ソースコード上では,以下の2行にバグがある,ということになります
std::vector<char> buf(len); std::snprintf(&buf[0], len+1, fmt.c_str(), args ... );
具体的には
- snprintf()の中でオーバーフロー発生
- オーバーフロー発生箇所は,buf の1byte後ろで
となります.len + 1 が見るからに怪しいですね.
正しいコードは
std::vector<char> buf(len); std::snprintf(&buf[0], len, fmt.c_str(), args ... );
のように思うかもしれませんが,この場合は
std::vector<char> buf(len+1); std::snprintf(&buf[0], len+1, fmt.c_str(), args ... );
が正解です.lenが文字列の長さで,snprintf()が文字列をNULL終端するので,そのために+1BYTEメモリが必要だからです.