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