Skip to content

Commit

Permalink
perf - deal with buffer underflow of kernel's perf_raw_record output
Browse files Browse the repository at this point in the history
https://elixir.bootlin.com/linux/v5.5.13/source/kernel/events/core.c#L6611
raw->size is used to size the buffer, but frag->size is used to fill it.

https://elixir.bootlin.com/linux/v5.5.13/source/kernel/events/core.c#L6827
While preparing the sample output, raw->size is set to the sum of all
fragments' sizes minus 4 bytes. However, header->size doesn't include this
4-byte deduction.
  • Loading branch information
ti-mo committed May 11, 2020
1 parent 2f1b4a1 commit 2cc7e46
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 11 additions & 1 deletion perf/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ import (
"golang.org/x/xerrors"
)

const (
// `perf_raw_record` contains a trailing `u32 size`, whose length is
// included in `perf_event_header.size`, the size of the record's buffer.
// When reading raw perf samples from the ring, this many bytes need to be
// popped from the end of the data to avoid returning garbage once the ring
// has wrapped around.
perfRawRecordTailLength = 4
)

var (
errClosed = xerrors.New("perf reader was closed")
errEOR = xerrors.New("end of ring")
Expand Down Expand Up @@ -131,7 +140,8 @@ func readRawSample(rd io.Reader) ([]byte, error) {
if _, err := io.ReadFull(rd, data); err != nil {
return nil, xerrors.Errorf("can't read sample: %v", err)
}
return data, nil

return data[:len(data)-perfRawRecordTailLength], nil
}

// Reader allows reading bpf_perf_event_output
Expand Down
2 changes: 1 addition & 1 deletion perf/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestPerfReader(t *testing.T) {
t.Fatal("Can't read samples:", err)
}

want := []byte{1, 2, 3, 4, 4, 0, 0, 0, 0, 0, 0, 0}
want := []byte{1, 2, 3, 4, 4, 0, 0, 0}
if !bytes.Equal(record.RawSample, want) {
t.Log(record.RawSample)
t.Error("Sample doesn't match expected output")
Expand Down

0 comments on commit 2cc7e46

Please sign in to comment.