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