]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/dump_entry.c
ncurses 6.0 - patch 20151101
[ncurses.git] / progs / dump_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2014,2015 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996 on                 *
33  ****************************************************************************/
34
35 #define __INTERNAL_CAPS_VISIBLE
36 #include <progs.priv.h>
37
38 #include "dump_entry.h"
39 #include "termsort.c"           /* this C file is generated */
40 #include <parametrized.h>       /* so is this */
41
42 MODULE_ID("$Id: dump_entry.c,v 1.123 2015/09/05 23:31:12 tom Exp $")
43
44 #define DISCARD(string) string = ABSENT_STRING
45 #define PRINTF (void) printf
46
47 #define OkIndex(index,array) ((int)(index) >= 0 && (int)(index) < (int) SIZEOF(array))
48
49 typedef struct {
50     char *text;
51     size_t used;
52     size_t size;
53 } DYNBUF;
54
55 static int tversion;            /* terminfo version */
56 static int outform;             /* output format to use */
57 static int sortmode;            /* sort mode to use */
58 static int width = 60;          /* max line width for listings */
59 static int height = 65535;      /* max number of lines for listings */
60 static int column;              /* current column, limited by 'width' */
61 static int oldcol;              /* last value of column before wrap */
62 static bool pretty;             /* true if we format if-then-else strings */
63 static bool checking;           /* true if we are checking for tic */
64 static int quickdump;           /* true if we are dumping compiled data */
65
66 static char *save_sgr;
67
68 static DYNBUF outbuf;
69 static DYNBUF tmpbuf;
70
71 /* indirection pointers for implementing sort and display modes */
72 static const PredIdx *bool_indirect, *num_indirect, *str_indirect;
73 static NCURSES_CONST char *const *bool_names;
74 static NCURSES_CONST char *const *num_names;
75 static NCURSES_CONST char *const *str_names;
76
77 static const char *separator = "", *trailer = "";
78 static int indent = 8;
79
80 /* cover various ports and variants of terminfo */
81 #define V_ALLCAPS       0       /* all capabilities (SVr4, XSI, ncurses) */
82 #define V_SVR1          1       /* SVR1, Ultrix */
83 #define V_HPUX          2       /* HP/UX */
84 #define V_AIX           3       /* AIX */
85 #define V_BSD           4       /* BSD */
86
87 #if NCURSES_XNAMES
88 #define OBSOLETE(n) (!_nc_user_definable && (n[0] == 'O' && n[1] == 'T'))
89 #else
90 #define OBSOLETE(n) (n[0] == 'O' && n[1] == 'T')
91 #endif
92
93 #define isObsolete(f,n) ((f == F_TERMINFO || f == F_VARIABLE) && OBSOLETE(n))
94
95 #if NCURSES_XNAMES
96 #define BoolIndirect(j) ((j >= BOOLCOUNT) ? (j) : ((sortmode == S_NOSORT) ? j : bool_indirect[j]))
97 #define NumIndirect(j)  ((j >= NUMCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : num_indirect[j]))
98 #define StrIndirect(j)  ((j >= STRCOUNT)  ? (j) : ((sortmode == S_NOSORT) ? j : str_indirect[j]))
99 #else
100 #define BoolIndirect(j) ((sortmode == S_NOSORT) ? (j) : bool_indirect[j])
101 #define NumIndirect(j)  ((sortmode == S_NOSORT) ? (j) : num_indirect[j])
102 #define StrIndirect(j)  ((sortmode == S_NOSORT) ? (j) : str_indirect[j])
103 #endif
104
105 static void failed(const char *) GCC_NORETURN;
106
107 static void
108 failed(const char *s)
109 {
110     perror(s);
111     ExitProgram(EXIT_FAILURE);
112 }
113
114 static void
115 strncpy_DYN(DYNBUF * dst, const char *src, size_t need)
116 {
117     size_t want = need + dst->used + 1;
118     if (want > dst->size) {
119         dst->size += (want + 1024);     /* be generous */
120         dst->text = typeRealloc(char, dst->size, dst->text);
121         if (dst->text == 0)
122             failed("strncpy_DYN");
123     }
124     (void) strncpy(dst->text + dst->used, src, need);
125     dst->used += need;
126     dst->text[dst->used] = 0;
127 }
128
129 static void
130 strcpy_DYN(DYNBUF * dst, const char *src)
131 {
132     if (src == 0) {
133         dst->used = 0;
134         strcpy_DYN(dst, "");
135     } else {
136         strncpy_DYN(dst, src, strlen(src));
137     }
138 }
139
140 #if NO_LEAKS
141 static void
142 free_DYN(DYNBUF * p)
143 {
144     if (p->text != 0)
145         free(p->text);
146     p->text = 0;
147     p->size = 0;
148     p->used = 0;
149 }
150
151 void
152 _nc_leaks_dump_entry(void)
153 {
154     free_DYN(&outbuf);
155     free_DYN(&tmpbuf);
156 }
157 #endif
158
159 #define NameTrans(check,result) \
160             if ((np->nte_index <= OK_ ## check) \
161                 && check[np->nte_index]) \
162                 return (result[np->nte_index])
163
164 NCURSES_CONST char *
165 nametrans(const char *name)
166 /* translate a capability name to termcap from terminfo */
167 {
168     const struct name_table_entry *np;
169
170     if ((np = _nc_find_entry(name, _nc_get_hash_table(0))) != 0) {
171         switch (np->nte_type) {
172         case BOOLEAN:
173             NameTrans(bool_from_termcap, boolcodes);
174             break;
175
176         case NUMBER:
177             NameTrans(num_from_termcap, numcodes);
178             break;
179
180         case STRING:
181             NameTrans(str_from_termcap, strcodes);
182             break;
183         }
184     }
185
186     return (0);
187 }
188
189 void
190 dump_init(const char *version,
191           int mode,
192           int sort,
193           int twidth,
194           int theight,
195           unsigned traceval,
196           bool formatted,
197           bool check,
198           int quick)
199 /* set up for entry display */
200 {
201     width = twidth;
202     height = theight;
203     pretty = formatted;
204     checking = check;
205     quickdump = (quick & 3);
206
207     /* versions */
208     if (version == 0)
209         tversion = V_ALLCAPS;
210     else if (!strcmp(version, "SVr1") || !strcmp(version, "SVR1")
211              || !strcmp(version, "Ultrix"))
212         tversion = V_SVR1;
213     else if (!strcmp(version, "HP"))
214         tversion = V_HPUX;
215     else if (!strcmp(version, "AIX"))
216         tversion = V_AIX;
217     else if (!strcmp(version, "BSD"))
218         tversion = V_BSD;
219     else
220         tversion = V_ALLCAPS;
221
222     /* implement display modes */
223     switch (outform = mode) {
224     case F_LITERAL:
225     case F_TERMINFO:
226         bool_names = boolnames;
227         num_names = numnames;
228         str_names = strnames;
229         separator = (twidth > 0 && theight > 1) ? ", " : ",";
230         trailer = "\n\t";
231         break;
232
233     case F_VARIABLE:
234         bool_names = boolfnames;
235         num_names = numfnames;
236         str_names = strfnames;
237         separator = (twidth > 0 && theight > 1) ? ", " : ",";
238         trailer = "\n\t";
239         break;
240
241     case F_TERMCAP:
242     case F_TCONVERR:
243         bool_names = boolcodes;
244         num_names = numcodes;
245         str_names = strcodes;
246         separator = ":";
247         trailer = "\\\n\t:";
248         break;
249     }
250     indent = 8;
251
252     /* implement sort modes */
253     switch (sortmode = sort) {
254     case S_NOSORT:
255         if (traceval)
256             (void) fprintf(stderr,
257                            "%s: sorting by term structure order\n", _nc_progname);
258         break;
259
260     case S_TERMINFO:
261         if (traceval)
262             (void) fprintf(stderr,
263                            "%s: sorting by terminfo name order\n", _nc_progname);
264         bool_indirect = bool_terminfo_sort;
265         num_indirect = num_terminfo_sort;
266         str_indirect = str_terminfo_sort;
267         break;
268
269     case S_VARIABLE:
270         if (traceval)
271             (void) fprintf(stderr,
272                            "%s: sorting by C variable order\n", _nc_progname);
273         bool_indirect = bool_variable_sort;
274         num_indirect = num_variable_sort;
275         str_indirect = str_variable_sort;
276         break;
277
278     case S_TERMCAP:
279         if (traceval)
280             (void) fprintf(stderr,
281                            "%s: sorting by termcap name order\n", _nc_progname);
282         bool_indirect = bool_termcap_sort;
283         num_indirect = num_termcap_sort;
284         str_indirect = str_termcap_sort;
285         break;
286     }
287
288     if (traceval)
289         (void) fprintf(stderr,
290                        "%s: width = %d, tversion = %d, outform = %d\n",
291                        _nc_progname, width, tversion, outform);
292 }
293
294 static TERMTYPE *cur_type;
295
296 static int
297 dump_predicate(PredType type, PredIdx idx)
298 /* predicate function to use for ordinary decompilation */
299 {
300     switch (type) {
301     case BOOLEAN:
302         return (cur_type->Booleans[idx] == FALSE)
303             ? FAIL : cur_type->Booleans[idx];
304
305     case NUMBER:
306         return (cur_type->Numbers[idx] == ABSENT_NUMERIC)
307             ? FAIL : cur_type->Numbers[idx];
308
309     case STRING:
310         return (cur_type->Strings[idx] != ABSENT_STRING)
311             ? (int) TRUE : FAIL;
312     }
313
314     return (FALSE);             /* pacify compiler */
315 }
316
317 static void set_obsolete_termcaps(TERMTYPE *tp);
318
319 /* is this the index of a function key string? */
320 #define FNKEY(i) \
321     (((i) >= STR_IDX(key_f0) && \
322       (i) <= STR_IDX(key_f9)) || \
323      ((i) >= STR_IDX(key_f11) && \
324       (i) <= STR_IDX(key_f63)))
325
326 /*
327  * If we configure with a different Caps file, the offsets into the arrays
328  * will change.  So we use an address expression.
329  */
330 #define BOOL_IDX(name) (PredType) (&(name) - &(CUR Booleans[0]))
331 #define NUM_IDX(name)  (PredType) (&(name) - &(CUR Numbers[0]))
332 #define STR_IDX(name)  (PredType) (&(name) - &(CUR Strings[0]))
333
334 static bool
335 version_filter(PredType type, PredIdx idx)
336 /* filter out capabilities we may want to suppress */
337 {
338     switch (tversion) {
339     case V_ALLCAPS:             /* SVr4, XSI Curses */
340         return (TRUE);
341
342     case V_SVR1:                /* System V Release 1, Ultrix */
343         switch (type) {
344         case BOOLEAN:
345             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
346         case NUMBER:
347             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
348         case STRING:
349             return ((idx <= STR_IDX(prtr_non)) ? TRUE : FALSE);
350         }
351         break;
352
353     case V_HPUX:                /* Hewlett-Packard */
354         switch (type) {
355         case BOOLEAN:
356             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
357         case NUMBER:
358             return ((idx <= NUM_IDX(label_width)) ? TRUE : FALSE);
359         case STRING:
360             if (idx <= STR_IDX(prtr_non))
361                 return (TRUE);
362             else if (FNKEY(idx))        /* function keys */
363                 return (TRUE);
364             else if (idx == STR_IDX(plab_norm)
365                      || idx == STR_IDX(label_on)
366                      || idx == STR_IDX(label_off))
367                 return (TRUE);
368             else
369                 return (FALSE);
370         }
371         break;
372
373     case V_AIX:         /* AIX */
374         switch (type) {
375         case BOOLEAN:
376             return ((idx <= BOOL_IDX(xon_xoff)) ? TRUE : FALSE);
377         case NUMBER:
378             return ((idx <= NUM_IDX(width_status_line)) ? TRUE : FALSE);
379         case STRING:
380             if (idx <= STR_IDX(prtr_non))
381                 return (TRUE);
382             else if (FNKEY(idx))        /* function keys */
383                 return (TRUE);
384             else
385                 return (FALSE);
386         }
387         break;
388
389 #define is_termcap(type) (OkIndex(idx, type##_from_termcap) && \
390                           type##_from_termcap[idx])
391
392     case V_BSD:         /* BSD */
393         switch (type) {
394         case BOOLEAN:
395             return is_termcap(bool);
396         case NUMBER:
397             return is_termcap(num);
398         case STRING:
399             return is_termcap(str);
400         }
401         break;
402     }
403
404     return (FALSE);             /* pacify the compiler */
405 }
406
407 static void
408 trim_trailing(void)
409 {
410     while (outbuf.used > 0 && outbuf.text[outbuf.used - 1] == ' ')
411         outbuf.text[--outbuf.used] = '\0';
412 }
413
414 static void
415 force_wrap(void)
416 {
417     oldcol = column;
418     trim_trailing();
419     strcpy_DYN(&outbuf, trailer);
420     column = indent;
421 }
422
423 static void
424 wrap_concat(const char *src)
425 {
426     size_t need = strlen(src);
427     size_t want = strlen(separator) + need;
428
429     if (column > indent
430         && column + (int) want > width) {
431         force_wrap();
432     }
433     strcpy_DYN(&outbuf, src);
434     strcpy_DYN(&outbuf, separator);
435     column += (int) need;
436 }
437
438 #define IGNORE_SEP_TRAIL(first,last,sep_trail) \
439         if ((size_t)(last - first) > sizeof(sep_trail)-1 \
440          && !strncmp(first, sep_trail, sizeof(sep_trail)-1)) \
441                 first += sizeof(sep_trail)-2
442
443 /* Returns the nominal length of the buffer assuming it is termcap format,
444  * i.e., the continuation sequence is treated as a single character ":".
445  *
446  * There are several implementations of termcap which read the text into a
447  * fixed-size buffer.  Generally they strip the newlines from the text, but may
448  * not do it until after the buffer is read.  Also, "tc=" resolution may be
449  * expanded in the same buffer.  This function is useful for measuring the size
450  * of the best fixed-buffer implementation; the worst case may be much worse.
451  */
452 #ifdef TEST_TERMCAP_LENGTH
453 static int
454 termcap_length(const char *src)
455 {
456     static const char pattern[] = ":\\\n\t:";
457
458     int len = 0;
459     const char *const t = src + strlen(src);
460
461     while (*src != '\0') {
462         IGNORE_SEP_TRAIL(src, t, pattern);
463         src++;
464         len++;
465     }
466     return len;
467 }
468 #else
469 #define termcap_length(src) strlen(src)
470 #endif
471
472 static void
473 indent_DYN(DYNBUF * buffer, int level)
474 {
475     int n;
476
477     for (n = 0; n < level; n++)
478         strncpy_DYN(buffer, "\t", (size_t) 1);
479 }
480
481 bool
482 has_params(const char *src)
483 {
484     bool result = FALSE;
485     int len = (int) strlen(src);
486     int n;
487     bool ifthen = FALSE;
488     bool params = FALSE;
489
490     for (n = 0; n < len - 1; ++n) {
491         if (!strncmp(src + n, "%p", (size_t) 2)) {
492             params = TRUE;
493         } else if (!strncmp(src + n, "%;", (size_t) 2)) {
494             ifthen = TRUE;
495             result = params;
496             break;
497         }
498     }
499     if (!ifthen) {
500         result = ((len > 50) && params);
501     }
502     return result;
503 }
504
505 static char *
506 fmt_complex(TERMTYPE *tterm, const char *capability, char *src, int level)
507 {
508     bool percent = FALSE;
509     bool params = has_params(src);
510
511     while (*src != '\0') {
512         switch (*src) {
513         case '\\':
514             percent = FALSE;
515             strncpy_DYN(&tmpbuf, src++, (size_t) 1);
516             break;
517         case '%':
518             percent = TRUE;
519             break;
520         case '?':               /* "if" */
521         case 't':               /* "then" */
522         case 'e':               /* "else" */
523             if (percent) {
524                 percent = FALSE;
525                 tmpbuf.text[tmpbuf.used - 1] = '\n';
526                 /* treat a "%e" as else-if, on the same level */
527                 if (*src == 'e') {
528                     indent_DYN(&tmpbuf, level);
529                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
530                     strncpy_DYN(&tmpbuf, src, (size_t) 1);
531                     src++;
532                     params = has_params(src);
533                     if (!params && *src != '\0' && *src != '%') {
534                         strncpy_DYN(&tmpbuf, "\n", (size_t) 1);
535                         indent_DYN(&tmpbuf, level + 1);
536                     }
537                 } else {
538                     indent_DYN(&tmpbuf, level + 1);
539                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
540                     strncpy_DYN(&tmpbuf, src, (size_t) 1);
541                     if (*src++ == '?') {
542                         src = fmt_complex(tterm, capability, src, level + 1);
543                         if (*src != '\0' && *src != '%') {
544                             strncpy_DYN(&tmpbuf, "\n", (size_t) 1);
545                             indent_DYN(&tmpbuf, level + 1);
546                         }
547                     } else if (level == 1) {
548                         if (checking)
549                             _nc_warning("%s: %%%c without %%? in %s",
550                                         _nc_first_name(tterm->term_names),
551                                         *src, capability);
552                     }
553                 }
554                 continue;
555             }
556             break;
557         case ';':               /* "endif" */
558             if (percent) {
559                 percent = FALSE;
560                 if (level > 1) {
561                     tmpbuf.text[tmpbuf.used - 1] = '\n';
562                     indent_DYN(&tmpbuf, level);
563                     strncpy_DYN(&tmpbuf, "%", (size_t) 1);
564                     strncpy_DYN(&tmpbuf, src++, (size_t) 1);
565                     if (src[0] == '%'
566                         && src[1] != '\0'
567                         && (strchr("?e;", src[1])) == 0) {
568                         tmpbuf.text[tmpbuf.used++] = '\n';
569                         indent_DYN(&tmpbuf, level);
570                     }
571                     return src;
572                 }
573                 if (checking)
574                     _nc_warning("%s: %%; without %%? in %s",
575                                 _nc_first_name(tterm->term_names),
576                                 capability);
577             }
578             break;
579         case 'p':
580             if (percent && params) {
581                 tmpbuf.text[tmpbuf.used - 1] = '\n';
582                 indent_DYN(&tmpbuf, level + 1);
583                 strncpy_DYN(&tmpbuf, "%", (size_t) 1);
584             }
585             params = FALSE;
586             percent = FALSE;
587             break;
588         case ' ':
589             strncpy_DYN(&tmpbuf, "\\s", (size_t) 2);
590             ++src;
591             continue;
592         default:
593             percent = FALSE;
594             break;
595         }
596         strncpy_DYN(&tmpbuf, src++, (size_t) 1);
597     }
598     return src;
599 }
600
601 #define SAME_CAP(n,cap) (&tterm->Strings[n] == &cap)
602 #define EXTRA_CAP 20
603
604 int
605 fmt_entry(TERMTYPE *tterm,
606           PredFunc pred,
607           int content_only,
608           int suppress_untranslatable,
609           int infodump,
610           int numbers)
611 {
612     PredIdx i, j;
613     char buffer[MAX_TERMINFO_LENGTH + EXTRA_CAP];
614     char *capability;
615     NCURSES_CONST char *name;
616     int predval, len;
617     PredIdx num_bools = 0;
618     PredIdx num_values = 0;
619     PredIdx num_strings = 0;
620     bool outcount = 0;
621
622 #define WRAP_CONCAT     \
623         wrap_concat(buffer); \
624         outcount = TRUE
625
626     len = 12;                   /* terminfo file-header */
627
628     if (pred == 0) {
629         cur_type = tterm;
630         pred = dump_predicate;
631     }
632
633     strcpy_DYN(&outbuf, 0);
634     if (content_only) {
635         column = indent;        /* FIXME: workaround to prevent empty lines */
636     } else {
637         strcpy_DYN(&outbuf, tterm->term_names);
638
639         /*
640          * Colon is legal in terminfo descriptions, but not in termcap.
641          */
642         if (!infodump) {
643             char *p = outbuf.text;
644             while (*p) {
645                 if (*p == ':') {
646                     *p = '=';
647                 }
648                 ++p;
649             }
650         }
651         strcpy_DYN(&outbuf, separator);
652         column = (int) outbuf.used;
653         if (height > 1)
654             force_wrap();
655     }
656
657     for_each_boolean(j, tterm) {
658         i = BoolIndirect(j);
659         name = ExtBoolname(tterm, (int) i, bool_names);
660         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
661
662         if (!version_filter(BOOLEAN, i))
663             continue;
664         else if (isObsolete(outform, name))
665             continue;
666
667         predval = pred(BOOLEAN, i);
668         if (predval != FAIL) {
669             _nc_STRCPY(buffer, name, sizeof(buffer));
670             if (predval <= 0)
671                 _nc_STRCAT(buffer, "@", sizeof(buffer));
672             else if (i + 1 > num_bools)
673                 num_bools = i + 1;
674             WRAP_CONCAT;
675         }
676     }
677
678     if (column != indent && height > 1)
679         force_wrap();
680
681     for_each_number(j, tterm) {
682         i = NumIndirect(j);
683         name = ExtNumname(tterm, (int) i, num_names);
684         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
685
686         if (!version_filter(NUMBER, i))
687             continue;
688         else if (isObsolete(outform, name))
689             continue;
690
691         predval = pred(NUMBER, i);
692         if (predval != FAIL) {
693             if (tterm->Numbers[i] < 0) {
694                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
695                             "%s@", name);
696             } else {
697                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
698                             "%s#%d", name, tterm->Numbers[i]);
699                 if (i + 1 > num_values)
700                     num_values = i + 1;
701             }
702             WRAP_CONCAT;
703         }
704     }
705
706     if (column != indent && height > 1)
707         force_wrap();
708
709     len += (int) (num_bools
710                   + num_values * 2
711                   + strlen(tterm->term_names) + 1);
712     if (len & 1)
713         len++;
714
715 #undef CUR
716 #define CUR tterm->
717     if (outform == F_TERMCAP) {
718         if (termcap_reset != ABSENT_STRING) {
719             if (init_3string != ABSENT_STRING
720                 && !strcmp(init_3string, termcap_reset))
721                 DISCARD(init_3string);
722
723             if (reset_2string != ABSENT_STRING
724                 && !strcmp(reset_2string, termcap_reset))
725                 DISCARD(reset_2string);
726         }
727     }
728
729     for_each_string(j, tterm) {
730         i = StrIndirect(j);
731         name = ExtStrname(tterm, (int) i, str_names);
732         assert(strlen(name) < sizeof(buffer) - EXTRA_CAP);
733
734         capability = tterm->Strings[i];
735
736         if (!version_filter(STRING, i))
737             continue;
738         else if (isObsolete(outform, name))
739             continue;
740
741 #if NCURSES_XNAMES
742         /*
743          * Extended names can be longer than 2 characters, but termcap programs
744          * cannot read those (filter them out).
745          */
746         if (outform == F_TERMCAP && (strlen(name) > 2))
747             continue;
748 #endif
749
750         if (outform == F_TERMCAP) {
751             /*
752              * Some older versions of vi want rmir/smir to be defined
753              * for ich/ich1 to work.  If they're not defined, force
754              * them to be output as defined and empty.
755              */
756             if (PRESENT(insert_character) || PRESENT(parm_ich)) {
757                 if (SAME_CAP(i, enter_insert_mode)
758                     && enter_insert_mode == ABSENT_STRING) {
759                     _nc_STRCPY(buffer, "im=", sizeof(buffer));
760                     WRAP_CONCAT;
761                     continue;
762                 }
763
764                 if (SAME_CAP(i, exit_insert_mode)
765                     && exit_insert_mode == ABSENT_STRING) {
766                     _nc_STRCPY(buffer, "ei=", sizeof(buffer));
767                     WRAP_CONCAT;
768                     continue;
769                 }
770             }
771             /*
772              * termcap applications such as screen will be confused if sgr0
773              * is translated to a string containing rmacs.  Filter that out.
774              */
775             if (PRESENT(exit_attribute_mode)) {
776                 if (SAME_CAP(i, exit_attribute_mode)) {
777                     char *trimmed_sgr0;
778                     char *my_sgr = set_attributes;
779
780                     set_attributes = save_sgr;
781
782                     trimmed_sgr0 = _nc_trim_sgr0(tterm);
783                     if (strcmp(capability, trimmed_sgr0))
784                         capability = trimmed_sgr0;
785                     else {
786                         if (trimmed_sgr0 != exit_attribute_mode)
787                             free(trimmed_sgr0);
788                     }
789
790                     set_attributes = my_sgr;
791                 }
792             }
793         }
794
795         predval = pred(STRING, i);
796         buffer[0] = '\0';
797
798         if (predval != FAIL) {
799             if (capability != ABSENT_STRING
800                 && i + 1 > num_strings)
801                 num_strings = i + 1;
802
803             if (!VALID_STRING(capability)) {
804                 _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
805                             "%s@", name);
806                 WRAP_CONCAT;
807             } else if (outform == F_TERMCAP || outform == F_TCONVERR) {
808                 char *srccap = _nc_tic_expand(capability, TRUE, numbers);
809                 int params = (((i < (int) SIZEOF(parametrized)) &&
810                                (i < STRCOUNT))
811                               ? parametrized[i]
812                               : ((*srccap == 'k')
813                                  ? 0
814                                  : has_params(srccap)));
815                 char *cv = _nc_infotocap(name, srccap, params);
816
817                 if (cv == 0) {
818                     if (outform == F_TCONVERR) {
819                         _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
820                                     "%s=!!! %s WILL NOT CONVERT !!!",
821                                     name, srccap);
822                     } else if (suppress_untranslatable) {
823                         continue;
824                     } else {
825                         char *s = srccap, *d = buffer;
826                         _nc_SPRINTF(d, _nc_SLIMIT(sizeof(buffer)) "..%s=", name);
827                         d += strlen(d);
828                         while ((*d = *s++) != 0) {
829                             if (*d == ':') {
830                                 *d++ = '\\';
831                                 *d = ':';
832                             } else if (*d == '\\') {
833                                 *++d = *s++;
834                             }
835                             d++;
836                         }
837                     }
838                 } else {
839                     _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
840                                 "%s=%s", name, cv);
841                 }
842                 len += (int) strlen(capability) + 1;
843                 WRAP_CONCAT;
844             } else {
845                 char *src = _nc_tic_expand(capability,
846                                            outform == F_TERMINFO, numbers);
847
848                 strcpy_DYN(&tmpbuf, 0);
849                 strcpy_DYN(&tmpbuf, name);
850                 strcpy_DYN(&tmpbuf, "=");
851                 if (pretty
852                     && (outform == F_TERMINFO
853                         || outform == F_VARIABLE)) {
854                     fmt_complex(tterm, name, src, 1);
855                 } else {
856                     strcpy_DYN(&tmpbuf, src);
857                 }
858                 len += (int) strlen(capability) + 1;
859                 wrap_concat(tmpbuf.text);
860                 outcount = TRUE;
861             }
862         }
863         /* e.g., trimmed_sgr0 */
864         if (capability != ABSENT_STRING &&
865             capability != CANCELLED_STRING &&
866             capability != tterm->Strings[i])
867             free(capability);
868     }
869     len += (int) (num_strings * 2);
870
871     /*
872      * This piece of code should be an effective inverse of the functions
873      * postprocess_terminfo() and postprocess_terminfo() in parse_entry.c.
874      * Much more work should be done on this to support dumping termcaps.
875      */
876     if (tversion == V_HPUX) {
877         if (VALID_STRING(memory_lock)) {
878             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
879                         "meml=%s", memory_lock);
880             WRAP_CONCAT;
881         }
882         if (VALID_STRING(memory_unlock)) {
883             _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
884                         "memu=%s", memory_unlock);
885             WRAP_CONCAT;
886         }
887     } else if (tversion == V_AIX) {
888         if (VALID_STRING(acs_chars)) {
889             bool box_ok = TRUE;
890             const char *acstrans = "lqkxjmwuvtn";
891             const char *cp;
892             char *tp, *sp, boxchars[11];
893
894             tp = boxchars;
895             for (cp = acstrans; *cp; cp++) {
896                 sp = (strchr) (acs_chars, *cp);
897                 if (sp)
898                     *tp++ = sp[1];
899                 else {
900                     box_ok = FALSE;
901                     break;
902                 }
903             }
904             tp[0] = '\0';
905
906             if (box_ok) {
907                 char *tmp = _nc_tic_expand(boxchars,
908                                            (outform == F_TERMINFO),
909                                            numbers);
910                 _nc_STRCPY(buffer, "box1=", sizeof(buffer));
911                 while (*tmp != '\0') {
912                     size_t have = strlen(buffer);
913                     size_t next = strlen(tmp);
914                     size_t want = have + next + 1;
915                     size_t last = next;
916                     char save = '\0';
917
918                     /*
919                      * If the expanded string is too long for the buffer,
920                      * chop it off and save the location where we chopped it.
921                      */
922                     if (want >= sizeof(buffer)) {
923                         save = tmp[last];
924                         tmp[last] = '\0';
925                     }
926                     _nc_STRCAT(buffer, tmp, sizeof(buffer));
927
928                     /*
929                      * If we chopped the buffer, replace the missing piece and
930                      * shift everything to append the remainder.
931                      */
932                     if (save != '\0') {
933                         next = 0;
934                         tmp[last] = save;
935                         while ((tmp[next] = tmp[last + next]) != '\0') {
936                             ++next;
937                         }
938                     } else {
939                         break;
940                     }
941                 }
942                 WRAP_CONCAT;
943             }
944         }
945     }
946
947     /*
948      * kludge: trim off trailer to avoid an extra blank line
949      * in infocmp -u output when there are no string differences
950      */
951     if (outcount) {
952         bool trimmed = FALSE;
953         j = (PredIdx) outbuf.used;
954         if (j >= 2
955             && outbuf.text[j - 1] == '\t'
956             && outbuf.text[j - 2] == '\n') {
957             outbuf.used -= 2;
958             trimmed = TRUE;
959         } else if (j >= 4
960                    && outbuf.text[j - 1] == ':'
961                    && outbuf.text[j - 2] == '\t'
962                    && outbuf.text[j - 3] == '\n'
963                    && outbuf.text[j - 4] == '\\') {
964             outbuf.used -= 4;
965             trimmed = TRUE;
966         }
967         if (trimmed) {
968             outbuf.text[outbuf.used] = '\0';
969             column = oldcol;
970             strcpy_DYN(&outbuf, " ");
971         }
972     }
973 #if 0
974     fprintf(stderr, "num_bools = %d\n", num_bools);
975     fprintf(stderr, "num_values = %d\n", num_values);
976     fprintf(stderr, "num_strings = %d\n", num_strings);
977     fprintf(stderr, "term_names=%s, len=%d, strlen(outbuf)=%d, outbuf=%s\n",
978             tterm->term_names, len, outbuf.used, outbuf.text);
979 #endif
980     /*
981      * Here's where we use infodump to trigger a more stringent length check
982      * for termcap-translation purposes.
983      * Return the length of the raw entry, without tc= expansions,
984      * It gives an idea of which entries are deadly to even *scan past*,
985      * as opposed to *use*.
986      */
987     return (infodump ? len : (int) termcap_length(outbuf.text));
988 }
989
990 static bool
991 kill_string(TERMTYPE *tterm, char *cap)
992 {
993     unsigned n;
994     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
995         if (cap == tterm->Strings[n]) {
996             tterm->Strings[n] = ABSENT_STRING;
997             return TRUE;
998         }
999     }
1000     return FALSE;
1001 }
1002
1003 static char *
1004 find_string(TERMTYPE *tterm, char *name)
1005 {
1006     PredIdx n;
1007     for (n = 0; n < NUM_STRINGS(tterm); ++n) {
1008         if (version_filter(STRING, n)
1009             && !strcmp(name, strnames[n])) {
1010             char *cap = tterm->Strings[n];
1011             if (VALID_STRING(cap)) {
1012                 return cap;
1013             }
1014             break;
1015         }
1016     }
1017     return ABSENT_STRING;
1018 }
1019
1020 /*
1021  * This is used to remove function-key labels from a termcap entry to
1022  * make it smaller.
1023  */
1024 static int
1025 kill_labels(TERMTYPE *tterm, int target)
1026 {
1027     int n;
1028     int result = 0;
1029     char *cap;
1030     char name[10];
1031
1032     for (n = 0; n <= 10; ++n) {
1033         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "lf%d", n);
1034         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1035             && kill_string(tterm, cap)) {
1036             target -= (int) (strlen(cap) + 5);
1037             ++result;
1038             if (target < 0)
1039                 break;
1040         }
1041     }
1042     return result;
1043 }
1044
1045 /*
1046  * This is used to remove function-key definitions from a termcap entry to
1047  * make it smaller.
1048  */
1049 static int
1050 kill_fkeys(TERMTYPE *tterm, int target)
1051 {
1052     int n;
1053     int result = 0;
1054     char *cap;
1055     char name[10];
1056
1057     for (n = 60; n >= 0; --n) {
1058         _nc_SPRINTF(name, _nc_SLIMIT(sizeof(name)) "kf%d", n);
1059         if ((cap = find_string(tterm, name)) != ABSENT_STRING
1060             && kill_string(tterm, cap)) {
1061             target -= (int) (strlen(cap) + 5);
1062             ++result;
1063             if (target < 0)
1064                 break;
1065         }
1066     }
1067     return result;
1068 }
1069
1070 /*
1071  * Check if the given acsc string is a 1-1 mapping, i.e., just-like-vt100.
1072  * Also, since this is for termcap, we only care about the line-drawing map.
1073  */
1074 #define isLine(c) (strchr("lmkjtuvwqxn", c) != 0)
1075
1076 static bool
1077 one_one_mapping(const char *mapping)
1078 {
1079     bool result = TRUE;
1080
1081     if (mapping != ABSENT_STRING) {
1082         int n = 0;
1083         while (mapping[n] != '\0') {
1084             if (isLine(mapping[n]) &&
1085                 mapping[n] != mapping[n + 1]) {
1086                 result = FALSE;
1087                 break;
1088             }
1089             n += 2;
1090         }
1091     }
1092     return result;
1093 }
1094
1095 #define FMT_ENTRY() \
1096                 fmt_entry(tterm, pred, \
1097                         0, \
1098                         suppress_untranslatable, \
1099                         infodump, numbers)
1100
1101 #define SHOW_WHY PRINTF
1102
1103 static bool
1104 purged_acs(TERMTYPE *tterm)
1105 {
1106     bool result = FALSE;
1107
1108     if (VALID_STRING(acs_chars)) {
1109         if (!one_one_mapping(acs_chars)) {
1110             enter_alt_charset_mode = ABSENT_STRING;
1111             exit_alt_charset_mode = ABSENT_STRING;
1112             SHOW_WHY("# (rmacs/smacs removed for consistency)\n");
1113         }
1114         result = TRUE;
1115     }
1116     return result;
1117 }
1118
1119 static void
1120 encode_b64(char *target, char *source, unsigned state, int *saved)
1121 {
1122     /* RFC-4648 */
1123     static const char data[] =
1124     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1125     "abcdefghijklmnopqrstuvwxyz"
1126     "0123456789" "-_";
1127     int ch = UChar(source[state]);
1128
1129     switch (state % 3) {
1130     case 0:
1131         *target++ = data[ch & 077];
1132         *saved = (ch >> 6) & 3;
1133         break;
1134     case 1:
1135         *target++ = data[((ch << 2) | *saved) & 077];
1136         *saved = (ch >> 4) & 017;
1137         break;
1138     case 2:
1139         *target++ = data[((ch << 4) | *saved) & 077];
1140         *target++ = data[(ch >> 2) & 077];
1141         *saved = 0;
1142         break;
1143     }
1144     *target = '\0';
1145 }
1146
1147 /*
1148  * Dump a single entry.
1149  */
1150 void
1151 dump_entry(TERMTYPE *tterm,
1152            int suppress_untranslatable,
1153            int limited,
1154            int numbers,
1155            PredFunc pred)
1156 {
1157     TERMTYPE save_tterm;
1158     int len, critlen;
1159     const char *legend;
1160     bool infodump;
1161
1162     if (quickdump) {
1163         char bigbuf[65536];
1164         unsigned n;
1165         unsigned offset = 0;
1166         separator = "";
1167         trailer = "\n";
1168         indent = 0;
1169         if (_nc_write_object(tterm, bigbuf, &offset, sizeof(bigbuf)) == OK) {
1170             char numbuf[80];
1171             if (quickdump & 1) {
1172                 if (outbuf.used)
1173                     wrap_concat("\n");
1174                 wrap_concat("hex:");
1175                 for (n = 0; n < offset; ++n) {
1176                     sprintf(numbuf, "%02X", UChar(bigbuf[n]));
1177                     wrap_concat(numbuf);
1178                 }
1179             }
1180             if (quickdump & 2) {
1181                 int value = 0;
1182                 if (outbuf.used)
1183                     wrap_concat("\n");
1184                 wrap_concat("b64:");
1185                 for (n = 0; n < offset; ++n) {
1186                     encode_b64(numbuf, bigbuf, n, &value);
1187                     wrap_concat(numbuf);
1188                 }
1189                 switch (n % 3) {
1190                 case 0:
1191                     break;
1192                 case 1:
1193                     wrap_concat("===");
1194                     break;
1195                 case 2:
1196                     wrap_concat("==");
1197                     break;
1198                 }
1199             }
1200         }
1201         return;
1202     }
1203
1204     if (outform == F_TERMCAP || outform == F_TCONVERR) {
1205         critlen = MAX_TERMCAP_LENGTH;
1206         legend = "older termcap";
1207         infodump = FALSE;
1208         set_obsolete_termcaps(tterm);
1209     } else {
1210         critlen = MAX_TERMINFO_LENGTH;
1211         legend = "terminfo";
1212         infodump = TRUE;
1213     }
1214
1215     save_sgr = set_attributes;
1216
1217     if ((FMT_ENTRY() > critlen)
1218         && limited) {
1219
1220         save_tterm = *tterm;
1221         if (!suppress_untranslatable) {
1222             SHOW_WHY("# (untranslatable capabilities removed to fit entry within %d bytes)\n",
1223                      critlen);
1224             suppress_untranslatable = TRUE;
1225         }
1226         if (FMT_ENTRY() > critlen) {
1227             /*
1228              * We pick on sgr because it's a nice long string capability that
1229              * is really just an optimization hack.  Another good candidate is
1230              * acsc since it is both long and unused by BSD termcap.
1231              */
1232             bool changed = FALSE;
1233
1234 #if NCURSES_XNAMES
1235             /*
1236              * Extended names are most likely function-key definitions.  Drop
1237              * those first.
1238              */
1239             unsigned n;
1240             for (n = STRCOUNT; n < NUM_STRINGS(tterm); n++) {
1241                 const char *name = ExtStrname(tterm, (int) n, strnames);
1242
1243                 if (VALID_STRING(tterm->Strings[n])) {
1244                     set_attributes = ABSENT_STRING;
1245                     /* we remove long names anyway - only report the short */
1246                     if (strlen(name) <= 2) {
1247                         SHOW_WHY("# (%s removed to fit entry within %d bytes)\n",
1248                                  name,
1249                                  critlen);
1250                     }
1251                     changed = TRUE;
1252                     if (FMT_ENTRY() <= critlen)
1253                         break;
1254                 }
1255             }
1256 #endif
1257             if (VALID_STRING(set_attributes)) {
1258                 set_attributes = ABSENT_STRING;
1259                 SHOW_WHY("# (sgr removed to fit entry within %d bytes)\n",
1260                          critlen);
1261                 changed = TRUE;
1262             }
1263             if (!changed || (FMT_ENTRY() > critlen)) {
1264                 if (purged_acs(tterm)) {
1265                     acs_chars = ABSENT_STRING;
1266                     SHOW_WHY("# (acsc removed to fit entry within %d bytes)\n",
1267                              critlen);
1268                     changed = TRUE;
1269                 }
1270             }
1271             if (!changed || (FMT_ENTRY() > critlen)) {
1272                 int oldversion = tversion;
1273
1274                 tversion = V_BSD;
1275                 SHOW_WHY("# (terminfo-only capabilities suppressed to fit entry within %d bytes)\n",
1276                          critlen);
1277
1278                 len = FMT_ENTRY();
1279                 if (len > critlen
1280                     && kill_labels(tterm, len - critlen)) {
1281                     SHOW_WHY("# (some labels capabilities suppressed to fit entry within %d bytes)\n",
1282                              critlen);
1283                     len = FMT_ENTRY();
1284                 }
1285                 if (len > critlen
1286                     && kill_fkeys(tterm, len - critlen)) {
1287                     SHOW_WHY("# (some function-key capabilities suppressed to fit entry within %d bytes)\n",
1288                              critlen);
1289                     len = FMT_ENTRY();
1290                 }
1291                 if (len > critlen) {
1292                     (void) fprintf(stderr,
1293                                    "warning: %s entry is %d bytes long\n",
1294                                    _nc_first_name(tterm->term_names),
1295                                    len);
1296                     SHOW_WHY("# WARNING: this entry, %d bytes long, may core-dump %s libraries!\n",
1297                              len, legend);
1298                 }
1299                 tversion = oldversion;
1300             }
1301             set_attributes = save_sgr;
1302             *tterm = save_tterm;
1303         }
1304     } else if (!version_filter(STRING, STR_IDX(acs_chars))) {
1305         save_tterm = *tterm;
1306         if (purged_acs(tterm)) {
1307             (void) FMT_ENTRY();
1308         }
1309         *tterm = save_tterm;
1310     }
1311 }
1312
1313 void
1314 dump_uses(const char *name, bool infodump)
1315 /* dump "use=" clauses in the appropriate format */
1316 {
1317     char buffer[MAX_TERMINFO_LENGTH];
1318
1319     if (outform == F_TERMCAP || outform == F_TCONVERR)
1320         trim_trailing();
1321     _nc_SPRINTF(buffer, _nc_SLIMIT(sizeof(buffer))
1322                 "%s%s", infodump ? "use=" : "tc=", name);
1323     wrap_concat(buffer);
1324 }
1325
1326 int
1327 show_entry(void)
1328 {
1329     /*
1330      * Trim any remaining whitespace.
1331      */
1332     if (outbuf.used != 0) {
1333         bool infodump = (outform != F_TERMCAP && outform != F_TCONVERR);
1334         char delim = (char) (infodump ? ',' : ':');
1335         int j;
1336
1337         for (j = (int) outbuf.used - 1; j > 0; --j) {
1338             char ch = outbuf.text[j];
1339             if (ch == '\n') {
1340                 ;
1341             } else if (isspace(UChar(ch))) {
1342                 outbuf.used = (size_t) j;
1343             } else if (!infodump && ch == '\\') {
1344                 outbuf.used = (size_t) j;
1345             } else if (ch == delim && (j == 0 || outbuf.text[j - 1] != '\\')) {
1346                 outbuf.used = (size_t) (j + 1);
1347             } else {
1348                 break;
1349             }
1350         }
1351         outbuf.text[outbuf.used] = '\0';
1352     }
1353     if (outbuf.text != 0) {
1354         (void) fputs(outbuf.text, stdout);
1355         putchar('\n');
1356     }
1357     return (int) outbuf.used;
1358 }
1359
1360 void
1361 compare_entry(PredHook hook,
1362               TERMTYPE *tp GCC_UNUSED,
1363               bool quiet)
1364 /* compare two entries */
1365 {
1366     PredIdx i, j;
1367     NCURSES_CONST char *name;
1368
1369     if (!quiet)
1370         fputs("    comparing booleans.\n", stdout);
1371     for_each_boolean(j, tp) {
1372         i = BoolIndirect(j);
1373         name = ExtBoolname(tp, (int) i, bool_names);
1374
1375         if (isObsolete(outform, name))
1376             continue;
1377
1378         (*hook) (CMP_BOOLEAN, i, name);
1379     }
1380
1381     if (!quiet)
1382         fputs("    comparing numbers.\n", stdout);
1383     for_each_number(j, tp) {
1384         i = NumIndirect(j);
1385         name = ExtNumname(tp, (int) i, num_names);
1386
1387         if (isObsolete(outform, name))
1388             continue;
1389
1390         (*hook) (CMP_NUMBER, i, name);
1391     }
1392
1393     if (!quiet)
1394         fputs("    comparing strings.\n", stdout);
1395     for_each_string(j, tp) {
1396         i = StrIndirect(j);
1397         name = ExtStrname(tp, (int) i, str_names);
1398
1399         if (isObsolete(outform, name))
1400             continue;
1401
1402         (*hook) (CMP_STRING, i, name);
1403     }
1404
1405     /* (void) fputs("    comparing use entries.\n", stdout); */
1406     (*hook) (CMP_USE, 0, "use");
1407
1408 }
1409
1410 #define NOTSET(s)       ((s) == 0)
1411
1412 /*
1413  * This bit of legerdemain turns all the terminfo variable names into
1414  * references to locations in the arrays Booleans, Numbers, and Strings ---
1415  * precisely what's needed.
1416  */
1417 #undef CUR
1418 #define CUR tp->
1419
1420 static void
1421 set_obsolete_termcaps(TERMTYPE *tp)
1422 {
1423 #include "capdefaults.c"
1424 }
1425
1426 /*
1427  * Convert an alternate-character-set string to canonical form: sorted and
1428  * unique.
1429  */
1430 void
1431 repair_acsc(TERMTYPE *tp)
1432 {
1433     if (VALID_STRING(acs_chars)) {
1434         size_t n, m;
1435         char mapped[256];
1436         char extra = 0;
1437         unsigned source;
1438         unsigned target;
1439         bool fix_needed = FALSE;
1440
1441         for (n = 0, source = 0; acs_chars[n] != 0; n++) {
1442             target = UChar(acs_chars[n]);
1443             if (source >= target) {
1444                 fix_needed = TRUE;
1445                 break;
1446             }
1447             source = target;
1448             if (acs_chars[n + 1])
1449                 n++;
1450         }
1451         if (fix_needed) {
1452             memset(mapped, 0, sizeof(mapped));
1453             for (n = 0; acs_chars[n] != 0; n++) {
1454                 source = UChar(acs_chars[n]);
1455                 if ((target = (unsigned char) acs_chars[n + 1]) != 0) {
1456                     mapped[source] = (char) target;
1457                     n++;
1458                 } else {
1459                     extra = (char) source;
1460                 }
1461             }
1462             for (n = m = 0; n < sizeof(mapped); n++) {
1463                 if (mapped[n]) {
1464                     acs_chars[m++] = (char) n;
1465                     acs_chars[m++] = mapped[n];
1466                 }
1467             }
1468             if (extra)
1469                 acs_chars[m++] = extra;         /* garbage in, garbage out */
1470             acs_chars[m] = 0;
1471         }
1472     }
1473 }