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