xref: /linux/scripts/gen_packed_field_checks.c (revision 816b02e63a759c4458edee142b721ab09c918b3d)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2024, Intel Corporation
3 #include <stdbool.h>
4 #include <stdio.h>
5 
6 #define MAX_PACKED_FIELD_SIZE 50
7 
8 int main(int argc, char **argv)
9 {
10 	/* The first macro doesn't need a 'do {} while(0)' loop */
11 	printf("#define CHECK_PACKED_FIELDS_1(fields) \\\n");
12 	printf("\tCHECK_PACKED_FIELD(fields, 0)\n\n");
13 
14 	/* Remaining macros require a do/while loop, and are implemented
15 	 * recursively by calling the previous iteration's macro.
16 	 */
17 	for (int i = 2; i <= MAX_PACKED_FIELD_SIZE; i++) {
18 		printf("#define CHECK_PACKED_FIELDS_%d(fields) do { \\\n", i);
19 		printf("\tCHECK_PACKED_FIELDS_%d(fields); \\\n", i - 1);
20 		printf("\tCHECK_PACKED_FIELD(fields, %d); \\\n", i - 1);
21 		printf("} while (0)\n\n");
22 	}
23 
24 	printf("#define CHECK_PACKED_FIELDS(fields) \\\n");
25 
26 	for (int i = 1; i <= MAX_PACKED_FIELD_SIZE; i++)
27 		printf("\t__builtin_choose_expr(ARRAY_SIZE(fields) == %d, ({ CHECK_PACKED_FIELDS_%d(fields); }), \\\n",
28 		       i, i);
29 
30 	printf("\t({ BUILD_BUG_ON_MSG(1, \"CHECK_PACKED_FIELDS() must be regenerated to support array sizes larger than %d.\"); }) \\\n",
31 	       MAX_PACKED_FIELD_SIZE);
32 
33 	for (int i = 1; i <= MAX_PACKED_FIELD_SIZE; i++)
34 		printf(")");
35 
36 	printf("\n");
37 }
38