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