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