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