]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/write_entry.c
ncurses 6.1 - patch 20180526
[ncurses.git] / ncurses / tinfo / write_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998-2017,2018 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.105 2018/05/20 18:38:08 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) >= limit2) {
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", UChar(first_name[0]),
388                 (int) (sizeof(filename) - LEAF_LEN - 2),
389                 first_name);
390
391     if (saved)
392         first_name[limit2] = saved;
393
394     /*
395      * Has this primary name been written since the first call to
396      * write_entry()?  If so, the newer write will step on the older,
397      * so warn the user.
398      */
399     if (start_time > 0 &&
400         stat(filename, &statbuf) >= 0
401         && statbuf.st_mtime >= start_time) {
402 #if HAVE_LINK && !USE_SYMLINKS
403         /*
404          * If the file has more than one link, the reason for the previous
405          * write could be that the current primary name used to be an alias for
406          * the previous entry.  In that case, unlink the file so that we will
407          * not modify the previous entry as we write this one.
408          */
409         if (statbuf.st_nlink > 1) {
410             _nc_warning("name redefined.");
411             unlink(filename);
412         } else {
413             _nc_warning("name multiply defined.");
414         }
415 #else
416         _nc_warning("name multiply defined.");
417 #endif
418     }
419
420     check_writeable(first_name[0]);
421     write_file(filename, tp);
422
423     if (start_time == 0) {
424         if (stat(filename, &statbuf) < 0
425             || (start_time = statbuf.st_mtime) == 0) {
426             _nc_syserr_abort("error obtaining time from %s/%s",
427                              _nc_tic_dir(0), filename);
428         }
429     }
430     while (*other_names != '\0') {
431         ptr = other_names++;
432         while (*other_names != '|' && *other_names != '\0')
433             other_names++;
434
435         if (*other_names != '\0')
436             *(other_names++) = '\0';
437
438         if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
439             _nc_warning("terminal alias %s too long.", ptr);
440             continue;
441         }
442         if (strchr(ptr, '/') != 0) {
443             _nc_warning("cannot link alias %s.", ptr);
444             continue;
445         }
446
447         check_writeable(ptr[0]);
448         _nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
449                     LEAF_FMT "/%s", ptr[0], ptr);
450
451         if (strcmp(filename, linkname) == 0) {
452             _nc_warning("self-synonym ignored");
453         } else if (stat(linkname, &statbuf) >= 0 &&
454                    statbuf.st_mtime < start_time) {
455             _nc_warning("alias %s multiply defined.", ptr);
456         } else if (_nc_access(linkname, W_OK) == 0)
457 #if HAVE_LINK
458         {
459             int code;
460 #if USE_SYMLINKS
461 #define MY_SIZE sizeof(symlinkname) - 1
462             if (first_name[0] == linkname[0]) {
463                 _nc_STRNCPY(symlinkname, first_name, MY_SIZE);
464             } else {
465                 _nc_STRCPY(symlinkname, "../", sizeof(symlinkname));
466                 _nc_STRNCPY(symlinkname + 3, filename, MY_SIZE - 3);
467             }
468             symlinkname[MY_SIZE] = '\0';
469 #endif /* USE_SYMLINKS */
470 #if HAVE_REMOVE
471             code = remove(linkname);
472 #else
473             code = unlink(linkname);
474 #endif
475             if (code != 0 && errno == ENOENT)
476                 code = 0;
477 #if USE_SYMLINKS
478             if (symlink(symlinkname, linkname) < 0)
479 #else
480             if (link(filename, linkname) < 0)
481 #endif /* USE_SYMLINKS */
482             {
483                 /*
484                  * If there wasn't anything there, and we cannot
485                  * link to the target because it is the same as the
486                  * target, then the source must be on a filesystem
487                  * that uses caseless filenames, such as Win32, etc.
488                  */
489                 if (code == 0 && errno == EEXIST)
490                     _nc_warning("can't link %s to %s", filename, linkname);
491                 else if (code == 0 && (errno == EPERM || errno == ENOENT))
492                     write_file(linkname, tp);
493                 else {
494 #if MIXEDCASE_FILENAMES
495                     _nc_syserr_abort("can't link %s to %s", filename, linkname);
496 #else
497                     _nc_warning("can't link %s to %s (errno=%d)", filename,
498                                 linkname, errno);
499 #endif
500                 }
501             } else {
502                 DEBUG(1, ("Linked %s", linkname));
503             }
504         }
505 #else /* just make copies */
506             write_file(linkname, tp);
507 #endif /* HAVE_LINK */
508     }
509 #endif /* USE_HASHED_DB */
510 }
511
512 static size_t
513 fake_write(char *dst,
514            unsigned *offset,
515            size_t limit,
516            char *src,
517            size_t want,
518            size_t size)
519 {
520     size_t have = (limit - *offset);
521
522     want *= size;
523     if (have > 0) {
524         if (want > have)
525             want = have;
526         memcpy(dst + *offset, src, want);
527         *offset += (unsigned) want;
528     } else {
529         want = 0;
530     }
531     return (want / size);
532 }
533
534 #define Write(buf, size, count) fake_write(buffer, offset, (size_t) limit, (char *) buf, (size_t) count, (size_t) size)
535
536 #undef LITTLE_ENDIAN            /* BSD/OS defines this as a feature macro */
537 #define HI(x)                   ((x) / 256)
538 #define LO(x)                   ((x) % 256)
539 #define LITTLE_ENDIAN(p, x)     (p)[0] = (unsigned char)LO(x),  \
540                                 (p)[1] = (unsigned char)HI(x)
541
542 #define WRITE_STRING(str) (Write(str, sizeof(char), strlen(str) + 1) == strlen(str) + 1)
543
544 static int
545 compute_offsets(char **Strings, size_t strmax, short *offsets)
546 {
547     int nextfree = 0;
548     size_t i;
549
550     for (i = 0; i < strmax; i++) {
551         if (Strings[i] == ABSENT_STRING) {
552             offsets[i] = -1;
553         } else if (Strings[i] == CANCELLED_STRING) {
554             offsets[i] = -2;
555         } else {
556             offsets[i] = (short) nextfree;
557             nextfree += (int) strlen(Strings[i]) + 1;
558             TRACE_OUT(("put Strings[%d]=%s(%d)", (int) i,
559                        _nc_visbuf(Strings[i]), (int) nextfree));
560         }
561     }
562     return nextfree;
563 }
564
565 static size_t
566 convert_shorts(unsigned char *buf, short *Numbers, size_t count)
567 {
568     size_t i;
569     for (i = 0; i < count; i++) {
570         if (Numbers[i] == ABSENT_NUMERIC) {     /* HI/LO won't work */
571             buf[2 * i] = buf[2 * i + 1] = 0377;
572         } else if (Numbers[i] == CANCELLED_NUMERIC) {   /* HI/LO won't work */
573             buf[2 * i] = 0376;
574             buf[2 * i + 1] = 0377;
575         } else {
576             LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
577             TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
578         }
579     }
580     return SIZEOF_SHORT;
581 }
582
583 #if NCURSES_EXT_NUMBERS
584 static size_t
585 convert_16bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
586 {
587     size_t i, j;
588     size_t size = SIZEOF_SHORT;
589     for (i = 0; i < count; i++) {
590         unsigned value = (unsigned) Numbers[i];
591         TRACE_NUM(i);
592         for (j = 0; j < size; ++j) {
593             *buf++ = value & 0xff;
594             value >>= 8;
595         }
596     }
597     return size;
598 }
599
600 static size_t
601 convert_32bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
602 {
603     size_t i, j;
604     size_t size = SIZEOF_INT2;
605     for (i = 0; i < count; i++) {
606         unsigned value = (unsigned) Numbers[i];
607         TRACE_NUM(i);
608         for (j = 0; j < size; ++j) {
609             *buf++ = value & 0xff;
610             value >>= 8;
611         }
612     }
613     return size;
614 }
615 #endif
616
617 #define even_boundary(value) \
618             ((value) % 2 != 0 && Write(&zero, sizeof(char), 1) != 1)
619
620 #if NCURSES_XNAMES
621 static unsigned
622 extended_Booleans(TERMTYPE2 *tp)
623 {
624     unsigned result = 0;
625     unsigned i;
626
627     for (i = 0; i < tp->ext_Booleans; ++i) {
628         if (tp->Booleans[BOOLCOUNT + i] == TRUE)
629             result = (i + 1);
630     }
631     return result;
632 }
633
634 static unsigned
635 extended_Numbers(TERMTYPE2 *tp)
636 {
637     unsigned result = 0;
638     unsigned i;
639
640     for (i = 0; i < tp->ext_Numbers; ++i) {
641         if (tp->Numbers[NUMCOUNT + i] != ABSENT_NUMERIC)
642             result = (i + 1);
643     }
644     return result;
645 }
646
647 static unsigned
648 extended_Strings(TERMTYPE2 *tp)
649 {
650     unsigned short result = 0;
651     unsigned short i;
652
653     for (i = 0; i < tp->ext_Strings; ++i) {
654         if (tp->Strings[STRCOUNT + i] != ABSENT_STRING)
655             result = (unsigned short) (i + 1);
656     }
657     return result;
658 }
659
660 /*
661  * _nc_align_termtype() will extend entries that are referenced in a use=
662  * clause - discard the unneeded data.
663  */
664 static bool
665 extended_object(TERMTYPE2 *tp)
666 {
667     bool result = FALSE;
668
669     if (_nc_user_definable) {
670         result = ((extended_Booleans(tp)
671                    + extended_Numbers(tp)
672                    + extended_Strings(tp)) != 0);
673     }
674     return result;
675 }
676 #endif
677
678 NCURSES_EXPORT(int)
679 _nc_write_object(TERMTYPE2 *tp, char *buffer, unsigned *offset, unsigned limit)
680 {
681     char *namelist;
682     size_t namelen, boolmax, nummax, strmax, numlen;
683     char zero = '\0';
684     size_t i;
685     int nextfree;
686     short offsets[MAX_ENTRY_SIZE / 2];
687     unsigned char buf[MAX_ENTRY_SIZE];
688     unsigned last_bool = BOOLWRITE;
689     unsigned last_num = NUMWRITE;
690     unsigned last_str = STRWRITE;
691 #if NCURSES_EXT_NUMBERS
692     bool need_ints = FALSE;
693     size_t (*convert_numbers) (unsigned char *, NCURSES_INT2 *, size_t) = convert_32bit;
694 #else
695 #define convert_numbers convert_shorts
696 #endif
697
698 #if NCURSES_XNAMES
699     /*
700      * Normally we limit the list of values to exclude the "obsolete"
701      * capabilities.  However, if we are accepting extended names, add
702      * these as well, since they are used for supporting translation
703      * to/from termcap.
704      */
705     if (_nc_user_definable) {
706         last_bool = BOOLCOUNT;
707         last_num = NUMCOUNT;
708         last_str = STRCOUNT;
709     }
710 #endif
711
712     namelist = tp->term_names;
713     namelen = strlen(namelist) + 1;
714
715     boolmax = 0;
716     for (i = 0; i < last_bool; i++) {
717         if (tp->Booleans[i] == TRUE) {
718             boolmax = i + 1;
719         }
720     }
721
722     nummax = 0;
723     for (i = 0; i < last_num; i++) {
724         if (tp->Numbers[i] != ABSENT_NUMERIC) {
725             nummax = i + 1;
726 #if NCURSES_EXT_NUMBERS
727             if (tp->Numbers[i] > MAX_OF_TYPE(NCURSES_COLOR_T)) {
728                 need_ints = TRUE;
729             }
730 #endif
731         }
732     }
733
734     strmax = 0;
735     for (i = 0; i < last_str; i++) {
736         if (tp->Strings[i] != ABSENT_STRING)
737             strmax = i + 1;
738     }
739
740     nextfree = compute_offsets(tp->Strings, strmax, offsets);
741
742     /* fill in the header */
743 #if NCURSES_EXT_NUMBERS
744     if (need_ints) {
745         convert_numbers = convert_32bit;
746         LITTLE_ENDIAN(buf, MAGIC2);
747     } else {
748         convert_numbers = convert_16bit;
749         LITTLE_ENDIAN(buf, MAGIC);
750     }
751 #else
752     LITTLE_ENDIAN(buf, MAGIC);
753 #endif
754     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
755     LITTLE_ENDIAN(buf + 4, boolmax);
756     LITTLE_ENDIAN(buf + 6, nummax);
757     LITTLE_ENDIAN(buf + 8, strmax);
758     LITTLE_ENDIAN(buf + 10, nextfree);
759
760     /* write out the header */
761     TRACE_OUT(("Header of %s @%d", namelist, *offset));
762     if (Write(buf, 12, 1) != 1
763         || Write(namelist, sizeof(char), namelen) != namelen)
764           return (ERR);
765
766     for (i = 0; i < boolmax; i++)
767         if (tp->Booleans[i] == TRUE)
768             buf[i] = TRUE;
769         else
770             buf[i] = FALSE;
771     if (Write(buf, sizeof(char), boolmax) != boolmax)
772           return (ERR);
773
774     if (even_boundary(namelen + boolmax))
775         return (ERR);
776
777     TRACE_OUT(("Numerics begin at %04x", *offset));
778
779     /* the numerics */
780     numlen = convert_numbers(buf, tp->Numbers, nummax);
781     if (Write(buf, numlen, nummax) != nummax)
782         return (ERR);
783
784     TRACE_OUT(("String offsets begin at %04x", *offset));
785
786     /* the string offsets */
787     convert_shorts(buf, offsets, strmax);
788     if (Write(buf, SIZEOF_SHORT, strmax) != strmax)
789         return (ERR);
790
791     TRACE_OUT(("String table begins at %04x", *offset));
792
793     /* the strings */
794     for (i = 0; i < strmax; i++)
795         if (VALID_STRING(tp->Strings[i]))
796             if (!WRITE_STRING(tp->Strings[i]))
797                 return (ERR);
798
799 #if NCURSES_XNAMES
800     if (extended_object(tp)) {
801         unsigned ext_total = (unsigned) NUM_EXT_NAMES(tp);
802         unsigned ext_usage = ext_total;
803
804         if (even_boundary(nextfree))
805             return (ERR);
806
807         nextfree = compute_offsets(tp->Strings + STRCOUNT,
808                                    (size_t) tp->ext_Strings,
809                                    offsets);
810         TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
811
812         if (tp->ext_Strings >= SIZEOF(offsets))
813             return (ERR);
814
815         nextfree += compute_offsets(tp->ext_Names,
816                                     (size_t) ext_total,
817                                     offsets + tp->ext_Strings);
818         TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
819         strmax = tp->ext_Strings + ext_total;
820         for (i = 0; i < tp->ext_Strings; ++i) {
821             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
822                 ext_usage++;
823             }
824         }
825         TRACE_OUT(("will write %u/%lu strings", ext_usage, (unsigned long) strmax));
826
827         /*
828          * Write the extended header
829          */
830         LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
831         LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
832         LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
833         LITTLE_ENDIAN(buf + 6, ext_usage);
834         LITTLE_ENDIAN(buf + 8, nextfree);
835         TRACE_OUT(("WRITE extended-header @%d", *offset));
836         if (Write(buf, 10, 1) != 1)
837             return (ERR);
838
839         TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
840         if (tp->ext_Booleans
841             && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
842                      tp->ext_Booleans) != tp->ext_Booleans)
843               return (ERR);
844
845         if (even_boundary(tp->ext_Booleans))
846             return (ERR);
847
848         TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
849         if (tp->ext_Numbers) {
850             numlen = convert_numbers(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
851             if (Write(buf, numlen, tp->ext_Numbers) != tp->ext_Numbers)
852                 return (ERR);
853         }
854
855         /*
856          * Convert the offsets for the ext_Strings and ext_Names tables,
857          * in that order.
858          */
859         convert_shorts(buf, offsets, strmax);
860         TRACE_OUT(("WRITE offsets @%d", *offset));
861         if (Write(buf, SIZEOF_SHORT, strmax) != strmax)
862             return (ERR);
863
864         /*
865          * Write the string table after the offset tables so we do not
866          * have to do anything about alignment.
867          */
868         for (i = 0; i < tp->ext_Strings; i++) {
869             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
870                 TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
871                            _nc_visbuf(tp->Strings[i + STRCOUNT])));
872                 if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
873                     return (ERR);
874             }
875         }
876
877         /*
878          * Write the extended names
879          */
880         for (i = 0; i < ext_total; i++) {
881             TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
882             if (!WRITE_STRING(tp->ext_Names[i]))
883                 return (ERR);
884         }
885
886     }
887 #endif /* NCURSES_XNAMES */
888
889     total_written++;
890     total_parts++;
891     total_size = total_size + (int) (*offset + 1);
892     return (OK);
893 }
894
895 /*
896  * Returns the total number of entries written by this process
897  */
898 NCURSES_EXPORT(int)
899 _nc_tic_written(void)
900 {
901     TR(TRACE_DATABASE, ("_nc_tic_written %d entries, %d parts, %d size",
902                         total_written, total_parts, total_size));
903     return total_written;
904 }