Skip to content

Commit

Permalink
libbpf-tools: Fix misaligned pointer accesses in tcplife
Browse files Browse the repository at this point in the history
The perf buffer in tcplife doesn't maintain 8 byte alignment
for saddr, daddr, ts_us, span_us, rx_b and tx_b in struct event.
 When building with "-fsanitize=alignment
 -fsanitize-trap=undefined" failures happen in handle_event.
Fix these by copying the event from the perf buffer before
accessing.

This is similar to a fix in exitsnoop where different ways to handle
misaligned pointers were discussed:
iovisor#4760

Signed-off-by: Ian Rogers <[email protected]>
  • Loading branch information
captain5050 authored and yonghong-song committed Dec 7, 2023
1 parent 93fad89 commit 7962f13
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions libbpf-tools/tcplife.c
Original file line number Diff line number Diff line change
Expand Up @@ -116,23 +116,30 @@ static void sig_int(int signo)
static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
{
char ts[32], saddr[48], daddr[48];
struct event *e = data;
struct event e;
struct tm *tm;
time_t t;

if (data_sz < sizeof(e)) {
printf("Error: packet too small\n");
return;
}
/* Copy data as alignment in the perf buffer isn't guaranteed. */
memcpy(&e, data, sizeof(e));

if (emit_timestamp) {
time(&t);
tm = localtime(&t);
strftime(ts, sizeof(ts), "%H:%M:%S", tm);
printf("%8s ", ts);
}

inet_ntop(e->family, &e->saddr, saddr, sizeof(saddr));
inet_ntop(e->family, &e->daddr, daddr, sizeof(daddr));
inet_ntop(e.family, &e.saddr, saddr, sizeof(saddr));
inet_ntop(e.family, &e.daddr, daddr, sizeof(daddr));

printf("%-7d %-16s %-*s %-5d %-*s %-5d %-6.2f %-6.2f %-.2f\n",
e->pid, e->comm, column_width, saddr, e->sport, column_width, daddr, e->dport,
(double)e->tx_b / 1024, (double)e->rx_b / 1024, (double)e->span_us / 1000);
e.pid, e.comm, column_width, saddr, e.sport, column_width, daddr, e.dport,
(double)e.tx_b / 1024, (double)e.rx_b / 1024, (double)e.span_us / 1000);
}

static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
Expand Down

0 comments on commit 7962f13

Please sign in to comment.