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