Debian Codegraph @

src/bin/gennames/gennames.c

raw
1 /*
2 Copyright 2009-2010 SN Systems Ltd. All rights reserved.
3 Portions Copyright 2009-2020 David Anderson. All rights reserved.
4
5 This program is free software; you can redistribute it
6 and/or modify it under the terms of version 2.1 of the
7 GNU Lesser General Public License as published by the
8 Free Software Foundation.
9
10 This program is distributed in the hope that it would
11 be useful, but WITHOUT ANY WARRANTY; without even the
12 implied warranty of MERCHANTABILITY or FITNESS FOR A
13 PARTICULAR PURPOSE.
14
15 Further, this software is distributed without any warranty
16 that it is free of the rightful claim of any third person
17 regarding infringement or the like. Any license provided
18 herein, whether implied or otherwise, applies only to
19 this software file. Patent licenses, if any, provided
20 herein do not apply to combinations of this program with
21 other software, or any other product whatsoever.
22
23 You should have received a copy of the GNU Lesser General
24 Public License along with this program; if not, write
25 the Free Software Foundation, Inc., 51 Franklin Street -
26 Fifth Floor, Boston MA 02110-1301, USA.
27
28 */
29 /* Used by scripts/libbuild.sh. Not in libdwarf itself. */
30
31 #include <config.h>
32 #include <stddef.h> /* NULL size_t */
33 #include <ctype.h> /* isspace() */
34 #include <errno.h> /* errno */
35 #include <stdio.h> /* fgets() fprintf() printf() sscanf() */
36 #include <stdlib.h> /* exit() qsort() strtoul() */
37 #include <string.h> /* strchr() strcmp() strcpy() strlen()
38 strncmp() */
39 #include "libdwarf_private.h"
40 #include "dd_getopt.h"
41 #include "dwarf_safe_strcpy.h"
42 #include "dd_minimal.h"
43
44 /* works around ref to this via dd_getopt */
45 void dd_minimal_count_global_error(void) {}
46
47 /* gennames.c
48 Prints routines to return constant name for the associated value
49 (such as the TAG name string for a particular tag).
50
51 The input is dwarf.h
52 For each set of names with a common prefix, we create a routine
53 to return the name given the value.
54 Also print header file that gives prototypes of routines.
55 To handle cases where there are multiple names for a single
56 value (DW_AT_* has some due to ambiguities in the DWARF2 spec)
57 we take the first of a given value as the definitive name.
58 TAGs, Attributes, etc are given distinct checks.
59
60 The doprinting argument is so that when used by tag_tree.c,
61 and tag_attr.c that we don't get irritating messages on stderr
62 when those dwarfdump built-time applications are run.
63
64 ======== For consistency across the library we
65 ======== now only use the #define macro version,
66 ======== never the enum version.
67 There are multiple output files as some people find one
68 form more pleasant than the other.
69
70 ======== It's difficult to believe compilers still
71 ======== generate poor switch() code.
72 Some compilers generate better code for switch statements than
73 others, so the -s and -t options let the user decide which
74 is better for their compiler (when building dwarfdump):
75 a simple switch or code doing binary search.
76 This choice affects the runtime speed of dwarfdump.
77
78 */
79
80 static void OpenAllFiles(void);
81 static void WriteFileTrailers(void);
82 static void CloseAllFiles(void);
83 static void GenerateInitialFileLines(void);
84 static void GenerateOneSet(void);
85 static void WriteNameDeclarations(void);
86 #ifdef TRACE_ARRAY
87 static void PrintArray(void);
88 #endif /* TRACE_ARRAY */
89 static int is_skippable_line(char *pLine);
90 static void ParseDefinitionsAndWriteOutput(void);
91
92 /* We don't need really long lines: the input file is simple. */
93 #define MAX_LINE_SIZE 1000
94 /* We don't need a variable array size,
95 it just has to be big enough. */
96 #define ARRAY_SIZE 350
97
98 #define MAX_NAME_LEN 64
99
100 /* To store entries from dwarf.h */
101 typedef struct {
102 char ad_prefixname[MAX_NAME_LEN]; /* short name */
103 char ad_name[MAX_NAME_LEN]; /* short name */
104 unsigned ad_value; /* value */
105 /* Original spot in array. Lets us guarantee a stable sort. */
106 unsigned ad_original_position;
107 } array_data;
108
109 /* A group_array is a grouping from dwarf.h.
110 All the TAGs are one group, all the
111 FORMs are another group, and so on. */
112 static array_data group_array[ARRAY_SIZE];
113 static unsigned array_count = 0;
114
115 typedef int (*compfn)(const void *,const void *);
116 static int Compare(array_data *,array_data *);
117
118 static const char *prefix_root = "DW_";
119 static const unsigned prefix_root_len = 3;
120
121 /* f_dwarf_in is the input dwarf.h. The others are output files. */
122 static FILE *f_dwarf_in;
123 static FILE *f_names_h;
124 static FILE *f_names_c;
125
126 /* Size unchecked, but large enough. */
127 static char prefix[200] = "";
128
129 static const char *usage[] = {
130 "Usage: gennames <options>",
131 " -i <path/src/lib/libdwarf",
132 " -o output-table-path",
133 "",
134 };
135
136 static void
137 print_args(int argc, char *argv[])
138 {
139 int index;
140 printf("Arguments: ");
141 for (index = 1; index < argc; ++index) {
142 printf("%s ",argv[index]);
143 }
144 printf("\n");
145 }
146
147 static char *program_name = 0;
148 static char *input_name = 0;
149 static char *output_name = 0;
150
151 static void
152 print_version(const char * name)
153 {
154 #ifdef _DEBUG
155 const char *acType = "Debug";
156 #else
157 const char *acType = "Release";
158 #endif /* _DEBUG */
159
160 printf("%s [%s %s]\n",name,PACKAGE_VERSION,acType);
161 }
162
163 static void
164 print_usage_message(const char *options[])
165 {
166 int index;
167 for (index = 0; *options[index]; ++index) {
168 printf("%s\n",options[index]);
169 }
170 }
171
172 /* process arguments */
173 static void
174 process_args(int argc, char *argv[])
175 {
176 int c = 0;
177 int usage_error = FALSE;
178
179 program_name = argv[0];
180
181 while ((c = dwgetopt(argc, argv, "i:o:")) != EOF) {
182 switch (c) {
183 case 'i':
184 input_name = dwoptarg;
185 break;
186 case 'o':
187 output_name = dwoptarg;
188 break;
189 default:
190 usage_error = TRUE;
191 break;
192 }
193 }
194
195 if (usage_error || 1 == dwoptind || dwoptind != argc) {
196 print_usage_message(usage);
197 exit(EXIT_FAILURE);
198 }
199 }
200
201 int
202 main(int argc,char **argv)
203 {
204 print_version(argv[0]);
205 print_args(argc,argv);
206 process_args(argc,argv);
207 OpenAllFiles();
208 GenerateInitialFileLines();
209 ParseDefinitionsAndWriteOutput();
210 WriteNameDeclarations();
211 WriteFileTrailers();
212 CloseAllFiles();
213 return 0;
214 }
215
216 /* Print the array used to hold the tags, attributes values */
217 #ifdef TRACE_ARRAY
218 static void
219 PrintArray(void)
220 {
221 int i;
222 for (i = 0; i < array_count; ++i) {
223 printf("%d: Name %s_%s, Value 0x%04x\n",
224 i,grouparray[i].ad_prefixname,
225 grouparray[i].ad_name,
226 grouparray[i].ad_value);
227 }
228 }
229 #endif /* TRACE_ARRAY */
230
231 /* By including original position we force a stable sort */
232 static int
233 Compare(array_data *elem1,array_data *elem2)
234 {
235 if (elem1->ad_value < elem2->ad_value) {
236 return -1;
237 }
238 if (elem1->ad_value > elem2->ad_value) {
239 return 1;
240 }
241 if (elem1->ad_original_position < elem2->ad_original_position) {
242 return -1;
243 }
244 if (elem1->ad_original_position > elem2->ad_original_position) {
245 return 1;
246 }
247 return 0;
248 }
249
250 static FILE *
251 open_path(const char *base, const char *file, const char *direction)
252 {
253 FILE *f = 0;
254 /* POSIX PATH_MAX would suffice, normally stdio
255 BUFSIZ is larger than PATH_MAX */
256 static char path_name[BUFSIZ];
257
258 /* 2 == space for / and NUL */
259 size_t baselen = strlen(base) +1;
260 size_t filelen = strlen(file) +1;
261 size_t netlen = baselen + filelen;
262
263 if (netlen >= BUFSIZ) {
264 printf("Error opening '%s/%s', name too long\n",base,file);
265 exit(EXIT_FAILURE);
266 }
267 _dwarf_safe_strcpy(path_name,BUFSIZ,
268 base,baselen-1);
269 _dwarf_safe_strcpy(path_name+baselen-1,BUFSIZ -baselen,
270 "/",1);
271 _dwarf_safe_strcpy(path_name+baselen,BUFSIZ -baselen -1,
272 file,filelen-1);
273 f = fopen(path_name,direction);
274 if (!f) {
275 printf("Error opening '%s'\n",path_name);
276 exit(EXIT_FAILURE);
277 }
278 return f;
279 }
280
281 /* Open files and write the basic headers */
282 static void
283 OpenAllFiles(void)
284 {
285 const char *dwarf_h = "dwarf.h";
286 const char *names_h = "dwarf_names.h";
287 const char *names_c = "dwarf_names.c";
288
289 f_dwarf_in = open_path(input_name,dwarf_h,"r");
290 f_names_h = open_path(output_name,names_h,"w");
291 f_names_c = open_path(output_name,names_c,"w");
292 }
293
294 static void
295 GenerateInitialFileLines(void)
296 {
297 /* Generate entries for 'dwarf_names.c' */
298 fprintf(f_names_c,"/* Generated routines, do not edit. */\n");
299 fprintf(f_names_c,"/* Generated for source version %s */\n",
300 PACKAGE_VERSION);
301 fprintf(f_names_c,"\n/* BEGIN FILE */\n\n");
302 fprintf(f_names_c,"#include \"dwarf.h\"\n\n");
303 fprintf(f_names_c,"#include \"libdwarf.h\"\n\n");
304 }
305
306 /* Close files and write basic trailers */
307 static void
308 WriteFileTrailers(void)
309 {
310 /* Generate entries for 'dwarf_names.c' */
311 fprintf(f_names_c,"\n/* END FILE */\n");
312 }
313
314 static void
315 CloseAllFiles(void)
316 {
317 fclose(f_dwarf_in);
318 fclose(f_names_h);
319 fclose(f_names_c);
320 }
321
322 struct NameEntry {
323 char ne_name[MAX_NAME_LEN];
324 };
325
326 /* Sort these by name, then write */
327 #define MAX_NAMES 200
328 static struct NameEntry nameentries[MAX_NAMES];
329 static int curnameentry;
330
331 /* We compare as capitals for sorting purposes.
332 This does not do right by UTF8, but the strings
333 are from in dwarf.h and are plain ASCII. */
334 static int
335 CompareName(struct NameEntry *elem1,struct NameEntry *elem2)
336 {
337 char *cpl = elem1->ne_name;
338 char *cpr = elem2->ne_name;
339 for ( ; *cpl && *cpr; ++cpl,++cpr) {
340 unsigned char l = *cpl;
341 unsigned char r = *cpr;
342 unsigned char l1 = 0;
343 unsigned char r1 = 0;
344
345 if (l == r) {
346 continue;
347 }
348 if (l <= 'z' && l >= 'a') {
349 l1 = l - 'a' + 'A';
350 l = l1;
351 }
352 if (r <= 'z' && r >= 'a') {
353 r1 = r -'a'+ 'A';
354 r = r1;
355 }
356 if (l < r) {
357 return -1;
358 }
359 if (l > r) {
360 return 1;
361 }
362 continue;
363 }
364 if (*cpl < *cpr) {
365 return -1;
366 }
367 if (*cpl > *cpr) {
368 return 1;
369 }
370 return 0; /* should NEVER happen */
371 }
372
373 /* Sort into name order for readability of the declarations,
374 then print the declarations. */
375 static void
376 WriteNameDeclarations(void)
377 {
378 int i = 0;
379
380 qsort((void *)&nameentries,curnameentry,
381 sizeof(struct NameEntry),(compfn)CompareName);
382 /* Generate entries for 'dwarf_names.h' and libdwarf.h */
383 for ( ; i < curnameentry;++i) {
384 fprintf(f_names_h,"DW_API int dwarf_get_%s_name"
385 "(unsigned int /*val_in*/,\n",nameentries[i].ne_name);
386 fprintf(f_names_h," const char ** /*s_out */);\n");
387 }
388 }
389 static void
390 SaveNameDeclaration(char *prefix_id)
391 {
392 unsigned long length = 0;
393
394 if (curnameentry >= MAX_NAMES) {
395 printf("FAIL gennames. Exceeded limit of declarations %d "
396 "when given %s\n",curnameentry,prefix_id);
397 exit(EXIT_FAILURE);
398 }
399 length = strlen(prefix_id);
400 if (length >= MAX_NAME_LEN) {
401 printf("FAIL gennames. Exceeded limit of declaration "
402 "name length at %ul "
403 "when given %s\n",curnameentry,prefix_id);
404 exit(EXIT_FAILURE);
405 }
406 strcpy(nameentries[curnameentry].ne_name,prefix_id);
407 ++curnameentry;
408 }
409
410 /* Write the table and code for a common set of names */
411 static void
412 GenerateOneSet(void)
413 {
414 unsigned u;
415 unsigned prev_value = 0;
416 char * prev_name = "";
417 char *prefix_id = prefix + prefix_root_len;
418
419 #ifdef TRACE_ARRAY
420 printf("List before sorting:\n");
421 PrintArray();
422 #endif /* TRACE_ARRAY */
423
424 /* Sort the array, because the values in 'libdwarf.h' are not in
425 ascending order; if we use '-t' we must be sure the values are
426 sorted, for the binary search to work properly.
427 We want a stable sort, hence mergesort. */
428 qsort((void *)&group_array,array_count,
429 sizeof(array_data),(compfn)Compare);
430
431 #ifdef TRACE_ARRAY
432 printf("\nList after sorting:\n");
433 PrintArray();
434 #endif /* TRACE_ARRAY */
435
436 SaveNameDeclaration(prefix_id);
437 /* Generate code for 'dwarf_names.c' */
438 fprintf(f_names_c,"/* ARGSUSED */\n");
439 fprintf(f_names_c,"int\n");
440 fprintf(f_names_c,"dwarf_get_%s_name (unsigned int val,\n",
441 prefix_id);
442 fprintf(f_names_c," const char ** s_out)\n");
443 fprintf(f_names_c,"{\n");
444 fprintf(f_names_c," switch (val) {\n");
445
446 for (u = 0; u < array_count; ++u) {
447 /* Check if value already dumped */
448 if (u > 0 && group_array[u].ad_value == prev_value) {
449 fprintf(f_names_c,
450 " /* Skipping alternate spelling of value\n");
451 fprintf(f_names_c,
452 " 0x%x. %s_%s */\n",
453 (unsigned)prev_value,
454 prefix,
455 group_array[u].ad_name);
456 printf("0x%04x: Skip "
457 "%s_%s Keep %s_%s\n",
458 (unsigned)prev_value,
459 prefix,
460 group_array[u].ad_name,
461 prefix,prev_name);
462 continue;
463 }
464 prev_value = group_array[u].ad_value;
465 prev_name = group_array[u].ad_name;
466
467 /* Generate entries for 'dwarf_names.c' */
468 fprintf(f_names_c," case %s_%s:\n",
469 prefix,group_array[u].ad_name);
470 fprintf(f_names_c," *s_out = \"%s_%s\";\n",
471 prefix,group_array[u].ad_name);
472 fprintf(f_names_c," return DW_DLV_OK;\n");
473 }
474
475 /* Closing entries for 'dwarf_names.h' */
476 fprintf(f_names_c," default: break;\n");
477 fprintf(f_names_c," }\n");
478 fprintf(f_names_c," return DW_DLV_NO_ENTRY;\n");
479 fprintf(f_names_c,"}\n");
480 /* Mark the group_array as empty */
481 array_count = 0;
482 }
483
484 /* Detect empty lines (and other lines we do not want to read) */
485 static int
486 is_skippable_line(char *pLine)
487 {
488 int empty = TRUE;
489
490 for (; *pLine && empty; ++pLine) {
491 empty = isspace(*pLine);
492 }
493 return empty;
494 }
495
496 /* Parse the 'dwarf.h' file and generate the tables */
497 static void
498 ParseDefinitionsAndWriteOutput(void)
499 {
500 char new_prefix[64];
501 char *second_underscore = NULL;
502 char type[1000];
503 char name[1000];
504 char value[1000];
505 char extra[1000];
506 char line_in[MAX_LINE_SIZE];
507 int pending = FALSE;
508 int prefix_len = 0;
509
510 /* Process each line from 'dwarf.h' */
511 while (!feof(f_dwarf_in)) {
512 /* errno is cleared here so printing errno after
513 the fgets is showing errno as set by fgets. */
514 char *fgbad = 0;
515 errno = 0;
516 fgbad = fgets(line_in,sizeof(line_in),f_dwarf_in);
517 if (!fgbad) {
518 if (feof(f_dwarf_in)) {
519 break;
520 }
521 /* Is error. errno must be set. */
522 fprintf(stderr,"Error reading dwarf.h!. Errno %d\n",
523 errno);
524 exit(EXIT_FAILURE);
525 }
526 if (is_skippable_line(line_in)) {
527 continue;
528 }
529 sscanf(line_in,"%s %s %s %s",type,name,value,extra);
530 if (strcmp(type,"#define") ||
531 strncmp(name,prefix_root,prefix_root_len)) {
532 continue;
533 }
534
535 second_underscore = strchr(name + prefix_root_len,'_');
536 prefix_len = (int)(second_underscore - name);
537 _dwarf_safe_strcpy(new_prefix,sizeof(new_prefix),
538 name,prefix_len);
539
540 /* Check for new prefix set */
541 if (strcmp(prefix,new_prefix)) {
542 if (pending) {
543 /* Generate current prefix set */
544 GenerateOneSet();
545 }
546 pending = TRUE;
547 _dwarf_safe_strcpy(prefix,sizeof(prefix),
548 new_prefix,strlen(new_prefix));
549 }
550
551 /* Be sure we have a valid entry */
552 if (array_count >= ARRAY_SIZE) {
553 printf("Too many entries for current "
554 "group_array size of %d",ARRAY_SIZE);
555 exit(EXIT_FAILURE);
556 }
557 if (!second_underscore) {
558 printf("Line has no underscore %s\n",line_in);
559 continue;
560 }
561
562 /* Move past the second underscore */
563 ++second_underscore;
564
565 {
566 unsigned long v = strtoul(value,NULL,16);
567 /* Some values are duplicated, that is ok.
568 After the sort we will weed out the duplicate values,
569 see GenerateOneSet(). */
570 /* Record current entry */
571 if (strlen(second_underscore) >= MAX_NAME_LEN) {
572 printf("Too long a name %s for max len %d\n",
573 second_underscore,MAX_NAME_LEN);
574 exit(EXIT_FAILURE);
575 }
576 _dwarf_safe_strcpy(group_array[array_count].ad_name,
577 MAX_NAME_LEN,second_underscore,
578 strlen(second_underscore));
579 group_array[array_count].ad_value = v;
580 group_array[array_count].ad_original_position =
581 array_count;
582 ++array_count;
583 }
584 }
585 if (pending) {
586 /* Generate final prefix set */
587 GenerateOneSet();
588 }
589 }