Re: perf/ring-buffer: Undefined behaviour in kernel/events/ring_buffer.c:685:22

From: Peter Zijlstra
Date: Fri Jan 29 2016 - 09:18:11 EST


On Fri, Jan 22, 2016 at 03:48:55PM +0300, Andrey Ryabinin wrote:
> 2016-01-19 17:31 GMT+03:00 Peter Zijlstra <peterz@xxxxxxxxxxxxx>:
> > On Sun, Jan 10, 2016 at 03:55:13PM -0500, Sasha Levin wrote:
> >> Hi all,
> >>
> >> While fuzzing with trinity inside a KVM tools guest, running the latest -next
> >> kernel, I've hit the following warning:
> >>
> >> [ 3494.030114] UBSAN: Undefined behaviour in kernel/events/ring_buffer.c:685:22
> >> [ 3494.030647] shift exponent -1 is negative
> >
> > That's rb->page_order == -1, which should 'never' happen, curious!
> >
>
> It happens if nr_pages = 0:
> rb->page_order = ilog2(nr_pages);

Ah indeed.

Something like so then. When !nr_pages, both variables should be 0 and
are due to the kzalloc() of rb slightly above.

---
kernel/events/ring_buffer.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/kernel/events/ring_buffer.c b/kernel/events/ring_buffer.c
index adfdc0536117..345130705c49 100644
--- a/kernel/events/ring_buffer.c
+++ b/kernel/events/ring_buffer.c
@@ -746,8 +746,10 @@ struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)

rb->user_page = all_buf;
rb->data_pages[0] = all_buf + PAGE_SIZE;
- rb->page_order = ilog2(nr_pages);
- rb->nr_pages = !!nr_pages;
+ if (nr_pages) {
+ rb->nr_pages = 1;
+ rb->page_order = ilog2(nr_pages);
+ }

ring_buffer_init(rb, watermark, flags);