]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/write_entry.c
ncurses 6.0 - patch 20180121
[ncurses.git] / ncurses / tinfo / write_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2015,2017 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996-on                 *
33  ****************************************************************************/
34
35 /*
36  *      write_entry.c -- write a terminfo structure onto the file system
37  */
38
39 #include <curses.priv.h>
40 #include <hashed_db.h>
41
42 #include <tic.h>
43
44 #if 1
45 #define TRACE_OUT(p) DEBUG(2, p)
46 #define TRACE_NUM(n) if (VALID_NUMERIC(Numbers[n])) { \
47         TRACE_OUT(("put Numbers[%u]=%d", (unsigned) (n), Numbers[n])); }
48 #else
49 #define TRACE_OUT(p)            /*nothing */
50 #define TRACE_NUM(n)            /* nothing */
51 #endif
52
53 MODULE_ID("$Id: write_entry.c,v 1.101 2017/11/25 19:56:06 tom Exp $")
54
55 static int total_written;
56 static int total_parts;
57 static int total_size;
58
59 static int make_db_root(const char *);
60
61 #if !USE_HASHED_DB
62 static void
63 write_file(char *filename, TERMTYPE2 *tp)
64 {
65     char buffer[MAX_ENTRY_SIZE];
66     unsigned limit = sizeof(buffer);
67     unsigned offset = 0;
68
69     FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
70     if (fp == 0) {
71         perror(filename);
72         _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
73     }
74     DEBUG(1, ("Created %s", filename));
75
76     if (_nc_write_object(tp, buffer, &offset, limit) == ERR
77         || fwrite(buffer, sizeof(char), (size_t) offset, fp) != offset) {
78         _nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
79     }
80
81     fclose(fp);
82 }
83
84 /*
85  * Check for access rights to destination directories
86  * Create any directories which don't exist.
87  *
88  * Note:  there's no reason to return the result of make_db_root(), since
89  * this function is called only in instances where that has to succeed.
90  */
91 static void
92 check_writeable(int code)
93 {
94     static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
95     static bool verified[sizeof(dirnames)];
96
97     char dir[sizeof(LEAF_FMT)];
98     char *s = 0;
99
100     if (code == 0 || (s = (strchr) (dirnames, code)) == 0)
101         _nc_err_abort("Illegal terminfo subdirectory \"" LEAF_FMT "\"", code);
102
103     if (verified[s - dirnames])
104         return;
105
106     _nc_SPRINTF(dir, _nc_SLIMIT(sizeof(dir)) LEAF_FMT, code);
107     if (make_db_root(dir) < 0) {
108         _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
109     }
110
111     verified[s - dirnames] = TRUE;
112 }
113 #endif /* !USE_HASHED_DB */
114
115 static int
116 make_db_path(char *dst, const char *src, size_t limit)
117 {
118     int rc = -1;
119     const char *top = _nc_tic_dir(0);
120
121     if (src == top || _nc_is_abs_path(src)) {
122         if (strlen(src) + 1 <= limit) {
123             _nc_STRCPY(dst, src, limit);
124             rc = 0;
125         }
126     } else {
127         if (strlen(top) + strlen(src) + 2 <= limit) {
128             _nc_SPRINTF(dst, _nc_SLIMIT(limit) "%s/%s", top, src);
129             rc = 0;
130         }
131     }
132 #if USE_HASHED_DB
133     if (rc == 0) {
134         static const char suffix[] = DBM_SUFFIX;
135         size_t have = strlen(dst);
136         size_t need = strlen(suffix);
137         if (have > need && strcmp(dst + (int) (have - need), suffix)) {
138             if (have + need <= limit) {
139                 _nc_STRCAT(dst, suffix, limit);
140             } else {
141                 rc = -1;
142             }
143         } else if (_nc_is_dir_path(dst)) {
144             rc = -1;
145         }
146     }
147 #endif
148     return rc;
149 }
150
151 /*
152  * Make a database-root if it doesn't exist.
153  */
154 static int
155 make_db_root(const char *path)
156 {
157     int rc;
158     char fullpath[PATH_MAX];
159
160     if ((rc = make_db_path(fullpath, path, sizeof(fullpath))) == 0) {
161 #if USE_HASHED_DB
162         DB *capdbp;
163
164         if ((capdbp = _nc_db_open(fullpath, TRUE)) == NULL) {
165             rc = -1;
166         } else if (_nc_db_close(capdbp) < 0) {
167             rc = -1;
168         }
169 #else
170         struct stat statbuf;
171
172         if ((rc = stat(path, &statbuf)) < 0) {
173             rc = mkdir(path
174 #if !defined(__MINGW32__)
175                        ,0777
176 #endif
177                 );
178         } else if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
179             rc = -1;            /* permission denied */
180         } else if (!(S_ISDIR(statbuf.st_mode))) {
181             rc = -1;            /* not a directory */
182         }
183 #endif
184     }
185     return rc;
186 }
187
188 /*
189  * Set the write directory for compiled entries.
190  */
191 NCURSES_EXPORT(void)
192 _nc_set_writedir(const char *dir)
193 {
194     const char *destination;
195     char actual[PATH_MAX];
196
197     if (dir == 0
198 #ifndef USE_ROOT_ENVIRON
199         && use_terminfo_vars()
200 #endif
201         )
202         dir = getenv("TERMINFO");
203
204     if (dir != 0)
205         (void) _nc_tic_dir(dir);
206
207     destination = _nc_tic_dir(0);
208     if (make_db_root(destination) < 0) {
209         char *home = _nc_home_terminfo();
210
211         if (home != 0) {
212             destination = home;
213             if (make_db_root(destination) < 0)
214                 _nc_err_abort("%s: permission denied (errno %d)",
215                               destination, errno);
216         }
217     }
218
219     /*
220      * Note: because of this code, this logic should be exercised
221      * *once only* per run.
222      */
223 #if USE_HASHED_DB
224     make_db_path(actual, destination, sizeof(actual));
225 #else
226     if (chdir(_nc_tic_dir(destination)) < 0
227         || getcwd(actual, sizeof(actual)) == 0)
228         _nc_err_abort("%s: not a directory", destination);
229 #endif
230     _nc_keep_tic_dir(strdup(actual));
231 }
232
233 /*
234  *      Save the compiled version of a description in the filesystem.
235  *
236  *      make a copy of the name-list
237  *      break it up into first-name and all-but-last-name
238  *      creat(first-name)
239  *      write object information to first-name
240  *      close(first-name)
241  *      for each name in all-but-last-name
242  *          link to first-name
243  *
244  *      Using 'time()' to obtain a reference for file timestamps is unreliable,
245  *      e.g., with NFS, because the filesystem may have a different time
246  *      reference.  We check for pre-existence of links by latching the first
247  *      timestamp from a file that we create.
248  *
249  *      The _nc_warning() calls will report a correct line number only if
250  *      _nc_curr_line is properly set before the write_entry() call.
251  */
252
253 NCURSES_EXPORT(void)
254 _nc_write_entry(TERMTYPE2 *const tp)
255 {
256 #if USE_HASHED_DB
257
258     char buffer[MAX_ENTRY_SIZE + 1];
259     unsigned limit = sizeof(buffer);
260     unsigned offset = 0;
261
262 #else /* !USE_HASHED_DB */
263
264     struct stat statbuf;
265     char filename[PATH_MAX];
266     char linkname[PATH_MAX];
267 #if USE_SYMLINKS
268     char symlinkname[PATH_MAX];
269 #if !HAVE_LINK
270 #undef HAVE_LINK
271 #define HAVE_LINK 1
272 #endif
273 #endif /* USE_SYMLINKS */
274
275     unsigned limit2 = sizeof(filename) - (2 + LEAF_LEN);
276     char saved = '\0';
277
278     static int call_count;
279     static time_t start_time;   /* time at start of writes */
280
281 #endif /* USE_HASHED_DB */
282
283     char name_list[MAX_TERMINFO_LENGTH];
284     char *first_name, *other_names;
285     char *ptr;
286     char *term_names = tp->term_names;
287     size_t name_size = strlen(term_names);
288
289     if (name_size == 0) {
290         _nc_syserr_abort("no terminal name found.");
291     } else if (name_size >= sizeof(name_list) - 1) {
292         _nc_syserr_abort("terminal name too long: %s", term_names);
293     }
294
295     _nc_STRCPY(name_list, term_names, sizeof(name_list));
296     DEBUG(7, ("Name list = '%s'", name_list));
297
298     first_name = name_list;
299
300     ptr = &name_list[name_size - 1];
301     other_names = ptr + 1;
302
303     while (ptr > name_list && *ptr != '|')
304         ptr--;
305
306     if (ptr != name_list) {
307         *ptr = '\0';
308
309         for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
310             continue;
311
312         if (*ptr == '\0')
313             other_names = ptr;
314         else {
315             *ptr = '\0';
316             other_names = ptr + 1;
317         }
318     }
319
320     DEBUG(7, ("First name = '%s'", first_name));
321     DEBUG(7, ("Other names = '%s'", other_names));
322
323     _nc_set_type(first_name);
324
325 #if USE_HASHED_DB
326     if (_nc_write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
327         DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
328         DBT key, data;
329
330         if (capdb != 0) {
331             buffer[0] = 0;
332
333             memset(&key, 0, sizeof(key));
334             key.data = term_names;
335             key.size = name_size;
336
337             memset(&data, 0, sizeof(data));
338             data.data = buffer;
339             data.size = offset + 1;
340
341             _nc_db_put(capdb, &key, &data);
342
343             buffer[0] = 2;
344
345             key.data = name_list;
346             key.size = strlen(name_list);
347
348             _nc_STRCPY(buffer + 1,
349                        term_names,
350                        sizeof(buffer) - 1);
351             data.size = name_size + 1;
352
353             total_size += data.size;
354             total_parts++;
355             _nc_db_put(capdb, &key, &data);
356
357             while (*other_names != '\0') {
358                 ptr = other_names++;
359                 assert(ptr < buffer + sizeof(buffer) - 1);
360                 while (*other_names != '|' && *other_names != '\0')
361                     other_names++;
362
363                 if (*other_names != '\0')
364                     *(other_names++) = '\0';
365
366                 key.data = ptr;
367                 key.size = strlen(ptr);
368
369                 total_size += data.size;
370                 total_parts++;
371                 _nc_db_put(capdb, &key, &data);
372             }
373         }
374     }
375 #else /* !USE_HASHED_DB */
376     if (call_count++ == 0) {
377         start_time = 0;
378     }
379
380     if (strlen(first_name) >= sizeof(filename) - (2 + LEAF_LEN)) {
381         _nc_warning("terminal name too long.");
382         saved = first_name[limit2];
383         first_name[limit2] = '\0';
384     }
385
386     _nc_SPRINTF(filename, _nc_SLIMIT(sizeof(filename))
387                 LEAF_FMT "/%s", first_name[0], first_name);
388
389     if (saved)
390         first_name[limit2] = saved;
391
392     /*
393      * Has this primary name been written since the first call to
394      * write_entry()?  If so, the newer write will step on the older,
395      * so warn the user.
396      */
397     if (start_time > 0 &&
398         stat(filename, &statbuf) >= 0
399         && statbuf.st_mtime >= start_time) {
400 #if HAVE_LINK && !USE_SYMLINKS
401         /*
402          * If the file has more than one link, the reason for the previous
403          * write could be that the current primary name used to be an alias for
404          * the previous entry.  In that case, unlink the file so that we will
405          * not modify the previous entry as we write this one.
406          */
407         if (statbuf.st_nlink > 1) {
408             _nc_warning("name redefined.");
409             unlink(filename);
410         } else {
411             _nc_warning("name multiply defined.");
412         }
413 #else
414         _nc_warning("name multiply defined.");
415 #endif
416     }
417
418     check_writeable(first_name[0]);
419     write_file(filename, tp);
420
421     if (start_time == 0) {
422         if (stat(filename, &statbuf) < 0
423             || (start_time = statbuf.st_mtime) == 0) {
424             _nc_syserr_abort("error obtaining time from %s/%s",
425                              _nc_tic_dir(0), filename);
426         }
427     }
428     while (*other_names != '\0') {
429         ptr = other_names++;
430         while (*other_names != '|' && *other_names != '\0')
431             other_names++;
432
433         if (*other_names != '\0')
434             *(other_names++) = '\0';
435
436         if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
437             _nc_warning("terminal alias %s too long.", ptr);
438             continue;
439         }
440         if (strchr(ptr, '/') != 0) {
441             _nc_warning("cannot link alias %s.", ptr);
442             continue;
443         }
444
445         check_writeable(ptr[0]);
446         _nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
447                     LEAF_FMT "/%s", ptr[0], ptr);
448
449         if (strcmp(filename, linkname) == 0) {
450             _nc_warning("self-synonym ignored");
451         } else if (stat(linkname, &statbuf) >= 0 &&
452                    statbuf.st_mtime < start_time) {
453             _nc_warning("alias %s multiply defined.", ptr);
454         } else if (_nc_access(linkname, W_OK) == 0)
455 #if HAVE_LINK
456         {
457             int code;
458 #if USE_SYMLINKS
459 #define MY_SIZE sizeof(symlinkname) - 1
460             if (first_name[0] == linkname[0]) {
461                 _nc_STRNCPY(symlinkname, first_name, MY_SIZE);
462             } else {
463                 _nc_STRCPY(symlinkname, "../", sizeof(symlinkname));
464                 _nc_STRNCPY(symlinkname + 3, filename, MY_SIZE - 3);
465             }
466             symlinkname[MY_SIZE] = '\0';
467 #endif /* USE_SYMLINKS */
468 #if HAVE_REMOVE
469             code = remove(linkname);
470 #else
471             code = unlink(linkname);
472 #endif
473             if (code != 0 && errno == ENOENT)
474                 code = 0;
475 #if USE_SYMLINKS
476             if (symlink(symlinkname, linkname) < 0)
477 #else
478             if (link(filename, linkname) < 0)
479 #endif /* USE_SYMLINKS */
480             {
481                 /*
482                  * If there wasn't anything there, and we cannot
483                  * link to the target because it is the same as the
484                  * target, then the source must be on a filesystem
485                  * that uses caseless filenames, such as Win32, etc.
486                  */
487                 if (code == 0 && errno == EEXIST)
488                     _nc_warning("can't link %s to %s", filename, linkname);
489                 else if (code == 0 && (errno == EPERM || errno == ENOENT))
490                     write_file(linkname, tp);
491                 else {
492 #if MIXEDCASE_FILENAMES
493                     _nc_syserr_abort("can't link %s to %s", filename, linkname);
494 #else
495                     _nc_warning("can't link %s to %s (errno=%d)", filename,
496                                 linkname, errno);
497 #endif
498                 }
499             } else {
500                 DEBUG(1, ("Linked %s", linkname));
501             }
502         }
503 #else /* just make copies */
504             write_file(linkname, tp);
505 #endif /* HAVE_LINK */
506     }
507 #endif /* USE_HASHED_DB */
508 }
509
510 static size_t
511 fake_write(char *dst,
512            unsigned *offset,
513            size_t limit,
514            char *src,
515            size_t want,
516            size_t size)
517 {
518     size_t have = (limit - *offset);
519
520     want *= size;
521     if (have > 0) {
522         if (want > have)
523             want = have;
524         memcpy(dst + *offset, src, want);
525         *offset += (unsigned) want;
526     } else {
527         want = 0;
528     }
529     return (want / size);
530 }
531
532 #define Write(buf, size, count) fake_write(buffer, offset, (size_t) limit, (char *) buf, (size_t) count, (size_t) size)
533
534 #undef LITTLE_ENDIAN            /* BSD/OS defines this as a feature macro */
535 #define HI(x)                   ((x) / 256)
536 #define LO(x)                   ((x) % 256)
537 #define LITTLE_ENDIAN(p, x)     (p)[0] = (unsigned char)LO(x),  \
538                                 (p)[1] = (unsigned char)HI(x)
539
540 #define WRITE_STRING(str) (Write(str, sizeof(char), strlen(str) + 1) == strlen(str) + 1)
541
542 static int
543 compute_offsets(char **Strings, size_t strmax, short *offsets)
544 {
545     int nextfree = 0;
546     size_t i;
547
548     for (i = 0; i < strmax; i++) {
549         if (Strings[i] == ABSENT_STRING) {
550             offsets[i] = -1;
551         } else if (Strings[i] == CANCELLED_STRING) {
552             offsets[i] = -2;
553         } else {
554             offsets[i] = (short) nextfree;
555             nextfree += (int) strlen(Strings[i]) + 1;
556             TRACE_OUT(("put Strings[%d]=%s(%d)", (int) i,
557                        _nc_visbuf(Strings[i]), (int) nextfree));
558         }
559     }
560     return nextfree;
561 }
562
563 static size_t
564 convert_shorts(unsigned char *buf, short *Numbers, size_t count)
565 {
566     size_t i;
567     for (i = 0; i < count; i++) {
568         if (Numbers[i] == ABSENT_NUMERIC) {     /* HI/LO won't work */
569             buf[2 * i] = buf[2 * i + 1] = 0377;
570         } else if (Numbers[i] == CANCELLED_NUMERIC) {   /* HI/LO won't work */
571             buf[2 * i] = 0376;
572             buf[2 * i + 1] = 0377;
573         } else {
574             LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
575             TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
576         }
577     }
578     return SIZEOF_SHORT;
579 }
580
581 #if NCURSES_EXT_NUMBERS
582 static size_t
583 convert_16bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
584 {
585     size_t i, j;
586     size_t size = SIZEOF_SHORT;
587     for (i = 0; i < count; i++) {
588         unsigned value = (unsigned) Numbers[i];
589         TRACE_NUM(i);
590         for (j = 0; j < size; ++j) {
591             *buf++ = value & 0xff;
592             value >>= 8;
593         }
594     }
595     return size;
596 }
597
598 static size_t
599 convert_32bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
600 {
601     size_t i, j;
602     size_t size = SIZEOF_INT2;
603     for (i = 0; i < count; i++) {
604         unsigned value = (unsigned) Numbers[i];
605         TRACE_NUM(i);
606         for (j = 0; j < size; ++j) {
607             *buf++ = value & 0xff;
608             value >>= 8;
609         }
610     }
611     return size;
612 }
613 #endif
614
615 #define even_boundary(value) \
616             ((value) % 2 != 0 && Write(&zero, sizeof(char), 1) != 1)
617
618 #if NCURSES_XNAMES
619 static unsigned
620 extended_Booleans(TERMTYPE2 *tp)
621 {
622     unsigned result = 0;
623     unsigned i;
624
625     for (i = 0; i < tp->ext_Booleans; ++i) {
626         if (tp->Booleans[BOOLCOUNT + i] == TRUE)
627             result = (i + 1);
628     }
629     return result;
630 }
631
632 static unsigned
633 extended_Numbers(TERMTYPE2 *tp)
634 {
635     unsigned result = 0;
636     unsigned i;
637
638     for (i = 0; i < tp->ext_Numbers; ++i) {
639         if (tp->Numbers[NUMCOUNT + i] != ABSENT_NUMERIC)
640             result = (i + 1);
641     }
642     return result;
643 }
644
645 static unsigned
646 extended_Strings(TERMTYPE2 *tp)
647 {
648     unsigned short result = 0;
649     unsigned short i;
650
651     for (i = 0; i < tp->ext_Strings; ++i) {
652         if (tp->Strings[STRCOUNT + i] != ABSENT_STRING)
653             result = (unsigned short) (i + 1);
654     }
655     return result;
656 }
657
658 /*
659  * _nc_align_termtype() will extend entries that are referenced in a use=
660  * clause - discard the unneeded data.
661  */
662 static bool
663 extended_object(TERMTYPE2 *tp)
664 {
665     bool result = FALSE;
666
667     if (_nc_user_definable) {
668         result = ((extended_Booleans(tp)
669                    + extended_Numbers(tp)
670                    + extended_Strings(tp)) != 0);
671     }
672     return result;
673 }
674 #endif
675
676 NCURSES_EXPORT(int)
677 _nc_write_object(TERMTYPE2 *tp, char *buffer, unsigned *offset, unsigned limit)
678 {
679     char *namelist;
680     size_t namelen, boolmax, nummax, strmax, numlen;
681     char zero = '\0';
682     size_t i;
683     int nextfree;
684     short offsets[MAX_ENTRY_SIZE / 2];
685     unsigned char buf[MAX_ENTRY_SIZE];
686     unsigned last_bool = BOOLWRITE;
687     unsigned last_num = NUMWRITE;
688     unsigned last_str = STRWRITE;
689 #if NCURSES_EXT_NUMBERS
690     bool need_ints = FALSE;
691     size_t (*convert_numbers) (unsigned char *, NCURSES_INT2 *, size_t) = convert_32bit;
692 #else
693 #define convert_numbers convert_shorts
694 #endif
695
696 #if NCURSES_XNAMES
697     /*
698      * Normally we limit the list of values to exclude the "obsolete"
699      * capabilities.  However, if we are accepting extended names, add
700      * these as well, since they are used for supporting translation
701      * to/from termcap.
702      */
703     if (_nc_user_definable) {
704         last_bool = BOOLCOUNT;
705         last_num = NUMCOUNT;
706         last_str = STRCOUNT;
707     }
708 #endif
709
710     namelist = tp->term_names;
711     namelen = strlen(namelist) + 1;
712
713     boolmax = 0;
714     for (i = 0; i < last_bool; i++) {
715         if (tp->Booleans[i] == TRUE) {
716             boolmax = i + 1;
717         }
718     }
719
720     nummax = 0;
721     for (i = 0; i < last_num; i++) {
722         if (tp->Numbers[i] != ABSENT_NUMERIC) {
723             nummax = i + 1;
724 #if NCURSES_EXT_NUMBERS
725             if (tp->Numbers[i] > MAX_OF_TYPE(NCURSES_COLOR_T)) {
726                 need_ints = TRUE;
727             }
728 #endif
729         }
730     }
731
732     strmax = 0;
733     for (i = 0; i < last_str; i++) {
734         if (tp->Strings[i] != ABSENT_STRING)
735             strmax = i + 1;
736     }
737
738     nextfree = compute_offsets(tp->Strings, strmax, offsets);
739
740     /* fill in the header */
741 #if NCURSES_EXT_NUMBERS
742     if (need_ints) {
743         convert_numbers = convert_32bit;
744         LITTLE_ENDIAN(buf, MAGIC2);
745     } else {
746         convert_numbers = convert_16bit;
747         LITTLE_ENDIAN(buf, MAGIC);
748     }
749 #else
750     LITTLE_ENDIAN(buf, MAGIC);
751 #endif
752     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
753     LITTLE_ENDIAN(buf + 4, boolmax);
754     LITTLE_ENDIAN(buf + 6, nummax);
755     LITTLE_ENDIAN(buf + 8, strmax);
756     LITTLE_ENDIAN(buf + 10, nextfree);
757
758     /* write out the header */
759     TRACE_OUT(("Header of %s @%d", namelist, *offset));
760     if (Write(buf, 12, 1) != 1
761         || Write(namelist, sizeof(char), namelen) != namelen)
762           return (ERR);
763
764     for (i = 0; i < boolmax; i++)
765         if (tp->Booleans[i] == TRUE)
766             buf[i] = TRUE;
767         else
768             buf[i] = FALSE;
769     if (Write(buf, sizeof(char), boolmax) != boolmax)
770           return (ERR);
771
772     if (even_boundary(namelen + boolmax))
773         return (ERR);
774
775     TRACE_OUT(("Numerics begin at %04x", *offset));
776
777     /* the numerics */
778     numlen = convert_numbers(buf, tp->Numbers, nummax);
779     if (Write(buf, numlen, nummax) != nummax)
780         return (ERR);
781
782     TRACE_OUT(("String offsets begin at %04x", *offset));
783
784     /* the string offsets */
785     convert_shorts(buf, offsets, strmax);
786     if (Write(buf, SIZEOF_SHORT, strmax) != strmax)
787         return (ERR);
788
789     TRACE_OUT(("String table begins at %04x", *offset));
790
791     /* the strings */
792     for (i = 0; i < strmax; i++)
793         if (VALID_STRING(tp->Strings[i]))
794             if (!WRITE_STRING(tp->Strings[i]))
795                 return (ERR);
796
797 #if NCURSES_XNAMES
798     if (extended_object(tp)) {
799         unsigned extcnt = (unsigned) NUM_EXT_NAMES(tp);
800
801         if (even_boundary(nextfree))
802             return (ERR);
803
804         nextfree = compute_offsets(tp->Strings + STRCOUNT,
805                                    (size_t) tp->ext_Strings,
806                                    offsets);
807         TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
808
809         if (tp->ext_Strings >= SIZEOF(offsets))
810             return (ERR);
811
812         nextfree += compute_offsets(tp->ext_Names,
813                                     (size_t) extcnt,
814                                     offsets + tp->ext_Strings);
815         TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
816         strmax = tp->ext_Strings + extcnt;
817
818         /*
819          * Write the extended header
820          */
821         LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
822         LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
823         LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
824         LITTLE_ENDIAN(buf + 6, strmax);
825         LITTLE_ENDIAN(buf + 8, nextfree);
826         TRACE_OUT(("WRITE extended-header @%d", *offset));
827         if (Write(buf, 10, 1) != 1)
828             return (ERR);
829
830         TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
831         if (tp->ext_Booleans
832             && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
833                      tp->ext_Booleans) != tp->ext_Booleans)
834               return (ERR);
835
836         if (even_boundary(tp->ext_Booleans))
837             return (ERR);
838
839         TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
840         if (tp->ext_Numbers) {
841             numlen = convert_numbers(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
842             if (Write(buf, numlen, tp->ext_Numbers) != tp->ext_Numbers)
843                 return (ERR);
844         }
845
846         /*
847          * Convert the offsets for the ext_Strings and ext_Names tables,
848          * in that order.
849          */
850         convert_shorts(buf, offsets, strmax);
851         TRACE_OUT(("WRITE offsets @%d", *offset));
852         if (Write(buf, SIZEOF_SHORT, strmax) != strmax)
853             return (ERR);
854
855         /*
856          * Write the string table after the offset tables so we do not
857          * have to do anything about alignment.
858          */
859         for (i = 0; i < tp->ext_Strings; i++) {
860             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
861                 TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
862                            _nc_visbuf(tp->Strings[i + STRCOUNT])));
863                 if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
864                     return (ERR);
865             }
866         }
867
868         /*
869          * Write the extended names
870          */
871         for (i = 0; i < extcnt; i++) {
872             TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
873             if (!WRITE_STRING(tp->ext_Names[i]))
874                 return (ERR);
875         }
876
877     }
878 #endif /* NCURSES_XNAMES */
879
880     total_written++;
881     total_parts++;
882     total_size = total_size + (int) (*offset + 1);
883     return (OK);
884 }
885
886 /*
887  * Returns the total number of entries written by this process
888  */
889 NCURSES_EXPORT(int)
890 _nc_tic_written(void)
891 {
892     TR(TRACE_DATABASE, ("_nc_tic_written %d entries, %d parts, %d size",
893                         total_written, total_parts, total_size));
894     return total_written;
895 }