[PATCH RESEND bpf-next 1/4] kernel: Add helper macros for loop unrolling

Kees Cook keescook at chromium.org
Fri Jan 20 03:48:31 UTC 2023


On Fri, Jan 20, 2023 at 01:08:15AM +0100, KP Singh wrote:
> This helps in easily initializing blocks of code (e.g. static calls and
> keys).
> 
> UNROLL(N, MACRO, __VA_ARGS__) calls MACRO N times with the first
> argument as the index of the iteration. This allows string pasting to
> create unique tokens for variable names, function calls etc.
> 
> As an example:
> 
> 	#include <linux/unroll.h>
> 
> 	#define MACRO(N, a, b)            \
> 		int add_##N(int a, int b) \
> 		{                         \
> 			return a + b + N; \
> 		}
> 
> 	UNROLL(2, MACRO, x, y)
> 
> expands to:
> 
> 	int add_0(int x, int y)
> 	{
> 		return x + y + 0;
> 	}
> 
> 	int add_1(int x, int y)
> 	{
> 		return x + y + 1;
> 	}
> 
> Signed-off-by: KP Singh <kpsingh at kernel.org>
> ---
>  include/linux/unroll.h | 35 +++++++++++++++++++++++++++++++++++
>  1 file changed, 35 insertions(+)
>  create mode 100644 include/linux/unroll.h
> 
> diff --git a/include/linux/unroll.h b/include/linux/unroll.h
> new file mode 100644
> index 000000000000..e19aef95b94b
> --- /dev/null
> +++ b/include/linux/unroll.h
> @@ -0,0 +1,35 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +
> +/*
> + * Copyright (C) 2020 Google LLC.
> + */
> +
> +#ifndef __UNROLL_H
> +#define __UNROLL_H
> +
> +#define __UNROLL_CONCAT(a, b) a ## _ ## b

#include <linux/kernel.h>
and just use CONCATENATE

> +#define UNROLL(N, MACRO, args...) __UNROLL_CONCAT(__UNROLL, N)(MACRO, args)

Which would be, and it just loses the _, which isn't important here:
#define UNROLL(N, MACRO, args...) CONCATENATE(__UNROLL, N)(MACRO, args)

> +#define __UNROLL_0(MACRO, args...)
> +#define __UNROLL_1(MACRO, args...)  __UNROLL_0(MACRO, args)  MACRO(0, args)

But yeah, I like it. It's an expression version of the __MAP() macro
used by the syscall wrappers for arguments.

-- 
Kees Cook



More information about the Linux-security-module-archive mailing list