Debian Codegraph @

internal/sys/signals.go

raw symbols SCIP
1 //go:build !windows
2
3 package sys
4
5 import (
6 "fmt"
7 "runtime"
8 "unsafe"
9
10 "github.com/cilium/ebpf/internal/unix"
11 )
12
13 // A sigset containing only SIGPROF.
14 var profSet unix.Sigset_t
15
16 func init() {
17 // See sigsetAdd for details on the implementation. Open coded here so
18 // that the compiler will check the constant calculations for us.
19 profSet.Val[sigprofBit/wordBits] |= 1 << (sigprofBit % wordBits)
20 }
21
22 // maskProfilerSignal locks the calling goroutine to its underlying OS thread
23 // and adds SIGPROF to the thread's signal mask. This prevents pprof from
24 // interrupting expensive syscalls like e.g. BPF_PROG_LOAD.
25 //
26 // The caller must defer unmaskProfilerSignal() to reverse the operation.
27 func maskProfilerSignal() {
28 runtime.LockOSThread()
29
30 if err := unix.PthreadSigmask(unix.SIG_BLOCK, &profSet, nil); err != nil {
31 runtime.UnlockOSThread()
32 panic(fmt.Errorf("masking profiler signal: %w", err))
33 }
34 }
35
36 // unmaskProfilerSignal removes SIGPROF from the underlying thread's signal
37 // mask, allowing it to be interrupted for profiling once again.
38 //
39 // It also unlocks the current goroutine from its underlying OS thread.
40 func unmaskProfilerSignal() {
41 defer runtime.UnlockOSThread()
42
43 if err := unix.PthreadSigmask(unix.SIG_UNBLOCK, &profSet, nil); err != nil {
44 panic(fmt.Errorf("unmasking profiler signal: %w", err))
45 }
46 }
47
48 const (
49 // Signal is the nth bit in the bitfield.
50 sigprofBit = int(unix.SIGPROF - 1)
51 // The number of bits in one Sigset_t word.
52 wordBits = int(unsafe.Sizeof(unix.Sigset_t{}.Val[0])) * 8
53 )
54
55 // sigsetAdd adds signal to set.
56 //
57 // Note: Sigset_t.Val's value type is uint32 or uint64 depending on the arch.
58 // This function must be able to deal with both and so must avoid any direct
59 // references to u32 or u64 types.
60 func sigsetAdd(set *unix.Sigset_t, signal unix.Signal) error {
61 if signal < 1 {
62 return fmt.Errorf("signal %d must be larger than 0", signal)
63 }
64
65 // For amd64, runtime.sigaddset() performs the following operation:
66 // set[(signal-1)/32] |= 1 << ((uint32(signal) - 1) & 31)
67 //
68 // This trick depends on sigset being two u32's, causing a signal in the
69 // bottom 31 bits to be written to the low word if bit 32 is low, or the high
70 // word if bit 32 is high.
71
72 // Signal is the nth bit in the bitfield.
73 bit := int(signal - 1)
74 // Word within the sigset the bit needs to be written to.
75 word := bit / wordBits
76
77 if word >= len(set.Val) {
78 return fmt.Errorf("signal %d does not fit within unix.Sigset_t", signal)
79 }
80
81 // Write the signal bit into its corresponding word at the corrected offset.
82 set.Val[word] |= 1 << (bit % wordBits)
83
84 return nil
85 }