一、简介
KASan,全称Kernel Address Sanitizer,它是一个动态检测内存错误的工具,主要功能是检查内存越界访问和使用已释放的内存等问题。KASan 集成在 Linux 内核中,随 Linux 内核代码一起发布,并由内核社区维护和发展。本文简要介绍 KASan 的原理及使用方法。
二、原理与使用
2.1 KASan原理
KASan利用额外的内存标记可用内存的状态,这部分额外的内存被称作shadow memory(影子区)。在我们Linux内核中有page结构体(页描述符),用来标识物理内存页,每个4KB的页面都需要一个page结构体来进行描述,除此之外还有大量的用来描述各类结构的结构体,这些用于描述各类结构的结构体会占用一定量的内存。同样的KASan也使用额外的内存来对内存使用进行标记(即内存的合法检测以内存空间作为代价)。
KASan将1/8的内存用作shadow memory,例如一个128G的内存,那么需要16G的内存用来作为影子区。KANsan使用特殊的magic num填充shadow memory,在每一次load/store内存的时候检测对应的shadow memory确定操作是否valid。连续8 bytes内存(8 bytes align)使用1 byte shadow memory标记。
图片来自:http://www.wowotech.net/memory_management/424.html
从上面可以看出,当有几个byte出现错误时,shadow memory的标志位中使用一个byte的数据来标识了8个byte中出错的个数。当没有错误时该标识的byte值为0~
2.2 配置KASan
KASan 是内核的一部分,使用时需要重新配置、编译并安装内核。KASan 在 Linux 内核 4.0 版本时被引入内核,所以选择的内核代码需要高于 4.0 版本。另外,最基本的 KASan 功能需要 GCC4.9.2 支持,更多的支持则需要 GCC5.0 及以上版本。
要是用KASan就重新配置和编译内核~
找一个版本的内核,我找到了一个linux-4.6.4就直接使用了,使用下列命令进行配置:
make menuconfig
通过前面三步,把KASan选上~
继续进入Instrumentation type里面~
选择Inline instrumentation,这个默认是Outline instrumentation~
至于这个为什么这么选,可以看:https://www.kernel.org/doc/html/latest/dev-tools/kasan.html
Outline and inline are compiler instrumentation types.
Software tag-based KASAN also has two instrumentation modes (outline, that emits callbacks to check memory accesses; and inline, that performs the shadow memory checks inline). With outline instrumentation mode, a bug report is simply printed from the function that performs the access check. With inline instrumentation a brk instruction is emitted by the compiler, and a dedicated brk handler is used to print bug reports.
选择好后,保存退出,并开始编译内核~
编译内核可以参考: https://blog.csdn.net/SweeNeil/article/details/83684565
2.3 KASan的使用
Linux 内核的源码中已经包含了针对 KASan 的测试代码,其位置在 linux/lib/test_kasan.c。编译内核或者单独编译 lib 模块的时候,会生成 te