← Documents Documentation/dev-tools/gcov.rst GitHub 원문 ↗

Linux 6.18.37 · Dev Tools

Using gcov with the Linux kernel

Linux 커널의 gcov coverage 수집을 구성하고 debugfs 파일, 모듈 data 유지, 분리된 빌드·테스트 환경, GCC와 Clang 도구 차이를 다루는 방법을 설명합니다.

Source pathDocumentation/dev-tools/gcov.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

gcov.rst:1-285

커널 gcov 지원은 실행 중인 코드의 coverage counter를 debugfs에 `.gcda` 형식으로 노출합니다. CONFIG_GCOV_KERNEL과 필요한 범위의 Makefile 설정을 사용하면 전체 커널 또는 선택한 object만 계측하고 gcov나 llvm-cov로 결과를 분석할 수 있습니다.

계측은 커널 크기와 실행 비용을 늘리므로 범위를 신중히 정해야 합니다. build와 test machine이 다르면 compiler 버전, 원본 경로, `.gcno` link와 `.gcda` 복사 방식을 맞추고, sysfs 파일은 seq_file 특성을 고려해 안전하게 수집해야 합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 Using gcov with the Linux kernel
2 ================================
3
4 gcov profiling kernel support enables the use of GCC's coverage testing
5 tool gcov_ with the Linux kernel. Coverage data of a running kernel
6 is exported in gcov-compatible format via the "gcov" debugfs directory.
7 To get coverage data for a specific file, change to the kernel build
8 directory and use gcov with the ``-o`` option as follows (requires root)::
9
10 # cd /tmp/linux-out
11 # gcov -o /sys/kernel/debug/gcov/tmp/linux-out/kernel spinlock.c
12
13 This will create source code files annotated with execution counts
14 in the current directory. In addition, graphical gcov front-ends such
15 as lcov_ can be used to automate the process of collecting data
16 for the entire kernel and provide coverage overviews in HTML format.
17
18 Possible uses:
19
20 * debugging (has this line been reached at all?)
21 * test improvement (how do I change my test to cover these lines?)
22 * minimizing kernel configurations (do I need this option if the
23 associated code is never run?)
24
25 .. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
26 .. _lcov: https://github.com/linux-test-project/lcov
27
28
29 Preparation
30 -----------
31
32 Configure the kernel with::
33
34 CONFIG_DEBUG_FS=y
35 CONFIG_GCOV_KERNEL=y
36
37 and to get coverage data for the entire kernel::
38
39 CONFIG_GCOV_PROFILE_ALL=y
40
41 Note that kernels compiled with profiling flags will be significantly
42 larger and run slower. Also CONFIG_GCOV_PROFILE_ALL may not be supported
43 on all architectures.
44
45 Profiling data will only become accessible once debugfs has been
46 mounted::
47
48 mount -t debugfs none /sys/kernel/debug
49
50
51 Customization
52 -------------
53
54 To enable profiling for specific files or directories, add a line
55 similar to the following to the respective kernel Makefile:
56
57 - For a single file (e.g. main.o)::
58
59 GCOV_PROFILE_main.o := y
60
61 - For all files in one directory::
62
63 GCOV_PROFILE := y
64
65 To exclude files from being profiled even when CONFIG_GCOV_PROFILE_ALL
66 is specified, use::
67
68 GCOV_PROFILE_main.o := n
69
70 and::
71
72 GCOV_PROFILE := n
73
74 Only files which are linked to the main kernel image or are compiled as
75 kernel modules are supported by this mechanism.
76
77
78 Module specific configs
79 -----------------------
80
81 Gcov kernel configs for specific modules are described below:
82
83 CONFIG_GCOV_PROFILE_RDS:
84 Enables GCOV profiling on RDS for checking which functions or
85 lines are executed. This config is used by the rds selftest to
86 generate coverage reports. If left unset the report is omitted.
87
88
89 Files
90 -----
91
92 The gcov kernel support creates the following files in debugfs:
93
94 ``/sys/kernel/debug/gcov``
95 Parent directory for all gcov-related files.
96
97 ``/sys/kernel/debug/gcov/reset``
98 Global reset file: resets all coverage data to zero when
99 written to.
100
101 ``/sys/kernel/debug/gcov/path/to/compile/dir/file.gcda``
102 The actual gcov data file as understood by the gcov
103 tool. Resets file coverage data to zero when written to.
104
105 ``/sys/kernel/debug/gcov/path/to/compile/dir/file.gcno``
106 Symbolic link to a static data file required by the gcov
107 tool. This file is generated by gcc when compiling with
108 option ``-ftest-coverage``.
109
110
111 Modules
112 -------
113
114 Kernel modules may contain cleanup code which is only run during
115 module unload time. The gcov mechanism provides a means to collect
116 coverage data for such code by keeping a copy of the data associated
117 with the unloaded module. This data remains available through debugfs.
118 Once the module is loaded again, the associated coverage counters are
119 initialized with the data from its previous instantiation.
120
121 This behavior can be deactivated by specifying the gcov_persist kernel
122 parameter::
123
124 gcov_persist=0
125
126 At run-time, a user can also choose to discard data for an unloaded
127 module by writing to its data file or the global reset file.
128
129
130 Separated build and test machines
131 ---------------------------------
132
133 The gcov kernel profiling infrastructure is designed to work out-of-the
134 box for setups where kernels are built and run on the same machine. In
135 cases where the kernel runs on a separate machine, special preparations
136 must be made, depending on where the gcov tool is used:
137
138 .. _gcov-test:
139
140 a) gcov is run on the TEST machine
141
142 The gcov tool version on the test machine must be compatible with the
143 gcc version used for kernel build. Also the following files need to be
144 copied from build to test machine:
145
146 from the source tree:
147 - all C source files + headers
148
149 from the build tree:
150 - all C source files + headers
151 - all .gcda and .gcno files
152 - all links to directories
153
154 It is important to note that these files need to be placed into the
155 exact same file system location on the test machine as on the build
156 machine. If any of the path components is symbolic link, the actual
157 directory needs to be used instead (due to make's CURDIR handling).
158
159 .. _gcov-build:
160
161 b) gcov is run on the BUILD machine
162
163 The following files need to be copied after each test case from test
164 to build machine:
165
166 from the gcov directory in sysfs:
167 - all .gcda files
168 - all links to .gcno files
169
170 These files can be copied to any location on the build machine. gcov
171 must then be called with the -o option pointing to that directory.
172
173 Example directory setup on the build machine::
174
175 /tmp/linux: kernel source tree
176 /tmp/out: kernel build directory as specified by make O=
177 /tmp/coverage: location of the files copied from the test machine
178
179 [user@build] cd /tmp/out
180 [user@build] gcov -o /tmp/coverage/tmp/out/init main.c
181
182
183 Note on compilers
184 -----------------
185
186 GCC and LLVM gcov tools are not necessarily compatible. Use gcov_ to work with
187 GCC-generated .gcno and .gcda files, and use llvm-cov_ for Clang.
188
189 .. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
190 .. _llvm-cov: https://llvm.org/docs/CommandGuide/llvm-cov.html
191
192 Build differences between GCC and Clang gcov are handled by Kconfig. It
193 automatically selects the appropriate gcov format depending on the detected
194 toolchain.
195
196
197 Troubleshooting
198 ---------------
199
200 Problem
201 Compilation aborts during linker step.
202
203 Cause
204 Profiling flags are specified for source files which are not
205 linked to the main kernel or which are linked by a custom
206 linker procedure.
207
208 Solution
209 Exclude affected source files from profiling by specifying
210 ``GCOV_PROFILE := n`` or ``GCOV_PROFILE_basename.o := n`` in the
211 corresponding Makefile.
212
213 Problem
214 Files copied from sysfs appear empty or incomplete.
215
216 Cause
217 Due to the way seq_file works, some tools such as cp or tar
218 may not correctly copy files from sysfs.
219
220 Solution
221 Use ``cat`` to read ``.gcda`` files and ``cp -d`` to copy links.
222 Alternatively use the mechanism shown in Appendix B.
223
224
225 Appendix A: gather_on_build.sh
226 ------------------------------
227
228 Sample script to gather coverage meta files on the build machine
229 (see :ref:`Separated build and test machines a. <gcov-test>`):
230
231 .. code-block:: sh
232
233 #!/bin/bash
234
235 KSRC=$1
236 KOBJ=$2
237 DEST=$3
238
239 if [ -z "$KSRC" ] || [ -z "$KOBJ" ] || [ -z "$DEST" ]; then
240 echo "Usage: $0 <ksrc directory> <kobj directory> <output.tar.gz>" >&2
241 exit 1
242 fi
243
244 KSRC=$(cd $KSRC; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
245 KOBJ=$(cd $KOBJ; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
246
247 find $KSRC $KOBJ \( -name '*.gcno' -o -name '*.[ch]' -o -type l \) -a \
248 -perm /u+r,g+r | tar cfz $DEST -P -T -
249
250 if [ $? -eq 0 ] ; then
251 echo "$DEST successfully created, copy to test system and unpack with:"
252 echo " tar xfz $DEST -P"
253 else
254 echo "Could not create file $DEST"
255 fi
256
257
258 Appendix B: gather_on_test.sh
259 -----------------------------
260
261 Sample script to gather coverage data files on the test machine
262 (see :ref:`Separated build and test machines b. <gcov-build>`):
263
264 .. code-block:: sh
265
266 #!/bin/bash -e
267
268 DEST=$1
269 GCDA=/sys/kernel/debug/gcov
270
271 if [ -z "$DEST" ] ; then
272 echo "Usage: $0 <output.tar.gz>" >&2
273 exit 1
274 fi
275
276 TEMPDIR=$(mktemp -d)
277 echo Collecting data..
278 find $GCDA -type d -exec mkdir -p $TEMPDIR/\{\} \;
279 find $GCDA -name '*.gcda' -exec sh -c 'cat < $0 > '$TEMPDIR'/$0' {} \;
280 find $GCDA -name '*.gcno' -exec sh -c 'cp -d $0 '$TEMPDIR'/$0' {} \;
281 tar czf $DEST -C $TEMPDIR sys
282 rm -rf $TEMPDIR
283
284 echo "$DEST successfully created, copy to build system and unpack with:"
285 echo " tar xfz $DEST"
286

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Linux 커널에서 gcov 사용

1-28

Linux 커널에서 gcov 사용

gcov profiling kernel 지원을 사용하면 GCC의 coverage testing 도구 gcov_를 Linux 커널에 적용할 수 있습니다. 실행 중인 커널의 coverage data는 debugfs의 `gcov` directory를 통해 gcov 호환 형식으로 내보냅니다. 특정 파일의 coverage data를 얻으려면 kernel build directory로 이동하고 다음과 같이 `-o` 옵션과 함께 gcov를 사용하십시오. root 권한이 필요합니다.

# cd /tmp/linux-out
# gcov -o /sys/kernel/debug/gcov/tmp/linux-out/kernel spinlock.c

이 명령은 현재 directory에 실행 횟수를 주석으로 표시한 source code file을 생성합니다. 또한 lcov_ 같은 그래픽 gcov front-end를 사용하면 전체 커널의 data 수집 과정을 자동화하고 HTML 형식의 coverage 개요를 제공할 수 있습니다.

가능한 용도는 다음과 같습니다.

디버깅: 이 줄에 한 번이라도 도달했는가?

테스트 개선: 이 줄들을 실행하도록 테스트를 어떻게 바꿀 것인가?

커널 구성 최소화: 연관된 코드가 전혀 실행되지 않는다면 이 옵션이 필요한가?

gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html

lcov: https://github.com/linux-test-project/lcov

준비

29-50

준비

커널을 다음과 같이 구성하십시오.

CONFIG_DEBUG_FS=y
CONFIG_GCOV_KERNEL=y

전체 커널의 coverage data를 얻으려면 다음 옵션도 설정하십시오.

CONFIG_GCOV_PROFILE_ALL=y

profiling flag로 컴파일한 커널은 크기가 상당히 커지고 더 느리게 실행됩니다. 또한 모든 architecture에서 CONFIG_GCOV_PROFILE_ALL을 지원하지 않을 수 있습니다.

debugfs를 mount한 뒤에만 profiling data에 접근할 수 있습니다.

mount -t debugfs none /sys/kernel/debug

대상 파일과 디렉터리 지정

51-77

사용자 지정

특정 파일이나 directory에 profiling을 활성화하려면 해당 kernel Makefile에 다음과 비슷한 줄을 추가하십시오.

단일 파일, 예를 들어 main.o에는 다음을 사용합니다.

GCOV_PROFILE_main.o := y

한 directory의 모든 파일에는 다음을 사용합니다.

GCOV_PROFILE := y

CONFIG_GCOV_PROFILE_ALL을 지정한 경우에도 특정 파일을 profiling에서 제외하려면 다음을 사용합니다.

GCOV_PROFILE_main.o := n

그리고 다음 설정도 사용할 수 있습니다.

GCOV_PROFILE := n

이 메커니즘은 main kernel image에 link되는 파일이나 kernel module로 컴파일되는 파일만 지원합니다.

모듈별 구성

78-88

모듈별 구성

특정 모듈의 gcov kernel 구성은 다음과 같습니다.

CONFIG_GCOV_PROFILE_RDS: 어떤 함수나 줄이 실행되는지 확인하기 위해 RDS에서 GCOV profiling을 활성화합니다. rds selftest는 이 구성을 사용해 coverage report를 생성합니다. 설정하지 않으면 보고서를 생략합니다.

debugfs 파일

89-110

파일

gcov kernel 지원은 debugfs에 다음 파일을 생성합니다.

`/sys/kernel/debug/gcov`: 모든 gcov 관련 파일의 상위 directory입니다.

`/sys/kernel/debug/gcov/reset`: 전역 reset 파일입니다. 이 파일에 쓰면 모든 coverage data를 0으로 reset합니다.

`/sys/kernel/debug/gcov/path/to/compile/dir/file.gcda`: gcov 도구가 이해하는 실제 gcov data file입니다. 이 파일에 쓰면 해당 파일의 coverage data를 0으로 reset합니다.

`/sys/kernel/debug/gcov/path/to/compile/dir/file.gcno`: gcov 도구에 필요한 static data file을 가리키는 symbolic link입니다. gcc가 `-ftest-coverage` 옵션으로 컴파일할 때 이 파일을 생성합니다.

모듈 unload coverage 유지

111-129

모듈

kernel module에는 module unload 시점에만 실행되는 cleanup code가 포함될 수 있습니다. gcov 메커니즘은 unload한 module과 연관된 data의 사본을 보관해 이런 코드의 coverage data를 수집할 수단을 제공합니다. 이 data는 debugfs를 통해 계속 사용할 수 있습니다. module을 다시 load하면 연관된 coverage counter를 이전 인스턴스의 data로 초기화합니다.

gcov_persist kernel parameter를 지정하면 이 동작을 비활성화할 수 있습니다.

gcov_persist=0

실행 중에도 사용자는 해당 data file이나 전역 reset 파일에 써서 unload한 module의 data를 버릴 수 있습니다.

빌드 머신과 테스트 머신 분리

130-182

분리된 build machine과 test machine

gcov kernel profiling infrastructure는 커널을 같은 machine에서 build하고 실행하는 구성을 별도 설정 없이 지원하도록 설계되었습니다. 커널을 별도 machine에서 실행하는 경우에는 gcov 도구를 사용하는 위치에 따라 특별한 준비가 필요합니다.

a) TEST machine에서 gcov 실행

test machine의 gcov 도구 버전은 kernel build에 사용한 gcc 버전과 호환되어야 합니다. 또한 다음 파일들을 build machine에서 test machine으로 복사해야 합니다.

source tree: 모든 C source file과 header.

build tree: 모든 C source file과 header, 모든 `.gcda` 및 `.gcno` 파일, directory를 가리키는 모든 link.

이 파일들을 test machine에서 build machine과 정확히 같은 filesystem 위치에 두어야 한다는 점이 중요합니다. 경로 구성 요소 중 하나라도 symbolic link라면 make의 CURDIR 처리 때문에 link가 아닌 실제 directory를 사용해야 합니다.

b) BUILD machine에서 gcov 실행

각 test case가 끝난 뒤 test machine에서 build machine으로 다음 파일을 복사해야 합니다.

sysfs의 gcov directory: 모든 `.gcda` 파일과 `.gcno` 파일을 가리키는 모든 link.

이 파일들은 build machine의 어느 위치로든 복사할 수 있습니다. 그다음 gcov를 호출할 때 `-o` 옵션이 그 directory를 가리키게 해야 합니다.

build machine의 directory 구성 예시는 다음과 같습니다.

/tmp/linux:    kernel source tree
/tmp/out:      kernel build directory as specified by make O=
/tmp/coverage: location of the files copied from the test machine

[user@build] cd /tmp/out
[user@build] gcov -o /tmp/coverage/tmp/out/init main.c

컴파일러별 gcov 도구

183-196

컴파일러 참고 사항

GCC와 LLVM의 gcov 도구는 반드시 서로 호환되지는 않습니다. GCC가 생성한 `.gcno` 및 `.gcda` 파일에는 gcov_를 사용하고, Clang에는 llvm-cov_를 사용하십시오.

gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html

llvm-cov: https://llvm.org/docs/CommandGuide/llvm-cov.html

GCC와 Clang gcov 사이의 build 차이는 Kconfig가 처리합니다. 감지된 toolchain에 따라 적절한 gcov 형식을 자동으로 선택합니다.

문제 해결

197-224

문제 해결

문제: linker 단계에서 컴파일이 중단됩니다.

원인: main kernel에 link되지 않거나 사용자 지정 linker 절차로 link되는 source file에 profiling flag가 지정되어 있습니다.

해결 방법: 해당 Makefile에서 `GCOV_PROFILE := n` 또는 `GCOV_PROFILE_basename.o := n`을 지정해 영향을 받는 source file을 profiling에서 제외하십시오.

문제: sysfs에서 복사한 파일이 비어 있거나 불완전해 보입니다.

원인: seq_file의 동작 방식 때문에 cp나 tar 같은 일부 도구가 sysfs의 파일을 올바르게 복사하지 못할 수 있습니다.

해결 방법: `.gcda` 파일은 `cat`으로 읽고 link는 `cp -d`로 복사하십시오. 또는 부록 B의 메커니즘을 사용하십시오.

부록 A: gather_on_build.sh

225-257

부록 A: gather_on_build.sh

build machine에서 coverage metadata file을 수집하는 예제 스크립트입니다. '분리된 build machine과 test machine a.'를 참조하십시오.

#!/bin/bash

KSRC=$1
KOBJ=$2
DEST=$3

if [ -z "$KSRC" ] || [ -z "$KOBJ" ] || [ -z "$DEST" ]; then
  echo "Usage: $0 <ksrc directory> <kobj directory> <output.tar.gz>" >&2
  exit 1
fi

KSRC=$(cd $KSRC; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
KOBJ=$(cd $KOBJ; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)

find $KSRC $KOBJ \( -name '*.gcno' -o -name '*.[ch]' -o -type l \) -a \
                 -perm /u+r,g+r | tar cfz $DEST -P -T -

if [ $? -eq 0 ] ; then
  echo "$DEST successfully created, copy to test system and unpack with:"
  echo "  tar xfz $DEST -P"
else
  echo "Could not create file $DEST"
fi

부록 B: gather_on_test.sh

258-285

부록 B: gather_on_test.sh

test machine에서 coverage data file을 수집하는 예제 스크립트입니다. '분리된 build machine과 test machine b.'를 참조하십시오.

#!/bin/bash -e

DEST=$1
GCDA=/sys/kernel/debug/gcov

if [ -z "$DEST" ] ; then
  echo "Usage: $0 <output.tar.gz>" >&2
  exit 1
fi

TEMPDIR=$(mktemp -d)
echo Collecting data..
find $GCDA -type d -exec mkdir -p $TEMPDIR/\{\} \;
find $GCDA -name '*.gcda' -exec sh -c 'cat < $0 > '$TEMPDIR'/$0' {} \;
find $GCDA -name '*.gcno' -exec sh -c 'cp -d $0 '$TEMPDIR'/$0' {} \;
tar czf $DEST -C $TEMPDIR sys
rm -rf $TEMPDIR

echo "$DEST successfully created, copy to build system and unpack with:"
echo "  tar xfz $DEST"