Re: [PATCH] cxgb4: fix undefined behavior in mem.c

From: Jason Gunthorpe
Date: Mon Mar 04 2019 - 14:54:51 EST


On Thu, Feb 28, 2019 at 03:38:38PM -0700, Shaobo He wrote:
> In function `c4iw_dealloc_mw`, variable mhp's value is printed after
> freed, which triggers undefined behavior according to this post:
> https://trust-in-soft.com/dangling-pointer-indeterminate/.
>
> This commit fixes it by swapping the order of `kfree` and `pr_debug`.
>
> Signed-off-by: Shaobo He <shaobo@xxxxxxxxxxx>
> ---
> drivers/infiniband/hw/cxgb4/mem.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)

Discussion aside, this is a worthwile fix. I rewrote the commit
message to avoid referencing 'undefined behavior' though, this is just
a straight up bug in the logging. Another thread could get the same
pointer value for the mhp before the print creating a confusing log.

cxgb4: kfree mhp after the debug print

In function `c4iw_dealloc_mw`, variable mhp's value is printed after
freed, it is clearer to have the print before the kfree.

Otherwise racing threads could allocate another mhp with the same pointer
value and create confusing tracing.

Jason