Home | History | Annotate | Line # | Download | only in ntpd
keyword-gen.c revision 1.3.8.1
      1 /*	$NetBSD: keyword-gen.c,v 1.3.8.1 2014/12/25 02:28:09 snj Exp $	*/
      2 
      3 /*
      4  * keyword-gen.c -- generate keyword scanner finite state machine and
      5  *		    keyword_text array.
      6  *
      7  * This program is run to generate ntp_keyword.h
      8  * After making a change here, two output files should be committed at
      9  * the same time as keyword-gen.c:
     10  *	ntp_keyword.h
     11  *	keyword-gen-utd
     12  *
     13  * keyword-gen-utd is a sentinel used by Makefile.am to avoid compiling
     14  * keyword_gen.c and generating ntp_keyword.h if the input keyword-gen.c
     15  * has not changed.  This is not solely an optimization, it also breaks
     16  * a dependency chain that otherwise would cause programs to be compiled
     17  * when running "make dist" or "make distdir".  We want these to package
     18  * the existing source without building anything but a tarball.  See
     19  * [Bug 1470].
     20  */
     21 #include <config.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <time.h>
     25 
     26 #include <ntp_stdlib.h>
     27 #include <ntp_config.h>
     28 #include <lib_strbuf.h>
     29 #include "ntp_scanner.h"
     30 #include "ntp_parser.h"
     31 
     32 
     33 /* Define a structure to hold a (keyword, token) pair */
     34 struct key_tok {
     35 	char *	key;		/* Keyword */
     36 	u_short	token;		/* Associated Token */
     37 	follby	followedby;	/* nonzero indicates the next token(s)
     38 				   forced to be string(s) */
     39 };
     40 
     41 struct key_tok ntp_keywords[] = {
     42 { "...",		T_Ellipsis,		FOLLBY_TOKEN },
     43 { "allpeers",		T_Allpeers,		FOLLBY_TOKEN },
     44 { "automax",		T_Automax,		FOLLBY_TOKEN },
     45 { "broadcast",		T_Broadcast,		FOLLBY_STRING },
     46 { "broadcastclient",	T_Broadcastclient,	FOLLBY_TOKEN },
     47 { "broadcastdelay",	T_Broadcastdelay,	FOLLBY_TOKEN },
     48 { "ctl",		T_Ctl,			FOLLBY_TOKEN },
     49 { "disable",		T_Disable,		FOLLBY_TOKEN },
     50 { "driftfile",		T_Driftfile,		FOLLBY_STRING },
     51 { "enable",		T_Enable,		FOLLBY_TOKEN },
     52 { "end",		T_End,			FOLLBY_TOKEN },
     53 { "filegen",		T_Filegen,		FOLLBY_TOKEN },
     54 { "fudge",		T_Fudge,		FOLLBY_STRING },
     55 { "io",			T_Io,			FOLLBY_TOKEN },
     56 { "includefile",	T_Includefile,		FOLLBY_STRING },
     57 { "leapfile",		T_Leapfile,		FOLLBY_STRING },
     58 { "logconfig",		T_Logconfig,		FOLLBY_STRINGS_TO_EOC },
     59 { "logfile",		T_Logfile,		FOLLBY_STRING },
     60 { "manycastclient",	T_Manycastclient,	FOLLBY_STRING },
     61 { "manycastserver",	T_Manycastserver,	FOLLBY_STRINGS_TO_EOC },
     62 { "mem",		T_Mem,			FOLLBY_TOKEN },
     63 { "multicastclient",	T_Multicastclient,	FOLLBY_STRINGS_TO_EOC },
     64 { "peer",		T_Peer,			FOLLBY_STRING },
     65 { "phone",		T_Phone,		FOLLBY_STRINGS_TO_EOC },
     66 { "pidfile",		T_Pidfile,		FOLLBY_STRING },
     67 { "pool",		T_Pool,			FOLLBY_STRING },
     68 { "discard",		T_Discard,		FOLLBY_TOKEN },
     69 { "reset",		T_Reset,		FOLLBY_TOKEN },
     70 { "restrict",		T_Restrict,		FOLLBY_TOKEN },
     71 { "rlimit",		T_Rlimit,		FOLLBY_TOKEN },
     72 { "server",		T_Server,		FOLLBY_STRING },
     73 { "setvar",		T_Setvar,		FOLLBY_STRING },
     74 { "statistics",		T_Statistics,		FOLLBY_TOKEN },
     75 { "statsdir",		T_Statsdir,		FOLLBY_STRING },
     76 { "sys",		T_Sys,			FOLLBY_TOKEN },
     77 { "tick",		T_Tick,			FOLLBY_TOKEN },
     78 { "timer",		T_Timer,		FOLLBY_TOKEN },
     79 { "tinker",		T_Tinker,		FOLLBY_TOKEN },
     80 { "tos",		T_Tos,			FOLLBY_TOKEN },
     81 { "trap",		T_Trap,			FOLLBY_STRING },
     82 { "unconfig",		T_Unconfig,		FOLLBY_STRING },
     83 { "unpeer",		T_Unpeer,		FOLLBY_STRING },
     84 /* authentication_command */
     85 { "controlkey",		T_ControlKey,		FOLLBY_TOKEN },
     86 { "crypto",		T_Crypto,		FOLLBY_TOKEN },
     87 { "keys",		T_Keys,			FOLLBY_STRING },
     88 { "keysdir",		T_Keysdir,		FOLLBY_STRING },
     89 { "ntpsigndsocket",	T_NtpSignDsocket,	FOLLBY_STRING },
     90 { "requestkey",		T_Requestkey,		FOLLBY_TOKEN },
     91 { "revoke",		T_Revoke,		FOLLBY_TOKEN },
     92 { "trustedkey",		T_Trustedkey,		FOLLBY_TOKEN },
     93 /* IPv4/IPv6 protocol override flag */
     94 { "-4",			T_Ipv4_flag,		FOLLBY_TOKEN },
     95 { "-6",			T_Ipv6_flag,		FOLLBY_TOKEN },
     96 /* option */
     97 { "autokey",		T_Autokey,		FOLLBY_TOKEN },
     98 { "burst",		T_Burst,		FOLLBY_TOKEN },
     99 { "iburst",		T_Iburst,		FOLLBY_TOKEN },
    100 { "key",		T_Key,			FOLLBY_TOKEN },
    101 { "maxpoll",		T_Maxpoll,		FOLLBY_TOKEN },
    102 { "mdnstries",		T_Mdnstries,		FOLLBY_TOKEN },
    103 { "minpoll",		T_Minpoll,		FOLLBY_TOKEN },
    104 { "mode",		T_Mode,			FOLLBY_TOKEN },
    105 { "noselect",		T_Noselect,		FOLLBY_TOKEN },
    106 { "preempt",		T_Preempt,		FOLLBY_TOKEN },
    107 { "true",		T_True,			FOLLBY_TOKEN },
    108 { "prefer",		T_Prefer,		FOLLBY_TOKEN },
    109 { "ttl",		T_Ttl,			FOLLBY_TOKEN },
    110 { "version",		T_Version,		FOLLBY_TOKEN },
    111 { "xleave",		T_Xleave,		FOLLBY_TOKEN },
    112 /* crypto_command */
    113 { "host",		T_Host,			FOLLBY_STRING },
    114 { "ident",		T_Ident,		FOLLBY_STRING },
    115 { "pw",			T_Pw,			FOLLBY_STRING },
    116 { "randfile",		T_Randfile,		FOLLBY_STRING },
    117 { "digest",		T_Digest,		FOLLBY_STRING },
    118 /*** MONITORING COMMANDS ***/
    119 /* stat */
    120 { "clockstats",		T_Clockstats,		FOLLBY_TOKEN },
    121 { "cryptostats",	T_Cryptostats,		FOLLBY_TOKEN },
    122 { "loopstats",		T_Loopstats,		FOLLBY_TOKEN },
    123 { "peerstats",		T_Peerstats,		FOLLBY_TOKEN },
    124 { "rawstats",		T_Rawstats,		FOLLBY_TOKEN },
    125 { "sysstats", 		T_Sysstats,		FOLLBY_TOKEN },
    126 { "protostats",		T_Protostats,		FOLLBY_TOKEN },
    127 { "timingstats",	T_Timingstats,		FOLLBY_TOKEN },
    128 /* filegen_option */
    129 { "file",		T_File,			FOLLBY_STRING },
    130 { "link",		T_Link,			FOLLBY_TOKEN },
    131 { "nolink",		T_Nolink,		FOLLBY_TOKEN },
    132 { "type",		T_Type,			FOLLBY_TOKEN },
    133 /* filegen_type */
    134 { "age",		T_Age,			FOLLBY_TOKEN },
    135 { "day",		T_Day,			FOLLBY_TOKEN },
    136 { "month",		T_Month,		FOLLBY_TOKEN },
    137 { "none",		T_None,			FOLLBY_TOKEN },
    138 { "pid",		T_Pid,			FOLLBY_TOKEN },
    139 { "week",		T_Week,			FOLLBY_TOKEN },
    140 { "year",		T_Year,			FOLLBY_TOKEN },
    141 /*** ORPHAN MODE COMMANDS ***/
    142 /* tos_option */
    143 { "minclock",		T_Minclock,		FOLLBY_TOKEN },
    144 { "maxclock",		T_Maxclock,		FOLLBY_TOKEN },
    145 { "minsane",		T_Minsane,		FOLLBY_TOKEN },
    146 { "floor",		T_Floor,		FOLLBY_TOKEN },
    147 { "ceiling",		T_Ceiling,		FOLLBY_TOKEN },
    148 { "cohort",		T_Cohort,		FOLLBY_TOKEN },
    149 { "mindist",		T_Mindist,		FOLLBY_TOKEN },
    150 { "maxdist",		T_Maxdist,		FOLLBY_TOKEN },
    151 { "beacon",		T_Beacon,		FOLLBY_TOKEN },
    152 { "orphan",		T_Orphan,		FOLLBY_TOKEN },
    153 { "orphanwait",		T_Orphanwait,		FOLLBY_TOKEN },
    154 { "nonvolatile",	T_Nonvolatile,		FOLLBY_TOKEN },
    155 /* access_control_flag */
    156 { "default",		T_Default,		FOLLBY_TOKEN },
    157 { "source",		T_Source,		FOLLBY_TOKEN },
    158 { "flake",		T_Flake,		FOLLBY_TOKEN },
    159 { "ignore",		T_Ignore,		FOLLBY_TOKEN },
    160 { "limited",		T_Limited,		FOLLBY_TOKEN },
    161 { "mssntp",		T_Mssntp,		FOLLBY_TOKEN },
    162 { "kod",		T_Kod,			FOLLBY_TOKEN },
    163 { "lowpriotrap",	T_Lowpriotrap,		FOLLBY_TOKEN },
    164 { "mask",		T_Mask,			FOLLBY_TOKEN },
    165 { "nomodify",		T_Nomodify,		FOLLBY_TOKEN },
    166 { "nomrulist",		T_Nomrulist,		FOLLBY_TOKEN },
    167 { "nopeer",		T_Nopeer,		FOLLBY_TOKEN },
    168 { "noquery",		T_Noquery,		FOLLBY_TOKEN },
    169 { "noserve",		T_Noserve,		FOLLBY_TOKEN },
    170 { "notrap",		T_Notrap,		FOLLBY_TOKEN },
    171 { "notrust",		T_Notrust,		FOLLBY_TOKEN },
    172 { "ntpport",		T_Ntpport,		FOLLBY_TOKEN },
    173 /* discard_option */
    174 { "average",		T_Average,		FOLLBY_TOKEN },
    175 { "minimum",		T_Minimum,		FOLLBY_TOKEN },
    176 { "monitor",		T_Monitor,		FOLLBY_TOKEN },
    177 /* mru_option */
    178 { "incalloc",		T_Incalloc,		FOLLBY_TOKEN },
    179 { "incmem",		T_Incmem,		FOLLBY_TOKEN },
    180 { "initalloc",		T_Initalloc,		FOLLBY_TOKEN },
    181 { "initmem",		T_Initmem,		FOLLBY_TOKEN },
    182 { "mindepth",		T_Mindepth,		FOLLBY_TOKEN },
    183 { "maxage",		T_Maxage,		FOLLBY_TOKEN },
    184 { "maxdepth",		T_Maxdepth,		FOLLBY_TOKEN },
    185 { "maxmem",		T_Maxmem,		FOLLBY_TOKEN },
    186 { "mru",		T_Mru,			FOLLBY_TOKEN },
    187 /* fudge_factor */
    188 { "abbrev",		T_Abbrev,		FOLLBY_STRING },
    189 { "flag1",		T_Flag1,		FOLLBY_TOKEN },
    190 { "flag2",		T_Flag2,		FOLLBY_TOKEN },
    191 { "flag3",		T_Flag3,		FOLLBY_TOKEN },
    192 { "flag4",		T_Flag4,		FOLLBY_TOKEN },
    193 { "refid",		T_Refid,		FOLLBY_STRING },
    194 { "stratum",		T_Stratum,		FOLLBY_TOKEN },
    195 { "time1",		T_Time1,		FOLLBY_TOKEN },
    196 { "time2",		T_Time2,		FOLLBY_TOKEN },
    197 /* system_option */
    198 { "auth",		T_Auth,			FOLLBY_TOKEN },
    199 { "bclient",		T_Bclient,		FOLLBY_TOKEN },
    200 { "calibrate",		T_Calibrate,		FOLLBY_TOKEN },
    201 { "kernel",		T_Kernel,		FOLLBY_TOKEN },
    202 { "ntp",		T_Ntp,			FOLLBY_TOKEN },
    203 { "mode7",		T_Mode7,		FOLLBY_TOKEN },
    204 { "stats",		T_Stats,		FOLLBY_TOKEN },
    205 /* rlimit_option */
    206 { "memlock",		T_Memlock,		FOLLBY_TOKEN },
    207 { "stacksize",		T_Stacksize,		FOLLBY_TOKEN },
    208 { "filenum",		T_Filenum,		FOLLBY_TOKEN },
    209 /* tinker_option */
    210 { "step",		T_Step,			FOLLBY_TOKEN },
    211 { "panic",		T_Panic,		FOLLBY_TOKEN },
    212 { "dispersion",		T_Dispersion,		FOLLBY_TOKEN },
    213 { "stepout",		T_Stepout,		FOLLBY_TOKEN },
    214 { "allan",		T_Allan,		FOLLBY_TOKEN },
    215 { "huffpuff",		T_Huffpuff,		FOLLBY_TOKEN },
    216 { "freq",		T_Freq,			FOLLBY_TOKEN },
    217 /* miscellaneous_command */
    218 { "port",		T_Port,			FOLLBY_TOKEN },
    219 { "interface",		T_Interface,		FOLLBY_TOKEN },
    220 { "saveconfigdir",	T_Saveconfigdir,	FOLLBY_STRING },
    221 /* interface_command (ignore and interface already defined) */
    222 { "nic",		T_Nic,			FOLLBY_TOKEN },
    223 { "all",		T_All,			FOLLBY_TOKEN },
    224 { "ipv4",		T_Ipv4,			FOLLBY_TOKEN },
    225 { "ipv6",		T_Ipv6,			FOLLBY_TOKEN },
    226 { "wildcard",		T_Wildcard,		FOLLBY_TOKEN },
    227 { "listen",		T_Listen,		FOLLBY_TOKEN },
    228 { "drop",		T_Drop,			FOLLBY_TOKEN },
    229 /* simulator commands */
    230 { "simulate",		T_Simulate,		FOLLBY_TOKEN },
    231 { "simulation_duration",T_Sim_Duration,		FOLLBY_TOKEN },
    232 { "beep_delay",		T_Beep_Delay,		FOLLBY_TOKEN },
    233 { "duration",		T_Duration,		FOLLBY_TOKEN },
    234 { "server_offset",	T_Server_Offset,	FOLLBY_TOKEN },
    235 { "freq_offset",	T_Freq_Offset,		FOLLBY_TOKEN },
    236 { "wander",		T_Wander,		FOLLBY_TOKEN },
    237 { "jitter",		T_Jitter,		FOLLBY_TOKEN },
    238 { "prop_delay",		T_Prop_Delay,		FOLLBY_TOKEN },
    239 { "proc_delay",		T_Proc_Delay,		FOLLBY_TOKEN },
    240 };
    241 
    242 typedef struct big_scan_state_tag {
    243 	char	ch;		/* Character this state matches on */
    244 	char	followedby;	/* Forces next token(s) to T_String */
    245 	u_short	finishes_token;	/* nonzero ID if last keyword char */
    246 	u_short	match_next_s;	/* next state to check matching ch */
    247 	u_short	other_next_s;	/* next state to check if not ch */
    248 } big_scan_state;
    249 
    250 /*
    251  * Note: to increase MAXSTATES beyond 2048, be aware it is currently
    252  * crammed into 11 bits in scan_state form.  Raising to 4096 would be
    253  * relatively easy by storing the followedby value in a separate
    254  * array with one entry per token, and shrinking the char value to
    255  * 7 bits to free a bit for accepting/non-accepting.  More than 4096
    256  * states will require expanding scan_state beyond 32 bits each.
    257  */
    258 #define MAXSTATES	2048
    259 #define MAX_TOK_LEN	63
    260 
    261 const char *	current_keyword;/* for error reporting */
    262 big_scan_state	sst[MAXSTATES];	/* scanner FSM state entries */
    263 u_short		sst_highwater;	/* next entry index to consider */
    264 char *		symb[1024];	/* map token ID to symbolic name */
    265 
    266 /* for libntp */
    267 const char *	progname = "keyword-gen";
    268 
    269 int		main			(int, char **);
    270 static void	generate_preamble	(void);
    271 static void	generate_fsm		(void);
    272 static void	generate_token_text	(void);
    273 static u_short	create_keyword_scanner	(void);
    274 static u_short	create_scan_states	(char *, u_short, follby, u_short);
    275 int		compare_key_tok_id	(const void *, const void *);
    276 int		compare_key_tok_text	(const void *, const void *);
    277 void		populate_symb		(char *);
    278 const char *	symbname		(u_short);
    279 
    280 
    281 int main(int argc, char **argv)
    282 {
    283 	if (argc < 2) {
    284 		fprintf(stderr, "Usage:\n%s t_header.h\n", argv[0]);
    285 		exit(1);
    286 	}
    287 	debug = 1;
    288 
    289 	populate_symb(argv[1]);
    290 
    291 	generate_preamble();
    292 	generate_token_text();
    293 	generate_fsm();
    294 
    295 	return 0;
    296 }
    297 
    298 
    299 static void
    300 generate_preamble(void)
    301 {
    302 	time_t now;
    303 	char timestamp[128];
    304 	char preamble[] =
    305 "/*\n"
    306 " * ntp_keyword.h\n"
    307 " * \n"
    308 " * NOTE: edit this file with caution, it is generated by keyword-gen.c\n"
    309 " *\t Generated %s UTC	  diff_ignore_line\n"
    310 " *\n"
    311 " */\n"
    312 "#include \"ntp_scanner.h\"\n"
    313 "#include \"ntp_parser.h\"\n"
    314 "\n";
    315 
    316 	time(&now);
    317 	if (!strftime(timestamp, sizeof(timestamp),
    318 		      "%Y-%m-%d %H:%M:%S", gmtime(&now)))
    319 		timestamp[0] = '\0';
    320 
    321 	printf(preamble, timestamp);
    322 }
    323 
    324 
    325 static void
    326 generate_fsm(void)
    327 {
    328 	char rprefix[MAX_TOK_LEN + 1];
    329 	char prefix[MAX_TOK_LEN + 1];
    330 	char token_id_comment[16 + MAX_TOK_LEN + 1];
    331 	size_t prefix_len;
    332 	char *p;
    333 	char *r;
    334 	u_short initial_state;
    335 	u_short this_state;
    336 	u_short prev_state;
    337 	u_short state;
    338 	u_short i;
    339 	u_short token;
    340 
    341 	/*
    342 	 * Sort ntp_keywords in alphabetical keyword order.  This is
    343 	 * not necessary, but minimizes nonfunctional changes in the
    344 	 * generated finite state machine when keywords are modified.
    345 	 */
    346 	qsort(ntp_keywords, COUNTOF(ntp_keywords),
    347 	      sizeof(ntp_keywords[0]), compare_key_tok_text);
    348 
    349 	/*
    350 	 * To save space, reserve the state array entry matching each
    351 	 * token number for its terminal state, so the token identifier
    352 	 * does not need to be stored in each state, but can be
    353 	 * recovered trivially.  To mark the entry reserved,
    354 	 * finishes_token is nonzero.
    355 	 */
    356 
    357 	for (i = 0; i < COUNTOF(ntp_keywords); i++) {
    358 		token = ntp_keywords[i].token;
    359 		if (1 > token || token >= COUNTOF(sst)) {
    360 			fprintf(stderr,
    361 				"keyword-gen sst[%u] too small "
    362 				"for keyword '%s' id %d\n",
    363 				(int)COUNTOF(sst),
    364 				ntp_keywords[i].key,
    365 				token);
    366 			exit(4);
    367 		}
    368 		sst[token].finishes_token = token;
    369 	}
    370 
    371 	initial_state = create_keyword_scanner();
    372 
    373 	fprintf(stderr,
    374 		"%d keywords consumed %d states of %d max.\n",
    375 		(int)COUNTOF(ntp_keywords),
    376 		sst_highwater - 1,
    377 		(int)COUNTOF(sst) - 1);
    378 
    379 	printf("#define SCANNER_INIT_S %d\n\n", initial_state);
    380 
    381 	printf("const scan_state sst[%d] = {\n"
    382 	       "/*SS_T( ch,\tf-by, match, other ),\t\t\t\t */\n"
    383 	       "  0,\t\t\t\t      /* %5d %-17s */\n",
    384 	       sst_highwater,
    385 	       0, "");
    386 
    387 	for (i = 1; i < sst_highwater; i++) {
    388 
    389 		/* verify fields will fit */
    390 		if (sst[i].followedby & ~0x3) {
    391 			fprintf(stderr,
    392 				"keyword-gen internal error "
    393 				"sst[%d].followedby %d too big\n",
    394 				i, sst[i].followedby);
    395 			exit(7);
    396 		}
    397 
    398 		if (sst_highwater <= sst[i].match_next_s
    399 		    || sst[i].match_next_s & ~0x7ff) {
    400 			fprintf(stderr,
    401 				"keyword-gen internal error "
    402 				"sst[%d].match_next_s %d too big\n",
    403 				i, sst[i].match_next_s);
    404 			exit(8);
    405 		}
    406 
    407 		if (sst_highwater <= sst[i].other_next_s
    408 		    || sst[i].other_next_s & ~0x7ff) {
    409 			fprintf(stderr,
    410 				"keyword-gen internal error "
    411 				"sst[%d].other_next_s %d too big\n",
    412 				i, sst[i].other_next_s);
    413 			exit(9);
    414 		}
    415 
    416 		if (sst[i].finishes_token) {
    417 			snprintf(token_id_comment,
    418 				 sizeof(token_id_comment), "%5d %-17s",
    419 				 i, symbname(sst[i].finishes_token));
    420 			if (i != sst[i].finishes_token) {
    421 				fprintf(stderr,
    422 					"keyword-gen internal error "
    423 					"entry %d finishes token %d\n",
    424 					i, sst[i].finishes_token);
    425 				exit(5);
    426 			}
    427 		} else {
    428 		/*
    429 		 * Determine the keyword prefix that leads to this
    430 		 * state.  This is expensive but keyword-gen is run
    431 		 * only when it changes.  Distributing keyword-gen-utd
    432 		 * achieves that, which is why it must be committed
    433 		 * at the same time as keyword-gen.c and ntp_keyword.h.
    434 		 *
    435 		 * Scan the state array iteratively looking for a state
    436 		 * which leads to the current one, collecting matching
    437 		 * characters along the way.  There is only one such
    438 		 * path back to the starting state given the way our
    439 		 * scanner state machine is built and the practice of
    440 		 * using the spelling of the keyword as its T_* token
    441 		 * identifier, which results in never having two
    442 		 * spellings result in the same T_* value.
    443 		 */
    444 			prefix_len = 0;
    445 			prev_state = 0;
    446 			this_state = i;
    447 			do {
    448 				for (state = 1; state < sst_highwater; state++)
    449 					if (sst[state].other_next_s == this_state) {
    450 						this_state = state;
    451 						break;
    452 					} else if (sst[state].match_next_s == this_state) {
    453 						this_state = state;
    454 						rprefix[prefix_len] = sst[state].ch;
    455 						prefix_len++;
    456 						break;
    457 					}
    458 			} while (this_state != initial_state);
    459 
    460 			if (prefix_len) {
    461 				/* reverse rprefix into prefix */
    462 				p = prefix + prefix_len;
    463 				r = rprefix;
    464 				while (r < rprefix + prefix_len)
    465 					*--p = *r++;
    466 			}
    467 			prefix[prefix_len] = '\0';
    468 
    469 			snprintf(token_id_comment,
    470 				 sizeof(token_id_comment), "%5d %-17s",
    471 				 i, (initial_state == i)
    472 					? "[initial state]"
    473 					: prefix);
    474 		}
    475 
    476 		printf("  S_ST( '%c',\t%d,    %5u, %5u )%s /* %s */\n",
    477 		       sst[i].ch,
    478 		       sst[i].followedby,
    479 		       sst[i].match_next_s,
    480 		       sst[i].other_next_s,
    481 		       (i + 1 < sst_highwater)
    482 			   ? ","
    483 			   : " ",
    484 		       token_id_comment);
    485 	}
    486 
    487 	printf("};\n\n");
    488 }
    489 
    490 
    491 /* Define a function to create the states of the scanner. This function
    492  * is used by the create_keyword_scanner function below.
    493  *
    494  * This function takes a suffix of a keyword, the token to be returned on
    495  * recognizing the complete keyword, and any pre-existing state that exists
    496  * for some other keyword that has the same prefix as the current one.
    497  */
    498 static u_short
    499 create_scan_states(
    500 	char *	text,
    501 	u_short	token,
    502 	follby	followedby,
    503 	u_short	prev_state
    504 	)
    505 {
    506 	u_short my_state;
    507 	u_short return_state;
    508 	u_short prev_char_s;
    509 	u_short curr_char_s;
    510 
    511 	return_state = prev_state;
    512 	curr_char_s = prev_state;
    513 	prev_char_s = 0;
    514 
    515 	/* Find the correct position to insert the state.
    516 	 * All states should be in alphabetical order
    517 	 */
    518 	while (curr_char_s && (text[0] < sst[curr_char_s].ch)) {
    519 		prev_char_s = curr_char_s;
    520 		curr_char_s = sst[curr_char_s].other_next_s;
    521 	}
    522 
    523 	/*
    524 	 * Check if a previously seen keyword has the same prefix as
    525 	 * the current keyword.  If so, simply use the state for that
    526 	 * keyword as my_state, otherwise, allocate a new state.
    527 	 */
    528 	if (curr_char_s && (text[0] == sst[curr_char_s].ch)) {
    529 		my_state = curr_char_s;
    530 		if ('\0' == text[1]) {
    531 			fprintf(stderr,
    532 				"Duplicate entries for keyword '%s' in"
    533 				" keyword_gen.c ntp_keywords[].\n",
    534 				current_keyword);
    535 			exit(2);
    536 		}
    537 	} else {
    538 		do
    539 			my_state = sst_highwater++;
    540 		while (my_state < COUNTOF(sst)
    541 		       && sst[my_state].finishes_token);
    542 		if (my_state >= COUNTOF(sst)) {
    543 			fprintf(stderr,
    544 				"fatal, keyword scanner state array "
    545 				"sst[%d] is too small, modify\n"
    546 				"keyword-gen.c to increase.\n",
    547 				(int)COUNTOF(sst));
    548 			exit(3);
    549 		}
    550 		/* Store the next character of the keyword */
    551 		sst[my_state].ch = text[0];
    552 		sst[my_state].other_next_s = curr_char_s;
    553 		sst[my_state].followedby = FOLLBY_NON_ACCEPTING;
    554 
    555 		if (prev_char_s)
    556 			sst[prev_char_s].other_next_s = my_state;
    557 		else
    558 			return_state = my_state;
    559 	}
    560 
    561 	/* Check if the next character is '\0'.
    562 	 * If yes, we are done with the recognition and this is an accepting
    563 	 * state.
    564 	 * If not, we need to continue scanning
    565 	 */
    566 	if ('\0' == text[1]) {
    567 		sst[my_state].finishes_token = (u_short)token;
    568 		sst[my_state].followedby = (char)followedby;
    569 
    570 		if (sst[token].finishes_token != (u_short)token) {
    571 			fprintf(stderr,
    572 				"fatal, sst[%d] not reserved for %s.\n",
    573 				token, symbname(token));
    574 			exit(6);
    575 		}
    576 		/* relocate so token id is sst[] index */
    577 		if (my_state != token) {
    578 			sst[token] = sst[my_state];
    579 			ZERO(sst[my_state]);
    580 			do
    581 				sst_highwater--;
    582 			while (sst[sst_highwater].finishes_token);
    583 			my_state = token;
    584 			if (prev_char_s)
    585 				sst[prev_char_s].other_next_s = my_state;
    586 			else
    587 				return_state = my_state;
    588 		}
    589 	} else
    590 		sst[my_state].match_next_s =
    591 		    create_scan_states(
    592 			&text[1],
    593 			token,
    594 			followedby,
    595 			sst[my_state].match_next_s);
    596 
    597 	return return_state;
    598 }
    599 
    600 
    601 /* Define a function that takes a list of (keyword, token) values and
    602  * creates a keywords scanner out of it.
    603  */
    604 
    605 static u_short
    606 create_keyword_scanner(void)
    607 {
    608 	u_short scanner;
    609 	u_short i;
    610 
    611 	sst_highwater = 1;	/* index 0 invalid, unused */
    612 	scanner = 0;
    613 
    614 	for (i = 0; i < COUNTOF(ntp_keywords); i++) {
    615 		current_keyword = ntp_keywords[i].key;
    616 		scanner =
    617 		    create_scan_states(
    618 			ntp_keywords[i].key,
    619 			ntp_keywords[i].token,
    620 			ntp_keywords[i].followedby,
    621 			scanner);
    622 	}
    623 
    624 	return scanner;
    625 }
    626 
    627 
    628 static void
    629 generate_token_text(void)
    630 {
    631 	u_short lowest_id;
    632 	u_short highest_id;
    633 	u_short id_count;
    634 	u_short id;
    635 	u_short i;
    636 
    637 	/* sort ntp_keywords in token ID order */
    638 	qsort(ntp_keywords, COUNTOF(ntp_keywords),
    639 	      sizeof(ntp_keywords[0]), compare_key_tok_id);
    640 
    641 	lowest_id = ntp_keywords[0].token;
    642 	highest_id = ntp_keywords[COUNTOF(ntp_keywords) - 1].token;
    643 	id_count = highest_id - lowest_id + 1;
    644 
    645 	printf("#define LOWEST_KEYWORD_ID %d\n\n", lowest_id);
    646 
    647 	printf("const char * const keyword_text[%d] = {", id_count);
    648 
    649 	id = lowest_id;
    650 	i = 0;
    651 	while (i < COUNTOF(ntp_keywords)) {
    652 		while (id < ntp_keywords[i].token) {
    653 			printf(",\n\t/* %-5d %5d %20s */\tNULL",
    654 			       id - lowest_id, id, symbname(id));
    655 			id++;
    656 		}
    657 		if (i > 0)
    658 			printf(",");
    659 		printf("\n\t/* %-5d %5d %20s */\t\"%s\"",
    660 		       id - lowest_id, id, symbname(id),
    661 		       ntp_keywords[i].key);
    662 		i++;
    663 		id++;
    664 	}
    665 
    666 	printf("\n};\n\n");
    667 }
    668 
    669 
    670 int
    671 compare_key_tok_id(
    672 	const void *a1,
    673 	const void *a2
    674 	)
    675 {
    676 	const struct key_tok *p1 = a1;
    677 	const struct key_tok *p2 = a2;
    678 
    679 	if (p1->token == p2->token)
    680 		return 0;
    681 
    682 	if (p1->token < p2->token)
    683 		return -1;
    684 	else
    685 		return 1;
    686 }
    687 
    688 
    689 int
    690 compare_key_tok_text(
    691 	const void *a1,
    692 	const void *a2
    693 	)
    694 {
    695 	const struct key_tok *p1 = a1;
    696 	const struct key_tok *p2 = a2;
    697 
    698 	return strcmp(p1->key, p2->key);
    699 }
    700 
    701 
    702 /*
    703  * populate_symb() - populate symb[] lookup array with symbolic token
    704  *		     names such that symb[T_Age] == "T_Age", etc.
    705  */
    706 void
    707 populate_symb(
    708 	char *header_file
    709 	)
    710 {
    711 	FILE *	yh;
    712 	char	line[2 * MAX_TOK_LEN];
    713 	char	name[2 * MAX_TOK_LEN];
    714 	int	token;
    715 
    716 	yh = fopen(header_file, "r");
    717 	if (NULL == yh) {
    718 		perror("unable to open yacc/bison header file");
    719 		exit(4);
    720 	}
    721 
    722 	while (NULL != fgets(line, sizeof(line), yh))
    723 		if (2 == sscanf(line, "#define %s %d", name, &token)
    724 		    && 'T' == name[0] && '_' == name[1] && token >= 0
    725 		    && token < COUNTOF(symb)) {
    726 
    727 			symb[token] = estrdup(name);
    728 			if (strlen(name) > MAX_TOK_LEN) {
    729 				fprintf(stderr,
    730 					"MAX_TOK_LEN %d too small for '%s'\n"
    731 					"Edit keyword-gen.c to raise.\n",
    732 					MAX_TOK_LEN, name);
    733 				exit(10);
    734 			}
    735 		}
    736 	fclose(yh);
    737 }
    738 
    739 
    740 const char *
    741 symbname(
    742 	u_short token
    743 	)
    744 {
    745 	char *name;
    746 
    747 	if (token < COUNTOF(symb) && symb[token] != NULL) {
    748 		name = symb[token];
    749 	} else {
    750 		LIB_GETBUF(name);
    751 		snprintf(name, LIB_BUFLENGTH, "%d", token);
    752 	}
    753 
    754 	return name;
    755 }
    756