요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
Using gcov with the Linux kernel
================================
gcov profiling kernel support enables the use of GCC's coverage testing
tool gcov_ with the Linux kernel. Coverage data of a running kernel
is exported in gcov-compatible format via the "gcov" debugfs directory.
To get coverage data for a specific file, change to the kernel build
directory and use gcov with the ``-o`` option as follows (requires root)::
# cd /tmp/linux-out
# gcov -o /sys/kernel/debug/gcov/tmp/linux-out/kernel spinlock.c
This will create source code files annotated with execution counts
in the current directory. In addition, graphical gcov front-ends such
as lcov_ can be used to automate the process of collecting data
for the entire kernel and provide coverage overviews in HTML format.
Possible uses:
* debugging (has this line been reached at all?)
* test improvement (how do I change my test to cover these lines?)
* minimizing kernel configurations (do I need this option if the
associated code is never run?)
.. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
.. _lcov: https://github.com/linux-test-project/lcov
Preparation
-----------
Configure the kernel with::
CONFIG_DEBUG_FS=y
CONFIG_GCOV_KERNEL=y
and to get coverage data for the entire kernel::
CONFIG_GCOV_PROFILE_ALL=y
Note that kernels compiled with profiling flags will be significantly
larger and run slower. Also CONFIG_GCOV_PROFILE_ALL may not be supported
on all architectures.
Profiling data will only become accessible once debugfs has been
mounted::
mount -t debugfs none /sys/kernel/debug
Customization
-------------
To enable profiling for specific files or directories, add a line
similar to the following to the respective kernel Makefile:
- For a single file (e.g. main.o)::
GCOV_PROFILE_main.o := y
- For all files in one directory::
GCOV_PROFILE := y
To exclude files from being profiled even when CONFIG_GCOV_PROFILE_ALL
is specified, use::
GCOV_PROFILE_main.o := n
and::
GCOV_PROFILE := n
Only files which are linked to the main kernel image or are compiled as
kernel modules are supported by this mechanism.
Module specific configs
-----------------------
Gcov kernel configs for specific modules are described below:
CONFIG_GCOV_PROFILE_RDS:
Enables GCOV profiling on RDS for checking which functions or
lines are executed. This config is used by the rds selftest to
generate coverage reports. If left unset the report is omitted.
Files
-----
The gcov kernel support creates the following files in debugfs:
``/sys/kernel/debug/gcov``
Parent directory for all gcov-related files.
``/sys/kernel/debug/gcov/reset``
Global reset file: resets all coverage data to zero when
written to.
``/sys/kernel/debug/gcov/path/to/compile/dir/file.gcda``
The actual gcov data file as understood by the gcov
tool. Resets file coverage data to zero when written to.
``/sys/kernel/debug/gcov/path/to/compile/dir/file.gcno``
Symbolic link to a static data file required by the gcov
tool. This file is generated by gcc when compiling with
option ``-ftest-coverage``.
Modules
-------
Kernel modules may contain cleanup code which is only run during
module unload time. The gcov mechanism provides a means to collect
coverage data for such code by keeping a copy of the data associated
with the unloaded module. This data remains available through debugfs.
Once the module is loaded again, the associated coverage counters are
initialized with the data from its previous instantiation.
This behavior can be deactivated by specifying the gcov_persist kernel
parameter::
gcov_persist=0
At run-time, a user can also choose to discard data for an unloaded
module by writing to its data file or the global reset file.
Separated build and test machines
---------------------------------
The gcov kernel profiling infrastructure is designed to work out-of-the
box for setups where kernels are built and run on the same machine. In
cases where the kernel runs on a separate machine, special preparations
must be made, depending on where the gcov tool is used:
.. _gcov-test:
a) gcov is run on the TEST machine
The gcov tool version on the test machine must be compatible with the
gcc version used for kernel build. Also the following files need to be
copied from build to test machine:
from the source tree:
- all C source files + headers
from the build tree:
- all C source files + headers
- all .gcda and .gcno files
- all links to directories
It is important to note that these files need to be placed into the
exact same file system location on the test machine as on the build
machine. If any of the path components is symbolic link, the actual
directory needs to be used instead (due to make's CURDIR handling).
.. _gcov-build:
b) gcov is run on the BUILD machine
The following files need to be copied after each test case from test
to build machine:
from the gcov directory in sysfs:
- all .gcda files
- all links to .gcno files
These files can be copied to any location on the build machine. gcov
must then be called with the -o option pointing to that directory.
Example directory setup on the build machine::
/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
Note on compilers
-----------------
GCC and LLVM gcov tools are not necessarily compatible. Use gcov_ to work with
GCC-generated .gcno and .gcda files, and use llvm-cov_ for Clang.
.. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
.. _llvm-cov: https://llvm.org/docs/CommandGuide/llvm-cov.html
Build differences between GCC and Clang gcov are handled by Kconfig. It
automatically selects the appropriate gcov format depending on the detected
toolchain.
Troubleshooting
---------------
Problem
Compilation aborts during linker step.
Cause
Profiling flags are specified for source files which are not
linked to the main kernel or which are linked by a custom
linker procedure.
Solution
Exclude affected source files from profiling by specifying
``GCOV_PROFILE := n`` or ``GCOV_PROFILE_basename.o := n`` in the
corresponding Makefile.
Problem
Files copied from sysfs appear empty or incomplete.
Cause
Due to the way seq_file works, some tools such as cp or tar
may not correctly copy files from sysfs.
Solution
Use ``cat`` to read ``.gcda`` files and ``cp -d`` to copy links.
Alternatively use the mechanism shown in Appendix B.
Appendix A: gather_on_build.sh
------------------------------
Sample script to gather coverage meta files on the build machine
(see :ref:`Separated build and test machines a. <gcov-test>`):
.. code-block:: sh
#!/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
Appendix B: gather_on_test.sh
-----------------------------
Sample script to gather coverage data files on the test machine
(see :ref:`Separated build and test machines b. <gcov-build>`):
.. code-block:: sh
#!/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"
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Linux 커널에서 gcov 사용
1-28Linux 커널에서 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"
요약과 해설
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 특성을 고려해 안전하게 수집해야 합니다.