1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-2000, 2006-2007, 2009-2014 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/>. */
25 #include "data/any-reader.h"
26 #include "data/case.h"
27 #include "data/casereader-provider.h"
28 #include "data/casereader.h"
29 #include "data/dictionary.h"
30 #include "data/file-handle-def.h"
31 #include "data/file-name.h"
32 #include "data/format.h"
33 #include "data/identifier.h"
34 #include "data/missing-values.h"
35 #include "data/value-labels.h"
36 #include "data/value.h"
37 #include "data/variable.h"
38 #include "libpspp/float-format.h"
39 #include "libpspp/i18n.h"
40 #include "libpspp/integer-format.h"
41 #include "libpspp/message.h"
42 #include "libpspp/misc.h"
43 #include "libpspp/pool.h"
44 #include "libpspp/str.h"
46 #include "gl/localcharset.h"
47 #include "gl/minmax.h"
48 #include "gl/xalloc.h"
52 #define _(msgid) gettext (msgid)
53 #define N_(msgid) (msgid)
63 struct pcp_dir_entry main;
64 struct pcp_dir_entry variables;
65 struct pcp_dir_entry labels;
66 struct pcp_dir_entry data;
69 struct pcp_main_header
71 char product[63]; /* "PCSPSS SYSTEM FILE..." */
72 unsigned int nominal_case_size; /* Number of var positions. */
73 char creation_date[9]; /* "[m]m/dd/yy". */
74 char creation_time[9]; /* "[H]H:MM:SS". */
75 char file_label[65]; /* File label. */
76 unsigned int weight_index; /* Index of weighting variable, 0 if none. */
85 struct fmt_spec format;
91 struct pcp_value_label *val_labs;
97 struct pcp_value_label
103 /* System file reader. */
106 struct any_reader any_reader;
108 /* Resource tracking. */
109 struct pool *pool; /* All system file state. */
112 unsigned int file_size;
113 struct any_read_info info;
114 struct pcp_directory directory;
115 struct pcp_main_header header;
116 struct pcp_var_record *vars;
120 struct file_handle *fh; /* File handle. */
121 struct fh_lock *lock; /* Mutual exclusion for file handle. */
122 FILE *file; /* File stream. */
123 unsigned int pos; /* Position in file. */
124 bool error; /* I/O or corruption error? */
125 struct caseproto *proto; /* Format of output cases. */
128 unsigned int n_cases; /* Number of cases */
129 const char *encoding; /* String encoding. */
133 uint8_t opcodes[8]; /* Current block of opcodes. */
134 size_t opcode_idx; /* Next opcode to interpret, 8 if none left. */
135 bool corruption_warning; /* Warned about possible corruption? */
138 static struct pcp_reader *
139 pcp_reader_cast (const struct any_reader *r_)
141 assert (r_->klass == &pcp_file_reader_class);
142 return UP_CAST (r_, struct pcp_reader, any_reader);
145 static const struct casereader_class pcp_file_casereader_class;
147 static bool pcp_close (struct any_reader *);
149 static bool read_variables_record (struct pcp_reader *);
151 static void pcp_msg (struct pcp_reader *r, off_t, int class,
152 const char *format, va_list args)
153 PRINTF_FORMAT (4, 0);
154 static void pcp_warn (struct pcp_reader *, off_t, const char *, ...)
155 PRINTF_FORMAT (3, 4);
156 static void pcp_error (struct pcp_reader *, off_t, const char *, ...)
157 PRINTF_FORMAT (3, 4);
159 static bool read_bytes (struct pcp_reader *, void *, size_t)
161 static int try_read_bytes (struct pcp_reader *, void *, size_t)
163 static bool read_uint16 (struct pcp_reader *, unsigned int *)
165 static bool read_uint32 (struct pcp_reader *, unsigned int *)
167 static bool read_float (struct pcp_reader *, double *)
169 static double parse_float (const uint8_t number[8]);
170 static bool read_string (struct pcp_reader *, char *, size_t)
172 static bool skip_bytes (struct pcp_reader *, size_t) WARN_UNUSED_RESULT;
174 static bool pcp_seek (struct pcp_reader *, off_t);
176 static bool pcp_is_sysmis(const uint8_t *);
178 /* Dictionary reader. */
180 static bool read_dictionary (struct pcp_reader *);
181 static bool read_main_header (struct pcp_reader *, struct pcp_main_header *);
182 static void parse_header (struct pcp_reader *,
183 const struct pcp_main_header *,
184 struct any_read_info *, struct dictionary *);
185 static bool parse_variable_records (struct pcp_reader *, struct dictionary *,
186 struct pcp_var_record *, size_t n);
188 /* Tries to open FH for reading as an SPSS/PC+ system file. Returns a
189 pcp_reader if successful, otherwise NULL. */
190 static struct any_reader *
191 pcp_open (struct file_handle *fh)
193 struct pcp_reader *r;
196 /* Create and initialize reader. */
197 r = xzalloc (sizeof *r);
198 r->any_reader.klass = &pcp_file_reader_class;
199 r->pool = pool_create ();
200 pool_register (r->pool, free, r);
202 r->opcode_idx = sizeof r->opcodes;
204 /* TRANSLATORS: this fragment will be interpolated into
205 messages in fh_lock() that identify types of files. */
206 r->lock = fh_lock (fh, FH_REF_FILE, N_("SPSS/PC+ system file"),
212 r->file = fn_open (fh_get_file_name (fh), "rb");
215 msg (ME, _("Error opening `%s' for reading as an SPSS/PC+ "
217 fh_get_file_name (r->fh), strerror (errno));
221 /* Fetch file size. */
222 if (fstat (fileno (r->file), &s))
224 pcp_error (ME, 0, _("%s: stat failed (%s)."),
225 fh_get_file_name (r->fh), strerror (errno));
228 if (s.st_size > UINT_MAX)
230 pcp_error (ME, 0, _("%s: file too large."), fh_get_file_name (r->fh));
233 r->file_size = s.st_size;
235 /* Read dictionary. */
236 if (!read_dictionary (r))
239 if (!pcp_seek (r, r->directory.data.ofs))
242 return &r->any_reader;
245 pcp_close (&r->any_reader);
250 pcp_read_dir_entry (struct pcp_reader *r, struct pcp_dir_entry *de)
252 if (!read_uint32 (r, &de->ofs) || !read_uint32 (r, &de->len))
255 if (de->len > r->file_size || de->ofs > r->file_size - de->len)
257 pcp_error (r, r->pos - 8, _("Directory entry is for a %u-byte record "
258 "starting at offset %u but file is only "
260 de->ofs, de->len, r->file_size);
268 read_dictionary (struct pcp_reader *r)
270 unsigned int two, zero;
272 if (!read_uint32 (r, &two) || !read_uint32 (r, &zero))
274 if (two != 2 || zero != 0)
275 pcp_warn (r, 0, _("Directory fields have unexpected values "
276 "(%u,%u)."), two, zero);
278 if (!pcp_read_dir_entry (r, &r->directory.main)
279 || !pcp_read_dir_entry (r, &r->directory.variables)
280 || !pcp_read_dir_entry (r, &r->directory.labels)
281 || !pcp_read_dir_entry (r, &r->directory.data))
284 if (!read_main_header (r, &r->header))
287 read_variables_record (r);
292 struct get_strings_aux
303 add_string__ (struct get_strings_aux *aux,
304 const char *string, bool id, char *title)
306 if (aux->n >= aux->allocated)
308 aux->allocated = 2 * (aux->allocated + 1);
309 aux->titles = pool_realloc (aux->pool, aux->titles,
310 aux->allocated * sizeof *aux->titles);
311 aux->strings = pool_realloc (aux->pool, aux->strings,
312 aux->allocated * sizeof *aux->strings);
313 aux->ids = pool_realloc (aux->pool, aux->ids,
314 aux->allocated * sizeof *aux->ids);
317 aux->titles[aux->n] = title;
318 aux->strings[aux->n] = pool_strdup (aux->pool, string);
319 aux->ids[aux->n] = id;
323 static void PRINTF_FORMAT (3, 4)
324 add_string (struct get_strings_aux *aux,
325 const char *string, const char *title, ...)
329 va_start (args, title);
330 add_string__ (aux, string, false, pool_vasprintf (aux->pool, title, args));
334 static void PRINTF_FORMAT (3, 4)
335 add_id (struct get_strings_aux *aux, const char *id, const char *title, ...)
339 va_start (args, title);
340 add_string__ (aux, id, true, pool_vasprintf (aux->pool, title, args));
344 /* Retrieves significant string data from R in its raw format, to allow the
345 caller to try to detect the encoding in use.
347 Returns the number of strings retrieved N. Sets each of *TITLESP, *IDSP,
348 and *STRINGSP to an array of N elements allocated from POOL. For each I in
349 0...N-1, UTF-8 string *TITLESP[I] describes *STRINGSP[I], which is in
350 whatever encoding system file R uses. *IDS[I] is true if *STRINGSP[I] must
351 be a valid PSPP language identifier, false if *STRINGSP[I] is free-form
354 pcp_get_strings (const struct any_reader *r_, struct pool *pool,
355 char ***titlesp, bool **idsp, char ***stringsp)
357 struct pcp_reader *r = pcp_reader_cast (r_);
358 struct get_strings_aux aux;
370 for (i = 0; i < r->n_vars; i++)
371 if (r->vars[i].width != -1)
372 add_id (&aux, r->vars[i].name, _("Variable %zu"), ++var_idx);
375 for (i = 0; i < r->n_vars; i++)
376 if (r->vars[i].width != -1)
379 if (r->vars[i].label)
380 add_string (&aux, r->vars[i].label, _("Variable %zu Label"),
383 for (j = 0; j < r->vars[i].n_val_labs; j++)
384 add_string (&aux, r->vars[i].label,
385 _("Variable %zu Value Label %zu"), var_idx, j);
388 add_string (&aux, r->header.creation_date, _("Creation Date"));
389 add_string (&aux, r->header.creation_time, _("Creation Time"));
390 add_string (&aux, r->header.product, _("Product"));
391 add_string (&aux, r->header.file_label, _("File Label"));
393 *titlesp = aux.titles;
395 *stringsp = aux.strings;
400 find_and_delete_var (struct dictionary *dict, const char *name)
402 struct variable *var = dict_lookup_var (dict, name);
404 dict_delete_var (dict, var);
407 /* Decodes the dictionary read from R, saving it into into *DICT. Character
408 strings in R are decoded using ENCODING, or an encoding obtained from R if
409 ENCODING is null, or the locale encoding if R specifies no encoding.
411 If INFOP is non-null, then it receives additional info about the system
412 file, which the caller must eventually free with any_read_info_destroy()
413 when it is no longer needed.
415 This function consumes R. The caller must use it again later, even to
416 destroy it with pcp_close(). */
417 static struct casereader *
418 pcp_decode (struct any_reader *r_, const char *encoding,
419 struct dictionary **dictp, struct any_read_info *infop)
421 struct pcp_reader *r = pcp_reader_cast (r_);
422 struct dictionary *dict;
424 if (encoding == NULL)
426 encoding = locale_charset ();
427 pcp_warn (r, -1, _("Using default encoding %s to read this SPSS/PC+ "
428 "system file. For best results, specify an "
429 "encoding explicitly. Use SYSFILE INFO with "
430 "ENCODING=\"DETECT\" to analyze the possible "
435 dict = dict_create (encoding);
436 r->encoding = dict_get_encoding (dict);
438 parse_header (r, &r->header, &r->info, dict);
439 if (!parse_variable_records (r, dict, r->vars, r->n_vars))
442 /* Create an index of dictionary variable widths for
443 pcp_read_case to use. We cannot use the `struct variable's
444 from the dictionary we created, because the caller owns the
445 dictionary and may destroy or modify its variables. */
446 r->proto = caseproto_ref_pool (dict_get_proto (dict), r->pool);
448 find_and_delete_var (dict, "CASENUM_");
449 find_and_delete_var (dict, "DATE_");
450 find_and_delete_var (dict, "WEIGHT_");
456 memset (&r->info, 0, sizeof r->info);
459 return casereader_create_sequential
460 (NULL, r->proto, r->n_cases, &pcp_file_casereader_class, r);
463 pcp_close (&r->any_reader);
469 /* Closes R, which should have been returned by pcp_open() but not already
470 closed with pcp_decode() or this function.
471 Returns true if an I/O error has occurred on READER, false
474 pcp_close (struct any_reader *r_)
476 struct pcp_reader *r = pcp_reader_cast (r_);
481 if (fn_close (fh_get_file_name (r->fh), r->file) == EOF)
483 msg (ME, _("Error closing system file `%s': %s."),
484 fh_get_file_name (r->fh), strerror (errno));
490 any_read_info_destroy (&r->info);
495 pool_destroy (r->pool);
500 /* Destroys READER. */
502 pcp_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
504 struct pcp_reader *r = r_;
505 pcp_close (&r->any_reader);
508 /* Returns true if FILE is an SPSS/PC+ system file,
511 pcp_detect (FILE *file)
513 static const char signature[4] = "SPSS";
514 char buf[sizeof signature];
516 if (fseek (file, 0x104, SEEK_SET)
517 || (fread (buf, sizeof buf, 1, file) != 1 && !feof (file)))
520 return !memcmp (buf, signature, sizeof buf);
523 /* Reads the main header of the SPSS/PC+ system file. Initializes *HEADER and
524 *INFO, except for the string fields in *INFO, which parse_header() will
525 initialize later once the file's encoding is known. */
527 read_main_header (struct pcp_reader *r, struct pcp_main_header *header)
529 unsigned int base_ofs = r->directory.main.ofs;
530 unsigned int zero0, zero1, zero2, zero3;
531 size_t min_values, min_data_size;
532 unsigned int one0, one1;
533 unsigned int compressed;
534 unsigned int n_cases1;
537 if (!pcp_seek (r, base_ofs))
540 if (r->directory.main.len < 0xb0)
542 pcp_error (r, r->pos, _("This is not an SPSS/PC+ system file."));
545 else if (r->directory.main.len > 0xb0)
546 pcp_warn (r, r->pos, _("Record 0 has unexpected length %u."),
547 r->directory.main.len);
549 if (!read_uint16 (r, &one0)
550 || !read_string (r, header->product, sizeof header->product)
551 || !read_bytes (r, sysmis, sizeof sysmis)
552 || !read_uint32 (r, &zero0)
553 || !read_uint32 (r, &zero1)
554 || !read_uint16 (r, &one1)
555 || !read_uint16 (r, &compressed)
556 || !read_uint16 (r, &header->nominal_case_size)
557 || !read_uint16 (r, &r->n_cases)
558 || !read_uint16 (r, &header->weight_index)
559 || !read_uint16 (r, &zero2)
560 || !read_uint16 (r, &n_cases1)
561 || !read_uint16 (r, &zero3)
562 || !read_string (r, header->creation_date, sizeof header->creation_date)
563 || !read_string (r, header->creation_time, sizeof header->creation_time)
564 || !read_string (r, header->file_label, sizeof header->file_label))
567 if (!pcp_is_sysmis (sysmis))
569 double d = parse_float (sysmis);
570 pcp_warn (r, base_ofs, _("Record 0 specifies unexpected system missing "
571 "value %g (%a)."), d, d);
573 if (one0 != 1 || one1 != 1
574 || zero0 != 0 || zero1 != 0 || zero2 != 0 || zero3 != 0)
575 pcp_warn (r, base_ofs, _("Record 0 reserved fields have unexpected values "
576 "(%u,%u,%u,%u,%u,%u)."),
577 one0, one1, zero0, zero1, zero2, zero3);
578 if (n_cases1 != r->n_cases)
579 pcp_warn (r, base_ofs, _("Record 0 case counts differ (%u versus %u)."),
580 r->n_cases, n_cases1);
581 if (compressed != 0 && compressed != 1)
583 pcp_error (r, base_ofs, _("Invalid compression type %u."), compressed);
587 r->compressed = compressed != 0;
589 min_values = xtimes (header->nominal_case_size, r->n_cases);
590 min_data_size = xtimes (compressed ? 1 : 8, min_values);
591 if (r->directory.data.len < min_data_size
592 || size_overflow_p (min_data_size))
594 pcp_warn (r, base_ofs, _("Record 0 claims %u cases with %u values per "
595 "case (requiring at least %zu bytes) but data "
596 "record is only %u bytes long."),
597 r->n_cases, header->nominal_case_size, min_data_size,
598 r->directory.data.len);
606 read_value_labels (struct pcp_reader *r, struct pcp_var_record *var,
607 unsigned int start, unsigned int end)
609 size_t allocated_val_labs = 0;
613 if (end > r->directory.labels.len)
615 pcp_warn (r, r->pos - 32,
616 _("Value labels claimed to end at offset %u in labels record "
617 "but labels record is only %u bytes."),
618 end, r->directory.labels.len);
622 start += r->directory.labels.ofs;
623 end += r->directory.labels.ofs;
624 if (start > end || end > r->file_size)
626 pcp_warn (r, r->pos - 32,
627 _("Value labels claimed to be at offset %u with length %u "
628 "but file size is only %u bytes."),
629 start, end - start, r->file_size);
633 if (!pcp_seek (r, start))
636 while (r->pos < end && end - r->pos > 8)
638 struct pcp_value_label *vl;
641 if (var->n_val_labs >= allocated_val_labs)
642 var->val_labs = x2nrealloc (var->val_labs, &allocated_val_labs,
643 sizeof *var->val_labs);
644 vl = &var->val_labs[var->n_val_labs];
646 if (!read_bytes (r, vl->value, sizeof vl->value)
647 || !read_bytes (r, &len, 1))
650 if (end - r->pos < len)
653 _("Value labels end with partial label (%u bytes left in "
654 "record, label length %"PRIu8")."),
658 vl->label = pool_malloc (r->pool, len + 1);
659 if (!read_bytes (r, vl->label, len))
662 vl->label[len] = '\0';
666 pcp_warn (r, r->pos, _("%u leftover bytes following value labels."),
673 read_var_label (struct pcp_reader *r, struct pcp_var_record *var,
679 if (ofs >= r->directory.labels.len)
681 pcp_warn (r, r->pos - 32,
682 _("Variable label claimed to start at offset %u in labels "
683 "record but labels record is only %u bytes."),
684 ofs, r->directory.labels.len);
688 if (!pcp_seek (r, ofs + r->directory.labels.ofs) || !read_bytes (r, &len, 1))
691 if (len >= r->directory.labels.len - ofs)
693 pcp_warn (r, r->pos - 1,
694 _("Variable label with length %u starting at offset %u in "
695 "labels record overruns end of %u-byte labels record."),
696 len, ofs + 1, r->directory.labels.len);
700 var->label = pool_malloc (r->pool, len + 1);
701 var->label[len] = '\0';
702 return read_bytes (r, var->label, len);
705 /* Reads the variables record (record 1) into R. */
707 read_variables_record (struct pcp_reader *r)
712 if (!pcp_seek (r, r->directory.variables.ofs))
714 if (r->directory.variables.len != r->header.nominal_case_size * 32)
716 pcp_error (r, r->pos, _("Record 1 has length %u (expected %u)."),
717 r->directory.variables.len, r->header.nominal_case_size * 32);
721 r->vars = pool_calloc (r->pool,
722 r->header.nominal_case_size, sizeof *r->vars);
724 for (i = 0; i < r->header.nominal_case_size; i++)
726 struct pcp_var_record *var = &r->vars[r->n_vars++];
727 unsigned int value_label_start, value_label_end;
728 unsigned int var_label_ofs;
733 if (!read_uint32 (r, &value_label_start)
734 || !read_uint32 (r, &value_label_end)
735 || !read_uint32 (r, &var_label_ofs)
736 || !read_uint32 (r, &format)
737 || !read_string (r, var->name, sizeof var->name)
738 || !read_bytes (r, var->missing, sizeof var->missing))
741 var->weight = r->header.weight_index && i == r->header.weight_index - 1;
745 raw_type = format >> 16;
746 if (!fmt_from_io (raw_type, &var->format.type))
748 pcp_error (r, var->pos, _("Variable %u has invalid type %"PRIu8"."),
753 var->format.w = (format >> 8) & 0xff;
754 var->format.d = format & 0xff;
755 fmt_fix_output (&var->format);
756 var->width = fmt_var_width (&var->format);
760 unsigned int save_pos = r->pos;
761 if (!read_var_label (r, var, var_label_ofs)
762 || !pcp_seek (r, save_pos))
766 if (value_label_end > value_label_start && var->width <= 8)
768 unsigned int save_pos = r->pos;
769 if (!read_value_labels (r, var, value_label_start, value_label_end)
770 || !pcp_seek (r, save_pos))
776 int extra = DIV_RND_UP (var->width - 8, 8);
778 if (!skip_bytes (r, 32 * extra))
783 if (r->header.weight_index && !weighted)
784 pcp_warn (r, -1, _("Invalid weight index %u."), r->header.weight_index);
790 recode_and_trim_string (struct pool *pool, const char *from, const char *in)
792 struct substring out;
794 out = recode_substring_pool ("UTF-8", from, ss_cstr (in), pool);
795 ss_trim (&out, ss_cstr (" "));
796 return ss_xstrdup (out);
800 parse_header (struct pcp_reader *r, const struct pcp_main_header *header,
801 struct any_read_info *info, struct dictionary *dict)
803 const char *dict_encoding = dict_get_encoding (dict);
806 memset (info, 0, sizeof *info);
808 info->integer_format = INTEGER_LSB_FIRST;
809 info->float_format = FLOAT_IEEE_DOUBLE_LE;
810 info->compression = r->compressed ? ANY_COMP_SIMPLE : ANY_COMP_NONE;
811 info->case_cnt = r->n_cases;
813 /* Convert file label to UTF-8 and put it into DICT. */
814 label = recode_and_trim_string (r->pool, dict_encoding, header->file_label);
815 dict_set_label (dict, label);
818 /* Put creation date, time, and product in UTF-8 into INFO. */
819 info->creation_date = recode_and_trim_string (r->pool, dict_encoding,
820 header->creation_date);
821 info->creation_time = recode_and_trim_string (r->pool, dict_encoding,
822 header->creation_time);
823 info->product = recode_and_trim_string (r->pool, dict_encoding,
827 /* Reads a variable (type 2) record from R and adds the
828 corresponding variable to DICT.
829 Also skips past additional variable records for long string
832 parse_variable_records (struct pcp_reader *r, struct dictionary *dict,
833 struct pcp_var_record *var_recs, size_t n_var_recs)
835 const char *dict_encoding = dict_get_encoding (dict);
836 struct pcp_var_record *rec;
838 for (rec = var_recs; rec < &var_recs[n_var_recs]; rec++)
840 struct variable *var;
844 name = recode_string_pool ("UTF-8", dict_encoding,
845 rec->name, -1, r->pool);
846 name[strcspn (name, " ")] = '\0';
848 /* Transform $DATE => DATE_, $WEIGHT => WEIGHT_, $CASENUM => CASENUM_. */
850 name = pool_asprintf (r->pool, "%s_", name + 1);
852 if (!dict_id_is_valid (dict, name, false) || name[0] == '#')
854 pcp_error (r, rec->pos, _("Invalid variable name `%s'."), name);
858 var = rec->var = dict_create_var (dict, name, rec->width);
861 char *new_name = dict_make_unique_var_name (dict, NULL, NULL);
862 pcp_warn (r, rec->pos, _("Renaming variable with duplicate name "
865 var = rec->var = dict_create_var_assert (dict, new_name, rec->width);
871 dict_set_weight (dict, var);
873 pcp_warn (r, rec->pos,
874 _("Cannot weight by string variable `%s'."), name);
877 /* Set the short name the same as the long name. */
878 var_set_short_name (var, 0, name);
880 /* Get variable label, if any. */
885 utf8_label = recode_string ("UTF-8", dict_encoding, rec->label, -1);
886 var_set_label (var, utf8_label);
890 /* Add value labels. */
891 for (i = 0; i < rec->n_val_labs; i++)
896 value_init (&value, rec->width);
897 if (var_is_numeric (var))
898 value.f = parse_float (rec->val_labs[i].value);
900 memcpy (value_str_rw (&value, rec->width),
901 rec->val_labs[i].value, rec->width);
903 utf8_label = recode_string ("UTF-8", dict_encoding,
904 rec->val_labs[i].label, -1);
905 var_add_value_label (var, &value, utf8_label);
908 value_destroy (&value, rec->width);
911 /* Set missing values. */
912 if (rec->width <= 8 && !pcp_is_sysmis (rec->missing))
914 int width = var_get_width (var);
915 struct missing_values mv;
917 mv_init_pool (r->pool, &mv, width);
918 if (var_is_numeric (var))
919 mv_add_num (&mv, parse_float (rec->missing));
921 mv_add_str (&mv, rec->missing, MIN (width, 8));
922 var_set_missing_values (var, &mv);
926 var_set_both_formats (var, &rec->format);
934 static void read_error (struct casereader *, const struct pcp_reader *);
936 static bool read_case_number (struct pcp_reader *, double *);
937 static int read_case_string (struct pcp_reader *, uint8_t *, size_t);
938 static int read_opcode (struct pcp_reader *);
939 static bool read_compressed_number (struct pcp_reader *, double *);
940 static int read_compressed_string (struct pcp_reader *, uint8_t *);
941 static int read_whole_strings (struct pcp_reader *, uint8_t *, size_t);
943 /* Reads and returns one case from READER's file. Returns a null
944 pointer if not successful. */
945 static struct ccase *
946 pcp_file_casereader_read (struct casereader *reader, void *r_)
948 struct pcp_reader *r = r_;
949 unsigned int start_pos = r->pos;
954 if (r->error || !r->n_cases)
958 c = case_create (r->proto);
959 for (i = 0; i < r->n_vars; i++)
961 struct pcp_var_record *var = &r->vars[i];
962 union value *v = case_data_rw_idx (c, i);
965 retval = read_case_number (r, &v->f);
967 retval = read_case_string (r, value_str_rw (v, var->width),
972 pcp_error (r, r->pos, _("File ends in partial case."));
976 if (r->pos > r->directory.data.ofs + r->directory.data.len)
978 pcp_error (r, r->pos, _("Case beginning at offset 0x%08x extends past "
979 "end of data record at offset 0x%08x."),
980 start_pos, r->directory.data.ofs + r->directory.data.len);
987 read_error (reader, r);
992 /* Issues an error that an unspecified error occurred PCP, and
995 read_error (struct casereader *r, const struct pcp_reader *pcp)
997 msg (ME, _("Error reading case from file %s."), fh_get_name (pcp->fh));
998 casereader_force_error (r);
1001 /* Reads a number from R and stores its value in *D.
1002 If R is compressed, reads a compressed number;
1003 otherwise, reads a number in the regular way.
1004 Returns true if successful, false if end of file is
1005 reached immediately. */
1007 read_case_number (struct pcp_reader *r, double *d)
1012 if (!try_read_bytes (r, number, sizeof number))
1014 *d = parse_float (number);
1018 return read_compressed_number (r, d);
1021 /* Reads LENGTH string bytes from R into S. Always reads a multiple of 8
1022 bytes; if LENGTH is not a multiple of 8, then extra bytes are read and
1023 discarded without being written to S. Reads compressed strings if S is
1024 compressed. Returns 1 if successful, 0 if end of file is reached
1025 immediately, or -1 for some kind of error. */
1027 read_case_string (struct pcp_reader *r, uint8_t *s, size_t length)
1029 size_t whole = ROUND_DOWN (length, 8);
1030 size_t partial = length % 8;
1034 int retval = read_whole_strings (r, s, whole);
1042 int retval = read_whole_strings (r, bounce, sizeof bounce);
1045 memcpy (s + whole, bounce, partial);
1051 /* Reads and returns the next compression opcode from R. */
1053 read_opcode (struct pcp_reader *r)
1055 assert (r->compressed);
1056 if (r->opcode_idx >= sizeof r->opcodes)
1058 int retval = try_read_bytes (r, r->opcodes, sizeof r->opcodes);
1063 return r->opcodes[r->opcode_idx++];
1066 /* Reads a compressed number from R and stores its value in D.
1067 Returns true if successful, false if end of file is
1068 reached immediately. */
1070 read_compressed_number (struct pcp_reader *r, double *d)
1072 int opcode = read_opcode (r);
1083 return read_float (r, d);
1086 *d = opcode - 105.0;
1091 /* Reads a compressed 8-byte string segment from R and stores it in DST. */
1093 read_compressed_string (struct pcp_reader *r, uint8_t *dst)
1098 opcode = read_opcode (r);
1105 retval = read_bytes (r, dst, 8);
1106 return retval == 1 ? 1 : -1;
1109 if (!r->corruption_warning)
1111 r->corruption_warning = true;
1112 pcp_warn (r, r->pos,
1113 _("Possible compressed data corruption: "
1114 "string contains compressed integer (opcode %d)."),
1117 memset (dst, ' ', 8);
1122 /* Reads LENGTH string bytes from R into S. LENGTH must be a multiple of 8.
1123 Reads compressed strings if S is compressed. Returns 1 if successful, 0 if
1124 end of file is reached immediately, or -1 for some kind of error. */
1126 read_whole_strings (struct pcp_reader *r, uint8_t *s, size_t length)
1128 assert (length % 8 == 0);
1130 return try_read_bytes (r, s, length);
1135 for (ofs = 0; ofs < length; ofs += 8)
1137 int retval = read_compressed_string (r, s + ofs);
1147 /* Displays a corruption message. */
1149 pcp_msg (struct pcp_reader *r, off_t offset,
1150 int class, const char *format, va_list args)
1155 ds_init_empty (&text);
1157 ds_put_format (&text, _("`%s' near offset 0x%llx: "),
1158 fh_get_file_name (r->fh), (long long int) offset);
1160 ds_put_format (&text, _("`%s': "), fh_get_file_name (r->fh));
1161 ds_put_vformat (&text, format, args);
1163 m.category = msg_class_to_category (class);
1164 m.severity = msg_class_to_severity (class);
1170 m.text = ds_cstr (&text);
1175 /* Displays a warning for offset OFFSET in the file. */
1177 pcp_warn (struct pcp_reader *r, off_t offset, const char *format, ...)
1181 va_start (args, format);
1182 pcp_msg (r, offset, MW, format, args);
1186 /* Displays an error for the current file position,
1187 marks it as in an error state,
1188 and aborts reading it using longjmp. */
1190 pcp_error (struct pcp_reader *r, off_t offset, const char *format, ...)
1194 va_start (args, format);
1195 pcp_msg (r, offset, ME, format, args);
1201 /* Reads BYTE_CNT bytes into BUF.
1202 Returns 1 if exactly BYTE_CNT bytes are successfully read.
1203 Returns -1 if an I/O error or a partial read occurs.
1204 Returns 0 for an immediate end-of-file and, if EOF_IS_OK is false, reports
1207 read_bytes_internal (struct pcp_reader *r, bool eof_is_ok,
1208 void *buf, size_t byte_cnt)
1210 size_t bytes_read = fread (buf, 1, byte_cnt, r->file);
1211 r->pos += bytes_read;
1212 if (bytes_read == byte_cnt)
1214 else if (ferror (r->file))
1216 pcp_error (r, r->pos, _("System error: %s."), strerror (errno));
1219 else if (!eof_is_ok || bytes_read != 0)
1221 pcp_error (r, r->pos, _("Unexpected end of file."));
1228 /* Reads BYTE_CNT into BUF.
1229 Returns true if successful.
1230 Returns false upon I/O error or if end-of-file is encountered. */
1232 read_bytes (struct pcp_reader *r, void *buf, size_t byte_cnt)
1234 return read_bytes_internal (r, false, buf, byte_cnt) == 1;
1237 /* Reads BYTE_CNT bytes into BUF.
1238 Returns 1 if exactly BYTE_CNT bytes are successfully read.
1239 Returns 0 if an immediate end-of-file is encountered.
1240 Returns -1 if an I/O error or a partial read occurs. */
1242 try_read_bytes (struct pcp_reader *r, void *buf, size_t byte_cnt)
1244 return read_bytes_internal (r, true, buf, byte_cnt);
1247 /* Reads a 16-bit signed integer from R and stores its value in host format in
1248 *X. Returns true if successful, otherwise false. */
1250 read_uint16 (struct pcp_reader *r, unsigned int *x)
1253 if (read_bytes (r, integer, sizeof integer) != 1)
1255 *x = integer_get (INTEGER_LSB_FIRST, integer, sizeof integer);
1259 /* Reads a 32-bit signed integer from R and stores its value in host format in
1260 *X. Returns true if successful, otherwise false. */
1262 read_uint32 (struct pcp_reader *r, unsigned int *x)
1265 if (read_bytes (r, integer, sizeof integer) != 1)
1267 *x = integer_get (INTEGER_LSB_FIRST, integer, sizeof integer);
1271 /* Reads exactly SIZE - 1 bytes into BUFFER
1272 and stores a null byte into BUFFER[SIZE - 1]. */
1274 read_string (struct pcp_reader *r, char *buffer, size_t size)
1279 ok = read_bytes (r, buffer, size - 1);
1281 buffer[size - 1] = '\0';
1285 /* Skips BYTES bytes forward in R. */
1287 skip_bytes (struct pcp_reader *r, size_t bytes)
1292 size_t chunk = MIN (sizeof buffer, bytes);
1293 if (!read_bytes (r, buffer, chunk))
1302 pcp_seek (struct pcp_reader *r, off_t offset)
1304 if (fseeko (r->file, offset, SEEK_SET))
1306 pcp_error (r, 0, _("%s: seek failed (%s)."),
1307 fh_get_file_name (r->fh), strerror (errno));
1314 /* Reads a 64-bit floating-point number from R and returns its
1315 value in host format. */
1317 read_float (struct pcp_reader *r, double *d)
1321 if (!read_bytes (r, number, sizeof number))
1325 *d = parse_float (number);
1331 parse_float (const uint8_t number[8])
1333 return (pcp_is_sysmis (number)
1335 : float_get_double (FLOAT_IEEE_DOUBLE_LE, number));
1339 pcp_is_sysmis(const uint8_t *p)
1341 static const uint8_t sysmis[8]
1342 = { 0xf5, 0x1e, 0x26, 0x02, 0x8a, 0x8c, 0xed, 0xff };
1343 return !memcmp (p, sysmis, 8);
1346 static const struct casereader_class pcp_file_casereader_class =
1348 pcp_file_casereader_read,
1349 pcp_file_casereader_destroy,
1354 const struct any_reader_class pcp_file_reader_class =
1356 N_("SPSS/PC+ System File"),