work
[pspp] / utilities / pspp-dump-sav.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <getopt.h>
23 #include <inttypes.h>
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27
28 #include "data/val-type.h"
29 #include "libpspp/cast.h"
30 #include "libpspp/compiler.h"
31 #include "libpspp/float-format.h"
32 #include "libpspp/integer-format.h"
33 #include "libpspp/misc.h"
34
35 #include "gl/error.h"
36 #include "gl/minmax.h"
37 #include "gl/progname.h"
38 #include "gl/version-etc.h"
39 #include "gl/xalloc.h"
40 #include "gl/xsize.h"
41
42 #define ID_MAX_LEN 64
43
44 enum compression
45   {
46     COMP_NONE,
47     COMP_SIMPLE,
48     COMP_ZLIB
49   };
50
51 struct sfm_reader
52   {
53     const char *file_name;
54     FILE *file;
55
56     int n_variable_records, n_variables;
57
58     int *var_widths;
59     size_t n_var_widths, allocated_var_widths;
60
61     enum integer_format integer_format;
62     enum float_format float_format;
63
64     enum compression compression;
65     double bias;
66   };
67
68   static int character_code;
69 static char *encoding;
70
71 static void read_header (struct sfm_reader *);
72 static void read_variable_record (struct sfm_reader *);
73 static void read_value_label_record (struct sfm_reader *);
74 static void read_document_record (struct sfm_reader *);
75 static void read_extension_record (struct sfm_reader *);
76 static void read_machine_integer_info (struct sfm_reader *,
77                                        size_t size, size_t count);
78 static void read_machine_float_info (struct sfm_reader *,
79                                      size_t size, size_t count);
80 static void read_extra_product_info (struct sfm_reader *,
81                                      size_t size, size_t count);
82 static void read_variable_sets (struct sfm_reader *, size_t size, size_t count);
83 static void read_mrsets (struct sfm_reader *, size_t size, size_t count);
84 static void read_display_parameters (struct sfm_reader *,
85                                      size_t size, size_t count);
86 static void read_long_var_name_map (struct sfm_reader *r,
87                                     size_t size, size_t count);
88 static void read_long_string_map (struct sfm_reader *r,
89                                   size_t size, size_t count);
90 static void read_datafile_attributes (struct sfm_reader *r,
91                                       size_t size, size_t count);
92 static void read_variable_attributes (struct sfm_reader *r,
93                                       size_t size, size_t count);
94 static void read_ncases64 (struct sfm_reader *, size_t size, size_t count);
95 static void read_character_encoding (struct sfm_reader *r,
96                                        size_t size, size_t count);
97 static void read_long_string_value_labels (struct sfm_reader *r,
98                                            size_t size, size_t count);
99 static void read_long_string_missing_values (struct sfm_reader *r,
100                                              size_t size, size_t count);
101 static void read_unknown_extension (struct sfm_reader *,
102                                     size_t size, size_t count);
103 static void read_simple_compressed_data (struct sfm_reader *, int max_cases);
104 static void read_zlib_compressed_data (struct sfm_reader *);
105
106 static struct text_record *open_text_record (
107   struct sfm_reader *, size_t size, size_t count);
108 static void close_text_record (struct text_record *);
109 static bool read_variable_to_value_pair (struct text_record *,
110                                          char **key, char **value);
111 static char *text_tokenize (struct text_record *, int delimiter);
112 static bool text_match (struct text_record *text, int c);
113 static const char *text_parse_counted_string (struct text_record *);
114 static size_t text_pos (const struct text_record *);
115 static const char *text_get_all (const struct text_record *);
116
117 static void usage (void);
118 static void sys_warn (struct sfm_reader *, const char *, ...)
119      PRINTF_FORMAT (2, 3);
120 static void sys_error (struct sfm_reader *, const char *, ...)
121      PRINTF_FORMAT (2, 3)
122      NO_RETURN;
123
124 static void read_bytes (struct sfm_reader *, void *, size_t);
125 static bool try_read_bytes (struct sfm_reader *, void *, size_t);
126 static int read_int (struct sfm_reader *);
127 static int64_t read_int64 (struct sfm_reader *);
128 static double read_float (struct sfm_reader *);
129 static void read_string (struct sfm_reader *, char *, size_t);
130 static void skip_bytes (struct sfm_reader *, size_t);
131 static void trim_spaces (char *);
132
133 static void print_string (const char *s, size_t len);
134
135 int
136 main (int argc, char *argv[])
137 {
138   int max_cases = 0;
139   struct sfm_reader r;
140   int i;
141
142   set_program_name (argv[0]);
143
144   for (;;)
145     {
146       static const struct option long_options[] =
147         {
148           { "data",    optional_argument, NULL, 'd' },
149           { "help",    no_argument,       NULL, 'h' },
150           { "version", no_argument,       NULL, 'v' },
151           { NULL,      0,                 NULL, 0 },
152         };
153
154       int c;
155
156       c = getopt_long (argc, argv, "d::hv", long_options, NULL);
157       if (c == -1)
158         break;
159
160       switch (c)
161         {
162         case 'd':
163           max_cases = optarg ? atoi (optarg) : INT_MAX;
164           break;
165
166         case 'v':
167           version_etc (stdout, "pspp-dump-sav", PACKAGE_NAME, PACKAGE_VERSION,
168                        "Ben Pfaff", "John Darrington", NULL_SENTINEL);
169           exit (EXIT_SUCCESS);
170
171         case 'h':
172           usage ();
173           exit (EXIT_SUCCESS);
174
175         default:
176           exit (EXIT_FAILURE);
177         }
178     }
179
180   if (optind == argc)
181     error (1, 0, "at least one non-option argument is required; "
182            "use --help for help");
183
184   for (i = optind; i < argc; i++)
185     {
186       int rec_type;
187
188       r.file_name = argv[i];
189       r.file = fopen (r.file_name, "rb");
190       if (r.file == NULL)
191         error (EXIT_FAILURE, errno, "error opening `%s'", r.file_name);
192       r.n_variable_records = 0;
193       r.n_variables = 0;
194       r.n_var_widths = 0;
195       r.allocated_var_widths = 0;
196       r.var_widths = 0;
197       r.compression = COMP_NONE;
198
199       if (argc - optind > 1)
200         printf ("Reading \"%s\":\n", r.file_name);
201
202       read_header (&r);
203       while ((rec_type = read_int (&r)) != 999)
204         {
205           switch (rec_type)
206             {
207             case 2:
208               read_variable_record (&r);
209               break;
210
211             case 3:
212               read_value_label_record (&r);
213               break;
214
215             case 4:
216               sys_error (&r, "Misplaced type 4 record.");
217
218             case 6:
219               read_document_record (&r);
220               break;
221
222             case 7:
223               read_extension_record (&r);
224               break;
225
226             default:
227               sys_error (&r, "Unrecognized record type %d.", rec_type);
228             }
229         }
230       printf ("%08llx: end-of-dictionary record "
231               "(first byte of data at %08llx)\n",
232               (long long int) ftello (r.file),
233               (long long int) ftello (r.file) + 4);
234
235       printf ("Character Encoding: %s (%d)\n", encoding ? encoding : "none", character_code);
236       if (r.compression == COMP_SIMPLE)
237         {
238           if (max_cases > 0)
239             read_simple_compressed_data (&r, max_cases);
240         }
241       else if (r.compression == COMP_ZLIB)
242         read_zlib_compressed_data (&r);
243
244       free (r.var_widths);
245
246       fclose (r.file);
247     }
248
249   return 0;
250 }
251
252 static void
253 read_header (struct sfm_reader *r)
254 {
255   char rec_type[5];
256   char eye_catcher[61];
257   uint8_t raw_layout_code[4];
258   int32_t layout_code;
259   int32_t compressed;
260   int32_t weight_index;
261   int32_t ncases;
262   uint8_t raw_bias[8];
263   char creation_date[10];
264   char creation_time[9];
265   char file_label[65];
266   bool zmagic;
267
268   read_string (r, rec_type, sizeof rec_type);
269   read_string (r, eye_catcher, sizeof eye_catcher);
270
271   if (!strcmp ("$FL2", rec_type))
272     zmagic = false;
273   else if (!strcmp ("$FL3", rec_type))
274     zmagic = true;
275   else
276     sys_error (r, "This is not an SPSS system file.");
277
278   /* Identify integer format. */
279   read_bytes (r, raw_layout_code, sizeof raw_layout_code);
280   if ((!integer_identify (2, raw_layout_code, sizeof raw_layout_code,
281                           &r->integer_format)
282        && !integer_identify (3, raw_layout_code, sizeof raw_layout_code,
283                              &r->integer_format))
284       || (r->integer_format != INTEGER_MSB_FIRST
285           && r->integer_format != INTEGER_LSB_FIRST))
286     sys_error (r, "This is not an SPSS system file.");
287   layout_code = integer_get (r->integer_format,
288                              raw_layout_code, sizeof raw_layout_code);
289
290   read_int (r);                 /* Nominal case size (not actually useful). */
291   compressed = read_int (r);
292   weight_index = read_int (r);
293   ncases = read_int (r);
294
295   if (!zmagic)
296     {
297       if (compressed == 0)
298         r->compression = COMP_NONE;
299       else if (compressed == 1)
300         r->compression = COMP_SIMPLE;
301       else if (compressed != 0)
302         sys_error (r, "SAV file header has invalid compression value "
303                    "%"PRId32".", compressed);
304     }
305   else
306     {
307       if (compressed == 2)
308         r->compression = COMP_ZLIB;
309       else
310         sys_error (r, "ZSAV file header has invalid compression value "
311                    "%"PRId32".", compressed);
312     }
313
314   /* Identify floating-point format and obtain compression bias. */
315   read_bytes (r, raw_bias, sizeof raw_bias);
316   if (float_identify (100.0, raw_bias, sizeof raw_bias, &r->float_format) == 0)
317     {
318       sys_warn (r, "Compression bias is not the usual value of 100, or system "
319                 "file uses unrecognized floating-point format.");
320       if (r->integer_format == INTEGER_MSB_FIRST)
321         r->float_format = FLOAT_IEEE_DOUBLE_BE;
322       else
323         r->float_format = FLOAT_IEEE_DOUBLE_LE;
324     }
325   if ((r->integer_format == INTEGER_MSB_FIRST && r->float_format != FLOAT_IEEE_DOUBLE_BE) ||
326       (r->integer_format == INTEGER_LSB_FIRST && r->float_format != FLOAT_IEEE_DOUBLE_LE)) 
327     {
328       printf ("unexpected floating-point format\n");
329     }
330
331   if (r->float_format != FLOAT_IEEE_DOUBLE_LE && r->float_format != FLOAT_IEEE_DOUBLE_BE)
332     {
333       printf ("non-IEEE format\n");
334     } else
335     {
336       printf ("IEEE format\n");
337     }
338   r->bias = float_get_double (r->float_format, raw_bias);
339
340   read_string (r, creation_date, sizeof creation_date);
341   read_string (r, creation_time, sizeof creation_time);
342   read_string (r, file_label, sizeof file_label);
343   trim_spaces (file_label);
344   skip_bytes (r, 3);
345
346   printf ("File header record:\n");
347   printf ("\t%17s: %s\n", "Product name", eye_catcher);
348   printf ("\t%17s: %"PRId32"\n", "Layout code", layout_code);
349   printf ("\t%17s: %"PRId32" (%s)\n", "Compressed",
350           compressed,
351           r->compression == COMP_NONE ? "no compression"
352           : r->compression == COMP_SIMPLE ? "simple compression"
353           : r->compression == COMP_ZLIB ? "ZLIB compression"
354           : "<error>");
355   printf ("\t%17s: %"PRId32"\n", "Weight index", weight_index);
356   printf ("\t%17s: %"PRId32"\n", "Number of cases", ncases);
357   printf ("\t%17s: %.*g\n", "Compression bias", DBL_DIG + 1, r->bias);
358   printf ("\t%17s: %s\n", "Creation date", creation_date);
359   printf ("\t%17s: %s\n", "Creation time", creation_time);
360   printf ("\t%17s: \"%s\"\n", "File label", file_label);
361 }
362
363 static const char *
364 format_name (int format)
365 {
366   switch ((format >> 16) & 0xff)
367     {
368     case 1: return "A";
369     case 2: return "AHEX";
370     case 3: return "COMMA";
371     case 4: return "DOLLAR";
372     case 5: return "F";
373     case 6: return "IB";
374     case 7: return "PIBHEX";
375     case 8: return "P";
376     case 9: return "PIB";
377     case 10: return "PK";
378     case 11: return "RB";
379     case 12: return "RBHEX";
380     case 15: return "Z";
381     case 16: return "N";
382     case 17: return "E";
383     case 20: return "DATE";
384     case 21: return "TIME";
385     case 22: return "DATETIME";
386     case 23: return "ADATE";
387     case 24: return "JDATE";
388     case 25: return "DTIME";
389     case 26: return "WKDAY";
390     case 27: return "MONTH";
391     case 28: return "MOYR";
392     case 29: return "QYR";
393     case 30: return "WKYR";
394     case 31: return "PCT";
395     case 32: return "DOT";
396     case 33: return "CCA";
397     case 34: return "CCB";
398     case 35: return "CCC";
399     case 36: return "CCD";
400     case 37: return "CCE";
401     case 38: return "EDATE";
402     case 39: return "SDATE";
403     case 40: return "MTIME";
404     case 41: return "YMDHMS";
405     default: return "invalid";
406     }
407 }
408
409 /* Reads a variable (type 2) record from R and adds the
410    corresponding variable to DICT.
411    Also skips past additional variable records for long string
412    variables. */
413 static void
414 read_variable_record (struct sfm_reader *r)
415 {
416   int width;
417   int has_variable_label;
418   int missing_value_code;
419   int print_format;
420   int write_format;
421   char name[9];
422
423   printf ("%08llx: variable record #%d\n",
424           (long long int) ftello (r->file), ++r->n_variable_records);
425
426   width = read_int (r);
427   has_variable_label = read_int (r);
428   missing_value_code = read_int (r);
429   print_format = read_int (r);
430   write_format = read_int (r);
431   read_string (r, name, sizeof name);
432   name[strcspn (name, " ")] = '\0';
433
434   if (width >= 0)
435     r->n_variables++;
436
437   if (r->n_var_widths >= r->allocated_var_widths)
438     r->var_widths = x2nrealloc (r->var_widths, &r->allocated_var_widths,
439                                 sizeof *r->var_widths);
440   r->var_widths[r->n_var_widths++] = width;
441
442   printf ("\tWidth: %d (%s)\n",
443           width,
444           width > 0 ? "string"
445           : width == 0 ? "numeric"
446           : "long string continuation record");
447   printf ("\tVariable label: %d\n", has_variable_label);
448   printf ("\tMissing values code: %d (%s)\n", missing_value_code,
449           (missing_value_code == 0 ? "no missing values"
450            : missing_value_code == 1 ? "one missing value"
451            : missing_value_code == 2 ? "two missing values"
452            : missing_value_code == 3 ? "three missing values"
453            : missing_value_code == -2 ? "one missing value range"
454            : missing_value_code == -3 ? "one missing value, one range"
455            : "bad value"));
456   printf ("\tPrint format: %06x (%s%d.%d)\n",
457           print_format, format_name (print_format),
458           (print_format >> 8) & 0xff, print_format & 0xff);
459   printf ("\tWrite format: %06x (%s%d.%d)\n",
460           write_format, format_name (write_format),
461           (write_format >> 8) & 0xff, write_format & 0xff);
462   printf ("\tName: %s\n", name);
463
464   /* Get variable label, if any. */
465   if (has_variable_label != 0 && has_variable_label != 1)
466     sys_error (r, "Variable label indicator field is not 0 or 1.");
467   if (has_variable_label == 1)
468     {
469       long long int offset = ftello (r->file);
470       enum { MAX_LABEL_LEN = 65536 };
471
472       size_t len = read_int (r);
473       size_t read_len = MIN (MAX_LABEL_LEN, len);
474       char *label = xmalloc (read_len + 1);
475       read_string (r, label, read_len + 1);
476       printf("\t%08llx Variable label: \"%s\"\n", offset, label);
477       free (label);
478
479       /* Skip label padding up to multiple of 4 bytes. */
480       skip_bytes (r, ROUND_UP (len, 4) - len);
481     }
482
483   /* Set missing values. */
484   if (missing_value_code != 0)
485     {
486       int i;
487
488       printf ("\t%08llx Missing values:", (long long int) ftello (r->file));
489       if (!width)
490         {
491           if (missing_value_code < -3 || missing_value_code > 3
492               || missing_value_code == -1)
493             sys_error (r, "Numeric missing value indicator field is not "
494                        "-3, -2, 0, 1, 2, or 3.");
495           if (missing_value_code < 0)
496             {
497               double low = read_float (r);
498               double high = read_float (r);
499               printf (" %.*g...%.*g", DBL_DIG + 1, low, DBL_DIG + 1, high);
500               missing_value_code = -missing_value_code - 2;
501             }
502           for (i = 0; i < missing_value_code; i++)
503             printf (" %.*g", DBL_DIG + 1, read_float (r));
504         }
505       else if (width > 0)
506         {
507           if (missing_value_code < 1 || missing_value_code > 3)
508             sys_error (r, "String missing value indicator field is not "
509                        "0, 1, 2, or 3.");
510           for (i = 0; i < missing_value_code; i++)
511             {
512               char string[9];
513               read_string (r, string, sizeof string);
514               printf (" \"%s\"", string);
515             }
516         }
517       putchar ('\n');
518     }
519 }
520
521 static void
522 print_untyped_value (struct sfm_reader *r, char raw_value[8])
523 {
524   int n_printable;
525   double value;
526
527   value = float_get_double (r->float_format, raw_value);
528   for (n_printable = 0; n_printable < 8; n_printable++)
529     if (!isprint (raw_value[n_printable]))
530       break;
531
532   printf ("%.*g/\"%.*s\"", DBL_DIG + 1, value, n_printable, raw_value);
533 }
534
535 /* Reads value labels from sysfile R and inserts them into the
536    associated dictionary. */
537 static void
538 read_value_label_record (struct sfm_reader *r)
539 {
540   int n_labels, n_vars;
541   int i;
542
543   printf ("%08llx: value labels record\n", (long long int) ftello (r->file));
544
545   /* Read number of labels. */
546   n_labels = read_int (r);
547   for (i = 0; i < n_labels; i++)
548     {
549       char raw_value[8];
550       unsigned char label_len;
551       size_t padded_len;
552       char label[256];
553
554       read_bytes (r, raw_value, sizeof raw_value);
555
556       /* Read label length. */
557       read_bytes (r, &label_len, sizeof label_len);
558       padded_len = ROUND_UP (label_len + 1, 8);
559
560       /* Read label, padding. */
561       read_bytes (r, label, padded_len - 1);
562       label[label_len] = 0;
563
564       printf ("\t");
565       print_untyped_value (r, raw_value);
566       printf (": \"%s\"\n", label);
567     }
568
569   /* Now, read the type 4 record that has the list of variables
570      to which the value labels are to be applied. */
571
572   /* Read record type of type 4 record. */
573   if (read_int (r) != 4)
574     sys_error (r, "Variable index record (type 4) does not immediately "
575                "follow value label record (type 3) as it should.");
576
577   /* Read number of variables associated with value label from type 4
578      record. */
579   printf ("\t%08llx: apply to variables", (long long int) ftello (r->file));
580   n_vars = read_int (r);
581   for (i = 0; i < n_vars; i++)
582     printf (" #%d", read_int (r));
583   putchar ('\n');
584 }
585
586 static void
587 read_document_record (struct sfm_reader *r)
588 {
589   int n_lines;
590   int i;
591
592   printf ("%08llx: document record\n", (long long int) ftello (r->file));
593   n_lines = read_int (r);
594   printf ("\t%d lines of documents\n", n_lines);
595
596   for (i = 0; i < n_lines; i++)
597     {
598       char line[81];
599       printf ("\t%08llx: ", (long long int) ftello (r->file));
600       read_string (r, line, sizeof line);
601       trim_spaces (line);
602       printf ("line %d: \"%s\"\n", i, line);
603     }
604 }
605
606 static void
607 read_extension_record (struct sfm_reader *r)
608 {
609   long long int offset = ftello (r->file);
610   int subtype = read_int (r);
611   size_t size = read_int (r);
612   size_t count = read_int (r);
613   size_t bytes = size * count;
614
615   printf ("%08llx: Record 7, subtype %d, size=%zu, count=%zu\n",
616           offset, subtype, size, count);
617
618   switch (subtype)
619     {
620     case 3:
621       read_machine_integer_info (r, size, count);
622       return;
623
624     case 4:
625       read_machine_float_info (r, size, count);
626       return;
627
628     case 5:
629       read_variable_sets (r, size, count);
630       return;
631
632     case 6:
633       /* DATE variable information.  We don't use it yet, but we
634          should. */
635       break;
636
637     case 7:
638     case 19:
639       read_mrsets (r, size, count);
640       return;
641
642     case 10:
643       read_extra_product_info (r, size, count);
644       return;
645
646     case 11:
647       read_display_parameters (r, size, count);
648       return;
649
650     case 13:
651       read_long_var_name_map (r, size, count);
652       return;
653
654     case 14:
655       read_long_string_map (r, size, count);
656       return;
657
658     case 16:
659       read_ncases64 (r, size, count);
660       return;
661
662     case 17:
663       read_datafile_attributes (r, size, count);
664       return;
665
666     case 18:
667       read_variable_attributes (r, size, count);
668       return;
669
670     case 20:
671       read_character_encoding (r, size, count);
672       return;
673
674     case 21:
675       read_long_string_value_labels (r, size, count);
676       return;
677
678     case 22:
679       read_long_string_missing_values (r, size, count);
680       return;
681
682     default:
683       sys_warn (r, "Unrecognized record type 7, subtype %d.", subtype);
684       read_unknown_extension (r, size, count);
685       return;
686     }
687
688   skip_bytes (r, bytes);
689 }
690
691 static void
692 read_machine_integer_info (struct sfm_reader *r, size_t size, size_t count)
693 {
694   long long int offset = ftello (r->file);
695   int version_major = read_int (r);
696   int version_minor = read_int (r);
697   int version_revision = read_int (r);
698   int machine_code = read_int (r);
699   int float_representation = read_int (r);
700   int compression_code = read_int (r);
701   int integer_representation = read_int (r);
702   character_code = read_int (r);
703
704   printf ("%08llx: machine integer info\n", offset);
705   if (size != 4 || count != 8)
706     sys_error (r, "Bad size (%zu) or count (%zu) field on record type 7, "
707                "subtype 3.", size, count);
708
709   printf ("\tVersion: %d.%d.%d\n",
710           version_major, version_minor, version_revision);
711   printf ("\tMachine code: %d\n", machine_code);
712   printf ("\tFloating point representation: %d (%s)\n",
713           float_representation,
714           float_representation == 1 ? "IEEE 754"
715           : float_representation == 2 ? "IBM 370"
716           : float_representation == 3 ? "DEC VAX"
717           : "unknown");
718   printf ("\tCompression code: %d\n", compression_code);
719   printf ("\tEndianness: %d (%s)\n", integer_representation,
720           integer_representation == 1 ? "big"
721           : integer_representation == 2 ? "little" : "unknown");
722   printf ("\tCharacter code: %d\n", character_code);
723 }
724
725 /* Read record type 7, subtype 4. */
726 static void
727 read_machine_float_info (struct sfm_reader *r, size_t size, size_t count)
728 {
729   long long int offset = ftello (r->file);
730   double sysmis = read_float (r);
731   double highest = read_float (r);
732   double lowest = read_float (r);
733
734   printf ("%08llx: machine float info\n", offset);
735   if (size != 8 || count != 3)
736     sys_error (r, "Bad size (%zu) or count (%zu) on extension 4.",
737                size, count);
738
739   printf ("\tsysmis: %.*g (%a)\n", DBL_DIG + 1, sysmis, sysmis);
740   if (sysmis != SYSMIS)
741     sys_warn (r, "File specifies unexpected value %.*g (%a) as %s.",
742               DBL_DIG + 1, sysmis, sysmis, "SYSMIS");
743
744   printf ("\thighest: %.*g (%a)\n", DBL_DIG + 1, highest, highest);
745   if (highest != HIGHEST)
746     sys_warn (r, "File specifies unexpected value %.*g (%a) as %s.",
747               DBL_DIG + 1, highest, highest, "HIGHEST");
748
749   printf ("\tlowest: %.*g (%a)\n", DBL_DIG + 1, lowest, lowest);
750   if (lowest != LOWEST && lowest != SYSMIS)
751     sys_warn (r, "File specifies unexpected value %.*g (%a) as %s.",
752               DBL_DIG + 1, lowest, lowest, "LOWEST");
753 }
754
755 /* Read record type 7, subtype 5. */
756 static void
757 read_variable_sets (struct sfm_reader *r, size_t size, size_t count)
758 {
759   printf ("%08llx: variable sets\n", (long long int) ftello (r->file));
760   struct text_record *text = open_text_record (r, size, count);
761   for (;;)
762     {
763       while (text_match (text, '\n'))
764         continue;
765
766       const char *set = text_tokenize (text, '=');
767       if (!set)
768         break;
769
770       /* Always present even for an empty set. */
771       text_match (text, ' ');
772
773       char *variables = text_tokenize (text, '\n');
774       if (!variables)
775         printf ("\tset \"%s\" is empty\n", set);
776       else
777         {
778           size_t length = strlen (variables);
779           if (variables[length - 1] == '\r')
780             variables[length - 1] = '\0';
781           printf ("\tset \"%s\" contains \"%s\"\n", set, variables);
782         }
783     }
784   close_text_record (text);
785 }
786
787 static void
788 read_extra_product_info (struct sfm_reader *r,
789                          size_t size, size_t count)
790 {
791   struct text_record *text;
792   const char *s;
793
794   printf ("%08llx: extra product info\n", (long long int) ftello (r->file));
795   text = open_text_record (r, size, count);
796   s = text_get_all (text);
797   print_string (s, strlen (s));
798   close_text_record (text);
799 }
800
801 /* Read record type 7, subtype 7. */
802 static void
803 read_mrsets (struct sfm_reader *r, size_t size, size_t count)
804 {
805   struct text_record *text;
806
807   printf ("%08llx: multiple response sets\n",
808           (long long int) ftello (r->file));
809   text = open_text_record (r, size, count);
810   for (;;)
811     {
812       const char *name;
813       enum { MRSET_MC, MRSET_MD } type;
814       bool cat_label_from_counted_values = false;
815       bool label_from_var_label = false;
816       const char *counted;
817       const char *label;
818       const char *variables;
819
820       while (text_match (text, '\n'))
821         continue;
822
823       name = text_tokenize (text, '=');
824       if (name == NULL)
825         break;
826
827       if (text_match (text, 'C'))
828         {
829           type = MRSET_MC;
830           counted = NULL;
831           if (!text_match (text, ' '))
832             {
833               sys_warn (r, "missing space following 'C' at offset %zu "
834                         "in mrsets record", text_pos (text));
835               break;
836             }
837         }
838       else if (text_match (text, 'D'))
839         {
840           type = MRSET_MD;
841         }
842       else if (text_match (text, 'E'))
843         {
844           char *number;
845
846           type = MRSET_MD;
847           cat_label_from_counted_values = true;
848
849           if (!text_match (text, ' '))
850             {
851               sys_warn (r, "Missing space following `%c' at offset %zu "
852                         "in MRSETS record", 'E', text_pos (text));
853               break;
854             }
855
856           number = text_tokenize (text, ' ');
857           if (!number)
858             sys_warn (r, "Missing label source value "
859                       "following `E' at offset %zu in MRSETS record",
860                       text_pos (text));
861           else if (!strcmp (number, "11"))
862             label_from_var_label = true;
863           else if (strcmp (number, "1"))
864             sys_warn (r, "Unexpected label source value `%s' "
865                       "following `E' at offset %zu in MRSETS record",
866                       number, text_pos (text));
867
868         }
869       else
870         {
871           sys_warn (r, "missing `C', `D', or `E' at offset %zu "
872                     "in mrsets record", text_pos (text));
873           break;
874         }
875
876       if (type == MRSET_MD)
877         {
878           counted = text_parse_counted_string (text);
879           if (counted == NULL)
880             break;
881         }
882
883       label = text_parse_counted_string (text);
884       if (label == NULL)
885         break;
886
887       variables = text_tokenize (text, '\n');
888
889       printf ("\t\"%s\": multiple %s set",
890               name, type == MRSET_MC ? "category" : "dichotomy");
891       if (counted != NULL)
892         printf (", counted value \"%s\"", counted);
893       if (cat_label_from_counted_values)
894         printf (", category labels from counted values");
895       if (label[0] != '\0')
896         printf (", label \"%s\"", label);
897       if (label_from_var_label)
898         printf (", label from variable label");
899       if (variables != NULL)
900         printf(", variables \"%s\"\n", variables);
901       else
902         printf(", no variables\n");
903     }
904   close_text_record (text);
905 }
906
907 /* Read record type 7, subtype 11. */
908 static void
909 read_display_parameters (struct sfm_reader *r, size_t size, size_t count)
910 {
911   size_t n_vars;
912   bool includes_width;
913   size_t i;
914
915   printf ("%08llx: variable display parameters\n",
916           (long long int) ftello (r->file));
917   if (size != 4)
918     {
919       sys_warn (r, "Bad size %zu on extension 11.", size);
920       skip_bytes (r, size * count);
921       return;
922     }
923
924   n_vars = r->n_variables;
925   if (count == 3 * n_vars)
926     includes_width = true;
927   else if (count == 2 * n_vars)
928     includes_width = false;
929   else
930     {
931       sys_warn (r, "Extension 11 has bad count %zu (for %zu variables).",
932                 count, n_vars);
933       skip_bytes (r, size * count);
934       return;
935     }
936
937   for (i = 0; i < n_vars; ++i)
938     {
939       int measure = read_int (r);
940       int width = includes_width ? read_int (r) : 0;
941       int align = read_int (r);
942
943       printf ("\tVar #%zu: measure=%d (%s)", i, measure,
944               (measure == 1 ? "nominal"
945                : measure == 2 ? "ordinal"
946                : measure == 3 ? "scale"
947                : "invalid"));
948       if (includes_width)
949         printf (", width=%d", width);
950       printf (", align=%d (%s)\n", align,
951               (align == 0 ? "left"
952                : align == 1 ? "right"
953                : align == 2 ? "centre"
954                : "invalid"));
955     }
956 }
957
958 /* Reads record type 7, subtype 13, which gives the long name
959    that corresponds to each short name.  */
960 static void
961 read_long_var_name_map (struct sfm_reader *r, size_t size, size_t count)
962 {
963   struct text_record *text;
964   char *var;
965   char *long_name;
966
967   printf ("%08llx: long variable names (short => long)\n",
968           (long long int) ftello (r->file));
969   text = open_text_record (r, size, count);
970   while (read_variable_to_value_pair (text, &var, &long_name))
971     printf ("\t%s => %s\n", var, long_name);
972   close_text_record (text);
973 }
974
975 /* Reads record type 7, subtype 14, which gives the real length
976    of each very long string.  Rearranges DICT accordingly. */
977 static void
978 read_long_string_map (struct sfm_reader *r, size_t size, size_t count)
979 {
980   struct text_record *text;
981   char *var;
982   char *length_s;
983
984   printf ("%08llx: very long strings (variable => length)\n",
985           (long long int) ftello (r->file));
986   text = open_text_record (r, size, count);
987   while (read_variable_to_value_pair (text, &var, &length_s))
988     printf ("\t%s => %d\n", var, atoi (length_s));
989   close_text_record (text);
990 }
991
992 static bool
993 read_attributes (struct sfm_reader *r, struct text_record *text,
994                  const char *variable)
995 {
996   const char *key;
997   int index;
998
999   for (;;)
1000     {
1001       key = text_tokenize (text, '(');
1002       if (key == NULL)
1003         return true;
1004
1005       for (index = 1; ; index++)
1006         {
1007           /* Parse the value. */
1008           const char *value = text_tokenize (text, '\n');
1009           if (value == NULL)
1010             {
1011               sys_warn (r, "%s: Error parsing attribute value %s[%d]",
1012                         variable, key, index);
1013               return false;
1014             }
1015           if (strlen (value) < 2
1016               || value[0] != '\'' || value[strlen (value) - 1] != '\'')
1017             sys_warn (r, "%s: Attribute value %s[%d] is not quoted: %s",
1018                       variable, key, index, value);
1019           else
1020             printf ("\t%s: %s[%d] = \"%.*s\"\n",
1021                     variable, key, index, (int) strlen (value) - 2, value + 1);
1022
1023           /* Was this the last value for this attribute? */
1024           if (text_match (text, ')'))
1025             break;
1026         }
1027
1028       if (text_match (text, '/'))
1029         return true;
1030     }
1031 }
1032
1033 /* Read extended number of cases record. */
1034 static void
1035 read_ncases64 (struct sfm_reader *r, size_t size, size_t count)
1036 {
1037   int64_t unknown, ncases64;
1038
1039   if (size != 8)
1040     {
1041       sys_warn (r, "Bad size %zu for extended number of cases.", size);
1042       skip_bytes (r, size * count);
1043       return;
1044     }
1045   if (count != 2)
1046     {
1047       sys_warn (r, "Bad count %zu for extended number of cases.", size);
1048       skip_bytes (r, size * count);
1049       return;
1050     }
1051   unknown = read_int64 (r);
1052   ncases64 = read_int64 (r);
1053   printf ("%08llx: extended number of cases: "
1054           "unknown=%"PRId64", ncases64=%"PRId64"\n",
1055           (long long int) ftello (r->file), unknown, ncases64);
1056 }
1057
1058 static void
1059 read_datafile_attributes (struct sfm_reader *r, size_t size, size_t count)
1060 {
1061   struct text_record *text;
1062
1063   printf ("%08llx: datafile attributes\n", (long long int) ftello (r->file));
1064   text = open_text_record (r, size, count);
1065   read_attributes (r, text, "datafile");
1066   close_text_record (text);
1067 }
1068
1069 static void
1070 read_character_encoding (struct sfm_reader *r, size_t size, size_t count)
1071 {
1072   encoding = xcalloc (size, count + 1);
1073   read_string (r, encoding, count + 1);
1074
1075 }
1076
1077 static void
1078 read_long_string_value_labels (struct sfm_reader *r, size_t size, size_t count)
1079 {
1080   long long int start = ftello (r->file);
1081
1082   printf ("%08llx: long string value labels\n", start);
1083   while (ftello (r->file) - start < size * count)
1084     {
1085       long long posn = ftello (r->file);
1086       char var_name[ID_MAX_LEN + 1];
1087       int var_name_len;
1088       int n_values;
1089       int width;
1090       int i;
1091
1092       /* Read variable name. */
1093       var_name_len = read_int (r);
1094       if (var_name_len > ID_MAX_LEN)
1095         sys_error (r, "Variable name length in long string value label "
1096                    "record (%d) exceeds %d-byte limit.",
1097                    var_name_len, ID_MAX_LEN);
1098       read_string (r, var_name, var_name_len + 1);
1099
1100       /* Read width, number of values. */
1101       width = read_int (r);
1102       n_values = read_int (r);
1103
1104       printf ("\t%08llx: %s, width %d, %d values\n",
1105               posn, var_name, width, n_values);
1106
1107       /* Read values. */
1108       for (i = 0; i < n_values; i++)
1109         {
1110           char *value;
1111           int value_length;
1112
1113           char *label;
1114           int label_length;
1115
1116           posn = ftello (r->file);
1117
1118           /* Read value. */
1119           value_length = read_int (r);
1120           value = xmalloc (value_length + 1);
1121           read_string (r, value, value_length + 1);
1122
1123           /* Read label. */
1124           label_length = read_int (r);
1125           label = xmalloc (label_length + 1);
1126           read_string (r, label, label_length + 1);
1127
1128           printf ("\t\t%08llx: \"%s\" (%d bytes) => \"%s\" (%d bytes)\n",
1129                   posn, value, value_length, label, label_length);
1130
1131           free (value);
1132           free (label);
1133         }
1134     }
1135 }
1136
1137 static void
1138 read_long_string_missing_values (struct sfm_reader *r,
1139                                  size_t size, size_t count)
1140 {
1141   long long int start = ftello (r->file);
1142
1143   printf ("%08llx: long string missing values\n", start);
1144   while (ftello (r->file) - start < size * count)
1145     {
1146       long long posn = ftello (r->file);
1147
1148       /* Read variable name. */
1149       int var_name_len = read_int (r);
1150       if (var_name_len > ID_MAX_LEN)
1151         sys_error (r, "Variable name length in long string missing value "
1152                    "record (%d) exceeds %d-byte limit.",
1153                    var_name_len, ID_MAX_LEN);
1154       char var_name[ID_MAX_LEN + 1];
1155       read_string (r, var_name, var_name_len + 1);
1156
1157       /* Read number of values. */
1158       uint8_t n_missing_values;
1159       read_bytes (r, &n_missing_values, 1);
1160
1161       /* Read value length. */
1162       int value_length = read_int (r);
1163
1164       printf ("\t%08llx: %s, %d missing values, each %d bytes:",
1165               posn, var_name, n_missing_values, value_length);
1166
1167       /* Read values. */
1168       for (int i = 0; i < n_missing_values; i++)
1169         {
1170           /* Read value. */
1171           char *value = xmalloc (value_length + 1);
1172           read_string (r, value, value_length + 1);
1173
1174           printf (" \"%s\"", value);
1175
1176           free (value);
1177         }
1178       printf ("\n");
1179     }
1180 }
1181
1182 static void
1183 hex_dump (size_t offset, const void *buffer_, size_t buffer_size)
1184 {
1185   const uint8_t *buffer = buffer_;
1186
1187   while (buffer_size > 0)
1188     {
1189       size_t n = MIN (buffer_size, 16);
1190       size_t i;
1191
1192       printf ("%04zx", offset);
1193       for (i = 0; i < 16; i++)
1194         {
1195           if (i < n)
1196             printf ("%c%02x", i == 8 ? '-' : ' ', buffer[i]);
1197           else
1198             printf ("   ");
1199         }
1200
1201       printf (" |");
1202       for (i = 0; i < 16; i++)
1203         {
1204           unsigned char c = i < n ? buffer[i] : ' ';
1205           putchar (isprint (c) ? c : '.');
1206         }
1207       printf ("|\n");
1208
1209       offset += n;
1210       buffer += n;
1211       buffer_size -= n;
1212     }
1213 }
1214
1215 /* Reads and prints any type 7 record that we don't understand. */
1216 static void
1217 read_unknown_extension (struct sfm_reader *r, size_t size, size_t count)
1218 {
1219   unsigned char *buffer;
1220   size_t i;
1221
1222   if (size == 0 || count > 65536 / size)
1223     skip_bytes (r, size * count);
1224   else if (size != 1)
1225     {
1226       buffer = xmalloc (size);
1227       for (i = 0; i < count; i++)
1228         {
1229           read_bytes (r, buffer, size);
1230           hex_dump (i * size, buffer, size);
1231         }
1232       free (buffer);
1233     }
1234   else
1235     {
1236       buffer = xmalloc (count);
1237       read_bytes (r, buffer, count);
1238       print_string (CHAR_CAST (char *, buffer), count);
1239       free (buffer);
1240     }
1241 }
1242
1243 static void
1244 read_variable_attributes (struct sfm_reader *r, size_t size, size_t count)
1245 {
1246   struct text_record *text;
1247
1248   printf ("%08llx: variable attributes\n", (long long int) ftello (r->file));
1249   text = open_text_record (r, size, count);
1250   for (;;)
1251     {
1252       const char *variable = text_tokenize (text, ':');
1253       if (variable == NULL || !read_attributes (r, text, variable))
1254         break;
1255     }
1256   close_text_record (text);
1257 }
1258
1259 static void
1260 read_simple_compressed_data (struct sfm_reader *r, int max_cases)
1261 {
1262   enum { N_OPCODES = 8 };
1263   uint8_t opcodes[N_OPCODES];
1264   long long int opcode_ofs;
1265   int opcode_idx;
1266   int case_num;
1267   int i;
1268
1269   read_int (r);
1270   printf ("\n%08llx: compressed data:\n", (long long int) ftello (r->file));
1271
1272   opcode_idx = N_OPCODES;
1273   opcode_ofs = 0;
1274   case_num = 0;
1275   for (case_num = 0; case_num < max_cases; case_num++)
1276     {
1277       printf ("%08llx: case %d's uncompressible data begins\n",
1278               (long long int) ftello (r->file), case_num);
1279       for (i = 0; i < r->n_var_widths;)
1280         {
1281           int width = r->var_widths[i];
1282           char raw_value[8];
1283           int opcode;
1284
1285           if (opcode_idx >= N_OPCODES)
1286             {
1287               opcode_ofs = ftello (r->file);
1288               if (i == 0)
1289                 {
1290                   if (!try_read_bytes (r, opcodes, 8))
1291                     return;
1292                 }
1293               else
1294                 read_bytes (r, opcodes, 8);
1295               opcode_idx = 0;
1296             }
1297           opcode = opcodes[opcode_idx];
1298           printf ("%08llx: variable %d: opcode %d: ",
1299                   opcode_ofs + opcode_idx, i, opcode);
1300
1301           switch (opcode)
1302             {
1303             default:
1304               printf ("%.*g", DBL_DIG + 1, opcode - r->bias);
1305               if (width != 0)
1306                 printf (", but this is a string variable (width=%d)", width);
1307               printf ("\n");
1308               i++;
1309               break;
1310
1311             case 0:
1312               printf ("ignored padding\n");
1313               break;
1314
1315             case 252:
1316               printf ("end of data\n");
1317               return;
1318
1319             case 253:
1320               read_bytes (r, raw_value, 8);
1321               printf ("uncompressible data: ");
1322               print_untyped_value (r, raw_value);
1323               printf ("\n");
1324               i++;
1325               break;
1326
1327             case 254:
1328               printf ("spaces");
1329               if (width == 0)
1330                 printf (", but this is a numeric variable");
1331               printf ("\n");
1332               i++;
1333               break;
1334
1335             case 255:
1336               printf ("SYSMIS");
1337               if (width != 0)
1338                 printf (", but this is a string variable (width=%d)", width);
1339               printf ("\n");
1340               i++;
1341               break;
1342             }
1343
1344           opcode_idx++;
1345         }
1346     }
1347 }
1348
1349 static void
1350 read_zlib_compressed_data (struct sfm_reader *r)
1351 {
1352   long long int ofs;
1353   long long int this_ofs, next_ofs, next_len;
1354   long long int bias, zero;
1355   long long int expected_uncmp_ofs, expected_cmp_ofs;
1356   unsigned int block_size, n_blocks;
1357   unsigned int i;
1358
1359   read_int (r);
1360   ofs = ftello (r->file);
1361   printf ("\n%08llx: ZLIB compressed data header:\n", ofs);
1362
1363   this_ofs = read_int64 (r);
1364   next_ofs = read_int64 (r);
1365   next_len = read_int64 (r);
1366
1367   printf ("\tzheader_ofs: 0x%llx\n", this_ofs);
1368   if (this_ofs != ofs)
1369     printf ("\t\t(Expected 0x%llx.)\n", ofs);
1370   printf ("\tztrailer_ofs: 0x%llx\n", next_ofs);
1371   printf ("\tztrailer_len: %lld\n", next_len);
1372   if (next_len < 24 || next_len % 24)
1373     printf ("\t\t(Trailer length is not a positive multiple of 24.)\n");
1374
1375   printf ("\n%08llx: 0x%llx bytes of ZLIB compressed data\n",
1376           ofs + 8 * 3, next_ofs - (ofs + 8 * 3));
1377
1378   skip_bytes (r, next_ofs - (ofs + 8 * 3));
1379
1380   printf ("\n%08llx: ZLIB trailer fixed header:\n", next_ofs);
1381   bias = read_int64 (r);
1382   zero = read_int64 (r);
1383   block_size = read_int (r);
1384   n_blocks = read_int (r);
1385   printf ("\tbias: %lld\n", bias);
1386   printf ("\tzero: 0x%llx\n", zero);
1387   if (zero != 0)
1388     printf ("\t\t(Expected 0.)\n");
1389   printf ("\tblock_size: 0x%x\n", block_size);
1390   if (block_size != 0x3ff000)
1391     printf ("\t\t(Expected 0x3ff000.)\n");
1392   printf ("\tn_blocks: %u\n", n_blocks);
1393   if (n_blocks != next_len / 24 - 1)
1394     printf ("\t\t(Expected %llu.)\n", next_len / 24 - 1);
1395
1396   expected_uncmp_ofs = ofs;
1397   expected_cmp_ofs = ofs + 24;
1398   for (i = 0; i < n_blocks; i++)
1399     {
1400       long long int blockinfo_ofs = ftello (r->file);
1401       unsigned long long int uncompressed_ofs = read_int64 (r);
1402       unsigned long long int compressed_ofs = read_int64 (r);
1403       unsigned int uncompressed_size = read_int (r);
1404       unsigned int compressed_size = read_int (r);
1405
1406       printf ("\n%08llx: ZLIB block descriptor %d\n", blockinfo_ofs, i + 1);
1407
1408       printf ("\tuncompressed_ofs: 0x%llx\n", uncompressed_ofs);
1409       if (uncompressed_ofs != expected_uncmp_ofs)
1410         printf ("\t\t(Expected 0x%llx.)\n", ofs);
1411
1412       printf ("\tcompressed_ofs: 0x%llx\n", compressed_ofs);
1413       if (compressed_ofs != expected_cmp_ofs)
1414         printf ("\t\t(Expected 0x%llx.)\n", ofs + 24);
1415
1416       printf ("\tuncompressed_size: 0x%x\n", uncompressed_size);
1417       if (i < n_blocks - 1 && uncompressed_size != block_size)
1418         printf ("\t\t(Expected 0x%x.)\n", block_size);
1419
1420       printf ("\tcompressed_size: 0x%x\n", compressed_size);
1421       if (i == n_blocks - 1 && compressed_ofs + compressed_size != next_ofs)
1422         printf ("\t\t(This was expected to be 0x%llx.)\n",
1423                 next_ofs - compressed_size);
1424
1425       expected_uncmp_ofs += uncompressed_size;
1426       expected_cmp_ofs += compressed_size;
1427     }
1428 }
1429 \f
1430 /* Helpers for reading records that consist of structured text
1431    strings. */
1432
1433 /* State. */
1434 struct text_record
1435   {
1436     struct sfm_reader *reader;  /* Reader. */
1437     char *buffer;               /* Record contents. */
1438     size_t size;                /* Size of buffer. */
1439     size_t pos;                 /* Current position in buffer. */
1440   };
1441
1442 /* Reads SIZE * COUNT bytes into a text record for R,
1443    and returns the new text record. */
1444 static struct text_record *
1445 open_text_record (struct sfm_reader *r, size_t size, size_t count)
1446 {
1447   struct text_record *text = xmalloc (sizeof *text);
1448
1449   if (size_overflow_p (xsum (1, xtimes (size, count))))
1450     sys_error (r, "Extension record too large.");
1451
1452   size_t n_bytes = size * count;
1453   char *buffer = xmalloc (n_bytes + 1);
1454   read_bytes (r, buffer, n_bytes);
1455   buffer[n_bytes] = '\0';
1456   text->reader = r;
1457   text->buffer = buffer;
1458   text->size = n_bytes;
1459   text->pos = 0;
1460   return text;
1461 }
1462
1463 /* Closes TEXT and frees its storage.
1464    Not really needed, because the pool will free the text record anyway,
1465    but can be used to free it earlier. */
1466 static void
1467 close_text_record (struct text_record *text)
1468 {
1469   free (text->buffer);
1470   free (text);
1471 }
1472
1473 static char *
1474 text_tokenize (struct text_record *text, int delimiter)
1475 {
1476   size_t start = text->pos;
1477   while (text->pos < text->size
1478          && text->buffer[text->pos] != delimiter
1479          && text->buffer[text->pos] != '\0')
1480     text->pos++;
1481   if (start == text->pos)
1482     return NULL;
1483   text->buffer[text->pos++] = '\0';
1484   return &text->buffer[start];
1485 }
1486
1487 static bool
1488 text_match (struct text_record *text, int c)
1489 {
1490   if (text->pos < text->size && text->buffer[text->pos] == c)
1491     {
1492       text->pos++;
1493       return true;
1494     }
1495   else
1496     return false;
1497 }
1498
1499 /* Reads a integer value expressed in decimal, then a space, then a string that
1500    consists of exactly as many bytes as specified by the integer, then a space,
1501    from TEXT.  Returns the string, null-terminated, as a subset of TEXT's
1502    buffer (so the caller should not free the string). */
1503 static const char *
1504 text_parse_counted_string (struct text_record *text)
1505 {
1506   size_t start;
1507   size_t n;
1508   char *s;
1509
1510   start = text->pos;
1511   n = 0;
1512   while (isdigit ((unsigned char) text->buffer[text->pos]))
1513     n = (n * 10) + (text->buffer[text->pos++] - '0');
1514   if (start == text->pos)
1515     {
1516       sys_error (text->reader, "expecting digit at offset %zu in record",
1517                  text->pos);
1518       return NULL;
1519     }
1520
1521   if (!text_match (text, ' '))
1522     {
1523       sys_error (text->reader, "expecting space at offset %zu in record",
1524                  text->pos);
1525       return NULL;
1526     }
1527
1528   if (text->pos + n > text->size)
1529     {
1530       sys_error (text->reader, "%zu-byte string starting at offset %zu "
1531                  "exceeds record length %zu", n, text->pos, text->size);
1532       return NULL;
1533     }
1534
1535   s = &text->buffer[text->pos];
1536   if (s[n] != ' ')
1537     {
1538       sys_error (text->reader, "expecting space at offset %zu following "
1539                  "%zu-byte string", text->pos + n, n);
1540       return NULL;
1541     }
1542   s[n] = '\0';
1543   text->pos += n + 1;
1544   return s;
1545 }
1546
1547 /* Reads a variable=value pair from TEXT.
1548    Looks up the variable in DICT and stores it into *VAR.
1549    Stores a null-terminated value into *VALUE. */
1550 static bool
1551 read_variable_to_value_pair (struct text_record *text,
1552                              char **key, char **value)
1553 {
1554   *key = text_tokenize (text, '=');
1555   *value = text_tokenize (text, '\t');
1556   if (!*key || !*value)
1557     return false;
1558
1559   while (text->pos < text->size
1560          && (text->buffer[text->pos] == '\t'
1561              || text->buffer[text->pos] == '\0'))
1562     text->pos++;
1563   return true;
1564 }
1565
1566 /* Returns the current byte offset inside the TEXT's string. */
1567 static size_t
1568 text_pos (const struct text_record *text)
1569 {
1570   return text->pos;
1571 }
1572
1573 static const char *
1574 text_get_all (const struct text_record *text)
1575 {
1576   return text->buffer;
1577 }
1578 \f
1579 static void
1580 usage (void)
1581 {
1582   printf ("\
1583 %s, a utility for dissecting system files.\n\
1584 Usage: %s [OPTION]... SYSFILE...\n\
1585 where each SYSFILE is the name of a system file.\n\
1586 \n\
1587 Options:\n\
1588   --data[=MAXCASES]   print (up to MAXCASES cases of) compressed data\n\
1589   --help              display this help and exit\n\
1590   --version           output version information and exit\n",
1591           program_name, program_name);
1592 }
1593
1594 /* Displays a corruption message. */
1595 static void
1596 sys_msg (struct sfm_reader *r, const char *format, va_list args)
1597 {
1598   printf ("\"%s\" near offset 0x%llx: ",
1599           r->file_name, (long long int) ftello (r->file));
1600   vprintf (format, args);
1601   putchar ('\n');
1602 }
1603
1604 /* Displays a warning for the current file position. */
1605 static void
1606 sys_warn (struct sfm_reader *r, const char *format, ...)
1607 {
1608   va_list args;
1609
1610   va_start (args, format);
1611   sys_msg (r, format, args);
1612   va_end (args);
1613 }
1614
1615 /* Displays an error for the current file position,
1616    marks it as in an error state,
1617    and aborts reading it using longjmp. */
1618 static void
1619 sys_error (struct sfm_reader *r, const char *format, ...)
1620 {
1621   va_list args;
1622
1623   va_start (args, format);
1624   sys_msg (r, format, args);
1625   va_end (args);
1626
1627   exit (EXIT_FAILURE);
1628 }
1629 \f
1630 /* Reads BYTE_CNT bytes into BUF.
1631    Returns true if exactly BYTE_CNT bytes are successfully read.
1632    Aborts if an I/O error or a partial read occurs.
1633    If EOF_IS_OK, then an immediate end-of-file causes false to be
1634    returned; otherwise, immediate end-of-file causes an abort
1635    too. */
1636 static inline bool
1637 read_bytes_internal (struct sfm_reader *r, bool eof_is_ok,
1638                      void *buf, size_t n_bytes)
1639 {
1640   size_t bytes_read = fread (buf, 1, n_bytes, r->file);
1641   if (bytes_read == n_bytes)
1642     return true;
1643   else if (ferror (r->file))
1644     sys_error (r, "System error: %s.", strerror (errno));
1645   else if (!eof_is_ok || bytes_read != 0)
1646     sys_error (r, "Unexpected end of file.");
1647   else
1648     return false;
1649 }
1650
1651 /* Reads BYTE_CNT into BUF.
1652    Aborts upon I/O error or if end-of-file is encountered. */
1653 static void
1654 read_bytes (struct sfm_reader *r, void *buf, size_t n_bytes)
1655 {
1656   read_bytes_internal (r, false, buf, n_bytes);
1657 }
1658
1659 /* Reads BYTE_CNT bytes into BUF.
1660    Returns true if exactly BYTE_CNT bytes are successfully read.
1661    Returns false if an immediate end-of-file is encountered.
1662    Aborts if an I/O error or a partial read occurs. */
1663 static bool
1664 try_read_bytes (struct sfm_reader *r, void *buf, size_t n_bytes)
1665 {
1666   return read_bytes_internal (r, true, buf, n_bytes);
1667 }
1668
1669 /* Reads a 32-bit signed integer from R and returns its value in
1670    host format. */
1671 static int
1672 read_int (struct sfm_reader *r)
1673 {
1674   uint8_t integer[4];
1675   read_bytes (r, integer, sizeof integer);
1676   return integer_get (r->integer_format, integer, sizeof integer);
1677 }
1678
1679 /* Reads a 64-bit signed integer from R and returns its value in
1680    host format. */
1681 static int64_t
1682 read_int64 (struct sfm_reader *r)
1683 {
1684   uint8_t integer[8];
1685   read_bytes (r, integer, sizeof integer);
1686   return integer_get (r->integer_format, integer, sizeof integer);
1687 }
1688
1689 /* Reads a 64-bit floating-point number from R and returns its
1690    value in host format. */
1691 static double
1692 read_float (struct sfm_reader *r)
1693 {
1694   uint8_t number[8];
1695   read_bytes (r, number, sizeof number);
1696   return float_get_double (r->float_format, number);
1697 }
1698
1699 /* Reads exactly SIZE - 1 bytes into BUFFER
1700    and stores a null byte into BUFFER[SIZE - 1]. */
1701 static void
1702 read_string (struct sfm_reader *r, char *buffer, size_t size)
1703 {
1704   assert (size > 0);
1705   read_bytes (r, buffer, size - 1);
1706   buffer[size - 1] = '\0';
1707 }
1708
1709 /* Skips BYTES bytes forward in R. */
1710 static void
1711 skip_bytes (struct sfm_reader *r, size_t bytes)
1712 {
1713   while (bytes > 0)
1714     {
1715       char buffer[1024];
1716       size_t chunk = MIN (sizeof buffer, bytes);
1717       read_bytes (r, buffer, chunk);
1718       bytes -= chunk;
1719     }
1720 }
1721
1722 static void
1723 trim_spaces (char *s)
1724 {
1725   char *end = strchr (s, '\0');
1726   while (end > s && end[-1] == ' ')
1727     end--;
1728   *end = '\0';
1729 }
1730
1731 static void
1732 print_string (const char *s, size_t len)
1733 {
1734   if (memchr (s, 0, len) == 0)
1735     {
1736       size_t i;
1737
1738       for (i = 0; i < len; i++)
1739         {
1740           unsigned char c = s[i];
1741
1742           if (c == '\\')
1743             printf ("\\\\");
1744           else if (c == '\n' || isprint (c))
1745             putchar (c);
1746           else
1747             printf ("\\%02x", c);
1748         }
1749       putchar ('\n');
1750     }
1751   else
1752     hex_dump (0, s, len);
1753 }