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