← Documents Documentation/trace/kprobetrace.rst GitHub 원문 ↗

Linux 6.18.37 · Tracing

Kprobe 기반 Event Tracing

Kprobe event 정의 문법, fetcharg와 type, user memory 접근, event filter·profile·boot parameter 및 entry·return probe 사용 예제를 설명합니다.

Source pathDocumentation/trace/kprobetrace.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

kprobetrace.rst:1-285

Kprobe event 정의 문법, fetcharg와 type, user memory 접근, event filter·profile·boot parameter 및 entry·return probe 사용 예제를 설명합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ==========================
2 Kprobe-based Event Tracing
3 ==========================
4
5 :Author: Masami Hiramatsu
6
7 Overview
8 --------
9 These events are similar to tracepoint-based events. Instead of tracepoints,
10 this is based on kprobes (kprobe and kretprobe). So it can probe wherever
11 kprobes can probe (this means, all functions except those with
12 __kprobes/nokprobe_inline annotation and those marked NOKPROBE_SYMBOL).
13 Unlike the tracepoint-based event, this can be added and removed
14 dynamically, on the fly.
15
16 To enable this feature, build your kernel with CONFIG_KPROBE_EVENTS=y.
17
18 Similar to the event tracer, this doesn't need to be activated via
19 current_tracer. Instead of that, add probe points via
20 /sys/kernel/tracing/kprobe_events, and enable it via
21 /sys/kernel/tracing/events/kprobes/<EVENT>/enable.
22
23 You can also use /sys/kernel/tracing/dynamic_events instead of
24 kprobe_events. That interface will provide unified access to other
25 dynamic events too.
26
27 Synopsis of kprobe_events
28 -------------------------
29 ::
30
31 p[:[GRP/][EVENT]] [MOD:]SYM[+offs]|MEMADDR [FETCHARGS] : Set a probe
32 r[MAXACTIVE][:[GRP/][EVENT]] [MOD:]SYM[+0] [FETCHARGS] : Set a return probe
33 p[:[GRP/][EVENT]] [MOD:]SYM[+0]%return [FETCHARGS] : Set a return probe
34 -:[GRP/][EVENT] : Clear a probe
35
36 GRP : Group name. If omitted, use "kprobes" for it.
37 EVENT : Event name. If omitted, the event name is generated
38 based on SYM+offs or MEMADDR.
39 MOD : Module name which has given SYM.
40 SYM[+offs] : Symbol+offset where the probe is inserted.
41 SYM%return : Return address of the symbol
42 MEMADDR : Address where the probe is inserted.
43 MAXACTIVE : Maximum number of instances of the specified function that
44 can be probed simultaneously, or 0 for the default value
45 as defined in Documentation/trace/kprobes.rst section 1.3.1.
46
47 FETCHARGS : Arguments. Each probe can have up to 128 args.
48 %REG : Fetch register REG
49 @ADDR : Fetch memory at ADDR (ADDR should be in kernel)
50 @SYM[+|-offs] : Fetch memory at SYM +|- offs (SYM should be a data symbol)
51 $stackN : Fetch Nth entry of stack (N >= 0)
52 $stack : Fetch stack address.
53 $argN : Fetch the Nth function argument. (N >= 1) (\*1)
54 $retval : Fetch return value.(\*2)
55 $comm : Fetch current task comm.
56 +|-[u]OFFS(FETCHARG) : Fetch memory at FETCHARG +|- OFFS address.(\*3)(\*4)
57 \IMM : Store an immediate value to the argument.
58 NAME=FETCHARG : Set NAME as the argument name of FETCHARG.
59 FETCHARG:TYPE : Set TYPE as the type of FETCHARG. Currently, basic types
60 (u8/u16/u32/u64/s8/s16/s32/s64), hexadecimal types
61 (x8/x16/x32/x64), VFS layer common type(%pd/%pD), "char",
62 "string", "ustring", "symbol", "symstr" and bitfield are
63 supported.
64
65 (\*1) only for the probe on function entry (offs == 0). Note, this argument access
66 is best effort, because depending on the argument type, it may be passed on
67 the stack. But this only support the arguments via registers.
68 (\*2) only for return probe. Note that this is also best effort. Depending on the
69 return value type, it might be passed via a pair of registers. But this only
70 accesses one register.
71 (\*3) this is useful for fetching a field of data structures.
72 (\*4) "u" means user-space dereference. See :ref:`user_mem_access`.
73
74 Function arguments at kretprobe
75 -------------------------------
76 Function arguments can be accessed at kretprobe using $arg<N> fetcharg. This
77 is useful to record the function parameter and return value at once, and
78 trace the difference of structure fields (for debugging a function whether it
79 correctly updates the given data structure or not).
80 See the :ref:`sample<fprobetrace_exit_args_sample>` in fprobe event for how
81 it works.
82
83 .. _kprobetrace_types:
84
85 Types
86 -----
87 Several types are supported for fetchargs. Kprobe tracer will access memory
88 by given type. Prefix 's' and 'u' means those types are signed and unsigned
89 respectively. 'x' prefix implies it is unsigned. Traced arguments are shown
90 in decimal ('s' and 'u') or hexadecimal ('x'). Without type casting, 'x32'
91 or 'x64' is used depends on the architecture (e.g. x86-32 uses x32, and
92 x86-64 uses x64).
93
94 These value types can be an array. To record array data, you can add '[N]'
95 (where N is a fixed number, less than 64) to the base type.
96 E.g. 'x16[4]' means an array of x16 (2-byte hex) with 4 elements.
97 Note that the array can be applied to memory type fetchargs, you can not
98 apply it to registers/stack-entries etc. (for example, '$stack1:x8[8]' is
99 wrong, but '+8($stack):x8[8]' is OK.)
100
101 Char type can be used to show the character value of traced arguments.
102
103 String type is a special type, which fetches a "null-terminated" string from
104 kernel space. This means it will fail and store NULL if the string container
105 has been paged out. "ustring" type is an alternative of string for user-space.
106 See :ref:`user_mem_access` for more info.
107
108 The string array type is a bit different from other types. For other base
109 types, <base-type>[1] is equal to <base-type> (e.g. +0(%di):x32[1] is same
110 as +0(%di):x32.) But string[1] is not equal to string. The string type itself
111 represents "char array", but string array type represents "char * array".
112 So, for example, +0(%di):string[1] is equal to +0(+0(%di)):string.
113 Bitfield is another special type, which takes 3 parameters, bit-width, bit-
114 offset, and container-size (usually 32). The syntax is::
115
116 b<bit-width>@<bit-offset>/<container-size>
117
118 Symbol type('symbol') is an alias of u32 or u64 type (depends on BITS_PER_LONG)
119 which shows given pointer in "symbol+offset" style.
120 On the other hand, symbol-string type ('symstr') converts the given address to
121 "symbol+offset/symbolsize" style and stores it as a null-terminated string.
122 With 'symstr' type, you can filter the event with wildcard pattern of the
123 symbols, and you don't need to solve symbol name by yourself.
124 For $comm, the default type is "string"; any other type is invalid.
125
126 VFS layer common type(%pd/%pD) is a special type, which fetches dentry's or
127 file's name from struct dentry's address or struct file's address.
128
129 .. _user_mem_access:
130
131 User Memory Access
132 ------------------
133 Kprobe events supports user-space memory access. For that purpose, you can use
134 either user-space dereference syntax or 'ustring' type.
135
136 The user-space dereference syntax allows you to access a field of a data
137 structure in user-space. This is done by adding the "u" prefix to the
138 dereference syntax. For example, +u4(%si) means it will read memory from the
139 address in the register %si offset by 4, and the memory is expected to be in
140 user-space. You can use this for strings too, e.g. +u0(%si):string will read
141 a string from the address in the register %si that is expected to be in user-
142 space. 'ustring' is a shortcut way of performing the same task. That is,
143 +0(%si):ustring is equivalent to +u0(%si):string.
144
145 Note that kprobe-event provides the user-memory access syntax but it doesn't
146 use it transparently. This means if you use normal dereference or string type
147 for user memory, it might fail, and may always fail on some architectures. The
148 user has to carefully check if the target data is in kernel or user space.
149
150 Per-Probe Event Filtering
151 -------------------------
152 Per-probe event filtering feature allows you to set different filter on each
153 probe and gives you what arguments will be shown in trace buffer. If an event
154 name is specified right after 'p:' or 'r:' in kprobe_events, it adds an event
155 under tracing/events/kprobes/<EVENT>, at the directory you can see 'id',
156 'enable', 'format', 'filter' and 'trigger'.
157
158 enable:
159 You can enable/disable the probe by writing 1 or 0 on it.
160
161 format:
162 This shows the format of this probe event.
163
164 filter:
165 You can write filtering rules of this event.
166
167 id:
168 This shows the id of this probe event.
169
170 trigger:
171 This allows to install trigger commands which are executed when the event is
172 hit (for details, see Documentation/trace/events.rst, section 6).
173
174 Event Profiling
175 ---------------
176 You can check the total number of probe hits and probe miss-hits via
177 /sys/kernel/tracing/kprobe_profile.
178 The first column is event name, the second is the number of probe hits,
179 the third is the number of probe miss-hits.
180
181 Kernel Boot Parameter
182 ---------------------
183 You can add and enable new kprobe events when booting up the kernel by
184 "kprobe_event=" parameter. The parameter accepts a semicolon-delimited
185 kprobe events, which format is similar to the kprobe_events.
186 The difference is that the probe definition parameters are comma-delimited
187 instead of space. For example, adding myprobe event on do_sys_open like below::
188
189 p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)
190
191 should be below for kernel boot parameter (just replace spaces with comma)::
192
193 p:myprobe,do_sys_open,dfd=%ax,filename=%dx,flags=%cx,mode=+4($stack)
194
195
196 Usage examples
197 --------------
198 To add a probe as a new event, write a new definition to kprobe_events
199 as below::
200
201 echo 'p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)' > /sys/kernel/tracing/kprobe_events
202
203 This sets a kprobe on the top of do_sys_open() function with recording
204 1st to 4th arguments as "myprobe" event. Note, which register/stack entry is
205 assigned to each function argument depends on arch-specific ABI. If you unsure
206 the ABI, please try to use probe subcommand of perf-tools (you can find it
207 under tools/perf/).
208 As this example shows, users can choose more familiar names for each arguments.
209 ::
210
211 echo 'r:myretprobe do_sys_open $retval' >> /sys/kernel/tracing/kprobe_events
212
213 This sets a kretprobe on the return point of do_sys_open() function with
214 recording return value as "myretprobe" event.
215 You can see the format of these events via
216 /sys/kernel/tracing/events/kprobes/<EVENT>/format.
217 ::
218
219 cat /sys/kernel/tracing/events/kprobes/myprobe/format
220 name: myprobe
221 ID: 780
222 format:
223 field:unsigned short common_type; offset:0; size:2; signed:0;
224 field:unsigned char common_flags; offset:2; size:1; signed:0;
225 field:unsigned char common_preempt_count; offset:3; size:1;signed:0;
226 field:int common_pid; offset:4; size:4; signed:1;
227
228 field:unsigned long __probe_ip; offset:12; size:4; signed:0;
229 field:int __probe_nargs; offset:16; size:4; signed:1;
230 field:unsigned long dfd; offset:20; size:4; signed:0;
231 field:unsigned long filename; offset:24; size:4; signed:0;
232 field:unsigned long flags; offset:28; size:4; signed:0;
233 field:unsigned long mode; offset:32; size:4; signed:0;
234
235
236 print fmt: "(%lx) dfd=%lx filename=%lx flags=%lx mode=%lx", REC->__probe_ip,
237 REC->dfd, REC->filename, REC->flags, REC->mode
238
239 You can see that the event has 4 arguments as in the expressions you specified.
240 ::
241
242 echo > /sys/kernel/tracing/kprobe_events
243
244 This clears all probe points.
245
246 Or,
247 ::
248
249 echo -:myprobe >> kprobe_events
250
251 This clears probe points selectively.
252
253 Right after definition, each event is disabled by default. For tracing these
254 events, you need to enable it.
255 ::
256
257 echo 1 > /sys/kernel/tracing/events/kprobes/myprobe/enable
258 echo 1 > /sys/kernel/tracing/events/kprobes/myretprobe/enable
259
260 Use the following command to start tracing in an interval.
261 ::
262
263 # echo 1 > tracing_on
264 Open something...
265 # echo 0 > tracing_on
266
267 And you can see the traced information via /sys/kernel/tracing/trace.
268 ::
269
270 cat /sys/kernel/tracing/trace
271 # tracer: nop
272 #
273 # TASK-PID CPU# TIMESTAMP FUNCTION
274 # | | | | |
275 <...>-1447 [001] 1038282.286875: myprobe: (do_sys_open+0x0/0xd6) dfd=3 filename=7fffd1ec4440 flags=8000 mode=0
276 <...>-1447 [001] 1038282.286878: myretprobe: (sys_openat+0xc/0xe <- do_sys_open) $retval=fffffffffffffffe
277 <...>-1447 [001] 1038282.286885: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=40413c flags=8000 mode=1b6
278 <...>-1447 [001] 1038282.286915: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3
279 <...>-1447 [001] 1038282.286969: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=4041c6 flags=98800 mode=10
280 <...>-1447 [001] 1038282.286976: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3
281
282
283 Each line shows when the kernel hits an event, and <- SYMBOL means kernel
284 returns from SYMBOL(e.g. "sys_open+0x1b/0x1d <- do_sys_open" means kernel
285 returns from do_sys_open to sys_open+0x1b).
286

3. 한국어 전문 번역

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

개요와 활성화

1-26

Kprobe event는 tracepoint event와 비슷하지만 tracepoint 대신 kprobe와 kretprobe를 기반으로 한다. 따라서 `__kprobes`·`nokprobe_inline` annotation이 있거나 `NOKPROBE_SYMBOL`로 표시된 function을 제외하면 Kprobes가 허용하는 모든 위치를 probe할 수 있다. 정적 tracepoint event와 달리 실행 중 동적으로 추가·제거할 수 있다.

기능을 사용하려면 `CONFIG_KPROBE_EVENTS=y`로 kernel을 build한다. Event tracer처럼 `current_tracer`로 활성화할 필요는 없다. `/sys/kernel/tracing/kprobe_events`에 probe point를 추가하고 `/sys/kernel/tracing/events/kprobes/<EVENT>/enable`로 event를 켠다.

`kprobe_events` 대신 `/sys/kernel/tracing/dynamic_events`를 사용해도 된다. 이 interface는 다른 dynamic event까지 통합해 접근하게 한다.

Kprobe event 활성화
CONFIG_KPROBE_EVENTS=ykprobe_events / dynamic_events
Probe definitionevents/kprobes/<EVENT>
enable=1trace buffer 기록

정의 파일과 event directory를 분리해 동적 probe를 만들고 기록을 켠다.

==========================
Kprobe-based Event Tracing
==========================

:Author: Masami Hiramatsu

Overview
--------
These events are similar to tracepoint-based events. Instead of tracepoints,
this is based on kprobes (kprobe and kretprobe). So it can probe wherever
kprobes can probe (this means, all functions except those with
__kprobes/nokprobe_inline annotation and those marked NOKPROBE_SYMBOL).
Unlike the tracepoint-based event, this can be added and removed
dynamically, on the fly.

To enable this feature, build your kernel with CONFIG_KPROBE_EVENTS=y.

Similar to the event tracer, this doesn't need to be activated via
current_tracer. Instead of that, add probe points via
/sys/kernel/tracing/kprobe_events, and enable it via
/sys/kernel/tracing/events/kprobes/<EVENT>/enable.

You can also use /sys/kernel/tracing/dynamic_events instead of
kprobe_events. That interface will provide unified access to other
dynamic events too.

`kprobe_events` 문법과 fetcharg

27-73
::

  p[:[GRP/][EVENT]] [MOD:]SYM[+offs]|MEMADDR [FETCHARGS]	: Set a probe
  r[MAXACTIVE][:[GRP/][EVENT]] [MOD:]SYM[+0] [FETCHARGS]	: Set a return probe
  p[:[GRP/][EVENT]] [MOD:]SYM[+0]%return [FETCHARGS]	: Set a return probe
  -:[GRP/][EVENT]						: Clear a probe

 GRP		: Group name. If omitted, use "kprobes" for it.
 EVENT		: Event name. If omitted, the event name is generated
		  based on SYM+offs or MEMADDR.
 MOD		: Module name which has given SYM.
 SYM[+offs]	: Symbol+offset where the probe is inserted.
 SYM%return	: Return address of the symbol
 MEMADDR	: Address where the probe is inserted.
 MAXACTIVE	: Maximum number of instances of the specified function that
		  can be probed simultaneously, or 0 for the default value
		  as defined in Documentation/trace/kprobes.rst section 1.3.1.

 FETCHARGS	: Arguments. Each probe can have up to 128 args.
  %REG		: Fetch register REG
  @ADDR		: Fetch memory at ADDR (ADDR should be in kernel)
  @SYM[+|-offs]	: Fetch memory at SYM +|- offs (SYM should be a data symbol)
  $stackN	: Fetch Nth entry of stack (N >= 0)
  $stack	: Fetch stack address.
  $argN		: Fetch the Nth function argument. (N >= 1) (\*1)
  $retval	: Fetch return value.(\*2)
  $comm		: Fetch current task comm.
  +|-[u]OFFS(FETCHARG) : Fetch memory at FETCHARG +|- OFFS address.(\*3)(\*4)
  \IMM		: Store an immediate value to the argument.
  NAME=FETCHARG : Set NAME as the argument name of FETCHARG.
  FETCHARG:TYPE : Set TYPE as the type of FETCHARG. Currently, basic types
		  (u8/u16/u32/u64/s8/s16/s32/s64), hexadecimal types
		  (x8/x16/x32/x64), VFS layer common type(%pd/%pD), "char",
                  "string", "ustring", "symbol", "symstr" and bitfield are
                  supported.

`p`는 일반 probe, `r[MAXACTIVE]` 또는 `%return`은 return probe를 만들고 `-:`는 지정 event를 지운다. Group을 생략하면 `kprobes`를 사용하며 event 이름을 생략하면 symbol·offset 또는 memory address에서 자동 생성한다. `MOD:`는 symbol이 속한 module을 지정한다.

`MAXACTIVE`는 동시에 추적할 function instance 최대 수이며 0은 `Documentation/trace/kprobes.rst`에 정의된 기본값을 사용한다. Probe마다 fetch argument를 최대 128개 지정할 수 있다.

Kprobe fetcharg
문법가져오는 값
`%REG`Register REG
`@ADDR`, `@SYM+offs`Kernel memory
`$stackN`, `$stack`Stack entry 또는 stack address
`$argN`Function entry argument, register 전달분에 한한 best effort
`$retval`Return probe의 return value, 단일 register best effort
`$comm`Current task comm
`+|-OFFS(FETCHARG)`Data structure field memory
`+|-uOFFS(FETCHARG)`User-space memory dereference
`\IMM`Immediate value
`NAME=FETCHARG:TYPE`Field 이름과 type 지정

Register, stack, memory, function argument와 return value를 event field로 가져온다.

`$argN`은 function entry와 offset 0에서만, `$retval`은 return probe에서만 쓸 수 있다. 두 접근 모두 ABI와 value type에 따라 register 하나로는 완전하지 않을 수 있다. Dereference의 `u`는 user-space address를 뜻한다.

Synopsis of kprobe_events
-------------------------
::

  p[:[GRP/][EVENT]] [MOD:]SYM[+offs]|MEMADDR [FETCHARGS]	: Set a probe
  r[MAXACTIVE][:[GRP/][EVENT]] [MOD:]SYM[+0] [FETCHARGS]	: Set a return probe
  p[:[GRP/][EVENT]] [MOD:]SYM[+0]%return [FETCHARGS]	: Set a return probe
  -:[GRP/][EVENT]						: Clear a probe

 GRP		: Group name. If omitted, use "kprobes" for it.
 EVENT		: Event name. If omitted, the event name is generated
		  based on SYM+offs or MEMADDR.
 MOD		: Module name which has given SYM.
 SYM[+offs]	: Symbol+offset where the probe is inserted.
 SYM%return	: Return address of the symbol
 MEMADDR	: Address where the probe is inserted.
 MAXACTIVE	: Maximum number of instances of the specified function that
		  can be probed simultaneously, or 0 for the default value
		  as defined in Documentation/trace/kprobes.rst section 1.3.1.

 FETCHARGS	: Arguments. Each probe can have up to 128 args.
  %REG		: Fetch register REG
  @ADDR		: Fetch memory at ADDR (ADDR should be in kernel)
  @SYM[+|-offs]	: Fetch memory at SYM +|- offs (SYM should be a data symbol)
  $stackN	: Fetch Nth entry of stack (N >= 0)
  $stack	: Fetch stack address.
  $argN		: Fetch the Nth function argument. (N >= 1) (\*1)
  $retval	: Fetch return value.(\*2)
  $comm		: Fetch current task comm.
  +|-[u]OFFS(FETCHARG) : Fetch memory at FETCHARG +|- OFFS address.(\*3)(\*4)
  \IMM		: Store an immediate value to the argument.
  NAME=FETCHARG : Set NAME as the argument name of FETCHARG.
  FETCHARG:TYPE : Set TYPE as the type of FETCHARG. Currently, basic types
		  (u8/u16/u32/u64/s8/s16/s32/s64), hexadecimal types
		  (x8/x16/x32/x64), VFS layer common type(%pd/%pD), "char",
                  "string", "ustring", "symbol", "symstr" and bitfield are
                  supported.

  (\*1) only for the probe on function entry (offs == 0). Note, this argument access
        is best effort, because depending on the argument type, it may be passed on
        the stack. But this only support the arguments via registers.
  (\*2) only for return probe. Note that this is also best effort. Depending on the
        return value type, it might be passed via a pair of registers. But this only
        accesses one register.
  (\*3) this is useful for fetching a field of data structures.
  (\*4) "u" means user-space dereference. See :ref:`user_mem_access`.

Function argument와 fetcharg type

74-128

Kretprobe에서도 `$argN`으로 function argument를 가져올 수 있다. Parameter와 return value를 한 event에서 기록하거나 function이 data structure field를 올바르게 갱신했는지 전후 차이를 추적할 때 유용하다. 동작 예는 fprobe exit-argument sample을 참조한다.

Fetcharg type의 `s`와 `u` prefix는 signed·unsigned decimal, `x`는 unsigned hexadecimal 출력을 뜻한다. Cast가 없으면 architecture에 따라 `x32` 또는 `x64`를 사용한다.

Base type 뒤에 `[N]`을 붙이면 64개 미만의 고정 길이 array를 기록한다. 예를 들어 `x16[4]`는 2-byte hexadecimal element 4개다. Array는 memory fetcharg에만 적용할 수 있어 `$stack1:x8[8]`은 틀리고 `+8($stack):x8[8]`은 유효하다.

`char`는 character value를 표시한다. `string`은 kernel space의 null-terminated string을 가져오며 page-out된 container에서는 실패해 `NULL`을 저장한다. User space에는 `ustring`을 사용한다.

`string[1]`은 일반 base type array와 달리 `string`과 같지 않다. `string`은 char array를, string array는 `char *` array를 나타낸다. 따라서 `+0(%di):string[1]`은 `+0(+0(%di)):string`과 같다.

Bitfield is another special type, which takes 3 parameters, bit-width, bit-
offset, and container-size (usually 32). The syntax is::

 b<bit-width>@<bit-offset>/<container-size>

Bitfield type은 bit width, bit offset, 보통 32인 container size를 받는다. `symbol`은 `BITS_PER_LONG`에 따른 u32/u64 alias이며 pointer를 `symbol+offset`으로 표시한다. `symstr`은 address를 `symbol+offset/symbolsize` 문자열로 변환해 wildcard symbol filter를 가능하게 한다.

`$comm`의 기본 type은 `string`이고 다른 type은 사용할 수 없다. `%pd`와 `%pD`는 각각 `struct dentry`와 `struct file` address에서 VFS layer name을 가져온다.

Fetcharg 특수 type
Type의미
`char`Character value
`string` / `ustring`Kernel / user null-terminated string
`symbol`Pointer를 symbol+offset으로 표시
`symstr`Symbol 표현을 문자열로 저장해 wildcard filtering
`bW@O/C`Bit width W, offset O, container C의 bitfield
`%pd` / `%pD`dentry / file name

일반 integer 외에 문자열·symbol·VFS object를 해석하는 type이다.

Function arguments at kretprobe
-------------------------------
Function arguments can be accessed at kretprobe using $arg<N> fetcharg. This
is useful to record the function parameter and return value at once, and
trace the difference of structure fields (for debugging a function whether it
correctly updates the given data structure or not).
See the :ref:`sample<fprobetrace_exit_args_sample>` in fprobe event for how
it works.

.. _kprobetrace_types:

Types
-----
Several types are supported for fetchargs. Kprobe tracer will access memory
by given type. Prefix 's' and 'u' means those types are signed and unsigned
respectively. 'x' prefix implies it is unsigned. Traced arguments are shown
in decimal ('s' and 'u') or hexadecimal ('x'). Without type casting, 'x32'
or 'x64' is used depends on the architecture (e.g. x86-32 uses x32, and
x86-64 uses x64).

These value types can be an array. To record array data, you can add '[N]'
(where N is a fixed number, less than 64) to the base type.
E.g. 'x16[4]' means an array of x16 (2-byte hex) with 4 elements.
Note that the array can be applied to memory type fetchargs, you can not
apply it to registers/stack-entries etc. (for example, '$stack1:x8[8]' is
wrong, but '+8($stack):x8[8]' is OK.)

Char type can be used to show the character value of traced arguments.

String type is a special type, which fetches a "null-terminated" string from
kernel space. This means it will fail and store NULL if the string container
has been paged out. "ustring" type is an alternative of string for user-space.
See :ref:`user_mem_access` for more info.

The string array type is a bit different from other types. For other base
types, <base-type>[1] is equal to <base-type> (e.g. +0(%di):x32[1] is same
as +0(%di):x32.) But string[1] is not equal to string. The string type itself
represents "char array", but string array type represents "char * array".
So, for example, +0(%di):string[1] is equal to +0(+0(%di)):string.
Bitfield is another special type, which takes 3 parameters, bit-width, bit-
offset, and container-size (usually 32). The syntax is::

 b<bit-width>@<bit-offset>/<container-size>

Symbol type('symbol') is an alias of u32 or u64 type (depends on BITS_PER_LONG)
which shows given pointer in "symbol+offset" style.
On the other hand, symbol-string type ('symstr') converts the given address to
"symbol+offset/symbolsize" style and stores it as a null-terminated string.
With 'symstr' type, you can filter the event with wildcard pattern of the
symbols, and you don't need to solve symbol name by yourself.
For $comm, the default type is "string"; any other type is invalid.

VFS layer common type(%pd/%pD) is a special type, which fetches dentry's or
file's name from struct dentry's address or struct file's address.

User memory 접근

129-149

Kprobe event는 user-space dereference 문법과 `ustring` type으로 user memory를 읽는다. Dereference 앞에 `u`를 붙이면 user-space data structure field를 뜻한다.

예를 들어 `+u4(%si)`는 `%si + 4`의 user memory를 읽는다. `+u0(%si):string`은 `%si`가 가리키는 user string을 읽고, `+0(%si):ustring`도 같은 의미다.

Interface가 user-memory 문법을 제공한다고 해서 일반 dereference를 자동 변환하지는 않는다. User address에 일반 dereference나 `string`을 사용하면 실패할 수 있고 일부 architecture에서는 항상 실패한다. 대상 data가 kernel space인지 user space인지 사용자가 확인해야 한다.

User memory fetcharg 선택
Target address 확인Kernel or user
Kernel+OFFS():string
User+uOFFS():string
User shortcut+OFFS():ustring

Address 공간을 명시해 올바른 fault-safe 접근 방식을 선택한다.

.. _user_mem_access:

User Memory Access
------------------
Kprobe events supports user-space memory access. For that purpose, you can use
either user-space dereference syntax or 'ustring' type.

The user-space dereference syntax allows you to access a field of a data
structure in user-space. This is done by adding the "u" prefix to the
dereference syntax. For example, +u4(%si) means it will read memory from the
address in the register %si offset by 4, and the memory is expected to be in
user-space. You can use this for strings too, e.g. +u0(%si):string will read
a string from the address in the register %si that is expected to be in user-
space. 'ustring' is a shortcut way of performing the same task. That is,
+0(%si):ustring is equivalent to +u0(%si):string.

Note that kprobe-event provides the user-memory access syntax but it doesn't
use it transparently. This means if you use normal dereference or string type
for user memory, it might fail, and may always fail on some architectures. The
user has to carefully check if the target data is in kernel or user space.

Probe별 filter와 profiling

150-180

`p:`나 `r:` 바로 뒤에 event 이름을 지정하면 `tracing/events/kprobes/<EVENT>` directory가 생기고 각 probe에 서로 다른 filter를 적용할 수 있다. Directory에는 `id`, `enable`, `format`, `filter`, `trigger`가 있다.

Kprobe event 파일
파일역할
`enable`1/0으로 probe 활성화·비활성화
`format`Probe event field format 표시
`filter`Event filtering rule 설정
`id`Probe event id 표시
`trigger`Event hit 때 실행할 trigger command 설치

Event별 recording, schema, filtering과 action을 제어한다.

`/sys/kernel/tracing/kprobe_profile`은 event별 총 probe hit와 miss-hit를 보여 준다. 첫 column은 event 이름, 둘째는 hit 수, 셋째는 miss-hit 수다.

Per-Probe Event Filtering
-------------------------
Per-probe event filtering feature allows you to set different filter on each
probe and gives you what arguments will be shown in trace buffer. If an event
name is specified right after 'p:' or 'r:' in kprobe_events, it adds an event
under tracing/events/kprobes/<EVENT>, at the directory you can see 'id',
'enable', 'format', 'filter' and 'trigger'.

enable:
  You can enable/disable the probe by writing 1 or 0 on it.

format:
  This shows the format of this probe event.

filter:
  You can write filtering rules of this event.

id:
  This shows the id of this probe event.

trigger:
  This allows to install trigger commands which are executed when the event is
  hit (for details, see Documentation/trace/events.rst, section 6).

Event Profiling
---------------
You can check the total number of probe hits and probe miss-hits via
/sys/kernel/tracing/kprobe_profile.
The first column is event name, the second is the number of probe hits,
the third is the number of probe miss-hits.

Kernel boot parameter

181-195

Boot 때 `kprobe_event=` parameter로 새 kprobe event를 추가하고 활성화할 수 있다. 여러 event는 semicolon으로 구분하며 형식은 `kprobe_events`와 비슷하지만 정의 parameter 사이를 space 대신 comma로 구분한다.

instead of space. For example, adding myprobe event on do_sys_open like below::

  p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)

should be below for kernel boot parameter (just replace spaces with comma)::

  p:myprobe,do_sys_open,dfd=%ax,filename=%dx,flags=%cx,mode=+4($stack)
Kprobe 정의의 boot parameter 변환
kprobe_events syntaxspace-delimited fields
Replace spacescomma-delimited fields
kprobe_event=Kernel boot registration

동일한 probe 정의에서 token separator만 space에서 comma로 바꾼다.

Kernel Boot Parameter
---------------------
You can add and enable new kprobe events when booting up the kernel by
"kprobe_event=" parameter. The parameter accepts a semicolon-delimited
kprobe events, which format is similar to the kprobe_events.
The difference is that the probe definition parameters are comma-delimited
instead of space. For example, adding myprobe event on do_sys_open like below::

  p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)

should be below for kernel boot parameter (just replace spaces with comma)::

  p:myprobe,do_sys_open,dfd=%ax,filename=%dx,flags=%cx,mode=+4($stack)

사용 예제

196-285

새 event를 만들려면 definition을 `kprobe_events`에 쓴다. 다음 예는 `do_sys_open()` entry에 `myprobe`를 설치하고 1~4번째 argument를 기록한다.

  echo 'p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)' > /sys/kernel/tracing/kprobe_events

Function argument가 어느 register나 stack entry에 배치되는지는 architecture ABI에 달려 있다. 확실하지 않으면 `tools/perf/`의 probe subcommand를 사용한다. Fetcharg에 익숙한 field 이름을 붙일 수 있다.

  echo 'r:myretprobe do_sys_open $retval' >> /sys/kernel/tracing/kprobe_events

두 번째 정의는 `do_sys_open()` return point에 `myretprobe`를 설치하고 `$retval`을 기록한다. 생성 event의 schema는 `events/kprobes/<EVENT>/format`에서 확인한다.

  cat /sys/kernel/tracing/events/kprobes/myprobe/format
  name: myprobe
  ID: 780
  format:
          field:unsigned short common_type;       offset:0;       size:2; signed:0;
          field:unsigned char common_flags;       offset:2;       size:1; signed:0;
          field:unsigned char common_preempt_count;       offset:3; size:1;signed:0;
          field:int common_pid;   offset:4;       size:4; signed:1;

          field:unsigned long __probe_ip; offset:12;      size:4; signed:0;
          field:int __probe_nargs;        offset:16;      size:4; signed:1;
          field:unsigned long dfd;        offset:20;      size:4; signed:0;
          field:unsigned long filename;   offset:24;      size:4; signed:0;
          field:unsigned long flags;      offset:28;      size:4; signed:0;
          field:unsigned long mode;       offset:32;      size:4; signed:0;


  print fmt: "(%lx) dfd=%lx filename=%lx flags=%lx mode=%lx", REC->__probe_ip,
  REC->dfd, REC->filename, REC->flags, REC->mode

Format 출력에는 정의한 네 argument가 event field와 print format으로 나타난다. `kprobe_events` 파일을 비우면 모든 probe point를 지우고, `-:myprobe`를 append하면 해당 probe만 선택적으로 지운다.

::

  echo > /sys/kernel/tracing/kprobe_events

This clears all probe points.

Or,
::

  echo -:myprobe >> kprobe_events

정의 직후 event는 기본적으로 disabled이므로 각 event의 `enable`에 1을 써야 한다.

::

  echo 1 > /sys/kernel/tracing/events/kprobes/myprobe/enable
  echo 1 > /sys/kernel/tracing/events/kprobes/myretprobe/enable

`tracing_on`을 1과 0으로 바꿔 관심 interval만 기록하고 `trace` 파일에서 결과를 읽는다.

Use the following command to start tracing in an interval.
::

    # echo 1 > tracing_on
    Open something...
    # echo 0 > tracing_on

And you can see the traced information via /sys/kernel/tracing/trace.
::

  cat /sys/kernel/tracing/trace
  # tracer: nop
  #
  #           TASK-PID    CPU#    TIMESTAMP  FUNCTION
  #              | |       |          |         |
             <...>-1447  [001] 1038282.286875: myprobe: (do_sys_open+0x0/0xd6) dfd=3 filename=7fffd1ec4440 flags=8000 mode=0
             <...>-1447  [001] 1038282.286878: myretprobe: (sys_openat+0xc/0xe <- do_sys_open) $retval=fffffffffffffffe
             <...>-1447  [001] 1038282.286885: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=40413c flags=8000 mode=1b6
             <...>-1447  [001] 1038282.286915: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3
             <...>-1447  [001] 1038282.286969: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=4041c6 flags=98800 mode=10
             <...>-1447  [001] 1038282.286976: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3

각 trace line은 kernel이 event를 hit한 시점을 보여 준다. `<- SYMBOL`은 kernel이 그 symbol에서 return했음을 뜻한다. 예를 들어 `sys_open+0x1b/0x1d <- do_sys_open`은 `do_sys_open`에서 `sys_open+0x1b`로 return했다는 의미다.

Kprobe event lifecycle
Write kprobe_eventsmyprobe / myretprobe 생성
Read formatField schema 확인
enable=1tracing_on interval
Read traceEntry + return event
-:myprobe선택적 삭제

Definition 생성부터 선택적 삭제까지 event directory를 통해 제어한다.

Usage examples
--------------
To add a probe as a new event, write a new definition to kprobe_events
as below::

  echo 'p:myprobe do_sys_open dfd=%ax filename=%dx flags=%cx mode=+4($stack)' > /sys/kernel/tracing/kprobe_events

This sets a kprobe on the top of do_sys_open() function with recording
1st to 4th arguments as "myprobe" event. Note, which register/stack entry is
assigned to each function argument depends on arch-specific ABI. If you unsure
the ABI, please try to use probe subcommand of perf-tools (you can find it
under tools/perf/).
As this example shows, users can choose more familiar names for each arguments.
::

  echo 'r:myretprobe do_sys_open $retval' >> /sys/kernel/tracing/kprobe_events

This sets a kretprobe on the return point of do_sys_open() function with
recording return value as "myretprobe" event.
You can see the format of these events via
/sys/kernel/tracing/events/kprobes/<EVENT>/format.
::

  cat /sys/kernel/tracing/events/kprobes/myprobe/format
  name: myprobe
  ID: 780
  format:
          field:unsigned short common_type;       offset:0;       size:2; signed:0;
          field:unsigned char common_flags;       offset:2;       size:1; signed:0;
          field:unsigned char common_preempt_count;       offset:3; size:1;signed:0;
          field:int common_pid;   offset:4;       size:4; signed:1;

          field:unsigned long __probe_ip; offset:12;      size:4; signed:0;
          field:int __probe_nargs;        offset:16;      size:4; signed:1;
          field:unsigned long dfd;        offset:20;      size:4; signed:0;
          field:unsigned long filename;   offset:24;      size:4; signed:0;
          field:unsigned long flags;      offset:28;      size:4; signed:0;
          field:unsigned long mode;       offset:32;      size:4; signed:0;


  print fmt: "(%lx) dfd=%lx filename=%lx flags=%lx mode=%lx", REC->__probe_ip,
  REC->dfd, REC->filename, REC->flags, REC->mode

You can see that the event has 4 arguments as in the expressions you specified.
::

  echo > /sys/kernel/tracing/kprobe_events

This clears all probe points.

Or,
::

  echo -:myprobe >> kprobe_events

This clears probe points selectively.

Right after definition, each event is disabled by default. For tracing these
events, you need to enable it.
::

  echo 1 > /sys/kernel/tracing/events/kprobes/myprobe/enable
  echo 1 > /sys/kernel/tracing/events/kprobes/myretprobe/enable

Use the following command to start tracing in an interval.
::

    # echo 1 > tracing_on
    Open something...
    # echo 0 > tracing_on

And you can see the traced information via /sys/kernel/tracing/trace.
::

  cat /sys/kernel/tracing/trace
  # tracer: nop
  #
  #           TASK-PID    CPU#    TIMESTAMP  FUNCTION
  #              | |       |          |         |
             <...>-1447  [001] 1038282.286875: myprobe: (do_sys_open+0x0/0xd6) dfd=3 filename=7fffd1ec4440 flags=8000 mode=0
             <...>-1447  [001] 1038282.286878: myretprobe: (sys_openat+0xc/0xe <- do_sys_open) $retval=fffffffffffffffe
             <...>-1447  [001] 1038282.286885: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=40413c flags=8000 mode=1b6
             <...>-1447  [001] 1038282.286915: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3
             <...>-1447  [001] 1038282.286969: myprobe: (do_sys_open+0x0/0xd6) dfd=ffffff9c filename=4041c6 flags=98800 mode=10
             <...>-1447  [001] 1038282.286976: myretprobe: (sys_open+0x1b/0x1d <- do_sys_open) $retval=3


Each line shows when the kernel hits an event, and <- SYMBOL means kernel
returns from SYMBOL(e.g. "sys_open+0x1b/0x1d <- do_sys_open" means kernel
returns from do_sys_open to sys_open+0x1b).