Some minor refinements from expanding the corpus.
[pspp] / dump.c
1 #include <assert.h>
2 #include <float.h>
3 #include <stdbool.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10 #include "u8-mbtouc.h"
11
12 static uint8_t *data;
13 static size_t n;
14
15 int version;
16
17 static bool
18 all_ascii(const uint8_t *p, size_t n)
19 {
20   for (size_t i = 0; i < n; i++)
21     if (p[i] < 32 || p[i] > 126)
22       return false;
23   return true;
24 }
25
26 static size_t
27 try_find(const char *target, size_t target_len)
28 {
29   const uint8_t *pos = (const uint8_t *) memmem (data, n, target, target_len);
30   return pos ? pos - data : 0;
31 }
32
33 static size_t
34 find(const char *target, size_t target_len)
35 {
36   size_t pos = try_find(target, target_len);
37   if (!pos)
38     {
39       fprintf (stderr, "not found\n");
40       exit(1);
41     }
42   return pos;
43 }
44
45 size_t pos;
46
47 #define XSTR(x) #x
48 #define STR(x) XSTR(x)
49 #define WHERE __FILE__":" STR(__LINE__)
50
51 static unsigned int
52 get_u32(void)
53 {
54   uint32_t x;
55   memcpy(&x, &data[pos], 4);
56   pos += 4;
57   return x;
58 }
59
60 static double
61 get_double(void)
62 {
63   double x;
64   memcpy(&x, &data[pos], 8);
65   pos += 8;
66   return x;
67 }
68
69 static bool
70 match_u32(uint32_t x)
71 {
72   if (get_u32() == x)
73     return true;
74   pos -= 4;
75   return false;
76 }
77
78 static void
79 match_u32_assert(uint32_t x, const char *where)
80 {
81   unsigned int y = get_u32();
82   if (x != y)
83     {
84       fprintf(stderr, "%s: 0x%x: expected i%u, got i%u\n", where, pos - 4, x, y);
85       exit(1);
86     }
87 }
88 #define match_u32_assert(x) match_u32_assert(x, WHERE)
89
90 static bool
91 match_byte(uint8_t b)
92 {
93   if (pos < n && data[pos] == b)
94     {
95       pos++;
96       return true;
97     }
98   else
99     return false;
100 }
101
102 static void
103 match_byte_assert(uint8_t b, const char *where)
104 {
105   if (!match_byte(b))
106     {
107       fprintf(stderr, "%s: 0x%x: expected %02x, got %02x\n", where, pos, b, data[pos]);
108       exit(1);
109     }
110 }
111 #define match_byte_assert(b) match_byte_assert(b, WHERE)
112
113 static void
114 newline(FILE *stream, int pos)
115 {
116   fprintf(stream, "\n%08x: ", pos);
117 }
118
119 static void
120 dump_raw(FILE *stream, int start, int end)
121 {
122   for (size_t i = start; i < end; )
123     {
124       if (i + 5 <= n
125           && data[i]
126           //&& !data[i + 1]
127           && !data[i + 2]
128           && !data[i + 3]
129           && i + 4 + data[i] + data[i + 1] * 256 <= end
130           && all_ascii(&data[i + 4], data[i] + data[i + 1] * 256))
131         {
132           newline(stream, i);
133           fprintf(stream, "\"");
134           fwrite(&data[i + 4], 1, data[i] + data[i + 1] * 256, stream);
135           fputs("\" ", stream);
136
137           i += 4 + data[i] + data[i + 1] * 256;
138         }
139       else if (i + 12 <= end
140                && data[i + 1] == 40
141                && data[i + 2] == 5
142                && data[i + 3] == 0)
143         {
144           double d;
145
146           memcpy (&d, &data[i + 4], 8);
147           fprintf (stream, "F40.%d(%.*f)", data[i], data[i], d);
148           i += 12;
149           newline (stream, i);
150         }
151       else if (i + 12 <= end
152                && data[i + 1] == 40
153                && data[i + 2] == 31
154                && data[i + 3] == 0)
155         {
156           double d;
157
158           memcpy (&d, &data[i + 4], 8);
159           fprintf (stream, "PCT40.%d(%.*f)", data[i], data[i], d);
160           i += 12;
161           newline(stream, i);
162         }
163       else if (i + 4 <= end
164                && (data[i] && data[i] != 88 && data[i] != 0x41)
165                && !data[i + 1]
166                && !data[i + 2]
167                && !data[i + 3])
168         {
169           fprintf (stream, "i%d ", data[i]);
170           i += 4;
171         }
172       else
173         {
174           fprintf(stream, "%02x ", data[i]);
175           i++;
176         }
177     }
178
179
180 }
181
182 static bool __attribute__((unused))
183 all_utf8(const char *p_)
184 {
185   const uint8_t *p = (const uint8_t *) p_;
186   size_t len = strlen ((char *) p);
187   for (size_t ofs = 0, mblen; ofs < len; ofs += mblen)
188     {
189       ucs4_t uc;
190
191       mblen = u8_mbtouc (&uc, p + ofs, len - ofs);
192       if ((uc < 32 && uc != '\n') || uc == 127 || uc == 0xfffd)
193         return false;
194     }
195   return true;
196 }
197
198 static char *
199 get_string(const char *where)
200 {
201   if (1
202       /*data[pos + 1] == 0 && data[pos + 2] == 0 && data[pos + 3] == 0*/
203       /*&& all_ascii(&data[pos + 4], data[pos])*/)
204     {
205       int len = data[pos] + data[pos + 1] * 256;
206       char *s = malloc(len + 1);
207
208       memcpy(s, &data[pos + 4], len);
209       s[len] = 0;
210       pos += 4 + len;
211       return s;
212     }
213   else
214     {
215       fprintf(stderr, "%s: 0x%x: expected string\n", where, pos);
216       exit(1);
217     }
218 }
219 #define get_string() get_string(WHERE)
220
221 static int
222 get_end(void)
223 {
224   int len = get_u32();
225   return pos + len;
226 }
227
228 static char *
229 dump_counted_string(void)
230 {
231   char *s = NULL;
232   int inner_end = get_end();
233   if (pos != inner_end)
234     {
235       match_u32_assert(0);
236       if (match_byte(0x31))
237         s = get_string();
238       else
239         match_byte_assert(0x58);
240       if (pos != inner_end)
241         {
242           fprintf(stderr, "inner end discrepancy\n");
243           exit(1);
244         }
245     }
246   return s;
247 }
248
249 static void __attribute__((unused))
250 hex_dump(int ofs, int n)
251 {
252   for (int i = 0; i < n; i++)
253     {
254       int c = data[ofs + i];
255 #if 1
256       if (i && !(i % 16))
257         fprintf(stderr, "-");
258       else
259         fprintf(stderr, " ");
260 #endif
261       fprintf(stderr, "%02x", c);
262       //fprintf(stderr, "%c", c >= 32 && c < 127 ? c : '.');
263     }
264   fprintf(stderr, "\n");
265 }
266
267 static void
268 dump_style(void)
269 {
270   match_byte(1);
271   match_byte(0);
272   match_byte(0);
273   match_byte(0);
274   match_byte_assert(1);
275   get_string();     /* foreground */
276   get_string();     /* background */
277   get_string();     /* font */
278   if (!match_byte(14))
279     match_byte_assert(12); /* size? */
280 }
281
282 static char *
283 dump_nested_string(void)
284 {
285   char *s = NULL;
286
287   match_byte_assert (0);
288   match_byte_assert (0);
289   int outer_end = get_end();
290   s = dump_counted_string();
291   if (match_byte(0x31))
292     dump_style();
293   else
294     match_byte_assert(0x58);
295   match_byte_assert(0x58);
296   if (pos != outer_end)
297     {
298       fprintf(stderr, "outer end discrepancy\n");
299       exit(1);
300     }
301
302   return s;
303 }
304
305 static void
306 dump_optional_value(FILE *stream)
307 {
308   if (match_byte (0x31))
309     {
310       if (match_u32 (0))
311         {
312           if (match_u32 (1))
313             {
314               /* Corpus frequencies:
315                  124 "a"
316                  12 "b"
317                  8 "a, b"
318               */
319               get_string();
320             }
321           else
322             match_u32_assert (0);
323
324           if (version == 1)
325             {
326               /* We only have one SPV file for this version (with many
327                  tables). */
328               match_byte(0);
329               if (!match_u32(1))
330                 match_u32_assert(2);
331               match_byte(0);
332               match_byte(0);
333               if (!match_u32(0) && !match_u32(1) && !match_u32(2) && !match_u32(3) && !match_u32(4) && !match_u32(5) && !match_u32(6) && !match_u32(7) && !match_u32(8) && !match_u32(9))
334                 match_u32_assert(10);
335               match_byte(0);
336               match_byte(0);
337               return;
338             }
339
340           int outer_end = get_end();
341           
342           /* This counted-string appears to be a template string,
343              e.g. "Design\: [:^1:]1 Within Subjects Design\: [:^1:]2". */
344           dump_counted_string();
345
346           if (match_byte(0x31))
347             dump_style();
348           else
349             match_byte_assert(0x58);
350           if (match_byte(0x31))
351             {
352               /* Only two SPV files have anything like this, so it's hard to
353                  generalize. */
354               match_u32_assert(0);
355               match_u32_assert(0);
356               match_u32_assert(0);
357               match_u32_assert(0);
358               match_byte_assert(1);
359               match_byte_assert(0);
360               if (!match_byte(8) && !match_byte(1))
361                 match_byte_assert(2);
362               match_byte_assert(0);
363               match_byte_assert(8);
364               match_byte_assert(0);
365               match_byte_assert(10);
366               match_byte_assert(0);
367             }
368           else
369             match_byte_assert(0x58);
370           if (pos != outer_end)
371             {
372               fprintf(stderr, "outer end discrepancy\n");
373               exit(1);
374             }
375         }
376       else if (match_u32 (1))
377         {
378           fprintf(stream, "(footnote %d) ", get_u32());
379           dump_nested_string();
380         }
381       else if (match_u32 (2))
382         {
383           fprintf(stream, "(special 2)");
384           if (!match_byte(0) && !match_byte(1))
385             match_byte_assert(2);
386           match_byte_assert(0);
387           if (!match_u32 (2) && !match_u32(1))
388             match_u32_assert(3);
389           dump_nested_string();
390         }
391       else
392         {
393           match_u32_assert(3);
394           fprintf(stream, "(special 3)");
395           match_byte_assert(0);
396           match_byte_assert(0);
397           match_byte_assert(1);
398           match_byte_assert(0);
399           match_u32_assert(2);
400           dump_nested_string(); /* Our corpus doesn't contain any examples with strings though. */
401         }
402     }
403   else
404     match_byte_assert (0x58);
405 }
406
407 static const char *
408 format_to_string (int type)
409 {
410   static char tmp[16];
411   switch (type)
412     {
413     case 1: return "A";
414     case 2: return "AHEX";
415     case 3: return "COMMA";
416     case 4: return "DOLLAR";
417     case 5: case 40: return "F";
418     case 6: return "IB";
419     case 7: return "PIBHEX";
420     case 8: return "P";
421     case 9: return "PIB";
422     case 10: return "PK";
423     case 11: return "RB";
424     case 12: return "RBHEX";
425     case 15: return "Z";
426     case 16: return "N";
427     case 17: return "E";
428     case 20: return "DATE";
429     case 21: return "TIME";
430     case 22: return "DATETIME";
431     case 23: return "ADATE";
432     case 24: return "JDATE";
433     case 25: return "DTIME";
434     case 26: return "WKDAY";
435     case 27: return "MONTH";
436     case 28: return "MOYR";
437     case 29: return "QYR";
438     case 30: return "WKYR";
439     case 31: return "PCT";
440     case 32: return "DOT";
441     case 33: return "CCA";
442     case 34: return "CCB";
443     case 35: return "CCC";
444     case 36: return "CCD";
445     case 37: return "CCE";
446     case 38: return "EDATE";
447     case 39: return "SDATE";
448     default:
449       abort();
450       sprintf(tmp, "<%d>", type);
451       return tmp;
452     }
453 }
454
455 static void
456 dump_value(FILE *stream, int level)
457 {
458   match_byte(0);
459   match_byte(0);
460   match_byte(0);
461   match_byte(0);
462
463   for (int i = 0; i <= level; i++)
464     fprintf (stream, "    ");
465
466   if (match_byte (1))
467     {
468       unsigned int format;
469       double value;
470
471       dump_optional_value(stream);
472       format = get_u32 ();
473       value = get_double ();
474       fprintf (stream, "<number value=\"%.*g\" format=\"%s%d.%d\"/>\n",
475                DBL_DIG, value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
476     }
477   else if (match_byte (2))
478     {
479       unsigned int format;
480       char *var, *vallab;
481       double value;
482
483       dump_optional_value (stream);
484       format = get_u32 ();
485       value = get_double ();
486       var = get_string ();
487       vallab = get_string ();
488       fprintf (stream, "<numeric-datum value=\"%.*g\" format=\"%s%d.%d\"",
489               DBL_DIG, value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
490       if (var[0])
491         fprintf (stream, " variable=\"%s\"", var);
492       if (vallab[0])
493         fprintf (stream, " label=\"%s\"/>\n", vallab);
494       fprintf (stream, "/>\n");
495       if (!match_byte (1) && !match_byte(2))
496         match_byte_assert (3);
497     }
498   else if (match_byte (3))
499     {
500       char *text =  get_string();
501       dump_optional_value(stream);
502       char *identifier = get_string();
503       char *text_eng = get_string();
504       fprintf (stream, "<string c=\"%s\"", text_eng);
505       if (identifier[0])
506         fprintf (stream, " identifier=\"%s\"", identifier);
507       if (strcmp(text_eng, text))
508         fprintf (stream, " local=\"%s\"", text);
509       fprintf (stream, "/>\n");
510       if (!match_byte (0))
511         match_byte_assert(1);
512     }
513   else if (match_byte (4))
514     {
515       unsigned int format;
516       char *var, *vallab, *value;
517
518       dump_optional_value(stream);
519       format = get_u32 ();
520       vallab = get_string ();
521       var = get_string ();
522       if (!match_byte(1) && !match_byte(2))
523         match_byte_assert (3);
524       value = get_string ();
525       fprintf (stream, "<string-datum value=\"%s\" format=\"%s%d.%d\"",
526               value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
527       if (var[0])
528         fprintf (stream, " variable=\"%s\"", var);
529       if (vallab[0])
530         fprintf (stream, " label=\"%s\"/>\n", vallab);
531       fprintf (stream, "/>\n");
532     }
533   else if (match_byte (5))
534     {
535       dump_optional_value(stream);
536       char *name = get_string ();
537       char *label = get_string ();
538       fprintf (stream, "<variable name=\"%s\"", name);
539       if (label[0])
540         fprintf (stream, " label=\"%s\"", label);
541       fprintf (stream, "/>\n");
542       if (!match_byte(1) && !match_byte(2))
543         match_byte_assert(3);
544     }
545   else
546     {
547       dump_optional_value(stream);
548
549       char *base = get_string();
550       int x = get_u32();
551       fprintf (stream, "<template format=\"%s\">\n", base);
552       for (int i = 0; i < x; i++)
553         {
554           int y = get_u32();
555           if (!y)
556             y = 1;
557           else
558             match_u32_assert(0);
559           for (int j = 0; j <= level + 1; j++)
560             fprintf (stream, "    ");
561           fprintf (stream, "<substitution index=\"%d\">\n", i + 1);
562           for (int j = 0; j < y; j++)
563             dump_value (stream, level + 2);
564           for (int j = 0; j <= level + 1; j++)
565             fprintf (stream, "    ");
566           fprintf (stream, "</substitution>\n");
567         }
568       for (int j = 0; j <= level; j++)
569         fprintf (stream, "    ");
570       fprintf (stream, "</template>\n");
571     }
572 }
573
574 static int
575 compare_int(const void *a_, const void *b_)
576 {
577   const int *a = a_;
578   const int *b = b_;
579   return *a < *b ? -1 : *a > *b;
580 }
581
582 static void
583 check_permutation(int *a, int n, const char *name)
584 {
585   int b[n];
586   memcpy(b, a, n * sizeof *a);
587   qsort(b, n, sizeof *b, compare_int);
588   for (int i = 0; i < n; i++)
589     if (b[i] != i)
590       {
591         fprintf(stderr, "bad %s permutation:", name);
592         for (int i = 0; i < n; i++)
593           fprintf(stderr, " %d", a[i]);
594         putc('\n', stderr);
595         exit(1);
596       }
597 }
598
599 static void
600 dump_category(FILE *stream, int level, int *indexes, int *n_indexes, int max_indexes)
601 {
602   for (int i = 0; i <= level; i++)
603     fprintf (stream, "    ");
604   printf ("<category>\n");
605   dump_value (stream, level + 1);
606
607   int merge = data[pos];
608   if (!match_byte(0))
609     match_byte_assert (1);
610
611   match_byte_assert (0);
612
613   int unindexed = data[pos];
614   if (!match_byte(0))
615     match_byte_assert (1);
616
617   int x = get_u32 ();
618   pos -= 4;
619   if (!match_u32 (0))
620     match_u32_assert (2);
621
622   int indx = get_u32();
623   int n_categories = get_u32();
624   if (indx == -1)
625     {
626       if (merge)
627         {
628           for (int i = 0; i <= level + 1; i++)
629             fprintf (stream, "    ");
630           fprintf (stream, "<merge/>\n");
631         }
632     }
633   else
634     {
635       if (merge)
636         {
637           fprintf(stderr, "index not -1 but merged\n");
638           exit(1);
639         }
640       if (x != 2)
641         {
642           fprintf(stderr, "index not -1 but x != 2\n");
643           exit(1);
644         }
645       if (n_categories != 0)
646         {
647           fprintf(stderr, "index not -1 but subcategories\n");
648           exit(1);
649         }
650       if (*n_indexes >= max_indexes)
651         {
652           fprintf(stderr, "too many categories (increase max_indexes)\n");
653           exit(1);
654         }
655       indexes[(*n_indexes)++] = indx;
656     }
657
658   int expected_unindexed = indx == -1;
659   if (unindexed != expected_unindexed)
660     {
661       fprintf(stderr, "unindexed (%d) mismatch with indx (%d)\n",
662               unindexed, indx);
663       exit(1);
664     }
665
666   if (n_categories == 0)
667     {
668       for (int i = 0; i <= level + 1; i++)
669         fprintf (stream, "    ");
670       fprintf (stream, "<category-index>%d</category-index>\n", indx);
671     }
672   for (int i = 0; i < n_categories; i++)
673     dump_category (stream, level + 1, indexes, n_indexes, max_indexes);
674   for (int i = 0; i <= level; i++)
675     fprintf (stream, "    ");
676   printf ("</category>\n");
677 }
678
679 static int
680 dump_dim(int indx)
681 {
682   int n_categories;
683
684   printf ("<dimension index=\"%d\">\n", indx);
685   dump_value (stdout, 0);
686
687   /* This byte is usually 0 but many other values have been spotted. */
688   pos++;
689
690   if (!match_byte(0) && !match_byte(1))
691     match_byte_assert(2);
692   if (!match_u32(0))
693     match_u32_assert(2);
694   if (!match_byte(0))
695     match_byte_assert(1);
696   if (!match_byte(0))
697     match_byte_assert(1);
698   match_byte_assert(1);
699   if (!match_u32(UINT32_MAX))
700     match_u32_assert(indx);
701   n_categories = get_u32();
702
703   int indexes[2048];
704   int n_indexes = 0;
705   for (int i = 0; i < n_categories; i++)
706     dump_category (stdout, 0, indexes, &n_indexes, sizeof indexes / sizeof *indexes);
707   check_permutation(indexes, n_indexes, "categories");
708
709   fprintf (stdout, "</dimension>\n");
710   return n_indexes;
711 }
712
713 int n_dims;
714 static int dim_n_cats[64];
715 #define MAX_DIMS (sizeof dim_n_cats / sizeof *dim_n_cats)
716
717 static void
718 dump_dims(void)
719 {
720   n_dims = get_u32();
721   assert(n_dims < MAX_DIMS);
722   for (int i = 0; i < n_dims; i++)
723     dim_n_cats[i] = dump_dim (i);
724 }
725
726 static void
727 dump_data(void)
728 {
729   /* The first three numbers add to the number of dimensions. */
730   int l = get_u32();
731   int r = get_u32();
732   int c = n_dims - l - r;
733   match_u32_assert(c);
734
735   /* The next n_dims numbers are a permutation of the dimension numbers. */
736   int a[n_dims];
737   for (int i = 0; i < n_dims; i++)
738     {
739       int dim = get_u32();
740       a[i] = dim;
741
742       const char *name = i < l ? "layer" : i < l + r ? "row" : "column";
743       printf ("<%s dimension=\"%d\"/>\n", name, dim);
744     }
745   check_permutation(a, n_dims, "dimensions");
746
747   int x = get_u32();
748   printf ("<data>\n");
749   for (int i = 0; i < x; i++)
750     {
751       unsigned int indx = get_u32();
752       printf ("    <datum index=\"%d\" coords=", indx);
753
754       int coords[MAX_DIMS];
755       for (int i = n_dims; i-- > 0; )
756         {
757           coords[i] = indx % dim_n_cats[i];
758           indx /= dim_n_cats[i];
759         }
760       for (int i = 0; i < n_dims; i++)
761         printf("%c%d", i ? ',' : '"', coords[i]);
762
763       printf ("\">\n");
764       match_u32_assert(0);
765       if (version == 1)
766         match_byte(0);
767       dump_value(stdout, 1);
768       fprintf (stdout, "    </datum>\n");
769     }
770   printf ("</data>\n");
771 }
772
773 static void
774 dump_title(void)
775 {
776   printf ("<title-local>\n");
777   dump_value(stdout, 0);
778   match_byte(1);
779   printf ("</title-local>\n");
780
781   printf ("<subtype>\n");
782   dump_value(stdout, 0);
783   match_byte(1);
784   printf ("</subtype>\n");
785
786   match_byte_assert(0x31);
787
788   printf ("<title-c>\n");
789   dump_value(stdout, 0);
790   match_byte(1);
791   printf ("</title-c>\n");
792
793   match_byte(0);
794   match_byte_assert(0x58);
795   if (match_byte(0x31))
796     {
797       printf ("<caption>\n");
798       dump_value(stdout, 0);
799       printf ("</caption>\n");
800     }
801   else
802     match_byte_assert(0x58);
803
804   int n_footnotes = get_u32();
805   for (int i = 0; i < n_footnotes; i++)
806     {
807       printf ("<footnote index=\"%d\">\n", i);
808       dump_value(stdout, 0);
809       /* Custom footnote marker string. */
810       if (match_byte (0x31))
811         dump_value(stdout, 0);
812       else
813         match_byte_assert (0x58);
814       get_u32 ();
815       printf ("</footnote>\n");
816     }
817 }
818
819 static void
820 dump_fonts(void)
821 {
822   match_byte(0);
823   for (int i = 1; i <= 8; i++)
824     {
825       printf ("<style index=\"%d\"", i);
826       match_byte_assert(i);
827       match_byte_assert(0x31);
828       printf(" font=\"%s\"", get_string());
829       match_byte_assert(0);
830       match_byte_assert(0);
831       if (!match_byte(0x40) && !match_byte(0x20) && !match_byte(0x80) && !match_byte(0x10) && !match_byte(0x70))
832         match_byte_assert(0x50);
833       match_byte_assert(0x41);
834       if (!match_u32(0) && !match_u32(1))
835         match_u32_assert(2);
836       match_byte_assert(0);
837
838       /* OK, this seems really unlikely to be totally correct, but it matches my corpus... */
839       if (!match_u32(0) && !match_u32(2))
840         {
841           if (i == 7)
842             match_u32_assert(0xfaad);
843           else
844             match_u32_assert(0);
845         }
846
847       if (!match_u32(0) && !match_u32(1) && !match_u32(2))
848         match_u32_assert(3);
849       printf (" fgcolor=\"%s\"", get_string());
850       printf (" bgcolor=\"%s\"", get_string());
851       match_u32_assert(0);
852       match_u32_assert(0);
853       match_byte_assert(0);
854
855       if (version > 1)
856         {
857           if (i != 3)
858             {
859               if (!match_u32(8))
860                 match_u32_assert(5);
861               if (!match_u32(10) && !match_u32(11) && !match_u32(5))
862                 match_u32_assert(9);
863               if (!match_u32(0) && !match_u32(1))
864                 match_u32_assert(2);
865             }
866           else
867             {
868               get_u32();
869               if (!match_u32(-1) && !match_u32(8))
870                 match_u32_assert(24);
871               if (!match_u32(-1) && !match_u32(2))
872                 match_u32_assert(3);
873             }
874
875           /* Who knows? Ranges from -1 to 8 with no obvious pattern. */
876           get_u32();
877         }
878
879       printf ("/>\n");
880     }
881
882   match_u32_assert(240);
883   pos += 240;
884
885   match_u32_assert(18);
886   pos += 18;
887
888   int x3 = get_u32();
889   if (version == 3)
890     {
891       assert(x3 >= 117);
892       int len = data[pos + 0x34];
893       if (len)
894         printf("<tablelook>%.*s</tablelook>\n", len, &data[pos + 0x35]);
895     }
896   pos += x3;
897
898   int count = get_u32();
899   pos += 4 * count;
900
901   const char *locale = get_string();
902   printf ("<locale>%s</locale>\n", locale);
903
904   if (!match_u32(0))
905     match_u32_assert(UINT32_MAX);
906   if (!match_byte(0))
907     match_byte_assert(1);
908   match_byte_assert(0);
909   if (!match_byte(0))
910     match_byte_assert(1);
911   if (version > 1)
912     {
913       if (!match_byte(0x97) && !match_byte(0x98)
914           && !match_byte(0x99) && !match_byte(0x9a))
915         match_byte_assert(0x9b);
916       match_byte_assert(7);
917       match_byte_assert(0);
918       match_byte_assert(0);
919     }
920   else
921     match_u32_assert(UINT32_MAX);
922
923   int decimal = data[pos];
924   int grouping = data[pos + 1];
925   if (match_byte('.'))
926     {
927       if (!match_byte(',') && !match_byte('\''))
928         match_byte_assert(' ');
929     }
930   else
931     {
932       match_byte_assert(',');
933       if (!match_byte('.') && !match_byte(' '))
934         match_byte_assert(0);
935     }
936   printf("<format decimal=\"%c\" grouping=\"", decimal);
937   if (grouping)
938     putchar(grouping);
939   printf("\"/>\n");
940   if (match_u32(5))
941     {
942       for (int i = 0; i < 5; i++)
943         printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
944     }
945   else
946     match_u32_assert(0);
947
948   /* The last chunk is an outer envelope that contains two inner envelopes.
949      The second inner envelope has some interesting data like the encoding and
950      the locale. */
951   if (version == 3)
952     {
953       int outer_end = get_end();
954
955       /* First inner envelope: byte*33 int[n] int*[n]. */
956       pos = get_end();
957
958       /* Second inner envelope. */
959       assert(get_end() == outer_end);
960
961       match_byte_assert(1);
962       match_byte_assert(0);
963       if (!match_byte(3) && !match_byte(4))
964         match_byte_assert(5);
965       match_byte_assert(0);
966       match_byte_assert(0);
967       match_byte_assert(0);
968
969       printf("<command>%s</command>\n", get_string());
970       printf("<subcommand>%s</subcommand>\n", get_string());
971       printf("<language>%s</language>\n", get_string());
972       printf("<charset>%s</charset>\n", get_string());
973       printf("<locale>%s</locale>\n", get_string());
974
975       if (!match_byte(0))
976         match_byte_assert(1);
977       match_byte_assert(0);
978       if (!match_byte(0))
979         match_byte_assert(1);
980       if (!match_byte(0))
981         match_byte_assert(1);
982
983       if (!match_byte(0x97) && !match_byte(0x98)
984           && !match_byte(0x99) && !match_byte(0x9a))
985         match_byte_assert(0x9b);
986       match_byte_assert(7);
987       match_byte_assert(0);
988       match_byte_assert(0);
989
990       if (match_byte('.'))
991         {
992           if (!match_byte(',') && !match_byte('\''))
993             match_byte_assert(' ');
994         }
995       else
996         {
997           match_byte_assert(',');
998           if (!match_byte('.') && !match_byte(' '))
999             match_byte_assert(0);
1000         }
1001
1002       pos += 8;
1003       match_byte_assert(1);
1004
1005       if (outer_end - pos > 6)
1006         {
1007           /* There might be a pair of strings representing a dataset and
1008              datafile name, or there might be a set of custom currency strings.
1009              The custom currency strings start with a pair of integers, so we
1010              can distinguish these from a string by checking for a null byte; a
1011              small 32-bit integer will always contain a null and a text string
1012              never will. */
1013           int save_pos = pos;
1014           int len = get_u32();
1015           bool has_dataset = !memchr(&data[pos], '\0', len);
1016           pos = save_pos;
1017
1018           if (has_dataset)
1019             {
1020               printf("<dataset>%s</dataset>\n", get_string());
1021               printf("<datafile>%s</datafile>\n", get_string());
1022
1023               match_u32_assert(0);
1024               get_u32();
1025               match_u32_assert(0);
1026             }
1027         }
1028
1029       if (match_u32(5))
1030         {
1031           for (int i = 0; i < 5; i++)
1032             printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
1033         }
1034       else
1035         match_u32_assert(0);
1036
1037       match_byte_assert(0x2e);
1038       if (!match_byte(0))
1039         match_byte_assert(1);
1040
1041       if (pos < outer_end)
1042         {
1043           match_u32_assert(2000000);
1044           match_u32_assert(0);
1045         }
1046       assert(pos == outer_end);
1047
1048       pos = outer_end;
1049     }
1050   else
1051     match_u32_assert(0);
1052 }
1053
1054 int
1055 main(int argc, char *argv[])
1056 {
1057   size_t start;
1058   struct stat s;
1059
1060   if (isatty(STDIN_FILENO))
1061     {
1062       fprintf(stderr, "redirect stdin from a .bin file\n");
1063       exit(1);
1064     }
1065   if (fstat(STDIN_FILENO, &s))
1066     {
1067       perror("fstat");
1068       exit(1);
1069     }
1070   n = s.st_size;
1071   data = malloc(n);
1072   if (!data)
1073     {
1074       perror("malloc");
1075       exit(1);
1076     }
1077   if (read(STDIN_FILENO, data, n) != n)
1078     {
1079       perror("read");
1080       exit(1);
1081     }
1082
1083   if (argc != 2)
1084     {
1085       fprintf (stderr, "usage: %s TYPE < .bin", argv[0]);
1086       exit (1);
1087     }
1088
1089   if (!strcmp(argv[1], "title0"))
1090     {
1091       pos = 0x27;
1092       if (match_byte (0x03)
1093           || (match_byte (0x05) && match_byte (0x58)))
1094         printf ("%s\n", get_string());
1095       else
1096         printf ("<unknown>\n");
1097       return 0;
1098     }
1099   else if (!strcmp(argv[1], "title"))
1100     {
1101       pos = 0x27;
1102       dump_title();
1103       exit(0);
1104     }
1105   else if (!strcmp(argv[1], "titleraw"))
1106     {
1107       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1108       start = 0x27;
1109       n = find(fonts, sizeof fonts - 1);
1110     }
1111   else if (!strcmp(argv[1], "fonts"))
1112     {
1113       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1114       const char styles[] = "\xf0\0\0\0";
1115       start = find(fonts, sizeof fonts - 1);
1116       n = find(styles, sizeof styles - 1);
1117     }
1118   else if (!strcmp(argv[1], "styles"))
1119     {
1120       const char styles[] = "\xf0\0\0\0";
1121       const char dimensions[] = "-,,,.\0";
1122       start = find(styles, sizeof styles - 1);
1123       n = find(dimensions, sizeof dimensions - 1) + sizeof dimensions - 1;
1124     }
1125   else if (!strcmp(argv[1], "dimensions") || !strcmp(argv[1], "all"))
1126     {
1127       pos = 0;
1128       match_byte_assert(1);
1129       match_byte_assert(0);
1130
1131       /* This might be a version number of some kind, because value 1 seems
1132          to only appear in an SPV file that also required its own weird
1133          special cases in dump_optional_value(). */
1134       version = get_u32();
1135       pos -= 4;
1136       if (!match_u32(1))
1137         match_u32_assert(3);
1138
1139       match_byte_assert(1);
1140       if (!match_byte(0))
1141         match_byte_assert(1);
1142
1143       /* Offset 8. */
1144       match_byte_assert(0);
1145       match_byte_assert(0);
1146       if (!match_byte(0))
1147         match_byte_assert(1);
1148
1149       /* Offset 11. */
1150       pos++;
1151       match_byte_assert(0);
1152       match_byte_assert(0);
1153       match_byte_assert(0);
1154
1155       /* Offset 15. */
1156       pos++;
1157       if (!match_byte(0))
1158         match_byte_assert(1);
1159       match_byte_assert(0);
1160       match_byte_assert(0);
1161
1162       /* Offset 19. */
1163       pos++;
1164       if (!match_byte(0))
1165         match_byte_assert(1);
1166       match_byte_assert(0);
1167       match_byte_assert(0);
1168
1169       /* Offset 23. */
1170       pos++;
1171       if (!match_byte(0))
1172         match_byte_assert(1);
1173       match_byte_assert(0);
1174       match_byte_assert(0);
1175
1176       /* Offset 27. */
1177       pos++;
1178       pos++;
1179       match_byte_assert(0);
1180       match_byte_assert(0);
1181
1182       /* Offset 31.
1183
1184          This is the tableId, e.g. -4154297861994971133 would be 0xdca00003.
1185          We don't have enough context to validate it. */
1186       pos += 4;
1187
1188       /* Offset 35. */
1189       pos += 4;
1190
1191       dump_title ();
1192       dump_fonts();
1193       dump_dims ();
1194       dump_data ();
1195       match_byte (1);
1196       if (pos != n)
1197         {
1198           fprintf (stderr, "%x / %x\n", pos, n);
1199           exit(1);
1200         }
1201       exit(0);
1202     }
1203   else if (!strcmp(argv[1], "raw"))
1204     {
1205       start = 0x27;
1206
1207       dump_raw(stdout, start, n);
1208     }
1209   else
1210     {
1211       fprintf (stderr, "unknown section %s\n", argv[1]);
1212       exit(1);
1213     }
1214
1215   return 0;
1216 }