1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2007, 2009 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include <data/sys-file-reader.h>
20 #include <data/sys-file-private.h>
28 #include <libpspp/assertion.h>
29 #include <libpspp/message.h>
30 #include <libpspp/compiler.h>
31 #include <libpspp/misc.h>
32 #include <libpspp/pool.h>
33 #include <libpspp/str.h>
34 #include <libpspp/hash.h>
35 #include <libpspp/array.h>
37 #include <data/attributes.h>
38 #include <data/case.h>
39 #include <data/casereader-provider.h>
40 #include <data/casereader.h>
41 #include <data/dictionary.h>
42 #include <data/file-handle-def.h>
43 #include <data/file-name.h>
44 #include <data/format.h>
45 #include <data/missing-values.h>
46 #include <data/short-names.h>
47 #include <data/value-labels.h>
48 #include <data/variable.h>
49 #include <data/value.h>
54 #include "unlocked-io.h"
59 #define _(msgid) gettext (msgid)
60 #define N_(msgid) (msgid)
62 /* System file reader. */
65 /* Resource tracking. */
66 struct pool *pool; /* All system file state. */
67 jmp_buf bail_out; /* longjmp() target for error handling. */
70 struct file_handle *fh; /* File handle. */
71 struct fh_lock *lock; /* Mutual exclusion for file handle. */
72 FILE *file; /* File stream. */
73 bool error; /* I/O or corruption error? */
74 struct caseproto *proto; /* Format of output cases. */
77 enum integer_format integer_format; /* On-disk integer format. */
78 enum float_format float_format; /* On-disk floating point format. */
79 int oct_cnt; /* Number of 8-byte units per case. */
80 struct sfm_var *sfm_vars; /* Variables. */
81 size_t sfm_var_cnt; /* Number of variables. */
82 casenumber case_cnt; /* Number of cases */
83 bool has_long_var_names; /* File has a long variable name map */
86 bool compressed; /* File is compressed? */
87 double bias; /* Compression bias, usually 100.0. */
88 uint8_t opcodes[8]; /* Current block of opcodes. */
89 size_t opcode_idx; /* Next opcode to interpret, 8 if none left. */
92 static const struct casereader_class sys_file_casereader_class;
94 static bool close_reader (struct sfm_reader *);
96 static struct variable **make_var_by_value_idx (struct sfm_reader *,
98 static struct variable *lookup_var_by_value_idx (struct sfm_reader *,
102 static void sys_msg (struct sfm_reader *r, int class,
103 const char *format, va_list args)
104 PRINTF_FORMAT (3, 0);
105 static void sys_warn (struct sfm_reader *, const char *, ...)
106 PRINTF_FORMAT (2, 3);
107 static void sys_error (struct sfm_reader *, const char *, ...)
111 static void read_bytes (struct sfm_reader *, void *, size_t);
112 static bool try_read_bytes (struct sfm_reader *, void *, size_t);
113 static int read_int (struct sfm_reader *);
114 static double read_float (struct sfm_reader *);
115 static void read_string (struct sfm_reader *, char *, size_t);
116 static void skip_bytes (struct sfm_reader *, size_t);
118 static struct text_record *open_text_record (struct sfm_reader *, size_t size);
119 static void close_text_record (struct sfm_reader *r,
120 struct text_record *);
121 static bool read_variable_to_value_pair (struct sfm_reader *,
123 struct text_record *,
124 struct variable **var, char **value);
125 static void text_warn (struct sfm_reader *r, struct text_record *text,
126 const char *format, ...)
127 PRINTF_FORMAT (3, 4);
128 static char *text_get_token (struct text_record *,
129 struct substring delimiters);
130 static bool text_match (struct text_record *, char c);
131 static bool text_read_short_name (struct sfm_reader *, struct dictionary *,
132 struct text_record *,
133 struct substring delimiters,
136 static bool close_reader (struct sfm_reader *r);
138 /* Dictionary reader. */
146 static void read_header (struct sfm_reader *, struct dictionary *,
147 int *weight_idx, int *claimed_oct_cnt,
148 struct sfm_read_info *);
149 static void read_variable_record (struct sfm_reader *, struct dictionary *,
150 int *format_warning_cnt);
151 static void parse_format_spec (struct sfm_reader *, unsigned int,
152 enum which_format, struct variable *,
153 int *format_warning_cnt);
154 static void setup_weight (struct sfm_reader *, int weight_idx,
155 struct variable **var_by_value_idx,
156 struct dictionary *);
157 static void read_documents (struct sfm_reader *, struct dictionary *);
158 static void read_value_labels (struct sfm_reader *, struct dictionary *,
159 struct variable **var_by_value_idx);
161 static void read_extension_record (struct sfm_reader *, struct dictionary *,
162 struct sfm_read_info *);
163 static void read_machine_integer_info (struct sfm_reader *,
164 size_t size, size_t count,
165 struct sfm_read_info *,
168 static void read_machine_float_info (struct sfm_reader *,
169 size_t size, size_t count);
170 static void read_display_parameters (struct sfm_reader *,
171 size_t size, size_t count,
172 struct dictionary *);
173 static void read_long_var_name_map (struct sfm_reader *,
174 size_t size, size_t count,
175 struct dictionary *);
176 static void read_long_string_map (struct sfm_reader *,
177 size_t size, size_t count,
178 struct dictionary *);
179 static void read_data_file_attributes (struct sfm_reader *,
180 size_t size, size_t count,
181 struct dictionary *);
182 static void read_variable_attributes (struct sfm_reader *,
183 size_t size, size_t count,
184 struct dictionary *);
185 static void read_long_string_value_labels (struct sfm_reader *,
186 size_t size, size_t count,
187 struct dictionary *);
189 /* Opens the system file designated by file handle FH for
190 reading. Reads the system file's dictionary into *DICT.
191 If INFO is non-null, then it receives additional info about the
194 sfm_open_reader (struct file_handle *fh, struct dictionary **dict,
195 struct sfm_read_info *volatile info)
197 struct sfm_reader *volatile r = NULL;
198 struct variable **var_by_value_idx;
199 struct sfm_read_info local_info;
200 int format_warning_cnt = 0;
205 *dict = dict_create ();
207 /* Create and initialize reader. */
208 r = pool_create_container (struct sfm_reader, pool);
214 r->has_long_var_names = false;
215 r->opcode_idx = sizeof r->opcodes;
217 /* TRANSLATORS: this fragment will be interpolated into
218 messages in fh_lock() that identify types of files. */
219 r->lock = fh_lock (fh, FH_REF_FILE, N_("system file"), FH_ACC_READ, false);
223 r->file = fn_open (fh_get_file_name (fh), "rb");
226 msg (ME, _("Error opening \"%s\" for reading as a system file: %s."),
227 fh_get_file_name (r->fh), strerror (errno));
231 /* Initialize info. */
234 memset (info, 0, sizeof *info);
236 if (setjmp (r->bail_out))
241 read_header (r, *dict, &weight_idx, &claimed_oct_cnt, info);
243 /* Read all the variable definition records. */
244 rec_type = read_int (r);
245 while (rec_type == 2)
247 read_variable_record (r, *dict, &format_warning_cnt);
248 rec_type = read_int (r);
251 /* Figure out the case format. */
252 var_by_value_idx = make_var_by_value_idx (r, *dict);
253 setup_weight (r, weight_idx, var_by_value_idx, *dict);
255 /* Read all the rest of the dictionary records. */
256 while (rec_type != 999)
261 read_value_labels (r, *dict, var_by_value_idx);
265 sys_error (r, _("Misplaced type 4 record."));
268 read_documents (r, *dict);
272 read_extension_record (r, *dict, info);
276 sys_error (r, _("Unrecognized record type %d."), rec_type);
278 rec_type = read_int (r);
282 if ( ! r->has_long_var_names )
285 for (i = 0; i < dict_get_var_cnt (*dict); i++)
287 struct variable *var = dict_get_var (*dict, i);
288 char short_name[SHORT_NAME_LEN + 1];
289 char long_name[SHORT_NAME_LEN + 1];
291 strcpy (short_name, var_get_name (var));
293 strcpy (long_name, short_name);
294 str_lowercase (long_name);
296 /* Set long name. Renaming a variable may clear the short
297 name, but we want to retain it, so re-set it
299 dict_rename_var (*dict, var, long_name);
300 var_set_short_name (var, 0, short_name);
303 r->has_long_var_names = true;
306 /* Read record 999 data, which is just filler. */
309 /* Warn if the actual amount of data per case differs from the
310 amount that the header claims. SPSS version 13 gets this
311 wrong when very long strings are involved, so don't warn in
313 if (claimed_oct_cnt != -1 && claimed_oct_cnt != r->oct_cnt
314 && info->version_major != 13)
315 sys_warn (r, _("File header claims %d variable positions but "
316 "%d were read from file."),
317 claimed_oct_cnt, r->oct_cnt);
319 /* Create an index of dictionary variable widths for
320 sfm_read_case to use. We cannot use the `struct variable's
321 from the dictionary we created, because the caller owns the
322 dictionary and may destroy or modify its variables. */
323 sfm_dictionary_to_sfm_vars (*dict, &r->sfm_vars, &r->sfm_var_cnt);
324 pool_register (r->pool, free, r->sfm_vars);
325 r->proto = caseproto_ref_pool (dict_get_proto (*dict), r->pool);
327 pool_free (r->pool, var_by_value_idx);
328 return casereader_create_sequential
330 r->case_cnt == -1 ? CASENUMBER_MAX: r->case_cnt,
331 &sys_file_casereader_class, r);
335 dict_destroy (*dict);
340 /* Closes a system file after we're done with it.
341 Returns true if an I/O error has occurred on READER, false
344 close_reader (struct sfm_reader *r)
353 if (fn_close (fh_get_file_name (r->fh), r->file) == EOF)
355 msg (ME, _("Error closing system file \"%s\": %s."),
356 fh_get_file_name (r->fh), strerror (errno));
366 pool_destroy (r->pool);
371 /* Destroys READER. */
373 sys_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
375 struct sfm_reader *r = r_;
379 /* Returns true if FILE is an SPSS system file,
382 sfm_detect (FILE *file)
386 if (fread (rec_type, 4, 1, file) != 1)
390 return !strcmp ("$FL2", rec_type);
393 /* Reads the global header of the system file.
394 Sets DICT's file label to the system file's label.
395 Sets *WEIGHT_IDX to 0 if the system file is unweighted,
396 or to the value index of the weight variable otherwise.
397 Sets *CLAIMED_OCT_CNT to the number of "octs" (8-byte units)
398 per case that the file claims to have (although it is not
400 Initializes INFO with header information. */
402 read_header (struct sfm_reader *r, struct dictionary *dict,
403 int *weight_idx, int *claimed_oct_cnt,
404 struct sfm_read_info *info)
407 char eye_catcher[61];
408 uint8_t raw_layout_code[4];
410 char creation_date[10];
411 char creation_time[9];
413 struct substring file_label_ss;
414 struct substring product;
416 read_string (r, rec_type, sizeof rec_type);
417 read_string (r, eye_catcher, sizeof eye_catcher);
419 if (strcmp ("$FL2", rec_type) != 0)
420 sys_error (r, _("This is not an SPSS system file."));
422 /* Identify integer format. */
423 read_bytes (r, raw_layout_code, sizeof raw_layout_code);
424 if ((!integer_identify (2, raw_layout_code, sizeof raw_layout_code,
426 && !integer_identify (3, raw_layout_code, sizeof raw_layout_code,
428 || (r->integer_format != INTEGER_MSB_FIRST
429 && r->integer_format != INTEGER_LSB_FIRST))
430 sys_error (r, _("This is not an SPSS system file."));
432 *claimed_oct_cnt = read_int (r);
433 if (*claimed_oct_cnt < 0 || *claimed_oct_cnt > INT_MAX / 16)
434 *claimed_oct_cnt = -1;
436 r->compressed = read_int (r) != 0;
438 *weight_idx = read_int (r);
440 r->case_cnt = read_int (r);
441 if ( r->case_cnt > INT_MAX / 2)
445 /* Identify floating-point format and obtain compression bias. */
446 read_bytes (r, raw_bias, sizeof raw_bias);
447 if (float_identify (100.0, raw_bias, sizeof raw_bias, &r->float_format) == 0)
449 sys_warn (r, _("Compression bias is not the usual "
450 "value of 100, or system file uses unrecognized "
451 "floating-point format."));
452 if (r->integer_format == INTEGER_MSB_FIRST)
453 r->float_format = FLOAT_IEEE_DOUBLE_BE;
455 r->float_format = FLOAT_IEEE_DOUBLE_LE;
457 float_convert (r->float_format, raw_bias, FLOAT_NATIVE_DOUBLE, &r->bias);
459 read_string (r, creation_date, sizeof creation_date);
460 read_string (r, creation_time, sizeof creation_time);
461 read_string (r, file_label, sizeof file_label);
464 file_label_ss = ss_cstr (file_label);
465 ss_trim (&file_label_ss, ss_cstr (" "));
466 if (!ss_is_empty (file_label_ss))
468 ss_data (file_label_ss)[ss_length (file_label_ss)] = '\0';
469 dict_set_label (dict, ss_data (file_label_ss));
472 strcpy (info->creation_date, creation_date);
473 strcpy (info->creation_time, creation_time);
474 info->integer_format = r->integer_format;
475 info->float_format = r->float_format;
476 info->compressed = r->compressed;
477 info->case_cnt = r->case_cnt;
479 product = ss_cstr (eye_catcher);
480 ss_match_string (&product, ss_cstr ("@(#) SPSS DATA FILE"));
481 ss_trim (&product, ss_cstr (" "));
482 str_copy_buf_trunc (info->product, sizeof info->product,
483 ss_data (product), ss_length (product));
486 /* Reads a variable (type 2) record from R and adds the
487 corresponding variable to DICT.
488 Also skips past additional variable records for long string
491 read_variable_record (struct sfm_reader *r, struct dictionary *dict,
492 int *format_warning_cnt)
495 int has_variable_label;
496 int missing_value_code;
501 struct variable *var;
504 width = read_int (r);
505 has_variable_label = read_int (r);
506 missing_value_code = read_int (r);
507 print_format = read_int (r);
508 write_format = read_int (r);
509 read_string (r, name, sizeof name);
510 name[strcspn (name, " ")] = '\0';
512 /* Check variable name. */
513 if (name[0] == '$' || name[0] == '#')
514 sys_error (r, "Variable name begins with invalid character `%c'.",
516 if (!var_is_plausible_name (name, false))
517 sys_error (r, _("Invalid variable name `%s'."), name);
519 /* Create variable. */
520 if (width < 0 || width > 255)
521 sys_error (r, _("Bad width %d for variable %s."), width, name);
522 var = dict_create_var (dict, name, width);
525 _("Duplicate variable name `%s' within system file."),
528 /* Set the short name the same as the long name. */
529 var_set_short_name (var, 0, var_get_name (var));
531 /* Get variable label, if any. */
532 if (has_variable_label != 0 && has_variable_label != 1)
533 sys_error (r, _("Variable label indicator field is not 0 or 1."));
534 if (has_variable_label == 1)
540 if (len >= sizeof label)
541 sys_error (r, _("Variable %s has label of invalid length %zu."),
543 read_string (r, label, len + 1);
544 var_set_label (var, label);
546 skip_bytes (r, ROUND_UP (len, 4) - len);
549 /* Set missing values. */
550 if (missing_value_code != 0)
552 struct missing_values mv;
555 mv_init_pool (r->pool, &mv, var_get_width (var));
556 if (var_is_numeric (var))
558 if (missing_value_code < -3 || missing_value_code > 3
559 || missing_value_code == -1)
560 sys_error (r, _("Numeric missing value indicator field is not "
561 "-3, -2, 0, 1, 2, or 3."));
562 if (missing_value_code < 0)
564 double low = read_float (r);
565 double high = read_float (r);
566 mv_add_range (&mv, low, high);
567 missing_value_code = -missing_value_code - 2;
569 for (i = 0; i < missing_value_code; i++)
570 mv_add_num (&mv, read_float (r));
574 int mv_width = MAX (width, 8);
577 if (missing_value_code < 1 || missing_value_code > 3)
578 sys_error (r, _("String missing value indicator field is not "
581 value_init (&value, mv_width);
582 value_set_missing (&value, mv_width);
583 for (i = 0; i < missing_value_code; i++)
585 char *s = value_str_rw (&value, mv_width);
586 read_bytes (r, s, 8);
589 value_destroy (&value, mv_width);
591 var_set_missing_values (var, &mv);
595 parse_format_spec (r, print_format, PRINT_FORMAT, var, format_warning_cnt);
596 parse_format_spec (r, write_format, WRITE_FORMAT, var, format_warning_cnt);
598 /* Account for values.
599 Skip long string continuation records, if any. */
600 nv = width == 0 ? 1 : DIV_RND_UP (width, 8);
606 for (i = 1; i < nv; i++)
608 /* Check for record type 2 and width -1. */
609 if (read_int (r) != 2 || read_int (r) != -1)
610 sys_error (r, _("Missing string continuation record."));
612 /* Skip and ignore remaining continuation data. */
613 has_variable_label = read_int (r);
614 missing_value_code = read_int (r);
615 print_format = read_int (r);
616 write_format = read_int (r);
617 read_string (r, name, sizeof name);
619 /* Variable label fields on continuation records have
620 been spotted in system files created by "SPSS Power
621 Macintosh Release 6.1". */
622 if (has_variable_label)
623 skip_bytes (r, ROUND_UP (read_int (r), 4));
628 /* Translates the format spec from sysfile format to internal
631 parse_format_spec (struct sfm_reader *r, unsigned int s,
632 enum which_format which, struct variable *v,
633 int *format_warning_cnt)
635 const int max_format_warnings = 8;
637 uint8_t raw_type = s >> 16;
643 if (!fmt_from_io (raw_type, &f.type))
644 sys_error (r, _("Unknown variable format %"PRIu8"."), raw_type);
649 ok = fmt_check_output (&f) && fmt_check_width_compat (&f, var_get_width (v));
654 if (which == PRINT_FORMAT)
655 var_set_print_format (v, &f);
657 var_set_write_format (v, &f);
659 else if (*++format_warning_cnt <= max_format_warnings)
661 char fmt_string[FMT_STRING_LEN_MAX + 1];
662 sys_warn (r, _("%s variable %s has invalid %s format %s."),
663 var_is_numeric (v) ? _("Numeric") : _("String"),
665 which == PRINT_FORMAT ? _("print") : _("write"),
666 fmt_to_string (&f, fmt_string));
668 if (*format_warning_cnt == max_format_warnings)
669 sys_warn (r, _("Suppressing further invalid format warnings."));
673 /* Sets the weighting variable in DICT to the variable
674 corresponding to the given 1-based VALUE_IDX, if VALUE_IDX is
677 setup_weight (struct sfm_reader *r, int weight_idx,
678 struct variable **var_by_value_idx, struct dictionary *dict)
682 struct variable *weight_var
683 = lookup_var_by_value_idx (r, var_by_value_idx, weight_idx);
684 if (var_is_numeric (weight_var))
685 dict_set_weight (dict, weight_var);
687 sys_error (r, _("Weighting variable must be numeric."));
691 /* Reads a document record, type 6, from system file R, and sets up
692 the documents and n_documents fields in the associated
695 read_documents (struct sfm_reader *r, struct dictionary *dict)
700 if (dict_get_documents (dict) != NULL)
701 sys_error (r, _("Multiple type 6 (document) records."));
703 line_cnt = read_int (r);
705 sys_error (r, _("Number of document lines (%d) "
706 "must be greater than 0."), line_cnt);
708 documents = pool_nmalloc (r->pool, line_cnt + 1, DOC_LINE_LENGTH);
709 read_string (r, documents, DOC_LINE_LENGTH * line_cnt + 1);
710 if (strlen (documents) == DOC_LINE_LENGTH * line_cnt)
711 dict_set_documents (dict, documents);
713 sys_error (r, _("Document line contains null byte."));
714 pool_free (r->pool, documents);
717 /* Read a type 7 extension record. */
719 read_extension_record (struct sfm_reader *r, struct dictionary *dict,
720 struct sfm_read_info *info)
722 int subtype = read_int (r);
723 size_t size = read_int (r);
724 size_t count = read_int (r);
725 size_t bytes = size * count;
727 /* Check that SIZE * COUNT + 1 doesn't overflow. Adding 1
728 allows an extra byte for a null terminator, used by some
729 extension processing routines. */
730 if (size != 0 && size_overflow_p (xsum (1, xtimes (count, size))))
731 sys_error (r, "Record type 7 subtype %d too large.", subtype);
736 read_machine_integer_info (r, size, count, info, dict);
740 read_machine_float_info (r, size, count);
744 /* Variable sets information. We don't use these yet.
745 They only apply to GUIs; see VARSETS on the APPLY
746 DICTIONARY command in SPSS documentation. */
750 /* DATE variable information. We don't use it yet, but we
755 /* Used by the MRSETS command. */
759 /* Used by the SPSS Data Entry software. */
763 read_display_parameters (r, size, count, dict);
767 read_long_var_name_map (r, size, count, dict);
771 read_long_string_map (r, size, count, dict);
775 /* New in SPSS v14? Unknown purpose. */
779 read_data_file_attributes (r, size, count, dict);
783 read_variable_attributes (r, size, count, dict);
787 /* New in SPSS 16. Contains a single string that describes
788 the character encoding, e.g. "windows-1252". */
790 char *encoding = pool_calloc (r->pool, size, count + 1);
791 read_string (r, encoding, count + 1);
792 dict_set_encoding (dict, encoding);
797 /* New in SPSS 16. Encodes value labels for long string
799 read_long_string_value_labels (r, size, count, dict);
803 sys_warn (r, _("Unrecognized record type 7, subtype %d. Please send a copy of this file, and the syntax which created it to %s"),
804 subtype, PACKAGE_BUGREPORT);
808 skip_bytes (r, bytes);
811 /* Read record type 7, subtype 3. */
813 read_machine_integer_info (struct sfm_reader *r, size_t size, size_t count,
814 struct sfm_read_info *info,
815 struct dictionary *dict)
817 int version_major = read_int (r);
818 int version_minor = read_int (r);
819 int version_revision = read_int (r);
820 int machine_code UNUSED = read_int (r);
821 int float_representation = read_int (r);
822 int compression_code UNUSED = read_int (r);
823 int integer_representation = read_int (r);
824 int character_code = read_int (r);
826 int expected_float_format;
827 int expected_integer_format;
829 if (size != 4 || count != 8)
830 sys_error (r, _("Bad size (%zu) or count (%zu) field on record type 7, "
834 /* Save version info. */
835 info->version_major = version_major;
836 info->version_minor = version_minor;
837 info->version_revision = version_revision;
839 /* Check floating point format. */
840 if (r->float_format == FLOAT_IEEE_DOUBLE_BE
841 || r->float_format == FLOAT_IEEE_DOUBLE_LE)
842 expected_float_format = 1;
843 else if (r->float_format == FLOAT_Z_LONG)
844 expected_float_format = 2;
845 else if (r->float_format == FLOAT_VAX_G || r->float_format == FLOAT_VAX_D)
846 expected_float_format = 3;
849 if (float_representation != expected_float_format)
850 sys_error (r, _("Floating-point representation indicated by "
851 "system file (%d) differs from expected (%d)."),
852 r->float_format, expected_float_format);
854 /* Check integer format. */
855 if (r->integer_format == INTEGER_MSB_FIRST)
856 expected_integer_format = 1;
857 else if (r->integer_format == INTEGER_LSB_FIRST)
858 expected_integer_format = 2;
861 if (integer_representation != expected_integer_format)
863 static const char *const endian[] = {N_("little-endian"), N_("big-endian")};
864 sys_warn (r, _("Integer format indicated by system file (%s) "
865 "differs from expected (%s)."),
866 gettext (endian[integer_representation == 1]),
867 gettext (endian[expected_integer_format == 1]));
872 Record 7 (20) provides a much more reliable way of
873 setting the encoding.
874 The character_code is used as a fallback only.
876 if ( NULL == dict_get_encoding (dict))
878 switch (character_code)
881 dict_set_encoding (dict, "EBCDIC-US");
885 /* These ostensibly mean "7-bit ASCII" and "8-bit ASCII"[sic]
886 respectively. However, there are known to be many files
887 in the wild with character code 2, yet have data which are
889 Therefore we ignore these values.
893 dict_set_encoding (dict, "MS_KANJI");
896 dict_set_encoding (dict, "UTF-7");
899 dict_set_encoding (dict, "UTF-8");
904 snprintf (enc, 100, "CP%d", character_code);
905 dict_set_encoding (dict, enc);
912 /* Read record type 7, subtype 4. */
914 read_machine_float_info (struct sfm_reader *r, size_t size, size_t count)
916 double sysmis = read_float (r);
917 double highest = read_float (r);
918 double lowest = read_float (r);
920 if (size != 8 || count != 3)
921 sys_error (r, _("Bad size (%zu) or count (%zu) on extension 4."),
924 if (sysmis != SYSMIS)
925 sys_warn (r, _("File specifies unexpected value %g as %s."),
928 if (highest != HIGHEST)
929 sys_warn (r, _("File specifies unexpected value %g as %s."),
932 if (lowest != LOWEST)
933 sys_warn (r, _("File specifies unexpected value %g as %s."),
937 /* Read record type 7, subtype 11, which specifies how variables
938 should be displayed in GUI environments. */
940 read_display_parameters (struct sfm_reader *r, size_t size, size_t count,
941 struct dictionary *dict)
950 sys_warn (r, _("Bad size %zu on extension 11."), size);
951 skip_bytes (r, size * count);
955 n_vars = dict_get_var_cnt (dict);
956 if (count == 3 * n_vars)
957 includes_width = true;
958 else if (count == 2 * n_vars)
959 includes_width = false;
962 sys_warn (r, _("Extension 11 has bad count %zu (for %zu variables)."),
964 skip_bytes (r, size * count);
968 for (i = 0; i < n_vars; ++i)
970 struct variable *v = dict_get_var (dict, i);
971 int measure = read_int (r);
972 int width = includes_width ? read_int (r) : 0;
973 int align = read_int (r);
975 /* SPSS 14 sometimes seems to set string variables' measure
977 if (0 == measure && var_is_alpha (v))
980 if (measure < 1 || measure > 3 || align < 0 || align > 2)
983 sys_warn (r, _("Invalid variable display parameters "
984 "for variable %zu (%s). "
985 "Default parameters substituted."),
986 i, var_get_name (v));
991 var_set_measure (v, (measure == 1 ? MEASURE_NOMINAL
992 : measure == 2 ? MEASURE_ORDINAL
994 var_set_alignment (v, (align == 0 ? ALIGN_LEFT
995 : align == 1 ? ALIGN_RIGHT
998 /* Older versions (SPSS 9.0) sometimes set the display
999 width to zero. This causes confusion in the GUI, so
1000 only set the width if it is nonzero. */
1002 var_set_display_width (v, width);
1006 /* Reads record type 7, subtype 13, which gives the long name
1007 that corresponds to each short name. Modifies variable names
1008 in DICT accordingly. */
1010 read_long_var_name_map (struct sfm_reader *r, size_t size, size_t count,
1011 struct dictionary *dict)
1013 struct text_record *text;
1014 struct variable *var;
1017 text = open_text_record (r, size * count);
1018 while (read_variable_to_value_pair (r, dict, text, &var, &long_name))
1021 size_t short_name_cnt;
1024 /* Validate long name. */
1025 if (!var_is_valid_name (long_name, false))
1027 sys_warn (r, _("Long variable mapping from %s to invalid "
1028 "variable name `%s'."),
1029 var_get_name (var), long_name);
1033 /* Identify any duplicates. */
1034 if (strcasecmp (var_get_short_name (var, 0), long_name)
1035 && dict_lookup_var (dict, long_name) != NULL)
1037 sys_warn (r, _("Duplicate long variable name `%s' "
1038 "within system file."), long_name);
1042 /* Renaming a variable may clear its short names, but we
1043 want to retain them, so we save them and re-set them
1045 short_name_cnt = var_get_short_name_cnt (var);
1046 short_names = xnmalloc (short_name_cnt, sizeof *short_names);
1047 for (i = 0; i < short_name_cnt; i++)
1049 const char *s = var_get_short_name (var, i);
1050 short_names[i] = s != NULL ? xstrdup (s) : NULL;
1053 /* Set long name. */
1054 dict_rename_var (dict, var, long_name);
1056 /* Restore short names. */
1057 for (i = 0; i < short_name_cnt; i++)
1059 var_set_short_name (var, i, short_names[i]);
1060 free (short_names[i]);
1064 close_text_record (r, text);
1065 r->has_long_var_names = true;
1068 /* Reads record type 7, subtype 14, which gives the real length
1069 of each very long string. Rearranges DICT accordingly. */
1071 read_long_string_map (struct sfm_reader *r, size_t size, size_t count,
1072 struct dictionary *dict)
1074 struct text_record *text;
1075 struct variable *var;
1078 text = open_text_record (r, size * count);
1079 while (read_variable_to_value_pair (r, dict, text, &var, &length_s))
1081 size_t idx = var_get_dict_index (var);
1087 length = strtol (length_s, NULL, 10);
1088 if (length < 1 || length > MAX_STRING)
1090 sys_warn (r, _("%s listed as string of invalid length %s "
1091 "in very length string record."),
1092 var_get_name (var), length_s);
1096 /* Check segments. */
1097 segment_cnt = sfm_width_to_segments (length);
1098 if (segment_cnt == 1)
1100 sys_warn (r, _("%s listed in very long string record with width %s, "
1101 "which requires only one segment."),
1102 var_get_name (var), length_s);
1105 if (idx + segment_cnt > dict_get_var_cnt (dict))
1106 sys_error (r, _("Very long string %s overflows dictionary."),
1107 var_get_name (var));
1109 /* Get the short names from the segments and check their
1111 for (i = 0; i < segment_cnt; i++)
1113 struct variable *seg = dict_get_var (dict, idx + i);
1114 int alloc_width = sfm_segment_alloc_width (length, i);
1115 int width = var_get_width (seg);
1118 var_set_short_name (var, i, var_get_short_name (seg, 0));
1119 if (ROUND_UP (width, 8) != ROUND_UP (alloc_width, 8))
1120 sys_error (r, _("Very long string with width %ld has segment %d "
1121 "of width %d (expected %d)"),
1122 length, i, width, alloc_width);
1124 dict_delete_consecutive_vars (dict, idx + 1, segment_cnt - 1);
1125 var_set_width (var, length);
1127 close_text_record (r, text);
1128 dict_compact_values (dict);
1131 /* Reads value labels from sysfile H and inserts them into the
1132 associated dictionary. */
1134 read_value_labels (struct sfm_reader *r,
1135 struct dictionary *dict, struct variable **var_by_value_idx)
1137 struct pool *subpool;
1141 char raw_value[8]; /* Value as uninterpreted bytes. */
1142 union value value; /* Value. */
1143 char *label; /* Null-terminated label string. */
1146 struct label *labels = NULL;
1147 int label_cnt; /* Number of labels. */
1149 struct variable **var = NULL; /* Associated variables. */
1150 int var_cnt; /* Number of associated variables. */
1151 int max_width; /* Maximum width of string variables. */
1155 subpool = pool_create_subpool (r->pool);
1157 /* Read the type 3 record and record its contents. We can't do
1158 much with the data yet because we don't know whether it is
1159 of numeric or string type. */
1161 /* Read number of labels. */
1162 label_cnt = read_int (r);
1164 if (size_overflow_p (xtimes (label_cnt, sizeof *labels)))
1166 sys_warn (r, _("Invalid number of labels: %d. Ignoring labels."),
1171 /* Read each value/label tuple into labels[]. */
1172 labels = pool_nalloc (subpool, label_cnt, sizeof *labels);
1173 for (i = 0; i < label_cnt; i++)
1175 struct label *label = labels + i;
1176 unsigned char label_len;
1180 read_bytes (r, label->raw_value, sizeof label->raw_value);
1182 /* Read label length. */
1183 read_bytes (r, &label_len, sizeof label_len);
1184 padded_len = ROUND_UP (label_len + 1, 8);
1186 /* Read label, padding. */
1187 label->label = pool_alloc (subpool, padded_len + 1);
1188 read_bytes (r, label->label, padded_len - 1);
1189 label->label[label_len] = 0;
1192 /* Now, read the type 4 record that has the list of variables
1193 to which the value labels are to be applied. */
1195 /* Read record type of type 4 record. */
1196 if (read_int (r) != 4)
1197 sys_error (r, _("Variable index record (type 4) does not immediately "
1198 "follow value label record (type 3) as it should."));
1200 /* Read number of variables associated with value label from type 4
1202 var_cnt = read_int (r);
1203 if (var_cnt < 1 || var_cnt > dict_get_var_cnt (dict))
1204 sys_error (r, _("Number of variables associated with a value label (%d) "
1205 "is not between 1 and the number of variables (%zu)."),
1206 var_cnt, dict_get_var_cnt (dict));
1208 /* Read the list of variables. */
1209 var = pool_nalloc (subpool, var_cnt, sizeof *var);
1211 for (i = 0; i < var_cnt; i++)
1213 var[i] = lookup_var_by_value_idx (r, var_by_value_idx, read_int (r));
1214 if (var_get_width (var[i]) > 8)
1215 sys_error (r, _("Value labels may not be added to long string "
1216 "variables (e.g. %s) using records types 3 and 4."),
1217 var_get_name (var[i]));
1218 max_width = MAX (max_width, var_get_width (var[i]));
1221 /* Type check the variables. */
1222 for (i = 1; i < var_cnt; i++)
1223 if (var_get_type (var[i]) != var_get_type (var[0]))
1224 sys_error (r, _("Variables associated with value label are not all of "
1225 "identical type. Variable %s is %s, but variable "
1227 var_get_name (var[0]),
1228 var_is_numeric (var[0]) ? _("numeric") : _("string"),
1229 var_get_name (var[i]),
1230 var_is_numeric (var[i]) ? _("numeric") : _("string"));
1232 /* Fill in labels[].value, now that we know the desired type. */
1233 for (i = 0; i < label_cnt; i++)
1235 struct label *label = labels + i;
1237 value_init_pool (subpool, &label->value, max_width);
1238 if (var_is_alpha (var[0]))
1239 buf_copy_rpad (value_str_rw (&label->value, max_width), max_width,
1240 label->raw_value, sizeof label->raw_value, ' ');
1242 label->value.f = float_get_double (r->float_format, label->raw_value);
1245 /* Assign the `value_label's to each variable. */
1246 for (i = 0; i < var_cnt; i++)
1248 struct variable *v = var[i];
1251 /* Add each label to the variable. */
1252 for (j = 0; j < label_cnt; j++)
1254 struct label *label = &labels[j];
1255 if (!var_add_value_label (v, &label->value, label->label))
1257 if (var_is_numeric (var[0]))
1258 sys_warn (r, _("Duplicate value label for %g on %s."),
1259 label->value.f, var_get_name (v));
1261 sys_warn (r, _("Duplicate value label for \"%.*s\" on %s."),
1262 max_width, value_str (&label->value, max_width),
1268 pool_destroy (subpool);
1271 /* Reads a set of custom attributes from TEXT into ATTRS.
1272 ATTRS may be a null pointer, in which case the attributes are
1273 read but discarded. */
1275 read_attributes (struct sfm_reader *r, struct text_record *text,
1276 struct attrset *attrs)
1280 struct attribute *attr;
1284 /* Parse the key. */
1285 key = text_get_token (text, ss_cstr ("("));
1289 attr = attribute_create (key);
1290 for (index = 1; ; index++)
1292 /* Parse the value. */
1296 value = text_get_token (text, ss_cstr ("\n"));
1299 text_warn (r, text, _("Error parsing attribute value %s[%d]"),
1304 length = strlen (value);
1305 if (length >= 2 && value[0] == '\'' && value[length - 1] == '\'')
1307 value[length - 1] = '\0';
1308 attribute_add_value (attr, value + 1);
1313 _("Attribute value %s[%d] is not quoted: %s"),
1315 attribute_add_value (attr, value);
1318 /* Was this the last value for this attribute? */
1319 if (text_match (text, ')'))
1323 attrset_add (attrs, attr);
1325 attribute_destroy (attr);
1327 while (!text_match (text, '/'));
1330 /* Reads record type 7, subtype 17, which lists custom
1331 attributes on the data file. */
1333 read_data_file_attributes (struct sfm_reader *r,
1334 size_t size, size_t count,
1335 struct dictionary *dict)
1337 struct text_record *text = open_text_record (r, size * count);
1338 read_attributes (r, text, dict_get_attributes (dict));
1339 close_text_record (r, text);
1343 skip_long_string_value_labels (struct sfm_reader *r, size_t n_labels)
1347 for (i = 0; i < n_labels; i++)
1349 size_t value_length, label_length;
1351 value_length = read_int (r);
1352 skip_bytes (r, value_length);
1353 label_length = read_int (r);
1354 skip_bytes (r, label_length);
1359 read_long_string_value_labels (struct sfm_reader *r,
1360 size_t size, size_t count,
1361 struct dictionary *d)
1363 const off_t start = ftello (r->file);
1364 while (ftello (r->file) - start < size * count)
1366 char var_name[VAR_NAME_LEN + 1];
1374 var_name_len = read_int (r);
1375 if (var_name_len > VAR_NAME_LEN)
1376 sys_error (r, _("Variable name length in long string value label "
1377 "record (%d) exceeds %d-byte limit."),
1378 var_name_len, VAR_NAME_LEN);
1379 read_string (r, var_name, var_name_len + 1);
1380 width = read_int (r);
1381 n_labels = read_int (r);
1383 v = dict_lookup_var (d, var_name);
1386 sys_warn (r, _("Ignoring long string value record for "
1387 "unknown variable %s."), var_name);
1388 skip_long_string_value_labels (r, n_labels);
1391 if (var_is_numeric (v))
1393 sys_warn (r, _("Ignoring long string value record for "
1394 "numeric variable %s."), var_name);
1395 skip_long_string_value_labels (r, n_labels);
1398 if (width != var_get_width (v))
1400 sys_warn (r, _("Ignoring long string value record for variable %s "
1401 "because the record's width (%d) does not match the "
1402 "variable's width (%d)"),
1403 var_name, width, var_get_width (v));
1404 skip_long_string_value_labels (r, n_labels);
1409 value_init_pool (r->pool, &value, width);
1410 for (i = 0; i < n_labels; i++)
1412 size_t value_length, label_length;
1417 value_length = read_int (r);
1418 if (value_length == width)
1419 read_string (r, value_str_rw (&value, width), width + 1);
1422 sys_warn (r, _("Ignoring long string value %zu for variable %s, "
1423 "with width %d, that has bad value width %zu."),
1424 i, var_get_name (v), width, value_length);
1425 skip_bytes (r, value_length);
1430 label_length = read_int (r);
1431 read_string (r, label, MIN (sizeof label, label_length + 1));
1432 if (label_length >= sizeof label)
1434 /* Skip and silently ignore label text after the
1435 first 255 bytes. The maximum documented length
1436 of a label is 120 bytes so this is more than
1438 skip_bytes (r, sizeof label - (label_length + 1));
1441 if (!skip && !var_add_value_label (v, &value, label))
1442 sys_warn (r, _("Duplicate value label for \"%.*s\" on %s."),
1443 width, value_str (&value, width), var_get_name (v));
1449 /* Reads record type 7, subtype 18, which lists custom
1450 attributes on individual variables. */
1452 read_variable_attributes (struct sfm_reader *r,
1453 size_t size, size_t count,
1454 struct dictionary *dict)
1456 struct text_record *text = open_text_record (r, size * count);
1459 struct variable *var;
1460 if (!text_read_short_name (r, dict, text, ss_cstr (":"), &var))
1462 read_attributes (r, text, var != NULL ? var_get_attributes (var) : NULL);
1464 close_text_record (r, text);
1470 static void partial_record (struct sfm_reader *r)
1473 static void read_error (struct casereader *, const struct sfm_reader *);
1475 static bool read_case_number (struct sfm_reader *, double *);
1476 static bool read_case_string (struct sfm_reader *, char *, size_t);
1477 static int read_opcode (struct sfm_reader *);
1478 static bool read_compressed_number (struct sfm_reader *, double *);
1479 static bool read_compressed_string (struct sfm_reader *, char *);
1480 static bool read_whole_strings (struct sfm_reader *, char *, size_t);
1481 static bool skip_whole_strings (struct sfm_reader *, size_t);
1483 /* Reads and returns one case from READER's file. Returns a null
1484 pointer if not successful. */
1485 static struct ccase *
1486 sys_file_casereader_read (struct casereader *reader, void *r_)
1488 struct sfm_reader *r = r_;
1489 struct ccase *volatile c;
1495 c = case_create (r->proto);
1496 if (setjmp (r->bail_out))
1498 casereader_force_error (reader);
1503 for (i = 0; i < r->sfm_var_cnt; i++)
1505 struct sfm_var *sv = &r->sfm_vars[i];
1506 union value *v = case_data_rw_idx (c, sv->case_index);
1508 if (sv->var_width == 0)
1510 if (!read_case_number (r, &v->f))
1515 char *s = value_str_rw (v, sv->var_width);
1516 if (!read_case_string (r, s + sv->offset, sv->segment_width))
1518 if (!skip_whole_strings (r, ROUND_DOWN (sv->padding, 8)))
1528 if (r->case_cnt != -1)
1529 read_error (reader, r);
1533 /* Issues an error that R ends in a partial record. */
1535 partial_record (struct sfm_reader *r)
1537 sys_error (r, _("File ends in partial case."));
1540 /* Issues an error that an unspecified error occurred SFM, and
1543 read_error (struct casereader *r, const struct sfm_reader *sfm)
1545 msg (ME, _("Error reading case from file %s."), fh_get_name (sfm->fh));
1546 casereader_force_error (r);
1549 /* Reads a number from R and stores its value in *D.
1550 If R is compressed, reads a compressed number;
1551 otherwise, reads a number in the regular way.
1552 Returns true if successful, false if end of file is
1553 reached immediately. */
1555 read_case_number (struct sfm_reader *r, double *d)
1560 if (!try_read_bytes (r, number, sizeof number))
1562 float_convert (r->float_format, number, FLOAT_NATIVE_DOUBLE, d);
1566 return read_compressed_number (r, d);
1569 /* Reads LENGTH string bytes from R into S.
1570 Always reads a multiple of 8 bytes; if LENGTH is not a
1571 multiple of 8, then extra bytes are read and discarded without
1573 Reads compressed strings if S is compressed.
1574 Returns true if successful, false if end of file is
1575 reached immediately. */
1577 read_case_string (struct sfm_reader *r, char *s, size_t length)
1579 size_t whole = ROUND_DOWN (length, 8);
1580 size_t partial = length % 8;
1584 if (!read_whole_strings (r, s, whole))
1591 if (!read_whole_strings (r, bounce, sizeof bounce))
1597 memcpy (s + whole, bounce, partial);
1603 /* Reads and returns the next compression opcode from R. */
1605 read_opcode (struct sfm_reader *r)
1607 assert (r->compressed);
1611 if (r->opcode_idx >= sizeof r->opcodes)
1613 if (!try_read_bytes (r, r->opcodes, sizeof r->opcodes))
1617 opcode = r->opcodes[r->opcode_idx++];
1624 /* Reads a compressed number from R and stores its value in D.
1625 Returns true if successful, false if end of file is
1626 reached immediately. */
1628 read_compressed_number (struct sfm_reader *r, double *d)
1630 int opcode = read_opcode (r);
1638 *d = read_float (r);
1642 sys_error (r, _("Compressed data is corrupt."));
1649 *d = opcode - r->bias;
1656 /* Reads a compressed 8-byte string segment from R and stores it
1658 Returns true if successful, false if end of file is
1659 reached immediately. */
1661 read_compressed_string (struct sfm_reader *r, char *dst)
1663 switch (read_opcode (r))
1670 read_bytes (r, dst, 8);
1674 memset (dst, ' ', 8);
1678 sys_error (r, _("Compressed data is corrupt."));
1684 /* Reads LENGTH string bytes from R into S.
1685 LENGTH must be a multiple of 8.
1686 Reads compressed strings if S is compressed.
1687 Returns true if successful, false if end of file is
1688 reached immediately. */
1690 read_whole_strings (struct sfm_reader *r, char *s, size_t length)
1692 assert (length % 8 == 0);
1694 return try_read_bytes (r, s, length);
1698 for (ofs = 0; ofs < length; ofs += 8)
1699 if (!read_compressed_string (r, s + ofs))
1709 /* Skips LENGTH string bytes from R.
1710 LENGTH must be a multiple of 8.
1711 (LENGTH is also limited to 1024, but that's only because the
1712 current caller never needs more than that many bytes.)
1713 Returns true if successful, false if end of file is
1714 reached immediately. */
1716 skip_whole_strings (struct sfm_reader *r, size_t length)
1719 assert (length < sizeof buffer);
1720 return read_whole_strings (r, buffer, length);
1723 /* Creates and returns a table that can be used for translating a value
1724 index into a case to a "struct variable *" for DICT. Multiple
1725 system file fields reference variables this way.
1727 This table must be created before processing the very long
1728 string extension record, because that record causes some
1729 values to be deleted from the case and the dictionary to be
1731 static struct variable **
1732 make_var_by_value_idx (struct sfm_reader *r, struct dictionary *dict)
1734 struct variable **var_by_value_idx;
1738 var_by_value_idx = pool_nmalloc (r->pool,
1739 r->oct_cnt, sizeof *var_by_value_idx);
1740 for (i = 0; i < dict_get_var_cnt (dict); i++)
1742 struct variable *v = dict_get_var (dict, i);
1743 int nv = var_is_numeric (v) ? 1 : DIV_RND_UP (var_get_width (v), 8);
1746 var_by_value_idx[value_idx++] = v;
1747 for (j = 1; j < nv; j++)
1748 var_by_value_idx[value_idx++] = NULL;
1750 assert (value_idx == r->oct_cnt);
1752 return var_by_value_idx;
1755 /* Returns the "struct variable" corresponding to the given
1756 1-basd VALUE_IDX in VAR_BY_VALUE_IDX. Verifies that the index
1758 static struct variable *
1759 lookup_var_by_value_idx (struct sfm_reader *r,
1760 struct variable **var_by_value_idx, int value_idx)
1762 struct variable *var;
1764 if (value_idx < 1 || value_idx > r->oct_cnt)
1765 sys_error (r, _("Variable index %d not in valid range 1...%d."),
1766 value_idx, r->oct_cnt);
1768 var = var_by_value_idx[value_idx - 1];
1770 sys_error (r, _("Variable index %d refers to long string "
1777 /* Returns the variable in D with the given SHORT_NAME,
1778 or a null pointer if there is none. */
1779 static struct variable *
1780 lookup_var_by_short_name (struct dictionary *d, const char *short_name)
1782 struct variable *var;
1786 /* First try looking up by full name. This often succeeds. */
1787 var = dict_lookup_var (d, short_name);
1788 if (var != NULL && !strcasecmp (var_get_short_name (var, 0), short_name))
1791 /* Iterate through the whole dictionary as a fallback. */
1792 var_cnt = dict_get_var_cnt (d);
1793 for (i = 0; i < var_cnt; i++)
1795 var = dict_get_var (d, i);
1796 if (!strcasecmp (var_get_short_name (var, 0), short_name))
1803 /* Helpers for reading records that contain structured text
1806 /* Maximum number of warnings to issue for a single text
1808 #define MAX_TEXT_WARNINGS 5
1813 struct substring buffer; /* Record contents. */
1814 size_t pos; /* Current position in buffer. */
1815 int n_warnings; /* Number of warnings issued or suppressed. */
1818 /* Reads SIZE bytes into a text record for R,
1819 and returns the new text record. */
1820 static struct text_record *
1821 open_text_record (struct sfm_reader *r, size_t size)
1823 struct text_record *text = pool_alloc (r->pool, sizeof *text);
1824 char *buffer = pool_malloc (r->pool, size + 1);
1825 read_bytes (r, buffer, size);
1826 text->buffer = ss_buffer (buffer, size);
1828 text->n_warnings = 0;
1832 /* Closes TEXT, frees its storage, and issues a final warning
1833 about suppressed warnings if necesary. */
1835 close_text_record (struct sfm_reader *r, struct text_record *text)
1837 if (text->n_warnings > MAX_TEXT_WARNINGS)
1838 sys_warn (r, _("Suppressed %d additional related warnings."),
1839 text->n_warnings - MAX_TEXT_WARNINGS);
1840 pool_free (r->pool, ss_data (text->buffer));
1843 /* Reads a variable=value pair from TEXT.
1844 Looks up the variable in DICT and stores it into *VAR.
1845 Stores a null-terminated value into *VALUE. */
1847 read_variable_to_value_pair (struct sfm_reader *r, struct dictionary *dict,
1848 struct text_record *text,
1849 struct variable **var, char **value)
1853 if (!text_read_short_name (r, dict, text, ss_cstr ("="), var))
1856 *value = text_get_token (text, ss_buffer ("\t\0", 2));
1860 text->pos += ss_span (ss_substr (text->buffer, text->pos, SIZE_MAX),
1861 ss_buffer ("\t\0", 2));
1869 text_read_short_name (struct sfm_reader *r, struct dictionary *dict,
1870 struct text_record *text, struct substring delimiters,
1871 struct variable **var)
1873 char *short_name = text_get_token (text, delimiters);
1874 if (short_name == NULL)
1877 *var = lookup_var_by_short_name (dict, short_name);
1879 text_warn (r, text, _("Variable map refers to unknown variable %s."),
1884 /* Displays a warning for the current file position, limiting the
1885 number to MAX_TEXT_WARNINGS for TEXT. */
1887 text_warn (struct sfm_reader *r, struct text_record *text,
1888 const char *format, ...)
1890 if (text->n_warnings++ < MAX_TEXT_WARNINGS)
1894 va_start (args, format);
1895 sys_msg (r, MW, format, args);
1901 text_get_token (struct text_record *text, struct substring delimiters)
1903 struct substring token;
1905 if (!ss_tokenize (text->buffer, delimiters, &text->pos, &token))
1907 ss_data (token)[ss_length (token)] = '\0';
1908 return ss_data (token);
1912 text_match (struct text_record *text, char c)
1914 if (text->buffer.string[text->pos] == c)
1925 /* Displays a corruption message. */
1927 sys_msg (struct sfm_reader *r, int class, const char *format, va_list args)
1932 ds_init_empty (&text);
1933 ds_put_format (&text, "\"%s\" near offset 0x%lx: ",
1934 fh_get_file_name (r->fh), (unsigned long) ftell (r->file));
1935 ds_put_vformat (&text, format, args);
1937 m.category = msg_class_to_category (class);
1938 m.severity = msg_class_to_severity (class);
1939 m.where.file_name = NULL;
1940 m.where.line_number = 0;
1941 m.text = ds_cstr (&text);
1946 /* Displays a warning for the current file position. */
1948 sys_warn (struct sfm_reader *r, const char *format, ...)
1952 va_start (args, format);
1953 sys_msg (r, MW, format, args);
1957 /* Displays an error for the current file position,
1958 marks it as in an error state,
1959 and aborts reading it using longjmp. */
1961 sys_error (struct sfm_reader *r, const char *format, ...)
1965 va_start (args, format);
1966 sys_msg (r, ME, format, args);
1970 longjmp (r->bail_out, 1);
1973 /* Reads BYTE_CNT bytes into BUF.
1974 Returns true if exactly BYTE_CNT bytes are successfully read.
1975 Aborts if an I/O error or a partial read occurs.
1976 If EOF_IS_OK, then an immediate end-of-file causes false to be
1977 returned; otherwise, immediate end-of-file causes an abort
1980 read_bytes_internal (struct sfm_reader *r, bool eof_is_ok,
1981 void *buf, size_t byte_cnt)
1983 size_t bytes_read = fread (buf, 1, byte_cnt, r->file);
1984 if (bytes_read == byte_cnt)
1986 else if (ferror (r->file))
1987 sys_error (r, _("System error: %s."), strerror (errno));
1988 else if (!eof_is_ok || bytes_read != 0)
1989 sys_error (r, _("Unexpected end of file."));
1994 /* Reads BYTE_CNT into BUF.
1995 Aborts upon I/O error or if end-of-file is encountered. */
1997 read_bytes (struct sfm_reader *r, void *buf, size_t byte_cnt)
1999 read_bytes_internal (r, false, buf, byte_cnt);
2002 /* Reads BYTE_CNT bytes into BUF.
2003 Returns true if exactly BYTE_CNT bytes are successfully read.
2004 Returns false if an immediate end-of-file is encountered.
2005 Aborts if an I/O error or a partial read occurs. */
2007 try_read_bytes (struct sfm_reader *r, void *buf, size_t byte_cnt)
2009 return read_bytes_internal (r, true, buf, byte_cnt);
2012 /* Reads a 32-bit signed integer from R and returns its value in
2015 read_int (struct sfm_reader *r)
2018 read_bytes (r, integer, sizeof integer);
2019 return integer_get (r->integer_format, integer, sizeof integer);
2022 /* Reads a 64-bit floating-point number from R and returns its
2023 value in host format. */
2025 read_float (struct sfm_reader *r)
2028 read_bytes (r, number, sizeof number);
2029 return float_get_double (r->float_format, number);
2032 /* Reads exactly SIZE - 1 bytes into BUFFER
2033 and stores a null byte into BUFFER[SIZE - 1]. */
2035 read_string (struct sfm_reader *r, char *buffer, size_t size)
2038 read_bytes (r, buffer, size - 1);
2039 buffer[size - 1] = '\0';
2042 /* Skips BYTES bytes forward in R. */
2044 skip_bytes (struct sfm_reader *r, size_t bytes)
2049 size_t chunk = MIN (sizeof buffer, bytes);
2050 read_bytes (r, buffer, chunk);
2055 static const struct casereader_class sys_file_casereader_class =
2057 sys_file_casereader_read,
2058 sys_file_casereader_destroy,