kcov.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. kcov: code coverage for fuzzing
  2. ===============================
  3. kcov exposes kernel code coverage information in a form suitable for coverage-
  4. guided fuzzing (randomized testing). Coverage data of a running kernel is
  5. exported via the "kcov" debugfs file. Coverage collection is enabled on a task
  6. basis, and thus it can capture precise coverage of a single system call.
  7. Note that kcov does not aim to collect as much coverage as possible. It aims
  8. to collect more or less stable coverage that is function of syscall inputs.
  9. To achieve this goal it does not collect coverage in soft/hard interrupts
  10. and instrumentation of some inherently non-deterministic parts of kernel is
  11. disabled (e.g. scheduler, locking).
  12. kcov is also able to collect comparison operands from the instrumented code
  13. (this feature currently requires that the kernel is compiled with clang).
  14. Prerequisites
  15. -------------
  16. Configure the kernel with::
  17. CONFIG_KCOV=y
  18. CONFIG_KCOV requires gcc 6.1.0 or later.
  19. If the comparison operands need to be collected, set::
  20. CONFIG_KCOV_ENABLE_COMPARISONS=y
  21. Profiling data will only become accessible once debugfs has been mounted::
  22. mount -t debugfs none /sys/kernel/debug
  23. Coverage collection
  24. -------------------
  25. The following program demonstrates coverage collection from within a test
  26. program using kcov:
  27. .. code-block:: c
  28. #include <stdio.h>
  29. #include <stddef.h>
  30. #include <stdint.h>
  31. #include <stdlib.h>
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/mman.h>
  36. #include <unistd.h>
  37. #include <fcntl.h>
  38. #include <linux/types.h>
  39. #define KCOV_INIT_TRACE _IOR('c', 1, unsigned long)
  40. #define KCOV_ENABLE _IO('c', 100)
  41. #define KCOV_DISABLE _IO('c', 101)
  42. #define COVER_SIZE (64<<10)
  43. #define KCOV_TRACE_PC 0
  44. #define KCOV_TRACE_CMP 1
  45. int main(int argc, char **argv)
  46. {
  47. int fd;
  48. unsigned long *cover, n, i;
  49. /* A single fd descriptor allows coverage collection on a single
  50. * thread.
  51. */
  52. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  53. if (fd == -1)
  54. perror("open"), exit(1);
  55. /* Setup trace mode and trace size. */
  56. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  57. perror("ioctl"), exit(1);
  58. /* Mmap buffer shared between kernel- and user-space. */
  59. cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  60. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  61. if ((void*)cover == MAP_FAILED)
  62. perror("mmap"), exit(1);
  63. /* Enable coverage collection on the current thread. */
  64. if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_PC))
  65. perror("ioctl"), exit(1);
  66. /* Reset coverage from the tail of the ioctl() call. */
  67. __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
  68. /* That's the target syscal call. */
  69. read(-1, NULL, 0);
  70. /* Read number of PCs collected. */
  71. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  72. for (i = 0; i < n; i++)
  73. printf("0x%lx\n", cover[i + 1]);
  74. /* Disable coverage collection for the current thread. After this call
  75. * coverage can be enabled for a different thread.
  76. */
  77. if (ioctl(fd, KCOV_DISABLE, 0))
  78. perror("ioctl"), exit(1);
  79. /* Free resources. */
  80. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  81. perror("munmap"), exit(1);
  82. if (close(fd))
  83. perror("close"), exit(1);
  84. return 0;
  85. }
  86. After piping through addr2line output of the program looks as follows::
  87. SyS_read
  88. fs/read_write.c:562
  89. __fdget_pos
  90. fs/file.c:774
  91. __fget_light
  92. fs/file.c:746
  93. __fget_light
  94. fs/file.c:750
  95. __fget_light
  96. fs/file.c:760
  97. __fdget_pos
  98. fs/file.c:784
  99. SyS_read
  100. fs/read_write.c:562
  101. If a program needs to collect coverage from several threads (independently),
  102. it needs to open /sys/kernel/debug/kcov in each thread separately.
  103. The interface is fine-grained to allow efficient forking of test processes.
  104. That is, a parent process opens /sys/kernel/debug/kcov, enables trace mode,
  105. mmaps coverage buffer and then forks child processes in a loop. Child processes
  106. only need to enable coverage (disable happens automatically on thread end).
  107. Comparison operands collection
  108. ------------------------------
  109. Comparison operands collection is similar to coverage collection:
  110. .. code-block:: c
  111. /* Same includes and defines as above. */
  112. /* Number of 64-bit words per record. */
  113. #define KCOV_WORDS_PER_CMP 4
  114. /*
  115. * The format for the types of collected comparisons.
  116. *
  117. * Bit 0 shows whether one of the arguments is a compile-time constant.
  118. * Bits 1 & 2 contain log2 of the argument size, up to 8 bytes.
  119. */
  120. #define KCOV_CMP_CONST (1 << 0)
  121. #define KCOV_CMP_SIZE(n) ((n) << 1)
  122. #define KCOV_CMP_MASK KCOV_CMP_SIZE(3)
  123. int main(int argc, char **argv)
  124. {
  125. int fd;
  126. uint64_t *cover, type, arg1, arg2, is_const, size;
  127. unsigned long n, i;
  128. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  129. if (fd == -1)
  130. perror("open"), exit(1);
  131. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  132. perror("ioctl"), exit(1);
  133. /*
  134. * Note that the buffer pointer is of type uint64_t*, because all
  135. * the comparison operands are promoted to uint64_t.
  136. */
  137. cover = (uint64_t *)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  138. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  139. if ((void*)cover == MAP_FAILED)
  140. perror("mmap"), exit(1);
  141. /* Note KCOV_TRACE_CMP instead of KCOV_TRACE_PC. */
  142. if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_CMP))
  143. perror("ioctl"), exit(1);
  144. __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
  145. read(-1, NULL, 0);
  146. /* Read number of comparisons collected. */
  147. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  148. for (i = 0; i < n; i++) {
  149. uint64_t ip;
  150. type = cover[i * KCOV_WORDS_PER_CMP + 1];
  151. /* arg1 and arg2 - operands of the comparison. */
  152. arg1 = cover[i * KCOV_WORDS_PER_CMP + 2];
  153. arg2 = cover[i * KCOV_WORDS_PER_CMP + 3];
  154. /* ip - caller address. */
  155. ip = cover[i * KCOV_WORDS_PER_CMP + 4];
  156. /* size of the operands. */
  157. size = 1 << ((type & KCOV_CMP_MASK) >> 1);
  158. /* is_const - true if either operand is a compile-time constant.*/
  159. is_const = type & KCOV_CMP_CONST;
  160. printf("ip: 0x%lx type: 0x%lx, arg1: 0x%lx, arg2: 0x%lx, "
  161. "size: %lu, %s\n",
  162. ip, type, arg1, arg2, size,
  163. is_const ? "const" : "non-const");
  164. }
  165. if (ioctl(fd, KCOV_DISABLE, 0))
  166. perror("ioctl"), exit(1);
  167. /* Free resources. */
  168. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  169. perror("munmap"), exit(1);
  170. if (close(fd))
  171. perror("close"), exit(1);
  172. return 0;
  173. }
  174. Note that the kcov modes (coverage collection or comparison operands) are
  175. mutually exclusive.
  176. Remote coverage collection
  177. --------------------------
  178. With KCOV_ENABLE coverage is collected only for syscalls that are issued
  179. from the current process. With KCOV_REMOTE_ENABLE it's possible to collect
  180. coverage for arbitrary parts of the kernel code, provided that those parts
  181. are annotated with kcov_remote_start()/kcov_remote_stop().
  182. This allows to collect coverage from two types of kernel background
  183. threads: the global ones, that are spawned during kernel boot in a limited
  184. number of instances (e.g. one USB hub_event() worker thread is spawned per
  185. USB HCD); and the local ones, that are spawned when a user interacts with
  186. some kernel interface (e.g. vhost workers); as well as from soft
  187. interrupts.
  188. To enable collecting coverage from a global background thread or from a
  189. softirq, a unique global handle must be assigned and passed to the
  190. corresponding kcov_remote_start() call. Then a userspace process can pass
  191. a list of such handles to the KCOV_REMOTE_ENABLE ioctl in the handles
  192. array field of the kcov_remote_arg struct. This will attach the used kcov
  193. device to the code sections, that are referenced by those handles.
  194. Since there might be many local background threads spawned from different
  195. userspace processes, we can't use a single global handle per annotation.
  196. Instead, the userspace process passes a non-zero handle through the
  197. common_handle field of the kcov_remote_arg struct. This common handle gets
  198. saved to the kcov_handle field in the current task_struct and needs to be
  199. passed to the newly spawned threads via custom annotations. Those threads
  200. should in turn be annotated with kcov_remote_start()/kcov_remote_stop().
  201. Internally kcov stores handles as u64 integers. The top byte of a handle
  202. is used to denote the id of a subsystem that this handle belongs to, and
  203. the lower 4 bytes are used to denote the id of a thread instance within
  204. that subsystem. A reserved value 0 is used as a subsystem id for common
  205. handles as they don't belong to a particular subsystem. The bytes 4-7 are
  206. currently reserved and must be zero. In the future the number of bytes
  207. used for the subsystem or handle ids might be increased.
  208. When a particular userspace process collects coverage via a common
  209. handle, kcov will collect coverage for each code section that is annotated
  210. to use the common handle obtained as kcov_handle from the current
  211. task_struct. However non common handles allow to collect coverage
  212. selectively from different subsystems.
  213. .. code-block:: c
  214. /* Same includes and defines as above. */
  215. struct kcov_remote_arg {
  216. __u32 trace_mode;
  217. __u32 area_size;
  218. __u32 num_handles;
  219. __aligned_u64 common_handle;
  220. __aligned_u64 handles[0];
  221. };
  222. #define KCOV_INIT_TRACE _IOR('c', 1, unsigned long)
  223. #define KCOV_DISABLE _IO('c', 101)
  224. #define KCOV_REMOTE_ENABLE _IOW('c', 102, struct kcov_remote_arg)
  225. #define COVER_SIZE (64 << 10)
  226. #define KCOV_TRACE_PC 0
  227. #define KCOV_SUBSYSTEM_COMMON (0x00ull << 56)
  228. #define KCOV_SUBSYSTEM_USB (0x01ull << 56)
  229. #define KCOV_SUBSYSTEM_MASK (0xffull << 56)
  230. #define KCOV_INSTANCE_MASK (0xffffffffull)
  231. static inline __u64 kcov_remote_handle(__u64 subsys, __u64 inst)
  232. {
  233. if (subsys & ~KCOV_SUBSYSTEM_MASK || inst & ~KCOV_INSTANCE_MASK)
  234. return 0;
  235. return subsys | inst;
  236. }
  237. #define KCOV_COMMON_ID 0x42
  238. #define KCOV_USB_BUS_NUM 1
  239. int main(int argc, char **argv)
  240. {
  241. int fd;
  242. unsigned long *cover, n, i;
  243. struct kcov_remote_arg *arg;
  244. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  245. if (fd == -1)
  246. perror("open"), exit(1);
  247. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  248. perror("ioctl"), exit(1);
  249. cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  250. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  251. if ((void*)cover == MAP_FAILED)
  252. perror("mmap"), exit(1);
  253. /* Enable coverage collection via common handle and from USB bus #1. */
  254. arg = calloc(1, sizeof(*arg) + sizeof(uint64_t));
  255. if (!arg)
  256. perror("calloc"), exit(1);
  257. arg->trace_mode = KCOV_TRACE_PC;
  258. arg->area_size = COVER_SIZE;
  259. arg->num_handles = 1;
  260. arg->common_handle = kcov_remote_handle(KCOV_SUBSYSTEM_COMMON,
  261. KCOV_COMMON_ID);
  262. arg->handles[0] = kcov_remote_handle(KCOV_SUBSYSTEM_USB,
  263. KCOV_USB_BUS_NUM);
  264. if (ioctl(fd, KCOV_REMOTE_ENABLE, arg))
  265. perror("ioctl"), free(arg), exit(1);
  266. free(arg);
  267. /*
  268. * Here the user needs to trigger execution of a kernel code section
  269. * that is either annotated with the common handle, or to trigger some
  270. * activity on USB bus #1.
  271. */
  272. sleep(2);
  273. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  274. for (i = 0; i < n; i++)
  275. printf("0x%lx\n", cover[i + 1]);
  276. if (ioctl(fd, KCOV_DISABLE, 0))
  277. perror("ioctl"), exit(1);
  278. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  279. perror("munmap"), exit(1);
  280. if (close(fd))
  281. perror("close"), exit(1);
  282. return 0;
  283. }