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