]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
28e48738b300163108736e228551fd433c73ea38
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2011,2012 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  *                      and Thomas E Dickey
39  *
40  */
41
42 #include <progs.priv.h>
43 #include <sys/stat.h>
44
45 #include <dump_entry.h>
46 #include <hashed_db.h>
47 #include <transform.h>
48
49 MODULE_ID("$Id: tic.c,v 1.170 2012/04/21 19:59:53 tom Exp $")
50
51 #define STDIN_NAME "<stdin>"
52
53 const char *_nc_progname = "tic";
54
55 static FILE *log_fp;
56 static FILE *tmp_fp;
57 static bool capdump = FALSE;    /* running as infotocap? */
58 static bool infodump = FALSE;   /* running as captoinfo? */
59 static bool showsummary = FALSE;
60 static char **namelst = 0;
61 static const char *to_remove;
62
63 static void (*save_check_termtype) (TERMTYPE *, bool);
64 static void check_termtype(TERMTYPE *tt, bool);
65
66 static const char usage_string[] = "\
67 [-e names] \
68 [-o dir] \
69 [-R name] \
70 [-v[n]] \
71 [-V] \
72 [-w[n]] \
73 [-\
74 1\
75 a\
76 C\
77 D\
78 c\
79 f\
80 G\
81 g\
82 I\
83 K\
84 L\
85 N\
86 r\
87 s\
88 T\
89 t\
90 U\
91 x\
92 ] \
93 source-file\n";
94
95 #if NO_LEAKS
96 static void
97 free_namelist(char **src)
98 {
99     if (src != 0) {
100         int n;
101         for (n = 0; src[n] != 0; ++n)
102             free(src[n]);
103         free(src);
104     }
105 }
106 #endif
107
108 static void
109 cleanup(void)
110 {
111 #if NO_LEAKS
112     free_namelist(namelst);
113 #endif
114     if (tmp_fp != 0)
115         fclose(tmp_fp);
116     if (to_remove != 0) {
117 #if HAVE_REMOVE
118         remove(to_remove);
119 #else
120         unlink(to_remove);
121 #endif
122     }
123 }
124
125 static void
126 failed(const char *msg)
127 {
128     perror(msg);
129     ExitProgram(EXIT_FAILURE);
130 }
131
132 static void
133 usage(void)
134 {
135     static const char *const tbl[] =
136     {
137         "Options:",
138         "  -1         format translation output one capability per line",
139 #if NCURSES_XNAMES
140         "  -a         retain commented-out capabilities (sets -x also)",
141 #endif
142         "  -K         translate entries to termcap source form with BSD syntax",
143         "  -C         translate entries to termcap source form",
144         "  -D         print list of tic's database locations (first must be writable)",
145         "  -c         check only, validate input without compiling or translating",
146         "  -e<names>  translate/compile only entries named by comma-separated list",
147         "  -f         format complex strings for readability",
148         "  -G         format %{number} to %'char'",
149         "  -g         format %'char' to %{number}",
150         "  -I         translate entries to terminfo source form",
151         "  -L         translate entries to full terminfo source form",
152         "  -N         disable smart defaults for source translation",
153         "  -o<dir>    set output directory for compiled entry writes",
154         "  -R<name>   restrict translation to given terminfo/termcap version",
155         "  -r         force resolution of all use entries in source translation",
156         "  -s         print summary statistics",
157         "  -T         remove size-restrictions on compiled description",
158 #if NCURSES_XNAMES
159         "  -t         suppress commented-out capabilities",
160 #endif
161         "  -U         suppress post-processing of entries",
162         "  -V         print version",
163         "  -v[n]      set verbosity level",
164         "  -w[n]      set format width for translation output",
165 #if NCURSES_XNAMES
166         "  -x         treat unknown capabilities as user-defined",
167 #endif
168         "",
169         "Parameters:",
170         "  <file>     file to translate or compile"
171     };
172     size_t j;
173
174     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
175     for (j = 0; j < SIZEOF(tbl); j++) {
176         fputs(tbl[j], stderr);
177         putc('\n', stderr);
178     }
179     ExitProgram(EXIT_FAILURE);
180 }
181
182 #define L_BRACE '{'
183 #define R_BRACE '}'
184 #define S_QUOTE '\''
185
186 static void
187 write_it(ENTRY * ep)
188 {
189     unsigned n;
190     int ch;
191     char *s, *d, *t;
192     char result[MAX_ENTRY_SIZE];
193
194     /*
195      * Look for strings that contain %{number}, convert them to %'char',
196      * which is shorter and runs a little faster.
197      */
198     for (n = 0; n < STRCOUNT; n++) {
199         s = ep->tterm.Strings[n];
200         if (VALID_STRING(s)
201             && strchr(s, L_BRACE) != 0) {
202             d = result;
203             t = s;
204             while ((ch = *t++) != 0) {
205                 *d++ = (char) ch;
206                 if (ch == '\\') {
207                     *d++ = *t++;
208                 } else if ((ch == '%')
209                            && (*t == L_BRACE)) {
210                     char *v = 0;
211                     long value = strtol(t + 1, &v, 0);
212                     if (v != 0
213                         && *v == R_BRACE
214                         && value > 0
215                         && value != '\\'        /* FIXME */
216                         && value < 127
217                         && isprint((int) value)) {
218                         *d++ = S_QUOTE;
219                         *d++ = (char) value;
220                         *d++ = S_QUOTE;
221                         t = (v + 1);
222                     }
223                 }
224             }
225             *d = 0;
226             if (strlen(result) < strlen(s))
227                 _nc_STRCPY(s, result, strlen(s) + 1);
228         }
229     }
230
231     _nc_set_type(_nc_first_name(ep->tterm.term_names));
232     _nc_curr_line = (int) ep->startline;
233     _nc_write_entry(&ep->tterm);
234 }
235
236 static bool
237 immedhook(ENTRY * ep GCC_UNUSED)
238 /* write out entries with no use capabilities immediately to save storage */
239 {
240 #if !HAVE_BIG_CORE
241     /*
242      * This is strictly a core-economy kluge.  The really clean way to handle
243      * compilation is to slurp the whole file into core and then do all the
244      * name-collision checks and entry writes in one swell foop.  But the
245      * terminfo master file is large enough that some core-poor systems swap
246      * like crazy when you compile it this way...there have been reports of
247      * this process taking *three hours*, rather than the twenty seconds or
248      * less typical on my development box.
249      *
250      * So.  This hook *immediately* writes out the referenced entry if it
251      * has no use capabilities.  The compiler main loop refrains from
252      * adding the entry to the in-core list when this hook fires.  If some
253      * other entry later needs to reference an entry that got written
254      * immediately, that's OK; the resolution code will fetch it off disk
255      * when it can't find it in core.
256      *
257      * Name collisions will still be detected, just not as cleanly.  The
258      * write_entry() code complains before overwriting an entry that
259      * postdates the time of tic's first call to write_entry().  Thus
260      * it will complain about overwriting entries newly made during the
261      * tic run, but not about overwriting ones that predate it.
262      *
263      * The reason this is a hook, and not in line with the rest of the
264      * compiler code, is that the support for termcap fallback cannot assume
265      * it has anywhere to spool out these entries!
266      *
267      * The _nc_set_type() call here requires a compensating one in
268      * _nc_parse_entry().
269      *
270      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
271      * make tic a bit faster (because the resolution code won't have to do
272      * disk I/O nearly as often).
273      */
274     if (ep->nuses == 0) {
275         int oldline = _nc_curr_line;
276
277         write_it(ep);
278         _nc_curr_line = oldline;
279         free(ep->tterm.str_table);
280         return (TRUE);
281     }
282 #endif /* HAVE_BIG_CORE */
283     return (FALSE);
284 }
285
286 static void
287 put_translate(int c)
288 /* emit a comment char, translating terminfo names to termcap names */
289 {
290     static bool in_name = FALSE;
291     static size_t have, used;
292     static char *namebuf, *suffix;
293
294     if (in_name) {
295         if (used + 1 >= have) {
296             have += 132;
297             namebuf = typeRealloc(char, have, namebuf);
298             suffix = typeRealloc(char, have, suffix);
299         }
300         if (c == '\n' || c == '@') {
301             namebuf[used++] = '\0';
302             (void) putchar('<');
303             (void) fputs(namebuf, stdout);
304             putchar(c);
305             in_name = FALSE;
306         } else if (c != '>') {
307             namebuf[used++] = (char) c;
308         } else {                /* ah! candidate name! */
309             char *up;
310             NCURSES_CONST char *tp;
311
312             namebuf[used++] = '\0';
313             in_name = FALSE;
314
315             suffix[0] = '\0';
316             if ((up = strchr(namebuf, '#')) != 0
317                 || (up = strchr(namebuf, '=')) != 0
318                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
319                 _nc_STRCPY(suffix, up, have);
320                 *up = '\0';
321             }
322
323             if ((tp = nametrans(namebuf)) != 0) {
324                 (void) putchar(':');
325                 (void) fputs(tp, stdout);
326                 (void) fputs(suffix, stdout);
327                 (void) putchar(':');
328             } else {
329                 /* couldn't find a translation, just dump the name */
330                 (void) putchar('<');
331                 (void) fputs(namebuf, stdout);
332                 (void) fputs(suffix, stdout);
333                 (void) putchar('>');
334             }
335         }
336     } else {
337         used = 0;
338         if (c == '<') {
339             in_name = TRUE;
340         } else {
341             putchar(c);
342         }
343     }
344 }
345
346 /* Returns a string, stripped of leading/trailing whitespace */
347 static char *
348 stripped(char *src)
349 {
350     char *dst = 0;
351
352     while (isspace(UChar(*src)))
353         src++;
354
355     if (*src != '\0') {
356         size_t len;
357
358         if ((dst = strdup(src)) == NULL) {
359             failed("strdup");
360         } else {
361             len = strlen(dst);
362             while (--len != 0 && isspace(UChar(dst[len])))
363                 dst[len] = '\0';
364         }
365     }
366     return dst;
367 }
368
369 static FILE *
370 open_tempfile(char *filename)
371 {
372     FILE *result = 0;
373
374     _nc_STRCPY(filename, "/tmp/XXXXXX", PATH_MAX);
375 #if HAVE_MKSTEMP
376     {
377         int fd = mkstemp(filename);
378         if (fd >= 0)
379             result = fdopen(fd, "w");
380     }
381 #else
382     if (tmpnam(filename) != 0)
383         result = fopen(filename, "w");
384 #endif
385     return result;
386 }
387
388 static FILE *
389 copy_input(FILE *source, const char *filename, char *alt_file)
390 {
391     FILE *result = 0;
392     FILE *target = open_tempfile(alt_file);
393     int ch;
394
395     if (source == 0) {
396         failed("copy_input (source)");
397     } else if (target == 0) {
398         failed("copy_input (target)");
399     } else {
400         clearerr(source);
401         for (;;) {
402             ch = fgetc(source);
403             if (feof(source)) {
404                 break;
405             } else if (ferror(source)) {
406                 failed(filename);
407             } else if (ch == 0) {
408                 /* don't loop in case someone wants to convert /dev/zero */
409                 fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename);
410                 ExitProgram(EXIT_FAILURE);
411             }
412             fputc(ch, target);
413         }
414         fclose(source);
415         /*
416          * rewind() does not force the target file's data to disk (not does
417          * fflush()...).  So open a second stream on the data and then close
418          * the one that we were writing on before starting to read from the
419          * second stream.
420          */
421         result = fopen(alt_file, "r+");
422         fclose(target);
423         to_remove = alt_file;
424     }
425     return result;
426 }
427
428 static FILE *
429 open_input(const char *filename, char *alt_file)
430 {
431     FILE *fp;
432     struct stat sb;
433     int mode;
434
435     if (!strcmp(filename, "-")) {
436         fp = copy_input(stdin, STDIN_NAME, alt_file);
437     } else if (stat(filename, &sb) < 0) {
438         fprintf(stderr, "%s: %s %s\n", _nc_progname, filename, strerror(errno));
439         ExitProgram(EXIT_FAILURE);
440     } else if ((mode = (sb.st_mode & S_IFMT)) == S_IFDIR
441                || (mode != S_IFREG && mode != S_IFCHR)) {
442         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
443         ExitProgram(EXIT_FAILURE);
444     } else {
445         fp = fopen(filename, "r");
446
447         if (fp == 0) {
448             fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
449             ExitProgram(EXIT_FAILURE);
450         }
451         if (mode != S_IFREG) {
452             if (alt_file != 0) {
453                 FILE *fp2 = copy_input(fp, filename, alt_file);
454                 fp = fp2;
455             } else {
456                 fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
457                 ExitProgram(EXIT_FAILURE);
458             }
459         }
460     }
461     return fp;
462 }
463
464 /* Parse the "-e" option-value into a list of names */
465 static char **
466 make_namelist(char *src)
467 {
468     char **dst = 0;
469
470     char *s, *base;
471     unsigned pass, n, nn;
472     char buffer[BUFSIZ];
473
474     if (src == 0) {
475         /* EMPTY */ ;
476     } else if (strchr(src, '/') != 0) {         /* a filename */
477         FILE *fp = open_input(src, (char *) 0);
478
479         for (pass = 1; pass <= 2; pass++) {
480             nn = 0;
481             while (fgets(buffer, sizeof(buffer), fp) != 0) {
482                 if ((s = stripped(buffer)) != 0) {
483                     if (dst != 0)
484                         dst[nn] = s;
485                     else
486                         free(s);
487                     nn++;
488                 }
489             }
490             if (pass == 1) {
491                 dst = typeCalloc(char *, nn + 1);
492                 rewind(fp);
493             }
494         }
495         fclose(fp);
496     } else {                    /* literal list of names */
497         for (pass = 1; pass <= 2; pass++) {
498             for (n = nn = 0, base = src;; n++) {
499                 int mark = src[n];
500                 if (mark == ',' || mark == '\0') {
501                     if (pass == 1) {
502                         nn++;
503                     } else {
504                         src[n] = '\0';
505                         if ((s = stripped(base)) != 0)
506                             dst[nn++] = s;
507                         base = &src[n + 1];
508                     }
509                 }
510                 if (mark == '\0')
511                     break;
512             }
513             if (pass == 1)
514                 dst = typeCalloc(char *, nn + 1);
515         }
516     }
517     if (showsummary && (dst != 0)) {
518         fprintf(log_fp, "Entries that will be compiled:\n");
519         for (n = 0; dst[n] != 0; n++)
520             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
521     }
522     return dst;
523 }
524
525 static bool
526 matches(char **needle, const char *haystack)
527 /* does entry in needle list match |-separated field in haystack? */
528 {
529     bool code = FALSE;
530     size_t n;
531
532     if (needle != 0) {
533         for (n = 0; needle[n] != 0; n++) {
534             if (_nc_name_match(haystack, needle[n], "|")) {
535                 code = TRUE;
536                 break;
537             }
538         }
539     } else
540         code = TRUE;
541     return (code);
542 }
543
544 static const char *
545 valid_db_path(const char *nominal)
546 {
547     struct stat sb;
548 #if USE_HASHED_DB
549     char suffix[] = DBM_SUFFIX;
550     size_t need = strlen(nominal) + sizeof(suffix);
551     char *result = malloc(need);
552
553     _nc_STRCPY(result, nominal, need);
554     if (strcmp(result + need - sizeof(suffix), suffix)) {
555         _nc_STRCAT(result, suffix, need);
556     }
557 #else
558     char *result = strdup(nominal);
559 #endif
560
561     DEBUG(1, ("** stat(%s)", result));
562     if (stat(result, &sb) >= 0) {
563 #if USE_HASHED_DB
564         if (!S_ISREG(sb.st_mode)
565             || access(result, R_OK | W_OK) != 0) {
566             DEBUG(1, ("...not a writable file"));
567             free(result);
568             result = 0;
569         }
570 #else
571         if (!S_ISDIR(sb.st_mode)
572             || access(result, R_OK | W_OK | X_OK) != 0) {
573             DEBUG(1, ("...not a writable directory"));
574             free(result);
575             result = 0;
576         }
577 #endif
578     } else {
579         /* check if parent is directory and is writable */
580         unsigned leaf = _nc_pathlast(result);
581
582         DEBUG(1, ("...not found"));
583         if (leaf) {
584             char save = result[leaf];
585             result[leaf] = 0;
586             if (stat(result, &sb) >= 0
587                 && S_ISDIR(sb.st_mode)
588                 && access(result, R_OK | W_OK | X_OK) == 0) {
589                 result[leaf] = save;
590             } else {
591                 DEBUG(1, ("...parent directory %s is not writable", result));
592                 free(result);
593                 result = 0;
594             }
595         } else {
596             DEBUG(1, ("... no parent directory"));
597             free(result);
598             result = 0;
599         }
600     }
601     return result;
602 }
603
604 /*
605  * Show the databases to which tic could write.  The location to which it
606  * writes is always the first one.  If none are writable, print an error
607  * message.
608  */
609 static void
610 show_databases(const char *outdir)
611 {
612     bool specific = (outdir != 0) || getenv("TERMINFO") != 0;
613     const char *result;
614     const char *tried = 0;
615
616     if (outdir == 0) {
617         outdir = _nc_tic_dir(0);
618     }
619     if ((result = valid_db_path(outdir)) != 0) {
620         printf("%s\n", result);
621     } else {
622         tried = outdir;
623     }
624
625     if ((outdir = _nc_home_terminfo())) {
626         if ((result = valid_db_path(outdir)) != 0) {
627             printf("%s\n", result);
628         } else if (!specific) {
629             tried = outdir;
630         }
631     }
632
633     /*
634      * If we can write in neither location, give an error message.
635      */
636     if (tried) {
637         fflush(stdout);
638         fprintf(stderr, "%s: %s (no permission)\n", _nc_progname, tried);
639         ExitProgram(EXIT_FAILURE);
640     }
641 }
642
643 #define VtoTrace(opt) (unsigned) ((opt > 0) ? opt : (opt == 0))
644
645 int
646 main(int argc, char *argv[])
647 {
648     char my_tmpname[PATH_MAX];
649     char my_altfile[PATH_MAX];
650     int v_opt = -1;
651     unsigned debug_level;
652     int smart_defaults = TRUE;
653     char *termcap;
654     ENTRY *qp;
655
656     int this_opt, last_opt = '?';
657
658     int outform = F_TERMINFO;   /* output format */
659     int sortmode = S_TERMINFO;  /* sort_mode */
660
661     int width = 60;
662     int height = 65535;
663     bool formatted = FALSE;     /* reformat complex strings? */
664     bool literal = FALSE;       /* suppress post-processing? */
665     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
666     bool forceresolve = FALSE;  /* force resolution */
667     bool limited = TRUE;
668     char *tversion = (char *) NULL;
669     const char *source_file = "terminfo";
670     char *outdir = (char *) NULL;
671     bool check_only = FALSE;
672     bool suppress_untranslatable = FALSE;
673
674     log_fp = stderr;
675
676     _nc_progname = _nc_rootname(argv[0]);
677     atexit(cleanup);
678
679     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
680         outform = F_TERMINFO;
681         sortmode = S_TERMINFO;
682     }
683     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
684         outform = F_TERMCAP;
685         sortmode = S_TERMCAP;
686     }
687 #if NCURSES_XNAMES
688     use_extended_names(FALSE);
689 #endif
690     _nc_strict_bsd = 0;
691
692     /*
693      * Processing arguments is a little complicated, since someone made a
694      * design decision to allow the numeric values for -w, -v options to
695      * be optional.
696      */
697     while ((this_opt = getopt(argc, argv,
698                               "0123456789CDIKLNR:TUVace:fGgo:rstvwx")) != -1) {
699         if (isdigit(this_opt)) {
700             switch (last_opt) {
701             case 'v':
702                 v_opt = (v_opt * 10) + (this_opt - '0');
703                 break;
704             case 'w':
705                 width = (width * 10) + (this_opt - '0');
706                 break;
707             default:
708                 switch (this_opt) {
709                 case '0':
710                     last_opt = this_opt;
711                     width = 65535;
712                     height = 1;
713                     break;
714                 case '1':
715                     last_opt = this_opt;
716                     width = 0;
717                     break;
718                 default:
719                     usage();
720                 }
721             }
722             continue;
723         }
724         switch (this_opt) {
725         case 'K':
726             _nc_strict_bsd = 1;
727             /* the initial version of -K in 20110730 fell-thru here, but the
728              * same flag is useful when reading sources -TD
729              */
730             break;
731         case 'C':
732             capdump = TRUE;
733             outform = F_TERMCAP;
734             sortmode = S_TERMCAP;
735             break;
736         case 'D':
737             debug_level = VtoTrace(v_opt);
738             set_trace_level(debug_level);
739             show_databases(outdir);
740             ExitProgram(EXIT_SUCCESS);
741             break;
742         case 'I':
743             infodump = TRUE;
744             outform = F_TERMINFO;
745             sortmode = S_TERMINFO;
746             break;
747         case 'L':
748             infodump = TRUE;
749             outform = F_VARIABLE;
750             sortmode = S_VARIABLE;
751             break;
752         case 'N':
753             smart_defaults = FALSE;
754             literal = TRUE;
755             break;
756         case 'R':
757             tversion = optarg;
758             break;
759         case 'T':
760             limited = FALSE;
761             break;
762         case 'U':
763             literal = TRUE;
764             break;
765         case 'V':
766             puts(curses_version());
767             ExitProgram(EXIT_SUCCESS);
768         case 'c':
769             check_only = TRUE;
770             break;
771         case 'e':
772             namelst = make_namelist(optarg);
773             break;
774         case 'f':
775             formatted = TRUE;
776             break;
777         case 'G':
778             numbers = 1;
779             break;
780         case 'g':
781             numbers = -1;
782             break;
783         case 'o':
784             outdir = optarg;
785             break;
786         case 'r':
787             forceresolve = TRUE;
788             break;
789         case 's':
790             showsummary = TRUE;
791             break;
792         case 'v':
793             v_opt = 0;
794             break;
795         case 'w':
796             width = 0;
797             break;
798 #if NCURSES_XNAMES
799         case 't':
800             _nc_disable_period = FALSE;
801             suppress_untranslatable = TRUE;
802             break;
803         case 'a':
804             _nc_disable_period = TRUE;
805             /* FALLTHRU */
806         case 'x':
807             use_extended_names(TRUE);
808             break;
809 #endif
810         default:
811             usage();
812         }
813         last_opt = this_opt;
814     }
815
816     debug_level = VtoTrace(v_opt);
817     set_trace_level(debug_level);
818
819     if (_nc_tracing) {
820         save_check_termtype = _nc_check_termtype2;
821         _nc_check_termtype2 = check_termtype;
822     }
823 #if !HAVE_BIG_CORE
824     /*
825      * Aaargh! immedhook seriously hoses us!
826      *
827      * One problem with immedhook is it means we can't do -e.  Problem
828      * is that we can't guarantee that for each terminal listed, all the
829      * terminals it depends on will have been kept in core for reference
830      * resolution -- in fact it's certain the primitive types at the end
831      * of reference chains *won't* be in core unless they were explicitly
832      * in the select list themselves.
833      */
834     if (namelst && (!infodump && !capdump)) {
835         (void) fprintf(stderr,
836                        "%s: Sorry, -e can't be used without -I or -C\n",
837                        _nc_progname);
838         ExitProgram(EXIT_FAILURE);
839     }
840 #endif /* HAVE_BIG_CORE */
841
842     if (optind < argc) {
843         source_file = argv[optind++];
844         if (optind < argc) {
845             fprintf(stderr,
846                     "%s: Too many file names.  Usage:\n\t%s %s",
847                     _nc_progname,
848                     _nc_progname,
849                     usage_string);
850             ExitProgram(EXIT_FAILURE);
851         }
852     } else {
853         if (infodump == TRUE) {
854             /* captoinfo's no-argument case */
855             source_file = "/etc/termcap";
856             if ((termcap = getenv("TERMCAP")) != 0
857                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
858                 if (access(termcap, F_OK) == 0) {
859                     /* file exists */
860                     source_file = termcap;
861                 } else {
862                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
863                         source_file = my_tmpname;
864                         fprintf(tmp_fp, "%s\n", termcap);
865                         fclose(tmp_fp);
866                         tmp_fp = open_input(source_file, (char *) 0);
867                         to_remove = source_file;
868                     } else {
869                         failed("tmpnam");
870                     }
871                 }
872             }
873         } else {
874             /* tic */
875             fprintf(stderr,
876                     "%s: File name needed.  Usage:\n\t%s %s",
877                     _nc_progname,
878                     _nc_progname,
879                     usage_string);
880             ExitProgram(EXIT_FAILURE);
881         }
882     }
883
884     if (tmp_fp == 0) {
885         tmp_fp = open_input(source_file, my_altfile);
886         if (!strcmp(source_file, "-")) {
887             source_file = STDIN_NAME;
888         }
889     }
890
891     if (infodump) {
892         dump_init(tversion,
893                   smart_defaults
894                   ? outform
895                   : F_LITERAL,
896                   sortmode, width, height, debug_level, formatted);
897     } else if (capdump) {
898         dump_init(tversion,
899                   outform,
900                   sortmode, width, height, debug_level, FALSE);
901     }
902
903     /* parse entries out of the source file */
904     _nc_set_source(source_file);
905 #if !HAVE_BIG_CORE
906     if (!(check_only || infodump || capdump))
907         _nc_set_writedir(outdir);
908 #endif /* HAVE_BIG_CORE */
909     _nc_read_entry_source(tmp_fp, (char *) NULL,
910                           !smart_defaults || literal, FALSE,
911                           ((check_only || infodump || capdump)
912                            ? NULLHOOK
913                            : immedhook));
914
915     /* do use resolution */
916     if (check_only || (!infodump && !capdump) || forceresolve) {
917         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
918             ExitProgram(EXIT_FAILURE);
919         }
920     }
921
922     /* length check */
923     if (check_only && (capdump || infodump)) {
924         for_entry_list(qp) {
925             if (matches(namelst, qp->tterm.term_names)) {
926                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
927
928                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
929                     (void) fprintf(stderr,
930                                    "warning: resolved %s entry is %d bytes long\n",
931                                    _nc_first_name(qp->tterm.term_names),
932                                    len);
933             }
934         }
935     }
936
937     /* write or dump all entries */
938     if (!check_only) {
939         if (!infodump && !capdump) {
940             _nc_set_writedir(outdir);
941             for_entry_list(qp) {
942                 if (matches(namelst, qp->tterm.term_names))
943                     write_it(qp);
944             }
945         } else {
946             /* this is in case infotocap() generates warnings */
947             _nc_curr_col = _nc_curr_line = -1;
948
949             for_entry_list(qp) {
950                 if (matches(namelst, qp->tterm.term_names)) {
951                     long j = qp->cend - qp->cstart;
952                     int len = 0;
953
954                     /* this is in case infotocap() generates warnings */
955                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
956
957                     (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
958                     while (j-- > 0) {
959                         if (infodump)
960                             (void) putchar(fgetc(tmp_fp));
961                         else
962                             put_translate(fgetc(tmp_fp));
963                     }
964
965                     repair_acsc(&qp->tterm);
966                     dump_entry(&qp->tterm, suppress_untranslatable,
967                                limited, numbers, NULL);
968                     for (j = 0; j < (long) qp->nuses; j++)
969                         dump_uses(qp->uses[j].name, !capdump);
970                     len = show_entry();
971                     if (debug_level != 0 && !limited)
972                         printf("# length=%d\n", len);
973                 }
974             }
975             if (!namelst && _nc_tail) {
976                 int c, oldc = '\0';
977                 bool in_comment = FALSE;
978                 bool trailing_comment = FALSE;
979
980                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
981                 while ((c = fgetc(tmp_fp)) != EOF) {
982                     if (oldc == '\n') {
983                         if (c == '#') {
984                             trailing_comment = TRUE;
985                             in_comment = TRUE;
986                         } else {
987                             in_comment = FALSE;
988                         }
989                     }
990                     if (trailing_comment
991                         && (in_comment || (oldc == '\n' && c == '\n')))
992                         putchar(c);
993                     oldc = c;
994                 }
995             }
996         }
997     }
998
999     /* Show the directory into which entries were written, and the total
1000      * number of entries
1001      */
1002     if (showsummary
1003         && (!(check_only || infodump || capdump))) {
1004         int total = _nc_tic_written();
1005         if (total != 0)
1006             fprintf(log_fp, "%d entries written to %s\n",
1007                     total,
1008                     _nc_tic_dir((char *) 0));
1009         else
1010             fprintf(log_fp, "No entries written\n");
1011     }
1012     ExitProgram(EXIT_SUCCESS);
1013 }
1014
1015 /*
1016  * This bit of legerdemain turns all the terminfo variable names into
1017  * references to locations in the arrays Booleans, Numbers, and Strings ---
1018  * precisely what's needed (see comp_parse.c).
1019  */
1020 #undef CUR
1021 #define CUR tp->
1022
1023 /*
1024  * Check if the alternate character-set capabilities are consistent.
1025  */
1026 static void
1027 check_acs(TERMTYPE *tp)
1028 {
1029     if (VALID_STRING(acs_chars)) {
1030         const char *boxes = "lmkjtuvwqxn";
1031         char mapped[256];
1032         char missing[256];
1033         const char *p;
1034         char *q;
1035
1036         memset(mapped, 0, sizeof(mapped));
1037         for (p = acs_chars; *p != '\0'; p += 2) {
1038             if (p[1] == '\0') {
1039                 _nc_warning("acsc has odd number of characters");
1040                 break;
1041             }
1042             mapped[UChar(p[0])] = p[1];
1043         }
1044
1045         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1046             _nc_warning("acsc refers to 'I', which is probably an error");
1047         }
1048
1049         for (p = boxes, q = missing; *p != '\0'; ++p) {
1050             if (!mapped[UChar(p[0])]) {
1051                 *q++ = p[0];
1052             }
1053         }
1054         *q = '\0';
1055
1056         assert(strlen(missing) <= strlen(boxes));
1057         if (*missing != '\0' && strcmp(missing, boxes)) {
1058             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1059         }
1060     }
1061 }
1062
1063 /*
1064  * Check if the color capabilities are consistent
1065  */
1066 static void
1067 check_colors(TERMTYPE *tp)
1068 {
1069     if ((max_colors > 0) != (max_pairs > 0)
1070         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1071         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1072                     max_colors, max_pairs);
1073
1074     PAIRED(set_foreground, set_background);
1075     PAIRED(set_a_foreground, set_a_background);
1076     PAIRED(set_color_pair, initialize_pair);
1077
1078     if (VALID_STRING(set_foreground)
1079         && VALID_STRING(set_a_foreground)
1080         && !_nc_capcmp(set_foreground, set_a_foreground))
1081         _nc_warning("expected setf/setaf to be different");
1082
1083     if (VALID_STRING(set_background)
1084         && VALID_STRING(set_a_background)
1085         && !_nc_capcmp(set_background, set_a_background))
1086         _nc_warning("expected setb/setab to be different");
1087
1088     /* see: has_colors() */
1089     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1090         && (((set_foreground != NULL)
1091              && (set_background != NULL))
1092             || ((set_a_foreground != NULL)
1093                 && (set_a_background != NULL))
1094             || set_color_pair)) {
1095         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1096             _nc_warning("expected either op/oc string for resetting colors");
1097     }
1098 }
1099
1100 static char
1101 keypad_final(const char *string)
1102 {
1103     char result = '\0';
1104
1105     if (VALID_STRING(string)
1106         && *string++ == '\033'
1107         && *string++ == 'O'
1108         && strlen(string) == 1) {
1109         result = *string;
1110     }
1111
1112     return result;
1113 }
1114
1115 static long
1116 keypad_index(const char *string)
1117 {
1118     char *test;
1119     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1120     int ch;
1121     long result = -1;
1122
1123     if ((ch = keypad_final(string)) != '\0') {
1124         test = strchr(list, ch);
1125         if (test != 0)
1126             result = (long) (test - list);
1127     }
1128     return result;
1129 }
1130
1131 /*
1132  * list[] is down, up, left, right
1133  * "left" may be ^H rather than \E[D
1134  * "down" may be ^J rather than \E[B
1135  * But up/right are generally consistently escape sequences for ANSI terminals.
1136  */
1137 static void
1138 check_ansi_cursor(char *list[4])
1139 {
1140     int j, k;
1141     int want;
1142     size_t prefix = 0;
1143     size_t suffix;
1144     bool skip[4];
1145     bool repeated = FALSE;
1146
1147     for (j = 0; j < 4; ++j) {
1148         skip[j] = FALSE;
1149         for (k = 0; k < j; ++k) {
1150             if (j != k
1151                 && !strcmp(list[j], list[k])) {
1152                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1153                 _nc_warning("repeated cursor control %s\n", value);
1154                 repeated = TRUE;
1155             }
1156         }
1157     }
1158     if (!repeated) {
1159         char *up = list[1];
1160
1161         if (UChar(up[0]) == '\033') {
1162             if (up[1] == '[') {
1163                 prefix = 2;
1164             } else {
1165                 prefix = 1;
1166             }
1167         } else if (UChar(up[0]) == UChar('\233')) {
1168             prefix = 1;
1169         }
1170         if (prefix) {
1171             suffix = prefix;
1172             while (up[suffix] && isdigit(UChar(up[suffix])))
1173                 ++suffix;
1174         }
1175         if (prefix && up[suffix] == 'A') {
1176             skip[1] = TRUE;
1177             if (!strcmp(list[0], "\n"))
1178                 skip[0] = TRUE;
1179             if (!strcmp(list[2], "\b"))
1180                 skip[2] = TRUE;
1181
1182             for (j = 0; j < 4; ++j) {
1183                 if (skip[j] || strlen(list[j]) == 1)
1184                     continue;
1185                 if (memcmp(list[j], up, prefix)) {
1186                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1187                     _nc_warning("inconsistent prefix for %s\n", value);
1188                     continue;
1189                 }
1190                 if (strlen(list[j]) < suffix) {
1191                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1192                     _nc_warning("inconsistent length for %s, expected %d\n",
1193                                 value, (int) suffix + 1);
1194                     continue;
1195                 }
1196                 want = "BADC"[j];
1197                 if (list[j][suffix] != want) {
1198                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1199                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1200                                 value, want, list[j][suffix]);
1201                 }
1202             }
1203         }
1204     }
1205 }
1206
1207 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1208
1209 static void
1210 check_cursor(TERMTYPE *tp)
1211 {
1212     int count;
1213     char *list[4];
1214
1215     /* if we have a parameterized form, then the non-parameterized is easy */
1216     ANDMISSING(parm_down_cursor, cursor_down);
1217     ANDMISSING(parm_up_cursor, cursor_up);
1218     ANDMISSING(parm_left_cursor, cursor_left);
1219     ANDMISSING(parm_right_cursor, cursor_right);
1220
1221     /* Given any of a set of cursor movement, the whole set should be present.
1222      * Technically this is not true (we could use cursor_address to fill in
1223      * unsupported controls), but it is likely.
1224      */
1225     count = 0;
1226     if (PRESENT(parm_down_cursor)) {
1227         list[count++] = parm_down_cursor;
1228     }
1229     if (PRESENT(parm_up_cursor)) {
1230         list[count++] = parm_up_cursor;
1231     }
1232     if (PRESENT(parm_left_cursor)) {
1233         list[count++] = parm_left_cursor;
1234     }
1235     if (PRESENT(parm_right_cursor)) {
1236         list[count++] = parm_right_cursor;
1237     }
1238     if (count == 4) {
1239         check_ansi_cursor(list);
1240     } else if (count != 0) {
1241         EXPECTED(parm_down_cursor);
1242         EXPECTED(parm_up_cursor);
1243         EXPECTED(parm_left_cursor);
1244         EXPECTED(parm_right_cursor);
1245     }
1246
1247     count = 0;
1248     if (PRESENT(cursor_down)) {
1249         list[count++] = cursor_down;
1250     }
1251     if (PRESENT(cursor_up)) {
1252         list[count++] = cursor_up;
1253     }
1254     if (PRESENT(cursor_left)) {
1255         list[count++] = cursor_left;
1256     }
1257     if (PRESENT(cursor_right)) {
1258         list[count++] = cursor_right;
1259     }
1260     if (count == 4) {
1261         check_ansi_cursor(list);
1262     } else if (count != 0) {
1263         count = 0;
1264         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1265             ++count;
1266         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1267             ++count;
1268         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1269             ++count;
1270         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1271             ++count;
1272         if (count) {
1273             EXPECTED(cursor_down);
1274             EXPECTED(cursor_up);
1275             EXPECTED(cursor_left);
1276             EXPECTED(cursor_right);
1277         }
1278     }
1279 }
1280
1281 #define MAX_KP 5
1282 /*
1283  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1284  * is mapped inconsistently.
1285  */
1286 static void
1287 check_keypad(TERMTYPE *tp)
1288 {
1289     char show[80];
1290
1291     if (VALID_STRING(key_a1) &&
1292         VALID_STRING(key_a3) &&
1293         VALID_STRING(key_b2) &&
1294         VALID_STRING(key_c1) &&
1295         VALID_STRING(key_c3)) {
1296         char final[MAX_KP + 1];
1297         long list[MAX_KP];
1298         int increase = 0;
1299         int j, k, kk;
1300         long last;
1301         long test;
1302
1303         final[0] = keypad_final(key_a1);
1304         final[1] = keypad_final(key_a3);
1305         final[2] = keypad_final(key_b2);
1306         final[3] = keypad_final(key_c1);
1307         final[4] = keypad_final(key_c3);
1308         final[5] = '\0';
1309
1310         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1311         assert(strlen(final) <= MAX_KP);
1312         if (!strcmp(final, "qsrpn"))
1313             return;
1314
1315         list[0] = keypad_index(key_a1);
1316         list[1] = keypad_index(key_a3);
1317         list[2] = keypad_index(key_b2);
1318         list[3] = keypad_index(key_c1);
1319         list[4] = keypad_index(key_c3);
1320
1321         /* check that they're all vt100 keys */
1322         for (j = 0; j < MAX_KP; ++j) {
1323             if (list[j] < 0) {
1324                 return;
1325             }
1326         }
1327
1328         /* check if they're all in increasing order */
1329         for (j = 1; j < MAX_KP; ++j) {
1330             if (list[j] > list[j - 1]) {
1331                 ++increase;
1332             }
1333         }
1334         if (increase != (MAX_KP - 1)) {
1335             show[0] = '\0';
1336
1337             for (j = 0, last = -1; j < MAX_KP; ++j) {
1338                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1339                     if (list[k] > last &&
1340                         list[k] < test) {
1341                         test = list[k];
1342                         kk = k;
1343                     }
1344                 }
1345                 last = test;
1346                 assert(strlen(show) < (MAX_KP * 4));
1347                 switch (kk) {
1348                 case 0:
1349                     _nc_STRCAT(show, " ka1", sizeof(show));
1350                     break;
1351                 case 1:
1352                     _nc_STRCAT(show, " ka3", sizeof(show));
1353                     break;
1354                 case 2:
1355                     _nc_STRCAT(show, " kb2", sizeof(show));
1356                     break;
1357                 case 3:
1358                     _nc_STRCAT(show, " kc1", sizeof(show));
1359                     break;
1360                 case 4:
1361                     _nc_STRCAT(show, " kc3", sizeof(show));
1362                     break;
1363                 }
1364             }
1365
1366             _nc_warning("vt100 keypad order inconsistent: %s", show);
1367         }
1368
1369     } else if (VALID_STRING(key_a1) ||
1370                VALID_STRING(key_a3) ||
1371                VALID_STRING(key_b2) ||
1372                VALID_STRING(key_c1) ||
1373                VALID_STRING(key_c3)) {
1374         show[0] = '\0';
1375         if (keypad_index(key_a1) >= 0)
1376             _nc_STRCAT(show, " ka1", sizeof(show));
1377         if (keypad_index(key_a3) >= 0)
1378             _nc_STRCAT(show, " ka3", sizeof(show));
1379         if (keypad_index(key_b2) >= 0)
1380             _nc_STRCAT(show, " kb2", sizeof(show));
1381         if (keypad_index(key_c1) >= 0)
1382             _nc_STRCAT(show, " kc1", sizeof(show));
1383         if (keypad_index(key_c3) >= 0)
1384             _nc_STRCAT(show, " kc3", sizeof(show));
1385         if (*show != '\0')
1386             _nc_warning("vt100 keypad map incomplete:%s", show);
1387     }
1388 }
1389
1390 static void
1391 check_printer(TERMTYPE *tp)
1392 {
1393     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1394     PAIRED(enter_italics_mode, exit_italics_mode);
1395     PAIRED(enter_leftward_mode, exit_leftward_mode);
1396     PAIRED(enter_micro_mode, exit_micro_mode);
1397     PAIRED(enter_shadow_mode, exit_shadow_mode);
1398     PAIRED(enter_subscript_mode, exit_subscript_mode);
1399     PAIRED(enter_superscript_mode, exit_superscript_mode);
1400     PAIRED(enter_upward_mode, exit_upward_mode);
1401
1402     ANDMISSING(start_char_set_def, stop_char_set_def);
1403
1404     /* if we have a parameterized form, then the non-parameterized is easy */
1405     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1406     ANDMISSING(set_left_margin_parm, set_left_margin);
1407     ANDMISSING(set_right_margin_parm, set_right_margin);
1408     ANDMISSING(set_top_margin_parm, set_top_margin);
1409
1410     ANDMISSING(parm_down_micro, micro_down);
1411     ANDMISSING(parm_left_micro, micro_left);
1412     ANDMISSING(parm_right_micro, micro_right);
1413     ANDMISSING(parm_up_micro, micro_up);
1414 }
1415
1416 static bool
1417 uses_SGR_39_49(const char *value)
1418 {
1419     return (strstr(value, "39;49") != 0
1420             || strstr(value, "49;39") != 0);
1421 }
1422
1423 /*
1424  * Check consistency of termcap extensions related to "screen".
1425  */
1426 static void
1427 check_screen(TERMTYPE *tp)
1428 {
1429     if (_nc_user_definable) {
1430         int have_XT = tigetflag("XT");
1431         int have_XM = tigetflag("XM");
1432         int have_bce = back_color_erase;
1433         bool have_kmouse = FALSE;
1434         bool use_sgr_39_49 = FALSE;
1435         char *name = _nc_first_name(tp->term_names);
1436
1437         if (!VALID_BOOLEAN(have_bce)) {
1438             have_bce = FALSE;
1439         }
1440         if (!VALID_BOOLEAN(have_XM)) {
1441             have_XM = FALSE;
1442         }
1443         if (!VALID_BOOLEAN(have_XT)) {
1444             have_XT = FALSE;
1445         }
1446         if (VALID_STRING(key_mouse)) {
1447             have_kmouse = !strcmp("\033[M", key_mouse);
1448         }
1449         if (VALID_STRING(orig_colors)) {
1450             use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1451         } else if (VALID_STRING(orig_pair)) {
1452             use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1453         }
1454
1455         if (have_XM && have_XT) {
1456             _nc_warning("Screen's XT capability conflicts with XM");
1457         } else if (have_XT
1458                    && strstr(name, "screen") != 0
1459                    && strchr(name, '.') != 0) {
1460             _nc_warning("Screen's \"screen\" entries should not have XT set");
1461         } else if (have_XT) {
1462             if (!have_kmouse && have_bce) {
1463                 if (VALID_STRING(key_mouse)) {
1464                     _nc_warning("Value of kmous inconsistent with screen's usage");
1465                 } else {
1466                     _nc_warning("Expected kmous capability with XT");
1467                 }
1468             }
1469             if (!have_bce && max_colors > 0)
1470                 _nc_warning("Expected bce capability with XT");
1471             if (!use_sgr_39_49 && have_bce && max_colors > 0)
1472                 _nc_warning("Expected orig_colors capability with XT to have 39/49 parameters");
1473             if (VALID_STRING(to_status_line))
1474                 _nc_warning("\"tsl\" capability is redundant, given XT");
1475         } else {
1476             if (have_kmouse && !have_XM)
1477                 _nc_warning("Expected XT to be set, given kmous");
1478         }
1479     }
1480 }
1481
1482 /*
1483  * Returns the expected number of parameters for the given capability.
1484  */
1485 static int
1486 expected_params(const char *name)
1487 {
1488     /* *INDENT-OFF* */
1489     static const struct {
1490         const char *name;
1491         int count;
1492     } table[] = {
1493         { "S0",                 1 },    /* 'screen' extension */
1494         { "birep",              2 },
1495         { "chr",                1 },
1496         { "colornm",            1 },
1497         { "cpi",                1 },
1498         { "csnm",               1 },
1499         { "csr",                2 },
1500         { "cub",                1 },
1501         { "cud",                1 },
1502         { "cuf",                1 },
1503         { "cup",                2 },
1504         { "cuu",                1 },
1505         { "cvr",                1 },
1506         { "cwin",               5 },
1507         { "dch",                1 },
1508         { "defc",               3 },
1509         { "dial",               1 },
1510         { "dispc",              1 },
1511         { "dl",                 1 },
1512         { "ech",                1 },
1513         { "getm",               1 },
1514         { "hpa",                1 },
1515         { "ich",                1 },
1516         { "il",                 1 },
1517         { "indn",               1 },
1518         { "initc",              4 },
1519         { "initp",              7 },
1520         { "lpi",                1 },
1521         { "mc5p",               1 },
1522         { "mrcup",              2 },
1523         { "mvpa",               1 },
1524         { "pfkey",              2 },
1525         { "pfloc",              2 },
1526         { "pfx",                2 },
1527         { "pfxl",               3 },
1528         { "pln",                2 },
1529         { "qdial",              1 },
1530         { "rcsd",               1 },
1531         { "rep",                2 },
1532         { "rin",                1 },
1533         { "sclk",               3 },
1534         { "scp",                1 },
1535         { "scs",                1 },
1536         { "scsd",               2 },
1537         { "setab",              1 },
1538         { "setaf",              1 },
1539         { "setb",               1 },
1540         { "setcolor",           1 },
1541         { "setf",               1 },
1542         { "sgr",                9 },
1543         { "sgr1",               6 },
1544         { "slength",            1 },
1545         { "slines",             1 },
1546         { "smgbp",              1 },    /* 2 if smgtp is not given */
1547         { "smglp",              1 },
1548         { "smglr",              2 },
1549         { "smgrp",              1 },
1550         { "smgtb",              2 },
1551         { "smgtp",              1 },
1552         { "tsl",                1 },
1553         { "u6",                 -1 },
1554         { "vpa",                1 },
1555         { "wind",               4 },
1556         { "wingo",              1 },
1557     };
1558     /* *INDENT-ON* */
1559
1560     unsigned n;
1561     int result = 0;             /* function-keys, etc., use none */
1562
1563     for (n = 0; n < SIZEOF(table); n++) {
1564         if (!strcmp(name, table[n].name)) {
1565             result = table[n].count;
1566             break;
1567         }
1568     }
1569
1570     return result;
1571 }
1572
1573 /*
1574  * Make a quick sanity check for the parameters which are used in the given
1575  * strings.  If there are no "%p" tokens, then there should be no other "%"
1576  * markers.
1577  */
1578 static void
1579 check_params(TERMTYPE *tp, const char *name, char *value)
1580 {
1581     int expected = expected_params(name);
1582     int actual = 0;
1583     int n;
1584     bool params[10];
1585     char *s = value;
1586
1587 #ifdef set_top_margin_parm
1588     if (!strcmp(name, "smgbp")
1589         && set_top_margin_parm == 0)
1590         expected = 2;
1591 #endif
1592
1593     for (n = 0; n < 10; n++)
1594         params[n] = FALSE;
1595
1596     while (*s != 0) {
1597         if (*s == '%') {
1598             if (*++s == '\0') {
1599                 _nc_warning("expected character after %% in %s", name);
1600                 break;
1601             } else if (*s == 'p') {
1602                 if (*++s == '\0' || !isdigit((int) *s)) {
1603                     _nc_warning("expected digit after %%p in %s", name);
1604                     return;
1605                 } else {
1606                     n = (*s - '0');
1607                     if (n > actual)
1608                         actual = n;
1609                     params[n] = TRUE;
1610                 }
1611             }
1612         }
1613         s++;
1614     }
1615
1616     if (params[0]) {
1617         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1618     }
1619     if (value == set_attributes || expected < 0) {
1620         ;
1621     } else if (expected != actual) {
1622         _nc_warning("%s uses %d parameters, expected %d", name,
1623                     actual, expected);
1624         for (n = 1; n < actual; n++) {
1625             if (!params[n])
1626                 _nc_warning("%s omits parameter %d", name, n);
1627         }
1628     }
1629 }
1630
1631 static char *
1632 skip_delay(char *s)
1633 {
1634     while (*s == '/' || isdigit(UChar(*s)))
1635         ++s;
1636     return s;
1637 }
1638
1639 /*
1640  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
1641  * the latter may have a worst-case delay on the end.
1642  */
1643 static char *
1644 ignore_delays(char *s)
1645 {
1646     int delaying = 0;
1647
1648     do {
1649         switch (*s) {
1650         case '$':
1651             if (delaying == 0)
1652                 delaying = 1;
1653             break;
1654         case '<':
1655             if (delaying == 1)
1656                 delaying = 2;
1657             break;
1658         case '\0':
1659             delaying = 0;
1660             break;
1661         default:
1662             if (delaying) {
1663                 s = skip_delay(s);
1664                 if (*s == '>')
1665                     ++s;
1666                 delaying = 0;
1667             }
1668             break;
1669         }
1670         if (delaying)
1671             ++s;
1672     } while (delaying);
1673     return s;
1674 }
1675
1676 /*
1677  * An sgr string may contain several settings other than the one we're
1678  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
1679  * "whatever" is contained in the sgr string, that is close enough for our
1680  * sanity check.
1681  */
1682 static bool
1683 similar_sgr(int num, char *a, char *b)
1684 {
1685     static const char *names[] =
1686     {
1687         "none"
1688         ,"standout"
1689         ,"underline"
1690         ,"reverse"
1691         ,"blink"
1692         ,"dim"
1693         ,"bold"
1694         ,"invis"
1695         ,"protect"
1696         ,"altcharset"
1697     };
1698     char *base_a = a;
1699     char *base_b = b;
1700     int delaying = 0;
1701
1702     while (*b != 0) {
1703         while (*a != *b) {
1704             if (*a == 0) {
1705                 if (b[0] == '$'
1706                     && b[1] == '<') {
1707                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
1708                 } else {
1709                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
1710                                 names[num], _nc_visbuf2(1, base_a),
1711                                 _nc_visbuf2(2, base_b),
1712                                 _nc_visbuf2(3, b));
1713                 }
1714                 return FALSE;
1715             } else if (delaying) {
1716                 a = skip_delay(a);
1717                 b = skip_delay(b);
1718             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
1719                 b++;
1720             } else {
1721                 a++;
1722             }
1723         }
1724         switch (*a) {
1725         case '$':
1726             if (delaying == 0)
1727                 delaying = 1;
1728             break;
1729         case '<':
1730             if (delaying == 1)
1731                 delaying = 2;
1732             break;
1733         default:
1734             delaying = 0;
1735             break;
1736         }
1737         a++;
1738         b++;
1739     }
1740     /* ignore delays on the end of the string */
1741     a = ignore_delays(a);
1742     return ((num != 0) || (*a == 0));
1743 }
1744
1745 static char *
1746 check_sgr(TERMTYPE *tp, char *zero, int num, char *cap, const char *name)
1747 {
1748     char *test;
1749
1750     _nc_tparm_err = 0;
1751     test = TPARM_9(set_attributes,
1752                    num == 1,
1753                    num == 2,
1754                    num == 3,
1755                    num == 4,
1756                    num == 5,
1757                    num == 6,
1758                    num == 7,
1759                    num == 8,
1760                    num == 9);
1761     if (test != 0) {
1762         if (PRESENT(cap)) {
1763             if (!similar_sgr(num, test, cap)) {
1764                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
1765                             name, num,
1766                             name, _nc_visbuf2(1, cap),
1767                             num, _nc_visbuf2(2, test));
1768             }
1769         } else if (_nc_capcmp(test, zero)) {
1770             _nc_warning("sgr(%d) present, but not %s", num, name);
1771         }
1772     } else if (PRESENT(cap)) {
1773         _nc_warning("sgr(%d) missing, but %s present", num, name);
1774     }
1775     if (_nc_tparm_err)
1776         _nc_warning("stack error in sgr(%d) string", num);
1777     return test;
1778 }
1779
1780 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
1781
1782 #ifdef TRACE
1783 /*
1784  * If tic is compiled with TRACE, we'll be able to see the output from the
1785  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
1786  * the standard error.  Use this function to make it simpler to follow the
1787  * resulting debug traces.
1788  */
1789 static void
1790 show_where(unsigned level)
1791 {
1792     if (_nc_tracing >= DEBUG_LEVEL(level)) {
1793         char my_name[256];
1794         _nc_get_type(my_name);
1795         _tracef("\"%s\", line %d, '%s'",
1796                 _nc_get_source(),
1797                 _nc_curr_line, my_name);
1798     }
1799 }
1800
1801 #else
1802 #define show_where(level)       /* nothing */
1803 #endif
1804
1805 /* other sanity-checks (things that we don't want in the normal
1806  * logic that reads a terminfo entry)
1807  */
1808 static void
1809 check_termtype(TERMTYPE *tp, bool literal)
1810 {
1811     bool conflict = FALSE;
1812     unsigned j, k;
1813     char fkeys[STRCOUNT];
1814
1815     /*
1816      * A terminal entry may contain more than one keycode assigned to
1817      * a given string (e.g., KEY_END and KEY_LL).  But curses will only
1818      * return one (the last one assigned).
1819      */
1820     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
1821         memset(fkeys, 0, sizeof(fkeys));
1822         for (j = 0; _nc_tinfo_fkeys[j].code; j++) {
1823             char *a = tp->Strings[_nc_tinfo_fkeys[j].offset];
1824             bool first = TRUE;
1825             if (!VALID_STRING(a))
1826                 continue;
1827             for (k = j + 1; _nc_tinfo_fkeys[k].code; k++) {
1828                 char *b = tp->Strings[_nc_tinfo_fkeys[k].offset];
1829                 if (!VALID_STRING(b)
1830                     || fkeys[k])
1831                     continue;
1832                 if (!_nc_capcmp(a, b)) {
1833                     fkeys[j] = 1;
1834                     fkeys[k] = 1;
1835                     if (first) {
1836                         if (!conflict) {
1837                             _nc_warning("Conflicting key definitions (using the last)");
1838                             conflict = TRUE;
1839                         }
1840                         fprintf(stderr, "... %s is the same as %s",
1841                                 keyname((int) _nc_tinfo_fkeys[j].code),
1842                                 keyname((int) _nc_tinfo_fkeys[k].code));
1843                         first = FALSE;
1844                     } else {
1845                         fprintf(stderr, ", %s",
1846                                 keyname((int) _nc_tinfo_fkeys[k].code));
1847                     }
1848                 }
1849             }
1850             if (!first)
1851                 fprintf(stderr, "\n");
1852         }
1853     }
1854
1855     for (j = 0; j < NUM_STRINGS(tp); j++) {
1856         char *a = tp->Strings[j];
1857         if (VALID_STRING(a))
1858             check_params(tp, ExtStrname(tp, (int) j, strnames), a);
1859     }
1860
1861     check_acs(tp);
1862     check_colors(tp);
1863     check_cursor(tp);
1864     check_keypad(tp);
1865     check_printer(tp);
1866     check_screen(tp);
1867
1868     /*
1869      * These may be mismatched because the terminal description relies on
1870      * restoring the cursor visibility by resetting it.
1871      */
1872     ANDMISSING(cursor_invisible, cursor_normal);
1873     ANDMISSING(cursor_visible, cursor_normal);
1874
1875     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
1876         && !_nc_capcmp(cursor_visible, cursor_normal))
1877         _nc_warning("cursor_visible is same as cursor_normal");
1878
1879     /*
1880      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
1881      * given, because the cursor position after the scrolling operation is
1882      * performed is undefined.
1883      */
1884     ANDMISSING(change_scroll_region, save_cursor);
1885     ANDMISSING(change_scroll_region, restore_cursor);
1886
1887     /*
1888      * If we can clear tabs, we should be able to initialize them.
1889      */
1890     ANDMISSING(clear_all_tabs, set_tab);
1891
1892     if (PRESENT(set_attributes)) {
1893         char *zero = 0;
1894
1895         _nc_tparm_err = 0;
1896         if (PRESENT(exit_attribute_mode)) {
1897             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
1898         } else {
1899             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1900         }
1901         if (_nc_tparm_err)
1902             _nc_warning("stack error in sgr(0) string");
1903
1904         if (zero != 0) {
1905             CHECK_SGR(1, enter_standout_mode);
1906             CHECK_SGR(2, enter_underline_mode);
1907             CHECK_SGR(3, enter_reverse_mode);
1908             CHECK_SGR(4, enter_blink_mode);
1909             CHECK_SGR(5, enter_dim_mode);
1910             CHECK_SGR(6, enter_bold_mode);
1911             CHECK_SGR(7, enter_secure_mode);
1912             CHECK_SGR(8, enter_protected_mode);
1913             CHECK_SGR(9, enter_alt_charset_mode);
1914             free(zero);
1915         } else {
1916             _nc_warning("sgr(0) did not return a value");
1917         }
1918     } else if (PRESENT(exit_attribute_mode) &&
1919                set_attributes != CANCELLED_STRING) {
1920         if (_nc_syntax == SYN_TERMINFO)
1921             _nc_warning("missing sgr string");
1922     }
1923
1924     if (PRESENT(exit_attribute_mode)) {
1925         char *check_sgr0 = _nc_trim_sgr0(tp);
1926
1927         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
1928             _nc_warning("trimmed sgr0 is empty");
1929         } else {
1930             show_where(2);
1931             if (check_sgr0 != exit_attribute_mode) {
1932                 DEBUG(2,
1933                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
1934                        _nc_visbuf2(1, exit_attribute_mode),
1935                        _nc_visbuf2(2, check_sgr0)));
1936                 free(check_sgr0);
1937             } else {
1938                 DEBUG(2,
1939                       ("will not trim sgr0\n\toriginal sgr0=%s",
1940                        _nc_visbuf(exit_attribute_mode)));
1941             }
1942         }
1943     }
1944 #ifdef TRACE
1945     show_where(2);
1946     if (!auto_right_margin) {
1947         DEBUG(2,
1948               ("can write to lower-right directly"));
1949     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
1950         DEBUG(2,
1951               ("can write to lower-right by suppressing automargin"));
1952     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
1953                || PRESENT(insert_character) || PRESENT(parm_ich)) {
1954         DEBUG(2,
1955               ("can write to lower-right by using inserts"));
1956     } else {
1957         DEBUG(2,
1958               ("cannot write to lower-right"));
1959     }
1960 #endif
1961
1962     /*
1963      * Some standard applications (e.g., vi) and some non-curses
1964      * applications (e.g., jove) get confused if we have both ich1 and
1965      * smir/rmir.  Let's be nice and warn about that, too, even though
1966      * ncurses handles it.
1967      */
1968     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
1969         && PRESENT(parm_ich)) {
1970         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
1971     }
1972
1973     /*
1974      * Finally, do the non-verbose checks
1975      */
1976     if (save_check_termtype != 0)
1977         save_check_termtype(tp, literal);
1978 }