Skip to content

Commit

Permalink
linker: do not copy instructions when there is no reference
Browse files Browse the repository at this point in the history
When resolving the bpf-to-bpf calls we need to copy the
instructions from the program to flatten the references.

But when there is no reference there is nothing to do so we
can skip the copy operation altogether.

Signed-off-by: Paul Cacheux <[email protected]>
  • Loading branch information
paulcacheux committed Jan 21, 2025
1 parent fd1fe1b commit 610f088
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 8 additions & 2 deletions linker.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,19 @@ func flattenPrograms(progs map[string]*ProgramSpec, names []string) {
// dependencies of each program.
func flattenInstructions(name string, progs map[string]*ProgramSpec, refs map[*ProgramSpec][]string) asm.Instructions {
prog := progs[name]
progRefs := refs[prog]

if len(progRefs) == 0 {
// No references, nothing to do.
return prog.Instructions
}

insns := make(asm.Instructions, len(prog.Instructions))
copy(insns, prog.Instructions)

// Add all direct references of prog to the list of to be linked programs.
pending := make([]string, len(refs[prog]))
copy(pending, refs[prog])
pending := make([]string, len(progRefs))
copy(pending, progRefs)

// All references for which we've appended instructions.
linked := make(map[string]bool)
Expand Down
21 changes: 21 additions & 0 deletions linker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,24 @@ func TestSplitSymbols(t *testing.T) {
qt.Assert(t, qt.HasLen(m["sym3"], 3))
qt.Assert(t, qt.HasLen(m["sym4"], 4))
}

func TestFlattenInstructionsAllocations(t *testing.T) {
name := "entrypoint"
instructions := asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
}
prog := &ProgramSpec{
Name: name,
Instructions: instructions,
}
progs := map[string]*ProgramSpec{name: prog}
refs := make(map[*ProgramSpec][]string)

// ensure that flattenInstructions does not allocate memory
// if there is no reference for the given program.
allocs := testing.AllocsPerRun(5, func() {
_ = flattenInstructions(name, progs, refs)
})
qt.Assert(t, qt.Equals(allocs, float64(0)))
}

0 comments on commit 610f088

Please sign in to comment.