Debian Codegraph @

link/uprobe.go

raw symbols SCIP
1 //go:build !windows
2
3 package link
4
5 import (
6 "debug/elf"
7 "errors"
8 "fmt"
9 "os"
10 "sync"
11
12 "github.com/cilium/ebpf"
13 "github.com/cilium/ebpf/internal"
14 "github.com/cilium/ebpf/internal/tracefs"
15 )
16
17 var (
18 uprobeRefCtrOffsetPMUPath = "/sys/bus/event_source/devices/uprobe/format/ref_ctr_offset"
19 // elixir.bootlin.com/linux/v5.15-rc7/source/kernel/events/core.c#L9799
20 uprobeRefCtrOffsetShift = 32
21 haveRefCtrOffsetPMU = internal.NewFeatureTest("RefCtrOffsetPMU", func() error {
22 _, err := os.Stat(uprobeRefCtrOffsetPMUPath)
23 if errors.Is(err, os.ErrNotExist) {
24 return internal.ErrNotSupported
25 }
26 if err != nil {
27 return err
28 }
29 return nil
30 }, "4.20")
31
32 // ErrNoSymbol indicates that the given symbol was not found
33 // in the ELF symbols table.
34 ErrNoSymbol = errors.New("not found")
35 )
36
37 // Executable defines an executable program on the filesystem.
38 type Executable struct {
39 // Path of the executable on the filesystem.
40 path string
41 // Cached symbol values for all ELF and dynamic symbols.
42 // Before using this, lazyLoadSymbols() must be called.
43 cachedSymbols map[string]symbol
44 // cachedSymbolsOnce tracks the lazy load of cachedSymbols.
45 cachedSymbolsOnce sync.Once
46 }
47
48 type symbol struct {
49 addr uint64
50 size uint64
51 }
52
53 // contains returns true if the given address falls within the range
54 // covered by the symbol.
55 func (s symbol) contains(address uint64) bool {
56 return s.addr <= address && address < s.addr+s.size
57 }
58
59 // UprobeOptions defines additional parameters that will be used
60 // when loading Uprobes.
61 type UprobeOptions struct {
62 // Symbol address. Must be provided in case of external symbols (shared libs).
63 // If set, overrides the address eventually parsed from the executable.
64 Address uint64
65 // The offset relative to given symbol. Useful when tracing an arbitrary point
66 // inside the frame of given symbol.
67 //
68 // Note: this field changed from being an absolute offset to being relative
69 // to Address.
70 Offset uint64
71 // Only set the uprobe on the given process ID. Useful when tracing
72 // shared library calls or programs that have many running instances.
73 PID int
74 // Automatically manage SDT reference counts (semaphores).
75 //
76 // If this field is set, the Kernel will increment/decrement the
77 // semaphore located in the process memory at the provided address on
78 // probe attach/detach.
79 //
80 // See also:
81 // sourceware.org/systemtap/wiki/UserSpaceProbeImplementation (Semaphore Handling)
82 // github.com/torvalds/linux/commit/1cc33161a83d
83 // github.com/torvalds/linux/commit/a6ca88b241d5
84 RefCtrOffset uint64
85 // Arbitrary value that can be fetched from an eBPF program
86 // via `bpf_get_attach_cookie()`.
87 //
88 // Needs kernel 5.15+.
89 Cookie uint64
90 // Prefix used for the event name if the uprobe must be attached using tracefs.
91 // The group name will be formatted as `<prefix>_<randomstr>`.
92 // The default empty string is equivalent to "ebpf" as the prefix.
93 TraceFSPrefix string
94 }
95
96 func (uo *UprobeOptions) cookie() uint64 {
97 if uo == nil {
98 return 0
99 }
100 return uo.Cookie
101 }
102
103 // To open a new Executable, use:
104 //
105 // OpenExecutable("/bin/bash")
106 //
107 // The returned value can then be used to open Uprobe(s).
108 func OpenExecutable(path string) (*Executable, error) {
109 if path == "" {
110 return nil, fmt.Errorf("path cannot be empty")
111 }
112
113 if _, err := os.Stat(path); err != nil {
114 return nil, fmt.Errorf("stat executable: %w", err)
115 }
116
117 return &Executable{
118 path: path,
119 cachedSymbols: make(map[string]symbol),
120 }, nil
121 }
122
123 func (ex *Executable) load(f *internal.SafeELFFile) error {
124 syms, err := f.Symbols()
125 if err != nil && !errors.Is(err, elf.ErrNoSymbols) {
126 return err
127 }
128
129 dynsyms, err := f.DynamicSymbols()
130 if err != nil && !errors.Is(err, elf.ErrNoSymbols) {
131 return err
132 }
133
134 syms = append(syms, dynsyms...)
135
136 for _, s := range syms {
137 if elf.ST_TYPE(s.Info) != elf.STT_FUNC {
138 // Symbol not associated with a function or other executable code.
139 continue
140 }
141
142 address := s.Value
143
144 // Loop over ELF segments.
145 for _, prog := range f.Progs {
146 // Skip uninteresting segments.
147 if prog.Type != elf.PT_LOAD || (prog.Flags&elf.PF_X) == 0 {
148 continue
149 }
150
151 if prog.Vaddr <= s.Value && s.Value < (prog.Vaddr+prog.Memsz) {
152 // If the symbol value is contained in the segment, calculate
153 // the symbol offset.
154 //
155 // fn symbol offset = fn symbol VA - .text VA + .text offset
156 //
157 // stackoverflow.com/a/40249502
158 address = s.Value - prog.Vaddr + prog.Off
159 break
160 }
161 }
162
163 ex.cachedSymbols[s.Name] = symbol{
164 addr: address,
165 size: s.Size,
166 }
167 }
168
169 return nil
170 }
171
172 func (ex *Executable) lazyLoadSymbols() error {
173 var err error
174 ex.cachedSymbolsOnce.Do(func() {
175 var f *internal.SafeELFFile
176 f, err = internal.OpenSafeELFFile(ex.path)
177 if err != nil {
178 err = fmt.Errorf("parse ELF file: %w", err)
179 return
180 }
181 defer f.Close()
182
183 if f.Type != elf.ET_EXEC && f.Type != elf.ET_DYN {
184 // ELF is not an executable or a shared object.
185 err = errors.New("the given file is not an executable or a shared object")
186 return
187 }
188 err = ex.load(f)
189 })
190 return err
191 }
192
193 // address calculates the address of a symbol in the executable.
194 //
195 // opts must not be nil.
196 func (ex *Executable) address(symbol string, address, offset uint64) (uint64, error) {
197 if address > 0 {
198 return address + offset, nil
199 }
200
201 err := ex.lazyLoadSymbols()
202 if err != nil {
203 return 0, fmt.Errorf("lazy load symbols: %w", err)
204 }
205
206 sym, ok := ex.cachedSymbols[symbol]
207 if !ok {
208 return 0, fmt.Errorf("symbol %s: %w", symbol, ErrNoSymbol)
209 }
210
211 // Symbols with location 0 from section undef are shared library calls and
212 // are relocated before the binary is executed. Dynamic linking is not
213 // implemented by the library, so mark this as unsupported for now.
214 //
215 // Since only offset values are stored and not elf.Symbol, if the value is 0,
216 // assume it's an external symbol.
217 if sym.addr == 0 {
218 return 0, fmt.Errorf("cannot resolve %s library call '%s': %w "+
219 "(consider providing UprobeOptions.Address)", ex.path, symbol, ErrNotSupported)
220 }
221
222 if offset >= sym.size {
223 return 0, fmt.Errorf("offset %d is out of range of symbol %s", offset, symbol)
224 }
225
226 return sym.addr + offset, nil
227 }
228
229 // SymbolOffset represents an offset within a symbol within a binary.
230 type SymbolOffset struct {
231 Symbol string
232 Offset uint64
233 }
234
235 // Symbol returns the SymbolOffset that the given address points to.
236 // This includes the symbol name and the offset within that symbol.
237 //
238 // If no symbol is found for the given address, ErrNoSymbol is returned.
239 func (ex *Executable) Symbol(address uint64) (SymbolOffset, error) {
240 if err := ex.lazyLoadSymbols(); err != nil {
241 return SymbolOffset{}, fmt.Errorf("lazy load symbols: %w", err)
242 }
243
244 for name, symbol := range ex.cachedSymbols {
245 if symbol.contains(address) {
246 return SymbolOffset{name, address - symbol.addr}, nil
247 }
248 }
249 return SymbolOffset{}, ErrNoSymbol
250 }
251
252 // Uprobe attaches the given eBPF program to a perf event that fires when the
253 // given symbol starts executing in the given Executable.
254 // For example, /bin/bash::main():
255 //
256 // ex, _ = OpenExecutable("/bin/bash")
257 // ex.Uprobe("main", prog, nil)
258 //
259 // When tracing a location for which no ELF symbol is available, or a shared
260 // library symbol whose static address is zero, set UprobeOptions.Address to
261 // the absolute file offset and pass an empty symbol:
262 //
263 // up, err := ex.Uprobe("", prog, &UprobeOptions{Address: 0x123})
264 //
265 // Address bypasses symbol lookup. Offset, if set, is added to the resolved
266 // address (whether from symbol resolution or from Address); on its own it
267 // does not replace symbol resolution.
268 //
269 // Losing the reference to the resulting Link (up) will close the Uprobe
270 // and prevent further execution of prog. The Link must be Closed during
271 // program shutdown to avoid leaking system resources.
272 //
273 // Functions provided by shared libraries can currently not be traced and
274 // will result in an ErrNotSupported.
275 //
276 // The returned Link may implement [PerfEvent].
277 func (ex *Executable) Uprobe(symbol string, prog *ebpf.Program, opts *UprobeOptions) (Link, error) {
278 u, err := ex.uprobe(symbol, prog, opts, false)
279 if err != nil {
280 return nil, err
281 }
282
283 lnk, err := attachPerfEvent(u, prog, opts.cookie())
284 if err != nil {
285 u.Close()
286 return nil, err
287 }
288
289 return lnk, nil
290 }
291
292 // Uretprobe attaches the given eBPF program to a perf event that fires right
293 // before the given symbol exits. For example, /bin/bash::main():
294 //
295 // ex, _ = OpenExecutable("/bin/bash")
296 // ex.Uretprobe("main", prog, nil)
297 //
298 // When tracing a location for which no ELF symbol is available, or a shared
299 // library symbol whose static address is zero, set UprobeOptions.Address to
300 // the absolute file offset and pass an empty symbol:
301 //
302 // up, err := ex.Uretprobe("", prog, &UprobeOptions{Address: 0x123})
303 //
304 // Address bypasses symbol lookup. Offset, if set, is added to the resolved
305 // address (whether from symbol resolution or from Address); on its own it
306 // does not replace symbol resolution.
307 //
308 // Losing the reference to the resulting Link (up) will close the Uprobe
309 // and prevent further execution of prog. The Link must be Closed during
310 // program shutdown to avoid leaking system resources.
311 //
312 // Functions provided by shared libraries can currently not be traced and
313 // will result in an ErrNotSupported.
314 //
315 // The returned Link may implement [PerfEvent].
316 func (ex *Executable) Uretprobe(symbol string, prog *ebpf.Program, opts *UprobeOptions) (Link, error) {
317 u, err := ex.uprobe(symbol, prog, opts, true)
318 if err != nil {
319 return nil, err
320 }
321
322 lnk, err := attachPerfEvent(u, prog, opts.cookie())
323 if err != nil {
324 u.Close()
325 return nil, err
326 }
327
328 return lnk, nil
329 }
330
331 // uprobe opens a perf event for the given binary/symbol and attaches prog to it.
332 // If ret is true, create a uretprobe.
333 func (ex *Executable) uprobe(symbol string, prog *ebpf.Program, opts *UprobeOptions, ret bool) (*perfEvent, error) {
334 if prog == nil {
335 return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
336 }
337 if prog.Type() != ebpf.Kprobe {
338 return nil, fmt.Errorf("eBPF program type %s is not Kprobe: %w", prog.Type(), errInvalidInput)
339 }
340 if opts == nil {
341 opts = &UprobeOptions{}
342 }
343
344 offset, err := ex.address(symbol, opts.Address, opts.Offset)
345 if err != nil {
346 return nil, err
347 }
348
349 pid := opts.PID
350 if pid == 0 {
351 pid = perfAllThreads
352 }
353
354 if opts.RefCtrOffset != 0 {
355 if err := haveRefCtrOffsetPMU(); err != nil {
356 return nil, fmt.Errorf("uprobe ref_ctr_offset: %w", err)
357 }
358 }
359
360 args := tracefs.ProbeArgs{
361 Type: tracefs.Uprobe,
362 Symbol: symbol,
363 Path: ex.path,
364 Offset: offset,
365 Pid: pid,
366 RefCtrOffset: opts.RefCtrOffset,
367 Ret: ret,
368 Cookie: opts.Cookie,
369 Group: opts.TraceFSPrefix,
370 }
371
372 // Use uprobe PMU if the kernel has it available.
373 tp, err := pmuProbe(args)
374 if err == nil {
375 return tp, nil
376 }
377 if !errors.Is(err, ErrNotSupported) {
378 return nil, fmt.Errorf("creating perf_uprobe PMU: %w", err)
379 }
380
381 // Use tracefs if uprobe PMU is missing.
382 tp, err = tracefsProbe(args)
383 if err != nil {
384 return nil, fmt.Errorf("creating trace event '%s:%s' in tracefs: %w", ex.path, symbol, err)
385 }
386
387 return tp, nil
388 }