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