linker.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package ebpf
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "github.com/cilium/ebpf/asm"
  7. "github.com/cilium/ebpf/btf"
  8. )
  9. // splitSymbols splits insns into subsections delimited by Symbol Instructions.
  10. // insns cannot be empty and must start with a Symbol Instruction.
  11. //
  12. // The resulting map is indexed by Symbol name.
  13. func splitSymbols(insns asm.Instructions) (map[string]asm.Instructions, error) {
  14. if len(insns) == 0 {
  15. return nil, errors.New("insns is empty")
  16. }
  17. if insns[0].Symbol() == "" {
  18. return nil, errors.New("insns must start with a Symbol")
  19. }
  20. var name string
  21. progs := make(map[string]asm.Instructions)
  22. for _, ins := range insns {
  23. if sym := ins.Symbol(); sym != "" {
  24. if progs[sym] != nil {
  25. return nil, fmt.Errorf("insns contains duplicate Symbol %s", sym)
  26. }
  27. name = sym
  28. }
  29. progs[name] = append(progs[name], ins)
  30. }
  31. return progs, nil
  32. }
  33. // The linker is responsible for resolving bpf-to-bpf calls between programs
  34. // within an ELF. Each BPF program must be a self-contained binary blob,
  35. // so when an instruction in one ELF program section wants to jump to
  36. // a function in another, the linker needs to pull in the bytecode
  37. // (and BTF info) of the target function and concatenate the instruction
  38. // streams.
  39. //
  40. // Later on in the pipeline, all call sites are fixed up with relative jumps
  41. // within this newly-created instruction stream to then finally hand off to
  42. // the kernel with BPF_PROG_LOAD.
  43. //
  44. // Each function is denoted by an ELF symbol and the compiler takes care of
  45. // register setup before each jump instruction.
  46. // hasFunctionReferences returns true if insns contains one or more bpf2bpf
  47. // function references.
  48. func hasFunctionReferences(insns asm.Instructions) bool {
  49. for _, i := range insns {
  50. if i.IsFunctionReference() {
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. // applyRelocations collects and applies any CO-RE relocations in insns.
  57. //
  58. // Passing a nil target will relocate against the running kernel. insns are
  59. // modified in place.
  60. func applyRelocations(insns asm.Instructions, local, target *btf.Spec) error {
  61. var relos []*btf.CORERelocation
  62. var reloInsns []*asm.Instruction
  63. iter := insns.Iterate()
  64. for iter.Next() {
  65. if relo := btf.CORERelocationMetadata(iter.Ins); relo != nil {
  66. relos = append(relos, relo)
  67. reloInsns = append(reloInsns, iter.Ins)
  68. }
  69. }
  70. if len(relos) == 0 {
  71. return nil
  72. }
  73. target, err := maybeLoadKernelBTF(target)
  74. if err != nil {
  75. return err
  76. }
  77. fixups, err := btf.CORERelocate(local, target, relos)
  78. if err != nil {
  79. return err
  80. }
  81. for i, fixup := range fixups {
  82. if err := fixup.Apply(reloInsns[i]); err != nil {
  83. return fmt.Errorf("apply fixup %s: %w", &fixup, err)
  84. }
  85. }
  86. return nil
  87. }
  88. // flattenPrograms resolves bpf-to-bpf calls for a set of programs.
  89. //
  90. // Links all programs in names by modifying their ProgramSpec in progs.
  91. func flattenPrograms(progs map[string]*ProgramSpec, names []string) {
  92. // Pre-calculate all function references.
  93. refs := make(map[*ProgramSpec][]string)
  94. for _, prog := range progs {
  95. refs[prog] = prog.Instructions.FunctionReferences()
  96. }
  97. // Create a flattened instruction stream, but don't modify progs yet to
  98. // avoid linking multiple times.
  99. flattened := make([]asm.Instructions, 0, len(names))
  100. for _, name := range names {
  101. flattened = append(flattened, flattenInstructions(name, progs, refs))
  102. }
  103. // Finally, assign the flattened instructions.
  104. for i, name := range names {
  105. progs[name].Instructions = flattened[i]
  106. }
  107. }
  108. // flattenInstructions resolves bpf-to-bpf calls for a single program.
  109. //
  110. // Flattens the instructions of prog by concatenating the instructions of all
  111. // direct and indirect dependencies.
  112. //
  113. // progs contains all referenceable programs, while refs contain the direct
  114. // dependencies of each program.
  115. func flattenInstructions(name string, progs map[string]*ProgramSpec, refs map[*ProgramSpec][]string) asm.Instructions {
  116. prog := progs[name]
  117. insns := make(asm.Instructions, len(prog.Instructions))
  118. copy(insns, prog.Instructions)
  119. // Add all direct references of prog to the list of to be linked programs.
  120. pending := make([]string, len(refs[prog]))
  121. copy(pending, refs[prog])
  122. // All references for which we've appended instructions.
  123. linked := make(map[string]bool)
  124. // Iterate all pending references. We can't use a range since pending is
  125. // modified in the body below.
  126. for len(pending) > 0 {
  127. var ref string
  128. ref, pending = pending[0], pending[1:]
  129. if linked[ref] {
  130. // We've already linked this ref, don't append instructions again.
  131. continue
  132. }
  133. progRef := progs[ref]
  134. if progRef == nil {
  135. // We don't have instructions that go with this reference. This
  136. // happens when calling extern functions.
  137. continue
  138. }
  139. insns = append(insns, progRef.Instructions...)
  140. linked[ref] = true
  141. // Make sure we link indirect references.
  142. pending = append(pending, refs[progRef]...)
  143. }
  144. return insns
  145. }
  146. // fixupAndValidate is called by the ELF reader right before marshaling the
  147. // instruction stream. It performs last-minute adjustments to the program and
  148. // runs some sanity checks before sending it off to the kernel.
  149. func fixupAndValidate(insns asm.Instructions) error {
  150. iter := insns.Iterate()
  151. for iter.Next() {
  152. ins := iter.Ins
  153. // Map load was tagged with a Reference, but does not contain a Map pointer.
  154. if ins.IsLoadFromMap() && ins.Reference() != "" && ins.Map() == nil {
  155. return fmt.Errorf("instruction %d: map %s: %w", iter.Index, ins.Reference(), asm.ErrUnsatisfiedMapReference)
  156. }
  157. fixupProbeReadKernel(ins)
  158. }
  159. return nil
  160. }
  161. // fixupProbeReadKernel replaces calls to bpf_probe_read_{kernel,user}(_str)
  162. // with bpf_probe_read(_str) on kernels that don't support it yet.
  163. func fixupProbeReadKernel(ins *asm.Instruction) {
  164. if !ins.IsBuiltinCall() {
  165. return
  166. }
  167. // Kernel supports bpf_probe_read_kernel, nothing to do.
  168. if haveProbeReadKernel() == nil {
  169. return
  170. }
  171. switch asm.BuiltinFunc(ins.Constant) {
  172. case asm.FnProbeReadKernel, asm.FnProbeReadUser:
  173. ins.Constant = int64(asm.FnProbeRead)
  174. case asm.FnProbeReadKernelStr, asm.FnProbeReadUserStr:
  175. ins.Constant = int64(asm.FnProbeReadStr)
  176. }
  177. }
  178. var kernelBTF struct {
  179. sync.Mutex
  180. spec *btf.Spec
  181. }
  182. // maybeLoadKernelBTF loads the current kernel's BTF if spec is nil, otherwise
  183. // it returns spec unchanged.
  184. //
  185. // The kernel BTF is cached for the lifetime of the process.
  186. func maybeLoadKernelBTF(spec *btf.Spec) (*btf.Spec, error) {
  187. if spec != nil {
  188. return spec, nil
  189. }
  190. kernelBTF.Lock()
  191. defer kernelBTF.Unlock()
  192. if kernelBTF.spec != nil {
  193. return kernelBTF.spec, nil
  194. }
  195. var err error
  196. kernelBTF.spec, err = btf.LoadKernelSpec()
  197. return kernelBTF.spec, err
  198. }