| 1 |
|
| 2 |
|
| 3 |
package link |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"runtime" |
| 8 |
|
| 9 |
"github.com/cilium/ebpf" |
| 10 |
"github.com/cilium/ebpf/internal/sys" |
| 11 |
) |
| 12 |
|
| 13 |
type RawAttachProgramOptions struct { |
| 14 |
|
| 15 |
|
| 16 |
Target int |
| 17 |
|
| 18 |
Program *ebpf.Program |
| 19 |
|
| 20 |
Attach ebpf.AttachType |
| 21 |
|
| 22 |
Anchor Anchor |
| 23 |
|
| 24 |
|
| 25 |
Flags uint32 |
| 26 |
|
| 27 |
ExpectedRevision uint64 |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
func RawAttachProgram(opts RawAttachProgramOptions) error { |
| 35 |
if opts.Flags&anchorFlags != 0 { |
| 36 |
return fmt.Errorf("disallowed flags: use Anchor to specify attach target") |
| 37 |
} |
| 38 |
|
| 39 |
attr := sys.ProgAttachAttr{ |
| 40 |
TargetFdOrIfindex: uint32(opts.Target), |
| 41 |
AttachBpfFd: uint32(opts.Program.FD()), |
| 42 |
AttachType: uint32(opts.Attach), |
| 43 |
AttachFlags: uint32(opts.Flags), |
| 44 |
ExpectedRevision: opts.ExpectedRevision, |
| 45 |
} |
| 46 |
|
| 47 |
if opts.Anchor != nil { |
| 48 |
fdOrID, flags, err := opts.Anchor.anchor() |
| 49 |
if err != nil { |
| 50 |
return fmt.Errorf("attach program: %w", err) |
| 51 |
} |
| 52 |
|
| 53 |
attr.AttachFlags |= flags |
| 54 |
if flags&sys.BPF_F_REPLACE != 0 { |
| 55 |
attr.ReplaceBpfFd = fdOrID |
| 56 |
} else { |
| 57 |
attr.RelativeFdOrId = fdOrID |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
if err := sys.ProgAttach(&attr); err != nil { |
| 62 |
if haveFeatErr := haveProgAttach(); haveFeatErr != nil { |
| 63 |
return haveFeatErr |
| 64 |
} |
| 65 |
return fmt.Errorf("attach program: %w", err) |
| 66 |
} |
| 67 |
runtime.KeepAlive(opts.Program) |
| 68 |
|
| 69 |
return nil |
| 70 |
} |
| 71 |
|
| 72 |
type RawDetachProgramOptions RawAttachProgramOptions |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
func RawDetachProgram(opts RawDetachProgramOptions) error { |
| 79 |
if opts.Flags&anchorFlags != 0 { |
| 80 |
return fmt.Errorf("disallowed flags: use Anchor to specify attach target") |
| 81 |
} |
| 82 |
|
| 83 |
attr := sys.ProgDetachAttr{ |
| 84 |
TargetFdOrIfindex: uint32(opts.Target), |
| 85 |
AttachBpfFd: uint32(opts.Program.FD()), |
| 86 |
AttachType: uint32(opts.Attach), |
| 87 |
ExpectedRevision: opts.ExpectedRevision, |
| 88 |
} |
| 89 |
|
| 90 |
if opts.Anchor != nil { |
| 91 |
fdOrID, flags, err := opts.Anchor.anchor() |
| 92 |
if err != nil { |
| 93 |
return fmt.Errorf("detach program: %w", err) |
| 94 |
} |
| 95 |
|
| 96 |
attr.RelativeFdOrId = fdOrID |
| 97 |
attr.AttachFlags |= flags |
| 98 |
} |
| 99 |
|
| 100 |
if err := sys.ProgDetach(&attr); err != nil { |
| 101 |
if haveFeatErr := haveProgAttach(); haveFeatErr != nil { |
| 102 |
return haveFeatErr |
| 103 |
} |
| 104 |
return fmt.Errorf("can't detach program: %w", err) |
| 105 |
} |
| 106 |
|
| 107 |
return nil |
| 108 |
} |