]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/tic.c
478da6c472a22ada8392fbe9ec3735ad52aeee7a
[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.248 2017/12/16 23:05:21 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 int
678 main(int argc, char *argv[])
679 {
680     char my_tmpname[PATH_MAX];
681     char my_altfile[PATH_MAX];
682     int v_opt = -1;
683     unsigned debug_level;
684     int smart_defaults = TRUE;
685     char *termcap;
686     ENTRY *qp;
687
688     int this_opt, last_opt = '?';
689
690     int outform = F_TERMINFO;   /* output format */
691     int sortmode = S_TERMINFO;  /* sort_mode */
692
693     int width = 60;
694     int height = 65535;
695     bool formatted = FALSE;     /* reformat complex strings? */
696     bool literal = FALSE;       /* suppress post-processing? */
697     int numbers = 0;            /* format "%'char'" to/from "%{number}" */
698     bool forceresolve = FALSE;  /* force resolution */
699     bool limited = TRUE;
700     char *tversion = (char *) NULL;
701     const char *source_file = "terminfo";
702     char *outdir = (char *) NULL;
703     bool check_only = FALSE;
704     bool suppress_untranslatable = FALSE;
705     int quickdump = 0;
706     bool quiet = FALSE;
707     bool wrap_strings = FALSE;
708
709     log_fp = stderr;
710
711     _nc_progname = _nc_rootname(argv[0]);
712     atexit(cleanup);
713
714     if ((infodump = same_program(_nc_progname, PROG_CAPTOINFO)) != FALSE) {
715         outform = F_TERMINFO;
716         sortmode = S_TERMINFO;
717     }
718     if ((capdump = same_program(_nc_progname, PROG_INFOTOCAP)) != FALSE) {
719         outform = F_TERMCAP;
720         sortmode = S_TERMCAP;
721     }
722 #if NCURSES_XNAMES
723     use_extended_names(FALSE);
724 #endif
725     _nc_strict_bsd = 0;
726
727     /*
728      * Processing arguments is a little complicated, since someone made a
729      * design decision to allow the numeric values for -w, -v options to
730      * be optional.
731      */
732     while ((this_opt = getopt(argc, argv,
733                               "0123456789CDIKLNQR:TUVWace:fGgo:qrstvwx")) != -1) {
734         if (isdigit(this_opt)) {
735             switch (last_opt) {
736             case 'Q':
737                 add_digit(&quickdump, this_opt);
738                 break;
739             case 'v':
740                 add_digit(&v_opt, this_opt);
741                 break;
742             case 'w':
743                 add_digit(&width, this_opt);
744                 break;
745             default:
746                 switch (this_opt) {
747                 case '0':
748                     last_opt = this_opt;
749                     width = 65535;
750                     height = 1;
751                     break;
752                 case '1':
753                     last_opt = this_opt;
754                     width = 0;
755                     break;
756                 default:
757                     usage();
758                 }
759             }
760             continue;
761         }
762         switch (this_opt) {
763         case 'K':
764             _nc_strict_bsd = 1;
765             /* the initial version of -K in 20110730 fell-thru here, but the
766              * same flag is useful when reading sources -TD
767              */
768             break;
769         case 'C':
770             capdump = TRUE;
771             outform = F_TERMCAP;
772             sortmode = S_TERMCAP;
773             break;
774         case 'D':
775             debug_level = VtoTrace(v_opt);
776             set_trace_level(debug_level);
777             show_databases(outdir);
778             ExitProgram(EXIT_SUCCESS);
779             break;
780         case 'I':
781             infodump = TRUE;
782             outform = F_TERMINFO;
783             sortmode = S_TERMINFO;
784             break;
785         case 'L':
786             infodump = TRUE;
787             outform = F_VARIABLE;
788             sortmode = S_VARIABLE;
789             break;
790         case 'N':
791             smart_defaults = FALSE;
792             literal = TRUE;
793             break;
794         case 'Q':
795             quickdump = 0;
796             break;
797         case 'R':
798             tversion = optarg;
799             break;
800         case 'T':
801             limited = FALSE;
802             break;
803         case 'U':
804             literal = TRUE;
805             break;
806         case 'V':
807             puts(curses_version());
808             ExitProgram(EXIT_SUCCESS);
809         case 'W':
810             wrap_strings = TRUE;
811             break;
812         case 'c':
813             check_only = TRUE;
814             break;
815         case 'e':
816             namelst = make_namelist(optarg);
817             break;
818         case 'f':
819             formatted = TRUE;
820             break;
821         case 'G':
822             numbers = 1;
823             break;
824         case 'g':
825             numbers = -1;
826             break;
827         case 'o':
828             outdir = optarg;
829             break;
830         case 'q':
831             quiet = TRUE;
832             break;
833         case 'r':
834             forceresolve = TRUE;
835             break;
836         case 's':
837             showsummary = TRUE;
838             break;
839         case 'v':
840             v_opt = 0;
841             break;
842         case 'w':
843             width = 0;
844             break;
845 #if NCURSES_XNAMES
846         case 't':
847             _nc_disable_period = FALSE;
848             suppress_untranslatable = TRUE;
849             break;
850         case 'a':
851             _nc_disable_period = TRUE;
852             /* FALLTHRU */
853         case 'x':
854             use_extended_names(TRUE);
855             using_extensions = TRUE;
856             break;
857 #endif
858         default:
859             usage();
860         }
861         last_opt = this_opt;
862     }
863
864     debug_level = VtoTrace(v_opt);
865     set_trace_level(debug_level);
866
867     if (_nc_tracing) {
868         save_check_termtype = _nc_check_termtype2;
869         _nc_check_termtype2 = check_termtype;
870     }
871 #if !HAVE_BIG_CORE
872     /*
873      * Aaargh! immedhook seriously hoses us!
874      *
875      * One problem with immedhook is it means we can't do -e.  Problem
876      * is that we can't guarantee that for each terminal listed, all the
877      * terminals it depends on will have been kept in core for reference
878      * resolution -- in fact it's certain the primitive types at the end
879      * of reference chains *won't* be in core unless they were explicitly
880      * in the select list themselves.
881      */
882     if (namelst && (!infodump && !capdump)) {
883         (void) fprintf(stderr,
884                        "%s: Sorry, -e can't be used without -I or -C\n",
885                        _nc_progname);
886         ExitProgram(EXIT_FAILURE);
887     }
888 #endif /* HAVE_BIG_CORE */
889
890     if (optind < argc) {
891         source_file = argv[optind++];
892         if (optind < argc) {
893             fprintf(stderr,
894                     "%s: Too many file names.  Usage:\n\t%s %s",
895                     _nc_progname,
896                     _nc_progname,
897                     usage_string);
898             ExitProgram(EXIT_FAILURE);
899         }
900     } else {
901         if (infodump == TRUE) {
902             /* captoinfo's no-argument case */
903             source_file = "/etc/termcap";
904             if ((termcap = getenv("TERMCAP")) != 0
905                 && (namelst = make_namelist(getenv("TERM"))) != 0) {
906                 if (access(termcap, F_OK) == 0) {
907                     /* file exists */
908                     source_file = termcap;
909                 } else {
910                     if ((tmp_fp = open_tempfile(my_tmpname)) != 0) {
911                         source_file = my_tmpname;
912                         fprintf(tmp_fp, "%s\n", termcap);
913                         fclose(tmp_fp);
914                         tmp_fp = open_input(source_file, (char *) 0);
915                         to_remove = source_file;
916                     } else {
917                         failed("tmpnam");
918                     }
919                 }
920             }
921         } else {
922             /* tic */
923             fprintf(stderr,
924                     "%s: File name needed.  Usage:\n\t%s %s",
925                     _nc_progname,
926                     _nc_progname,
927                     usage_string);
928             ExitProgram(EXIT_FAILURE);
929         }
930     }
931
932     if (tmp_fp == 0) {
933         tmp_fp = open_input(source_file, my_altfile);
934         if (!strcmp(source_file, "-")) {
935             source_file = STDIN_NAME;
936         }
937     }
938
939     if (infodump || check_only) {
940         dump_init(tversion,
941                   (smart_defaults
942                    ? outform
943                    : F_LITERAL),
944                   sortmode,
945                   wrap_strings, width, height,
946                   debug_level, formatted || check_only, check_only, quickdump);
947     } else if (capdump) {
948         dump_init(tversion,
949                   outform,
950                   sortmode,
951                   wrap_strings, width, height,
952                   debug_level, FALSE, FALSE, FALSE);
953     }
954
955     /* parse entries out of the source file */
956     _nc_set_source(source_file);
957 #if !HAVE_BIG_CORE
958     if (!(check_only || infodump || capdump))
959         _nc_set_writedir(outdir);
960 #endif /* HAVE_BIG_CORE */
961     _nc_read_entry_source(tmp_fp, (char *) NULL,
962                           !smart_defaults || literal, FALSE,
963                           ((check_only || infodump || capdump)
964                            ? NULLHOOK
965                            : immedhook));
966
967     /* do use resolution */
968     if (check_only || (!infodump && !capdump) || forceresolve) {
969         if (!_nc_resolve_uses2(TRUE, literal) && !check_only) {
970             ExitProgram(EXIT_FAILURE);
971         }
972     }
973
974     /* length check */
975     if (check_only && limited && (capdump || infodump)) {
976         for_entry_list(qp) {
977             if (matches(namelst, qp->tterm.term_names)) {
978                 int len = fmt_entry(&qp->tterm, NULL, FALSE, TRUE, infodump, numbers);
979
980                 if (len > (infodump ? MAX_TERMINFO_LENGTH : MAX_TERMCAP_LENGTH))
981                     (void) fprintf(stderr,
982                                    "%s: resolved %s entry is %d bytes long\n",
983                                    _nc_progname,
984                                    _nc_first_name(qp->tterm.term_names),
985                                    len);
986             }
987         }
988     }
989
990     /* write or dump all entries */
991     if (check_only) {
992         /* this is in case infotocap() generates warnings */
993         _nc_curr_col = _nc_curr_line = -1;
994
995         for_entry_list(qp) {
996             if (matches(namelst, qp->tterm.term_names)) {
997                 /* this is in case infotocap() generates warnings */
998                 _nc_set_type(_nc_first_name(qp->tterm.term_names));
999                 _nc_curr_line = (int) qp->startline;
1000                 repair_acsc(&qp->tterm);
1001                 dump_entry(&qp->tterm, suppress_untranslatable,
1002                            limited, numbers, NULL);
1003             }
1004         }
1005     } else {
1006         if (!infodump && !capdump) {
1007             _nc_set_writedir(outdir);
1008             for_entry_list(qp) {
1009                 if (matches(namelst, qp->tterm.term_names))
1010                     write_it(qp);
1011             }
1012         } else {
1013             /* this is in case infotocap() generates warnings */
1014             _nc_curr_col = _nc_curr_line = -1;
1015
1016             for_entry_list(qp) {
1017                 if (matches(namelst, qp->tterm.term_names)) {
1018                     long j = qp->cend - qp->cstart;
1019                     int len = 0;
1020
1021                     /* this is in case infotocap() generates warnings */
1022                     _nc_set_type(_nc_first_name(qp->tterm.term_names));
1023
1024                     if (!quiet) {
1025                         (void) fseek(tmp_fp, qp->cstart, SEEK_SET);
1026                         while (j-- > 0) {
1027                             if (infodump)
1028                                 (void) putchar(fgetc(tmp_fp));
1029                             else
1030                                 put_translate(fgetc(tmp_fp));
1031                         }
1032                     }
1033
1034                     repair_acsc(&qp->tterm);
1035                     dump_entry(&qp->tterm, suppress_untranslatable,
1036                                limited, numbers, NULL);
1037                     for (j = 0; j < (long) qp->nuses; j++)
1038                         dump_uses(qp->uses[j].name, !capdump);
1039                     len = show_entry();
1040                     if (debug_level != 0 && !limited)
1041                         printf("# length=%d\n", len);
1042                 }
1043             }
1044             if (!namelst && _nc_tail && !quiet) {
1045                 int c, oldc = '\0';
1046                 bool in_comment = FALSE;
1047                 bool trailing_comment = FALSE;
1048
1049                 (void) fseek(tmp_fp, _nc_tail->cend, SEEK_SET);
1050                 while ((c = fgetc(tmp_fp)) != EOF) {
1051                     if (oldc == '\n') {
1052                         if (c == '#') {
1053                             trailing_comment = TRUE;
1054                             in_comment = TRUE;
1055                         } else {
1056                             in_comment = FALSE;
1057                         }
1058                     }
1059                     if (trailing_comment
1060                         && (in_comment || (oldc == '\n' && c == '\n')))
1061                         putchar(c);
1062                     oldc = c;
1063                 }
1064             }
1065         }
1066     }
1067
1068     /* Show the directory into which entries were written, and the total
1069      * number of entries
1070      */
1071     if (showsummary
1072         && (!(check_only || infodump || capdump))) {
1073         int total = _nc_tic_written();
1074         if (total != 0)
1075             fprintf(log_fp, "%d entries written to %s\n",
1076                     total,
1077                     _nc_tic_dir((char *) 0));
1078         else
1079             fprintf(log_fp, "No entries written\n");
1080     }
1081     ExitProgram(EXIT_SUCCESS);
1082 }
1083
1084 /*
1085  * This bit of legerdemain turns all the terminfo variable names into
1086  * references to locations in the arrays Booleans, Numbers, and Strings ---
1087  * precisely what's needed (see comp_parse.c).
1088  */
1089 #undef CUR
1090 #define CUR tp->
1091
1092 /*
1093  * Check if the alternate character-set capabilities are consistent.
1094  */
1095 static void
1096 check_acs(TERMTYPE2 *tp)
1097 {
1098     if (VALID_STRING(acs_chars)) {
1099         const char *boxes = "lmkjtuvwqxn";
1100         char mapped[256];
1101         char missing[256];
1102         const char *p;
1103         char *q;
1104
1105         memset(mapped, 0, sizeof(mapped));
1106         for (p = acs_chars; *p != '\0'; p += 2) {
1107             if (p[1] == '\0') {
1108                 _nc_warning("acsc has odd number of characters");
1109                 break;
1110             }
1111             mapped[UChar(p[0])] = p[1];
1112         }
1113
1114         if (mapped[UChar('I')] && !mapped[UChar('i')]) {
1115             _nc_warning("acsc refers to 'I', which is probably an error");
1116         }
1117
1118         for (p = boxes, q = missing; *p != '\0'; ++p) {
1119             if (!mapped[UChar(p[0])]) {
1120                 *q++ = p[0];
1121             }
1122         }
1123         *q = '\0';
1124
1125         assert(strlen(missing) <= strlen(boxes));
1126         if (*missing != '\0' && strcmp(missing, boxes)) {
1127             _nc_warning("acsc is missing some line-drawing mapping: %s", missing);
1128         }
1129     }
1130 }
1131
1132 /*
1133  * Check if the color capabilities are consistent
1134  */
1135 static void
1136 check_colors(TERMTYPE2 *tp)
1137 {
1138     if ((max_colors > 0) != (max_pairs > 0)
1139         || ((max_colors > max_pairs) && (initialize_pair == 0)))
1140         _nc_warning("inconsistent values for max_colors (%d) and max_pairs (%d)",
1141                     max_colors, max_pairs);
1142
1143     PAIRED(set_foreground, set_background);
1144     PAIRED(set_a_foreground, set_a_background);
1145     PAIRED(set_color_pair, initialize_pair);
1146
1147     if (VALID_STRING(set_foreground)
1148         && VALID_STRING(set_a_foreground)
1149         && !_nc_capcmp(set_foreground, set_a_foreground))
1150         _nc_warning("expected setf/setaf to be different");
1151
1152     if (VALID_STRING(set_background)
1153         && VALID_STRING(set_a_background)
1154         && !_nc_capcmp(set_background, set_a_background))
1155         _nc_warning("expected setb/setab to be different");
1156
1157     /* see: has_colors() */
1158     if (VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
1159         && (((set_foreground != NULL)
1160              && (set_background != NULL))
1161             || ((set_a_foreground != NULL)
1162                 && (set_a_background != NULL))
1163             || set_color_pair)) {
1164         if (!VALID_STRING(orig_pair) && !VALID_STRING(orig_colors))
1165             _nc_warning("expected either op/oc string for resetting colors");
1166     }
1167     if (can_change) {
1168         if (!VALID_STRING(initialize_pair) &&
1169             !VALID_STRING(initialize_color)) {
1170             _nc_warning("expected initc or initp because ccc is given");
1171         }
1172     } else {
1173         if (VALID_STRING(initialize_pair) ||
1174             VALID_STRING(initialize_color)) {
1175             _nc_warning("expected ccc because initc is given");
1176         }
1177     }
1178 }
1179
1180 static int
1181 csi_length(const char *value)
1182 {
1183     int result = 0;
1184
1185     if (value[0] == '\033' && value[1] == '[') {
1186         result = 2;
1187     } else if (UChar(value[0]) == 0x9a) {
1188         result = 1;
1189     }
1190     return result;
1191 }
1192
1193 static char
1194 keypad_final(const char *string)
1195 {
1196     char result = '\0';
1197
1198     if (VALID_STRING(string)
1199         && *string++ == '\033'
1200         && *string++ == 'O'
1201         && strlen(string) == 1) {
1202         result = *string;
1203     }
1204
1205     return result;
1206 }
1207
1208 static long
1209 keypad_index(const char *string)
1210 {
1211     char *test;
1212     const char *list = "PQRSwxymtuvlqrsPpn";    /* app-keypad except "Enter" */
1213     int ch;
1214     long result = -1;
1215
1216     if ((ch = keypad_final(string)) != '\0') {
1217         test = (strchr) (list, ch);
1218         if (test != 0)
1219             result = (long) (test - list);
1220     }
1221     return result;
1222 }
1223
1224 /*
1225  * list[] is down, up, left, right
1226  * "left" may be ^H rather than \E[D
1227  * "down" may be ^J rather than \E[B
1228  * But up/right are generally consistently escape sequences for ANSI terminals.
1229  */
1230 static void
1231 check_ansi_cursor(char *list[4])
1232 {
1233     int j, k;
1234     int want;
1235     size_t suffix;
1236     bool skip[4];
1237     bool repeated = FALSE;
1238
1239     for (j = 0; j < 4; ++j) {
1240         skip[j] = FALSE;
1241         for (k = 0; k < j; ++k) {
1242             if (j != k
1243                 && !strcmp(list[j], list[k])) {
1244                 char *value = _nc_tic_expand(list[k], TRUE, 0);
1245                 _nc_warning("repeated cursor control %s\n", value);
1246                 repeated = TRUE;
1247             }
1248         }
1249     }
1250     if (!repeated) {
1251         char *up = list[1];
1252         size_t prefix = (size_t) csi_length(up);
1253
1254         if (prefix) {
1255             suffix = prefix;
1256             while (up[suffix] && isdigit(UChar(up[suffix])))
1257                 ++suffix;
1258         }
1259         if (prefix && up[suffix] == 'A') {
1260             skip[1] = TRUE;
1261             if (!strcmp(list[0], "\n"))
1262                 skip[0] = TRUE;
1263             if (!strcmp(list[2], "\b"))
1264                 skip[2] = TRUE;
1265
1266             for (j = 0; j < 4; ++j) {
1267                 if (skip[j] || strlen(list[j]) == 1)
1268                     continue;
1269                 if (memcmp(list[j], up, prefix)) {
1270                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1271                     _nc_warning("inconsistent prefix for %s\n", value);
1272                     continue;
1273                 }
1274                 if (strlen(list[j]) < suffix) {
1275                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1276                     _nc_warning("inconsistent length for %s, expected %d\n",
1277                                 value, (int) suffix + 1);
1278                     continue;
1279                 }
1280                 want = "BADC"[j];
1281                 if (list[j][suffix] != want) {
1282                     char *value = _nc_tic_expand(list[j], TRUE, 0);
1283                     _nc_warning("inconsistent suffix for %s, expected %c, have %c\n",
1284                                 value, want, list[j][suffix]);
1285                 }
1286             }
1287         }
1288     }
1289 }
1290
1291 #define EXPECTED(name) if (!PRESENT(name)) _nc_warning("expected " #name)
1292 #define UNEXPECTED(name) if (PRESENT(name)) _nc_warning("unexpected " #name ", for %s", why)
1293
1294 static void
1295 check_noaddress(TERMTYPE2 *tp, const char *why)
1296 {
1297     UNEXPECTED(column_address);
1298     UNEXPECTED(cursor_address);
1299     UNEXPECTED(cursor_home);
1300     UNEXPECTED(cursor_mem_address);
1301     UNEXPECTED(cursor_to_ll);
1302     UNEXPECTED(row_address);
1303     UNEXPECTED(row_address);
1304 }
1305
1306 static void
1307 check_cursor(TERMTYPE2 *tp)
1308 {
1309     int count;
1310     char *list[4];
1311
1312     if (hard_copy) {
1313         check_noaddress(tp, "hard_copy");
1314     } else if (generic_type) {
1315         check_noaddress(tp, "generic_type");
1316     } else if (strchr(tp->term_names, '+') == 0) {
1317         int y = 0;
1318         int x = 0;
1319         if (PRESENT(column_address))
1320             ++y;
1321         if (PRESENT(cursor_address))
1322             y = x = 10;
1323         if (PRESENT(cursor_home))
1324             ++y, ++x;
1325         if (PRESENT(cursor_mem_address))
1326             y = x = 10;
1327         if (PRESENT(cursor_to_ll))
1328             ++y, ++x;
1329         if (PRESENT(row_address))
1330             ++x;
1331         if (PRESENT(cursor_down))
1332             ++y;
1333         if (PRESENT(cursor_up))
1334             ++y;
1335         if (PRESENT(cursor_left))
1336             ++x;
1337         if (PRESENT(cursor_right))
1338             ++x;
1339         if (x < 2 && y < 2) {
1340             _nc_warning("terminal lacks cursor addressing");
1341         } else {
1342             if (x < 2)
1343                 _nc_warning("terminal lacks cursor column-addressing");
1344             if (y < 2)
1345                 _nc_warning("terminal lacks cursor row-addressing");
1346         }
1347     }
1348
1349     /* it is rare to have an insert-line feature without a matching delete */
1350     ANDMISSING(parm_insert_line, insert_line);
1351     ANDMISSING(parm_delete_line, delete_line);
1352     ANDMISSING(parm_insert_line, parm_delete_line);
1353
1354     /* if we have a parameterized form, then the non-parameterized is easy */
1355     ANDMISSING(parm_down_cursor, cursor_down);
1356     ANDMISSING(parm_up_cursor, cursor_up);
1357     ANDMISSING(parm_left_cursor, cursor_left);
1358     ANDMISSING(parm_right_cursor, cursor_right);
1359
1360     /* Given any of a set of cursor movement, the whole set should be present.
1361      * Technically this is not true (we could use cursor_address to fill in
1362      * unsupported controls), but it is likely.
1363      */
1364     count = 0;
1365     if (PRESENT(parm_down_cursor)) {
1366         list[count++] = parm_down_cursor;
1367     }
1368     if (PRESENT(parm_up_cursor)) {
1369         list[count++] = parm_up_cursor;
1370     }
1371     if (PRESENT(parm_left_cursor)) {
1372         list[count++] = parm_left_cursor;
1373     }
1374     if (PRESENT(parm_right_cursor)) {
1375         list[count++] = parm_right_cursor;
1376     }
1377     if (count == 4) {
1378         check_ansi_cursor(list);
1379     } else if (count != 0) {
1380         EXPECTED(parm_down_cursor);
1381         EXPECTED(parm_up_cursor);
1382         EXPECTED(parm_left_cursor);
1383         EXPECTED(parm_right_cursor);
1384     }
1385
1386     count = 0;
1387     if (PRESENT(cursor_down)) {
1388         list[count++] = cursor_down;
1389     }
1390     if (PRESENT(cursor_up)) {
1391         list[count++] = cursor_up;
1392     }
1393     if (PRESENT(cursor_left)) {
1394         list[count++] = cursor_left;
1395     }
1396     if (PRESENT(cursor_right)) {
1397         list[count++] = cursor_right;
1398     }
1399     if (count == 4) {
1400         check_ansi_cursor(list);
1401     } else if (count != 0) {
1402         count = 0;
1403         if (PRESENT(cursor_down) && strcmp(cursor_down, "\n"))
1404             ++count;
1405         if (PRESENT(cursor_left) && strcmp(cursor_left, "\b"))
1406             ++count;
1407         if (PRESENT(cursor_up) && strlen(cursor_up) > 1)
1408             ++count;
1409         if (PRESENT(cursor_right) && strlen(cursor_right) > 1)
1410             ++count;
1411         if (count) {
1412             EXPECTED(cursor_down);
1413             EXPECTED(cursor_up);
1414             EXPECTED(cursor_left);
1415             EXPECTED(cursor_right);
1416         }
1417     }
1418 }
1419
1420 #define MAX_KP 5
1421 /*
1422  * Do a quick sanity-check for vt100-style keypads to see if the 5-key keypad
1423  * is mapped inconsistently.
1424  */
1425 static void
1426 check_keypad(TERMTYPE2 *tp)
1427 {
1428     char show[80];
1429
1430     if (VALID_STRING(key_a1) &&
1431         VALID_STRING(key_a3) &&
1432         VALID_STRING(key_b2) &&
1433         VALID_STRING(key_c1) &&
1434         VALID_STRING(key_c3)) {
1435         char final[MAX_KP + 1];
1436         long list[MAX_KP];
1437         int increase = 0;
1438         int j, k, kk;
1439         long last;
1440         long test;
1441
1442         final[0] = keypad_final(key_a1);
1443         final[1] = keypad_final(key_a3);
1444         final[2] = keypad_final(key_b2);
1445         final[3] = keypad_final(key_c1);
1446         final[4] = keypad_final(key_c3);
1447         final[5] = '\0';
1448
1449         /* special case: legacy coding using 1,2,3,0,. on the bottom */
1450         assert(strlen(final) <= MAX_KP);
1451         if (!strcmp(final, "qsrpn"))
1452             return;
1453
1454         list[0] = keypad_index(key_a1);
1455         list[1] = keypad_index(key_a3);
1456         list[2] = keypad_index(key_b2);
1457         list[3] = keypad_index(key_c1);
1458         list[4] = keypad_index(key_c3);
1459
1460         /* check that they're all vt100 keys */
1461         for (j = 0; j < MAX_KP; ++j) {
1462             if (list[j] < 0) {
1463                 return;
1464             }
1465         }
1466
1467         /* check if they're all in increasing order */
1468         for (j = 1; j < MAX_KP; ++j) {
1469             if (list[j] > list[j - 1]) {
1470                 ++increase;
1471             }
1472         }
1473         if (increase != (MAX_KP - 1)) {
1474             show[0] = '\0';
1475
1476             for (j = 0, last = -1; j < MAX_KP; ++j) {
1477                 for (k = 0, kk = -1, test = 100; k < 5; ++k) {
1478                     if (list[k] > last &&
1479                         list[k] < test) {
1480                         test = list[k];
1481                         kk = k;
1482                     }
1483                 }
1484                 last = test;
1485                 assert(strlen(show) < (MAX_KP * 4));
1486                 switch (kk) {
1487                 case 0:
1488                     _nc_STRCAT(show, " ka1", sizeof(show));
1489                     break;
1490                 case 1:
1491                     _nc_STRCAT(show, " ka3", sizeof(show));
1492                     break;
1493                 case 2:
1494                     _nc_STRCAT(show, " kb2", sizeof(show));
1495                     break;
1496                 case 3:
1497                     _nc_STRCAT(show, " kc1", sizeof(show));
1498                     break;
1499                 case 4:
1500                     _nc_STRCAT(show, " kc3", sizeof(show));
1501                     break;
1502                 }
1503             }
1504
1505             _nc_warning("vt100 keypad order inconsistent: %s", show);
1506         }
1507
1508     } else if (VALID_STRING(key_a1) ||
1509                VALID_STRING(key_a3) ||
1510                VALID_STRING(key_b2) ||
1511                VALID_STRING(key_c1) ||
1512                VALID_STRING(key_c3)) {
1513         show[0] = '\0';
1514         if (keypad_index(key_a1) >= 0)
1515             _nc_STRCAT(show, " ka1", sizeof(show));
1516         if (keypad_index(key_a3) >= 0)
1517             _nc_STRCAT(show, " ka3", sizeof(show));
1518         if (keypad_index(key_b2) >= 0)
1519             _nc_STRCAT(show, " kb2", sizeof(show));
1520         if (keypad_index(key_c1) >= 0)
1521             _nc_STRCAT(show, " kc1", sizeof(show));
1522         if (keypad_index(key_c3) >= 0)
1523             _nc_STRCAT(show, " kc3", sizeof(show));
1524         if (*show != '\0')
1525             _nc_warning("vt100 keypad map incomplete:%s", show);
1526     }
1527
1528     /*
1529      * These warnings are useful for consistency checks - it is possible that
1530      * there are real terminals with mismatches in these
1531      */
1532     ANDMISSING(key_ic, key_dc);
1533 }
1534
1535 static void
1536 check_printer(TERMTYPE2 *tp)
1537 {
1538     (void) tp;
1539 #if defined(enter_doublewide_mode) && defined(exit_doublewide_mode)
1540     PAIRED(enter_doublewide_mode, exit_doublewide_mode);
1541 #endif
1542 #if defined(enter_italics_mode) && defined(exit_italics_mode)
1543     PAIRED(enter_italics_mode, exit_italics_mode);
1544 #endif
1545 #if defined(enter_leftward_mode) && defined(exit_leftward_mode)
1546     PAIRED(enter_leftward_mode, exit_leftward_mode);
1547 #endif
1548 #if defined(enter_micro_mode) && defined(exit_micro_mode)
1549     PAIRED(enter_micro_mode, exit_micro_mode);
1550 #endif
1551 #if defined(enter_shadow_mode) && defined(exit_shadow_mode)
1552     PAIRED(enter_shadow_mode, exit_shadow_mode);
1553 #endif
1554 #if defined(enter_subscript_mode) && defined(exit_subscript_mode)
1555     PAIRED(enter_subscript_mode, exit_subscript_mode);
1556 #endif
1557 #if defined(enter_superscript_mode) && defined(exit_superscript_mode)
1558     PAIRED(enter_superscript_mode, exit_superscript_mode);
1559 #endif
1560 #if defined(enter_upward_mode) && defined(exit_upward_mode)
1561     PAIRED(enter_upward_mode, exit_upward_mode);
1562 #endif
1563
1564 #if defined(start_char_set_def) && defined(stop_char_set_def)
1565     ANDMISSING(start_char_set_def, stop_char_set_def);
1566 #endif
1567
1568     /* if we have a parameterized form, then the non-parameterized is easy */
1569 #if defined(set_bottom_margin_parm) && defined(set_bottom_margin)
1570     ANDMISSING(set_bottom_margin_parm, set_bottom_margin);
1571 #endif
1572 #if defined(set_left_margin_parm) && defined(set_left_margin)
1573     ANDMISSING(set_left_margin_parm, set_left_margin);
1574 #endif
1575 #if defined(set_right_margin_parm) && defined(set_right_margin)
1576     ANDMISSING(set_right_margin_parm, set_right_margin);
1577 #endif
1578 #if defined(set_top_margin_parm) && defined(set_top_margin)
1579     ANDMISSING(set_top_margin_parm, set_top_margin);
1580 #endif
1581
1582 #if defined(parm_down_micro) && defined(micro_down)
1583     ANDMISSING(parm_down_micro, micro_down);
1584 #endif
1585 #if defined(parm_left_micro) && defined(micro_left)
1586     ANDMISSING(parm_left_micro, micro_left);
1587 #endif
1588 #if defined(parm_right_micro) && defined(micro_right)
1589     ANDMISSING(parm_right_micro, micro_right);
1590 #endif
1591 #if defined(parm_up_micro) && defined(micro_up)
1592     ANDMISSING(parm_up_micro, micro_up);
1593 #endif
1594 }
1595
1596 static bool
1597 uses_SGR_39_49(const char *value)
1598 {
1599     return (strstr(value, "39;49") != 0
1600             || strstr(value, "49;39") != 0);
1601 }
1602
1603 /*
1604  * Check consistency of termcap extensions related to "screen".
1605  */
1606 static void
1607 check_screen(TERMTYPE2 *tp)
1608 {
1609 #if NCURSES_XNAMES
1610     if (_nc_user_definable) {
1611         int have_XT = tigetflag("XT");
1612         int have_XM = tigetflag("XM");
1613         int have_bce = back_color_erase;
1614         bool have_kmouse = FALSE;
1615         bool use_sgr_39_49 = FALSE;
1616         char *name = _nc_first_name(tp->term_names);
1617
1618         if (!VALID_BOOLEAN(have_bce)) {
1619             have_bce = FALSE;
1620         }
1621         if (!VALID_BOOLEAN(have_XM)) {
1622             have_XM = FALSE;
1623         }
1624         if (!VALID_BOOLEAN(have_XT)) {
1625             have_XT = FALSE;
1626         }
1627         if (VALID_STRING(key_mouse)) {
1628             have_kmouse = !strcmp("\033[M", key_mouse);
1629         }
1630         if (VALID_STRING(orig_colors)) {
1631             use_sgr_39_49 = uses_SGR_39_49(orig_colors);
1632         } else if (VALID_STRING(orig_pair)) {
1633             use_sgr_39_49 = uses_SGR_39_49(orig_pair);
1634         }
1635
1636         if (have_XM && have_XT) {
1637             _nc_warning("Screen's XT capability conflicts with XM");
1638         } else if (have_XT
1639                    && strstr(name, "screen") != 0
1640                    && strchr(name, '.') != 0) {
1641             _nc_warning("Screen's \"screen\" entries should not have XT set");
1642         } else if (have_XT) {
1643             if (!have_kmouse && have_bce) {
1644                 if (VALID_STRING(key_mouse)) {
1645                     _nc_warning("Value of kmous inconsistent with screen's usage");
1646                 } else {
1647                     _nc_warning("Expected kmous capability with XT");
1648                 }
1649             }
1650             if (!have_bce && max_colors > 0)
1651                 _nc_warning("Expected bce capability with XT");
1652             if (!use_sgr_39_49 && have_bce && max_colors > 0)
1653                 _nc_warning("Expected orig_colors capability with XT to have 39/49 parameters");
1654             if (VALID_STRING(to_status_line))
1655                 _nc_warning("\"tsl\" capability is redundant, given XT");
1656         } else {
1657             if (have_kmouse && !have_XM)
1658                 _nc_warning("Expected XT to be set, given kmous");
1659         }
1660     }
1661 #endif
1662 }
1663
1664 /*
1665  * Returns the expected number of parameters for the given capability.
1666  */
1667 static int
1668 expected_params(const char *name)
1669 {
1670 #define DATA(name,count) { { name }, count }
1671     /* *INDENT-OFF* */
1672     static const struct {
1673         const char name[9];
1674         int count;
1675     } table[] = {
1676         DATA( "S0",             1 ),    /* 'screen' extension */
1677         DATA( "birep",          2 ),
1678         DATA( "chr",            1 ),
1679         DATA( "colornm",        1 ),
1680         DATA( "cpi",            1 ),
1681         DATA( "csnm",           1 ),
1682         DATA( "csr",            2 ),
1683         DATA( "cub",            1 ),
1684         DATA( "cud",            1 ),
1685         DATA( "cuf",            1 ),
1686         DATA( "cup",            2 ),
1687         DATA( "cuu",            1 ),
1688         DATA( "cvr",            1 ),
1689         DATA( "cwin",           5 ),
1690         DATA( "dch",            1 ),
1691         DATA( "defc",           3 ),
1692         DATA( "dial",           1 ),
1693         DATA( "dispc",          1 ),
1694         DATA( "dl",             1 ),
1695         DATA( "ech",            1 ),
1696         DATA( "getm",           1 ),
1697         DATA( "hpa",            1 ),
1698         DATA( "ich",            1 ),
1699         DATA( "il",             1 ),
1700         DATA( "indn",           1 ),
1701         DATA( "initc",          4 ),
1702         DATA( "initp",          7 ),
1703         DATA( "lpi",            1 ),
1704         DATA( "mc5p",           1 ),
1705         DATA( "mrcup",          2 ),
1706         DATA( "mvpa",           1 ),
1707         DATA( "pfkey",          2 ),
1708         DATA( "pfloc",          2 ),
1709         DATA( "pfx",            2 ),
1710         DATA( "pfxl",           3 ),
1711         DATA( "pln",            2 ),
1712         DATA( "qdial",          1 ),
1713         DATA( "rcsd",           1 ),
1714         DATA( "rep",            2 ),
1715         DATA( "rin",            1 ),
1716         DATA( "sclk",           3 ),
1717         DATA( "scp",            1 ),
1718         DATA( "scs",            1 ),
1719         DATA( "scsd",           2 ),
1720         DATA( "setab",          1 ),
1721         DATA( "setaf",          1 ),
1722         DATA( "setb",           1 ),
1723         DATA( "setcolor",       1 ),
1724         DATA( "setf",           1 ),
1725         DATA( "sgr",            9 ),
1726         DATA( "sgr1",           6 ),
1727         DATA( "slength",        1 ),
1728         DATA( "slines",         1 ),
1729         DATA( "smgbp",          1 ),    /* 2 if smgtp is not given */
1730         DATA( "smglp",          1 ),
1731         DATA( "smglr",          2 ),
1732         DATA( "smgrp",          1 ),
1733         DATA( "smgtb",          2 ),
1734         DATA( "smgtp",          1 ),
1735         DATA( "tsl",            1 ),
1736         DATA( "u6",             -1 ),
1737         DATA( "vpa",            1 ),
1738         DATA( "wind",           4 ),
1739         DATA( "wingo",          1 ),
1740     };
1741     /* *INDENT-ON* */
1742
1743 #undef DATA
1744
1745     unsigned n;
1746     int result = 0;             /* function-keys, etc., use none */
1747
1748     for (n = 0; n < SIZEOF(table); n++) {
1749         if (!strcmp(name, table[n].name)) {
1750             result = table[n].count;
1751             break;
1752         }
1753     }
1754
1755     return result;
1756 }
1757
1758 /*
1759  * ncurses assumes that u6 could be used for getting the cursor-position, but
1760  * that is not implemented.  Make a special case for that, to quiet needless
1761  * warnings.
1762  *
1763  * There are other string-capability extensions (see terminfo.src) which could
1764  * have parameters such as "Ss", "%u", but are not used by ncurses.
1765  */
1766 static int
1767 is_user_capability(const char *name)
1768 {
1769     int result = -1;
1770     if (name[0] == 'u' &&
1771         (name[1] >= '0' && name[1] <= '9') &&
1772         name[2] == '\0')
1773         result = (name[1] == '6') ? 2 : 0;
1774     return result;
1775 }
1776
1777 /*
1778  * Make a quick sanity check for the parameters which are used in the given
1779  * strings.  If there are no "%p" tokens, then there should be no other "%"
1780  * markers.
1781  */
1782 static void
1783 check_params(TERMTYPE2 *tp, const char *name, char *value, int extended)
1784 {
1785     int expected = expected_params(name);
1786     int actual = 0;
1787     int n;
1788     bool params[NUM_PARM];
1789     char *s = value;
1790
1791 #ifdef set_top_margin_parm
1792     if (!strcmp(name, "smgbp")
1793         && set_top_margin_parm == 0)
1794         expected = 2;
1795 #endif
1796
1797     for (n = 0; n < NUM_PARM; n++)
1798         params[n] = FALSE;
1799
1800     while (*s != 0) {
1801         if (*s == '%') {
1802             if (*++s == '\0') {
1803                 _nc_warning("expected character after %% in %s", name);
1804                 break;
1805             } else if (*s == 'p') {
1806                 if (*++s == '\0' || !isdigit((int) *s)) {
1807                     _nc_warning("expected digit after %%p in %s", name);
1808                     return;
1809                 } else {
1810                     n = (*s - '0');
1811                     if (n > actual)
1812                         actual = n;
1813                     params[n] = TRUE;
1814                 }
1815             }
1816         }
1817         s++;
1818     }
1819
1820     if (extended) {
1821         if (actual > 0) {
1822             _nc_warning("extended %s capability has %d parameters",
1823                         name, actual);
1824             expected = actual;
1825         }
1826     }
1827
1828     if (params[0]) {
1829         _nc_warning("%s refers to parameter 0 (%%p0), which is not allowed", name);
1830     }
1831     if (value == set_attributes || expected < 0) {
1832         ;
1833     } else if (expected != actual) {
1834         _nc_warning("%s uses %d parameters, expected %d", name,
1835                     actual, expected);
1836         for (n = 1; n < actual; n++) {
1837             if (!params[n])
1838                 _nc_warning("%s omits parameter %d", name, n);
1839         }
1840     }
1841
1842     /*
1843      * Counting "%p" markers does not account for termcap expressions which
1844      * may not have been fully translated.  Also, tparm does its own analysis.
1845      * Report differences here.
1846      */
1847     if (actual >= 0) {
1848         char *p_is_s[NUM_PARM];
1849         int popcount;
1850         int analyzed = _nc_tparm_analyze(value, p_is_s, &popcount);
1851         if (analyzed < popcount) {
1852             analyzed = popcount;
1853         }
1854         if (actual != analyzed && expected != analyzed) {
1855             int user_cap = is_user_capability(name);
1856             if ((user_cap == analyzed) && using_extensions) {
1857                 ;               /* ignore */
1858             } else if (user_cap >= 0) {
1859                 _nc_warning("tparm will use %d parameters for %s",
1860                             analyzed, name);
1861             } else {
1862                 _nc_warning("tparm analyzed %d parameters for %s, expected %d",
1863                             analyzed, name, actual);
1864             }
1865         }
1866     }
1867 }
1868
1869 static bool
1870 line_capability(const char *name)
1871 {
1872     bool result = FALSE;
1873     static const char *table[] =
1874     {
1875         "csr",                  /* change_scroll_region          */
1876         "clear",                /* clear_screen                  */
1877         "ed",                   /* clr_eos                       */
1878         "cwin",                 /* create_window                 */
1879         "cup",                  /* cursor_address                */
1880         "cud1",                 /* cursor_down                   */
1881         "home",                 /* cursor_home                   */
1882         "mrcup",                /* cursor_mem_address            */
1883         "ll",                   /* cursor_to_ll                  */
1884         "cuu1",                 /* cursor_up                     */
1885         "dl1",                  /* delete_line                   */
1886         "hd",                   /* down_half_line                */
1887         "flash",                /* flash_screen                  */
1888         "ff",                   /* form_feed                     */
1889         "il1",                  /* insert_line                   */
1890         "nel",                  /* newline                       */
1891         "dl",                   /* parm_delete_line              */
1892         "cud",                  /* parm_down_cursor              */
1893         "indn",                 /* parm_index                    */
1894         "il",                   /* parm_insert_line              */
1895         "rin",                  /* parm_rindex                   */
1896         "cuu",                  /* parm_up_cursor                */
1897         "mc0",                  /* print_screen                  */
1898         "vpa",                  /* row_address                   */
1899         "ind",                  /* scroll_forward                */
1900         "ri",                   /* scroll_reverse                */
1901         "hu",                   /* up_half_line                  */
1902     };
1903     size_t n;
1904     for (n = 0; n < SIZEOF(table); ++n) {
1905         if (!strcmp(name, table[n])) {
1906             result = TRUE;
1907             break;
1908         }
1909     }
1910     return result;
1911 }
1912
1913 /*
1914  * Check for DEC VT100 private mode for reverse video.
1915  */
1916 static const char *
1917 skip_DECSCNM(const char *value, int *flag)
1918 {
1919     *flag = -1;
1920     if (value != 0) {
1921         int skip = csi_length(value);
1922         if (skip > 0 &&
1923             value[skip++] == '?' &&
1924             value[skip++] == '5') {
1925             if (value[skip] == 'h') {
1926                 *flag = 1;
1927             } else if (value[skip] == 'l') {
1928                 *flag = 0;
1929             }
1930             value += skip + 1;
1931         }
1932     }
1933     return value;
1934 }
1935
1936 static void
1937 check_delays(TERMTYPE2 *tp, const char *name, const char *value)
1938 {
1939     const char *p, *q;
1940     const char *first = 0;
1941     const char *last = 0;
1942
1943     for (p = value; *p != '\0'; ++p) {
1944         if (p[0] == '$' && p[1] == '<') {
1945             const char *base = p + 2;
1946             const char *mark = 0;
1947             bool maybe = TRUE;
1948             bool mixed = FALSE;
1949             int proportional = 0;
1950             int mandatory = 0;
1951
1952             first = p;
1953
1954             for (q = base; *q != '\0'; ++q) {
1955                 if (*q == '>') {
1956                     if (mark == 0)
1957                         mark = q;
1958                     break;
1959                 } else if (*q == '*' || *q == '/') {
1960                     if (*q == '*')
1961                         ++proportional;
1962                     if (*q == '/')
1963                         ++mandatory;
1964                     if (mark == 0)
1965                         mark = q;
1966                 } else if (!(isalnum(UChar(*q)) || strchr("+-.", *q) != 0)) {
1967                     maybe = FALSE;
1968                     break;
1969                 } else if (proportional || mandatory) {
1970                     mixed = TRUE;
1971                 }
1972             }
1973             last = *q ? (q + 1) : q;
1974             if (*q == '\0') {
1975                 maybe = FALSE;  /* just an isolated "$<" */
1976             } else if (maybe) {
1977                 float check_f;
1978                 char check_c;
1979                 int rc = sscanf(base, "%f%c", &check_f, &check_c);
1980                 if ((rc != 2) || (check_c != *mark) || mixed) {
1981                     _nc_warning("syntax error in %s delay '%.*s'", name,
1982                                 (int) (q - base), base);
1983                 } else if (*name == 'k') {
1984                     _nc_warning("function-key %s has delay", name);
1985                 } else if (proportional && !line_capability(name)) {
1986                     _nc_warning("non-line capability using proportional delay: %s", name);
1987                 } else if (!xon_xoff &&
1988                            !mandatory &&
1989                            strchr(_nc_first_name(tp->term_names), '+') == 0) {
1990                     _nc_warning("%s in %s is used since no xon/xoff",
1991                                 (proportional
1992                                  ? "proportional delay"
1993                                  : "delay"),
1994                                 name);
1995                 }
1996             } else {
1997                 p = q - 1;      /* restart scan */
1998             }
1999         }
2000     }
2001
2002     if (!strcmp(name, "flash") ||
2003         !strcmp(name, "beep")) {
2004
2005         if (first != 0) {
2006             if (first == value || *last == 0) {
2007                 /*
2008                  * Delay is on one end or the other.
2009                  */
2010                 _nc_warning("expected delay embedded within %s", name);
2011             }
2012         } else {
2013             int flag;
2014
2015             /*
2016              * Check for missing delay when using VT100 reverse-video.
2017              * A real VT100 might not need this, but terminal emulators do.
2018              */
2019             if ((p = skip_DECSCNM(value, &flag)) != 0 &&
2020                 flag > 0 &&
2021                 (q = skip_DECSCNM(p, &flag)) != 0 &&
2022                 flag == 0) {
2023                 _nc_warning("expected a delay in %s", name);
2024             }
2025         }
2026     }
2027 }
2028
2029 static char *
2030 check_1_infotocap(const char *name, NCURSES_CONST char *value, int count)
2031 {
2032     int k;
2033     int ignored;
2034     long numbers[1 + NUM_PARM];
2035     char *strings[1 + NUM_PARM];
2036     char *p_is_s[NUM_PARM];
2037     char *result;
2038     char blob[NUM_PARM * 10];
2039     char *next = blob;
2040
2041     *next++ = '\0';
2042     for (k = 1; k <= NUM_PARM; k++) {
2043         numbers[k] = count;
2044         _nc_SPRINTF(next,
2045                     _nc_SLIMIT(sizeof(blob) - (size_t) (next - blob))
2046                     "XYZ%d", count);
2047         strings[k] = next;
2048         next += strlen(next) + 1;
2049     }
2050
2051     switch (tparm_type(name)) {
2052     case Num_Str:
2053         result = TPARM_2(value, numbers[1], strings[2]);
2054         break;
2055     case Num_Str_Str:
2056         result = TPARM_3(value, numbers[1], strings[2], strings[3]);
2057         break;
2058     case Numbers:
2059     default:
2060         (void) _nc_tparm_analyze(value, p_is_s, &ignored);
2061 #define myParam(n) (p_is_s[n - 1] != 0 ? ((TPARM_ARG) strings[n]) : numbers[n])
2062         result = TPARM_9(value,
2063                          myParam(1),
2064                          myParam(2),
2065                          myParam(3),
2066                          myParam(4),
2067                          myParam(5),
2068                          myParam(6),
2069                          myParam(7),
2070                          myParam(8),
2071                          myParam(9));
2072         break;
2073     }
2074     return result;
2075 }
2076
2077 #define IsDelay(ch) ((ch) == '.' || isdigit(UChar(ch)))
2078
2079 static const char *
2080 parse_delay_value(const char *src, double *delays, int *always)
2081 {
2082     int star = 0;
2083
2084     *delays = 0.0;
2085     if (always)
2086         *always = 0;
2087
2088     while (isdigit(UChar(*src))) {
2089         (*delays) = (*delays) * 10 + (*src++ - '0');
2090     }
2091     if (*src == '.') {
2092         int gotdot = 1;
2093
2094         ++src;
2095         while (isdigit(UChar(*src))) {
2096             gotdot *= 10;
2097             (*delays) += (*src++ - '0') / gotdot;
2098         }
2099     }
2100     while (*src == '*' || *src == '/') {
2101         if (always == 0 && *src == '/')
2102             break;
2103         if (*src++ == '*') {
2104             star = 1;
2105         } else {
2106             *always = 1;
2107         }
2108     }
2109     if (star)
2110         *delays = -(*delays);
2111     return src;
2112 }
2113
2114 static const char *
2115 parse_ti_delay(const char *ti, double *delays)
2116 {
2117     *delays = 0.0;
2118     while (*ti != '\0') {
2119         if (*ti == '\\') {
2120             ++ti;
2121         }
2122         if (ti[0] == '$'
2123             && ti[1] == '<'
2124             && IsDelay(UChar(ti[2]))) {
2125             int ignored;
2126             const char *last = parse_delay_value(ti + 2, delays, &ignored);
2127             if (*last == '>') {
2128                 ti = last;
2129             }
2130         } else {
2131             ++ti;
2132         }
2133     }
2134     return ti;
2135 }
2136
2137 static const char *
2138 parse_tc_delay(const char *tc, double *delays)
2139 {
2140     return parse_delay_value(tc, delays, (int *) 0);
2141 }
2142
2143 /*
2144  * Compare terminfo- and termcap-strings, factoring out delays.
2145  */
2146 static bool
2147 same_ti_tc(const char *ti, const char *tc, bool * embedded)
2148 {
2149     bool same = TRUE;
2150     double ti_delay = 0.0;
2151     double tc_delay = 0.0;
2152     const char *ti_last;
2153
2154     *embedded = FALSE;
2155     ti_last = parse_ti_delay(ti, &ti_delay);
2156     tc = parse_tc_delay(tc, &tc_delay);
2157
2158     while ((ti < ti_last) && *tc) {
2159         if (*ti == '\\' && ispunct(UChar(ti[1]))) {
2160             ++ti;
2161             if ((*ti == '^') && !strncmp(tc, "\\136", 4)) {
2162                 ti += 1;
2163                 tc += 4;
2164                 continue;
2165             }
2166         } else if (ti[0] == '$' && ti[1] == '<') {
2167             double no_delay;
2168             const char *ss = parse_ti_delay(ti, &no_delay);
2169             if (ss != ti) {
2170                 *embedded = TRUE;
2171                 ti = ss;
2172                 continue;
2173             }
2174         }
2175         if (*tc == '\\' && ispunct(UChar(tc[1]))) {
2176             ++tc;
2177         }
2178         if (*ti++ != *tc++) {
2179             same = FALSE;
2180             break;
2181         }
2182     }
2183
2184     if (*embedded) {
2185         if (same) {
2186             same = FALSE;
2187         } else {
2188             *embedded = FALSE;  /* report only one problem */
2189         }
2190     }
2191
2192     return same;
2193 }
2194
2195 /*
2196  * Check terminfo to termcap translation.
2197  */
2198 static void
2199 check_infotocap(TERMTYPE2 *tp, int i, const char *value)
2200 {
2201     const char *name = ExtStrname(tp, i, strnames);
2202     int params = (((i < (int) SIZEOF(parametrized)) &&
2203                    (i < STRCOUNT))
2204                   ? parametrized[i]
2205                   : ((*value == 'k')
2206                      ? 0
2207                      : has_params(value)));
2208     int to_char = 0;
2209     char *ti_value;
2210     char *tc_value;
2211     bool embedded;
2212
2213     if ((ti_value = _nc_tic_expand(value, TRUE, to_char)) == ABSENT_STRING) {
2214         _nc_warning("tic-expansion of %s failed", name);
2215     } else if ((tc_value = _nc_infotocap(name, ti_value, params)) == ABSENT_STRING) {
2216         _nc_warning("tic-conversion of %s failed", name);
2217     } else if (params > 0) {
2218         int limit = 5;
2219         int count;
2220         bool first = TRUE;
2221
2222         if (!strcmp(name, "setf")
2223             || !strcmp(name, "setb")
2224             || !strcmp(name, "setaf")
2225             || !strcmp(name, "setab")) {
2226             limit = max_colors;
2227         }
2228         for (count = 0; count < limit; ++count) {
2229             char *ti_check = check_1_infotocap(name, ti_value, count);
2230             char *tc_check = check_1_infotocap(name, tc_value, count);
2231
2232             if (strcmp(ti_check, tc_check)) {
2233                 if (first) {
2234                     fprintf(stderr, "check_infotocap(%s)\n", name);
2235                     fprintf(stderr, "...ti '%s'\n", ti_value);
2236                     fprintf(stderr, "...tc '%s'\n", tc_value);
2237                     first = FALSE;
2238                 }
2239                 _nc_warning("tparm-conversion of %s(%d) differs between\n\tterminfo %s\n\ttermcap  %s",
2240                             name, count, ti_check, tc_check);
2241             }
2242         }
2243     } else if (params == 0 && !same_ti_tc(ti_value, tc_value, &embedded)) {
2244         if (embedded) {
2245             _nc_warning("termcap equivalent of %s cannot use embedded delay", name);
2246         } else {
2247             _nc_warning("tic-conversion of %s changed value\n\tfrom %s\n\tto   %s",
2248                         name, ti_value, tc_value);
2249         }
2250     }
2251 }
2252
2253 static char *
2254 skip_delay(char *s)
2255 {
2256     while (*s == '/' || isdigit(UChar(*s)))
2257         ++s;
2258     return s;
2259 }
2260
2261 /*
2262  * Skip a delay altogether, e.g., when comparing a simple string to sgr,
2263  * the latter may have a worst-case delay on the end.
2264  */
2265 static char *
2266 ignore_delays(char *s)
2267 {
2268     int delaying = 0;
2269
2270     do {
2271         switch (*s) {
2272         case '$':
2273             if (delaying == 0)
2274                 delaying = 1;
2275             break;
2276         case '<':
2277             if (delaying == 1)
2278                 delaying = 2;
2279             break;
2280         case '\0':
2281             delaying = 0;
2282             break;
2283         default:
2284             if (delaying) {
2285                 s = skip_delay(s);
2286                 if (*s == '>')
2287                     ++s;
2288                 delaying = 0;
2289             }
2290             break;
2291         }
2292         if (delaying)
2293             ++s;
2294     } while (delaying);
2295     return s;
2296 }
2297
2298 #define DATA(name) { #name }
2299 static const char sgr_names[][11] =
2300 {
2301     DATA(none),
2302     DATA(standout),
2303     DATA(underline),
2304     DATA(reverse),
2305     DATA(blink),
2306     DATA(dim),
2307     DATA(bold),
2308     DATA(invis),
2309     DATA(protect),
2310     DATA(altcharset),
2311     ""
2312 };
2313 #undef DATA
2314
2315 /*
2316  * An sgr string may contain several settings other than the one we're
2317  * interested in, essentially sgr0 + rmacs + whatever.  As long as the
2318  * "whatever" is contained in the sgr string, that is close enough for our
2319  * sanity check.
2320  */
2321 static bool
2322 similar_sgr(int num, char *a, char *b)
2323 {
2324     char *base_a = a;
2325     char *base_b = b;
2326     int delaying = 0;
2327
2328     while (*b != 0) {
2329         while (*a != *b) {
2330             if (*a == 0) {
2331                 if (num < 0) {
2332                     ;
2333                 } else if (b[0] == '$'
2334                            && b[1] == '<') {
2335                     _nc_warning("Did not find delay %s", _nc_visbuf(b));
2336                 } else {
2337                     _nc_warning("checking sgr(%s) %s\n\tcompare to %s\n\tunmatched %s",
2338                                 sgr_names[num], _nc_visbuf2(1, base_a),
2339                                 _nc_visbuf2(2, base_b),
2340                                 _nc_visbuf2(3, b));
2341                 }
2342                 return FALSE;
2343             } else if (delaying) {
2344                 a = skip_delay(a);
2345                 b = skip_delay(b);
2346             } else if ((*b == '0' || (*b == ';')) && *a == 'm') {
2347                 b++;
2348             } else {
2349                 a++;
2350             }
2351         }
2352         switch (*a) {
2353         case '$':
2354             if (delaying == 0)
2355                 delaying = 1;
2356             break;
2357         case '<':
2358             if (delaying == 1)
2359                 delaying = 2;
2360             break;
2361         default:
2362             delaying = 0;
2363             break;
2364         }
2365         a++;
2366         b++;
2367     }
2368     /* ignore delays on the end of the string */
2369     a = ignore_delays(a);
2370     return ((num != 0) || (*a == 0));
2371 }
2372
2373 static char *
2374 check_sgr(TERMTYPE2 *tp, char *zero, int num, char *cap, const char *name)
2375 {
2376     char *test;
2377
2378     _nc_tparm_err = 0;
2379     test = TPARM_9(set_attributes,
2380                    num == 1,
2381                    num == 2,
2382                    num == 3,
2383                    num == 4,
2384                    num == 5,
2385                    num == 6,
2386                    num == 7,
2387                    num == 8,
2388                    num == 9);
2389     if (test != 0) {
2390         if (PRESENT(cap)) {
2391             if (!similar_sgr(num, test, cap)) {
2392                 _nc_warning("%s differs from sgr(%d)\n\t%s=%s\n\tsgr(%d)=%s",
2393                             name, num,
2394                             name, _nc_visbuf2(1, cap),
2395                             num, _nc_visbuf2(2, test));
2396             }
2397         } else if (_nc_capcmp(test, zero)) {
2398             _nc_warning("sgr(%d) present, but not %s", num, name);
2399         }
2400     } else if (PRESENT(cap)) {
2401         _nc_warning("sgr(%d) missing, but %s present", num, name);
2402     }
2403     if (_nc_tparm_err)
2404         _nc_warning("stack error in sgr(%d) string", num);
2405     return test;
2406 }
2407
2408 #define CHECK_SGR(num,name) check_sgr(tp, zero, num, name, #name)
2409
2410 #ifdef TRACE
2411 /*
2412  * If tic is compiled with TRACE, we'll be able to see the output from the
2413  * DEBUG() macro.  But since it doesn't use traceon(), it always goes to
2414  * the standard error.  Use this function to make it simpler to follow the
2415  * resulting debug traces.
2416  */
2417 static void
2418 show_where(unsigned level)
2419 {
2420     if (_nc_tracing >= DEBUG_LEVEL(level)) {
2421         char my_name[MAX_NAME_SIZE];
2422         _nc_get_type(my_name);
2423         _tracef("\"%s\", line %d, '%s'",
2424                 _nc_get_source(),
2425                 _nc_curr_line, my_name);
2426     }
2427 }
2428
2429 #else
2430 #define show_where(level)       /* nothing */
2431 #endif
2432
2433 typedef struct {
2434     int keycode;
2435     const char *name;
2436     const char *value;
2437 } NAME_VALUE;
2438
2439 static NAME_VALUE *
2440 get_fkey_list(TERMTYPE2 *tp)
2441 {
2442     NAME_VALUE *result = typeMalloc(NAME_VALUE, NUM_STRINGS(tp) + 1);
2443     const struct tinfo_fkeys *all_fkeys = _nc_tinfo_fkeys;
2444     int used = 0;
2445     unsigned j;
2446
2447     if (result == 0)
2448         failed("get_fkey_list");
2449
2450     for (j = 0; all_fkeys[j].code; j++) {
2451         char *a = tp->Strings[all_fkeys[j].offset];
2452         if (VALID_STRING(a)) {
2453             result[used].keycode = (int) all_fkeys[j].code;
2454             result[used].name = strnames[all_fkeys[j].offset];
2455             result[used].value = a;
2456             ++used;
2457         }
2458     }
2459 #if NCURSES_XNAMES
2460     for (j = STRCOUNT; j < NUM_STRINGS(tp); ++j) {
2461         const char *name = ExtStrname(tp, (int) j, strnames);
2462         if (*name == 'k') {
2463             result[used].keycode = -1;
2464             result[used].name = name;
2465             result[used].value = tp->Strings[j];
2466             ++used;
2467         }
2468     }
2469 #endif
2470     result[used].keycode = 0;
2471     return result;
2472 }
2473
2474 static void
2475 show_fkey_name(NAME_VALUE * data)
2476 {
2477     if (data->keycode > 0) {
2478         fprintf(stderr, " %s", keyname(data->keycode));
2479         fprintf(stderr, " (capability \"%s\")", data->name);
2480     } else {
2481         fprintf(stderr, " capability \"%s\"", data->name);
2482     }
2483 }
2484
2485 /*
2486  * A terminal entry may contain more than one keycode assigned to a given
2487  * string (e.g., KEY_END and KEY_LL).  But curses will only return one (the
2488  * last one assigned).
2489  */
2490 static void
2491 check_conflict(TERMTYPE2 *tp)
2492 {
2493     bool conflict = FALSE;
2494     unsigned j, k;
2495
2496     if (!(_nc_syntax == SYN_TERMCAP && capdump)) {
2497         char *check = calloc((size_t) (NUM_STRINGS(tp) + 1), sizeof(char));
2498         NAME_VALUE *given = get_fkey_list(tp);
2499
2500         if (check == 0)
2501             failed("check_conflict");
2502
2503         for (j = 0; given[j].keycode; ++j) {
2504             const char *a = given[j].value;
2505             bool first = TRUE;
2506
2507             if (!VALID_STRING(a))
2508                 continue;
2509
2510             for (k = j + 1; given[k].keycode; k++) {
2511                 const char *b = given[k].value;
2512
2513                 if (!VALID_STRING(b))
2514                     continue;
2515                 if (check[k])
2516                     continue;
2517
2518                 if (!_nc_capcmp(a, b)) {
2519                     check[j] = 1;
2520                     check[k] = 1;
2521                     if (first) {
2522                         if (!conflict) {
2523                             _nc_warning("Conflicting key definitions (using the last)");
2524                             conflict = TRUE;
2525                         }
2526                         fprintf(stderr, "...");
2527                         show_fkey_name(given + j);
2528                         fprintf(stderr, " is the same as");
2529                         show_fkey_name(given + k);
2530                         first = FALSE;
2531                     } else {
2532                         fprintf(stderr, ", ");
2533                         show_fkey_name(given + k);
2534                     }
2535                 }
2536             }
2537             if (!first)
2538                 fprintf(stderr, "\n");
2539         }
2540 #if NCURSES_XNAMES
2541         if (using_extensions) {
2542             /* *INDENT-OFF* */
2543             static struct {
2544                 const char *xcurses;
2545                 const char *shifted;
2546             } table[] = {
2547                 { "kDC",  NULL },
2548                 { "kDN",  "kind" },
2549                 { "kEND", NULL },
2550                 { "kHOM", NULL },
2551                 { "kLFT", NULL },
2552                 { "kNXT", NULL },
2553                 { "kPRV", NULL },
2554                 { "kRIT", NULL },
2555                 { "kUP",  "kri" },
2556                 { NULL,   NULL },
2557             };
2558             /* *INDENT-ON* */
2559
2560             /*
2561              * SVr4 curses defines the "xcurses" names listed above except for
2562              * the special cases in the "shifted" column.  When using these
2563              * names for xterm's extensions, that was confusing, and resulted
2564              * in adding extended capabilities with "2" (shift) suffix.  This
2565              * check warns about unnecessary use of extensions for this quirk.
2566              */
2567             for (j = 0; given[j].keycode; ++j) {
2568                 const char *find = given[j].name;
2569                 int value;
2570                 char ch;
2571
2572                 if (!VALID_STRING(given[j].value))
2573                     continue;
2574
2575                 for (k = 0; table[k].xcurses; ++k) {
2576                     const char *test = table[k].xcurses;
2577                     size_t size = strlen(test);
2578
2579                     if (!strncmp(find, test, size) && strcmp(find, test)) {
2580                         switch (sscanf(find + size, "%d%c", &value, &ch)) {
2581                         case 1:
2582                             if (value == 2) {
2583                                 _nc_warning("expected '%s' rather than '%s'",
2584                                             (table[k].shifted
2585                                              ? table[k].shifted
2586                                              : test), find);
2587                             } else if (value < 2 || value > 15) {
2588                                 _nc_warning("expected numeric 2..15 '%s'", find);
2589                             }
2590                             break;
2591                         default:
2592                             _nc_warning("expected numeric suffix for '%s'", find);
2593                             break;
2594                         }
2595                         break;
2596                     }
2597                 }
2598             }
2599         }
2600 #endif
2601         free(given);
2602         free(check);
2603     }
2604 }
2605
2606 /*
2607  * Exiting a video mode should not duplicate sgr0
2608  */
2609 static void
2610 check_exit_attribute(const char *name, char *test, char *trimmed, char *untrimmed)
2611 {
2612     if (VALID_STRING(test) && (trimmed != 0)) {
2613         if (similar_sgr(-1, trimmed, test) ||
2614             similar_sgr(-1, untrimmed, test)) {
2615             _nc_warning("%s matches exit_attribute_mode", name);
2616         }
2617     }
2618 }
2619
2620 /*
2621  * Returns true if the string looks like a standard SGR string.
2622  */
2623 static bool
2624 is_sgr_string(char *value)
2625 {
2626     bool result = FALSE;
2627
2628     if (VALID_STRING(value)) {
2629         int skip = csi_length(value);
2630
2631         if (skip) {
2632             int ch;
2633
2634             result = TRUE;
2635             value += skip;
2636             while ((ch = UChar(*value++)) != '\0') {
2637                 if (isdigit(ch) || ch == ';') {
2638                     ;
2639                 } else if (ch == 'm' && *value == '\0') {
2640                     ;
2641                 } else {
2642                     result = FALSE;
2643                     break;
2644                 }
2645             }
2646         }
2647     }
2648     return result;
2649 }
2650
2651 /*
2652  * Check if the given capability contains a given SGR attribute.
2653  */
2654 static void
2655 check_sgr_param(TERMTYPE2 *tp, int code, const char *name, char *value)
2656 {
2657     if (VALID_STRING(value)) {
2658         int ncv = ((code != 0) ? (1 << (code - 1)) : 0);
2659         char *test = tgoto(value, 0, 0);
2660         if (is_sgr_string(test)) {
2661             int param = 0;
2662             int count = 0;
2663             int skips = 0;
2664             int color = (value == set_a_foreground ||
2665                          value == set_a_background ||
2666                          value == set_foreground ||
2667                          value == set_background);
2668             while (*test != 0) {
2669                 if (isdigit(UChar(*test))) {
2670                     param = 10 * param + (*test - '0');
2671                     ++count;
2672                 } else {
2673                     if (count) {
2674                         /*
2675                          * Avoid unnecessary warning for xterm 256color codes.
2676                          */
2677                         if (color && (param == 38 || param == 48))
2678                             skips = 3;
2679                         if ((skips-- <= 0) && (param == code))
2680                             break;
2681                     }
2682                     count = 0;
2683                     param = 0;
2684                 }
2685                 ++test;
2686             }
2687             if (count != 0 && param == code) {
2688                 if (code == 0 ||
2689                     no_color_video < 0 ||
2690                     !(no_color_video & ncv)) {
2691                     _nc_warning("\"%s\" SGR-attribute used in %s",
2692                                 sgr_names[code],
2693                                 name);
2694                 }
2695             }
2696         }
2697     }
2698 }
2699
2700 /* other sanity-checks (things that we don't want in the normal
2701  * logic that reads a terminfo entry)
2702  */
2703 static void
2704 check_termtype(TERMTYPE2 *tp, bool literal)
2705 {
2706     unsigned j;
2707
2708     check_conflict(tp);
2709
2710     for_each_string(j, tp) {
2711         char *a = tp->Strings[j];
2712         if (VALID_STRING(a)) {
2713             const char *name = ExtStrname(tp, (int) j, strnames);
2714             /*
2715              * If we expect parameters, or if there might be parameters,
2716              * check for consistent number of parameters.
2717              */
2718             if (j >= SIZEOF(parametrized) ||
2719                 is_user_capability(name) > 0 ||
2720                 parametrized[j] > 0) {
2721                 check_params(tp, name, a, (j >= STRCOUNT));
2722             }
2723             check_delays(tp, ExtStrname(tp, (int) j, strnames), a);
2724             if (capdump) {
2725                 check_infotocap(tp, (int) j, a);
2726             }
2727         }
2728     }
2729
2730     check_acs(tp);
2731     check_colors(tp);
2732     check_cursor(tp);
2733     check_keypad(tp);
2734     check_printer(tp);
2735     check_screen(tp);
2736
2737     /*
2738      * These may be mismatched because the terminal description relies on
2739      * restoring the cursor visibility by resetting it.
2740      */
2741     ANDMISSING(cursor_invisible, cursor_normal);
2742     ANDMISSING(cursor_visible, cursor_normal);
2743
2744     if (PRESENT(cursor_visible) && PRESENT(cursor_normal)
2745         && !_nc_capcmp(cursor_visible, cursor_normal))
2746         _nc_warning("cursor_visible is same as cursor_normal");
2747
2748     /*
2749      * From XSI & O'Reilly, we gather that sc/rc are required if csr is
2750      * given, because the cursor position after the scrolling operation is
2751      * performed is undefined.
2752      */
2753     ANDMISSING(change_scroll_region, save_cursor);
2754     ANDMISSING(change_scroll_region, restore_cursor);
2755
2756     /*
2757      * If we can clear tabs, we should be able to initialize them.
2758      */
2759     ANDMISSING(clear_all_tabs, set_tab);
2760
2761     if (PRESENT(set_attributes)) {
2762         char *zero = 0;
2763
2764         _nc_tparm_err = 0;
2765         if (PRESENT(exit_attribute_mode)) {
2766             zero = strdup(CHECK_SGR(0, exit_attribute_mode));
2767         } else {
2768             zero = strdup(TPARM_9(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, 0));
2769         }
2770         if (_nc_tparm_err)
2771             _nc_warning("stack error in sgr(0) string");
2772
2773         if (zero != 0) {
2774             CHECK_SGR(1, enter_standout_mode);
2775             CHECK_SGR(2, enter_underline_mode);
2776             CHECK_SGR(3, enter_reverse_mode);
2777             CHECK_SGR(4, enter_blink_mode);
2778             CHECK_SGR(5, enter_dim_mode);
2779             CHECK_SGR(6, enter_bold_mode);
2780             CHECK_SGR(7, enter_secure_mode);
2781             CHECK_SGR(8, enter_protected_mode);
2782             CHECK_SGR(9, enter_alt_charset_mode);
2783             free(zero);
2784         } else {
2785             _nc_warning("sgr(0) did not return a value");
2786         }
2787     } else if (PRESENT(exit_attribute_mode) &&
2788                set_attributes != CANCELLED_STRING) {
2789         if (_nc_syntax == SYN_TERMINFO)
2790             _nc_warning("missing sgr string");
2791     }
2792 #define CHECK_SGR0(name) check_exit_attribute(#name, name, check_sgr0, exit_attribute_mode)
2793     if (PRESENT(exit_attribute_mode)) {
2794         char *check_sgr0 = _nc_trim_sgr0(tp);
2795
2796         if (check_sgr0 == 0 || *check_sgr0 == '\0') {
2797             _nc_warning("trimmed sgr0 is empty");
2798         } else {
2799             show_where(2);
2800             if (check_sgr0 != exit_attribute_mode) {
2801                 DEBUG(2,
2802                       ("will trim sgr0\n\toriginal sgr0=%s\n\ttrimmed  sgr0=%s",
2803                        _nc_visbuf2(1, exit_attribute_mode),
2804                        _nc_visbuf2(2, check_sgr0)));
2805             } else {
2806                 DEBUG(2,
2807                       ("will not trim sgr0\n\toriginal sgr0=%s",
2808                        _nc_visbuf(exit_attribute_mode)));
2809             }
2810         }
2811 #if defined(exit_italics_mode)
2812         CHECK_SGR0(exit_italics_mode);
2813 #endif
2814         CHECK_SGR0(exit_standout_mode);
2815         CHECK_SGR0(exit_underline_mode);
2816         if (check_sgr0 != exit_attribute_mode) {
2817             free(check_sgr0);
2818         }
2819     }
2820 #define CHECK_SGR_PARAM(code, name) check_sgr_param(tp, (int)code, #name, name)
2821     for (j = 0; *sgr_names[j] != '\0'; ++j) {
2822         CHECK_SGR_PARAM(j, set_a_foreground);
2823         CHECK_SGR_PARAM(j, set_a_background);
2824         CHECK_SGR_PARAM(j, set_foreground);
2825         CHECK_SGR_PARAM(j, set_background);
2826     }
2827 #ifdef TRACE
2828     show_where(2);
2829     if (!auto_right_margin) {
2830         DEBUG(2,
2831               ("can write to lower-right directly"));
2832     } else if (PRESENT(enter_am_mode) && PRESENT(exit_am_mode)) {
2833         DEBUG(2,
2834               ("can write to lower-right by suppressing automargin"));
2835     } else if ((PRESENT(enter_insert_mode) && PRESENT(exit_insert_mode))
2836                || PRESENT(insert_character) || PRESENT(parm_ich)) {
2837         DEBUG(2,
2838               ("can write to lower-right by using inserts"));
2839     } else {
2840         DEBUG(2,
2841               ("cannot write to lower-right"));
2842     }
2843 #endif
2844
2845     /*
2846      * Some standard applications (e.g., vi) and some non-curses
2847      * applications (e.g., jove) get confused if we have both ich1 and
2848      * smir/rmir.  Let's be nice and warn about that, too, even though
2849      * ncurses handles it.
2850      */
2851     if ((PRESENT(enter_insert_mode) || PRESENT(exit_insert_mode))
2852         && PRESENT(parm_ich)) {
2853         _nc_warning("non-curses applications may be confused by ich1 with smir/rmir");
2854     }
2855
2856     /*
2857      * Finally, do the non-verbose checks
2858      */
2859     if (save_check_termtype != 0)
2860         save_check_termtype(tp, literal);
2861 }