]> git.pond.sub.org Git - empserver/blob - src/lib/common/xundump.c
d579dd8a6db0090777f86eac6f065d54ab226894
[empserver] / src / lib / common / xundump.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2014, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  xundump.c: Load back xdump output
28  *
29  *  Known contributors to this file:
30  *     Ron Koenderink, 2005
31  *     Markus Armbruster, 2005-2014
32  */
33
34 /*
35  * See doc/xdump!  And keep it up-to-date.
36  *
37  * Parsing of machine-readable xdump is not precise: it recognizes
38  * comments, accepts whitespace in place of single space, and accepts
39  * the full human-readable field syntax instead of its machine-
40  * readable subset.
41  *
42  * FIXME:
43  * - Normalize terminology: table/rows/columns or file/records/fields
44  * - Loading tables with NSC_STRING elements more than once leaks memory
45  * TODO:
46  * - Symbolic array indexes
47  * - Option to treat missing and unknown fields as warning, not error
48  * TODO, but hardly worth the effort:
49  * - Permit reordering of array elements
50  */
51
52 #include <config.h>
53
54 #include <ctype.h>
55 #include <limits.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <time.h>
61 #include "file.h"
62 #include "match.h"
63 #include "nsc.h"
64 #include "optlist.h"
65 #include "xdump.h"
66
67 static char *fname;             /* Name of file being read */
68 static int lineno;              /* Current line number */
69
70 static int cur_type;            /* Current table's file type */
71 static int partno;              /* Counts from 0..#parts-1 */
72 static void *cur_obj;           /* The object being read into */
73 static int cur_id;              /* and its index in the table */
74 static int old_nelem;
75 static unsigned char *idgap;    /* idgap && idgap[ID] iff part#0 lacks ID */
76 static int idgap_len;           /* #elements in idgap[] */
77
78 static int human;               /* Reading human-readable syntax? */
79 static int ellipsis;            /* Header ended with ...? */
80 static int nflds;               /* #fields in input records */
81 static struct castr **fldca;    /* Map field number to selector */
82 static int *fldidx;             /* Map field number to index */
83 static int *caflds;             /* Map selector number to #fields seen */
84 static int *cafldspp;           /* ditto, in previous parts */
85
86 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
87 static int deffld(int, char *, int);
88 static int chkflds(void);
89 static int setnum(int, double);
90 static int setstr(int, char *);
91 static int setsym(int, char *);
92 static int mtsymset(int, long *);
93 static int add2symset(int, long *, char *);
94 static int xubody(FILE *);
95 static int xutail(FILE *, struct castr *);
96
97 /*
98  * Does the code hardcode indexes for table TYPE?
99  */
100 static int
101 have_hardcoded_indexes(int type)
102 {
103     return type == EF_ITEM || type == EF_SECTOR_CHR
104         || type == EF_INFRASTRUCTURE;
105 }
106
107 /*
108  * Okay to truncate table TYPE?
109  */
110 static int
111 may_truncate(int type)
112 {
113     return empfile[type].nent < 0 && !have_hardcoded_indexes(type);
114 }
115
116 /*
117  * Can we fill in gaps in table TYPE?
118  */
119 static int
120 can_fill_gaps(int type)
121 {
122     struct castr *ca = ef_cadef(type);
123
124     return ca[0].ca_table == type && !(ca[0].ca_flags & NSC_EXTRA)
125         && !have_hardcoded_indexes(type);
126 }
127
128 /*
129  * Gripe about the current line to stderr, return -1.
130  */
131 static int
132 gripe(char *fmt, ...)
133 {
134     va_list ap;
135
136     fprintf(stderr, "%s:%d: ", fname, lineno);
137     va_start(ap, fmt);
138     vfprintf(stderr, fmt, ap);
139     va_end(ap);
140     putc('\n', stderr);
141
142     return -1;
143 }
144
145 /* Make TYPE the current table.  */
146 static void
147 tbl_start(int type)
148 {
149     cur_type = type;
150     partno = 0;
151     cur_id = -1;
152     cur_obj = NULL;
153     old_nelem = type == EF_BAD ? 0 : ef_nelem(type);
154     idgap = NULL;
155     idgap_len = 0;
156 }
157
158 /* End the current table.  */
159 static void
160 tbl_end(void)
161 {
162     free(idgap);
163     tbl_start(EF_BAD);
164 }
165
166 /*
167  * Seek to current table's ID-th record.
168  * ID must be acceptable.
169  * Store it in cur_obj, and set cur_id accordingly.
170  * Return 0 on success, -1 on failure.
171  */
172 static int
173 tbl_seek(int id)
174 {
175     struct empfile *ep = &empfile[cur_type];
176
177     if (id >= ef_nelem(cur_type)) {
178         if (!ef_ensure_space(cur_type, id, 1))
179             return gripe("Can't put ID %d into table %s", id, ep->name);
180     }
181
182     cur_obj = ef_ptr(cur_type, id);
183     if (CANT_HAPPEN(!cur_obj))
184         return -1;
185     cur_id = id;
186     return 0;
187 }
188
189 /*
190  * Omit ID1..ID2-1.
191  * Reset the omitted objects to default state.
192  */
193 static void
194 omit_ids(int id1, int id2)
195 {
196     int i;
197
198     if (id1 >= id2)
199         return;
200
201     idgap = realloc(idgap, id2 * sizeof(*idgap));
202     for (i = idgap_len; i < id1; i++)
203         idgap[i] = 0;
204     for (i = id1; i < id2; i++) {
205         ef_blank(cur_type, i, ef_ptr(cur_type, i));
206         idgap[i] = 1;
207     }
208     idgap_len = id2;
209 }
210
211 /*
212  * Return the smallest non-omitted ID in ID1..ID2-1 if any, else -1.
213  */
214 static int
215 expected_id(int id1, int id2)
216 {
217     int i;
218
219     for (i = id1; i < id2; i++) {
220         if (i >= idgap_len || !idgap[i])
221             return i;
222     }
223     return -1;
224 }
225
226 /*
227  * Get the next object, it has record index ID.
228  * Store it in cur_obj, and set cur_id accordingly.
229  * Reset any omitted objects to default state.
230  * Return 0 on success, -1 on failure.
231  */
232 static int
233 tbl_skip_to_obj(int id)
234 {
235     int prev_id = cur_id;
236     int max_id;
237
238     if (CANT_HAPPEN(partno != 0))
239         return -1;
240     if (!can_fill_gaps(cur_type) && id != cur_id + 1)
241         return gripe("Expected %d in field %d", cur_id + 1, 1);
242     if (id <= cur_id)
243         return gripe("Field %d must be > %d", 1, cur_id);
244     max_id = ef_id_limit(cur_type);
245     if (id > max_id)
246         return gripe("Field %d must be <= %d", 1, max_id);
247
248     if (tbl_seek(id) < 0)
249         return -1;
250
251     omit_ids(prev_id + 1, id);
252     return 0;
253 }
254
255 /*
256  * Get the next object.
257  * Store it in cur_obj, and set cur_id accordingly.
258  * Return 0 on success, -1 on failure.
259  */
260 static int
261 tbl_next_obj(void)
262 {
263     int next_id;
264
265     if (partno == 0) {
266         if (cur_id >= ef_id_limit(cur_type))
267             return gripe("Too many rows");
268         next_id = cur_id + 1;
269     } else {
270         next_id = expected_id(cur_id + 1, empfile[cur_type].fids);
271         if (next_id < 0)
272             return gripe("Table's first part doesn't have this row");
273     }
274     return tbl_seek(next_id);
275 }
276
277 /*
278  * Finish table part.
279  * If the table has variable length, truncate it.
280  * Else ensure we're omitting the same objects as the previous parts.
281  * Reset any omitted objects to default state.
282  * Return 0 on success, -1 on failure.
283  */
284 static int
285 tbl_part_done(void)
286 {
287     struct empfile *ep = &empfile[cur_type];
288     int exp_id;
289
290     if (cur_id + 1 < ep->fids) {
291         if (partno == 0) {
292             if (may_truncate(cur_type)) {
293                 if (!ef_truncate(cur_type, cur_id + 1))
294                     return -1;
295             } else {
296                 if (!can_fill_gaps(cur_type))
297                     return gripe("Expected %d more rows",
298                                  ep->fids - (cur_id + 1));
299                 omit_ids(cur_id + 1, ep->fids);
300             }
301         } else {
302             exp_id = expected_id(cur_id + 1, ep->fids);
303             if (exp_id >= 0)
304                 return gripe("Expected row with %d in field %d,"
305                              " like in table's first part",
306                              exp_id, 1);
307         }
308     }
309
310     partno++;
311     cur_id = -1;
312     cur_obj = NULL;
313     return 0;
314 }
315
316 /*
317  * Read and ignore field separators from FP.
318  * Return first character that is not a field separator.
319  */
320 static int
321 skipfs(FILE *fp)
322 {
323     int ch;
324
325     do {
326         ch = getc(fp);
327     } while (ch == ' ' || ch == '\t');
328
329     if (ch == '#') {
330         do {
331             ch = getc(fp);
332         } while (ch != EOF && ch != '\n');
333     }
334
335     return ch;
336 }
337
338 /*
339  * Decode escape sequences in BUF.
340  * Return BUF on success, null pointer on failure.
341  */
342 static char *
343 xuesc(char *buf)
344 {
345     char *src, *dst;
346     int octal_chr, n;
347
348     dst = buf;
349     src = buf;
350     while (*src) {
351         if (*src == '\\') {
352             if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
353                 return NULL;
354             *dst++ = (char)octal_chr;
355             src += 3;
356         } else
357             *dst++ = *src++;
358     }
359     *dst = '\0';
360     return buf;
361 }
362
363 /*
364  * Read an identifier from FP into BUF.
365  * BUF must have space for 1024 characters.
366  * Return number of characters read on success, -1 on failure.
367  */
368 static int
369 getid(FILE *fp, char *buf)
370 {
371     int n;
372     if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
373         || !isalpha(buf[0]))
374         return -1;
375     xuesc(buf);
376     return n;
377 }
378
379 /*
380  * Try to read a field name from FP.
381  * I is the field number, counting from zero.
382  * If a name is read, set fldca[I] and fldidx[I] for it, and update
383  * caflds[].
384  * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
385  */
386 static int
387 xufldname(FILE *fp, int i)
388 {
389     int ch, idx;
390     char buf[1024];
391
392     ch = skipfs(fp);
393     switch (ch) {
394     case EOF:
395         return gripe("Unexpected EOF");
396     case '\n':
397         if (chkflds() < 0)
398             return -1;
399         lineno++;
400         return 0;
401     case '.':
402         if (getc(fp) != '.' || getc(fp) != '.')
403             return gripe("Junk in header field %d", i + 1);
404         if (i == 0)
405             return gripe("Header fields expected");
406         ellipsis = 1;
407         ch = skipfs(fp);
408         if (ch != EOF && ch != '\n')
409             return gripe("Junk after ...");
410         ungetc(ch, fp);
411         return 1;
412     default:
413         ungetc(ch, fp);
414         if (getid(fp, buf) < 0)
415             return gripe("Junk in header field %d", i + 1);
416         ch = getc(fp);
417         if (ch != '(') {
418             ungetc(ch, fp);
419             return deffld(i, buf, -1);
420         }
421         ch = getc(fp);
422         ungetc(ch, fp);
423         if (isdigit(ch) || ch == '-' || ch == '+') {
424             if (fscanf(fp, "%d", &idx) != 1)
425                 return gripe("Malformed number in index of header field %d",
426                              i + 1);
427             if (idx < 0)
428                 return gripe("Index must not be negative in header field %d",
429                              i + 1);
430         } else {
431             if (getid(fp, buf) < 0)
432                 return gripe("Malformed index in header field %d", i + 1);
433             return gripe("Symbolic index in header field %d not yet implemented",
434                          i + 1);
435         }
436         ch = getc(fp);
437         if (ch != ')')
438             return gripe("Malformed index in header field %d", i + 1);
439         return deffld(i, buf, idx);
440     }
441 }
442
443 /*
444  * Try to read a field value from FP.
445  * I is the field number, counting from zero.
446  * Return 1 if a value was read, 0 on end of line, -1 on error.
447  */
448 static int
449 xufld(FILE *fp, int i)
450 {
451     int ch, j;
452     char buf[1024];
453     double dbl;
454     long set;
455
456     ch = skipfs(fp);
457     switch (ch) {
458     case EOF:
459         return gripe("Unexpected EOF");
460     case '\n':
461         CANT_HAPPEN(i > nflds);
462         for (j = i; j < nflds; j++) {
463             if (CA_IS_ARRAY(fldca[j]))
464                 gripe("Field %s(%d) missing",
465                       fldca[j]->ca_name, fldidx[j]);
466             else
467                 gripe("Field %s missing", fldca[j]->ca_name);
468         }
469         lineno++;
470         return i < nflds ? -1 : 0;
471     case '+': case '-': case '.':
472     case '0': case '1': case '2': case '3': case '4':
473     case '5': case '6': case '7': case '8': case '9':
474         ungetc(ch, fp);
475         if (fscanf(fp, "%lg", &dbl) != 1)
476             return gripe("Malformed number in field %d", i + 1);
477         return setnum(i, dbl);
478     case '"':
479         ch = getc(fp);
480         if (ch == '"')
481             buf[0] = 0;
482         else {
483             ungetc(ch, fp);
484             if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
485                 return gripe("Malformed string in field %d", i + 1);
486             if (!xuesc(buf))
487                 return gripe("Invalid escape sequence in field %d",
488                              i + 1);
489         }
490         return setstr(i, buf);
491     case '(':
492         if (mtsymset(i, &set) < 0)
493             return -1;
494         for (;;) {
495             ch = skipfs(fp);
496             if (ch == EOF || ch == '\n')
497                 return gripe("Unmatched '(' in field %d", i + 1);
498             if (ch == ')')
499                 break;
500             ungetc(ch, fp);
501             if (getid(fp, buf) < 0)
502                 return gripe("Junk in field %d", i + 1);
503             if (add2symset(i, &set, buf) < 0)
504                 return -1;
505         }
506         return setnum(i, set);
507     default:
508         ungetc(ch, fp);
509         if (getid(fp, buf) < 0)
510             return gripe("Junk in field %d", i + 1);
511         if (!strcmp(buf, "nil"))
512             return setstr(i, NULL);
513         else
514             return setsym(i, buf);
515     }
516 }
517
518 /*
519  * Read fields from FP.
520  * Use PARSE() to read each field.
521  * Return number of fields read on success, -1 on error.
522  */
523 static int
524 xuflds(FILE *fp, int (*parse)(FILE *, int))
525 {
526     int i, ch, res;
527
528     for (i = 0; ; i++) {
529         res = parse(fp, i);
530         if (res < 0)
531             return -1;
532         if (res == 0)
533             return i;
534         ch = getc(fp);
535         if (ch == '\n')
536             ungetc(ch, fp);
537         else if (ch != ' ' && ch != '\t')
538             return gripe("Bad field separator after field %d", i + 1);
539     }
540 }
541
542 /*
543  * Define the FLDNO-th field.
544  * If IDX is negative, define as selector NAME, else as NAME(IDX).
545  * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
546  * Update caflds[].
547  * Return 1 on success, -1 on error.
548  */
549 static int
550 deffld(int fldno, char *name, int idx)
551 {
552     struct castr *ca = ef_cadef(cur_type);
553     int res;
554
555     res = stmtch(name, ca, offsetof(struct castr, ca_name),
556                  sizeof(struct castr));
557     if (res < 0)
558         return gripe("Header %s of field %d is %s", name, fldno + 1,
559                      res == M_NOTUNIQUE ? "ambiguous" : "unknown");
560     if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
561         return gripe("Extraneous header %s in field %d", name, fldno + 1);
562     if (CA_IS_ARRAY(&ca[res])) {
563         if (idx < 0)
564             return gripe("Header %s requires an index in field %d",
565                          ca[res].ca_name, fldno + 1);
566         if (idx >= ca[res].ca_len)
567             return gripe("Header %s(%d) index out of bounds in field %d",
568                          ca[res].ca_name, idx, fldno + 1);
569         if (idx < caflds[res])
570             return gripe("Duplicate header %s(%d) in field %d",
571                          ca[res].ca_name, idx, fldno + 1);
572         if (idx > caflds[res])
573             return gripe("Expected header %s(%d) in field %d",
574                          ca[res].ca_name, caflds[res], fldno + 1);
575     } else {
576         if (idx >= 0)
577             return gripe("Header %s doesn't take an index in field %d",
578                          ca[res].ca_name, fldno + 1);
579         idx = 0;
580         if (caflds[res])
581             return gripe("Duplicate header %s in field %d",
582                          ca[res].ca_name, fldno + 1);
583     }
584     fldca[fldno] = &ca[res];
585     fldidx[fldno] = idx;
586     caflds[res]++;
587     return 1;
588 }
589
590 /*
591  * Check fields in xdump are sane.
592  * Return 0 on success, -1 on error.
593  */
594 static int
595 chkflds(void)
596 {
597     struct castr *ca = ef_cadef(cur_type);
598     int i, len, cafldsmax, res = 0;
599
600     /* Record index must come first, to make cur_id work, see setnum() */
601     if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
602         res = gripe("Header field %s must come first", ca[0].ca_name);
603
604     if (ellipsis)
605         return res;             /* table is split, another part expected */
606
607     /* Check for missing fields */
608     for (i = 0; ca[i].ca_name; i++) {
609         cafldsmax = MAX(caflds[i], cafldspp[i]);
610         if (ca[i].ca_flags & NSC_EXTRA)
611             continue;
612         len = CA_ARRAY_LEN(&ca[i]);
613         if (!len && !cafldsmax)
614             res = gripe("Header field %s missing", ca[i].ca_name);
615         else if (len && cafldsmax == len - 1)
616             res = gripe("Header field %s(%d) missing",
617                         ca[i].ca_name, len - 1);
618         else if (len && cafldsmax < len - 1)
619             res = gripe("Header fields %s(%d) ... %s(%d) missing",
620                         ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
621     }
622
623     return res;
624 }
625
626 /*
627  * Get selector for field FLDNO.
628  * Assign the field's selector index to *IDX, unless it is null.
629  * Return the selector on success, null pointer on error.
630  */
631 static struct castr *
632 getfld(int fldno, int *idx)
633 {
634     if (fldno >= nflds) {
635         gripe("Too many fields, expected only %d", nflds);
636         return NULL;
637     }
638     if (CANT_HAPPEN(fldno < 0))
639         return NULL;
640     if (idx)
641         *idx = fldidx[fldno];
642     return fldca[fldno];
643 }
644
645 /*
646  * Is a new value for field FLDNO required to match the old one?
647  */
648 static int
649 fldval_must_match(int fldno)
650 {
651     struct castr *ca = ef_cadef(cur_type);
652     int i = fldca[fldno] - ca;
653
654     /*
655      * Value must match if:
656      * it's for a const selector, unless the object is still blank, or
657      * it was already given in a previous part of a split table.
658      */
659     return (cur_id < old_nelem && (fldca[fldno]->ca_flags & NSC_CONST))
660         || fldidx[fldno] < cafldspp[i];
661 }
662
663 /*
664  * Set value of field FLDNO in current object to DBL.
665  * Return 1 on success, -1 on error.
666  */
667 static int
668 setnum(int fldno, double dbl)
669 {
670     struct castr *ca;
671     int next_id, idx;
672     char *memb_ptr;
673     double old, new;
674
675     ca = getfld(fldno, &idx);
676     if (!ca)
677         return -1;
678
679     if (fldno == 0) {
680         if (partno == 0 && ca->ca_table == cur_type) {
681             /* Got record index */
682             next_id = (int)dbl;
683             if (next_id != dbl)
684                 return gripe("Field %d can't hold this value", fldno + 1);
685             if (tbl_skip_to_obj(next_id) < 0)
686                 return -1;
687         } else {
688             if (tbl_next_obj() < 0)
689                 return -1;
690         }
691     }
692     memb_ptr = cur_obj;
693     memb_ptr += ca->ca_off;
694
695     switch (ca->ca_type) {
696     case NSC_CHAR:
697         old = ((signed char *)memb_ptr)[idx];
698         new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
699         break;
700     case NSC_UCHAR:
701         old = ((unsigned char *)memb_ptr)[idx];
702         new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
703         break;
704     case NSC_SHORT:
705         old = ((short *)memb_ptr)[idx];
706         new = ((short *)memb_ptr)[idx] = (short)dbl;
707         break;
708     case NSC_USHORT:
709         old = ((unsigned short *)memb_ptr)[idx];
710         new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
711         break;
712     case NSC_INT:
713         old = ((int *)memb_ptr)[idx];
714         new = ((int *)memb_ptr)[idx] = (int)dbl;
715         break;
716     case NSC_LONG:
717         old = ((long *)memb_ptr)[idx];
718         new = ((long *)memb_ptr)[idx] = (long)dbl;
719         break;
720     case NSC_XCOORD:
721         old = ((coord *)memb_ptr)[idx];
722         /* FIXME use variant of xrel() that takes orig instead of nation */
723         if (old >= WORLD_X / 2)
724             old -= WORLD_X;
725         new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
726         if (new >= WORLD_X / 2)
727             new -= WORLD_X;
728         break;
729     case NSC_YCOORD:
730         old = ((coord *)memb_ptr)[idx];
731         /* FIXME use variant of yrel() that takes orig instead of nation */
732         if (old >= WORLD_Y / 2)
733             old -= WORLD_Y;
734         new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
735         if (new >= WORLD_Y / 2)
736             new -= WORLD_Y;
737         break;
738     case NSC_FLOAT:
739         old = ((float *)memb_ptr)[idx];
740         ((float *)memb_ptr)[idx] = (float)dbl;
741         new = dbl;              /* suppress new != dbl check */
742         break;
743     case NSC_DOUBLE:
744         old = ((double *)memb_ptr)[idx];
745         ((double *)memb_ptr)[idx] = dbl;
746         new = dbl;              /* suppress new != dbl check */
747         break;
748     case NSC_TIME:
749         old = ((time_t *)memb_ptr)[idx];
750         new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
751         break;
752     default:
753         return gripe("Field %d doesn't take numbers", fldno + 1);
754     }
755
756     if (fldval_must_match(fldno) && old != dbl)
757         return gripe("Value for field %d must be %g", fldno + 1, old);
758     if (new != dbl)
759         return gripe("Field %d can't hold this value", fldno + 1);
760
761     return 1;
762 }
763
764 /*
765  * Set value of field FLDNO in current object to STR.
766  * Return 1 on success, -1 on error.
767  */
768 static int
769 setstr(int fldno, char *str)
770 {
771     struct castr *ca;
772     int must_match, mismatch, idx;
773     size_t sz, len;
774     char *memb_ptr, *old;
775
776     ca = getfld(fldno, &idx);
777     if (!ca)
778         return -1;
779
780     if (fldno == 0) {
781         if (tbl_next_obj() < 0)
782             return -1;
783     }
784     memb_ptr = cur_obj;
785     memb_ptr += ca->ca_off;
786     must_match = fldval_must_match(fldno);
787     mismatch = 0;
788
789     switch (ca->ca_type) {
790     case NSC_STRING:
791         old = ((char **)memb_ptr)[idx];
792         if (must_match)
793             mismatch = old ? !str || strcmp(old, str) : !!str;
794         else
795             /* FIXME may leak old value */
796             ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
797         len = -1;               /* unlimited */
798         break;
799     case NSC_STRINGY:
800         if (CANT_HAPPEN(idx))
801             return -1;
802         if (!str)
803             return gripe("Field %d doesn't take nil", fldno + 1);
804         /* Wart: if ca_len <= 1, the terminating null may be omitted */
805         sz = ca->ca_len;
806         len = sz > 1 ? sz - 1 : sz;
807         if (strlen(str) > len)
808             return gripe("Field %d takes at most %d characters",
809                          fldno + 1, (int)len);
810         old = memb_ptr;
811         if (must_match)
812             mismatch = !str || strncmp(old, str, len);
813         else
814             strncpy(memb_ptr, str, sz);
815         break;
816     default:
817         return gripe("Field %d doesn't take strings", fldno + 1);
818     }
819
820     if (mismatch) {
821         if (old)
822             return gripe("Value for field %d must be \"%.*s\"",
823                          fldno + 1, (int)len, old);
824         else
825             return gripe("Value for field %d must be nil", fldno + 1);
826     }
827
828     return 1;
829 }
830
831 /*
832  * Resolve symbol name ID in table referred to by CA.
833  * Use field number N for error messages.
834  * Return index in referred table on success, -1 on failure.
835  */
836 static int
837 xunsymbol(char *id, struct castr *ca, int n)
838 {
839     int i = ef_elt_byname(ca->ca_table, id);
840     if (i < 0)
841         return gripe("%s %s symbol `%s' in field %d",
842                      i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
843                      ca->ca_name, id, n + 1);
844     return i;
845 }
846
847 /*
848  * Map symbol index to symbol value.
849  * CA is the table, and I is the index in it.
850  */
851 static int
852 symval(struct castr *ca, int i)
853 {
854     int type = ca->ca_table;
855
856     if (type != EF_BAD && ef_cadef(type) == symbol_ca)
857         /* symbol table, value is in the table */
858         return ((struct symbol *)ef_ptr(type, i))->value;
859     /* value is the table index */
860     return i;
861 }
862
863 /*
864  * Set value of field FLDNO in current object to value of symbol SYM.
865  * Return 1 on success, -1 on error.
866  */
867 static int
868 setsym(int fldno, char *sym)
869 {
870     struct castr *ca;
871     int i;
872
873     ca = getfld(fldno, NULL);
874     if (!ca)
875         return -1;
876
877     if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
878         return gripe("Field %d doesn't take symbols", fldno + 1);
879
880     i = xunsymbol(sym, ca, fldno);
881     if (i < 0)
882         return -1;
883     return setnum(fldno, symval(ca, i));
884 }
885
886 /*
887  * Create an empty symbol set for field FLDNO in *SET.
888  * Return 1 on success, -1 on error.
889  */
890 static int
891 mtsymset(int fldno, long *set)
892 {
893     struct castr *ca;
894
895     ca = getfld(fldno, NULL);
896     if (!ca)
897         return -1;
898
899     if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
900         || !(ca->ca_flags & NSC_BITS))
901         return gripe("Field %d doesn't take symbol sets", fldno + 1);
902     *set = 0;
903     return 0;
904 }
905
906 /*
907  * Add a symbol to a symbol set for field FLDNO in *SET.
908  * SYM is the name of the symbol to add.
909  * Return 1 on success, -1 on error.
910  */
911 static int
912 add2symset(int fldno, long *set, char *sym)
913 {
914     struct castr *ca;
915     int i;
916
917     ca = getfld(fldno, NULL);
918     if (!ca)
919         return -1;
920
921     i = xunsymbol(sym, ca, fldno);
922     if (i < 0)
923         return -1;
924     *set |= symval(ca, i);
925     return 0;
926 }
927
928 /*
929  * Read an xdump table header line from FP.
930  * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
931  * Recognize header for machine- and human-readable syntax, and set
932  * human accordingly.
933  * Return table type on success, -2 on EOF before header, -1 on failure.
934  */
935 static int
936 xuheader(FILE *fp, int expected_table)
937 {
938     char name[64];
939     int res, ch;
940     int type;
941
942     while ((ch = skipfs(fp)) == '\n')
943         lineno++;
944     if (ch == EOF && expected_table == EF_BAD)
945         return -2;
946     ungetc(ch, fp);
947
948     human = ch == 'c';
949     res = -1;
950     if ((human
951          ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
952          : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
953                   name, &res) != 1) || res < 0)
954         return gripe("Expected xdump header");
955
956     type = ef_byname(name);
957     if (type < 0)
958         return gripe("Unknown table `%s'", name);
959     if (expected_table != EF_BAD && expected_table != type)
960         return gripe("Expected table `%s', not `%s'",
961                      ef_nameof(expected_table), name);
962
963     if (!empfile[type].file
964         || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
965         CANT_HAPPEN(expected_table != EF_BAD);
966         return gripe("Table `%s' is not permitted here", name);
967     }
968
969     if (skipfs(fp) != '\n')
970         return gripe("Junk after xdump header");
971     lineno++;
972
973     return type;
974 }
975
976 /*
977  * Find fields in this xdump.
978  * If reading human-readable syntax, read a field header line from FP.
979  * Else take fields from the table's selectors in CA[].
980  * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
981  * Return 0 on success, -1 on failure.
982  */
983 static int
984 xufldhdr(FILE *fp, struct castr ca[])
985 {
986     struct castr **fca;
987     int *fidx;
988     int ch, i, j, n;
989
990     for (i = 0; ca[i].ca_name; i++)
991         caflds[i] = 0;
992     ellipsis = 0;
993
994     if (human) {
995         while ((ch = skipfs(fp)) == '\n')
996             lineno++;
997         ungetc(ch, fp);
998         nflds = xuflds(fp, xufldname);
999         if (nflds < 0)
1000             return -1;
1001         nflds -= ellipsis != 0;
1002     } else {
1003         fca = fldca;
1004         fidx = fldidx;
1005
1006         for (i = 0; ca[i].ca_name; i++) {
1007             if ((ca[i].ca_flags & NSC_EXTRA))
1008                 continue;
1009             n = CA_ARRAY_LEN(&ca[i]);
1010             j = 0;
1011             do {
1012                 *fca++ = &ca[i];
1013                 *fidx++ = j;
1014             } while (++j < n);
1015         }
1016
1017         nflds = fidx - fldidx;
1018     }
1019
1020     return 0;
1021 }
1022
1023 /*
1024  * Read xdump footer from FP.
1025  * CA[] contains the table's selectors.
1026  * The body had RECS records.
1027  * Update cafldspp[] from caflds[].
1028  * Return 0 on success, -1 on failure.
1029  */
1030 static int
1031 xufooter(FILE *fp, struct castr ca[], int recs)
1032 {
1033     int res, n, i;
1034
1035     res = -1;
1036     if (human) {
1037         if (fscanf(fp, "config%n", &res) != 0 || res < 0)
1038             return gripe("Malformed table footer");
1039     } else {
1040         if (fscanf(fp, "%d", &n) != 1)
1041             return gripe("Malformed table footer");
1042         if (recs != n)
1043             return gripe("Read %d rows, which doesn't match footer "
1044                          "%d rows", recs, n);
1045     }
1046     if (skipfs(fp) != '\n')
1047         return gripe("Junk after table footer");
1048     if (tbl_part_done() < 0)
1049         return -1;
1050     lineno++;
1051
1052     for (i = 0; ca[i].ca_name; i++) {
1053         if (cafldspp[i] < caflds[i])
1054             cafldspp[i] = caflds[i];
1055     }
1056
1057     return 0;
1058 }
1059
1060 /*
1061  * Read an xdump table from FP.
1062  * Both machine- and human-readable xdump syntax are recognized.
1063  * Expect table EXPECTED_TABLE, unless it is EF_BAD.
1064  * Report errors to stderr.
1065  * Messages assume FP starts in the file FILE at line *PLNO.
1066  * Update *PLNO to reflect lines read from FP.
1067  * Return table type on success, -2 on EOF before header, -1 on failure.
1068  */
1069 int
1070 xundump(FILE *fp, char *file, int *plno, int expected_table)
1071 {
1072     struct castr *ca;
1073     int type, nca, nf, i, ch;
1074
1075     fname = file;
1076     lineno = *plno;
1077
1078     if ((type = xuheader(fp, expected_table)) < 0)
1079         return type;
1080
1081     ca = ef_cadef(type);
1082     if (CANT_HAPPEN(!ca))
1083         return -1;
1084
1085     nca = nf = 0;
1086     for (i = 0; ca[i].ca_name; i++) {
1087         nca++;
1088         if (!(ca[i].ca_flags & NSC_EXTRA))
1089             nf += MAX(1, CA_ARRAY_LEN(&ca[i]));
1090     }
1091     fldca = malloc(nf * sizeof(*fldca));
1092     fldidx = malloc(nf * sizeof(*fldidx));
1093     caflds = malloc(nca * sizeof(*caflds));
1094     cafldspp = calloc(nca, sizeof(*cafldspp));
1095
1096     tbl_start(type);
1097     if (xutail(fp, ca) < 0)
1098         type = EF_BAD;
1099     tbl_end();
1100
1101     free(cafldspp);
1102     free(caflds);
1103     free(fldidx);
1104     free(fldca);
1105
1106     /* Skip empty lines so that callers can easily check for EOF */
1107     while ((ch = skipfs(fp)) == '\n')
1108         lineno++;
1109     ungetc(ch, fp);
1110
1111     *plno = lineno;
1112     return type;
1113 }
1114
1115 /*
1116  * Read the remainder of an xdump after the table header line from FP.
1117  * CA[] contains the table's selectors.
1118  * Return 0 on success, -1 on failure.
1119  */
1120 static int
1121 xutail(FILE *fp, struct castr *ca)
1122 {
1123     int recs;
1124
1125     for (;;) {
1126         if (xufldhdr(fp, ca) < 0)
1127             return -1;
1128         if ((recs = xubody(fp)) < 0)
1129             return -1;
1130         if (xufooter(fp, ca, recs) < 0)
1131             return -1;
1132         if (!ellipsis)
1133             return 0;
1134         if (xuheader(fp, cur_type) < 0)
1135             return -1;
1136     }
1137 }
1138
1139 /*
1140  * Read the body of an xdump table from FP.
1141  * Return number of rows read on success, -1 on failure.
1142  */
1143 static int
1144 xubody(FILE *fp)
1145 {
1146     int i, ch;
1147
1148     for (i = 0;; ++i) {
1149         while ((ch = skipfs(fp)) == '\n')
1150             lineno++;
1151         if (ch == '/')
1152             break;
1153         ungetc(ch, fp);
1154         if (xuflds(fp, xufld) < 0)
1155             return -1;
1156     }
1157     return i;
1158 }