tic.c revision 166124
1/****************************************************************************
2 * Copyright (c) 1998-2005,2006 Free Software Foundation, Inc.              *
3 *                                                                          *
4 * Permission is hereby granted, free of charge, to any person obtaining a  *
5 * copy of this software and associated documentation files (the            *
6 * "Software"), to deal in the Software without restriction, including      *
7 * without limitation the rights to use, copy, modify, merge, publish,      *
8 * distribute, distribute with modifications, sublicense, and/or sell       *
9 * copies of the Software, and to permit persons to whom the Software is    *
10 * furnished to do so, subject to the following conditions:                 *
11 *                                                                          *
12 * The above copyright notice and this permission notice shall be included  *
13 * in all copies or substantial portions of the Software.                   *
14 *                                                                          *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22 *                                                                          *
23 * Except as contained in this notice, the name(s) of the above copyright   *
24 * holders shall not be used in advertising or otherwise to promote the     *
25 * sale, use or other dealings in this Software without prior written       *
26 * authorization.                                                           *
27 ****************************************************************************/
28
29/****************************************************************************
30 *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31 *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32 *     and: Thomas E. Dickey 1996 on                                        *
33 ****************************************************************************/
34
35/*
36 *	tic.c --- Main program for terminfo compiler
37 *			by Eric S. Raymond
38 *
39 */
40
41#include <progs.priv.h>
42#include <sys/stat.h>
43
44#include <dump_entry.h>
45#include <transform.h>
46
47MODULE_ID("$Id: tic.c,v 1.131 2006/12/02 22:13:17 tom Exp $")
48
49const char *_nc_progname = "tic";
50
51static FILE *log_fp;
52static FILE *tmp_fp;
53static bool capdump = FALSE;	/* running as infotocap? */
54static bool infodump = FALSE;	/* running as captoinfo? */
55static bool showsummary = FALSE;
56static const char *to_remove;
57
58static void (*save_check_termtype) (TERMTYPE *, bool);
59static void check_termtype(TERMTYPE *tt, bool);
60
61static const char usage_string[] = "\
62[-e names] \
63[-o dir] \
64[-R name] \
65[-v[n]] \
66[-V] \
67[-w[n]] \
68[-\
691\
70a\
71C\
72c\
73f\
74G\
75g\
76I\
77L\
78N\
79r\
80s\
81T\
82t\
83U\
84x\
85] \
86source-file\n";
87
88static void
89cleanup(void)
90{
91    if (tmp_fp != 0)
92	fclose(tmp_fp);
93    if (to_remove != 0) {
94#if HAVE_REMOVE
95	remove(to_remove);
96#else
97	unlink(to_remove);
98#endif
99    }
100}
101
102static void
103failed(const char *msg)
104{
105    perror(msg);
106    cleanup();
107    ExitProgram(EXIT_FAILURE);
108}
109
110static void
111usage(void)
112{
113    static const char *const tbl[] =
114    {
115	"Options:",
116	"  -1         format translation output one capability per line",
117#if NCURSES_XNAMES
118	"  -a         retain commented-out capabilities (sets -x also)",
119#endif
120	"  -C         translate entries to termcap source form",
121	"  -c         check only, validate input without compiling or translating",
122	"  -e<names>  translate/compile only entries named by comma-separated list",
123	"  -f         format complex strings for readability",
124	"  -G         format %{number} to %'char'",
125	"  -g         format %'char' to %{number}",
126	"  -I         translate entries to terminfo source form",
127	"  -L         translate entries to full terminfo source form",
128	"  -N         disable smart defaults for source translation",
129	"  -o<dir>    set output directory for compiled entry writes",
130	"  -R<name>   restrict translation to given terminfo/termcap version",
131	"  -r         force resolution of all use entries in source translation",
132	"  -s         print summary statistics",
133	"  -T         remove size-restrictions on compiled description",
134#if NCURSES_XNAMES
135	"  -t         suppress commented-out capabilities",
136#endif
137	"  -U         suppress post-processing of entries",
138	"  -V         print version",
139	"  -v[n]      set verbosity level",
140	"  -w[n]      set format width for translation output",
141#if NCURSES_XNAMES
142	"  -x         treat unknown capabilities as user-defined",
143#endif
144	"",
145	"Parameters:",
146	"  <file>     file to translate or compile"
147    };
148    size_t j;
149
150    fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
151    for (j = 0; j < SIZEOF(tbl); j++) {
152	fputs(tbl[j], stderr);
153	putc('\n', stderr);
154    }
155    ExitProgram(EXIT_FAILURE);
156}
157
158#define L_BRACE '{'
159#define R_BRACE '}'
160#define S_QUOTE '\'';
161
162static void
163write_it(ENTRY * ep)
164{
165    unsigned n;
166    int ch;
167    char *s, *d, *t;
168    char result[MAX_ENTRY_SIZE];
169
170    /*
171     * Look for strings that contain %{number}, convert them to %'char',
172     * which is shorter and runs a little faster.
173     */
174    for (n = 0; n < STRCOUNT; n++) {
175	s = ep->tterm.Strings[n];
176	if (VALID_STRING(s)
177	    && strchr(s, L_BRACE) != 0) {
178	    d = result;
179	    t = s;
180	    while ((ch = *t++) != 0) {
181		*d++ = ch;
182		if (ch == '\\') {
183		    *d++ = *t++;
184		} else if ((ch == '%')
185			   && (*t == L_BRACE)) {
186		    char *v = 0;
187		    long value = strtol(t + 1, &v, 0);
188		    if (v != 0
189			&& *v == R_BRACE
190			&& value > 0
191			&& value != '\\'	/* FIXME */
192			&& value < 127
193			&& isprint((int) value)) {
194			*d++ = S_QUOTE;
195			*d++ = (int) value;
196			*d++ = S_QUOTE;
197			t = (v + 1);
198		    }
199		}
200	    }
201	    *d = 0;
202	    if (strlen(result) < strlen(s))
203		strcpy(s, result);
204	}
205    }
206
207    _nc_set_type(_nc_first_name(ep->tterm.term_names));
208    _nc_curr_line = ep->startline;
209    _nc_write_entry(&ep->tterm);
210}
211
212static bool
213immedhook(ENTRY * ep GCC_UNUSED)
214/* write out entries with no use capabilities immediately to save storage */
215{
216#if !HAVE_BIG_CORE
217    /*
218     * This is strictly a core-economy kluge.  The really clean way to handle
219     * compilation is to slurp the whole file into core and then do all the
220     * name-collision checks and entry writes in one swell foop.  But the
221     * terminfo master file is large enough that some core-poor systems swap
222     * like crazy when you compile it this way...there have been reports of
223     * this process taking *three hours*, rather than the twenty seconds or
224     * less typical on my development box.
225     *
226     * So.  This hook *immediately* writes out the referenced entry if it
227     * has no use capabilities.  The compiler main loop refrains from
228     * adding the entry to the in-core list when this hook fires.  If some
229     * other entry later needs to reference an entry that got written
230     * immediately, that's OK; the resolution code will fetch it off disk
231     * when it can't find it in core.
232     *
233     * Name collisions will still be detected, just not as cleanly.  The
234     * write_entry() code complains before overwriting an entry that
235     * postdates the time of tic's first call to write_entry().  Thus
236     * it will complain about overwriting entries newly made during the
237     * tic run, but not about overwriting ones that predate it.
238     *
239     * The reason this is a hook, and not in line with the rest of the
240     * compiler code, is that the support for termcap fallback cannot assume
241     * it has anywhere to spool out these entries!
242     *
243     * The _nc_set_type() call here requires a compensating one in
244     * _nc_parse_entry().
245     *
246     * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
247     * make tic a bit faster (because the resolution code won't have to do
248     * disk I/O nearly as often).
249     */
250    if (ep->nuses == 0) {
251	int oldline = _nc_curr_line;
252
253	write_it(ep);
254	_nc_curr_line = oldline;
255	free(ep->tterm.str_table);
256	return (TRUE);
257    }
258#endif /* HAVE_BIG_CORE */
259    return (FALSE);
260}
261
262static void
263put_translate(int c)
264/* emit a comment char, translating terminfo names to termcap names */
265{
266    static bool in_name = FALSE;
267    static size_t have, used;
268    static char *namebuf, *suffix;
269
270    if (in_name) {
271	if (used + 1 >= have) {
272	    have += 132;
273	    namebuf = typeRealloc(char, have, namebuf);
274	    suffix = typeRealloc(char, have, suffix);
275	}
276	if (c == '\n' || c == '@') {
277	    namebuf[used++] = '\0';
278	    (void) putchar('<');
279	    (void) fputs(namebuf, stdout);
280	    putchar(c);
281	    in_name = FALSE;
282	} else if (c != '>') {
283	    namebuf[used++] = c;
284	} else {		/* ah! candidate name! */
285	    char *up;
286	    NCURSES_CONST char *tp;
287
288	    namebuf[used++] = '\0';
289	    in_name = FALSE;
290
291	    suffix[0] = '\0';
292	    if ((up = strchr(namebuf, '#')) != 0
293		|| (up = strchr(namebuf, '=')) != 0
294		|| ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
295		(void) strcpy(suffix, up);
296		*up = '\0';
297	    }
298
299	    if ((tp = nametrans(namebuf)) != 0) {
300		(void) putchar(':');
301		(void) fputs(tp, stdout);
302		(void) fputs(suffix, stdout);
303		(void) putchar(':');
304	    } else {
305		/* couldn't find a translation, just dump the name */
306		(void) putchar('<');
307		(void) fputs(namebuf, stdout);
308		(void) fputs(suffix, stdout);
309		(void) putchar('>');
310	    }
311	}
312    } else {
313	used = 0;
314	if (c == '<') {
315	    in_name = TRUE;
316	} else {
317	    putchar(c);
318	}
319    }
320}
321
322/* Returns a string, stripped of leading/trailing whitespace */
323static char *
324stripped(char *src)
325{
326    while (isspace(UChar(*src)))
327	src++;
328    if (*src != '\0') {
329	char *dst = strcpy((char *) malloc(strlen(src) + 1), src);
330	size_t len = strlen(dst);
331	while (--len != 0 && isspace(UChar(dst[len])))
332	    dst[len] = '\0';
333	return dst;
334    }
335    return 0;
336}
337
338static FILE *
339open_input(const char *filename)
340{
341    FILE *fp = fopen(filename, "r");
342    struct stat sb;
343
344    if (fp == 0) {
345	fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
346	ExitProgram(EXIT_FAILURE);
347    }
348    if (fstat(fileno(fp), &sb) < 0
349	|| (sb.st_mode & S_IFMT) != S_IFREG) {
350	fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
351	ExitProgram(EXIT_FAILURE);
352    }
353    return fp;
354}
355
356/* Parse the "-e" option-value into a list of names */
357static const char **
358make_namelist(char *src)
359{
360    const char **dst = 0;
361
362    char *s, *base;
363    unsigned pass, n, nn;
364    char buffer[BUFSIZ];
365
366    if (src == 0) {
367	/* EMPTY */ ;
368    } else if (strchr(src, '/') != 0) {		/* a filename */
369	FILE *fp = open_input(src);
370
371	for (pass = 1; pass <= 2; pass++) {
372	    nn = 0;
373	    while (fgets(buffer, sizeof(buffer), fp) != 0) {
374		if ((s = stripped(buffer)) != 0) {
375		    if (dst != 0)
376			dst[nn] = s;
377		    nn++;
378		}
379	    }
380	    if (pass == 1) {
381		dst = typeCalloc(const char *, nn + 1);
382		rewind(fp);
383	    }
384	}
385	fclose(fp);
386    } else {			/* literal list of names */
387	for (pass = 1; pass <= 2; pass++) {
388	    for (n = nn = 0, base = src;; n++) {
389		int mark = src[n];
390		if (mark == ',' || mark == '\0') {
391		    if (pass == 1) {
392			nn++;
393		    } else {
394			src[n] = '\0';
395			if ((s = stripped(base)) != 0)
396			    dst[nn++] = s;
397			base = &src[n + 1];
398		    }
399		}
400		if (mark == '\0')
401		    break;
402	    }
403	    if (pass == 1)
404		dst = typeCalloc(const char *, nn + 1);
405	}
406    }
407    if (showsummary) {
408	fprintf(log_fp, "Entries that will be compiled:\n");
409	for (n = 0; dst[n] != 0; n++)
410	    fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
411    }
412    return dst;
413}
414
415static bool
416matches(const char **needle, const char *haystack)
417/* does entry in needle list match |-separated field in haystack? */
418{
419    bool code = FALSE;
420    size_t n;
421
422    if (needle != 0) {
423	for (n = 0; needle[n] != 0; n++) {
424	    if (_nc_name_match(haystack, needle[n], "|")) {
425		code = TRUE;
426		break;
427	    }
428	}
429    } else
430	code = TRUE;
431    return (code);
432}
433
434static FILE *
435open_tempfile(char *name)
436{
437    FILE *result = 0;
438#if HAVE_MKSTEMP
439    int fd = mkstemp(name);
440    if (fd >= 0)
441	result = fdopen(fd, "w");
442#else
443    if (tmpnam(name) != 0)
444	result = fopen(name, "w");
445#endif
446    return result;
447}
448
449int
450main(int argc, char *argv[])
451{
452    char my_tmpname[PATH_MAX];
453    int v_opt = -1, debug_level;
454    int smart_defaults = TRUE;
455    char *termcap;
456    ENTRY *qp;
457
458    int this_opt, last_opt = '?';
459
460    int outform = F_TERMINFO;	/* output format */
461    int sortmode = S_TERMINFO;	/* sort_mode */
462
463    int width = 60;
464    bool formatted = FALSE;	/* reformat complex strings? */
465    bool literal = FALSE;	/* suppress post-processing? */
466    int numbers = 0;		/* format "%'char'" to/from "%{number}" */
467    bool forceresolve = FALSE;	/* force resolution */
468    bool limited = TRUE;
469    char *tversion = (char *) NULL;
470    const char *source_file = "terminfo";
471    const char **namelst = 0;
472    char *outdir = (char *) NULL;
473    bool check_only = FALSE;
474    bool suppress_untranslatable = FALSE;
475
476    log_fp = stderr;
477
478    _nc_progname = _nc_rootname(argv[0]);
479
480    if ((infodump = (strcmp(_nc_progname, PROG_CAPTOINFO) == 0)) != FALSE) {
481	outform = F_TERMINFO;
482	sortmode = S_TERMINFO;
483    }
484    if ((capdump = (strcmp(_nc_progname, PROG_INFOTOCAP) == 0)) != FALSE) {
485	outform = F_TERMCAP;
486	sortmode = S_TERMCAP;
487    }
488#if NCURSES_XNAMES
489    use_extended_names(FALSE);
490#endif
491
492    /*
493     * Processing arguments is a little complicated, since someone made a
494     * design decision to allow the numeric values for -w, -v options to
495     * be optional.
496     */
497    while ((this_opt = getopt(argc, argv,
498			      "0123456789CILNR:TUVace:fGgo:rstvwx")) != EOF) {
499	if (isdigit(this_opt)) {
500	    switch (last_opt) {
501	    case 'v':
502		v_opt = (v_opt * 10) + (this_opt - '0');
503		break;
504	    case 'w':
505		width = (width * 10) + (this_opt - '0');
506		break;
507	    default:
508		if (this_opt != '1')
509		    usage();
510		last_opt = this_opt;
511		width = 0;
512	    }
513	    continue;
514	}
515	switch (this_opt) {
516	case 'C':
517	    capdump = TRUE;
518	    outform = F_TERMCAP;
519	    sortmode = S_TERMCAP;
520	    break;
521	case 'I':
522	    infodump = TRUE;
523	    outform = F_TERMINFO;
524	    sortmode = S_TERMINFO;
525	    break;
526	case 'L':
527	    infodump = TRUE;
528	    outform = F_VARIABLE;
529	    sortmode = S_VARIABLE;
530	    break;
531	case 'N':
532	    smart_defaults = FALSE;
533	    literal = TRUE;
534	    break;
535	case 'R':
536	    tversion = optarg;
537	    break;
538	case 'T':
539	    limited = FALSE;
540	    break;
541	case 'U':
542	    literal = TRUE;
543	    break;
544	case 'V':
545	    puts(curses_version());
546	    return EXIT_SUCCESS;
547	case 'c':
548	    check_only = TRUE;
549	    break;
550	case 'e':
551	    namelst = make_namelist(optarg);
552	    break;
553	case 'f':
554	    formatted = TRUE;
555	    break;
556	case 'G':
557	    numbers = 1;
558	    break;
559	case 'g':
560	    numbers = -1;
561	    break;
562	case 'o':
563	    outdir = optarg;
564	    break;
565	case 'r':
566	    forceresolve = TRUE;
567	    break;
568	case 's':
569	    showsummary = TRUE;
570	    break;
571	case 'v':
572	    v_opt = 0;
573	    break;
574	case 'w':
575	    width = 0;
576	    break;
577#if NCURSES_XNAMES
578	case 't':
579	    _nc_disable_period = FALSE;
580	    suppress_untranslatable = TRUE;
581	    break;
582	case 'a':
583	    _nc_disable_period = TRUE;
584	    /* FALLTHRU */
585	case 'x':
586	    use_extended_names(TRUE);
587	    break;
588#endif
589	default:
590	    usage();
591	}
592	last_opt = this_opt;
593    }
594
595    debug_level = (v_opt > 0) ? v_opt : (v_opt == 0);
596    set_trace_level(debug_level);
597
598    if (_nc_tracing) {
599	save_check_termtype = _nc_check_termtype2;
600	_nc_check_termtype2 = check_termtype;
601    }
602#if !HAVE_BIG_CORE
603    /*
604     * Aaargh! immedhook seriously hoses us!
605     *
606     * One problem with immedhook is it means we can't do -e.  Problem
607     * is that we can't guarantee that for each terminal listed, all the
608     * terminals it depends on will have been kept in core for reference
609     * resolution -- in fact it's certain the primitive types at the end
610     * of reference chains *won't* be in core unless they were explicitly
611     * in the select list themselves.
612     */
613    if (namelst && (!infodump && !capdump)) {
614	(void) fprintf(stderr,
615		       "Sorry, -e can't be used without -I or -C\n");
616	cleanup();
617	ExitProgram(EXIT_FAILURE);
618    }
619#endif /* HAVE_BIG_CORE */
620
621    if (optind < argc) {
622	source_file = argv[optind++];
623	if (optind < argc) {
624	    fprintf(stderr,
625		    "%s: Too many file names.  Usage:\n\t%s %s",
626		    _nc_progname,
627		    _nc_progname,
628		    usage_string);
629	    ExitProgram(EXIT_FAILURE);
630	}
631    } else {
632	if (infodump == TRUE) {
633	    /* captoinfo's no-argument case */
634	    source_file = "/etc/termcap";
635	    if ((termcap = getenv("TERMCAP")) != 0
636		&& (namelst = make_namelist(getenv("TERM"))) != 0) {
637		if (access(termcap, F_OK) == 0) {
638		    /* file exists */
639		    source_file = termcap;
640		} else if ((tmp_fp = open_tempfile(strcpy(my_tmpname,
641							  "/tmp/XXXXXX")))
642			   != 0) {
643		    source_file = my_tmpname;
644		    fprintf(tmp_fp, "%s\n", termcap);
645		    fclose(tmp_fp);
646		    tmp_fp = open_input(source_file);
647		    to_remove = source_file;
648		} else {
649		    failed("tmpnam");
650		}
651	    }
652	} else {
653	    /* tic */
654	    fprintf(stderr,
655		    "%s: File name needed.  Usage:\n\t%s %s",
656		    _nc_progname,
657		    _nc_progname,
658		    usage_string);
659	    cleanup();
660	    ExitProgram(EXIT_FAILURE);
661	}
662    }
663
664    if (tmp_fp == 0)
665	tmp_fp = open_input(source_file);
666
667    if (infodump)
668	dump_init(tversion,
669		  smart_defaults
670		  ? outform
671		  : F_LITERAL,
672		  sortmode, width, debug_level, formatted);
673    else if (capdump)
674	dump_init(tversion,
675		  outform,
676		  sortmode, width, debug_level, FALSE);
677
678    /* parse entries out of the source file */
679    _nc_set_source(source_file);
680#if !HAVE_BIG_CORE
681    if (!(check_only || infodump || capdump))
682	_nc_set_writedir(outdir);
683#endif /* HAVE_BIG_CORE */
684    _nc_read_entry_source(tmp_fp, (char *) NULL,
685			  !smart_defaults || literal, FALSE,
686			  ((check_only || infodump || capdump)
687			   ? NULLHOOK
688			   : immedhook));
689
690    /* do use resolution */
691    if (check_only || (!infodump && !capdump) || forceresolve) {
692	if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
693	    cleanup();
694	    ExitProgram(EXIT_FAILURE);
695	}
696    }
697
698    /* length check */
699    if (check_only && (capdump || infodump)) {
700	for_entry_list(qp) {
701	    if (matches(namelst, qp->tterm.term_names)) {
702		int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
703
704		if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
705		    (void) fprintf(stderr,
706				   "warning: resolved %s entry is %d bytes long\n",
707				   _nc_first_name(qp->tterm.term_names),
708				   len);
709	    }
710	}
711    }
712
713    /* write or dump all entries */
714    if (!check_only) {
715	if (!infodump && !capdump) {
716	    _nc_set_writedir(outdir);
717	    for_entry_list(qp) {
718		if (matches(namelst, qp->tterm.term_names))
719		    write_it(qp);
720	    }
721	} else {
722	    /* this is in case infotocap() generates warnings */
723	    _nc_curr_col = _nc_curr_line = -1;
724
725	    for_entry_list(qp) {
726		if (matches(namelst, qp->tterm.term_names)) {
727		    int j = qp->cend - qp->cstart;
728		    int len = 0;
729
730		    /* this is in case infotocap() generates warnings */
731		    _nc_set_type(_nc_first_name(qp->tterm.term_names));
732
733		    (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
734		    while (j-- > 0) {
735			if (infodump)
736			    (void) putchar(fgetc(tmp_fp));
737			else
738			    put_translate(fgetc(tmp_fp));
739		    }
740
741		    dump_entry(&qp->tterm, suppress_untranslatable,
742			       limited, numbers, NULL);
743		    for (j = 0; j < qp->nuses; j++)
744			dump_uses(qp->uses[j].name, !capdump);
745		    len = show_entry();
746		    if (debug_level != 0 && !limited)
747			printf("# length=%d\n", len);
748		}
749	    }
750	    if (!namelst && _nc_tail) {
751		int c, oldc = '\0';
752		bool in_comment = FALSE;
753		bool trailing_comment = FALSE;
754
755		(void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
756		while ((c = fgetc(tmp_fp)) != EOF) {
757		    if (oldc == '\n') {
758			if (c == '#') {
759			    trailing_comment = TRUE;
760			    in_comment = TRUE;
761			} else {
762			    in_comment = FALSE;
763			}
764		    }
765		    if (trailing_comment
766			&& (in_comment || (oldc == '\n' && c == '\n')))
767			putchar(c);
768		    oldc = c;
769		}
770	    }
771	}
772    }
773
774    /* Show the directory into which entries were written, and the total
775     * number of entries
776     */
777    if (showsummary
778	&& (!(check_only || infodump || capdump))) {
779	int total = _nc_tic_written();
780	if (total != 0)
781	    fprintf(log_fp, "%d entries written to %s\n",
782		    total,
783		    _nc_tic_dir((char *) 0));
784	else
785	    fprintf(log_fp, "No entries written\n");
786    }
787    cleanup();
788    ExitProgram(EXIT_SUCCESS);
789}
790
791/*
792 * This bit of legerdemain turns all the terminfo variable names into
793 * references to locations in the arrays Booleans, Numbers, and Strings ---
794 * precisely what's needed (see comp_parse.c).
795 */
796#undef CUR
797#define CUR tp->
798
799/*
800 * Check if the alternate character-set capabilities are consistent.
801 */
802static void
803check_acs(TERMTYPE *tp)
804{
805    if (VALID_STRING(acs_chars)) {
806	const char *boxes = "lmkjtuvwqxn";
807	char mapped[256];
808	char missing[256];
809	const char *p;
810	char *q;
811
812	memset(mapped, 0, sizeof(mapped));
813	for (p = acs_chars; *p != '\0'; p += 2) {
814	    if (p[1] == '\0') {
815		_nc_warning("acsc has odd number of characters");
816		break;
817	    }
818	    mapped[UChar(p[0])] = p[1];
819	}
820	if (mapped[UChar('I')] && !mapped[UChar('i')]) {
821	    _nc_warning("acsc refers to 'I', which is probably an error");
822	}
823	for (p = boxes, q = missing; *p != '\0'; ++p) {
824	    if (!mapped[UChar(p[0])]) {
825		*q++ = p[0];
826	    }
827	    *q = '\0';
828	}
829	if (*missing != '\0' && strcmp(missing, boxes)) {
830	    _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
831	}
832    }
833}
834
835/*
836 * Check if the color capabilities are consistent
837 */
838static void
839check_colors(TERMTYPE *tp)
840{
841    if ((max_colors > 0) != (max_pairs > 0)
842	|| ((max_colors > max_pairs) && (initialize_pair == 0)))
843	_nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
844		    max_colors, max_pairs);
845
846    PAIRED(set_foreground, set_background);
847    PAIRED(set_a_foreground, set_a_background);
848    PAIRED(set_color_pair, initialize_pair);
849
850    if (VALID_STRING(set_foreground)
851	&& VALID_STRING(set_a_foreground)
852	&& !_nc_capcmp(set_foreground, set_a_foreground))
853	_nc_warning("expected setf/setaf to be different");
854
855    if (VALID_STRING(set_background)
856	&& VALID_STRING(set_a_background)
857	&& !_nc_capcmp(set_background, set_a_background))
858	_nc_warning("expected setb/setab to be different");
859
860    /* see: has_colors() */
861    if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
862	&& (((set_foreground != NULL)
863	     && (set_background != NULL))
864	    || ((set_a_foreground != NULL)
865		&& (set_a_background != NULL))
866	    || set_color_pair)) {
867	if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
868	    _nc_warning("expected either op/oc string for resetting colors");
869    }
870}
871
872static int
873keypad_final(const char *string)
874{
875    int result = '\0';
876
877    if (VALID_STRING(string)
878	&& *string++ == '\033'
879	&& *string++ == 'O'
880	&& strlen(string) == 1) {
881	result = *string;
882    }
883
884    return result;
885}
886
887static int
888keypad_index(const char *string)
889{
890    char *test;
891    const char *list = "PQRSwxymtuvlqrsPpn";	/* app-keypad except "Enter" */
892    int ch;
893    int result = -1;
894
895    if ((ch = keypad_final(string)) != '\0') {
896	test = strchr(list, ch);
897	if (test != 0)
898	    result = (test - list);
899    }
900    return result;
901}
902
903/*
904 * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
905 * is mapped inconsistently.
906 */
907static void
908check_keypad(TERMTYPE *tp)
909{
910    char show[80];
911
912    if (VALID_STRING(key_a1) &&
913	VALID_STRING(key_a3) &&
914	VALID_STRING(key_b2) &&
915	VALID_STRING(key_c1) &&
916	VALID_STRING(key_c3)) {
917	char final[6];
918	int list[5];
919	int increase = 0;
920	int j, k, kk;
921	int last;
922	int test;
923
924	final[0] = keypad_final(key_a1);
925	final[1] = keypad_final(key_a3);
926	final[2] = keypad_final(key_b2);
927	final[3] = keypad_final(key_c1);
928	final[4] = keypad_final(key_c3);
929	final[5] = '\0';
930
931	/* special case: legacy coding using 1,2,3,0,. on the bottom */
932	if (!strcmp(final, "qsrpn"))
933	    return;
934
935	list[0] = keypad_index(key_a1);
936	list[1] = keypad_index(key_a3);
937	list[2] = keypad_index(key_b2);
938	list[3] = keypad_index(key_c1);
939	list[4] = keypad_index(key_c3);
940
941	/* check that they're all vt100 keys */
942	for (j = 0; j < 5; ++j) {
943	    if (list[j] < 0) {
944		return;
945	    }
946	}
947
948	/* check if they're all in increasing order */
949	for (j = 1; j < 5; ++j) {
950	    if (list[j] > list[j - 1]) {
951		++increase;
952	    }
953	}
954	if (increase != 4) {
955	    show[0] = '\0';
956
957	    for (j = 0, last = -1; j < 5; ++j) {
958		for (k = 0, kk = -1, test = 100; k < 5; ++k) {
959		    if (list[k] > last &&
960			list[k] < test) {
961			test = list[k];
962			kk = k;
963		    }
964		}
965		last = test;
966		switch (kk) {
967		case 0:
968		    strcat(show, " ka1");
969		    break;
970		case 1:
971		    strcat(show, " ka3");
972		    break;
973		case 2:
974		    strcat(show, " kb2");
975		    break;
976		case 3:
977		    strcat(show, " kc1");
978		    break;
979		case 4:
980		    strcat(show, " kc3");
981		    break;
982		}
983	    }
984
985	    _nc_warning("vt100 keypad order inconsistent: %s", show);
986	}
987
988    } else if (VALID_STRING(key_a1) ||
989	       VALID_STRING(key_a3) ||
990	       VALID_STRING(key_b2) ||
991	       VALID_STRING(key_c1) ||
992	       VALID_STRING(key_c3)) {
993	show[0] = '\0';
994	if (keypad_index(key_a1) >= 0)
995	    strcat(show, " ka1");
996	if (keypad_index(key_a3) >= 0)
997	    strcat(show, " ka3");
998	if (keypad_index(key_b2) >= 0)
999	    strcat(show, " kb2");
1000	if (keypad_index(key_c1) >= 0)
1001	    strcat(show, " kc1");
1002	if (keypad_index(key_c3) >= 0)
1003	    strcat(show, " kc3");
1004	if (*show != '\0')
1005	    _nc_warning("vt100 keypad map incomplete:%s", show);
1006    }
1007}
1008
1009/*
1010 * Returns the expected number of parameters for the given capability.
1011 */
1012static int
1013expected_params(const char *name)
1014{
1015    /* *INDENT-OFF* */
1016    static const struct {
1017	const char *name;
1018	int count;
1019    } table[] = {
1020	{ "S0",			1 },	/* 'screen' extension */
1021	{ "birep",		2 },
1022	{ "chr",		1 },
1023	{ "colornm",		1 },
1024	{ "cpi",		1 },
1025	{ "csnm",		1 },
1026	{ "csr",		2 },
1027	{ "cub",		1 },
1028	{ "cud",		1 },
1029	{ "cuf",		1 },
1030	{ "cup",		2 },
1031	{ "cuu",		1 },
1032	{ "cvr",		1 },
1033	{ "cwin",		5 },
1034	{ "dch",		1 },
1035	{ "defc",		3 },
1036	{ "dial",		1 },
1037	{ "dispc",		1 },
1038	{ "dl",			1 },
1039	{ "ech",		1 },
1040	{ "getm",		1 },
1041	{ "hpa",		1 },
1042	{ "ich",		1 },
1043	{ "il",			1 },
1044	{ "indn",		1 },
1045	{ "initc",		4 },
1046	{ "initp",		7 },
1047	{ "lpi",		1 },
1048	{ "mc5p",		1 },
1049	{ "mrcup",		2 },
1050	{ "mvpa",		1 },
1051	{ "pfkey",		2 },
1052	{ "pfloc",		2 },
1053	{ "pfx",		2 },
1054	{ "pfxl",		3 },
1055	{ "pln",		2 },
1056	{ "qdial",		1 },
1057	{ "rcsd",		1 },
1058	{ "rep",		2 },
1059	{ "rin",		1 },
1060	{ "sclk",		3 },
1061	{ "scp",		1 },
1062	{ "scs",		1 },
1063	{ "scsd",		2 },
1064	{ "setab",		1 },
1065	{ "setaf",		1 },
1066	{ "setb",		1 },
1067	{ "setcolor",		1 },
1068	{ "setf",		1 },
1069	{ "sgr",		9 },
1070	{ "sgr1",		6 },
1071	{ "slength",		1 },
1072	{ "slines",		1 },
1073	{ "smgbp",		1 },	/* 2 if smgtp is not given */
1074	{ "smglp",		1 },
1075	{ "smglr",		2 },
1076	{ "smgrp",		1 },
1077	{ "smgtb",		2 },
1078	{ "smgtp",		1 },
1079	{ "tsl",		1 },
1080	{ "u6",			-1 },
1081	{ "vpa",		1 },
1082	{ "wind",		4 },
1083	{ "wingo",		1 },
1084    };
1085    /* *INDENT-ON* */
1086
1087    unsigned n;
1088    int result = 0;		/* function-keys, etc., use none */
1089
1090    for (n = 0; n < SIZEOF(table); n++) {
1091	if (!strcmp(name, table[n].name)) {
1092	    result = table[n].count;
1093	    break;
1094	}
1095    }
1096
1097    return result;
1098}
1099
1100/*
1101 * Make a quick sanity check for the parameters which are used in the given
1102 * strings.  If there are no "%p" tokens, then there should be no other "%"
1103 * markers.
1104 */
1105static void
1106check_params(TERMTYPE *tp, const char *name, char *value)
1107{
1108    int expected = expected_params(name);
1109    int actual = 0;
1110    int n;
1111    bool params[10];
1112    char *s = value;
1113
1114#ifdef set_top_margin_parm
1115    if (!strcmp(name, "smgbp")
1116	&& set_top_margin_parm == 0)
1117	expected = 2;
1118#endif
1119
1120    for (n = 0; n < 10; n++)
1121	params[n] = FALSE;
1122
1123    while (*s != 0) {
1124	if (*s == '%') {
1125	    if (*++s == '\0') {
1126		_nc_warning("expected character after %% in %s", name);
1127		break;
1128	    } else if (*s == 'p') {
1129		if (*++s == '\0' || !isdigit((int) *s)) {
1130		    _nc_warning("expected digit after %%p in %s", name);
1131		    return;
1132		} else {
1133		    n = (*s - '0');
1134		    if (n > actual)
1135			actual = n;
1136		    params[n] = TRUE;
1137		}
1138	    }
1139	}
1140	s++;
1141    }
1142
1143    if (params[0]) {
1144	_nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1145    }
1146    if (value == set_attributes || expected < 0) {
1147	;
1148    } else if (expected != actual) {
1149	_nc_warning("%s uses %d parameters, expected %d", name,
1150		    actual, expected);
1151	for (n = 1; n < actual; n++) {
1152	    if (!params[n])
1153		_nc_warning("%s omits parameter %d", name, n);
1154	}
1155    }
1156}
1157
1158static char *
1159skip_delay(char *s)
1160{
1161    while (*s == '/' || isdigit(UChar(*s)))
1162	++s;
1163    return s;
1164}
1165
1166/*
1167 * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1168 * the latter may have a worst-case delay on the end.
1169 */
1170static char *
1171ignore_delays(char *s)
1172{
1173    int delaying = 0;
1174
1175    do {
1176	switch (*s) {
1177	case '$':
1178	    if (delaying == 0)
1179		delaying = 1;
1180	    break;
1181	case '<':
1182	    if (delaying == 1)
1183		delaying = 2;
1184	    break;
1185	case '\0':
1186	    delaying = 0;
1187	    break;
1188	default:
1189	    if (delaying) {
1190		s = skip_delay(s);
1191		if (*s == '>')
1192		    ++s;
1193		delaying = 0;
1194	    }
1195	    break;
1196	}
1197	if (delaying)
1198	    ++s;
1199    } while (delaying);
1200    return s;
1201}
1202
1203/*
1204 * An sgr string may contain several settings other than the one we're
1205 * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1206 * "whatever" is contained in the sgr string, that is close enough for our
1207 * sanity check.
1208 */
1209static bool
1210similar_sgr(int num, char *a, char *b)
1211{
1212    static const char *names[] =
1213    {
1214	"none"
1215	,"standout"
1216	,"underline"
1217	,"reverse"
1218	,"blink"
1219	,"dim"
1220	,"bold"
1221	,"invis"
1222	,"protect"
1223	,"altcharset"
1224    };
1225    char *base_a = a;
1226    char *base_b = b;
1227    int delaying = 0;
1228
1229    while (*b != 0) {
1230	while (*a != *b) {
1231	    if (*a == 0) {
1232		if (b[0] == '$'
1233		    && b[1] == '<') {
1234		    _nc_warning("Did not find delay %s", _nc_visbuf(b));
1235		} else {
1236		    _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1237				names[num], _nc_visbuf2(1, base_a),
1238				_nc_visbuf2(2, base_b),
1239				_nc_visbuf2(3, b));
1240		}
1241		return FALSE;
1242	    } else if (delaying) {
1243		a = skip_delay(a);
1244		b = skip_delay(b);
1245	    } else {
1246		a++;
1247	    }
1248	}
1249	switch (*a) {
1250	case '$':
1251	    if (delaying == 0)
1252		delaying = 1;
1253	    break;
1254	case '<':
1255	    if (delaying == 1)
1256		delaying = 2;
1257	    break;
1258	default:
1259	    delaying = 0;
1260	    break;
1261	}
1262	a++;
1263	b++;
1264    }
1265    /* ignore delays on the end of the string */
1266    a = ignore_delays(a);
1267    return ((num != 0) || (*a == 0));
1268}
1269
1270static char *
1271check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1272{
1273    char *test;
1274
1275    _nc_tparm_err = 0;
1276    test = TPARM_9(set_attributes,
1277		   num == 1,
1278		   num == 2,
1279		   num == 3,
1280		   num == 4,
1281		   num == 5,
1282		   num == 6,
1283		   num == 7,
1284		   num == 8,
1285		   num == 9);
1286    if (test != 0) {
1287	if (PRESENT(cap)) {
1288	    if (!similar_sgr(num, test, cap)) {
1289		_nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1290			    name, num,
1291			    name, _nc_visbuf2(1, cap),
1292			    num, _nc_visbuf2(2, test));
1293	    }
1294	} else if (_nc_capcmp(test, zero)) {
1295	    _nc_warning("sgr(%d) present, but not %s", num, name);
1296	}
1297    } else if (PRESENT(cap)) {
1298	_nc_warning("sgr(%d) missing, but %s present", num, name);
1299    }
1300    if (_nc_tparm_err)
1301	_nc_warning("stack error in sgr(%d) string", num);
1302    return test;
1303}
1304
1305#define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1306
1307#ifdef TRACE
1308/*
1309 * If tic is compiled with TRACE, we'll be able to see the output from the
1310 * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1311 * the standard error.  Use this function to make it simpler to follow the
1312 * resulting debug traces.
1313 */
1314static void
1315show_where(unsigned level)
1316{
1317    if (_nc_tracing >= DEBUG_LEVEL(level)) {
1318	char my_name[256];
1319	_nc_get_type(my_name);
1320	fprintf(stderr, "\"%s\", line %d, '%s' ",
1321		_nc_get_source(),
1322		_nc_curr_line, my_name);
1323    }
1324}
1325
1326#else
1327#define show_where(level)	/* nothing */
1328#endif
1329
1330/* other sanity-checks (things that we don't want in the normal
1331 * logic that reads a terminfo entry)
1332 */
1333static void
1334check_termtype(TERMTYPE *tp, bool literal)
1335{
1336    bool conflict = FALSE;
1337    unsigned j, k;
1338    char fkeys[STRCOUNT];
1339
1340    /*
1341     * A terminal entry may contain more than one keycode assigned to
1342     * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1343     * return one (the last one assigned).
1344     */
1345    if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1346	memset(fkeys, 0, sizeof(fkeys));
1347	for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1348	    char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1349	    bool first = TRUE;
1350	    if (!VALID_STRING(a))
1351		continue;
1352	    for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1353		char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1354		if (!VALID_STRING(b)
1355		    || fkeys[k])
1356		    continue;
1357		if (!_nc_capcmp(a, b)) {
1358		    fkeys[j] = 1;
1359		    fkeys[k] = 1;
1360		    if (first) {
1361			if (!conflict) {
1362			    _nc_warning("Conflicting key definitions (using the last)");
1363			    conflict = TRUE;
1364			}
1365			fprintf(stderr, "... %s is the same as %s",
1366				keyname((int) _nc_tinfo_fkeys[j].code),
1367				keyname((int) _nc_tinfo_fkeys[k].code));
1368			first = FALSE;
1369		    } else {
1370			fprintf(stderr, ", %s",
1371				keyname((int) _nc_tinfo_fkeys[k].code));
1372		    }
1373		}
1374	    }
1375	    if (!first)
1376		fprintf(stderr, "\n");
1377	}
1378    }
1379
1380    for (j = 0; j < NUM_STRINGS(tp); j++) {
1381	char *a = tp->Strings[j];
1382	if (VALID_STRING(a))
1383	    check_params(tp, ExtStrname(tp, j, strnames), a);
1384    }
1385
1386    check_acs(tp);
1387    check_colors(tp);
1388    check_keypad(tp);
1389
1390    /*
1391     * These may be mismatched because the terminal description relies on
1392     * restoring the cursor visibility by resetting it.
1393     */
1394    ANDMISSING(cursor_invisible, cursor_normal);
1395    ANDMISSING(cursor_visible, cursor_normal);
1396
1397    if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1398	&& !_nc_capcmp(cursor_visible, cursor_normal))
1399	_nc_warning("cursor_visible is same as cursor_normal");
1400
1401    /*
1402     * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1403     * given, because the cursor position after the scrolling operation is
1404     * performed is undefined.
1405     */
1406    ANDMISSING(change_scroll_region, save_cursor);
1407    ANDMISSING(change_scroll_region, restore_cursor);
1408
1409    if (PRESENT(set_attributes)) {
1410	char *zero = 0;
1411
1412	_nc_tparm_err = 0;
1413	if (PRESENT(exit_attribute_mode)) {
1414	    zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1415	} else {
1416	    zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1417	}
1418	if (_nc_tparm_err)
1419	    _nc_warning("stack error in sgr(0) string");
1420
1421	if (zero != 0) {
1422	    CHECK_SGR(1, enter_standout_mode);
1423	    CHECK_SGR(2, enter_underline_mode);
1424	    CHECK_SGR(3, enter_reverse_mode);
1425	    CHECK_SGR(4, enter_blink_mode);
1426	    CHECK_SGR(5, enter_dim_mode);
1427	    CHECK_SGR(6, enter_bold_mode);
1428	    CHECK_SGR(7, enter_secure_mode);
1429	    CHECK_SGR(8, enter_protected_mode);
1430	    CHECK_SGR(9, enter_alt_charset_mode);
1431	    free(zero);
1432	} else {
1433	    _nc_warning("sgr(0) did not return a value");
1434	}
1435    } else if (PRESENT(exit_attribute_mode) &&
1436	       set_attributes != CANCELLED_STRING) {
1437	if (_nc_syntax == SYN_TERMINFO)
1438	    _nc_warning("missing sgr string");
1439    }
1440
1441    if (PRESENT(exit_attribute_mode)) {
1442	char *check_sgr0 = _nc_trim_sgr0(tp);
1443
1444	if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1445	    _nc_warning("trimmed sgr0 is empty");
1446	} else {
1447	    show_where(2);
1448	    if (check_sgr0 != exit_attribute_mode) {
1449		DEBUG(2,
1450		      ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1451		       _nc_visbuf2(1, exit_attribute_mode),
1452		       _nc_visbuf2(2, check_sgr0)));
1453		free(check_sgr0);
1454	    } else {
1455		DEBUG(2,
1456		      ("will not trim sgr0\n\toriginal sgr0=%s",
1457		       _nc_visbuf(exit_attribute_mode)));
1458	    }
1459	}
1460    }
1461#ifdef TRACE
1462    show_where(2);
1463    if (!auto_right_margin) {
1464	DEBUG(2,
1465	      ("can write to lower-right directly"));
1466    } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1467	DEBUG(2,
1468	      ("can write to lower-right by suppressing automargin"));
1469    } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1470	       || PRESENT(insert_character) || PRESENT(parm_ich)) {
1471	DEBUG(2,
1472	      ("can write to lower-right by using inserts"));
1473    } else {
1474	DEBUG(2,
1475	      ("cannot write to lower-right"));
1476    }
1477#endif
1478
1479    /*
1480     * Some standard applications (e.g., vi) and some non-curses
1481     * applications (e.g., jove) get confused if we have both ich1 and
1482     * smir/rmir.  Let's be nice and warn about that, too, even though
1483     * ncurses handles it.
1484     */
1485    if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1486	&& PRESENT(parm_ich)) {
1487	_nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1488    }
1489
1490    /*
1491     * Finally, do the non-verbose checks
1492     */
1493    if (save_check_termtype != 0)
1494	save_check_termtype(tp, literal);
1495}
1496