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