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