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