Skip to content

Commit

Permalink
pkg/exitsnoop: hold raw_tp link to prevent from GC
Browse files Browse the repository at this point in the history
The cilium/ebpf defines sys.FD's SetFinalizer to close fd when GC.
Since the exec process's exit code needs memory-type exitsnoop, we
should keep the reference on the raw_tp link. Otherwise, the exitsnoop
will be gone and process's exit code will be wrong.

Signed-off-by: Wei Fu <[email protected]>
  • Loading branch information
fuweid committed Apr 8, 2022
1 parent a541c7f commit ded339a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
7 changes: 2 additions & 5 deletions pkg/exitsnoop/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ var (
// NewStoreFromAttach only opens but not pinned in bpffs, which has common
// functionality with EnsureRunning. I think we should use options to merge
// two function in the future.
//
// FIXME(fuweid):
//
// How to close the link after close the store?
func NewStoreFromAttach() (_ *Store, retErr error) {
spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(progByteCode))
if err != nil {
Expand All @@ -63,7 +59,7 @@ func NewStoreFromAttach() (_ *Store, retErr error) {
}
}()

_, err = link.AttachRawTracepoint(link.RawTracepointOptions{
link, err := link.AttachRawTracepoint(link.RawTracepointOptions{
Name: "sched_process_exit",
Program: collection.Programs[bpfProgName],
})
Expand All @@ -74,6 +70,7 @@ func NewStoreFromAttach() (_ *Store, retErr error) {
return &Store{
tracingTasks: collection.Maps[bpfMapTracingTasks],
exitedEvents: collection.Maps[bpfMapExitedEvents],
link: link,
}, nil
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/exitsnoop/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path/filepath"

"github.com/cilium/ebpf"
"github.com/cilium/ebpf/link"
)

// TaskInfo is used to trace the target task.
Expand Down Expand Up @@ -51,6 +52,10 @@ func NewStore(bpffsRoot string) (*Store, error) {
type Store struct {
tracingTasks *ebpf.Map
exitedEvents *ebpf.Map

// NOTE: It is only used to prevent the memory-type prog from go runtime
// GC. For the persisted-type, the field is nil.
link link.Link
}

func (store *Store) Trace(pid uint32, taskInfo *TaskInfo) error {
Expand Down Expand Up @@ -95,6 +100,9 @@ func (store *Store) DeleteExitedEvent(traceEventID uint64) error {
func (store *Store) Close() error {
store.tracingTasks.Close()
store.exitedEvents.Close()
if store.link != nil {
store.link.Close()
}
return nil
}

Expand Down

0 comments on commit ded339a

Please sign in to comment.