]> git.pond.sub.org Git - empserver/blob - src/lib/common/xundump.c
Don't stop checking xdump field headers when join field is missing
[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     if (is_partial) {
412         /* Need a join field, use 0-th selector */
413         if (!caflds[0])
414             res = gripe("Header field %s required in each table part",
415                         ca[0].ca_name);
416     }
417
418     if (ellipsis)
419         return res;             /* table is split, another part expected */
420
421     /* Check for missing fields */
422     for (i = 0; ca[i].ca_name; i++) {
423         cafldsmax = MAX(caflds[i], cafldspp[i]);
424         if (ca[i].ca_flags & NSC_EXTRA)
425             continue;
426         len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
427         if (!len && !cafldsmax)
428             res = gripe("Header field %s missing", ca[i].ca_name);
429         else if (len && cafldsmax == len - 1)
430             res = gripe("Header field %s(%d) missing",
431                         ca[i].ca_name, len - 1);
432         else if (len && cafldsmax < len - 1)
433             res = gripe("Header fields %s(%d) ... %s(%d) missing",
434                         ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
435     }
436
437     return res;
438 }
439
440 /*
441  * Get selector for field FLDNO.
442  * Assign the field's selector index to *IDX, unless it is null.
443  * Return the selector on success, null pointer on error.
444  */
445 static struct castr *
446 getfld(int fldno, int *idx)
447 {
448     if (fldno >= nflds) {
449         gripe("Too many fields, expected only %d", nflds);
450         return NULL;
451     }
452     if (CANT_HAPPEN(fldno < 0))
453         return NULL;
454     if (idx)
455         *idx = fldidx[fldno];
456     return fldca[fldno];
457 }
458
459 /*
460  * Is a new value for field FLDNO required to match the old one?
461  */
462 static int
463 fldval_must_match(int fldno)
464 {
465     struct castr *ca = ef_cadef(cur_type);
466     int i = fldca[fldno] - ca;
467
468     /*
469      * Value must match if:
470      * it's for a const selector, unless the object is still blank, or
471      * it was already given in a previous part of a split table.
472      */
473     return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
474         || fldidx[fldno] < cafldspp[i];
475 }
476
477 /*
478  * Get the current object.
479  * Store it in cur_obj, and set cur_obj_is_blank accordingly.
480  * Return cur_obj, which is null on error.
481  */
482 static void *
483 getobj(void)
484 {
485     struct empfile *ep = &empfile[cur_type];
486
487     if (!cur_obj) {
488         cur_obj_is_blank = cur_id >= ep->fids;
489         if (cur_obj_is_blank) {
490             if (ef_ensure_space(cur_type, cur_id, 1))
491                 cur_obj = ef_ptr(cur_type, cur_id);
492             /* FIXME diagnose out of dynamic memory vs. static table full */
493             if (!cur_obj)
494                 gripe("Can't put ID %d into table %s, it holds only 0..%d.",
495                       cur_id, ep->name, ep->fids - 1);
496         } else
497             cur_obj = ef_ptr(cur_type, cur_id);
498     }
499
500     return cur_obj;
501 }
502
503 /*
504  * Set value of field FLDNO in current object to DBL.
505  * Return 1 on success, -1 on error.
506  */
507 static int
508 setnum(int fldno, double dbl)
509 {
510     struct castr *ca;
511     int idx;
512     char *memb_ptr;
513     double old;
514
515     ca = getfld(fldno, &idx);
516     if (!ca)
517         return -1;
518
519     /*
520      * If this is the record index, put it into cur_id.
521      */
522     if (fldno == 0 && ca->ca_table == cur_type)
523         cur_id = (int)dbl;
524
525     memb_ptr = getobj();
526     if (!memb_ptr)
527         return -1;
528     memb_ptr += ca->ca_off;
529
530     /* FIXME check assignment preserves value */
531     switch (ca->ca_type) {
532     case NSC_CHAR:
533         old = ((signed char *)memb_ptr)[idx];
534         ((signed char *)memb_ptr)[idx] = (signed char)dbl;
535         break;
536     case NSC_UCHAR:
537     case NSC_HIDDEN:
538         old = ((unsigned char *)memb_ptr)[idx];
539         ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
540         break;
541     case NSC_SHORT:
542         old = ((short *)memb_ptr)[idx];
543         ((short *)memb_ptr)[idx] = (short)dbl;
544         break;
545     case NSC_USHORT:
546         old = ((unsigned short *)memb_ptr)[idx];
547         ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
548         break;
549     case NSC_INT:
550         old = ((int *)memb_ptr)[idx];
551         ((int *)memb_ptr)[idx] = (int)dbl;
552         break;
553     case NSC_LONG:
554         old = ((long *)memb_ptr)[idx];
555         ((long *)memb_ptr)[idx] = (long)dbl;
556         break;
557     case NSC_XCOORD:
558         old = ((coord *)memb_ptr)[idx];
559         /* FIXME use variant of xrel() that takes orig instead of nation */
560         if (old >= WORLD_X / 2)
561             old -= WORLD_X;
562         ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
563         break;
564     case NSC_YCOORD:
565         old = ((coord *)memb_ptr)[idx];
566         /* FIXME use variant of yrel() that takes orig instead of nation */
567         if (old >= WORLD_Y / 2)
568             old -= WORLD_Y;
569         ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
570         break;
571     case NSC_FLOAT:
572         old = ((float *)memb_ptr)[idx];
573         ((float *)memb_ptr)[idx] = (float)dbl;
574         break;
575     case NSC_DOUBLE:
576         old = ((double *)memb_ptr)[idx];
577         ((double *)memb_ptr)[idx] = dbl;
578         break;
579     case NSC_TIME:
580         old = ((time_t *)memb_ptr)[idx];
581         ((time_t *)memb_ptr)[idx] = (time_t)dbl;
582         break;
583     default:
584         return gripe("Field %d doesn't take numbers", fldno + 1);
585     }
586
587     if (fldval_must_match(fldno) && old != dbl)
588         return gripe("Value for field %d must be %g", fldno + 1, old);
589
590     return 1;
591 }
592
593 /*
594  * Set value of field FLDNO in current object to STR.
595  * Return 1 on success, -1 on error.
596  */
597 static int
598 setstr(int fldno, char *str)
599 {
600     struct castr *ca;
601     int must_match, idx;
602     size_t len;
603     char *memb_ptr, *old;
604
605     ca = getfld(fldno, &idx);
606     if (!ca)
607         return -1;
608
609     memb_ptr = getobj();
610     if (!memb_ptr)
611         return -1;
612     memb_ptr += ca->ca_off;
613     must_match = fldval_must_match(fldno);
614
615     switch (ca->ca_type) {
616     case NSC_STRING:
617         old = ((char **)memb_ptr)[idx];
618         if (!must_match)
619             /* FIXME may leak old value */
620             ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
621         len = 65535;            /* really SIZE_MAX, but that's C99 */
622         break;
623     case NSC_STRINGY:
624         if (CANT_HAPPEN(idx))
625             return -1;
626         if (!str)
627             return gripe("Field %d doesn't take nil", fldno + 1);
628         len = ca->ca_len;
629         if (strlen(str) > len)
630             return gripe("Field %d takes at most %d characters",
631                          fldno + 1, (int)len);
632         old = memb_ptr;
633         if (!must_match)
634             strncpy(memb_ptr, str, len);
635         break;
636     default:
637         return gripe("Field %d doesn't take strings", fldno + 1);
638     }
639
640     if (must_match) {
641         if (old && (!str || strncmp(old, str, len)))
642             return gripe("Value for field %d must be \"%.*s\"",
643                          fldno + 1, (int)len, old);
644         if (!old && str)
645             return gripe("Value for field %d must be nil", fldno + 1);
646     }
647
648     return 1;
649 }
650
651 /*
652  * Resolve symbol name ID in table referred to by CA.
653  * Use field number N for error messages.
654  * Return index in referred table on success, -1 on failure.
655  */
656 static int
657 xunsymbol(char *id, struct castr *ca, int n)
658 {
659     int i = ef_elt_byname(ca->ca_table, id);
660     if (i < 0)
661         return gripe("%s %s symbol `%s' in field %d",
662                      i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
663                      ca->ca_name, id, n + 1);
664     return i;
665 }
666
667 /*
668  * Map symbol index to symbol value.
669  * CA is the table, and I is the index in it.
670  */
671 static int
672 symval(struct castr *ca, int i)
673 {
674     int type = ca->ca_table;
675
676     if (type != EF_BAD && ef_cadef(type) == symbol_ca)
677         /* symbol table, value is in the table */
678         return ((struct symbol *)ef_ptr(type, i))->value;
679     /* value is the table index */
680     return i;
681 }
682
683 /*
684  * Set value of field FLDNO in current object to value of symbol SYM.
685  * Return 1 on success, -1 on error.
686  */
687 static int
688 setsym(int fldno, char *sym)
689 {
690     struct castr *ca;
691     int i;
692
693     ca = getfld(fldno, NULL);
694     if (!ca)
695         return -1;
696
697     if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
698         return gripe("Field %d doesn't take symbols", fldno + 1);
699
700     i = xunsymbol(sym, ca, fldno);
701     if (i < 0)
702         return -1;
703     return setnum(fldno, symval(ca, i));
704 }
705
706 /*
707  * Create an empty symbol set for field FLDNO in *SET.
708  * Return 1 on success, -1 on error.
709  */
710 static int
711 mtsymset(int fldno, long *set)
712 {
713     struct castr *ca;
714
715     ca = getfld(fldno, NULL);
716     if (!ca)
717         return -1;
718
719     if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
720         || !(ca->ca_flags & NSC_BITS))
721         return gripe("Field %d doesn't take symbol sets", fldno + 1);
722     *set = 0;
723     return 0;
724 }
725
726 /*
727  * Add a symbol to a symbol set for field FLDNO in *SET.
728  * SYM is the name of the symbol to add.
729  * Return 1 on success, -1 on error.
730  */
731 static int
732 add2symset(int fldno, long *set, char *sym)
733 {
734     struct castr *ca;
735     int i;
736
737     ca = getfld(fldno, NULL);
738     if (!ca)
739         return -1;
740
741     i = xunsymbol(sym, ca, fldno);
742     if (i < 0)
743         return -1;
744     *set |= symval(ca, i);
745     return 0;
746 }
747
748 /*
749  * Read an xdump table header line from FP.
750  * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
751  * Recognize header for machine- and human-readable syntax, and set
752  * human accordingly.
753  * Return table type on success, -2 on EOF before header, -1 on failure.
754  */
755 static int
756 xuheader(FILE *fp, int expected_table)
757 {
758     char name[64];
759     int res, ch;
760     int type;
761
762     while ((ch = skipfs(fp)) == '\n')
763         lineno++;
764     if (ch == EOF && expected_table == EF_BAD)
765         return -2;
766     ungetc(ch, fp);
767
768     human = ch == 'c';
769     res = -1;
770     if ((human
771          ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
772          : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
773                   name, &res) != 1) || res < 0)
774         return gripe("Expected xdump header");
775
776     type = ef_byname(name);
777     if (type < 0)
778         return gripe("Unknown table `%s'", name);
779     if (expected_table != EF_BAD && expected_table != type)
780         return gripe("Expected table `%s', not `%s'",
781                      ef_nameof(expected_table), name);
782
783     if (!ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
784         CANT_HAPPEN(expected_table != EF_BAD);
785         return gripe("Table `%s' is not permitted here", name);
786     }
787
788     if (skipfs(fp) != '\n')
789         return gripe("Junk after xdump header");
790     lineno++;
791
792     return type;
793 }
794
795 /*
796  * Find fields in this xdump.
797  * If reading human-readable syntax, read a field header line from FP.
798  * Else take fields from the table's selectors in CA[].
799  * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
800  * Return 0 on success, -1 on failure.
801  */
802 static int
803 xufldhdr(FILE *fp, struct castr ca[])
804 {
805     struct castr **fca;
806     int *fidx;
807     int ch, i, j, n;
808
809     for (i = 0; ca[i].ca_name; i++)
810         caflds[i] = 0;
811     ellipsis = 0;
812
813     if (human) {
814         while ((ch = skipfs(fp)) == '\n')
815             lineno++;
816         ungetc(ch, fp);
817         nflds = xuflds(fp, xufldname);
818         if (nflds < 0)
819             return -1;
820         nflds -= ellipsis != 0;
821     } else {
822         fca = fldca;
823         fidx = fldidx;
824
825         for (i = 0; ca[i].ca_name; i++) {
826             if ((ca[i].ca_flags & NSC_EXTRA))
827                 continue;
828             n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
829             j = 0;
830             do {
831                 *fca++ = &ca[i];
832                 *fidx++ = j;
833             } while (++j < n);
834         }
835
836         nflds = fidx - fldidx;
837     }
838
839     return 0;
840 }
841
842 /*
843  * Read xdump footer from FP.
844  * CA[] contains the table's selectors.
845  * The body had RECS records.
846  * Update cafldspp[] from caflds[].
847  * Return 0 on success, -1 on failure.
848  */
849 static int
850 xufooter(FILE *fp, struct castr ca[], int recs)
851 {
852     int res, n, i;
853
854     res = -1;
855     if (human) {
856         if (fscanf(fp, "config%n", &res) != 0 || res < 0)
857             return gripe("Malformed table footer");
858     } else {
859         if (fscanf(fp, "%d", &n) != 1)
860             return gripe("Malformed table footer");
861         if (recs != n)
862             return gripe("Read %d rows, which doesn't match footer "
863                          "%d rows", recs, n);
864     }
865     if (skipfs(fp) != '\n')
866         return gripe("Junk after table footer");
867     lineno++;
868
869     for (i = 0; ca[i].ca_name; i++) {
870         if (cafldspp[i] < caflds[i])
871             cafldspp[i] = caflds[i];
872     }
873
874     return 0;
875 }
876
877 /*
878  * Read an xdump table from FP.
879  * Both machine- and human-readable xdump syntax are recognized.
880  * Expect table EXPECTED_TABLE, unless it is EF_BAD.
881  * Report errors to stderr.
882  * Messages assume FP starts in the file FILE at line *PLNO.
883  * Update *PLNO to reflect lines read from FP.
884  * Return table type on success, -2 on EOF before header, -1 on failure.
885  */
886 int
887 xundump(FILE *fp, char *file, int *plno, int expected_table)
888 {
889     struct castr *ca;
890     int type, nca, nf, i, ch;
891
892     fname = file;
893     lineno = *plno;
894
895     if ((type = xuheader(fp, expected_table)) < 0)
896         return type;
897
898     ca = ef_cadef(type);
899     if (CANT_HAPPEN(!ca))
900         return -1;
901
902     nca = nf = 0;
903     for (i = 0; ca[i].ca_name; i++) {
904         nca++;
905         if (!(ca[i].ca_flags & NSC_EXTRA))
906             nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
907     }
908     fldca = malloc(nf * sizeof(*fldca));
909     fldidx = malloc(nf * sizeof(*fldidx));
910     caflds = malloc(nca * sizeof(*caflds));
911     cafldspp = calloc(nca, sizeof(*cafldspp));
912     cur_type = type;
913
914     if (xutail(fp, ca) < 0)
915         type = EF_BAD;
916
917     free(cafldspp);
918     free(caflds);
919     free(fldidx);
920     free(fldca);
921
922     /* Skip empty lines so that callers can easily check for EOF */
923     while ((ch = skipfs(fp)) == '\n')
924         lineno++;
925     ungetc(ch, fp);
926
927     *plno = lineno;
928     return type;
929 }
930
931 /*
932  * Read the remainder of an xdump after the table header line from FP.
933  * CA[] contains the table's selectors.
934  * Return 0 on success, -1 on failure.
935  */
936 static int
937 xutail(FILE *fp, struct castr *ca)
938 {
939     int recs;
940
941     is_partial = 0;
942     for (;;) {
943         if (xufldhdr(fp, ca) < 0)
944             return -1;
945         if ((recs = xubody(fp)) < 0)
946             return -1;
947         if (xufooter(fp, ca, recs) < 0)
948             return -1;
949         if (!ellipsis)
950             return 0;
951         if (xuheader(fp, cur_type) < 0)
952             return -1;
953     }
954 }
955
956 /*
957  * Read the body of an xdump table from FP.
958  * Return number of rows read on success, -1 on failure.
959  */
960 static int
961 xubody(FILE *fp)
962 {
963     struct empfile *ep = &empfile[cur_type];
964     int i, maxid, ch;
965
966     maxid = 0;
967     for (i = 0;; ++i) {
968         while ((ch = skipfs(fp)) == '\n')
969             lineno++;
970         if (ch == '/')
971             break;
972         ungetc(ch, fp);
973         cur_obj = NULL;
974         cur_id = i;
975         if (xuflds(fp, xufld) < 0)
976             return -1;
977         maxid = MAX(maxid, cur_id + 1);
978     }
979
980     if (CANT_HAPPEN(maxid > ep->fids))
981         maxid = ep->fids;
982     if (maxid < ep->fids) {
983         if (EF_IS_GAME_STATE(cur_type)
984             || (cur_type >= EF_SHIP_CHR && cur_type <= EF_NUKE_CHR))
985             ef_truncate(cur_type, maxid);
986         else
987             return gripe("Table %s requires %d rows, got %d",
988                          ef_nameof(cur_type), ep->fids, maxid);
989     }
990
991     return i;
992 }