forked from linux-nvme/nvme-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-accessors.c
More file actions
1794 lines (1576 loc) · 50.2 KB
/
generate-accessors.c
File metadata and controls
1794 lines (1576 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: LGPL-2.1-or-later
/**
* This file is part of libnvme.
*
* Copyright (c) 2025, Dell Technologies Inc. or its subsidiaries.
*
* Authors: Martin Belanger <[email protected]>
*
* This program parses C header files and generates accessor
* functions (setter/getter) for each member found within.
*
* Limitations:
* - Does not support typedef struct. For example,
* typedef struct {
* ...
* } my_struct_t;
*
* - Does not support struct within struct. For example,
* struct my_struct {
* struct another_struct {
* ...
* } my_var;
* ...
* };
*
* Example usage:
* ./generate-accessors private.h
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <regex.h>
#include <stdbool.h>
#include <getopt.h>
#include <glob.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <libgen.h>
#include <stdio.h>
#include <ctype.h>
#ifdef NVME_HAVE_SENDFILE
#include <sys/sendfile.h>
#endif
#define OUTPUT_FNAME_DEFAULT_C "accessors.c"
#define OUTPUT_FNAME_DEFAULT_H "accessors.h"
#define OUTPUT_FNAME_DEFAULT_LD "accessors.ld"
#define STRUCT_RE "struct[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*\\{([^}]*)\\}[[:space:]]*;"
#define CHAR_ARRAY_RE "^(const[[:space:]]+)?char[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*\\[[[:space:]]*([A-Za-z0-9_]+)[[:space:]]*\\][[:space:]]*;"
#define MEMBER_RE "^(const[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)([*[:space:]]+)([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*;"
#define SPACES " \t\n\r"
#define streq(a, b) (strcmp((a), (b)) == 0)
/**
* Function naming convention:
* This controls whether to generate the functions as:
* nvme_foo_get() / nvme_foo_set()
* Or:
* nvme_get_foo() / nvme_set_foo()
*/
#define SET_FMT "%s_set_%s" /* alternate name: "%s_%s_set" */
#define GET_FMT "%s_get_%s" /* alternate name: "%s_%s_get" */
static const char *banner =
"// SPDX-License-Identifier: LGPL-2.1-or-later\n"
"/**\n"
" * This file is part of libnvme.\n"
" *\n"
" * ____ _ _ ____ _\n"
" * / ___| ___ _ __ ___ _ __ __ _| |_ ___ __| | / ___|___ __| | ___\n"
" * | | _ / _ \\ '_ \\ / _ \\ '__/ _` | __/ _ \\/ _` | | | / _ \\ / _` |/ _ \\\n"
" * | |_| | __/ | | | __/ | | (_| | || __/ (_| | | |__| (_) | (_| | __/\n"
" * \\____|\\___|_| |_|\\___|_| \\__,_|\\__\\___|\\__,_| \\____\\___/ \\__,_|\\___|\n"
" *\n"
" * Auto-generated struct member accessors (setter/getter)\n"
" */\n";
/**
* @brief Remove leading whitespace characters from string
* in-place.
*
* Removes leading whitespace defined by SPACES by returning
* a pointer within @s to the first character that is not a
* whitespace.
*
* @param s: The writable string to trim. If NULL, return NULL.
*
* @return Pointer to the first character of s that is not a
* white space, or NULL if @s is NULL.
*/
static inline char *ltrim(const char *s)
{
return s ? (char *)s + strspn(s, SPACES) : NULL;
}
/**
* @brief Remove trailing whitespace characters from a string in-place.
*
* Removes trailing whitespace defined by SPACES by writing a
* terminating NUL byte at the first trailing whitespace position.
*
* @param s: The writable string to trim. If NULL, return NULL.
*
* @return The same pointer @s, or NULL if @s is NULL.
*/
static char *rtrim(char *s)
{
if (!s)
return NULL;
char *p0 = s;
for (char *p = s; *p; p++) {
if (!strchr(SPACES, *p))
p0 = p + 1;
}
*p0 = '\0';
return s;
}
/**
* @brief Trim both leading and trailing whitespace from a string.
*
* Uses ltrim to skip leading whitespace (returns pointer into original
* string) and rtrim to remove trailing whitespace in-place.
*
* @param s: The string to trim. If NULL, returns NULL.
*
* @return Pointer to the trimmed string (may be interior of original),
* or NULL if @s is NULL.
*/
static char *trim(char *s)
{
return s ? rtrim(ltrim(s)) : NULL;
}
/**
* @brief Strip inline C++-style comments ("// ...") from a line.
*
* If the substring "//" is found in @line, it is replaced by a NUL
* terminator so the remainder is ignored.
*
* @param line: Line buffer to modify (in-place).
*
* @return Pointer to the (possibly truncated) line.
*/
static char *trim_inline_comments(char *line)
{
char *p = strstr(line, "//");
if (p)
*p = '\0';
return line;
}
/**
* @brief Remove C-style block comments (like this comment) from
* a text buffer.
*
* Replaces all comment characters with space characters to
* preserve offsets while removing comment content.
*
* @param text: The buffer to clean (modified in-place). If no
* match is found the text pointed to by @text is
* left alone.
*/
static void mask_c_comments(char *text)
{
char *p = text;
while ((p = strstr(p, "/*")) != NULL) {
char *end = strstr(p + 2, "*/");
if (!end)
break;
memset(p, ' ', end - p + 2);
p = end + 2;
}
}
/**
* @brief Convert a string to uppercase in-place.
*
* Iterates each character of @s and transforms it to uppercase
* using toupper().
*
* @param s: The string to convert (modified in-place). Must be
* writable.
*
* @return Pointer to the modified @s.
*/
static char *to_uppercase(char *s)
{
if (!s)
return s;
for (int i = 0; s[i] != '\0'; i++)
s[i] = toupper((unsigned char)s[i]);
return s;
}
/**
* @brief Sanitize a string to form a valid C identifier.
*
* This function modifies the given string in place so that all characters
* conform to the rules of a valid C variable name (identifier):
* - The first character must be a letter (A–Z, a–z) or underscore ('_').
* - Subsequent characters may be letters, digits, or underscores.
*
* Any character that violates these rules is replaced with an underscore ('_').
* The string is always modified in place; no new memory is allocated.
*
* @param s Pointer to the NUL-terminated string to sanitize. If @s is NULL or
* points to an empty string, the function does nothing.
*
* @note This function does not check for C keywords or identifier length limits.
*
* @code
* char name[] = "123bad-name!";
* sanitize_identifier(name);
* // Result: "_23bad_name_"
* @endcode
*/
static const char *sanitize_identifier(char *s)
{
if (s == NULL || *s == '\0')
return s;
// The first character must be a letter or underscore
if (!isalpha((unsigned char)s[0]) && s[0] != '_')
s[0] = '_';
// Remaining characters: letters, digits, underscores allowed
for (char *p = s + 1; *p; ++p) {
if (!isalnum((unsigned char)*p) && *p != '_')
*p = '_';
}
return s;
}
/**
* @brief Duplicate a C string safely.
*
* Allocates memory for and returns a copy of @s including the
* terminating NUL. Uses malloc and memcpy to copy the entire buffer.
*
* The POSIX strdup() has unpredictable behavior when provided
* with a NULL pointer. This function adds a NULL check for
* safety. Also, strdup() is a POSIX extension that may not be
* available on all platforms. Therefore, this function uses
* malloc() and memcpy() instead of invoking strdup().
*
* @param s: Source string to duplicate. If NULL, returns NULL.
*
* @return Newly allocated copy of @s, or NULL on allocation failure or
* if @s is NULL. Caller must free().
*/
static char *safe_strdup(const char *s)
{
if (!s)
return NULL;
size_t len = strlen(s) + 1; /* length including NUL-terminator */
char *new_string = (char *)malloc(len);
if (!new_string)
return NULL; /* Return NULL on allocation failure */
memcpy(new_string, s, len); /* Copy the string including NUL-terminator */
return new_string;
}
/**
* @brief Duplicate up to @size characters of a C string safely.
*
* Copies at most @size characters from @s into a newly allocated,
* NUL-terminated buffer. If @s is shorter than @size, copies only
* up to the terminating NUL.
*
* The POSIX strndup() has unpredictable behavior when provided
* with a NULL pointer. This function adds a NULL check for
* safety. Also, strndup() is a POSIX extension that may not be
* available on all platforms. Therefore, this function uses
* malloc() and memcpy() instead of invoking strndup().
*
* @param s: Source string to duplicate. If NULL, returns NULL.
* @param size: Maximum number of characters to consider from @s.
*
* @return Newly allocated NUL-terminated copy, or NULL on
* allocation failure or if @s is NULL. Caller must
* free().
*/
static char *safe_strndup(const char *s, size_t size)
{
if (!s)
return NULL;
size_t len = strnlen(s, size);
char *new_string = malloc(len + 1);
if (!new_string)
return NULL;
memcpy(new_string, s, len);
new_string[len] = '\0';
return new_string;
}
/**
* @brief Test whether a string contains only decimal digits.
*
* Returns false for NULL or empty string.
*
* @param s: Null-terminated string to test.
*
* @return true if every character in @s is a decimal digit (0-9),
* false otherwise.
*/
static bool str_is_all_numbers(const char *s)
{
if (!s || *s == '\0')
return false;
for (; *s != '\0'; s++) {
if (!isdigit((unsigned char)*s))
return false;
}
return true;
}
/**
* @brief Return pointer to filename component within a path.
*
* Finds the last '/' in @path and returns pointer to the next
* character; if no '/' is found returns the original @path.
*
* @param path: Input path string (must be NUL-terminated).
*
* @return Pointer to filename portion (not newly allocated).
*/
static const char *get_filename(const char *path)
{
const char *slash = strrchr(path, '/');
return slash ? slash + 1 : path;
}
/**
* @brief Create directories recursively (mkdir -p behavior).
*
* Walks the path components and creates each intermediate directory
* with the specified @mode. If @path is ".", returns success.
*
* @param path: Path to create (e.g., "/tmp/a/b").
* @param mode: Permissions bits for created directories (as for mkdir).
*
* @return true on success (directories created or already exist),
* false on error (errno is set).
*/
static bool mkdir_p(const char *path, mode_t mode)
{
bool ok = false;
char *tmp;
char *p = NULL;
size_t len;
if (streq(path, "."))
return true;
if (!path || !*path) {
errno = EINVAL;
return false;
}
/* Copy path to temporary buffer */
tmp = safe_strdup(path);
len = strlen(tmp);
if (tmp[len - 1] == '/')
tmp[len - 1] = '\0'; /* remove trailing slash */
for (p = tmp + 1; *p; p++) {
if (*p == '/') {
*p = '\0';
/* Attempt to create directory */
if (mkdir(tmp, mode) != 0) {
if (errno != EEXIST)
goto mkdir_out;
}
*p = '/';
}
}
/* Create final directory */
if (mkdir(tmp, mode) != 0) {
if (errno != EEXIST)
goto mkdir_out;
}
ok = true;
mkdir_out:
free(tmp);
return ok;
}
/**
* @brief Create directories to hold file specified by @fullpath
*
* Given a path and file name (@fullpath), create the
* directories to hold the file. This is done by splitting the
* file portion from @fullpath and creating the directory tree.
*
* @param fullpath: Directories + file name.
* @param mode: Permissions bits for created directories (as for mkdir).
*
* @return true on success (directories created or already exist),
* false on error (errno is set).
*/
static bool mkdir_fullpath(const char *fullpath, mode_t mode)
{
char saved;
bool ok;
char *fname = (char *)get_filename(fullpath);
/* Check whether it's just a file name w/o a path. */
if (fname == fullpath)
return true;
saved = fname[0];
fname[0] = '\0'; /* split file name from path */
ok = mkdir_p(fullpath, mode);
fname[0] = saved; /* restore full path */
return ok;
}
/**
* @brief Read entire file into a newly-allocated buffer.
*
* Opens the file at @path and reads all bytes into a buffer that is
* NUL-terminated. Exits the program on failure to open the file.
*
* @param path: Path to the file to read.
*
* @return Pointer to a malloc()-allocated buffer containing the file
* contents (NUL-terminated). Caller must free(). On error the
* program exits with EXIT_FAILURE.
*/
static char *read_file(const char *path)
{
long len;
char *buf;
FILE *f = fopen(path, "rb");
if (!f) {
perror(path);
exit(EXIT_FAILURE);
}
fseek(f, 0, SEEK_END);
len = ftell(f);
rewind(f);
buf = malloc(len + 1);
len = fread(buf, 1, len, f);
buf[len] = '\0';
fclose(f);
return buf;
}
/******************************************************************************/
/**
* @brief Compute the length of a regex match represented by regmatch_t.
*
* Returns zero if the match is invalid (rm_so or rm_eo negative or
* rm_eo < rm_so).
*
* @param m: Pointer to regmatch_t describing the match.
*
* @return Size in bytes of the match, or 0 if invalid.
*/
static size_t regmatch_size(const regmatch_t *m)
{
bool invalid = m->rm_so < 0 || m->rm_eo < 0 || m->rm_eo < m->rm_so;
return invalid ? 0 : m->rm_eo - m->rm_so;
}
/**
* @brief Duplicate the substring matched by a regmatch_t.
*
* Allocates a new NUL-terminated buffer and copies the matched span
* from @src.
*
* @param src: Source string used in the regexec().
* @param m: Pointer to regmatch_t describing the match.
*
* @return Newly allocated string containing the match, or NULL if the
* match has zero length. Caller must free().
*/
static char *regmatch_strdup(const char *src, const regmatch_t *m)
{
size_t len = regmatch_size(m);
return len ? safe_strndup(src + m->rm_so, len) : NULL;
}
/**
* @brief Check whether a regex match contains a specific character.
*
* Iterates characters inside the matched span and returns true if
* character @c appears within.
*
* @param src: Source string used for the match.
* @param m: Match information.
* @param c: Character to search for.
*
* @return true if @c present in match span, false otherwise.
*/
static bool regmatch_contains_char(const char *src, const regmatch_t *m, char c)
{
size_t len = regmatch_size(m);
if (!len)
return false;
const char *arr = src + m->rm_so;
for (size_t i = 0; (arr[i] != '\0') && (i < len); i++) {
if (arr[i] == c)
return true;
}
return false;
}
/**
* @brief Test whether the matched substring begins with a given prefix.
*
* Compares the first bytes of the match against @s.
*
* @param src: Source string used for matching.
* @param m: Match information.
* @param s: Prefix to compare.
*
* @return true if the matched substring starts with @s, false
* otherwise.
*/
static bool regmatch_startswith(const char *src,
const regmatch_t *m,
const char *s)
{
size_t size;
size_t len = regmatch_size(m);
if (len == 0)
return false;
size = strlen(s);
if (len < size)
return false;
const char *arr = src + m->rm_so;
return !strncmp(arr, s, size);
}
/******************************************************************************/
typedef struct StringList {
const char **strings; /* Pointer to an array of char pointers */
size_t count; /* Current number of strings */
size_t capacity; /* Allocated capacity for strings */
} StringList_t;
/**
* @brief Initialize a StringList_t object.
*
* Allocates the internal array with at least @initial_capacity
* entries (minimum STRINGLIST_INITIAL_CAPACITY). The list is
* empty after initialization.
*
* @param list: Pointer to the list to initialize.
* @param initial_capacity: Desired initial capacity (will be rounded
* up to at least STRINGLIST_INITIAL_CAPACITY).
*/
#define STRINGLIST_INITIAL_CAPACITY 8
static void strlst_init(StringList_t *list, size_t initial_capacity)
{
if (initial_capacity < STRINGLIST_INITIAL_CAPACITY)
initial_capacity = STRINGLIST_INITIAL_CAPACITY;
list->strings = (const char **)calloc(initial_capacity, sizeof(char *));
list->count = 0;
list->capacity = initial_capacity;
}
/**
* @brief Append a string to a StringList_t.
*
* If list capacity is exhausted, it doubles the capacity and
* reallocates. The input string is set either by stealing the
* passed pointer or by duplicating it depending on @steal.
*
* @param list: Pointer to the string list.
* @param string: Null-terminated string to add.
* @param steal: If true, take ownership of @string pointer (no copy).
*/
static void strlst_add(StringList_t *list, const char *string, bool steal)
{
if (!string)
return; /* Do nothing is string is NULL */
if (list->count == list->capacity) {
/* Reallocate to double capacity */
list->capacity *= 2;
list->strings = (const char **)realloc(list->strings,
list->capacity * sizeof(char *));
for (size_t i = list->count; i < list->capacity; i++)
list->strings[i] = NULL;
}
/* Allocate memory for the new string and copy its content */
list->strings[list->count++] = steal ? string : safe_strdup(string);
}
/**
* @brief Remove all strings from the list and free them.
*
* Frees each stored string and resets count to zero but leaves the
* allocated array in place so the list can be reused.
*
* @param list: Pointer to the string list to clear.
*/
static void strlst_clear(StringList_t *list)
{
for (size_t i = 0; i < list->count; i++) {
free((void *)list->strings[i]);
list->strings[i] = NULL;
}
list->count = 0;
}
/**
* @brief Free a StringList_t and its contents.
*
* Frees all stored strings and the internal array and resets the list
* fields to indicate an empty/unallocated list.
*
* @param list: Pointer to the list to free.
*/
static void strlst_free(StringList_t *list)
{
strlst_clear(list);
free(list->strings);
list->strings = NULL;
list->capacity = 0;
}
/**
* @brief Test if the string list is empty.
*
* @param list: Pointer to the string list.
*
* @return true if list contains no elements, false otherwise.
*/
#define STRLST_EMPTY(list) ((list)->count == 0)
/**
* @brief Iterate over a StringList_t returning next element.
*
* @param sl: Pointer to the string list.
* @param s: Pointer that gets updated with char* at current
* index or NULL if end reached.
*/
#define STRLST_FOREACH(sl, s) \
for (size_t __str_next = 0; \
({ \
(s) = (__str_next >= (sl)->count) ? NULL : (sl)->strings[__str_next++]; \
(s) != NULL; \
});)
/**
* @brief Check whether a list contains a given string.
*
* Compares strings using strcmp (streq macro).
*
* @param list: Pointer to the string list.
* @param s: String to search for.
*
* @return true if @s exists in the list, false otherwise.
*/
static bool strlst_contains(const StringList_t *list, const char *s)
{
const char *str;
STRLST_FOREACH(list, str) {
if (streq(s, str))
return true;
}
return false;
}
/**
* @brief Load strings from a text file into a StringList_t.
*
* Reads the file line-by-line. For each line, trims whitespace and
* skips empty lines or lines starting with '#'. Remaining lines are
* added to @list.
*
* @param list: Pointer to the initialized StringList_t to append to.
* @param filename: Path to the file to read. If NULL, the
* function returns immediately.
*/
static void strlst_load(StringList_t *list, const char *filename)
{
char line[LINE_MAX];
FILE *f;
if (!filename)
return;
f = fopen(filename, "r");
if (!f) {
fprintf(stderr, "Warning: could not open file '%s'\n", filename);
return;
}
while (fgets(line, sizeof(line), f)) {
/* Strip whitespace and comments */
char *p = trim(line);
if (*p == '\0' || *p == '#')
continue;
strlst_add(list, p, false);
}
fclose(f);
}
/**
* @brief Check whether a struct or struct member is excluded.
*
* The exclusion list may contain either struct names (to exclude the
* whole struct) or entries of the form "StructName::member" to exclude
* individual members.
*
* @param excl_list: Pointer to the exclusion StringList_t.
* @param struct_name: Name of the struct being considered.
* @param member_name: Name of the member (or NULL to check whole struct).
*
* @return true if the struct or member is present in the exclusion list,
* false otherwise.
*/
static bool is_excluded(const StringList_t *excl_list,
const char *struct_name,
const char *member_name)
{
char key[LINE_MAX];
/* First, check if the whole struct is excluded */
for (size_t i = 0; i < excl_list->count; i++) {
if (streq(excl_list->strings[i], struct_name))
return true; /* exclude entire struct */
}
if (!member_name)
return false;
/* Second, check if StructName::member is excluded */
snprintf(key, sizeof(key), "%s::%s", struct_name, member_name);
for (size_t i = 0; i < excl_list->count; i++) {
if (streq(excl_list->strings[i], key))
return true; /* exclude member of struct */
}
return false;
}
/**
* @brief Decide whether a struct name is included by the include list.
*
* If the include list is empty, everything is considered included.
*
* @param incl_list: Pointer to inclusion StringList_t.
* @param struct_name: Name of the struct to test.
*
* @return true if struct is included (or include list empty), false otherwise.
*/
static bool is_included(const StringList_t *incl_list, const char *struct_name)
{
/* Note: If include list is empty, then everything is included */
if (STRLST_EMPTY(incl_list))
return true;
return strlst_contains(incl_list, struct_name);
}
/******************************************************************************/
typedef struct Conf {
bool verbose;
const char *c_fname; /* Generated output *.c file name */
const char *h_fname; /* Generated output *.h file name */
const char *l_fname; /* Generated output *.ld file name */
const char *prefix; /* Prefix added to each functions */
StringList_t hdr_files; /* Input header file list */
StringList_t incl_list; /* Inclusion list (read from --incl) */
StringList_t excl_list; /* Enclusion list (read from --excl) */
struct {
regex_t re_struct; /* regex to match struct definitions */
regex_t re_char_array; /* regex to match char array struct members */
regex_t re_member; /* regex to match all other struct members */
} re; /* Precompiled regular expressions */
} Conf_t;
/******************************************************************************/
/**
* The following structures are used to save the structs and members found
* while parsing the header files (*.h). Here's the relationship between
* the different objects.
*
* +--------------------------+
* | StructList_t |
* |--------------------------|
* | StructInfo_t *items ---> [ array of StructInfo_t ]
* | size_t count |
* | size_t capacity |
* +--------------------------+
* |
* v
* +--------------------------+
* | StructInfo_t |
* |--------------------------|
* | char *name |
* | Member_t *members ---> [ array of Member_t ]
* | size_t count |
* | size_t capacity |
* +--------------------------+
* |
* v
* +--------------------------+
* | Member_t |
* |--------------------------|
* | char *type |
* | char *name |
* | char *array_size |
* | bool is_char_array |
* | bool is_const |
* +--------------------------+
*/
typedef struct Member {
char *type; /* Type of the struct member */
char *name; /* Name of the struct member */
char *array_size; /* If member is an array, what is its [size] */
bool is_char_array; /* Whether the member is an array */
bool is_const; /* Whether the member is defined as const */
} Member_t;
typedef struct StructInfo {
char *name; /* Name of the struct */
Member_t *members; /* Array of struct members (each entry is one member) */
size_t count; /* Number of entries in members */
size_t capacity; /* Allocated capacity for members */
} StructInfo_t;
typedef struct StructList {
StructInfo_t *items; /* Array of structs (each entry corresponds to one struct) */
size_t count; /* Number of entries in items */
size_t capacity; /* Allocated capacity for items */
} StructList_t;
/**
* @brief Initialize Member_t to default empty values.
*
* Sets pointer fields to NULL and booleans to false.
*
* @param m: Pointer to Member_t to initialize.
*/
static void member_init(Member_t *m)
{
m->type = NULL;
m->name = NULL;
m->array_size = NULL;
m->is_char_array = false;
m->is_const = false;
}
/**
* @brief Free and reset Member_t fields.
*
* Frees any allocated strings in @m and reinitializes it.
*
* @param m: Pointer to Member_t to clear.
*/
static void member_clear(Member_t *m)
{
free(m->type);
free(m->name);
free(m->array_size);
member_init(m);
}
/**
* @brief Initialize a StructInfo_t object with default capacity.
*
* Allocates the members array with default capacity
* (MEMBERS_INITIAL_CAPACITY) and sets initial field values.
*
* @param si: Pointer to StructInfo_t to initialize.
*/
#define MEMBERS_INITIAL_CAPACITY 8
static void struct_info_init(StructInfo_t *si)
{
si->name = NULL;
si->count = 0;
si->capacity = MEMBERS_INITIAL_CAPACITY;
si->members = malloc(si->capacity * sizeof(Member_t));
for (size_t m = 0; m < si->capacity; m++)
member_init(&si->members[m]);
}
/**
* @brief Clear the contents (members and name) of a StructInfo_t.
*
* Frees per-member allocations and the name string, but leaves the
* struct ready for reuse (members array kept).
*
* @param si: Pointer to StructInfo_t to clear.
*/
static void struct_info_clear(StructInfo_t *si)
{
for (size_t i = 0; i < si->count; ++i)
member_clear(&si->members[i]);
si->count = 0;
free(si->name);
si->name = NULL;
}
/**
* @brief Free all resources used by a StructInfo_t.
*
* Frees members and the members array, resets pointers and capacity.
*
* @param si: Pointer to StructInfo_t to free.
*/
static void struct_info_free(StructInfo_t *si)
{
for (size_t i = 0; i < si->capacity; ++i)
member_clear(&si->members[i]);
si->count = 0;
free(si->members);
si->members = NULL;
free(si->name);
si->name = NULL;
si->capacity = 0;
}
/**
* @brief Add a member to a StructInfo_t, growing the array if needed.
*
* Adds a new Member_t to @si. If capacity is insufficient the members
* array is reallocated (doubled). The new Member_t's type and name are
* set either by stealing the passed pointers or by duplicating them
* depending on @steal_type/@steal_name.
*
* @param si: Pointer to StructInfo_t to append to.
* @param type: String describing the member type.
* @param name: Member name string.
* @param steal_type: If true, take ownership of @type pointer (no copy).
* @param steal_name: If true, take ownership of @name pointer (no copy).
*
* @return Pointer to the newly added Member_t.
*/
static Member_t *struct_info_member_add(StructInfo_t *si,
char *type,
char *name,
bool steal_type,
bool steal_name)