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