xref: /aosp_15_r20/external/libcap/libcap/_makenames.c (revision 2810ac1b38eead2603277920c78344c84ddf3aff)
1 /*
2  * Copyright (c) 1997-8,2020 Andrew G. Morgan <[email protected]>
3  *
4  * This is a file to make the capability <-> string mappings for
5  * libcap.
6  */
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 /*
13  * #include 'sed' generated array
14  */
15 
16 struct {
17     const char *name;
18     int index;
19 } const list[] = {
20 #include "cap_names.list.h"
21     {NULL, -1}
22 };
23 
24 /*
25  * recalloc uses realloc to grow some memory but it resets the
26  * indicated extended empty space.
27  */
recalloc(void * p,int was,int is)28 static void *recalloc(void *p, int was, int is) {
29     char *n = realloc(p, is);
30     if (!n) {
31 	fputs("out of memory", stderr);
32 	exit(1);
33     }
34     memset(n+was, 0, is-was);
35     return n;
36 }
37 
main(void)38 int main(void)
39 {
40     int i, maxcaps=0, maxlength=0;
41     const char **pointers = NULL;
42     int pointers_avail = 0;
43 
44     for ( i=0; list[i].index >= 0 && list[i].name; ++i ) {
45 	if (maxcaps <= list[i].index) {
46 	    maxcaps = list[i].index + 1;
47 	}
48         if (pointers == NULL || list[i].index >= pointers_avail) {
49 	    int was = pointers_avail * sizeof(char *);
50 	    pointers_avail = 2 * list[i].index + 1;
51 	    pointers = recalloc(pointers, was, pointers_avail * sizeof(char *));
52 	    if (pointers == NULL) {
53 		perror("unable to continue");
54 		exit(1);
55 	    }
56         }
57 	pointers[list[i].index] = list[i].name;
58 	int n = strlen(list[i].name);
59 	if (n > maxlength) {
60 	    maxlength = n;
61 	}
62     }
63 
64     printf("/*\n"
65 	   " * DO NOT EDIT: this file is generated automatically from\n"
66 	   " *\n"
67 	   " *     <uapi/linux/capability.h>\n"
68 	   " */\n\n"
69 	   "#define __CAP_BITS       %d\n"
70 	   "#define __CAP_NAME_SIZE  %d\n"
71 	   "\n"
72 	   "#ifdef LIBCAP_PLEASE_INCLUDE_ARRAY\n"
73 	   "#define LIBCAP_CAP_NAMES { \\\n", maxcaps, maxlength+1);
74 
75     for (i=0; i<maxcaps; ++i) {
76 	if (pointers[i]) {
77 	    printf("      /* %d */\t\"%s\", \\\n", i, pointers[i]);
78 	} else {
79 	    printf("      /* %d */\tNULL,\t\t/* - presently unused */ \\\n", i);
80 	}
81     }
82 
83     printf("  }\n"
84 	   "#endif /* LIBCAP_PLEASE_INCLUDE_ARRAY */\n"
85 	   "\n"
86 	   "/* END OF FILE */\n");
87 
88     free(pointers);
89     exit(0);
90 }
91