github.com/cilium/ebpf@v0.15.0/link/tracepoint.go (about)

     1  package link
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/cilium/ebpf"
     7  	"github.com/cilium/ebpf/internal/tracefs"
     8  )
     9  
    10  // TracepointOptions defines additional parameters that will be used
    11  // when loading Tracepoints.
    12  type TracepointOptions struct {
    13  	// Arbitrary value that can be fetched from an eBPF program
    14  	// via `bpf_get_attach_cookie()`.
    15  	//
    16  	// Needs kernel 5.15+.
    17  	Cookie uint64
    18  }
    19  
    20  // Tracepoint attaches the given eBPF program to the tracepoint with the given
    21  // group and name. See /sys/kernel/tracing/events to find available
    22  // tracepoints. The top-level directory is the group, the event's subdirectory
    23  // is the name. Example:
    24  //
    25  //	tp, err := Tracepoint("syscalls", "sys_enter_fork", prog, nil)
    26  //
    27  // Losing the reference to the resulting Link (tp) will close the Tracepoint
    28  // and prevent further execution of prog. The Link must be Closed during
    29  // program shutdown to avoid leaking system resources.
    30  //
    31  // Note that attaching eBPF programs to syscalls (sys_enter_*/sys_exit_*) is
    32  // only possible as of kernel 4.14 (commit cf5f5ce).
    33  func Tracepoint(group, name string, prog *ebpf.Program, opts *TracepointOptions) (Link, error) {
    34  	if group == "" || name == "" {
    35  		return nil, fmt.Errorf("group and name cannot be empty: %w", errInvalidInput)
    36  	}
    37  	if prog == nil {
    38  		return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
    39  	}
    40  	if prog.Type() != ebpf.TracePoint {
    41  		return nil, fmt.Errorf("eBPF program type %s is not a Tracepoint: %w", prog.Type(), errInvalidInput)
    42  	}
    43  
    44  	tid, err := tracefs.EventID(group, name)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	fd, err := openTracepointPerfEvent(tid, perfAllThreads)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	var cookie uint64
    55  	if opts != nil {
    56  		cookie = opts.Cookie
    57  	}
    58  
    59  	pe := newPerfEvent(fd, nil)
    60  
    61  	lnk, err := attachPerfEvent(pe, prog, cookie)
    62  	if err != nil {
    63  		pe.Close()
    64  		return nil, err
    65  	}
    66  
    67  	return lnk, nil
    68  }