2 * Copyright (c) 2001-2003
3 * Fraunhofer Institute for Open Communication Systems (FhG Fokus).
6 * Copyright (c) 2004-2006,2018
10 * Author: Harti Brandt <harti@freebsd.org>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * $Begemot: gensnmptree.c 383 2006-05-30 07:40:49Z brandt_h $
35 * Generate OID table from table description.
39 * file := top | top file
41 * top := tree | typedef | include
43 * tree := head elements ')'
45 * entry := head ':' index STRING elements ')'
47 * leaf := head type STRING ACCESS ')'
49 * column := head type ACCESS ')'
51 * type := BASETYPE | BASETYPE '|' subtype | enum | bits
55 * enum := ENUM '(' value ')'
57 * bits := BITS '(' value ')'
59 * value := optminus INT STRING | optminus INT STRING value
61 * optminus := '-' | EMPTY
63 * head := '(' INT STRING
65 * elements := EMPTY | elements element
67 * element := tree | leaf | column
69 * index := type | index type
71 * typedef := 'typedef' STRING type
73 * include := 'include' filespec
75 * filespec := '"' STRING '"' | '<' STRING '>'
77 #include <sys/types.h>
78 #include <sys/param.h>
90 #include <sys/queue.h>
94 #include "snmpagent.h"
97 * Constant prefix for all OIDs
99 static const asn_subid_t prefix[] = { 1, 3, 6 };
100 #define PREFIX_LEN (sizeof(prefix) / sizeof(prefix[0]))
103 static const char *file_prefix = "";
105 /* if true generate local include paths */
106 static int localincs = 0;
108 /* if true print tokens */
111 static const char usgtxt[] = "\
112 Generate SNMP tables.\n\
114 usage: gensnmptree [-dEeFfhlt] [-I directory] [-i infile] [-p prefix]\n\
118 -E extract the named or all enums and bits only\n\
119 -e extract the named oids or enums\n\
120 -F generate functions for -E into a .c file\n\
121 -f generate functions for -E into the header\n\
122 -h print this info\n\
123 -I directory add directory to include path\n\
124 -i ifile read from the named file instead of stdin\n\
125 -l generate local include directives\n\
126 -p prefix prepend prefix to file and variable names\n\
127 -t generate a .def file\n\
131 * A node in the OID tree
146 TAILQ_HEAD(node_list, node);
150 asn_subid_t id; /* last element of OID */
151 char *name; /* name of node */
152 TAILQ_ENTRY(node) link;
153 u_int lno; /* starting line number */
154 u_int flags; /* allowed operations */
158 struct node_list subs;
162 uint32_t index; /* index for table entry */
163 char *func; /* function for tables */
164 struct node_list subs;
168 enum snmp_syntax syntax; /* syntax for this leaf */
169 char *func; /* function name */
173 enum snmp_syntax syntax; /* syntax for this column */
180 LIST_ENTRY(func) link;
183 static LIST_HEAD(, func) funcs = LIST_HEAD_INITIALIZER(funcs);
188 TAILQ_ENTRY(enums) link;
193 const char *from_fname;
198 TAILQ_HEAD(, enums) enums;
199 LIST_ENTRY(type) link;
202 static LIST_HEAD(, type) types = LIST_HEAD_INITIALIZER(types);
204 static void report(const char *, ...) __dead2 __printflike(1, 2);
205 static void report_node(const struct node *, const char *, ...)
206 __dead2 __printflike(2, 3);
208 /************************************************************
210 * Allocate memory and panic just in the case...
217 if ((ptr = malloc(size)) == NULL)
218 err(1, "allocing %zu bytes", size);
224 savestr(const char *s)
229 return (strcpy(xalloc(strlen(s) + 1), s));
232 /************************************************************
241 LIST_ENTRY(input) link;
243 static LIST_HEAD(, input) inputs = LIST_HEAD_INITIALIZER(inputs);
244 static struct input *input = NULL;
246 #define MAX_PATHS 100
247 static u_int npaths = 2;
248 static u_int stdpaths = 2;
249 static const char *paths[MAX_PATHS + 1] = {
250 "/usr/share/snmp/defs",
251 "/usr/local/share/snmp/defs",
255 static int pbchar = -1;
258 path_new(const char *path)
260 if (npaths >= MAX_PATHS)
261 report("too many -I directives");
262 memmove(&paths[npaths - stdpaths + 1], &paths[npaths - stdpaths],
263 sizeof(path[0]) * stdpaths);
264 paths[npaths - stdpaths] = savestr(path);
269 input_new(FILE *fp, const char *path, const char *fname)
273 ip = xalloc(sizeof(*ip));
276 ip->fname = savestr(fname);
277 ip->path = savestr(path);
278 LIST_INSERT_HEAD(&inputs, ip, link);
292 LIST_REMOVE(input, link);
295 input = LIST_FIRST(&inputs);
299 tryopen(const char *path, const char *fname)
307 fn = xalloc(strlen(path) + strlen(fname) + 2);
308 sprintf(fn, "%s/%s", path, fname);
316 input_fopen(const char *fname, int loc)
322 if (fname[0] == '/') {
323 if ((fp = tryopen(NULL, fname)) != NULL) {
324 input_new(fp, NULL, fname);
335 if ((fp = tryopen(path, fname)) != NULL) {
336 input_new(fp, NULL, fname);
341 for (p = 0; paths[p] != NULL; p++)
342 if ((fp = tryopen(paths[p], fname)) != NULL) {
343 input_new(fp, paths[p], fname);
347 report("cannot open '%s'", fname);
365 if ((c = getc(input->fp)) != EOF)
381 /************************************************************
386 TOK_EOF = 0200, /* end-of-file seen */
387 TOK_NUM, /* number */
388 TOK_STR, /* string */
389 TOK_ACCESS, /* access operator */
390 TOK_TYPE, /* type operator */
391 TOK_ENUM, /* enum token (kind of a type) */
392 TOK_TYPEDEF, /* typedef directive */
393 TOK_DEFTYPE, /* defined type */
394 TOK_INCLUDE, /* include directive */
395 TOK_FILENAME, /* filename ("foo.bar" or <foo.bar>) */
396 TOK_BITS, /* bits token (kind of a type) */
399 static const struct {
404 { "GET", TOK_ACCESS, FL_GET },
405 { "SET", TOK_ACCESS, FL_SET },
406 { "NULL", TOK_TYPE, SNMP_SYNTAX_NULL },
407 { "INTEGER", TOK_TYPE, SNMP_SYNTAX_INTEGER },
408 { "INTEGER32", TOK_TYPE, SNMP_SYNTAX_INTEGER },
409 { "UNSIGNED32", TOK_TYPE, SNMP_SYNTAX_GAUGE },
410 { "OCTETSTRING", TOK_TYPE, SNMP_SYNTAX_OCTETSTRING },
411 { "IPADDRESS", TOK_TYPE, SNMP_SYNTAX_IPADDRESS },
412 { "OID", TOK_TYPE, SNMP_SYNTAX_OID },
413 { "TIMETICKS", TOK_TYPE, SNMP_SYNTAX_TIMETICKS },
414 { "COUNTER", TOK_TYPE, SNMP_SYNTAX_COUNTER },
415 { "GAUGE", TOK_TYPE, SNMP_SYNTAX_GAUGE },
416 { "COUNTER64", TOK_TYPE, SNMP_SYNTAX_COUNTER64 },
417 { "ENUM", TOK_ENUM, SNMP_SYNTAX_INTEGER },
418 { "BITS", TOK_BITS, SNMP_SYNTAX_OCTETSTRING },
419 { "typedef", TOK_TYPEDEF, 0 },
420 { "include", TOK_INCLUDE, 0 },
424 /* arbitrary upper limit on node names and function names */
426 static char str[MAXSTR];
427 static u_long val; /* integer values */
428 static int saved_token = -1;
431 * Report an error and exit.
434 report(const char *fmt, ...)
440 fprintf(stderr, "line %u: ", input->lno);
441 vfprintf(stderr, fmt, ap);
442 fprintf(stderr, "\n");
443 fprintf(stderr, "context: \"");
444 while ((c = tgetc()) != EOF && c != '\n')
445 fprintf(stderr, "%c", c);
446 fprintf(stderr, "\n");
451 report_node(const struct node *np, const char *fmt, ...)
456 fprintf(stderr, "line %u, node %s: ", np->lno, np->name);
457 vfprintf(stderr, fmt, ap);
458 fprintf(stderr, "\n");
464 * Return a fresh copy of the string constituting the current token.
469 return (savestr(str));
473 * Get the next token from input.
476 gettoken_internal(void)
481 if (saved_token != -1) {
489 * Skip any whitespace before the next token
491 while ((c = tgetc()) != EOF) {
500 report("unexpected character %#2x", (u_int)c);
506 while ((c = tgetc()) != EOF) {
512 report("unexpected EOF in comment");
516 * Single character tokens
518 if (strchr("():|-", c) != NULL)
521 if (c == '"' || c == '<') {
531 while ((c = tgetc()) != EOF) {
534 if (n == sizeof(str) - 1) {
536 report("filename too long '%s...'", str);
541 return (TOK_FILENAME);
550 while ((c = tgetc()) != EOF) {
555 if (n == sizeof(str) - 1) {
557 report("number too long '%s...'", str);
562 sscanf(str, "%lu", &val);
567 * So that has to be a string.
569 if (isalpha(c) || c == '_') {
572 while ((c = tgetc()) != EOF) {
573 if (!isalnum(c) && c != '_' && c != '-') {
577 if (n == sizeof(str) - 1) {
579 report("string too long '%s...'", str);
588 for (c = 0; keywords[c].str != NULL; c++)
589 if (strcmp(keywords[c].str, str) == 0) {
590 val = keywords[c].val;
591 return (keywords[c].tok);
594 LIST_FOREACH(t, &types, link) {
595 if (strcmp(t->name, str) == 0) {
597 return (TOK_DEFTYPE);
603 errx(1, "%u: unexpected character '%c'", input->lno, c);
605 errx(1, "%u: unexpected character 0x%02x", input->lno,
611 int tok = gettoken_internal();
617 fprintf(stderr, "EOF ");
621 fprintf(stderr, "NUM(%lu) ", val);
625 fprintf(stderr, "STR(%s) ", str);
629 fprintf(stderr, "ACCESS(%lu) ", val);
633 fprintf(stderr, "TYPE(%lu) ", val);
637 fprintf(stderr, "ENUM ");
641 fprintf(stderr, "BITS ");
645 fprintf(stderr, "TYPEDEF ");
649 fprintf(stderr, "DEFTYPE(%s,%lu) ", str, val);
653 fprintf(stderr, "INCLUDE ");
657 fprintf(stderr, "FILENAME ");
663 fprintf(stderr, "'%c' ", tok);
664 else if (tok == '\n')
665 fprintf(stderr, "\n");
667 fprintf(stderr, "%02x ", tok);
680 pushback(enum tok tok)
683 if (saved_token != -1)
692 make_type(const char *s)
696 t = xalloc(sizeof(*t));
697 t->name = savestr(s);
699 t->syntax = SNMP_SYNTAX_NULL;
700 t->from_fname = savestr(input->fname);
701 t->from_lno = input->lno;
702 TAILQ_INIT(&t->enums);
703 LIST_INSERT_HEAD(&types, t, link);
709 * Parse a type. We've seen the ENUM or type keyword already. Leave next
713 parse_type(enum tok *tok, struct type *t, const char *vname)
720 if (*tok == TOK_ENUM || *tok == TOK_BITS) {
721 if (t == NULL && vname != NULL) {
722 t = make_type(vname);
723 t->is_enum = (*tok == TOK_ENUM);
724 t->is_bits = (*tok == TOK_BITS);
727 if (gettoken() != '(')
728 report("'(' expected after ENUM");
730 if ((*tok = gettoken()) == TOK_EOF)
731 report("unexpected EOF in ENUM");
735 e = xalloc(sizeof(*e));
738 if ((*tok = gettoken()) == TOK_EOF)
739 report("unexpected EOF in ENUM");
740 e->value = -(long)val;
745 report("need value for ENUM/BITS");
746 if (gettoken() != TOK_STR)
747 report("need string in ENUM/BITS");
749 TAILQ_INSERT_TAIL(&t->enums, e, link);
750 if ((*tok = gettoken()) == TOK_EOF)
751 report("unexpected EOF in ENUM/BITS");
752 } while (*tok != ')');
755 } else if (*tok == TOK_DEFTYPE) {
759 if ((*tok = gettoken()) == '|') {
760 if (gettoken() != TOK_STR)
761 report("subtype expected after '|'");
770 * Parse the next node (complete with all subnodes)
779 node = xalloc(sizeof(struct node));
780 node->lno = input->lno;
784 report("'(' expected at begin of node");
785 if (gettoken() != TOK_NUM)
786 report("node id expected after opening '('");
788 report("subid too large '%lu'", val);
789 node->id = (asn_subid_t)val;
790 if (gettoken() != TOK_STR)
791 report("node name expected after '(' ID");
792 node->name = savetok();
794 if ((tok = gettoken()) == TOK_TYPE || tok == TOK_DEFTYPE ||
795 tok == TOK_ENUM || tok == TOK_BITS) {
797 u_int syntax = parse_type(&tok, NULL, node->name);
799 if (tok == TOK_STR) {
801 node->type = NODE_LEAF;
802 node->u.leaf.func = savetok();
803 node->u.leaf.syntax = syntax;
807 node->type = NODE_COLUMN;
808 node->u.column.syntax = syntax;
812 if (tok != TOK_ACCESS)
813 report("access keyword or ')' expected");
814 node->flags |= (u_int)val;
818 } else if (tok == ':') {
820 node->type = NODE_ENTRY;
821 TAILQ_INIT(&node->u.entry.subs);
824 node->u.entry.index = 0;
826 while (tok == TOK_TYPE || tok == TOK_DEFTYPE ||
827 tok == TOK_ENUM || tok == TOK_BITS) {
828 u_int syntax = parse_type(&tok, NULL, node->name);
829 if (index_count++ == SNMP_INDEXES_MAX)
830 report("too many table indexes");
831 node->u.entry.index |=
832 syntax << (SNMP_INDEX_SHIFT * index_count);
834 node->u.entry.index |= index_count;
835 if (index_count == 0)
836 report("need at least one index");
838 report("function name expected");
840 node->u.entry.func = savetok();
846 TAILQ_INSERT_TAIL(&node->u.entry.subs, sub, link);
852 node->type = NODE_TREE;
853 TAILQ_INIT(&node->u.tree.subs);
857 TAILQ_INSERT_TAIL(&node->u.tree.subs, sub, link);
865 * Parse a top level element. Return the tree if it was a tree, NULL
869 parse_top(enum tok tok)
876 if (tok == TOK_TYPEDEF) {
877 if (gettoken() != TOK_STR)
878 report("type name expected after typedef");
883 t->is_enum = (tok == TOK_ENUM);
884 t->is_bits = (tok == TOK_BITS);
885 t->syntax = parse_type(&tok, t, NULL);
891 if (tok == TOK_INCLUDE) {
892 if (gettoken() != TOK_FILENAME)
893 report("filename expected in include directive");
895 input_fopen(str, val);
899 report("'(' or 'typedef' expected");
903 * Generate the C-code table part for one node.
906 gen_node(FILE *fp, struct node *np, struct asn_oid *oid, u_int idx,
913 if (oid->len == ASN_MAXOIDLEN)
914 report_node(np, "OID too long");
915 oid->subs[oid->len++] = np->id;
917 if (np->type == NODE_TREE) {
918 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
919 gen_node(fp, sub, oid, 0, NULL);
923 if (np->type == NODE_ENTRY) {
924 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
925 gen_node(fp, sub, oid, np->u.entry.index,
932 if ((np->flags & (FL_GET|FL_SET)) == 0) {
937 fprintf(fp, " {{ %u, {", oid->len);
938 for (n = 0; n < oid->len; n++)
939 fprintf(fp, " %u,", oid->subs[n]);
940 fprintf(fp, " }}, \"%s\", ", np->name);
942 if (np->type == NODE_COLUMN) {
943 syntax = np->u.column.syntax;
944 fprintf(fp, "SNMP_NODE_COLUMN, ");
946 syntax = np->u.leaf.syntax;
947 fprintf(fp, "SNMP_NODE_LEAF, ");
952 case SNMP_SYNTAX_NULL:
953 fprintf(fp, "SNMP_SYNTAX_NULL, ");
956 case SNMP_SYNTAX_INTEGER:
957 fprintf(fp, "SNMP_SYNTAX_INTEGER, ");
960 case SNMP_SYNTAX_OCTETSTRING:
961 fprintf(fp, "SNMP_SYNTAX_OCTETSTRING, ");
964 case SNMP_SYNTAX_IPADDRESS:
965 fprintf(fp, "SNMP_SYNTAX_IPADDRESS, ");
968 case SNMP_SYNTAX_OID:
969 fprintf(fp, "SNMP_SYNTAX_OID, ");
972 case SNMP_SYNTAX_TIMETICKS:
973 fprintf(fp, "SNMP_SYNTAX_TIMETICKS, ");
976 case SNMP_SYNTAX_COUNTER:
977 fprintf(fp, "SNMP_SYNTAX_COUNTER, ");
980 case SNMP_SYNTAX_GAUGE:
981 fprintf(fp, "SNMP_SYNTAX_GAUGE, ");
984 case SNMP_SYNTAX_COUNTER64:
985 fprintf(fp, "SNMP_SYNTAX_COUNTER64, ");
988 case SNMP_SYNTAX_NOSUCHOBJECT:
989 case SNMP_SYNTAX_NOSUCHINSTANCE:
990 case SNMP_SYNTAX_ENDOFMIBVIEW:
994 if (np->type == NODE_COLUMN)
995 fprintf(fp, "%s, ", func);
997 fprintf(fp, "%s, ", np->u.leaf.func);
1000 if (np->flags & FL_SET)
1001 fprintf(fp, "|SNMP_NODE_CANSET");
1002 fprintf(fp, ", %#x, NULL, NULL },\n", idx);
1008 * Generate the header file with the function declarations.
1011 gen_header(FILE *fp, struct node *np, u_int oidlen, const char *func)
1018 if (np->type == NODE_TREE) {
1019 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1020 gen_header(fp, sub, oidlen, NULL);
1023 if (np->type == NODE_ENTRY) {
1024 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
1025 gen_header(fp, sub, oidlen, np->u.entry.func);
1029 if((np->flags & (FL_GET|FL_SET)) == 0)
1032 if (np->type == NODE_COLUMN) {
1034 errx(1, "column without function (%s) - probably "
1035 "outside of a table", np->name);
1036 sprintf(f, "%s", func);
1038 sprintf(f, "%s", np->u.leaf.func);
1040 LIST_FOREACH(ptr, &funcs, link)
1041 if (strcmp(ptr->name, f) == 0)
1045 ptr = xalloc(sizeof(*ptr));
1046 ptr->name = savestr(f);
1047 LIST_INSERT_HEAD(&funcs, ptr, link);
1049 fprintf(fp, "int %s(struct snmp_context *, "
1050 "struct snmp_value *, u_int, u_int, "
1051 "enum snmp_op);\n", f);
1054 fprintf(fp, "# define LEAF_%s %u\n", np->name, np->id);
1058 * Generate the OID table.
1061 gen_table(FILE *fp, struct node *node)
1065 fprintf(fp, "#include <sys/types.h>\n");
1066 fprintf(fp, "#include <stdio.h>\n");
1067 #ifdef HAVE_STDINT_H
1068 fprintf(fp, "#include <stdint.h>\n");
1070 fprintf(fp, "#include <string.h>\n");
1072 fprintf(fp, "#include \"asn1.h\"\n");
1073 fprintf(fp, "#include \"snmp.h\"\n");
1074 fprintf(fp, "#include \"snmpagent.h\"\n");
1076 fprintf(fp, "#include <bsnmp/asn1.h>\n");
1077 fprintf(fp, "#include <bsnmp/snmp.h>\n");
1078 fprintf(fp, "#include <bsnmp/snmpagent.h>\n");
1080 fprintf(fp, "#include \"%stree.h\"\n", file_prefix);
1083 fprintf(fp, "const struct snmp_node %sctree[] = {\n", file_prefix);
1085 oid.len = PREFIX_LEN;
1086 memcpy(oid.subs, prefix, sizeof(prefix));
1087 gen_node(fp, node, &oid, 0, NULL);
1089 fprintf(fp, "};\n\n");
1093 print_syntax(u_int syntax)
1097 for (i = 0; keywords[i].str != NULL; i++)
1098 if (keywords[i].tok == TOK_TYPE &&
1099 keywords[i].val == syntax) {
1100 printf(" %s", keywords[i].str);
1107 * Generate a tree definition file
1110 gen_tree(const struct node *np, int level)
1112 const struct node *sp;
1115 printf("%*s(%u %s", 2 * level, "", np->id, np->name);
1120 print_syntax(np->u.leaf.syntax);
1121 printf(" %s%s%s)\n", np->u.leaf.func,
1122 (np->flags & FL_GET) ? " GET" : "",
1123 (np->flags & FL_SET) ? " SET" : "");
1127 if (TAILQ_EMPTY(&np->u.tree.subs)) {
1131 TAILQ_FOREACH(sp, &np->u.tree.subs, link)
1132 gen_tree(sp, level + 1);
1133 printf("%*s)\n", 2 * level, "");
1140 for (i = 0; i < SNMP_INDEX_COUNT(np->u.entry.index); i++)
1141 print_syntax(SNMP_INDEX(np->u.entry.index, i));
1142 printf(" %s\n", np->u.entry.func);
1143 TAILQ_FOREACH(sp, &np->u.entry.subs, link)
1144 gen_tree(sp, level + 1);
1145 printf("%*s)\n", 2 * level, "");
1149 print_syntax(np->u.column.syntax);
1150 printf("%s%s)\n", (np->flags & FL_GET) ? " GET" : "",
1151 (np->flags & FL_SET) ? " SET" : "");
1157 extract(FILE *fp, const struct node *np, struct asn_oid *oid, const char *obj,
1158 const struct asn_oid *idx, const char *iname)
1163 if (oid->len == ASN_MAXOIDLEN)
1164 report_node(np, "OID too long");
1165 oid->subs[oid->len++] = np->id;
1167 if (strcmp(obj, np->name) == 0) {
1168 if (oid->len + idx->len >= ASN_MAXOIDLEN)
1169 report_node(np, "OID too long");
1170 fprintf(fp, "#define OID_%s%s\t%u\n", np->name,
1171 iname ? iname : "", np->id);
1172 fprintf(fp, "#define OIDLEN_%s%s\t%u\n", np->name,
1173 iname ? iname : "", oid->len + idx->len);
1174 fprintf(fp, "#define OIDX_%s%s\t{ %u, {", np->name,
1175 iname ? iname : "", oid->len + idx->len);
1176 for (n = 0; n < oid->len; n++)
1177 fprintf(fp, " %u,", oid->subs[n]);
1178 for (n = 0; n < idx->len; n++)
1179 fprintf(fp, " %u,", idx->subs[n]);
1180 fprintf(fp, " } }\n");
1184 if (np->type == NODE_TREE) {
1185 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1186 if (!extract(fp, sub, oid, obj, idx, iname))
1188 } else if (np->type == NODE_ENTRY) {
1189 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
1190 if (!extract(fp, sub, oid, obj, idx, iname))
1198 * Extract the named OID.
1200 * \param fp file to extract to
1201 * \param root root of the tree
1202 * \param object name of the object to extract
1204 * \return 0 on success, -1 if the object was not found
1207 gen_extract(FILE *fp, const struct node *root, char *object)
1211 char *s, *e, *end, *iname;
1215 /* look whether the object to extract has an index part */
1218 s = strchr(object, '.');
1220 iname = malloc(strlen(s) + 1);
1222 err(1, "cannot allocated index");
1225 for (e = iname; *e != '\0'; e++)
1232 errx(1, "bad index syntax");
1233 if ((e = strchr(s, '.')) != NULL)
1237 ul = strtoul(s, &end, 0);
1239 errx(1, "bad index syntax '%s'", end);
1241 err(1, "bad index syntax");
1243 if (idx.len == ASN_MAXOIDLEN)
1244 errx(1, "index oid too large");
1245 idx.subs[idx.len++] = ul;
1251 oid.len = PREFIX_LEN;
1252 memcpy(oid.subs, prefix, sizeof(prefix));
1253 ret = extract(fp, root, &oid, object, &idx, iname);
1262 check_sub_order(const struct node *np, const struct node_list *subs)
1265 const struct node *sub;
1266 asn_subid_t maxid = 0;
1268 /* ensure, that subids are ordered */
1270 TAILQ_FOREACH(sub, subs, link) {
1271 if (!first && sub->id <= maxid)
1272 report_node(np, "subids not ordered at %s", sub->name);
1279 * Do some sanity checks on the tree definition and do some computations.
1282 check_tree(struct node *np)
1286 if (np->type == NODE_LEAF || np->type == NODE_COLUMN) {
1287 if ((np->flags & (FL_GET|FL_SET)) != 0)
1292 if (np->type == NODE_ENTRY) {
1293 check_sub_order(np, &np->u.entry.subs);
1295 /* ensure all subnodes are columns */
1296 TAILQ_FOREACH(sub, &np->u.entry.subs, link) {
1297 if (sub->type != NODE_COLUMN)
1298 report_node(np, "entry subnode '%s' is not "
1299 "a column", sub->name);
1303 check_sub_order(np, &np->u.tree.subs);
1305 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1311 merge_subs(struct node_list *s1, struct node_list *s2)
1313 struct node *n1, *n2;
1315 while (!TAILQ_EMPTY(s2)) {
1316 n2 = TAILQ_FIRST(s2);
1317 TAILQ_REMOVE(s2, n2, link);
1319 TAILQ_FOREACH(n1, s1, link)
1320 if (n1->id >= n2->id)
1323 TAILQ_INSERT_TAIL(s1, n2, link);
1324 else if (n1->id > n2->id)
1325 TAILQ_INSERT_BEFORE(n1, n2, link);
1327 if (n1->type == NODE_TREE && n2->type == NODE_TREE) {
1328 if (strcmp(n1->name, n2->name) != 0)
1329 errx(1, "trees to merge must have "
1330 "same name '%s' '%s'", n1->name,
1332 merge_subs(&n1->u.tree.subs, &n2->u.tree.subs);
1334 } else if (n1->type == NODE_ENTRY &&
1335 n2->type == NODE_ENTRY) {
1336 if (strcmp(n1->name, n2->name) != 0)
1337 errx(1, "entries to merge must have "
1338 "same name '%s' '%s'", n1->name,
1340 if (n1->u.entry.index != n2->u.entry.index)
1341 errx(1, "entries to merge must have "
1342 "same index '%s'", n1->name);
1343 if (strcmp(n1->u.entry.func,
1344 n2->u.entry.func) != 0)
1345 errx(1, "entries to merge must have "
1346 "same op '%s'", n1->name);
1347 merge_subs(&n1->u.entry.subs,
1351 errx(1, "entities to merge must be both "
1352 "trees or both entries: %s, %s",
1353 n1->name, n2->name);
1359 merge(struct node **root, struct node *t)
1362 if (*root == NULL) {
1369 /* both must be trees */
1370 if ((*root)->type != NODE_TREE)
1371 errx(1, "root is not a tree");
1372 if (t->type != NODE_TREE)
1373 errx(1, "can merge only with tree");
1374 if ((*root)->id != t->id)
1375 errx(1, "trees to merge must have same id");
1377 merge_subs(&(*root)->u.tree.subs, &t->u.tree.subs);
1381 unminus(FILE *fp, const char *s)
1384 while (*s != '\0') {
1388 fprintf(fp, "%c", *s);
1394 * Generate a definition for the enum packed into a guard against multiple
1397 * \param fp file to write definition to
1401 gen_enum(FILE *fp, const struct type *t)
1403 const struct enums *e;
1404 long min = LONG_MAX;
1407 fprintf(fp, "#ifndef %s_defined__\n", t->name);
1408 fprintf(fp, "#define %s_defined__\n", t->name);
1409 fprintf(fp, "/*\n");
1410 fprintf(fp, " * From %s:%u\n", t->from_fname, t->from_lno);
1411 fprintf(fp, " */\n");
1412 fprintf(fp, "enum %s {\n", t->name);
1413 TAILQ_FOREACH(e, &t->enums, link) {
1414 fprintf(fp, "\t%s_", t->name);
1415 unminus(fp, e->name);
1416 fprintf(fp, " = %ld,\n", e->value);
1420 fprintf(fp, "};\n");
1421 fprintf(fp, "#define STROFF_%s %ld\n", t->name, min);
1422 fprintf(fp, "#define STRING_%s \\\n", t->name);
1423 TAILQ_FOREACH(e, &t->enums, link) {
1424 fprintf(fp, "\t[%ld] = \"%s_", e->value - min, t->name);
1425 unminus(fp, e->name);
1426 fprintf(fp, "\",\\\n");
1429 fprintf(fp, "#endif /* %s_defined__ */\n", t->name);
1433 * Generate helper functions for an enum.
1435 * We always generate a switch statement for the isok function. The compiler
1436 * optimizes this into range checks if possible.
1438 * \param fp file to write to
1440 * \param ccode generate externally visible non-inline functions
1443 gen_enum_funcs(FILE *fp, const struct type *t, int ccode)
1448 fprintf(fp, "static inline ");
1449 fprintf(fp, "int\n");
1450 fprintf(fp, "isok_%s(enum %s s)\n", t->name, t->name);
1452 fprintf(fp, " switch (s) {\n");
1454 const struct enums *e;
1455 TAILQ_FOREACH(e, &t->enums, link) {
1456 fprintf(fp, "\t case %s_", t->name);
1457 unminus(fp, e->name);
1461 fprintf(fp, " return (1);\n");
1462 fprintf(fp, " }\n");
1463 fprintf(fp, " return (0);\n");
1464 fprintf(fp, "}\n\n");
1467 fprintf(fp, "static inline ");
1468 fprintf(fp, "const char *\n");
1469 fprintf(fp, "tostr_%s(enum %s s)\n", t->name, t->name);
1471 fprintf(fp, " static const char *vals[] = { STRING_%s };\n", t->name);
1473 fprintf(fp, " if (isok_%s(s))\n", t->name);
1474 fprintf(fp, " return (vals[(int)s - STROFF_%s]);\n", t->name);
1475 fprintf(fp, " return (\"%s???\");\n", t->name);
1476 fprintf(fp, "}\n\n");
1479 fprintf(fp, "static inline ");
1480 fprintf(fp, "int\n");
1481 fprintf(fp, "fromstr_%s(const char *str, enum %s *s)\n",
1484 fprintf(fp, " static const char *vals[] = { STRING_%s };\n", t->name);
1486 fprintf(fp, " for (size_t i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) {\n");
1487 fprintf(fp, " if (vals[i] != NULL && strcmp(vals[i], str) == 0) {\n");
1488 fprintf(fp, " *s = i + STROFF_%s;\n", t->name);
1489 fprintf(fp, " return (1);\n");
1490 fprintf(fp, " }\n");
1491 fprintf(fp, " }\n");
1492 fprintf(fp, " return (0);\n");
1497 * Generate helper functions for an enum. This generates code for a c file.
1499 * \param fp file to write to
1500 * \param name enum name
1503 gen_enum_funcs_str(FILE *fp, const char *name)
1505 const struct type *t;
1507 LIST_FOREACH(t, &types, link)
1508 if ((t->is_enum || t->is_bits) && strcmp(t->name, name) == 0) {
1509 gen_enum_funcs(fp, t, 1);
1517 * Generate helper functions for all enums.
1519 * \param fp file to write to
1520 * \param ccode generate externally visible non-inline functions
1523 gen_all_enum_funcs(FILE *fp, int ccode)
1525 const struct type *t;
1527 LIST_FOREACH(t, &types, link)
1528 if (t->is_enum || t->is_bits)
1529 gen_enum_funcs(fp, t, ccode);
1533 * Extract a given enum to the specified file and optionally generate static
1534 * inline helper functions for them.
1536 * \param fp file to print on
1537 * \param name name of the enum
1538 * \param gen_funcs generate the functions too
1540 * \return 0 if found, -1 otherwise
1543 extract_enum(FILE *fp, const char *name, int gen_funcs)
1545 const struct type *t;
1547 LIST_FOREACH(t, &types, link)
1548 if ((t->is_enum || t->is_bits) && strcmp(t->name, name) == 0) {
1551 gen_enum_funcs(fp, t, 0);
1558 * Extract all enums to the given file and optionally generate static inline
1559 * helper functions for them.
1561 * \param fp file to print on
1562 * \param gen_funcs generate the functions too
1565 extract_all_enums(FILE *fp, int gen_funcs)
1567 const struct type *t;
1569 LIST_FOREACH(t, &types, link)
1570 if (t->is_enum || t->is_bits) {
1573 gen_enum_funcs(fp, t, 0);
1578 * Extract enums and optionally generate some helper functions for them.
1580 * \param argc number of arguments
1581 * \param argv arguments (enum names)
1582 * \param gen_funcs_h generate functions into the header file
1583 * \param gen_funcs_c generate a .c file with functions
1586 make_enums(int argc, char *argv[], int gen_funcs_h, int gen_funcs_c)
1590 gen_all_enum_funcs(stdout, 1);
1592 for (int i = 0; i < argc; i++)
1593 if (gen_enum_funcs_str(stdout, argv[i]))
1594 errx(1, "enum not found: %s", argv[i]);
1598 extract_all_enums(stdout, gen_funcs_h);
1600 for (int i = 0; i < argc; i++)
1601 if (extract_enum(stdout, argv[i], gen_funcs_h))
1602 errx(1, "enum not found: %s", argv[i]);
1608 main(int argc, char *argv[])
1613 int gen_funcs_h = 0;
1614 int gen_funcs_c = 0;
1617 char fname[MAXPATHLEN + 1];
1620 char *infile = NULL;
1622 while ((opt = getopt(argc, argv, "dEeFfhI:i:lp:t")) != EOF)
1646 fprintf(stderr, "%s", usgtxt);
1662 file_prefix = optarg;
1663 if (strlen(file_prefix) + strlen("tree.c") >
1665 errx(1, "prefix too long");
1673 if (do_extract + do_tree + do_enums > 1)
1674 errx(1, "conflicting options -e/-t/-E");
1675 if (!do_extract && !do_enums && argc != optind)
1676 errx(1, "no arguments allowed");
1677 if (do_extract && argc == optind)
1678 errx(1, "no objects specified");
1680 if ((gen_funcs_h || gen_funcs_c) && (do_extract || do_tree))
1681 errx(1, "-f and -F not allowed with -e or -t");
1682 if (gen_funcs_c && !do_enums)
1683 errx(1, "-F requires -E");
1684 if (gen_funcs_h && gen_funcs_c)
1685 errx(1, "-f and -F are mutually exclusive");
1687 if (infile == NULL) {
1688 input_new(stdin, NULL, "<stdin>");
1690 if ((fp = fopen(infile, "r")) == NULL)
1691 err(1, "%s", infile);
1692 input_new(fp, NULL, infile);
1695 root = parse_top(gettoken());
1696 while ((tok = gettoken()) != TOK_EOF)
1697 merge(&root, parse_top(tok));
1703 while (optind < argc) {
1704 if (gen_extract(stdout, root, argv[optind]))
1705 errx(1, "object not found: %s", argv[optind]);
1711 make_enums(argc - optind, argv + optind,
1712 gen_funcs_h, gen_funcs_c);
1719 sprintf(fname, "%stree.h", file_prefix);
1720 if ((fp = fopen(fname, "w")) == NULL)
1721 err(1, "%s: ", fname);
1722 gen_header(fp, root, PREFIX_LEN, NULL);
1724 fprintf(fp, "\n#ifdef SNMPTREE_TYPES\n");
1725 extract_all_enums(fp, gen_funcs_h);
1726 fprintf(fp, "\n#endif /* SNMPTREE_TYPES */\n\n");
1728 fprintf(fp, "#define %sCTREE_SIZE %u\n", file_prefix, tree_size);
1729 fprintf(fp, "extern const struct snmp_node %sctree[];\n", file_prefix);
1733 sprintf(fname, "%stree.c", file_prefix);
1734 if ((fp = fopen(fname, "w")) == NULL)
1735 err(1, "%s: ", fname);
1736 gen_table(fp, root);