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