]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
3545c3c92a9b401db68eceddf5f99477e3f6d8d4
[ncurses.git] / progs / tic.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 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 <tparm_type.h>
47 #include <hashed_db.h>
48 #include <parametrized.h>
49 #include <transform.h>
50
51 MODULE_ID("$Id: tic.c,v 1.244 2017/09/20 00:39:37 tom Exp $")
52
53 #define STDIN_NAME "<stdin>"
54
55 const char *_nc_progname = "tic";
56
57 static FILE *log_fp;
58 static FILE *tmp_fp;
59 static bool capdump = FALSE;    /* running as infotocap? */
60 static bool infodump = FALSE;   /* running as captoinfo? */
61 static bool showsummary = FALSE;
62 static char **namelst = 0;
63 static const char *to_remove;
64
65 #if NCURSES_XNAMES
66 static bool using_extensions = FALSE;
67 #endif
68
69 static void (*save_check_termtype) (TERMTYPE2 *, bool);
70 static void check_termtype(TERMTYPE2 *tt, bool);
71
72 static const char usage_string[] = "\
73 [-e names] \
74 [-o dir] \
75 [-R name] \
76 [-v[n]] \
77 [-V] \
78 [-w[n]] \
79 [-\
80 1\
81 a\
82 C\
83 D\
84 c\
85 f\
86 G\
87 g\
88 I\
89 K\
90 L\
91 N\
92 r\
93 s\
94 T\
95 t\
96 U\
97 x\
98 ] \
99 source-file\n";
100
101 #if NO_LEAKS
102 static void
103 free_namelist(char **src)
104 {
105     if (src != 0) {
106         int n;
107         for (n = 0; src[n] != 0; ++n)
108             free(src[n]);
109         free(src);
110     }
111 }
112 #endif
113
114 static void
115 cleanup(void)
116 {
117     int rc;
118
119 #if NO_LEAKS
120     free_namelist(namelst);
121     _nc_leaks_dump_entry();
122 #endif
123     if (tmp_fp != 0)
124         fclose(tmp_fp);
125     if (to_remove != 0) {
126 #if HAVE_REMOVE
127         rc = remove(to_remove);
128 #else
129         rc = unlink(to_remove);
130 #endif
131         if (rc != 0)
132             perror(to_remove);
133     }
134 }
135
136 static void
137 failed(const char *msg)
138 {
139     perror(msg);
140     ExitProgram(EXIT_FAILURE);
141 }
142
143 static void
144 usage(void)
145 {
146 #define DATA(s) s "\n"
147     static const char options_string[] =
148     {
149         DATA("Options:")
150         DATA("  -0         format translation output all capabilities on one line")
151         DATA("  -1         format translation output one capability per line")
152 #if NCURSES_XNAMES
153         DATA("  -a         retain commented-out capabilities (sets -x also)")
154 #endif
155         DATA("  -C         translate entries to termcap source form")
156         DATA("  -D         print list of tic's database locations (first must be writable)")
157         DATA("  -c         check only, validate input without compiling or translating")
158         DATA("  -e<names>  translate/compile only entries named by comma-separated list")
159         DATA("  -f         format complex strings for readability")
160         DATA("  -G         format %{number} to %'char'")
161         DATA("  -g         format %'char' to %{number}")
162         DATA("  -I         translate entries to terminfo source form")
163         DATA("  -K         translate entries to termcap source form with BSD syntax")
164         DATA("  -L         translate entries to full terminfo source form")
165         DATA("  -N         disable smart defaults for source translation")
166         DATA("  -o<dir>    set output directory for compiled entry writes")
167         DATA("  -Q[n]      dump compiled description")
168         DATA("  -q    brief listing, removes headers")
169         DATA("  -R<name>   restrict translation to given terminfo/termcap version")
170         DATA("  -r         force resolution of all use entries in source translation")
171         DATA("  -s         print summary statistics")
172         DATA("  -T         remove size-restrictions on compiled description")
173 #if NCURSES_XNAMES
174         DATA("  -t         suppress commented-out capabilities")
175 #endif
176         DATA("  -U         suppress post-processing of entries")
177         DATA("  -V         print version")
178         DATA("  -W         wrap long strings according to -w[n] option")
179         DATA("  -v[n]      set verbosity level")
180         DATA("  -w[n]      set format width for translation output")
181 #if NCURSES_XNAMES
182         DATA("  -x         treat unknown capabilities as user-defined")
183 #endif
184         DATA("")
185         DATA("Parameters:")
186         DATA("  <file>     file to translate or compile")
187     };
188 #undef DATA
189
190     fprintf(stderr, "Usage: %s %s\n", _nc_progname, usage_string);
191     fputs(options_string, stderr);
192     ExitProgram(EXIT_FAILURE);
193 }
194
195 #define L_BRACE '{'
196 #define R_BRACE '}'
197 #define S_QUOTE '\''
198
199 static void
200 write_it(ENTRY * ep)
201 {
202     unsigned n;
203     int ch;
204     char *s, *d, *t;
205     char result[MAX_ENTRY_SIZE];
206
207     /*
208      * Look for strings that contain %{number}, convert them to %'char',
209      * which is shorter and runs a little faster.
210      */
211     for (n = 0; n < STRCOUNT; n++) {
212         s = ep->tterm.Strings[n];
213         if (VALID_STRING(s)
214             && strchr(s, L_BRACE) != 0) {
215             d = result;
216             t = s;
217             while ((ch = *t++) != 0) {
218                 *d++ = (char) ch;
219                 if (ch == '\\') {
220                     *d++ = *t++;
221                 } else if ((ch == '%')
222                            && (*t == L_BRACE)) {
223                     char *v = 0;
224                     long value = strtol(t + 1, &v, 0);
225                     if (v != 0
226                         && *v == R_BRACE
227                         && value > 0
228                         && value != '\\'        /* FIXME */
229                         && value < 127
230                         && isprint((int) value)) {
231                         *d++ = S_QUOTE;
232                         *d++ = (char) value;
233                         *d++ = S_QUOTE;
234                         t = (v + 1);
235                     }
236                 }
237             }
238             *d = 0;
239             if (strlen(result) < strlen(s))
240                 _nc_STRCPY(s, result, strlen(s) + 1);
241         }
242     }
243
244     _nc_set_type(_nc_first_name(ep->tterm.term_names));
245     _nc_curr_line = (int) ep->startline;
246     _nc_write_entry(&ep->tterm);
247 }
248
249 static bool
250 immedhook(ENTRY * ep GCC_UNUSED)
251 /* write out entries with no use capabilities immediately to save storage */
252 {
253 #if !HAVE_BIG_CORE
254     /*
255      * This is strictly a core-economy kluge.  The really clean way to handle
256      * compilation is to slurp the whole file into core and then do all the
257      * name-collision checks and entry writes in one swell foop.  But the
258      * terminfo master file is large enough that some core-poor systems swap
259      * like crazy when you compile it this way...there have been reports of
260      * this process taking *three hours*, rather than the twenty seconds or
261      * less typical on my development box.
262      *
263      * So.  This hook *immediately* writes out the referenced entry if it
264      * has no use capabilities.  The compiler main loop refrains from
265      * adding the entry to the in-core list when this hook fires.  If some
266      * other entry later needs to reference an entry that got written
267      * immediately, that's OK; the resolution code will fetch it off disk
268      * when it can't find it in core.
269      *
270      * Name collisions will still be detected, just not as cleanly.  The
271      * write_entry() code complains before overwriting an entry that
272      * postdates the time of tic's first call to write_entry().  Thus
273      * it will complain about overwriting entries newly made during the
274      * tic run, but not about overwriting ones that predate it.
275      *
276      * The reason this is a hook, and not in line with the rest of the
277      * compiler code, is that the support for termcap fallback cannot assume
278      * it has anywhere to spool out these entries!
279      *
280      * The _nc_set_type() call here requires a compensating one in
281      * _nc_parse_entry().
282      *
283      * If you define HAVE_BIG_CORE, you'll disable this kluge.  This will
284      * make tic a bit faster (because the resolution code won't have to do
285      * disk I/O nearly as often).
286      */
287     if (ep->nuses == 0) {
288         int oldline = _nc_curr_line;
289
290         write_it(ep);
291         _nc_curr_line = oldline;
292         free(ep->tterm.str_table);
293         return (TRUE);
294     }
295 #endif /* HAVE_BIG_CORE */
296     return (FALSE);
297 }
298
299 static void
300 put_translate(int c)
301 /* emit a comment char, translating terminfo names to termcap names */
302 {
303     static bool in_name = FALSE;
304     static size_t have, used;
305     static char *namebuf, *suffix;
306
307     if (in_name) {
308         if (used + 1 >= have) {
309             have += 132;
310             if ((namebuf = typeRealloc(char, have, namebuf)) == 0)
311                   failed("put_translate namebuf");
312             if ((suffix = typeRealloc(char, have, suffix)) == 0)
313                   failed("put_translate suffix");
314         }
315         if (c == '\n' || c == '@') {
316             namebuf[used++] = '\0';
317             (void) putchar('<');
318             (void) fputs(namebuf, stdout);
319             putchar(c);
320             in_name = FALSE;
321         } else if (c != '>') {
322             namebuf[used++] = (char) c;
323         } else {                /* ah! candidate name! */
324             char *up;
325             NCURSES_CONST char *tp;
326
327             namebuf[used++] = '\0';
328             in_name = FALSE;
329
330             suffix[0] = '\0';
331             if ((up = strchr(namebuf, '#')) != 0
332                 || (up = strchr(namebuf, '=')) != 0
333                 || ((up = strchr(namebuf, '@')) != 0 && up[1] == '>')) {
334                 _nc_STRCPY(suffix, up, have);
335                 *up = '\0';
336             }
337
338             if ((tp = nametrans(namebuf)) != 0) {
339                 (void) putchar(':');
340                 (void) fputs(tp, stdout);
341                 (void) fputs(suffix, stdout);
342                 (void) putchar(':');
343             } else {
344                 /* couldn't find a translation, just dump the name */
345                 (void) putchar('<');
346                 (void) fputs(namebuf, stdout);
347                 (void) fputs(suffix, stdout);
348                 (void) putchar('>');
349             }
350         }
351     } else {
352         used = 0;
353         if (c == '<') {
354             in_name = TRUE;
355         } else {
356             putchar(c);
357         }
358     }
359 }
360
361 /* Returns a string, stripped of leading/trailing whitespace */
362 static char *
363 stripped(char *src)
364 {
365     char *dst = 0;
366
367     while (isspace(UChar(*src)))
368         src++;
369
370     if (*src != '\0') {
371         size_t len;
372
373         if ((dst = strdup(src)) == NULL) {
374             failed("strdup");
375         } else {
376             len = strlen(dst);
377             while (--len != 0 && isspace(UChar(dst[len])))
378                 dst[len] = '\0';
379         }
380     }
381     return dst;
382 }
383
384 static FILE *
385 open_tempfile(char *filename)
386 {
387     FILE *result = 0;
388
389     _nc_STRCPY(filename, "/tmp/XXXXXX", PATH_MAX);
390 #if HAVE_MKSTEMP
391     {
392         int oldmask = (int) umask(077);
393         int fd = mkstemp(filename);
394         if (fd >= 0)
395             result = fdopen(fd, "w");
396         umask((mode_t) oldmask);
397     }
398 #else
399     if (tmpnam(filename) != 0)
400         result = fopen(filename, "w");
401 #endif
402     return result;
403 }
404
405 static FILE *
406 copy_input(FILE *source, const char *filename, char *alt_file)
407 {
408     char my_altfile[PATH_MAX];
409     FILE *result = 0;
410     FILE *target = 0;
411     int ch;
412
413     if (alt_file == 0)
414         alt_file = my_altfile;
415
416     if (source == 0) {
417         failed("copy_input (source)");
418     } else if ((target = open_tempfile(alt_file)) == 0) {
419         failed("copy_input (target)");
420     } else {
421         clearerr(source);
422         for (;;) {
423             ch = fgetc(source);
424             if (feof(source)) {
425                 break;
426             } else if (ferror(source)) {
427                 failed(filename);
428             } else if (ch == 0) {
429                 /* don't loop in case someone wants to convert /dev/zero */
430                 fprintf(stderr, "%s: %s is not a text-file\n", _nc_progname, filename);
431                 ExitProgram(EXIT_FAILURE);
432             }
433             fputc(ch, target);
434         }
435         fclose(source);
436         /*
437          * rewind() does not force the target file's data to disk (not does
438          * fflush()...).  So open a second stream on the data and then close
439          * the one that we were writing on before starting to read from the
440          * second stream.
441          */
442         result = fopen(alt_file, "r+");
443         fclose(target);
444         to_remove = strdup(alt_file);
445     }
446     return result;
447 }
448
449 static FILE *
450 open_input(const char *filename, char *alt_file)
451 {
452     FILE *fp;
453     struct stat sb;
454     int mode;
455
456     if (!strcmp(filename, "-")) {
457         fp = copy_input(stdin, STDIN_NAME, alt_file);
458     } else if (stat(filename, &sb) < 0) {
459         fprintf(stderr, "%s: %s %s\n", _nc_progname, filename, strerror(errno));
460         ExitProgram(EXIT_FAILURE);
461     } else if ((mode = (sb.st_mode & S_IFMT)) == S_IFDIR
462                || (mode != S_IFREG && mode != S_IFCHR && mode != S_IFIFO)) {
463         fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
464         ExitProgram(EXIT_FAILURE);
465     } else {
466         fp = fopen(filename, "r");
467
468         if (fp == 0) {
469             fprintf(stderr, "%s: Can't open %s\n", _nc_progname, filename);
470             ExitProgram(EXIT_FAILURE);
471         }
472         if (mode != S_IFREG) {
473             if (alt_file != 0) {
474                 FILE *fp2 = copy_input(fp, filename, alt_file);
475                 fp = fp2;
476             } else {
477                 fprintf(stderr, "%s: %s is not a file\n", _nc_progname, filename);
478                 ExitProgram(EXIT_FAILURE);
479             }
480         }
481     }
482     return fp;
483 }
484
485 /* Parse the "-e" option-value into a list of names */
486 static char **
487 make_namelist(char *src)
488 {
489     char **dst = 0;
490
491     char *s, *base;
492     unsigned pass, n, nn;
493     char buffer[BUFSIZ];
494
495     if (src == 0) {
496         /* EMPTY */ ;
497     } else if (strchr(src, '/') != 0) {         /* a filename */
498         FILE *fp = open_input(src, (char *) 0);
499
500         for (pass = 1; pass <= 2; pass++) {
501             nn = 0;
502             while (fgets(buffer, sizeof(buffer), fp) != 0) {
503                 if ((s = stripped(buffer)) != 0) {
504                     if (dst != 0)
505                         dst[nn] = s;
506                     else
507                         free(s);
508                     nn++;
509                 }
510             }
511             if (pass == 1) {
512                 if ((dst = typeCalloc(char *, nn + 1)) == 0)
513                       failed("make_namelist");
514                 rewind(fp);
515             }
516         }
517         fclose(fp);
518     } else {                    /* literal list of names */
519         for (pass = 1; pass <= 2; pass++) {
520             for (n = nn = 0, base = src;; n++) {
521                 int mark = src[n];
522                 if (mark == ',' || mark == '\0') {
523                     if (pass == 1) {
524                         nn++;
525                     } else {
526                         src[n] = '\0';
527                         if ((s = stripped(base)) != 0)
528                             dst[nn++] = s;
529                         base = &src[n + 1];
530                     }
531                 }
532                 if (mark == '\0')
533                     break;
534             }
535             if (pass == 1) {
536                 if ((dst = typeCalloc(char *, nn + 1)) == 0)
537                       failed("make_namelist");
538             }
539         }
540     }
541     if (showsummary && (dst != 0)) {
542         fprintf(log_fp, "Entries that will be compiled:\n");
543         for (n = 0; dst[n] != 0; n++)
544             fprintf(log_fp, "%u:%s\n", n + 1, dst[n]);
545     }
546     return dst;
547 }
548
549 static bool
550 matches(char **needle, const char *haystack)
551 /* does entry in needle list match |-separated field in haystack? */
552 {
553     bool code = FALSE;
554     size_t n;
555
556     if (needle != 0) {
557         for (n = 0; needle[n] != 0; n++) {
558             if (_nc_name_match(haystack, needle[n], "|")) {
559                 code = TRUE;
560                 break;
561             }
562         }
563     } else
564         code = TRUE;
565     return (code);
566 }
567
568 static char *
569 valid_db_path(const char *nominal)
570 {
571     struct stat sb;
572 #if USE_HASHED_DB
573     char suffix[] = DBM_SUFFIX;
574     size_t need = strlen(nominal) + sizeof(suffix);
575     char *result = malloc(need);
576
577     if (result == 0)
578         failed("valid_db_path");
579     _nc_STRCPY(result, nominal, need);
580     if (strcmp(result + need - sizeof(suffix), suffix)) {
581         _nc_STRCAT(result, suffix, need);
582     }
583 #else
584     char *result = strdup(nominal);
585 #endif
586
587     DEBUG(1, ("** stat(%s)", result));
588     if (stat(result, &sb) >= 0) {
589 #if USE_HASHED_DB
590         if (!S_ISREG(sb.st_mode)
591             || access(result, R_OK | W_OK) != 0) {
592             DEBUG(1, ("...not a writable file"));
593             free(result);
594             result = 0;
595         }
596 #else
597         if (!S_ISDIR(sb.st_mode)
598             || access(result, R_OK | W_OK | X_OK) != 0) {
599             DEBUG(1, ("...not a writable directory"));
600             free(result);
601             result = 0;
602         }
603 #endif
604     } else {
605         /* check if parent is directory and is writable */
606         unsigned leaf = _nc_pathlast(result);
607
608         DEBUG(1, ("...not found"));
609         if (leaf) {
610             char save = result[leaf];
611             result[leaf] = 0;
612             if (stat(result, &sb) >= 0
613                 && S_ISDIR(sb.st_mode)
614                 && access(result, R_OK | W_OK | X_OK) == 0) {
615                 result[leaf] = save;
616             } else {
617                 DEBUG(1, ("...parent directory %s is not writable", result));
618                 free(result);
619                 result = 0;
620             }
621         } else {
622             DEBUG(1, ("... no parent directory"));
623             free(result);
624             result = 0;
625         }
626     }
627     return result;
628 }
629
630 /*
631  * Show the databases to which tic could write.  The location to which it
632  * writes is always the first one.  If none are writable, print an error
633  * message.
634  */
635 static void
636 show_databases(const char *outdir)
637 {
638     bool specific = (outdir != 0) || getenv("TERMINFO") != 0;
639     char *result;
640     const char *tried = 0;
641
642     if (outdir == 0) {
643         outdir = _nc_tic_dir(0);
644     }
645     if ((result = valid_db_path(outdir)) != 0) {
646         printf("%s\n", result);
647         free(result);
648     } else {
649         tried = outdir;
650     }
651
652     if ((outdir = _nc_home_terminfo())) {
653         if ((result = valid_db_path(outdir)) != 0) {
654             printf("%s\n", result);
655             free(result);
656         } else if (!specific) {
657             tried = outdir;
658         }
659     }
660
661     /*
662      * If we can write in neither location, give an error message.
663      */
664     if (tried) {
665         fflush(stdout);
666         fprintf(stderr, "%s: %s (no permission)\n", _nc_progname, tried);
667         ExitProgram(EXIT_FAILURE);
668     }
669 }
670
671 static void
672 add_digit(int *target, int source)
673 {
674     *target = (*target * 10) + (source - '0');
675 }
676
677 #define VtoTrace(opt) (unsigned) ((opt > 0) ? opt : (opt == 0))
678
679 int
680 main(int argc, char *argv[])
681 {
682     char my_tmpname[PATH_MAX];
683     char my_altfile[PATH_MAX];
684     int v_opt = -1;
685     unsigned debug_level;
686     int smart_defaults = TRUE;
687     char *termcap;
688     ENTRY *qp;
689
690     int this_opt, last_opt = '?';
691
692     int outform = F_TERMINFO;   /* output format */
693     int sortmode = S_TERMINFO;  /* sort_mode */
694
695     int width = 60;
696     int height = 65535;
697     bool formatted = FALSE;     /* reformat complex strings? */
698     bool literal = FALSE;       /* suppress post-processing? */
699     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
700     bool forceresolve = FALSE;  /* force resolution */
701     bool limited = TRUE;
702     char *tversion = (char *) NULL;
703     const char *source_file = "terminfo";
704     char *outdir = (char *) NULL;
705     bool check_only = FALSE;
706     bool suppress_untranslatable = FALSE;
707     int quickdump = 0;
708     bool quiet = FALSE;
709     bool wrap_strings = FALSE;
710
711     log_fp = stderr;
712
713     _nc_progname = _nc_rootname(argv[0]);
714     atexit(cleanup);
715
716     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
717         outform = F_TERMINFO;
718         sortmode = S_TERMINFO;
719     }
720     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
721         outform = F_TERMCAP;
722         sortmode = S_TERMCAP;
723     }
724 #if NCURSES_XNAMES
725     use_extended_names(FALSE);
726 #endif
727     _nc_strict_bsd = 0;
728
729     /*
730      * Processing arguments is a little complicated, since someone made a
731      * design decision to allow the numeric values for -w, -v options to
732      * be optional.
733      */
734     while ((this_opt = getopt(argc, argv,
735                               "0123456789CDIKLNQR:TUVWace:fGgo:qrstvwx")) != -1) {
736         if (isdigit(this_opt)) {
737             switch (last_opt) {
738             case 'Q':
739                 add_digit(&quickdump, this_opt);
740                 break;
741             case 'v':
742                 add_digit(&v_opt, this_opt);
743                 break;
744             case 'w':
745                 add_digit(&width, this_opt);
746                 break;
747             default:
748                 switch (this_opt) {
749                 case '0':
750                     last_opt = this_opt;
751                     width = 65535;
752                     height = 1;
753                     break;
754                 case '1':
755                     last_opt = this_opt;
756                     width = 0;
757                     break;
758                 default:
759                     usage();
760                 }
761             }
762             continue;
763         }
764         switch (this_opt) {
765         case 'K':
766             _nc_strict_bsd = 1;
767             /* the initial version of -K in 20110730 fell-thru here, but the
768              * same flag is useful when reading sources -TD
769              */
770             break;
771         case 'C':
772             capdump = TRUE;
773             outform = F_TERMCAP;
774             sortmode = S_TERMCAP;
775             break;
776         case 'D':
777             debug_level = VtoTrace(v_opt);
778             set_trace_level(debug_level);
779             show_databases(outdir);
780             ExitProgram(EXIT_SUCCESS);
781             break;
782         case 'I':
783             infodump = TRUE;
784             outform = F_TERMINFO;
785             sortmode = S_TERMINFO;
786             break;
787         case 'L':
788             infodump = TRUE;
789             outform = F_VARIABLE;
790             sortmode = S_VARIABLE;
791             break;
792         case 'N':
793             smart_defaults = FALSE;
794             literal = TRUE;
795             break;
796         case 'Q':
797             quickdump = 0;
798             break;
799         case 'R':
800             tversion = optarg;
801             break;
802         case 'T':
803             limited = FALSE;
804             break;
805         case 'U':
806             literal = TRUE;
807             break;
808         case 'V':
809             puts(curses_version());
810             ExitProgram(EXIT_SUCCESS);
811         case 'W':
812             wrap_strings = TRUE;
813             break;
814         case 'c':
815             check_only = TRUE;
816             break;
817         case 'e':
818             namelst = make_namelist(optarg);
819             break;
820         case 'f':
821             formatted = TRUE;
822             break;
823         case 'G':
824             numbers = 1;
825             break;
826         case 'g':
827             numbers = -1;
828             break;
829         case 'o':
830             outdir = optarg;
831             break;
832         case 'q':
833             quiet = TRUE;
834             break;
835         case 'r':
836             forceresolve = TRUE;
837             break;
838         case 's':
839             showsummary = TRUE;
840             break;
841         case 'v':
842             v_opt = 0;
843             break;
844         case 'w':
845             width = 0;
846             break;
847 #if NCURSES_XNAMES
848         case 't':
849             _nc_disable_period = FALSE;
850             suppress_untranslatable = TRUE;
851             break;
852         case 'a':
853             _nc_disable_period = TRUE;
854             /* FALLTHRU */
855         case 'x':
856             use_extended_names(TRUE);
857             using_extensions = TRUE;
858             break;
859 #endif
860         default:
861             usage();
862         }
863         last_opt = this_opt;
864     }
865
866     debug_level = VtoTrace(v_opt);
867     set_trace_level(debug_level);
868
869     if (_nc_tracing) {
870         save_check_termtype = _nc_check_termtype2;
871         _nc_check_termtype2 = check_termtype;
872     }
873 #if !HAVE_BIG_CORE
874     /*
875      * Aaargh! immedhook seriously hoses us!
876      *
877      * One problem with immedhook is it means we can't do -e.  Problem
878      * is that we can't guarantee that for each terminal listed, all the
879      * terminals it depends on will have been kept in core for reference
880      * resolution -- in fact it's certain the primitive types at the end
881      * of reference chains *won't* be in core unless they were explicitly
882      * in the select list themselves.
883      */
884     if (namelst && (!infodump && !capdump)) {
885         (void) fprintf(stderr,
886                        "%s: Sorry, -e can't be used without -I or -C\n",
887                        _nc_progname);
888         ExitProgram(EXIT_FAILURE);
889     }
890 #endif /* HAVE_BIG_CORE */
891
892     if (optind < argc) {
893         source_file = argv[optind++];
894         if (optind < argc) {
895             fprintf(stderr,
896                     "%s: Too many file names.  Usage:\n\t%s %s",
897                     _nc_progname,
898                     _nc_progname,
899                     usage_string);
900             ExitProgram(EXIT_FAILURE);
901         }
902     } else {
903         if (infodump == TRUE) {
904             /* captoinfo's no-argument case */
905             source_file = "/etc/termcap";
906             if ((termcap = getenv("TERMCAP")) != 0
907                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
908                 if (access(termcap, F_OK) == 0) {
909                     /* file exists */
910                     source_file = termcap;
911                 } else {
912                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
913                         source_file = my_tmpname;
914                         fprintf(tmp_fp, "%s\n", termcap);
915                         fclose(tmp_fp);
916                         tmp_fp = open_input(source_file, (char *) 0);
917                         to_remove = source_file;
918                     } else {
919                         failed("tmpnam");
920                     }
921                 }
922             }
923         } else {
924             /* tic */
925             fprintf(stderr,
926                     "%s: File name needed.  Usage:\n\t%s %s",
927                     _nc_progname,
928                     _nc_progname,
929                     usage_string);
930             ExitProgram(EXIT_FAILURE);
931         }
932     }
933
934     if (tmp_fp == 0) {
935         tmp_fp = open_input(source_file, my_altfile);
936         if (!strcmp(source_file, "-")) {
937             source_file = STDIN_NAME;
938         }
939     }
940
941     if (infodump || check_only) {
942         dump_init(tversion,
943                   (smart_defaults
944                    ? outform
945                    : F_LITERAL),
946                   sortmode,
947                   wrap_strings, width, height,
948                   debug_level, formatted || check_only, check_only, quickdump);
949     } else if (capdump) {
950         dump_init(tversion,
951                   outform,
952                   sortmode,
953                   wrap_strings, width, height,
954                   debug_level, FALSE, FALSE, FALSE);
955     }
956
957     /* parse entries out of the source file */
958     _nc_set_source(source_file);
959 #if !HAVE_BIG_CORE
960     if (!(check_only || infodump || capdump))
961         _nc_set_writedir(outdir);
962 #endif /* HAVE_BIG_CORE */
963     _nc_read_entry_source(tmp_fp, (char *) NULL,
964                           !smart_defaults || literal, FALSE,
965                           ((check_only || infodump || capdump)
966                            ? NULLHOOK
967                            : immedhook));
968
969     /* do use resolution */
970     if (check_only || (!infodump && !capdump) || forceresolve) {
971         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
972             ExitProgram(EXIT_FAILURE);
973         }
974     }
975
976     /* length check */
977     if (check_only && limited && (capdump || infodump)) {
978         for_entry_list(qp) {
979             if (matches(namelst, qp->tterm.term_names)) {
980                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
981
982                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
983                     (void) fprintf(stderr,
984                                    "%s: resolved %s entry is %d bytes long\n",
985                                    _nc_progname,
986                                    _nc_first_name(qp->tterm.term_names),
987                                    len);
988             }
989         }
990     }
991
992     /* write or dump all entries */
993     if (check_only) {
994         /* this is in case infotocap() generates warnings */
995         _nc_curr_col = _nc_curr_line = -1;
996
997         for_entry_list(qp) {
998             if (matches(namelst, qp->tterm.term_names)) {
999                 /* this is in case infotocap() generates warnings */
1000                 _nc_set_type(_nc_first_name(qp->tterm.term_names));
1001                 _nc_curr_line = (int) qp->startline;
1002                 repair_acsc(&qp->tterm);
1003                 dump_entry(&qp->tterm, suppress_untranslatable,
1004                            limited, numbers, NULL);
1005             }
1006         }
1007     } else {
1008         if (!infodump && !capdump) {
1009             _nc_set_writedir(outdir);
1010             for_entry_list(qp) {
1011                 if (matches(namelst, qp->tterm.term_names))
1012                     write_it(qp);
1013             }
1014         } else {
1015             /* this is in case infotocap() generates warnings */
1016             _nc_curr_col = _nc_curr_line = -1;
1017
1018             for_entry_list(qp) {
1019                 if (matches(namelst, qp->tterm.term_names)) {
1020                     long j = qp->cend - qp->cstart;
1021                     int len = 0;
1022
1023                     /* this is in case infotocap() generates warnings */
1024                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
1025
1026                     if (!quiet) {
1027                         (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
1028                         while (j-- > 0) {
1029                             if (infodump)
1030                                 (void) putchar(fgetc(tmp_fp));
1031                             else
1032                                 put_translate(fgetc(tmp_fp));
1033                         }
1034                     }
1035
1036                     repair_acsc(&qp->tterm);
1037                     dump_entry(&qp->tterm, suppress_untranslatable,
1038                                limited, numbers, NULL);
1039                     for (j = 0; j < (long) qp->nuses; j++)
1040                         dump_uses(qp->uses[j].name, !capdump);
1041                     len = show_entry();
1042                     if (debug_level != 0 && !limited)
1043                         printf("# length=%d\n", len);
1044                 }
1045             }
1046             if (!namelst && _nc_tail && !quiet) {
1047                 int c, oldc = '\0';
1048                 bool in_comment = FALSE;
1049                 bool trailing_comment = FALSE;
1050
1051                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1052                 while ((c = fgetc(tmp_fp)) != EOF) {
1053                     if (oldc == '\n') {
1054                         if (c == '#') {
1055                             trailing_comment = TRUE;
1056                             in_comment = TRUE;
1057                         } else {
1058                             in_comment = FALSE;
1059                         }
1060                     }
1061                     if (trailing_comment
1062                         && (in_comment || (oldc == '\n' && c == '\n')))
1063                         putchar(c);
1064                     oldc = c;
1065                 }
1066             }
1067         }
1068     }
1069
1070     /* Show the directory into which entries were written, and the total
1071      * number of entries
1072      */
1073     if (showsummary
1074         && (!(check_only || infodump || capdump))) {
1075         int total = _nc_tic_written();
1076         if (total != 0)
1077             fprintf(log_fp, "%d entries written to %s\n",
1078                     total,
1079                     _nc_tic_dir((char *) 0));
1080         else
1081             fprintf(log_fp, "No entries written\n");
1082     }
1083     ExitProgram(EXIT_SUCCESS);
1084 }
1085
1086 /*
1087  * This bit of legerdemain turns all the terminfo variable names into
1088  * references to locations in the arrays Booleans, Numbers, and Strings ---
1089  * precisely what's needed (see comp_parse.c).
1090  */
1091 #undef CUR
1092 #define CUR tp->
1093
1094 /*
1095  * Check if the alternate character-set capabilities are consistent.
1096  */
1097 static void
1098 check_acs(TERMTYPE2 *tp)
1099 {
1100     if (VALID_STRING(acs_chars)) {
1101         const char *boxes = "lmkjtuvwqxn";
1102         char mapped[256];
1103         char missing[256];
1104         const char *p;
1105         char *q;
1106
1107         memset(mapped, 0, sizeof(mapped));
1108         for (p = acs_chars; *p != '\0'; p += 2) {
1109             if (p[1] == '\0') {
1110                 _nc_warning("acsc has odd number of characters");
1111                 break;
1112             }
1113             mapped[UChar(p[0])] = p[1];
1114         }
1115
1116         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1117             _nc_warning("acsc refers to 'I', which is probably an error");
1118         }
1119
1120         for (p = boxes, q = missing; *p != '\0'; ++p) {
1121             if (!mapped[UChar(p[0])]) {
1122                 *q++ = p[0];
1123             }
1124         }
1125         *q = '\0';
1126
1127         assert(strlen(missing) <= strlen(boxes));
1128         if (*missing != '\0' && strcmp(missing, boxes)) {
1129             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1130         }
1131     }
1132 }
1133
1134 /*
1135  * Check if the color capabilities are consistent
1136  */
1137 static void
1138 check_colors(TERMTYPE2 *tp)
1139 {
1140     if ((max_colors > 0) != (max_pairs > 0)
1141         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1142         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1143                     max_colors, max_pairs);
1144
1145     PAIRED(set_foreground, set_background);
1146     PAIRED(set_a_foreground, set_a_background);
1147     PAIRED(set_color_pair, initialize_pair);
1148
1149     if (VALID_STRING(set_foreground)
1150         && VALID_STRING(set_a_foreground)
1151         && !_nc_capcmp(set_foreground, set_a_foreground))
1152         _nc_warning("expected setf/setaf to be different");
1153
1154     if (VALID_STRING(set_background)
1155         && VALID_STRING(set_a_background)
1156         && !_nc_capcmp(set_background, set_a_background))
1157         _nc_warning("expected setb/setab to be different");
1158
1159     /* see: has_colors() */
1160     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1161         && (((set_foreground != NULL)
1162              && (set_background != NULL))
1163             || ((set_a_foreground != NULL)
1164                 && (set_a_background != NULL))
1165             || set_color_pair)) {
1166         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1167             _nc_warning("expected either op/oc string for resetting colors");
1168     }
1169     if (can_change) {
1170         if (!VALID_STRING(initialize_pair) &&
1171             !VALID_STRING(initialize_color)) {
1172             _nc_warning("expected initc or initp because ccc is given");
1173         }
1174     } else {
1175         if (VALID_STRING(initialize_pair) ||
1176             VALID_STRING(initialize_color)) {
1177             _nc_warning("expected ccc because initc is given");
1178         }
1179     }
1180 }
1181
1182 static int
1183 csi_length(const char *value)
1184 {
1185     int result = 0;
1186
1187     if (value[0] == '\033' && value[1] == '[') {
1188         result = 2;
1189     } else if (UChar(value[0]) == 0x9a) {
1190         result = 1;
1191     }
1192     return result;
1193 }
1194
1195 static char
1196 keypad_final(const char *string)
1197 {
1198     char result = '\0';
1199
1200     if (VALID_STRING(string)
1201         && *string++ == '\033'
1202         && *string++ == 'O'
1203         && strlen(string) == 1) {
1204         result = *string;
1205     }
1206
1207     return result;
1208 }
1209
1210 static long
1211 keypad_index(const char *string)
1212 {
1213     char *test;
1214     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1215     int ch;
1216     long result = -1;
1217
1218     if ((ch = keypad_final(string)) != '\0') {
1219         test = (strchr) (list, ch);
1220         if (test != 0)
1221             result = (long) (test - list);
1222     }
1223     return result;
1224 }
1225
1226 /*
1227  * list[] is down, up, left, right
1228  * "left" may be ^H rather than \E[D
1229  * "down" may be ^J rather than \E[B
1230  * But up/right are generally consistently escape sequences for ANSI terminals.
1231  */
1232 static void
1233 check_ansi_cursor(char *list[4])
1234 {
1235     int j, k;
1236     int want;
1237     size_t suffix;
1238     bool skip[4];
1239     bool repeated = FALSE;
1240
1241     for (j = 0; j < 4; ++j) {
1242         skip[j] = FALSE;
1243         for (k = 0; k < j; ++k) {
1244             if (j != k
1245                 && !strcmp(list[j], list[k])) {
1246                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1247                 _nc_warning("repeated cursor control %s\n", value);
1248                 repeated = TRUE;
1249             }
1250         }
1251     }
1252     if (!repeated) {
1253         char *up = list[1];
1254         size_t prefix = (size_t) csi_length(up);
1255
1256         if (prefix) {
1257             suffix = prefix;
1258             while (up[suffix] && isdigit(UChar(up[suffix])))
1259                 ++suffix;
1260         }
1261         if (prefix && up[suffix] == 'A') {
1262             skip[1] = TRUE;
1263             if (!strcmp(list[0], "\n"))
1264                 skip[0] = TRUE;
1265             if (!strcmp(list[2], "\b"))
1266                 skip[2] = TRUE;
1267
1268             for (j = 0; j < 4; ++j) {
1269                 if (skip[j] || strlen(list[j]) == 1)
1270                     continue;
1271                 if (memcmp(list[j], up, prefix)) {
1272                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1273                     _nc_warning("inconsistent prefix for %s\n", value);
1274                     continue;
1275                 }
1276                 if (strlen(list[j]) < suffix) {
1277                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1278                     _nc_warning("inconsistent length for %s, expected %d\n",
1279                                 value, (int) suffix + 1);
1280                     continue;
1281                 }
1282                 want = "BADC"[j];
1283                 if (list[j][suffix] != want) {
1284                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1285                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1286                                 value, want, list[j][suffix]);
1287                 }
1288             }
1289         }
1290     }
1291 }
1292
1293 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1294 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1295
1296 static void
1297 check_noaddress(TERMTYPE2 *tp, const char *why)
1298 {
1299     UNEXPECTED(column_address);
1300     UNEXPECTED(cursor_address);
1301     UNEXPECTED(cursor_home);
1302     UNEXPECTED(cursor_mem_address);
1303     UNEXPECTED(cursor_to_ll);
1304     UNEXPECTED(row_address);
1305     UNEXPECTED(row_address);
1306 }
1307
1308 static void
1309 check_cursor(TERMTYPE2 *tp)
1310 {
1311     int count;
1312     char *list[4];
1313
1314     if (hard_copy) {
1315         check_noaddress(tp, "hard_copy");
1316     } else if (generic_type) {
1317         check_noaddress(tp, "generic_type");
1318     } else if (strchr(tp->term_names, '+') == 0) {
1319         int y = 0;
1320         int x = 0;
1321         if (PRESENT(column_address))
1322             ++y;
1323         if (PRESENT(cursor_address))
1324             y = x = 10;
1325         if (PRESENT(cursor_home))
1326             ++y, ++x;
1327         if (PRESENT(cursor_mem_address))
1328             y = x = 10;
1329         if (PRESENT(cursor_to_ll))
1330             ++y, ++x;
1331         if (PRESENT(row_address))
1332             ++x;
1333         if (PRESENT(cursor_down))
1334             ++y;
1335         if (PRESENT(cursor_up))
1336             ++y;
1337         if (PRESENT(cursor_left))
1338             ++x;
1339         if (PRESENT(cursor_right))
1340             ++x;
1341         if (x < 2 && y < 2) {
1342             _nc_warning("terminal lacks cursor addressing");
1343         } else {
1344             if (x < 2)
1345                 _nc_warning("terminal lacks cursor column-addressing");
1346             if (y < 2)
1347                 _nc_warning("terminal lacks cursor row-addressing");
1348         }
1349     }
1350
1351     /* it is rare to have an insert-line feature without a matching delete */
1352     ANDMISSING(parm_insert_line, insert_line);
1353     ANDMISSING(parm_delete_line, delete_line);
1354     ANDMISSING(parm_insert_line, parm_delete_line);
1355
1356     /* if we have a parameterized form, then the non-parameterized is easy */
1357     ANDMISSING(parm_down_cursor, cursor_down);
1358     ANDMISSING(parm_up_cursor, cursor_up);
1359     ANDMISSING(parm_left_cursor, cursor_left);
1360     ANDMISSING(parm_right_cursor, cursor_right);
1361
1362     /* Given any of a set of cursor movement, the whole set should be present.
1363      * Technically this is not true (we could use cursor_address to fill in
1364      * unsupported controls), but it is likely.
1365      */
1366     count = 0;
1367     if (PRESENT(parm_down_cursor)) {
1368         list[count++] = parm_down_cursor;
1369     }
1370     if (PRESENT(parm_up_cursor)) {
1371         list[count++] = parm_up_cursor;
1372     }
1373     if (PRESENT(parm_left_cursor)) {
1374         list[count++] = parm_left_cursor;
1375     }
1376     if (PRESENT(parm_right_cursor)) {
1377         list[count++] = parm_right_cursor;
1378     }
1379     if (count == 4) {
1380         check_ansi_cursor(list);
1381     } else if (count != 0) {
1382         EXPECTED(parm_down_cursor);
1383         EXPECTED(parm_up_cursor);
1384         EXPECTED(parm_left_cursor);
1385         EXPECTED(parm_right_cursor);
1386     }
1387
1388     count = 0;
1389     if (PRESENT(cursor_down)) {
1390         list[count++] = cursor_down;
1391     }
1392     if (PRESENT(cursor_up)) {
1393         list[count++] = cursor_up;
1394     }
1395     if (PRESENT(cursor_left)) {
1396         list[count++] = cursor_left;
1397     }
1398     if (PRESENT(cursor_right)) {
1399         list[count++] = cursor_right;
1400     }
1401     if (count == 4) {
1402         check_ansi_cursor(list);
1403     } else if (count != 0) {
1404         count = 0;
1405         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1406             ++count;
1407         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1408             ++count;
1409         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1410             ++count;
1411         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1412             ++count;
1413         if (count) {
1414             EXPECTED(cursor_down);
1415             EXPECTED(cursor_up);
1416             EXPECTED(cursor_left);
1417             EXPECTED(cursor_right);
1418         }
1419     }
1420 }
1421
1422 #define MAX_KP 5
1423 /*
1424  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1425  * is mapped inconsistently.
1426  */
1427 static void
1428 check_keypad(TERMTYPE2 *tp)
1429 {
1430     char show[80];
1431
1432     if (VALID_STRING(key_a1) &&
1433         VALID_STRING(key_a3) &&
1434         VALID_STRING(key_b2) &&
1435         VALID_STRING(key_c1) &&
1436         VALID_STRING(key_c3)) {
1437         char final[MAX_KP + 1];
1438         long list[MAX_KP];
1439         int increase = 0;
1440         int j, k, kk;
1441         long last;
1442         long test;
1443
1444         final[0] = keypad_final(key_a1);
1445         final[1] = keypad_final(key_a3);
1446         final[2] = keypad_final(key_b2);
1447         final[3] = keypad_final(key_c1);
1448         final[4] = keypad_final(key_c3);
1449         final[5] = '\0';
1450
1451         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1452         assert(strlen(final) <= MAX_KP);
1453         if (!strcmp(final, "qsrpn"))
1454             return;
1455
1456         list[0] = keypad_index(key_a1);
1457         list[1] = keypad_index(key_a3);
1458         list[2] = keypad_index(key_b2);
1459         list[3] = keypad_index(key_c1);
1460         list[4] = keypad_index(key_c3);
1461
1462         /* check that they're all vt100 keys */
1463         for (j = 0; j < MAX_KP; ++j) {
1464             if (list[j] < 0) {
1465                 return;
1466             }
1467         }
1468
1469         /* check if they're all in increasing order */
1470         for (j = 1; j < MAX_KP; ++j) {
1471             if (list[j] > list[j - 1]) {
1472                 ++increase;
1473             }
1474         }
1475         if (increase != (MAX_KP - 1)) {
1476             show[0] = '\0';
1477
1478             for (j = 0, last = -1; j < MAX_KP; ++j) {
1479                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1480                     if (list[k] > last &&
1481                         list[k] < test) {
1482                         test = list[k];
1483                         kk = k;
1484                     }
1485                 }
1486                 last = test;
1487                 assert(strlen(show) < (MAX_KP * 4));
1488                 switch (kk) {
1489                 case 0:
1490                     _nc_STRCAT(show, " ka1", sizeof(show));
1491                     break;
1492                 case 1:
1493                     _nc_STRCAT(show, " ka3", sizeof(show));
1494                     break;
1495                 case 2:
1496                     _nc_STRCAT(show, " kb2", sizeof(show));
1497                     break;
1498                 case 3:
1499                     _nc_STRCAT(show, " kc1", sizeof(show));
1500                     break;
1501                 case 4:
1502                     _nc_STRCAT(show, " kc3", sizeof(show));
1503                     break;
1504                 }
1505             }
1506
1507             _nc_warning("vt100 keypad order inconsistent: %s", show);
1508         }
1509
1510     } else if (VALID_STRING(key_a1) ||
1511                VALID_STRING(key_a3) ||
1512                VALID_STRING(key_b2) ||
1513                VALID_STRING(key_c1) ||
1514                VALID_STRING(key_c3)) {
1515         show[0] = '\0';
1516         if (keypad_index(key_a1) >= 0)
1517             _nc_STRCAT(show, " ka1", sizeof(show));
1518         if (keypad_index(key_a3) >= 0)
1519             _nc_STRCAT(show, " ka3", sizeof(show));
1520         if (keypad_index(key_b2) >= 0)
1521             _nc_STRCAT(show, " kb2", sizeof(show));
1522         if (keypad_index(key_c1) >= 0)
1523             _nc_STRCAT(show, " kc1", sizeof(show));
1524         if (keypad_index(key_c3) >= 0)
1525             _nc_STRCAT(show, " kc3", sizeof(show));
1526         if (*show != '\0')
1527             _nc_warning("vt100 keypad map incomplete:%s", show);
1528     }
1529
1530     /*
1531      * These warnings are useful for consistency checks - it is possible that
1532      * there are real terminals with mismatches in these
1533      */
1534     ANDMISSING(key_ic, key_dc);
1535 }
1536
1537 static void
1538 check_printer(TERMTYPE2 *tp)
1539 {
1540     (void) tp;
1541 #if defined(enter_doublewide_mode) && defined(exit_doublewide_mode)
1542     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1543 #endif
1544 #if defined(enter_italics_mode) && defined(exit_italics_mode)
1545     PAIRED(enter_italics_mode, exit_italics_mode);
1546 #endif
1547 #if defined(enter_leftward_mode) && defined(exit_leftward_mode)
1548     PAIRED(enter_leftward_mode, exit_leftward_mode);
1549 #endif
1550 #if defined(enter_micro_mode) && defined(exit_micro_mode)
1551     PAIRED(enter_micro_mode, exit_micro_mode);
1552 #endif
1553 #if defined(enter_shadow_mode) && defined(exit_shadow_mode)
1554     PAIRED(enter_shadow_mode, exit_shadow_mode);
1555 #endif
1556 #if defined(enter_subscript_mode) && defined(exit_subscript_mode)
1557     PAIRED(enter_subscript_mode, exit_subscript_mode);
1558 #endif
1559 #if defined(enter_superscript_mode) && defined(exit_superscript_mode)
1560     PAIRED(enter_superscript_mode, exit_superscript_mode);
1561 #endif
1562 #if defined(enter_upward_mode) && defined(exit_upward_mode)
1563     PAIRED(enter_upward_mode, exit_upward_mode);
1564 #endif
1565
1566 #if defined(start_char_set_def) && defined(stop_char_set_def)
1567     ANDMISSING(start_char_set_def, stop_char_set_def);
1568 #endif
1569
1570     /* if we have a parameterized form, then the non-parameterized is easy */
1571 #if defined(set_bottom_margin_parm) && defined(set_bottom_margin)
1572     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1573 #endif
1574 #if defined(set_left_margin_parm) && defined(set_left_margin)
1575     ANDMISSING(set_left_margin_parm, set_left_margin);
1576 #endif
1577 #if defined(set_right_margin_parm) && defined(set_right_margin)
1578     ANDMISSING(set_right_margin_parm, set_right_margin);
1579 #endif
1580 #if defined(set_top_margin_parm) && defined(set_top_margin)
1581     ANDMISSING(set_top_margin_parm, set_top_margin);
1582 #endif
1583
1584 #if defined(parm_down_micro) && defined(micro_down)
1585     ANDMISSING(parm_down_micro, micro_down);
1586 #endif
1587 #if defined(parm_left_micro) && defined(micro_left)
1588     ANDMISSING(parm_left_micro, micro_left);
1589 #endif
1590 #if defined(parm_right_micro) && defined(micro_right)
1591     ANDMISSING(parm_right_micro, micro_right);
1592 #endif
1593 #if defined(parm_up_micro) && defined(micro_up)
1594     ANDMISSING(parm_up_micro, micro_up);
1595 #endif
1596 }
1597
1598 static bool
1599 uses_SGR_39_49(const char *value)
1600 {
1601     return (strstr(value, "39;49") != 0
1602             || strstr(value, "49;39") != 0);
1603 }
1604
1605 /*
1606  * Check consistency of termcap extensions related to "screen".
1607  */
1608 static void
1609 check_screen(TERMTYPE2 *tp)
1610 {
1611 #if NCURSES_XNAMES
1612     if (_nc_user_definable) {
1613         int have_XT = tigetflag("XT");
1614         int have_XM = tigetflag("XM");
1615         int have_bce = back_color_erase;
1616         bool have_kmouse = FALSE;
1617         bool use_sgr_39_49 = FALSE;
1618         char *name = _nc_first_name(tp->term_names);
1619
1620         if (!VALID_BOOLEAN(have_bce)) {
1621             have_bce = FALSE;
1622         }
1623         if (!VALID_BOOLEAN(have_XM)) {
1624             have_XM = FALSE;
1625         }
1626         if (!VALID_BOOLEAN(have_XT)) {
1627             have_XT = FALSE;
1628         }
1629         if (VALID_STRING(key_mouse)) {
1630             have_kmouse = !strcmp("\033[M", key_mouse);
1631         }
1632         if (VALID_STRING(orig_colors)) {
1633             use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1634         } else if (VALID_STRING(orig_pair)) {
1635             use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1636         }
1637
1638         if (have_XM && have_XT) {
1639             _nc_warning("Screen's XT capability conflicts with XM");
1640         } else if (have_XT
1641                    && strstr(name, "screen") != 0
1642                    && strchr(name, '.') != 0) {
1643             _nc_warning("Screen's \"screen\" entries should not have XT set");
1644         } else if (have_XT) {
1645             if (!have_kmouse && have_bce) {
1646                 if (VALID_STRING(key_mouse)) {
1647                     _nc_warning("Value of kmous inconsistent with screen's usage");
1648                 } else {
1649                     _nc_warning("Expected kmous capability with XT");
1650                 }
1651             }
1652             if (!have_bce && max_colors > 0)
1653                 _nc_warning("Expected bce capability with XT");
1654             if (!use_sgr_39_49 && have_bce && max_colors > 0)
1655                 _nc_warning("Expected orig_colors capability with XT to have 39/49 parameters");
1656             if (VALID_STRING(to_status_line))
1657                 _nc_warning("\"tsl\" capability is redundant, given XT");
1658         } else {
1659             if (have_kmouse && !have_XM)
1660                 _nc_warning("Expected XT to be set, given kmous");
1661         }
1662     }
1663 #endif
1664 }
1665
1666 /*
1667  * Returns the expected number of parameters for the given capability.
1668  */
1669 static int
1670 expected_params(const char *name)
1671 {
1672 #define DATA(name,count) { { name }, count }
1673     /* *INDENT-OFF* */
1674     static const struct {
1675         const char name[9];
1676         int count;
1677     } table[] = {
1678         DATA( "S0",             1 ),    /* 'screen' extension */
1679         DATA( "birep",          2 ),
1680         DATA( "chr",            1 ),
1681         DATA( "colornm",        1 ),
1682         DATA( "cpi",            1 ),
1683         DATA( "csnm",           1 ),
1684         DATA( "csr",            2 ),
1685         DATA( "cub",            1 ),
1686         DATA( "cud",            1 ),
1687         DATA( "cuf",            1 ),
1688         DATA( "cup",            2 ),
1689         DATA( "cuu",            1 ),
1690         DATA( "cvr",            1 ),
1691         DATA( "cwin",           5 ),
1692         DATA( "dch",            1 ),
1693         DATA( "defc",           3 ),
1694         DATA( "dial",           1 ),
1695         DATA( "dispc",          1 ),
1696         DATA( "dl",             1 ),
1697         DATA( "ech",            1 ),
1698         DATA( "getm",           1 ),
1699         DATA( "hpa",            1 ),
1700         DATA( "ich",            1 ),
1701         DATA( "il",             1 ),
1702         DATA( "indn",           1 ),
1703         DATA( "initc",          4 ),
1704         DATA( "initp",          7 ),
1705         DATA( "lpi",            1 ),
1706         DATA( "mc5p",           1 ),
1707         DATA( "mrcup",          2 ),
1708         DATA( "mvpa",           1 ),
1709         DATA( "pfkey",          2 ),
1710         DATA( "pfloc",          2 ),
1711         DATA( "pfx",            2 ),
1712         DATA( "pfxl",           3 ),
1713         DATA( "pln",            2 ),
1714         DATA( "qdial",          1 ),
1715         DATA( "rcsd",           1 ),
1716         DATA( "rep",            2 ),
1717         DATA( "rin",            1 ),
1718         DATA( "sclk",           3 ),
1719         DATA( "scp",            1 ),
1720         DATA( "scs",            1 ),
1721         DATA( "scsd",           2 ),
1722         DATA( "setab",          1 ),
1723         DATA( "setaf",          1 ),
1724         DATA( "setb",           1 ),
1725         DATA( "setcolor",       1 ),
1726         DATA( "setf",           1 ),
1727         DATA( "sgr",            9 ),
1728         DATA( "sgr1",           6 ),
1729         DATA( "slength",        1 ),
1730         DATA( "slines",         1 ),
1731         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1732         DATA( "smglp",          1 ),
1733         DATA( "smglr",          2 ),
1734         DATA( "smgrp",          1 ),
1735         DATA( "smgtb",          2 ),
1736         DATA( "smgtp",          1 ),
1737         DATA( "tsl",            1 ),
1738         DATA( "u6",             -1 ),
1739         DATA( "vpa",            1 ),
1740         DATA( "wind",           4 ),
1741         DATA( "wingo",          1 ),
1742     };
1743     /* *INDENT-ON* */
1744
1745 #undef DATA
1746
1747     unsigned n;
1748     int result = 0;             /* function-keys, etc., use none */
1749
1750     for (n = 0; n < SIZEOF(table); n++) {
1751         if (!strcmp(name, table[n].name)) {
1752             result = table[n].count;
1753             break;
1754         }
1755     }
1756
1757     return result;
1758 }
1759
1760 static int
1761 is_user_capability(const char *name)
1762 {
1763     int result = 0;
1764     if (name[0] == 'u' &&
1765         (name[1] >= '0' && name[1] <= '9') &&
1766         name[2] == '\0')
1767         result = 1;
1768     return result;
1769 }
1770
1771 /*
1772  * Make a quick sanity check for the parameters which are used in the given
1773  * strings.  If there are no "%p" tokens, then there should be no other "%"
1774  * markers.
1775  */
1776 static void
1777 check_params(TERMTYPE2 *tp, const char *name, char *value, int extended)
1778 {
1779     int expected = expected_params(name);
1780     int actual = 0;
1781     int n;
1782     bool params[NUM_PARM];
1783     char *s = value;
1784
1785 #ifdef set_top_margin_parm
1786     if (!strcmp(name, "smgbp")
1787         && set_top_margin_parm == 0)
1788         expected = 2;
1789 #endif
1790
1791     for (n = 0; n < NUM_PARM; n++)
1792         params[n] = FALSE;
1793
1794     while (*s != 0) {
1795         if (*s == '%') {
1796             if (*++s == '\0') {
1797                 _nc_warning("expected character after %% in %s", name);
1798                 break;
1799             } else if (*s == 'p') {
1800                 if (*++s == '\0' || !isdigit((int) *s)) {
1801                     _nc_warning("expected digit after %%p in %s", name);
1802                     return;
1803                 } else {
1804                     n = (*s - '0');
1805                     if (n > actual)
1806                         actual = n;
1807                     params[n] = TRUE;
1808                 }
1809             }
1810         }
1811         s++;
1812     }
1813
1814     if (extended) {
1815         if (actual > 0) {
1816             _nc_warning("extended %s capability has %d parameters",
1817                         name, actual);
1818             expected = actual;
1819         }
1820     }
1821
1822     if (params[0]) {
1823         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1824     }
1825     if (value == set_attributes || expected < 0) {
1826         ;
1827     } else if (expected != actual) {
1828         _nc_warning("%s uses %d parameters, expected %d", name,
1829                     actual, expected);
1830         for (n = 1; n < actual; n++) {
1831             if (!params[n])
1832                 _nc_warning("%s omits parameter %d", name, n);
1833         }
1834     }
1835
1836     /*
1837      * Counting "%p" markers does not account for termcap expressions which
1838      * may not have been fully translated.  Also, tparm does its own analysis.
1839      * Report differences here.
1840      */
1841     if (actual >= 0) {
1842         char *p_is_s[NUM_PARM];
1843         int popcount;
1844         int analyzed = _nc_tparm_analyze(value, p_is_s, &popcount);
1845         if (analyzed < popcount) {
1846             analyzed = popcount;
1847         }
1848         if (actual != analyzed && expected != analyzed) {
1849             if (is_user_capability(name)) {
1850                 _nc_warning("tparm will use %d parameters for %s",
1851                             analyzed, name);
1852             } else {
1853                 _nc_warning("tparm analyzed %d parameters for %s, expected %d",
1854                             analyzed, name, actual);
1855             }
1856         }
1857     }
1858 }
1859
1860 static bool
1861 line_capability(const char *name)
1862 {
1863     bool result = FALSE;
1864     static const char *table[] =
1865     {
1866         "csr",                  /* change_scroll_region          */
1867         "clear",                /* clear_screen                  */
1868         "ed",                   /* clr_eos                       */
1869         "cwin",                 /* create_window                 */
1870         "cup",                  /* cursor_address                */
1871         "cud1",                 /* cursor_down                   */
1872         "home",                 /* cursor_home                   */
1873         "mrcup",                /* cursor_mem_address            */
1874         "ll",                   /* cursor_to_ll                  */
1875         "cuu1",                 /* cursor_up                     */
1876         "dl1",                  /* delete_line                   */
1877         "hd",                   /* down_half_line                */
1878         "flash",                /* flash_screen                  */
1879         "ff",                   /* form_feed                     */
1880         "il1",                  /* insert_line                   */
1881         "nel",                  /* newline                       */
1882         "dl",                   /* parm_delete_line              */
1883         "cud",                  /* parm_down_cursor              */
1884         "indn",                 /* parm_index                    */
1885         "il",                   /* parm_insert_line              */
1886         "rin",                  /* parm_rindex                   */
1887         "cuu",                  /* parm_up_cursor                */
1888         "mc0",                  /* print_screen                  */
1889         "vpa",                  /* row_address                   */
1890         "ind",                  /* scroll_forward                */
1891         "ri",                   /* scroll_reverse                */
1892         "hu",                   /* up_half_line                  */
1893     };
1894     size_t n;
1895     for (n = 0; n < SIZEOF(table); ++n) {
1896         if (!strcmp(name, table[n])) {
1897             result = TRUE;
1898             break;
1899         }
1900     }
1901     return result;
1902 }
1903
1904 /*
1905  * Check for DEC VT100 private mode for reverse video.
1906  */
1907 static const char *
1908 skip_DECSCNM(const char *value, int *flag)
1909 {
1910     *flag = -1;
1911     if (value != 0) {
1912         int skip = csi_length(value);
1913         if (skip > 0 &&
1914             value[skip++] == '?' &&
1915             value[skip++] == '5') {
1916             if (value[skip] == 'h') {
1917                 *flag = 1;
1918             } else if (value[skip] == 'l') {
1919                 *flag = 0;
1920             }
1921             value += skip + 1;
1922         }
1923     }
1924     return value;
1925 }
1926
1927 static void
1928 check_delays(const char *name, const char *value)
1929 {
1930     const char *p, *q;
1931     const char *first = 0;
1932     const char *last = 0;
1933
1934     for (p = value; *p != '\0'; ++p) {
1935         if (p[0] == '$' && p[1] == '<') {
1936             const char *base = p + 2;
1937             const char *mark = 0;
1938             bool maybe = TRUE;
1939             bool mixed = FALSE;
1940             int proportional = 0;
1941             int mandatory = 0;
1942
1943             first = p;
1944
1945             for (q = base; *q != '\0'; ++q) {
1946                 if (*q == '>') {
1947                     if (mark == 0)
1948                         mark = q;
1949                     break;
1950                 } else if (*q == '*' || *q == '/') {
1951                     if (*q == '*')
1952                         ++proportional;
1953                     if (*q == '/')
1954                         ++mandatory;
1955                     if (mark == 0)
1956                         mark = q;
1957                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
1958                     maybe = FALSE;
1959                     break;
1960                 } else if (proportional || mandatory) {
1961                     mixed = TRUE;
1962                 }
1963             }
1964             last = *q ? (q + 1) : q;
1965             if (*q == '\0') {
1966                 maybe = FALSE;  /* just an isolated "$<" */
1967             } else if (maybe) {
1968                 float check_f;
1969                 char check_c;
1970                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
1971                 if ((rc != 2) || (check_c != *mark) || mixed) {
1972                     _nc_warning("syntax error in %s delay '%.*s'", name,
1973                                 (int) (q - base), base);
1974                 } else if (*name == 'k') {
1975                     _nc_warning("function-key %s has delay", name);
1976                 } else if (proportional && !line_capability(name)) {
1977                     _nc_warning("non-line capability using proportional delay: %s", name);
1978                 }
1979             } else {
1980                 p = q - 1;      /* restart scan */
1981             }
1982         }
1983     }
1984
1985     if (!strcmp(name, "flash") ||
1986         !strcmp(name, "beep")) {
1987
1988         if (first != 0) {
1989             if (first == value || *last == 0) {
1990                 /*
1991                  * Delay is on one end or the other.
1992                  */
1993                 _nc_warning("expected delay embedded within %s", name);
1994             }
1995         } else {
1996             int flag;
1997
1998             /*
1999              * Check for missing delay when using VT100 reverse-video.
2000              * A real VT100 might not need this, but terminal emulators do.
2001              */
2002             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
2003                 flag > 0 &&
2004                 (q = skip_DECSCNM(p, &flag)) != 0 &&
2005                 flag == 0) {
2006                 _nc_warning("expected a delay in %s", name);
2007             }
2008         }
2009     }
2010 }
2011
2012 static char *
2013 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
2014 {
2015     int k;
2016     int ignored;
2017     long numbers[1 + NUM_PARM];
2018     char *strings[1 + NUM_PARM];
2019     char *p_is_s[NUM_PARM];
2020     char *result;
2021     char blob[NUM_PARM * 10];
2022     char *next = blob;
2023
2024     *next++ = '\0';
2025     for (k = 1; k <= NUM_PARM; k++) {
2026         numbers[k] = count;
2027         _nc_SPRINTF(next,
2028                     _nc_SLIMIT(sizeof(blob) - (size_t) (next - blob))
2029                     "XYZ%d", count);
2030         strings[k] = next;
2031         next += strlen(next) + 1;
2032     }
2033
2034     switch (tparm_type(name)) {
2035     case Num_Str:
2036         result = TPARM_2(value, numbers[1], strings[2]);
2037         break;
2038     case Num_Str_Str:
2039         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
2040         break;
2041     case Numbers:
2042     default:
2043         (void) _nc_tparm_analyze(value, p_is_s, &ignored);
2044 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
2045         result = TPARM_9(value,
2046                          myParam(1),
2047                          myParam(2),
2048                          myParam(3),
2049                          myParam(4),
2050                          myParam(5),
2051                          myParam(6),
2052                          myParam(7),
2053                          myParam(8),
2054                          myParam(9));
2055         break;
2056     }
2057     return result;
2058 }
2059
2060 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
2061
2062 static const char *
2063 parse_delay_value(const char *src, double *delays, int *always)
2064 {
2065     int star = 0;
2066
2067     *delays = 0.0;
2068     if (always)
2069         *always = 0;
2070
2071     while (isdigit(UChar(*src))) {
2072         (*delays) = (*delays) * 10 + (*src++ - '0');
2073     }
2074     if (*src == '.') {
2075         int gotdot = 1;
2076
2077         ++src;
2078         while (isdigit(UChar(*src))) {
2079             gotdot *= 10;
2080             (*delays) += (*src++ - '0') / gotdot;
2081         }
2082     }
2083     while (*src == '*' || *src == '/') {
2084         if (always == 0 && *src == '/')
2085             break;
2086         if (*src++ == '*') {
2087             star = 1;
2088         } else {
2089             *always = 1;
2090         }
2091     }
2092     if (star)
2093         *delays = -(*delays);
2094     return src;
2095 }
2096
2097 static const char *
2098 parse_ti_delay(const char *ti, double *delays)
2099 {
2100     *delays = 0.0;
2101     while (*ti != '\0') {
2102         if (*ti == '\\') {
2103             ++ti;
2104         }
2105         if (ti[0] == '$'
2106             && ti[1] == '<'
2107             && IsDelay(UChar(ti[2]))) {
2108             int ignored;
2109             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2110             if (*last == '>') {
2111                 ti = last;
2112             }
2113         } else {
2114             ++ti;
2115         }
2116     }
2117     return ti;
2118 }
2119
2120 static const char *
2121 parse_tc_delay(const char *tc, double *delays)
2122 {
2123     return parse_delay_value(tc, delays, (int *) 0);
2124 }
2125
2126 /*
2127  * Compare terminfo- and termcap-strings, factoring out delays.
2128  */
2129 static bool
2130 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2131 {
2132     bool same = TRUE;
2133     double ti_delay = 0.0;
2134     double tc_delay = 0.0;
2135     const char *ti_last;
2136
2137     *embedded = FALSE;
2138     ti_last = parse_ti_delay(ti, &ti_delay);
2139     tc = parse_tc_delay(tc, &tc_delay);
2140
2141     while ((ti < ti_last) && *tc) {
2142         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2143             ++ti;
2144             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2145                 ti += 1;
2146                 tc += 4;
2147                 continue;
2148             }
2149         } else if (ti[0] == '$' && ti[1] == '<') {
2150             double no_delay;
2151             const char *ss = parse_ti_delay(ti, &no_delay);
2152             if (ss != ti) {
2153                 *embedded = TRUE;
2154                 ti = ss;
2155                 continue;
2156             }
2157         }
2158         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2159             ++tc;
2160         }
2161         if (*ti++ != *tc++) {
2162             same = FALSE;
2163             break;
2164         }
2165     }
2166
2167     if (*embedded) {
2168         if (same) {
2169             same = FALSE;
2170         } else {
2171             *embedded = FALSE;  /* report only one problem */
2172         }
2173     }
2174
2175     return same;
2176 }
2177
2178 /*
2179  * Check terminfo to termcap translation.
2180  */
2181 static void
2182 check_infotocap(TERMTYPE2 *tp, int i, const char *value)
2183 {
2184     const char *name = ExtStrname(tp, i, strnames);
2185     int params = (((i < (int) SIZEOF(parametrized)) &&
2186                    (i < STRCOUNT))
2187                   ? parametrized[i]
2188                   : ((*value == 'k')
2189                      ? 0
2190                      : has_params(value)));
2191     int to_char = 0;
2192     char *ti_value;
2193     char *tc_value;
2194     bool embedded;
2195
2196     if ((ti_value = _nc_tic_expand(value, TRUE, to_char)) == ABSENT_STRING) {
2197         _nc_warning("tic-expansion of %s failed", name);
2198     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2199         _nc_warning("tic-conversion of %s failed", name);
2200     } else if (params > 0) {
2201         int limit = 5;
2202         int count;
2203         bool first = TRUE;
2204
2205         if (!strcmp(name, "setf")
2206             || !strcmp(name, "setb")
2207             || !strcmp(name, "setaf")
2208             || !strcmp(name, "setab")) {
2209             limit = max_colors;
2210         }
2211         for (count = 0; count < limit; ++count) {
2212             char *ti_check = check_1_infotocap(name, ti_value, count);
2213             char *tc_check = check_1_infotocap(name, tc_value, count);
2214
2215             if (strcmp(ti_check, tc_check)) {
2216                 if (first) {
2217                     fprintf(stderr, "check_infotocap(%s)\n", name);
2218                     fprintf(stderr, "...ti '%s'\n", ti_value);
2219                     fprintf(stderr, "...tc '%s'\n", tc_value);
2220                     first = FALSE;
2221                 }
2222                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2223                             name, count, ti_check, tc_check);
2224             }
2225         }
2226     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2227         if (embedded) {
2228             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2229         } else {
2230             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2231                         name, ti_value, tc_value);
2232         }
2233     }
2234 }
2235
2236 static char *
2237 skip_delay(char *s)
2238 {
2239     while (*s == '/' || isdigit(UChar(*s)))
2240         ++s;
2241     return s;
2242 }
2243
2244 /*
2245  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2246  * the latter may have a worst-case delay on the end.
2247  */
2248 static char *
2249 ignore_delays(char *s)
2250 {
2251     int delaying = 0;
2252
2253     do {
2254         switch (*s) {
2255         case '$':
2256             if (delaying == 0)
2257                 delaying = 1;
2258             break;
2259         case '<':
2260             if (delaying == 1)
2261                 delaying = 2;
2262             break;
2263         case '\0':
2264             delaying = 0;
2265             break;
2266         default:
2267             if (delaying) {
2268                 s = skip_delay(s);
2269                 if (*s == '>')
2270                     ++s;
2271                 delaying = 0;
2272             }
2273             break;
2274         }
2275         if (delaying)
2276             ++s;
2277     } while (delaying);
2278     return s;
2279 }
2280
2281 #define DATA(name) { #name }
2282 static const char sgr_names[][11] =
2283 {
2284     DATA(none),
2285     DATA(standout),
2286     DATA(underline),
2287     DATA(reverse),
2288     DATA(blink),
2289     DATA(dim),
2290     DATA(bold),
2291     DATA(invis),
2292     DATA(protect),
2293     DATA(altcharset),
2294     ""
2295 };
2296 #undef DATA
2297
2298 /*
2299  * An sgr string may contain several settings other than the one we're
2300  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2301  * "whatever" is contained in the sgr string, that is close enough for our
2302  * sanity check.
2303  */
2304 static bool
2305 similar_sgr(int num, char *a, char *b)
2306 {
2307     char *base_a = a;
2308     char *base_b = b;
2309     int delaying = 0;
2310
2311     while (*b != 0) {
2312         while (*a != *b) {
2313             if (*a == 0) {
2314                 if (num < 0) {
2315                     ;
2316                 } else if (b[0] == '$'
2317                            && b[1] == '<') {
2318                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
2319                 } else {
2320                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2321                                 sgr_names[num], _nc_visbuf2(1, base_a),
2322                                 _nc_visbuf2(2, base_b),
2323                                 _nc_visbuf2(3, b));
2324                 }
2325                 return FALSE;
2326             } else if (delaying) {
2327                 a = skip_delay(a);
2328                 b = skip_delay(b);
2329             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2330                 b++;
2331             } else {
2332                 a++;
2333             }
2334         }
2335         switch (*a) {
2336         case '$':
2337             if (delaying == 0)
2338                 delaying = 1;
2339             break;
2340         case '<':
2341             if (delaying == 1)
2342                 delaying = 2;
2343             break;
2344         default:
2345             delaying = 0;
2346             break;
2347         }
2348         a++;
2349         b++;
2350     }
2351     /* ignore delays on the end of the string */
2352     a = ignore_delays(a);
2353     return ((num != 0) || (*a == 0));
2354 }
2355
2356 static char *
2357 check_sgr(TERMTYPE2 *tp, char *zero, int num, char *cap, const char *name)
2358 {
2359     char *test;
2360
2361     _nc_tparm_err = 0;
2362     test = TPARM_9(set_attributes,
2363                    num == 1,
2364                    num == 2,
2365                    num == 3,
2366                    num == 4,
2367                    num == 5,
2368                    num == 6,
2369                    num == 7,
2370                    num == 8,
2371                    num == 9);
2372     if (test != 0) {
2373         if (PRESENT(cap)) {
2374             if (!similar_sgr(num, test, cap)) {
2375                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2376                             name, num,
2377                             name, _nc_visbuf2(1, cap),
2378                             num, _nc_visbuf2(2, test));
2379             }
2380         } else if (_nc_capcmp(test, zero)) {
2381             _nc_warning("sgr(%d) present, but not %s", num, name);
2382         }
2383     } else if (PRESENT(cap)) {
2384         _nc_warning("sgr(%d) missing, but %s present", num, name);
2385     }
2386     if (_nc_tparm_err)
2387         _nc_warning("stack error in sgr(%d) string", num);
2388     return test;
2389 }
2390
2391 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2392
2393 #ifdef TRACE
2394 /*
2395  * If tic is compiled with TRACE, we'll be able to see the output from the
2396  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2397  * the standard error.  Use this function to make it simpler to follow the
2398  * resulting debug traces.
2399  */
2400 static void
2401 show_where(unsigned level)
2402 {
2403     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2404         char my_name[MAX_NAME_SIZE];
2405         _nc_get_type(my_name);
2406         _tracef("\"%s\", line %d, '%s'",
2407                 _nc_get_source(),
2408                 _nc_curr_line, my_name);
2409     }
2410 }
2411
2412 #else
2413 #define show_where(level)       /* nothing */
2414 #endif
2415
2416 typedef struct {
2417     int keycode;
2418     const char *name;
2419     const char *value;
2420 } NAME_VALUE;
2421
2422 static NAME_VALUE *
2423 get_fkey_list(TERMTYPE2 *tp)
2424 {
2425     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2426     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2427     int used = 0;
2428     unsigned j;
2429
2430     if (result == 0)
2431         failed("get_fkey_list");
2432
2433     for (j = 0; all_fkeys[j].code; j++) {
2434         char *a = tp->Strings[all_fkeys[j].offset];
2435         if (VALID_STRING(a)) {
2436             result[used].keycode = (int) all_fkeys[j].code;
2437             result[used].name = strnames[all_fkeys[j].offset];
2438             result[used].value = a;
2439             ++used;
2440         }
2441     }
2442 #if NCURSES_XNAMES
2443     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2444         const char *name = ExtStrname(tp, (int) j, strnames);
2445         if (*name == 'k') {
2446             result[used].keycode = -1;
2447             result[used].name = name;
2448             result[used].value = tp->Strings[j];
2449             ++used;
2450         }
2451     }
2452 #endif
2453     result[used].keycode = 0;
2454     return result;
2455 }
2456
2457 static void
2458 show_fkey_name(NAME_VALUE * data)
2459 {
2460     if (data->keycode > 0) {
2461         fprintf(stderr, " %s", keyname(data->keycode));
2462         fprintf(stderr, " (capability \"%s\")", data->name);
2463     } else {
2464         fprintf(stderr, " capability \"%s\"", data->name);
2465     }
2466 }
2467
2468 /*
2469  * A terminal entry may contain more than one keycode assigned to a given
2470  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2471  * last one assigned).
2472  */
2473 static void
2474 check_conflict(TERMTYPE2 *tp)
2475 {
2476     bool conflict = FALSE;
2477     unsigned j, k;
2478
2479     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2480         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2481         NAME_VALUE *given = get_fkey_list(tp);
2482
2483         if (check == 0)
2484             failed("check_conflict");
2485
2486         for (j = 0; given[j].keycode; ++j) {
2487             const char *a = given[j].value;
2488             bool first = TRUE;
2489
2490             if (!VALID_STRING(a))
2491                 continue;
2492
2493             for (k = j + 1; given[k].keycode; k++) {
2494                 const char *b = given[k].value;
2495
2496                 if (!VALID_STRING(b))
2497                     continue;
2498                 if (check[k])
2499                     continue;
2500
2501                 if (!_nc_capcmp(a, b)) {
2502                     check[j] = 1;
2503                     check[k] = 1;
2504                     if (first) {
2505                         if (!conflict) {
2506                             _nc_warning("Conflicting key definitions (using the last)");
2507                             conflict = TRUE;
2508                         }
2509                         fprintf(stderr, "...");
2510                         show_fkey_name(given + j);
2511                         fprintf(stderr, " is the same as");
2512                         show_fkey_name(given + k);
2513                         first = FALSE;
2514                     } else {
2515                         fprintf(stderr, ", ");
2516                         show_fkey_name(given + k);
2517                     }
2518                 }
2519             }
2520             if (!first)
2521                 fprintf(stderr, "\n");
2522         }
2523 #if NCURSES_XNAMES
2524         if (using_extensions) {
2525             /* *INDENT-OFF* */
2526             static struct {
2527                 const char *xcurses;
2528                 const char *shifted;
2529             } table[] = {
2530                 { "kDC",  NULL },
2531                 { "kDN",  "kind" },
2532                 { "kEND", NULL },
2533                 { "kHOM", NULL },
2534                 { "kLFT", NULL },
2535                 { "kNXT", NULL },
2536                 { "kPRV", NULL },
2537                 { "kRIT", NULL },
2538                 { "kUP",  "kri" },
2539                 { NULL,   NULL },
2540             };
2541             /* *INDENT-ON* */
2542
2543             /*
2544              * SVr4 curses defines the "xcurses" names listed above except for
2545              * the special cases in the "shifted" column.  When using these
2546              * names for xterm's extensions, that was confusing, and resulted
2547              * in adding extended capabilities with "2" (shift) suffix.  This
2548              * check warns about unnecessary use of extensions for this quirk.
2549              */
2550             for (j = 0; given[j].keycode; ++j) {
2551                 const char *find = given[j].name;
2552                 int value;
2553                 char ch;
2554
2555                 if (!VALID_STRING(given[j].value))
2556                     continue;
2557
2558                 for (k = 0; table[k].xcurses; ++k) {
2559                     const char *test = table[k].xcurses;
2560                     size_t size = strlen(test);
2561
2562                     if (!strncmp(find, test, size) && strcmp(find, test)) {
2563                         switch (sscanf(find + size, "%d%c", &value, &ch)) {
2564                         case 1:
2565                             if (value == 2) {
2566                                 _nc_warning("expected '%s' rather than '%s'",
2567                                             (table[k].shifted
2568                                              ? table[k].shifted
2569                                              : test), find);
2570                             } else if (value < 2 || value > 15) {
2571                                 _nc_warning("expected numeric 2..15 '%s'", find);
2572                             }
2573                             break;
2574                         default:
2575                             _nc_warning("expected numeric suffix for '%s'", find);
2576                             break;
2577                         }
2578                         break;
2579                     }
2580                 }
2581             }
2582         }
2583 #endif
2584         free(given);
2585         free(check);
2586     }
2587 }
2588
2589 /*
2590  * Exiting a video mode should not duplicate sgr0
2591  */
2592 static void
2593 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2594 {
2595     if (VALID_STRING(test) && (trimmed != 0)) {
2596         if (similar_sgr(-1, trimmed, test) ||
2597             similar_sgr(-1, untrimmed, test)) {
2598             _nc_warning("%s matches exit_attribute_mode", name);
2599         }
2600     }
2601 }
2602
2603 /*
2604  * Returns true if the string looks like a standard SGR string.
2605  */
2606 static bool
2607 is_sgr_string(char *value)
2608 {
2609     bool result = FALSE;
2610
2611     if (VALID_STRING(value)) {
2612         int skip = csi_length(value);
2613
2614         if (skip) {
2615             int ch;
2616
2617             result = TRUE;
2618             value += skip;
2619             while ((ch = UChar(*value++)) != '\0') {
2620                 if (isdigit(ch) || ch == ';') {
2621                     ;
2622                 } else if (ch == 'm' && *value == '\0') {
2623                     ;
2624                 } else {
2625                     result = FALSE;
2626                     break;
2627                 }
2628             }
2629         }
2630     }
2631     return result;
2632 }
2633
2634 /*
2635  * Check if the given capability contains a given SGR attribute.
2636  */
2637 static void
2638 check_sgr_param(TERMTYPE2 *tp, int code, const char *name, char *value)
2639 {
2640     if (VALID_STRING(value)) {
2641         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2642         char *test = tgoto(value, 0, 0);
2643         if (is_sgr_string(test)) {
2644             int param = 0;
2645             int count = 0;
2646             int skips = 0;
2647             int color = (value == set_a_foreground ||
2648                          value == set_a_background ||
2649                          value == set_foreground ||
2650                          value == set_background);
2651             while (*test != 0) {
2652                 if (isdigit(UChar(*test))) {
2653                     param = 10 * param + (*test - '0');
2654                     ++count;
2655                 } else {
2656                     if (count) {
2657                         /*
2658                          * Avoid unnecessary warning for xterm 256color codes.
2659                          */
2660                         if (color && (param == 38 || param == 48))
2661                             skips = 3;
2662                         if ((skips-- <= 0) && (param == code))
2663                             break;
2664                     }
2665                     count = 0;
2666                     param = 0;
2667                 }
2668                 ++test;
2669             }
2670             if (count != 0 && param == code) {
2671                 if (code == 0 ||
2672                     no_color_video < 0 ||
2673                     !(no_color_video & ncv)) {
2674                     _nc_warning("\"%s\" SGR-attribute used in %s",
2675                                 sgr_names[code],
2676                                 name);
2677                 }
2678             }
2679         }
2680     }
2681 }
2682
2683 /* other sanity-checks (things that we don't want in the normal
2684  * logic that reads a terminfo entry)
2685  */
2686 static void
2687 check_termtype(TERMTYPE2 *tp, bool literal)
2688 {
2689     unsigned j;
2690
2691     check_conflict(tp);
2692
2693     for_each_string(j, tp) {
2694         char *a = tp->Strings[j];
2695         if (VALID_STRING(a)) {
2696             const char *name = ExtStrname(tp, (int) j, strnames);
2697             /*
2698              * If we expect parameters, or if there might be parameters,
2699              * check for consistent number of parameters.
2700              */
2701             if (j >= SIZEOF(parametrized) ||
2702                 is_user_capability(name) ||
2703                 parametrized[j] > 0) {
2704                 check_params(tp, name, a, (j >= STRCOUNT));
2705             }
2706             check_delays(ExtStrname(tp, (int) j, strnames), a);
2707             if (capdump) {
2708                 check_infotocap(tp, (int) j, a);
2709             }
2710         }
2711     }
2712
2713     check_acs(tp);
2714     check_colors(tp);
2715     check_cursor(tp);
2716     check_keypad(tp);
2717     check_printer(tp);
2718     check_screen(tp);
2719
2720     /*
2721      * These may be mismatched because the terminal description relies on
2722      * restoring the cursor visibility by resetting it.
2723      */
2724     ANDMISSING(cursor_invisible, cursor_normal);
2725     ANDMISSING(cursor_visible, cursor_normal);
2726
2727     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
2728         && !_nc_capcmp(cursor_visible, cursor_normal))
2729         _nc_warning("cursor_visible is same as cursor_normal");
2730
2731     /*
2732      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
2733      * given, because the cursor position after the scrolling operation is
2734      * performed is undefined.
2735      */
2736     ANDMISSING(change_scroll_region, save_cursor);
2737     ANDMISSING(change_scroll_region, restore_cursor);
2738
2739     /*
2740      * If we can clear tabs, we should be able to initialize them.
2741      */
2742     ANDMISSING(clear_all_tabs, set_tab);
2743
2744     if (PRESENT(set_attributes)) {
2745         char *zero = 0;
2746
2747         _nc_tparm_err = 0;
2748         if (PRESENT(exit_attribute_mode)) {
2749             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
2750         } else {
2751             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
2752         }
2753         if (_nc_tparm_err)
2754             _nc_warning("stack error in sgr(0) string");
2755
2756         if (zero != 0) {
2757             CHECK_SGR(1, enter_standout_mode);
2758             CHECK_SGR(2, enter_underline_mode);
2759             CHECK_SGR(3, enter_reverse_mode);
2760             CHECK_SGR(4, enter_blink_mode);
2761             CHECK_SGR(5, enter_dim_mode);
2762             CHECK_SGR(6, enter_bold_mode);
2763             CHECK_SGR(7, enter_secure_mode);
2764             CHECK_SGR(8, enter_protected_mode);
2765             CHECK_SGR(9, enter_alt_charset_mode);
2766             free(zero);
2767         } else {
2768             _nc_warning("sgr(0) did not return a value");
2769         }
2770     } else if (PRESENT(exit_attribute_mode) &&
2771                set_attributes != CANCELLED_STRING) {
2772         if (_nc_syntax == SYN_TERMINFO)
2773             _nc_warning("missing sgr string");
2774     }
2775 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
2776     if (PRESENT(exit_attribute_mode)) {
2777         char *check_sgr0 = _nc_trim_sgr0(tp);
2778
2779         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
2780             _nc_warning("trimmed sgr0 is empty");
2781         } else {
2782             show_where(2);
2783             if (check_sgr0 != exit_attribute_mode) {
2784                 DEBUG(2,
2785                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
2786                        _nc_visbuf2(1, exit_attribute_mode),
2787                        _nc_visbuf2(2, check_sgr0)));
2788             } else {
2789                 DEBUG(2,
2790                       ("will not trim sgr0\n\toriginal sgr0=%s",
2791                        _nc_visbuf(exit_attribute_mode)));
2792             }
2793         }
2794 #if defined(exit_italics_mode)
2795         CHECK_SGR0(exit_italics_mode);
2796 #endif
2797         CHECK_SGR0(exit_standout_mode);
2798         CHECK_SGR0(exit_underline_mode);
2799         if (check_sgr0 != exit_attribute_mode) {
2800             free(check_sgr0);
2801         }
2802     }
2803 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
2804     for (j = 0; *sgr_names[j] != '\0'; ++j) {
2805         CHECK_SGR_PARAM(j, set_a_foreground);
2806         CHECK_SGR_PARAM(j, set_a_background);
2807         CHECK_SGR_PARAM(j, set_foreground);
2808         CHECK_SGR_PARAM(j, set_background);
2809     }
2810 #ifdef TRACE
2811     show_where(2);
2812     if (!auto_right_margin) {
2813         DEBUG(2,
2814               ("can write to lower-right directly"));
2815     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
2816         DEBUG(2,
2817               ("can write to lower-right by suppressing automargin"));
2818     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
2819                || PRESENT(insert_character) || PRESENT(parm_ich)) {
2820         DEBUG(2,
2821               ("can write to lower-right by using inserts"));
2822     } else {
2823         DEBUG(2,
2824               ("cannot write to lower-right"));
2825     }
2826 #endif
2827
2828     /*
2829      * Some standard applications (e.g., vi) and some non-curses
2830      * applications (e.g., jove) get confused if we have both ich1 and
2831      * smir/rmir.  Let's be nice and warn about that, too, even though
2832      * ncurses handles it.
2833      */
2834     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
2835         && PRESENT(parm_ich)) {
2836         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
2837     }
2838
2839     /*
2840      * Finally, do the non-verbose checks
2841      */
2842     if (save_check_termtype != 0)
2843         save_check_termtype(tp, literal);
2844 }