xref: /freebsd/contrib/file/src/apprentice.c (revision 406a584d7e80c2617dc035ede0d922215a12141c)
1 /*
2  * Copyright (c) Ian F. Darwin 1986-1995.
3  * Software written by Ian F. Darwin and others;
4  * maintained 1995-present by Christos Zoulas and others.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*
29  * apprentice - make one pass through /etc/magic, learning its secrets.
30  */
31 
32 #include "file.h"
33 
34 #ifndef	lint
35 FILE_RCSID("@(#)$File: apprentice.c,v 1.272 2018/06/22 20:39:50 christos Exp $")
36 #endif	/* lint */
37 
38 #include "magic.h"
39 #include <stdlib.h>
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #ifdef HAVE_STDDEF_H
44 #include <stddef.h>
45 #endif
46 #include <string.h>
47 #include <assert.h>
48 #include <ctype.h>
49 #include <fcntl.h>
50 #ifdef QUICK
51 #include <sys/mman.h>
52 #endif
53 #include <dirent.h>
54 #if defined(HAVE_LIMITS_H)
55 #include <limits.h>
56 #endif
57 
58 #ifndef SSIZE_MAX
59 #define MAXMAGIC_SIZE        ((ssize_t)0x7fffffff)
60 #else
61 #define MAXMAGIC_SIZE        SSIZE_MAX
62 #endif
63 
64 #define	EATAB {while (isascii((unsigned char) *l) && \
65 		      isspace((unsigned char) *l))  ++l;}
66 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
67 			tolower((unsigned char) (l)) : (l))
68 /*
69  * Work around a bug in headers on Digital Unix.
70  * At least confirmed for: OSF1 V4.0 878
71  */
72 #if defined(__osf__) && defined(__DECC)
73 #ifdef MAP_FAILED
74 #undef MAP_FAILED
75 #endif
76 #endif
77 
78 #ifndef MAP_FAILED
79 #define MAP_FAILED (void *) -1
80 #endif
81 
82 #ifndef MAP_FILE
83 #define MAP_FILE 0
84 #endif
85 
86 #define ALLOC_CHUNK	(size_t)10
87 #define ALLOC_INCR	(size_t)200
88 
89 #define MAP_TYPE_USER	0
90 #define MAP_TYPE_MALLOC	1
91 #define MAP_TYPE_MMAP	2
92 
93 struct magic_entry {
94 	struct magic *mp;
95 	uint32_t cont_count;
96 	uint32_t max_count;
97 };
98 
99 struct magic_entry_set {
100 	struct magic_entry *me;
101 	uint32_t count;
102 	uint32_t max;
103 };
104 
105 struct magic_map {
106 	void *p;
107 	size_t len;
108 	int type;
109 	struct magic *magic[MAGIC_SETS];
110 	uint32_t nmagic[MAGIC_SETS];
111 };
112 
113 int file_formats[FILE_NAMES_SIZE];
114 const size_t file_nformats = FILE_NAMES_SIZE;
115 const char *file_names[FILE_NAMES_SIZE];
116 const size_t file_nnames = FILE_NAMES_SIZE;
117 
118 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
119 private int hextoint(int);
120 private const char *getstr(struct magic_set *, struct magic *, const char *,
121     int);
122 private int parse(struct magic_set *, struct magic_entry *, const char *,
123     size_t, int);
124 private void eatsize(const char **);
125 private int apprentice_1(struct magic_set *, const char *, int);
126 private size_t apprentice_magic_strength(const struct magic *);
127 private int apprentice_sort(const void *, const void *);
128 private void apprentice_list(struct mlist *, int );
129 private struct magic_map *apprentice_load(struct magic_set *,
130     const char *, int);
131 private struct mlist *mlist_alloc(void);
132 private void mlist_free(struct mlist *);
133 private void byteswap(struct magic *, uint32_t);
134 private void bs1(struct magic *);
135 private uint16_t swap2(uint16_t);
136 private uint32_t swap4(uint32_t);
137 private uint64_t swap8(uint64_t);
138 private char *mkdbname(struct magic_set *, const char *, int);
139 private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
140     size_t);
141 private struct magic_map *apprentice_map(struct magic_set *, const char *);
142 private int check_buffer(struct magic_set *, struct magic_map *, const char *);
143 private void apprentice_unmap(struct magic_map *);
144 private int apprentice_compile(struct magic_set *, struct magic_map *,
145     const char *);
146 private int check_format_type(const char *, int, const char **);
147 private int check_format(struct magic_set *, struct magic *);
148 private int get_op(char);
149 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
150 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
151 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
152 private int parse_ext(struct magic_set *, struct magic_entry *, const char *);
153 
154 
155 private size_t magicsize = sizeof(struct magic);
156 
157 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
158 
159 private struct {
160 	const char *name;
161 	size_t len;
162 	int (*fun)(struct magic_set *, struct magic_entry *, const char *);
163 } bang[] = {
164 #define	DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
165 	DECLARE_FIELD(mime),
166 	DECLARE_FIELD(apple),
167 	DECLARE_FIELD(ext),
168 	DECLARE_FIELD(strength),
169 #undef	DECLARE_FIELD
170 	{ NULL, 0, NULL }
171 };
172 
173 #ifdef COMPILE_ONLY
174 
175 int main(int, char *[]);
176 
177 int
178 main(int argc, char *argv[])
179 {
180 	int ret;
181 	struct magic_set *ms;
182 	char *progname;
183 
184 	if ((progname = strrchr(argv[0], '/')) != NULL)
185 		progname++;
186 	else
187 		progname = argv[0];
188 
189 	if (argc != 2) {
190 		(void)fprintf(stderr, "Usage: %s file\n", progname);
191 		return 1;
192 	}
193 
194 	if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
195 		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
196 		return 1;
197 	}
198 	ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
199 	if (ret == 1)
200 		(void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
201 	magic_close(ms);
202 	return ret;
203 }
204 #endif /* COMPILE_ONLY */
205 
206 struct type_tbl_s {
207 	const char name[16];
208 	const size_t len;
209 	const int type;
210 	const int format;
211 };
212 
213 /*
214  * XXX - the actual Single UNIX Specification says that "long" means "long",
215  * as in the C data type, but we treat it as meaning "4-byte integer".
216  * Given that the OS X version of file 5.04 did the same, I guess that passes
217  * the actual test; having "long" be dependent on how big a "long" is on
218  * the machine running "file" is silly.
219  */
220 static const struct type_tbl_s type_tbl[] = {
221 # define XX(s)		s, (sizeof(s) - 1)
222 # define XX_NULL	"", 0
223 	{ XX("invalid"),	FILE_INVALID,		FILE_FMT_NONE },
224 	{ XX("byte"),		FILE_BYTE,		FILE_FMT_NUM },
225 	{ XX("short"),		FILE_SHORT,		FILE_FMT_NUM },
226 	{ XX("default"),	FILE_DEFAULT,		FILE_FMT_NONE },
227 	{ XX("long"),		FILE_LONG,		FILE_FMT_NUM },
228 	{ XX("string"),		FILE_STRING,		FILE_FMT_STR },
229 	{ XX("date"),		FILE_DATE,		FILE_FMT_STR },
230 	{ XX("beshort"),	FILE_BESHORT,		FILE_FMT_NUM },
231 	{ XX("belong"),		FILE_BELONG,		FILE_FMT_NUM },
232 	{ XX("bedate"),		FILE_BEDATE,		FILE_FMT_STR },
233 	{ XX("leshort"),	FILE_LESHORT,		FILE_FMT_NUM },
234 	{ XX("lelong"),		FILE_LELONG,		FILE_FMT_NUM },
235 	{ XX("ledate"),		FILE_LEDATE,		FILE_FMT_STR },
236 	{ XX("pstring"),	FILE_PSTRING,		FILE_FMT_STR },
237 	{ XX("ldate"),		FILE_LDATE,		FILE_FMT_STR },
238 	{ XX("beldate"),	FILE_BELDATE,		FILE_FMT_STR },
239 	{ XX("leldate"),	FILE_LELDATE,		FILE_FMT_STR },
240 	{ XX("regex"),		FILE_REGEX,		FILE_FMT_STR },
241 	{ XX("bestring16"),	FILE_BESTRING16,	FILE_FMT_STR },
242 	{ XX("lestring16"),	FILE_LESTRING16,	FILE_FMT_STR },
243 	{ XX("search"),		FILE_SEARCH,		FILE_FMT_STR },
244 	{ XX("medate"),		FILE_MEDATE,		FILE_FMT_STR },
245 	{ XX("meldate"),	FILE_MELDATE,		FILE_FMT_STR },
246 	{ XX("melong"),		FILE_MELONG,		FILE_FMT_NUM },
247 	{ XX("quad"),		FILE_QUAD,		FILE_FMT_QUAD },
248 	{ XX("lequad"),		FILE_LEQUAD,		FILE_FMT_QUAD },
249 	{ XX("bequad"),		FILE_BEQUAD,		FILE_FMT_QUAD },
250 	{ XX("qdate"),		FILE_QDATE,		FILE_FMT_STR },
251 	{ XX("leqdate"),	FILE_LEQDATE,		FILE_FMT_STR },
252 	{ XX("beqdate"),	FILE_BEQDATE,		FILE_FMT_STR },
253 	{ XX("qldate"),		FILE_QLDATE,		FILE_FMT_STR },
254 	{ XX("leqldate"),	FILE_LEQLDATE,		FILE_FMT_STR },
255 	{ XX("beqldate"),	FILE_BEQLDATE,		FILE_FMT_STR },
256 	{ XX("float"),		FILE_FLOAT,		FILE_FMT_FLOAT },
257 	{ XX("befloat"),	FILE_BEFLOAT,		FILE_FMT_FLOAT },
258 	{ XX("lefloat"),	FILE_LEFLOAT,		FILE_FMT_FLOAT },
259 	{ XX("double"),		FILE_DOUBLE,		FILE_FMT_DOUBLE },
260 	{ XX("bedouble"),	FILE_BEDOUBLE,		FILE_FMT_DOUBLE },
261 	{ XX("ledouble"),	FILE_LEDOUBLE,		FILE_FMT_DOUBLE },
262 	{ XX("leid3"),		FILE_LEID3,		FILE_FMT_NUM },
263 	{ XX("beid3"),		FILE_BEID3,		FILE_FMT_NUM },
264 	{ XX("indirect"),	FILE_INDIRECT,		FILE_FMT_NUM },
265 	{ XX("qwdate"),		FILE_QWDATE,		FILE_FMT_STR },
266 	{ XX("leqwdate"),	FILE_LEQWDATE,		FILE_FMT_STR },
267 	{ XX("beqwdate"),	FILE_BEQWDATE,		FILE_FMT_STR },
268 	{ XX("name"),		FILE_NAME,		FILE_FMT_NONE },
269 	{ XX("use"),		FILE_USE,		FILE_FMT_NONE },
270 	{ XX("clear"),		FILE_CLEAR,		FILE_FMT_NONE },
271 	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
272 	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
273 };
274 
275 /*
276  * These are not types, and cannot be preceded by "u" to make them
277  * unsigned.
278  */
279 static const struct type_tbl_s special_tbl[] = {
280 	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
281 	{ XX("name"),		FILE_NAME,		FILE_FMT_STR },
282 	{ XX("use"),		FILE_USE,		FILE_FMT_STR },
283 	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
284 };
285 # undef XX
286 # undef XX_NULL
287 
288 private int
289 get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
290 {
291 	const struct type_tbl_s *p;
292 
293 	for (p = tbl; p->len; p++) {
294 		if (strncmp(l, p->name, p->len) == 0) {
295 			if (t)
296 				*t = l + p->len;
297 			break;
298 		}
299 	}
300 	return p->type;
301 }
302 
303 private int
304 get_standard_integer_type(const char *l, const char **t)
305 {
306 	int type;
307 
308 	if (isalpha((unsigned char)l[1])) {
309 		switch (l[1]) {
310 		case 'C':
311 			/* "dC" and "uC" */
312 			type = FILE_BYTE;
313 			break;
314 		case 'S':
315 			/* "dS" and "uS" */
316 			type = FILE_SHORT;
317 			break;
318 		case 'I':
319 		case 'L':
320 			/*
321 			 * "dI", "dL", "uI", and "uL".
322 			 *
323 			 * XXX - the actual Single UNIX Specification says
324 			 * that "L" means "long", as in the C data type,
325 			 * but we treat it as meaning "4-byte integer".
326 			 * Given that the OS X version of file 5.04 did
327 			 * the same, I guess that passes the actual SUS
328 			 * validation suite; having "dL" be dependent on
329 			 * how big a "long" is on the machine running
330 			 * "file" is silly.
331 			 */
332 			type = FILE_LONG;
333 			break;
334 		case 'Q':
335 			/* "dQ" and "uQ" */
336 			type = FILE_QUAD;
337 			break;
338 		default:
339 			/* "d{anything else}", "u{anything else}" */
340 			return FILE_INVALID;
341 		}
342 		l += 2;
343 	} else if (isdigit((unsigned char)l[1])) {
344 		/*
345 		 * "d{num}" and "u{num}"; we only support {num} values
346 		 * of 1, 2, 4, and 8 - the Single UNIX Specification
347 		 * doesn't say anything about whether arbitrary
348 		 * values should be supported, but both the Solaris 10
349 		 * and OS X Mountain Lion versions of file passed the
350 		 * Single UNIX Specification validation suite, and
351 		 * neither of them support values bigger than 8 or
352 		 * non-power-of-2 values.
353 		 */
354 		if (isdigit((unsigned char)l[2])) {
355 			/* Multi-digit, so > 9 */
356 			return FILE_INVALID;
357 		}
358 		switch (l[1]) {
359 		case '1':
360 			type = FILE_BYTE;
361 			break;
362 		case '2':
363 			type = FILE_SHORT;
364 			break;
365 		case '4':
366 			type = FILE_LONG;
367 			break;
368 		case '8':
369 			type = FILE_QUAD;
370 			break;
371 		default:
372 			/* XXX - what about 3, 5, 6, or 7? */
373 			return FILE_INVALID;
374 		}
375 		l += 2;
376 	} else {
377 		/*
378 		 * "d" or "u" by itself.
379 		 */
380 		type = FILE_LONG;
381 		++l;
382 	}
383 	if (t)
384 		*t = l;
385 	return type;
386 }
387 
388 private void
389 init_file_tables(void)
390 {
391 	static int done = 0;
392 	const struct type_tbl_s *p;
393 
394 	if (done)
395 		return;
396 	done++;
397 
398 	for (p = type_tbl; p->len; p++) {
399 		assert(p->type < FILE_NAMES_SIZE);
400 		file_names[p->type] = p->name;
401 		file_formats[p->type] = p->format;
402 	}
403 	assert(p - type_tbl == FILE_NAMES_SIZE);
404 }
405 
406 private int
407 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
408 {
409 	struct mlist *ml;
410 
411 	mlp->map = NULL;
412 	if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
413 		return -1;
414 
415 	ml->map = idx == 0 ? map : NULL;
416 	ml->magic = map->magic[idx];
417 	ml->nmagic = map->nmagic[idx];
418 
419 	mlp->prev->next = ml;
420 	ml->prev = mlp->prev;
421 	ml->next = mlp;
422 	mlp->prev = ml;
423 	return 0;
424 }
425 
426 /*
427  * Handle one file or directory.
428  */
429 private int
430 apprentice_1(struct magic_set *ms, const char *fn, int action)
431 {
432 	struct magic_map *map;
433 #ifndef COMPILE_ONLY
434 	struct mlist *ml;
435 	size_t i;
436 #endif
437 
438 	if (magicsize != FILE_MAGICSIZE) {
439 		file_error(ms, 0, "magic element size %lu != %lu",
440 		    (unsigned long)sizeof(*map->magic[0]),
441 		    (unsigned long)FILE_MAGICSIZE);
442 		return -1;
443 	}
444 
445 	if (action == FILE_COMPILE) {
446 		map = apprentice_load(ms, fn, action);
447 		if (map == NULL)
448 			return -1;
449 		return apprentice_compile(ms, map, fn);
450 	}
451 
452 #ifndef COMPILE_ONLY
453 	map = apprentice_map(ms, fn);
454 	if (map == (struct magic_map *)-1)
455 		return -1;
456 	if (map == NULL) {
457 		if (ms->flags & MAGIC_CHECK)
458 			file_magwarn(ms, "using regular magic file `%s'", fn);
459 		map = apprentice_load(ms, fn, action);
460 		if (map == NULL)
461 			return -1;
462 	}
463 
464 	for (i = 0; i < MAGIC_SETS; i++) {
465 		if (add_mlist(ms->mlist[i], map, i) == -1) {
466 			file_oomem(ms, sizeof(*ml));
467 			return -1;
468 		}
469 	}
470 
471 	if (action == FILE_LIST) {
472 		for (i = 0; i < MAGIC_SETS; i++) {
473 			printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
474 			    i);
475 			apprentice_list(ms->mlist[i], BINTEST);
476 			printf("Text patterns:\n");
477 			apprentice_list(ms->mlist[i], TEXTTEST);
478 		}
479 	}
480 	return 0;
481 #else
482 	return 0;
483 #endif /* COMPILE_ONLY */
484 }
485 
486 protected void
487 file_ms_free(struct magic_set *ms)
488 {
489 	size_t i;
490 	if (ms == NULL)
491 		return;
492 	for (i = 0; i < MAGIC_SETS; i++)
493 		mlist_free(ms->mlist[i]);
494 	free(ms->o.pbuf);
495 	free(ms->o.buf);
496 	free(ms->c.li);
497 	free(ms);
498 }
499 
500 protected struct magic_set *
501 file_ms_alloc(int flags)
502 {
503 	struct magic_set *ms;
504 	size_t i, len;
505 
506 	if ((ms = CAST(struct magic_set *, calloc((size_t)1,
507 	    sizeof(struct magic_set)))) == NULL)
508 		return NULL;
509 
510 	if (magic_setflags(ms, flags) == -1) {
511 		errno = EINVAL;
512 		goto free;
513 	}
514 
515 	ms->o.buf = ms->o.pbuf = NULL;
516 	len = (ms->c.len = 10) * sizeof(*ms->c.li);
517 
518 	if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
519 		goto free;
520 
521 	ms->event_flags = 0;
522 	ms->error = -1;
523 	for (i = 0; i < MAGIC_SETS; i++)
524 		ms->mlist[i] = NULL;
525 	ms->file = "unknown";
526 	ms->line = 0;
527 	ms->indir_max = FILE_INDIR_MAX;
528 	ms->name_max = FILE_NAME_MAX;
529 	ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
530 	ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
531 	ms->elf_notes_max = FILE_ELF_NOTES_MAX;
532 	ms->regex_max = FILE_REGEX_MAX;
533 	ms->bytes_max = FILE_BYTES_MAX;
534 	return ms;
535 free:
536 	free(ms);
537 	return NULL;
538 }
539 
540 private void
541 apprentice_unmap(struct magic_map *map)
542 {
543 	size_t i;
544 	if (map == NULL)
545 		return;
546 
547 	switch (map->type) {
548 	case MAP_TYPE_USER:
549 		break;
550 	case MAP_TYPE_MALLOC:
551 		for (i = 0; i < MAGIC_SETS; i++) {
552 			void *b = map->magic[i];
553 			void *p = map->p;
554 			if (CAST(char *, b) >= CAST(char *, p) &&
555 			    CAST(char *, b) <= CAST(char *, p) + map->len)
556 				continue;
557 			free(map->magic[i]);
558 		}
559 		free(map->p);
560 		break;
561 #ifdef QUICK
562 	case MAP_TYPE_MMAP:
563 		if (map->p && map->p != MAP_FAILED)
564 			(void)munmap(map->p, map->len);
565 		break;
566 #endif
567 	default:
568 		abort();
569 	}
570 	free(map);
571 }
572 
573 private struct mlist *
574 mlist_alloc(void)
575 {
576 	struct mlist *mlist;
577 	if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
578 		return NULL;
579 	}
580 	mlist->next = mlist->prev = mlist;
581 	return mlist;
582 }
583 
584 private void
585 mlist_free(struct mlist *mlist)
586 {
587 	struct mlist *ml, *next;
588 
589 	if (mlist == NULL)
590 		return;
591 
592 	ml = mlist->next;
593 	for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
594 		if (ml->map)
595 			apprentice_unmap(CAST(struct magic_map *, ml->map));
596 		free(ml);
597 		if (ml == mlist)
598 			break;
599 	}
600 }
601 
602 #ifndef COMPILE_ONLY
603 /* void **bufs: an array of compiled magic files */
604 protected int
605 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
606     size_t *sizes, size_t nbufs)
607 {
608 	size_t i, j;
609 	struct mlist *ml;
610 	struct magic_map *map;
611 
612 	if (nbufs == 0)
613 		return -1;
614 
615 	(void)file_reset(ms, 0);
616 
617 	init_file_tables();
618 
619 	for (i = 0; i < MAGIC_SETS; i++) {
620 		mlist_free(ms->mlist[i]);
621 		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
622 			file_oomem(ms, sizeof(*ms->mlist[i]));
623 			goto fail;
624 		}
625 	}
626 
627 	for (i = 0; i < nbufs; i++) {
628 		map = apprentice_buf(ms, bufs[i], sizes[i]);
629 		if (map == NULL)
630 			goto fail;
631 
632 		for (j = 0; j < MAGIC_SETS; j++) {
633 			if (add_mlist(ms->mlist[j], map, j) == -1) {
634 				file_oomem(ms, sizeof(*ml));
635 				goto fail;
636 			}
637 		}
638 	}
639 
640 	return 0;
641 fail:
642 	for (i = 0; i < MAGIC_SETS; i++) {
643 		mlist_free(ms->mlist[i]);
644 		ms->mlist[i] = NULL;
645 	}
646 	return -1;
647 }
648 #endif
649 
650 /* const char *fn: list of magic files and directories */
651 protected int
652 file_apprentice(struct magic_set *ms, const char *fn, int action)
653 {
654 	char *p, *mfn;
655 	int fileerr, errs = -1;
656 	size_t i;
657 
658 	(void)file_reset(ms, 0);
659 
660 	if ((fn = magic_getpath(fn, action)) == NULL)
661 		return -1;
662 
663 	init_file_tables();
664 
665 	if ((mfn = strdup(fn)) == NULL) {
666 		file_oomem(ms, strlen(fn));
667 		return -1;
668 	}
669 
670 	for (i = 0; i < MAGIC_SETS; i++) {
671 		mlist_free(ms->mlist[i]);
672 		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
673 			file_oomem(ms, sizeof(*ms->mlist[i]));
674 			while (i-- > 0) {
675 				mlist_free(ms->mlist[i]);
676 				ms->mlist[i] = NULL;
677 			}
678 			free(mfn);
679 			return -1;
680 		}
681 	}
682 	fn = mfn;
683 
684 	while (fn) {
685 		p = strchr(fn, PATHSEP);
686 		if (p)
687 			*p++ = '\0';
688 		if (*fn == '\0')
689 			break;
690 		fileerr = apprentice_1(ms, fn, action);
691 		errs = MAX(errs, fileerr);
692 		fn = p;
693 	}
694 
695 	free(mfn);
696 
697 	if (errs == -1) {
698 		for (i = 0; i < MAGIC_SETS; i++) {
699 			mlist_free(ms->mlist[i]);
700 			ms->mlist[i] = NULL;
701 		}
702 		file_error(ms, 0, "could not find any valid magic files!");
703 		return -1;
704 	}
705 
706 #if 0
707 	/*
708 	 * Always leave the database loaded
709 	 */
710 	if (action == FILE_LOAD)
711 		return 0;
712 
713 	for (i = 0; i < MAGIC_SETS; i++) {
714 		mlist_free(ms->mlist[i]);
715 		ms->mlist[i] = NULL;
716 	}
717 #endif
718 
719 	switch (action) {
720 	case FILE_LOAD:
721 	case FILE_COMPILE:
722 	case FILE_CHECK:
723 	case FILE_LIST:
724 		return 0;
725 	default:
726 		file_error(ms, 0, "Invalid action %d", action);
727 		return -1;
728 	}
729 }
730 
731 /*
732  * Compute the real length of a magic expression, for the purposes
733  * of determining how "strong" a magic expression is (approximating
734  * how specific its matches are):
735  *	- magic characters count 0 unless escaped.
736  *	- [] expressions count 1
737  *	- {} expressions count 0
738  *	- regular characters or escaped magic characters count 1
739  *	- 0 length expressions count as one
740  */
741 private size_t
742 nonmagic(const char *str)
743 {
744 	const char *p;
745 	size_t rv = 0;
746 
747 	for (p = str; *p; p++)
748 		switch (*p) {
749 		case '\\':	/* Escaped anything counts 1 */
750 			if (!*++p)
751 				p--;
752 			rv++;
753 			continue;
754 		case '?':	/* Magic characters count 0 */
755 		case '*':
756 		case '.':
757 		case '+':
758 		case '^':
759 		case '$':
760 			continue;
761 		case '[':	/* Bracketed expressions count 1 the ']' */
762 			while (*p && *p != ']')
763 				p++;
764 			p--;
765 			continue;
766 		case '{':	/* Braced expressions count 0 */
767 			while (*p && *p != '}')
768 				p++;
769 			if (!*p)
770 				p--;
771 			continue;
772 		default:	/* Anything else counts 1 */
773 			rv++;
774 			continue;
775 		}
776 
777 	return rv == 0 ? 1 : rv;	/* Return at least 1 */
778 }
779 
780 
781 private size_t
782 typesize(int type)
783 {
784 	switch (type) {
785 	case FILE_BYTE:
786 		return 1;
787 
788 	case FILE_SHORT:
789 	case FILE_LESHORT:
790 	case FILE_BESHORT:
791 		return 2;
792 
793 	case FILE_LONG:
794 	case FILE_LELONG:
795 	case FILE_BELONG:
796 	case FILE_MELONG:
797 		return 4;
798 
799 	case FILE_DATE:
800 	case FILE_LEDATE:
801 	case FILE_BEDATE:
802 	case FILE_MEDATE:
803 	case FILE_LDATE:
804 	case FILE_LELDATE:
805 	case FILE_BELDATE:
806 	case FILE_MELDATE:
807 	case FILE_FLOAT:
808 	case FILE_BEFLOAT:
809 	case FILE_LEFLOAT:
810 		return 4;
811 
812 	case FILE_QUAD:
813 	case FILE_BEQUAD:
814 	case FILE_LEQUAD:
815 	case FILE_QDATE:
816 	case FILE_LEQDATE:
817 	case FILE_BEQDATE:
818 	case FILE_QLDATE:
819 	case FILE_LEQLDATE:
820 	case FILE_BEQLDATE:
821 	case FILE_QWDATE:
822 	case FILE_LEQWDATE:
823 	case FILE_BEQWDATE:
824 	case FILE_DOUBLE:
825 	case FILE_BEDOUBLE:
826 	case FILE_LEDOUBLE:
827 		return 8;
828 	default:
829 		return (size_t)~0;
830 	}
831 }
832 
833 /*
834  * Get weight of this magic entry, for sorting purposes.
835  */
836 private size_t
837 apprentice_magic_strength(const struct magic *m)
838 {
839 #define MULT 10
840 	size_t ts, v, val = 2 * MULT;	/* baseline strength */
841 
842 	switch (m->type) {
843 	case FILE_DEFAULT:	/* make sure this sorts last */
844 		if (m->factor_op != FILE_FACTOR_OP_NONE)
845 			abort();
846 		return 0;
847 
848 	case FILE_BYTE:
849 	case FILE_SHORT:
850 	case FILE_LESHORT:
851 	case FILE_BESHORT:
852 	case FILE_LONG:
853 	case FILE_LELONG:
854 	case FILE_BELONG:
855 	case FILE_MELONG:
856 	case FILE_DATE:
857 	case FILE_LEDATE:
858 	case FILE_BEDATE:
859 	case FILE_MEDATE:
860 	case FILE_LDATE:
861 	case FILE_LELDATE:
862 	case FILE_BELDATE:
863 	case FILE_MELDATE:
864 	case FILE_FLOAT:
865 	case FILE_BEFLOAT:
866 	case FILE_LEFLOAT:
867 	case FILE_QUAD:
868 	case FILE_BEQUAD:
869 	case FILE_LEQUAD:
870 	case FILE_QDATE:
871 	case FILE_LEQDATE:
872 	case FILE_BEQDATE:
873 	case FILE_QLDATE:
874 	case FILE_LEQLDATE:
875 	case FILE_BEQLDATE:
876 	case FILE_QWDATE:
877 	case FILE_LEQWDATE:
878 	case FILE_BEQWDATE:
879 	case FILE_DOUBLE:
880 	case FILE_BEDOUBLE:
881 	case FILE_LEDOUBLE:
882 		ts = typesize(m->type);
883 		if (ts == (size_t)~0)
884 			abort();
885 		val += ts * MULT;
886 		break;
887 
888 	case FILE_PSTRING:
889 	case FILE_STRING:
890 		val += m->vallen * MULT;
891 		break;
892 
893 	case FILE_BESTRING16:
894 	case FILE_LESTRING16:
895 		val += m->vallen * MULT / 2;
896 		break;
897 
898 	case FILE_SEARCH:
899 		val += m->vallen * MAX(MULT / m->vallen, 1);
900 		break;
901 
902 	case FILE_REGEX:
903 		v = nonmagic(m->value.s);
904 		val += v * MAX(MULT / v, 1);
905 		break;
906 
907 	case FILE_INDIRECT:
908 	case FILE_NAME:
909 	case FILE_USE:
910 		break;
911 
912 	case FILE_DER:
913 		val += MULT;
914 		break;
915 
916 	default:
917 		(void)fprintf(stderr, "Bad type %d\n", m->type);
918 		abort();
919 	}
920 
921 	switch (m->reln) {
922 	case 'x':	/* matches anything penalize */
923 	case '!':       /* matches almost anything penalize */
924 		val = 0;
925 		break;
926 
927 	case '=':	/* Exact match, prefer */
928 		val += MULT;
929 		break;
930 
931 	case '>':
932 	case '<':	/* comparison match reduce strength */
933 		val -= 2 * MULT;
934 		break;
935 
936 	case '^':
937 	case '&':	/* masking bits, we could count them too */
938 		val -= MULT;
939 		break;
940 
941 	default:
942 		(void)fprintf(stderr, "Bad relation %c\n", m->reln);
943 		abort();
944 	}
945 
946 	if (val == 0)	/* ensure we only return 0 for FILE_DEFAULT */
947 		val = 1;
948 
949 	switch (m->factor_op) {
950 	case FILE_FACTOR_OP_NONE:
951 		break;
952 	case FILE_FACTOR_OP_PLUS:
953 		val += m->factor;
954 		break;
955 	case FILE_FACTOR_OP_MINUS:
956 		val -= m->factor;
957 		break;
958 	case FILE_FACTOR_OP_TIMES:
959 		val *= m->factor;
960 		break;
961 	case FILE_FACTOR_OP_DIV:
962 		val /= m->factor;
963 		break;
964 	default:
965 		abort();
966 	}
967 
968 	/*
969 	 * Magic entries with no description get a bonus because they depend
970 	 * on subsequent magic entries to print something.
971 	 */
972 	if (m->desc[0] == '\0')
973 		val++;
974 	return val;
975 }
976 
977 /*
978  * Sort callback for sorting entries by "strength" (basically length)
979  */
980 private int
981 apprentice_sort(const void *a, const void *b)
982 {
983 	const struct magic_entry *ma = CAST(const struct magic_entry *, a);
984 	const struct magic_entry *mb = CAST(const struct magic_entry *, b);
985 	size_t sa = apprentice_magic_strength(ma->mp);
986 	size_t sb = apprentice_magic_strength(mb->mp);
987 	if (sa == sb)
988 		return 0;
989 	else if (sa > sb)
990 		return -1;
991 	else
992 		return 1;
993 }
994 
995 /*
996  * Shows sorted patterns list in the order which is used for the matching
997  */
998 private void
999 apprentice_list(struct mlist *mlist, int mode)
1000 {
1001 	uint32_t magindex = 0;
1002 	struct mlist *ml;
1003 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
1004 		for (magindex = 0; magindex < ml->nmagic; magindex++) {
1005 			struct magic *m = &ml->magic[magindex];
1006 			if ((m->flag & mode) != mode) {
1007 				/* Skip sub-tests */
1008 				while (magindex + 1 < ml->nmagic &&
1009 				       ml->magic[magindex + 1].cont_level != 0)
1010 					++magindex;
1011 				continue; /* Skip to next top-level test*/
1012 			}
1013 
1014 			/*
1015 			 * Try to iterate over the tree until we find item with
1016 			 * description/mimetype.
1017 			 */
1018 			while (magindex + 1 < ml->nmagic &&
1019 			       ml->magic[magindex + 1].cont_level != 0 &&
1020 			       *ml->magic[magindex].desc == '\0' &&
1021 			       *ml->magic[magindex].mimetype == '\0')
1022 				magindex++;
1023 
1024 			printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
1025 			    apprentice_magic_strength(m),
1026 			    ml->magic[magindex].lineno,
1027 			    ml->magic[magindex].desc,
1028 			    ml->magic[magindex].mimetype);
1029 		}
1030 	}
1031 }
1032 
1033 private void
1034 set_test_type(struct magic *mstart, struct magic *m)
1035 {
1036 	switch (m->type) {
1037 	case FILE_BYTE:
1038 	case FILE_SHORT:
1039 	case FILE_LONG:
1040 	case FILE_DATE:
1041 	case FILE_BESHORT:
1042 	case FILE_BELONG:
1043 	case FILE_BEDATE:
1044 	case FILE_LESHORT:
1045 	case FILE_LELONG:
1046 	case FILE_LEDATE:
1047 	case FILE_LDATE:
1048 	case FILE_BELDATE:
1049 	case FILE_LELDATE:
1050 	case FILE_MEDATE:
1051 	case FILE_MELDATE:
1052 	case FILE_MELONG:
1053 	case FILE_QUAD:
1054 	case FILE_LEQUAD:
1055 	case FILE_BEQUAD:
1056 	case FILE_QDATE:
1057 	case FILE_LEQDATE:
1058 	case FILE_BEQDATE:
1059 	case FILE_QLDATE:
1060 	case FILE_LEQLDATE:
1061 	case FILE_BEQLDATE:
1062 	case FILE_QWDATE:
1063 	case FILE_LEQWDATE:
1064 	case FILE_BEQWDATE:
1065 	case FILE_FLOAT:
1066 	case FILE_BEFLOAT:
1067 	case FILE_LEFLOAT:
1068 	case FILE_DOUBLE:
1069 	case FILE_BEDOUBLE:
1070 	case FILE_LEDOUBLE:
1071 	case FILE_DER:
1072 		mstart->flag |= BINTEST;
1073 		break;
1074 	case FILE_STRING:
1075 	case FILE_PSTRING:
1076 	case FILE_BESTRING16:
1077 	case FILE_LESTRING16:
1078 		/* Allow text overrides */
1079 		if (mstart->str_flags & STRING_TEXTTEST)
1080 			mstart->flag |= TEXTTEST;
1081 		else
1082 			mstart->flag |= BINTEST;
1083 		break;
1084 	case FILE_REGEX:
1085 	case FILE_SEARCH:
1086 		/* Check for override */
1087 		if (mstart->str_flags & STRING_BINTEST)
1088 			mstart->flag |= BINTEST;
1089 		if (mstart->str_flags & STRING_TEXTTEST)
1090 			mstart->flag |= TEXTTEST;
1091 
1092 		if (mstart->flag & (TEXTTEST|BINTEST))
1093 			break;
1094 
1095 		/* binary test if pattern is not text */
1096 		if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1097 		    NULL) <= 0)
1098 			mstart->flag |= BINTEST;
1099 		else
1100 			mstart->flag |= TEXTTEST;
1101 		break;
1102 	case FILE_DEFAULT:
1103 		/* can't deduce anything; we shouldn't see this at the
1104 		   top level anyway */
1105 		break;
1106 	case FILE_INVALID:
1107 	default:
1108 		/* invalid search type, but no need to complain here */
1109 		break;
1110 	}
1111 }
1112 
1113 private int
1114 addentry(struct magic_set *ms, struct magic_entry *me,
1115    struct magic_entry_set *mset)
1116 {
1117 	size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1118 	if (mset[i].count == mset[i].max) {
1119 		struct magic_entry *mp;
1120 
1121 		mset[i].max += ALLOC_INCR;
1122 		if ((mp = CAST(struct magic_entry *,
1123 		    realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1124 		    NULL) {
1125 			file_oomem(ms, sizeof(*mp) * mset[i].max);
1126 			return -1;
1127 		}
1128 		(void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1129 		    ALLOC_INCR);
1130 		mset[i].me = mp;
1131 	}
1132 	mset[i].me[mset[i].count++] = *me;
1133 	memset(me, 0, sizeof(*me));
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Load and parse one file.
1139  */
1140 private void
1141 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1142    struct magic_entry_set *mset)
1143 {
1144 	size_t lineno = 0, llen = 0;
1145 	char *line = NULL;
1146 	ssize_t len;
1147 	struct magic_entry me;
1148 
1149 	FILE *f = fopen(ms->file = fn, "r");
1150 	if (f == NULL) {
1151 		if (errno != ENOENT)
1152 			file_error(ms, errno, "cannot read magic file `%s'",
1153 				   fn);
1154 		(*errs)++;
1155 		return;
1156 	}
1157 
1158 	memset(&me, 0, sizeof(me));
1159 	/* read and parse this file */
1160 	for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1161 	    ms->line++) {
1162 		if (len == 0) /* null line, garbage, etc */
1163 			continue;
1164 		if (line[len - 1] == '\n') {
1165 			lineno++;
1166 			line[len - 1] = '\0'; /* delete newline */
1167 		}
1168 		switch (line[0]) {
1169 		case '\0':	/* empty, do not parse */
1170 		case '#':	/* comment, do not parse */
1171 			continue;
1172 		case '!':
1173 			if (line[1] == ':') {
1174 				size_t i;
1175 
1176 				for (i = 0; bang[i].name != NULL; i++) {
1177 					if ((size_t)(len - 2) > bang[i].len &&
1178 					    memcmp(bang[i].name, line + 2,
1179 					    bang[i].len) == 0)
1180 						break;
1181 				}
1182 				if (bang[i].name == NULL) {
1183 					file_error(ms, 0,
1184 					    "Unknown !: entry `%s'", line);
1185 					(*errs)++;
1186 					continue;
1187 				}
1188 				if (me.mp == NULL) {
1189 					file_error(ms, 0,
1190 					    "No current entry for :!%s type",
1191 						bang[i].name);
1192 					(*errs)++;
1193 					continue;
1194 				}
1195 				if ((*bang[i].fun)(ms, &me,
1196 				    line + bang[i].len + 2) != 0) {
1197 					(*errs)++;
1198 					continue;
1199 				}
1200 				continue;
1201 			}
1202 			/*FALLTHROUGH*/
1203 		default:
1204 		again:
1205 			switch (parse(ms, &me, line, lineno, action)) {
1206 			case 0:
1207 				continue;
1208 			case 1:
1209 				(void)addentry(ms, &me, mset);
1210 				goto again;
1211 			default:
1212 				(*errs)++;
1213 				break;
1214 			}
1215 		}
1216 	}
1217 	if (me.mp)
1218 		(void)addentry(ms, &me, mset);
1219 	free(line);
1220 	(void)fclose(f);
1221 }
1222 
1223 /*
1224  * parse a file or directory of files
1225  * const char *fn: name of magic file or directory
1226  */
1227 private int
1228 cmpstrp(const void *p1, const void *p2)
1229 {
1230         return strcmp(*(char *const *)p1, *(char *const *)p2);
1231 }
1232 
1233 
1234 private uint32_t
1235 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1236     uint32_t starttest)
1237 {
1238 	static const char text[] = "text";
1239 	static const char binary[] = "binary";
1240 	static const size_t len = sizeof(text);
1241 
1242 	uint32_t i = starttest;
1243 
1244 	do {
1245 		set_test_type(me[starttest].mp, me[i].mp);
1246 		if ((ms->flags & MAGIC_DEBUG) == 0)
1247 			continue;
1248 		(void)fprintf(stderr, "%s%s%s: %s\n",
1249 		    me[i].mp->mimetype,
1250 		    me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1251 		    me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1252 		    me[i].mp->flag & BINTEST ? binary : text);
1253 		if (me[i].mp->flag & BINTEST) {
1254 			char *p = strstr(me[i].mp->desc, text);
1255 			if (p && (p == me[i].mp->desc ||
1256 			    isspace((unsigned char)p[-1])) &&
1257 			    (p + len - me[i].mp->desc == MAXstring
1258 			    || (p[len] == '\0' ||
1259 			    isspace((unsigned char)p[len]))))
1260 				(void)fprintf(stderr, "*** Possible "
1261 				    "binary test for text type\n");
1262 		}
1263 	} while (++i < nme && me[i].mp->cont_level != 0);
1264 	return i;
1265 }
1266 
1267 private void
1268 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1269 {
1270 	uint32_t i;
1271 	for (i = 0; i < nme; i++) {
1272 		if (me[i].mp->cont_level == 0 &&
1273 		    me[i].mp->type == FILE_DEFAULT) {
1274 			while (++i < nme)
1275 				if (me[i].mp->cont_level == 0)
1276 					break;
1277 			if (i != nme) {
1278 				/* XXX - Ugh! */
1279 				ms->line = me[i].mp->lineno;
1280 				file_magwarn(ms,
1281 				    "level 0 \"default\" did not sort last");
1282 			}
1283 			return;
1284 		}
1285 	}
1286 }
1287 
1288 private int
1289 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1290     struct magic **ma, uint32_t *nma)
1291 {
1292 	uint32_t i, mentrycount = 0;
1293 	size_t slen;
1294 
1295 	for (i = 0; i < nme; i++)
1296 		mentrycount += me[i].cont_count;
1297 
1298 	slen = sizeof(**ma) * mentrycount;
1299 	if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1300 		file_oomem(ms, slen);
1301 		return -1;
1302 	}
1303 
1304 	mentrycount = 0;
1305 	for (i = 0; i < nme; i++) {
1306 		(void)memcpy(*ma + mentrycount, me[i].mp,
1307 		    me[i].cont_count * sizeof(**ma));
1308 		mentrycount += me[i].cont_count;
1309 	}
1310 	*nma = mentrycount;
1311 	return 0;
1312 }
1313 
1314 private void
1315 magic_entry_free(struct magic_entry *me, uint32_t nme)
1316 {
1317 	uint32_t i;
1318 	if (me == NULL)
1319 		return;
1320 	for (i = 0; i < nme; i++)
1321 		free(me[i].mp);
1322 	free(me);
1323 }
1324 
1325 private struct magic_map *
1326 apprentice_load(struct magic_set *ms, const char *fn, int action)
1327 {
1328 	int errs = 0;
1329 	uint32_t i, j;
1330 	size_t files = 0, maxfiles = 0;
1331 	char **filearr = NULL, *mfn;
1332 	struct stat st;
1333 	struct magic_map *map;
1334 	struct magic_entry_set mset[MAGIC_SETS];
1335 	DIR *dir;
1336 	struct dirent *d;
1337 
1338 	memset(mset, 0, sizeof(mset));
1339 	ms->flags |= MAGIC_CHECK;	/* Enable checks for parsed files */
1340 
1341 
1342 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1343 	{
1344 		file_oomem(ms, sizeof(*map));
1345 		return NULL;
1346 	}
1347 	map->type = MAP_TYPE_MALLOC;
1348 
1349 	/* print silly verbose header for USG compat. */
1350 	if (action == FILE_CHECK)
1351 		(void)fprintf(stderr, "%s\n", usg_hdr);
1352 
1353 	/* load directory or file */
1354 	if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1355 		dir = opendir(fn);
1356 		if (!dir) {
1357 			errs++;
1358 			goto out;
1359 		}
1360 		while ((d = readdir(dir)) != NULL) {
1361 			if (d->d_name[0] == '.')
1362 				continue;
1363 			if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1364 				file_oomem(ms,
1365 				    strlen(fn) + strlen(d->d_name) + 2);
1366 				errs++;
1367 				closedir(dir);
1368 				goto out;
1369 			}
1370 			if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1371 				free(mfn);
1372 				continue;
1373 			}
1374 			if (files >= maxfiles) {
1375 				size_t mlen;
1376 				maxfiles = (maxfiles + 1) * 2;
1377 				mlen = maxfiles * sizeof(*filearr);
1378 				if ((filearr = CAST(char **,
1379 				    realloc(filearr, mlen))) == NULL) {
1380 					file_oomem(ms, mlen);
1381 					free(mfn);
1382 					closedir(dir);
1383 					errs++;
1384 					goto out;
1385 				}
1386 			}
1387 			filearr[files++] = mfn;
1388 		}
1389 		closedir(dir);
1390 		qsort(filearr, files, sizeof(*filearr), cmpstrp);
1391 		for (i = 0; i < files; i++) {
1392 			load_1(ms, action, filearr[i], &errs, mset);
1393 			free(filearr[i]);
1394 		}
1395 		free(filearr);
1396 	} else
1397 		load_1(ms, action, fn, &errs, mset);
1398 	if (errs)
1399 		goto out;
1400 
1401 	for (j = 0; j < MAGIC_SETS; j++) {
1402 		/* Set types of tests */
1403 		for (i = 0; i < mset[j].count; ) {
1404 			if (mset[j].me[i].mp->cont_level != 0) {
1405 				i++;
1406 				continue;
1407 			}
1408 			i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1409 		}
1410 		if (mset[j].me)
1411 			qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1412 			    apprentice_sort);
1413 
1414 		/*
1415 		 * Make sure that any level 0 "default" line is last
1416 		 * (if one exists).
1417 		 */
1418 		set_last_default(ms, mset[j].me, mset[j].count);
1419 
1420 		/* coalesce per file arrays into a single one */
1421 		if (coalesce_entries(ms, mset[j].me, mset[j].count,
1422 		    &map->magic[j], &map->nmagic[j]) == -1) {
1423 			errs++;
1424 			goto out;
1425 		}
1426 	}
1427 
1428 out:
1429 	for (j = 0; j < MAGIC_SETS; j++)
1430 		magic_entry_free(mset[j].me, mset[j].count);
1431 
1432 	if (errs) {
1433 		apprentice_unmap(map);
1434 		return NULL;
1435 	}
1436 	return map;
1437 }
1438 
1439 /*
1440  * extend the sign bit if the comparison is to be signed
1441  */
1442 protected uint64_t
1443 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1444 {
1445 	if (!(m->flag & UNSIGNED)) {
1446 		switch(m->type) {
1447 		/*
1448 		 * Do not remove the casts below.  They are
1449 		 * vital.  When later compared with the data,
1450 		 * the sign extension must have happened.
1451 		 */
1452 		case FILE_BYTE:
1453 			v = (signed char) v;
1454 			break;
1455 		case FILE_SHORT:
1456 		case FILE_BESHORT:
1457 		case FILE_LESHORT:
1458 			v = (short) v;
1459 			break;
1460 		case FILE_DATE:
1461 		case FILE_BEDATE:
1462 		case FILE_LEDATE:
1463 		case FILE_MEDATE:
1464 		case FILE_LDATE:
1465 		case FILE_BELDATE:
1466 		case FILE_LELDATE:
1467 		case FILE_MELDATE:
1468 		case FILE_LONG:
1469 		case FILE_BELONG:
1470 		case FILE_LELONG:
1471 		case FILE_MELONG:
1472 		case FILE_FLOAT:
1473 		case FILE_BEFLOAT:
1474 		case FILE_LEFLOAT:
1475 			v = (int32_t) v;
1476 			break;
1477 		case FILE_QUAD:
1478 		case FILE_BEQUAD:
1479 		case FILE_LEQUAD:
1480 		case FILE_QDATE:
1481 		case FILE_QLDATE:
1482 		case FILE_QWDATE:
1483 		case FILE_BEQDATE:
1484 		case FILE_BEQLDATE:
1485 		case FILE_BEQWDATE:
1486 		case FILE_LEQDATE:
1487 		case FILE_LEQLDATE:
1488 		case FILE_LEQWDATE:
1489 		case FILE_DOUBLE:
1490 		case FILE_BEDOUBLE:
1491 		case FILE_LEDOUBLE:
1492 			v = (int64_t) v;
1493 			break;
1494 		case FILE_STRING:
1495 		case FILE_PSTRING:
1496 		case FILE_BESTRING16:
1497 		case FILE_LESTRING16:
1498 		case FILE_REGEX:
1499 		case FILE_SEARCH:
1500 		case FILE_DEFAULT:
1501 		case FILE_INDIRECT:
1502 		case FILE_NAME:
1503 		case FILE_USE:
1504 		case FILE_CLEAR:
1505 		case FILE_DER:
1506 			break;
1507 		default:
1508 			if (ms->flags & MAGIC_CHECK)
1509 			    file_magwarn(ms, "cannot happen: m->type=%d\n",
1510 				    m->type);
1511 			return ~0U;
1512 		}
1513 	}
1514 	return v;
1515 }
1516 
1517 private int
1518 string_modifier_check(struct magic_set *ms, struct magic *m)
1519 {
1520 	if ((ms->flags & MAGIC_CHECK) == 0)
1521 		return 0;
1522 
1523 	if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1524 	    (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1525 		file_magwarn(ms,
1526 		    "'/BHhLl' modifiers are only allowed for pascal strings\n");
1527 		return -1;
1528 	}
1529 	switch (m->type) {
1530 	case FILE_BESTRING16:
1531 	case FILE_LESTRING16:
1532 		if (m->str_flags != 0) {
1533 			file_magwarn(ms,
1534 			    "no modifiers allowed for 16-bit strings\n");
1535 			return -1;
1536 		}
1537 		break;
1538 	case FILE_STRING:
1539 	case FILE_PSTRING:
1540 		if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1541 			file_magwarn(ms,
1542 			    "'/%c' only allowed on regex and search\n",
1543 			    CHAR_REGEX_OFFSET_START);
1544 			return -1;
1545 		}
1546 		break;
1547 	case FILE_SEARCH:
1548 		if (m->str_range == 0) {
1549 			file_magwarn(ms,
1550 			    "missing range; defaulting to %d\n",
1551                             STRING_DEFAULT_RANGE);
1552 			m->str_range = STRING_DEFAULT_RANGE;
1553 			return -1;
1554 		}
1555 		break;
1556 	case FILE_REGEX:
1557 		if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1558 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1559 			    CHAR_COMPACT_WHITESPACE);
1560 			return -1;
1561 		}
1562 		if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1563 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1564 			    CHAR_COMPACT_OPTIONAL_WHITESPACE);
1565 			return -1;
1566 		}
1567 		break;
1568 	default:
1569 		file_magwarn(ms, "coding error: m->type=%d\n",
1570 		    m->type);
1571 		return -1;
1572 	}
1573 	return 0;
1574 }
1575 
1576 private int
1577 get_op(char c)
1578 {
1579 	switch (c) {
1580 	case '&':
1581 		return FILE_OPAND;
1582 	case '|':
1583 		return FILE_OPOR;
1584 	case '^':
1585 		return FILE_OPXOR;
1586 	case '+':
1587 		return FILE_OPADD;
1588 	case '-':
1589 		return FILE_OPMINUS;
1590 	case '*':
1591 		return FILE_OPMULTIPLY;
1592 	case '/':
1593 		return FILE_OPDIVIDE;
1594 	case '%':
1595 		return FILE_OPMODULO;
1596 	default:
1597 		return -1;
1598 	}
1599 }
1600 
1601 #ifdef ENABLE_CONDITIONALS
1602 private int
1603 get_cond(const char *l, const char **t)
1604 {
1605 	static const struct cond_tbl_s {
1606 		char name[8];
1607 		size_t len;
1608 		int cond;
1609 	} cond_tbl[] = {
1610 		{ "if",		2,	COND_IF },
1611 		{ "elif",	4,	COND_ELIF },
1612 		{ "else",	4,	COND_ELSE },
1613 		{ "",		0,	COND_NONE },
1614 	};
1615 	const struct cond_tbl_s *p;
1616 
1617 	for (p = cond_tbl; p->len; p++) {
1618 		if (strncmp(l, p->name, p->len) == 0 &&
1619 		    isspace((unsigned char)l[p->len])) {
1620 			if (t)
1621 				*t = l + p->len;
1622 			break;
1623 		}
1624 	}
1625 	return p->cond;
1626 }
1627 
1628 private int
1629 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1630 {
1631 	int last_cond;
1632 	last_cond = ms->c.li[cont_level].last_cond;
1633 
1634 	switch (cond) {
1635 	case COND_IF:
1636 		if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1637 			if (ms->flags & MAGIC_CHECK)
1638 				file_magwarn(ms, "syntax error: `if'");
1639 			return -1;
1640 		}
1641 		last_cond = COND_IF;
1642 		break;
1643 
1644 	case COND_ELIF:
1645 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1646 			if (ms->flags & MAGIC_CHECK)
1647 				file_magwarn(ms, "syntax error: `elif'");
1648 			return -1;
1649 		}
1650 		last_cond = COND_ELIF;
1651 		break;
1652 
1653 	case COND_ELSE:
1654 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1655 			if (ms->flags & MAGIC_CHECK)
1656 				file_magwarn(ms, "syntax error: `else'");
1657 			return -1;
1658 		}
1659 		last_cond = COND_NONE;
1660 		break;
1661 
1662 	case COND_NONE:
1663 		last_cond = COND_NONE;
1664 		break;
1665 	}
1666 
1667 	ms->c.li[cont_level].last_cond = last_cond;
1668 	return 0;
1669 }
1670 #endif /* ENABLE_CONDITIONALS */
1671 
1672 private int
1673 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1674 {
1675 	const char *l = *lp;
1676 
1677 	while (!isspace((unsigned char)*++l))
1678 		switch (*l) {
1679 		case CHAR_INDIRECT_RELATIVE:
1680 			m->str_flags |= INDIRECT_RELATIVE;
1681 			break;
1682 		default:
1683 			if (ms->flags & MAGIC_CHECK)
1684 				file_magwarn(ms, "indirect modifier `%c' "
1685 					"invalid", *l);
1686 			*lp = l;
1687 			return -1;
1688 		}
1689 	*lp = l;
1690 	return 0;
1691 }
1692 
1693 private void
1694 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1695     int op)
1696 {
1697 	const char *l = *lp;
1698 	char *t;
1699 	uint64_t val;
1700 
1701 	++l;
1702 	m->mask_op |= op;
1703 	val = (uint64_t)strtoull(l, &t, 0);
1704 	l = t;
1705 	m->num_mask = file_signextend(ms, m, val);
1706 	eatsize(&l);
1707 	*lp = l;
1708 }
1709 
1710 private int
1711 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1712 {
1713 	const char *l = *lp;
1714 	char *t;
1715 	int have_range = 0;
1716 
1717 	while (!isspace((unsigned char)*++l)) {
1718 		switch (*l) {
1719 		case '0':  case '1':  case '2':
1720 		case '3':  case '4':  case '5':
1721 		case '6':  case '7':  case '8':
1722 		case '9':
1723 			if (have_range && (ms->flags & MAGIC_CHECK))
1724 				file_magwarn(ms, "multiple ranges");
1725 			have_range = 1;
1726 			m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1727 			if (m->str_range == 0)
1728 				file_magwarn(ms, "zero range");
1729 			l = t - 1;
1730 			break;
1731 		case CHAR_COMPACT_WHITESPACE:
1732 			m->str_flags |= STRING_COMPACT_WHITESPACE;
1733 			break;
1734 		case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1735 			m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1736 			break;
1737 		case CHAR_IGNORE_LOWERCASE:
1738 			m->str_flags |= STRING_IGNORE_LOWERCASE;
1739 			break;
1740 		case CHAR_IGNORE_UPPERCASE:
1741 			m->str_flags |= STRING_IGNORE_UPPERCASE;
1742 			break;
1743 		case CHAR_REGEX_OFFSET_START:
1744 			m->str_flags |= REGEX_OFFSET_START;
1745 			break;
1746 		case CHAR_BINTEST:
1747 			m->str_flags |= STRING_BINTEST;
1748 			break;
1749 		case CHAR_TEXTTEST:
1750 			m->str_flags |= STRING_TEXTTEST;
1751 			break;
1752 		case CHAR_TRIM:
1753 			m->str_flags |= STRING_TRIM;
1754 			break;
1755 		case CHAR_PSTRING_1_LE:
1756 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1757 			if (m->type != FILE_PSTRING)
1758 				goto bad;
1759 			SET_LENGTH(PSTRING_1_LE);
1760 			break;
1761 		case CHAR_PSTRING_2_BE:
1762 			if (m->type != FILE_PSTRING)
1763 				goto bad;
1764 			SET_LENGTH(PSTRING_2_BE);
1765 			break;
1766 		case CHAR_PSTRING_2_LE:
1767 			if (m->type != FILE_PSTRING)
1768 				goto bad;
1769 			SET_LENGTH(PSTRING_2_LE);
1770 			break;
1771 		case CHAR_PSTRING_4_BE:
1772 			if (m->type != FILE_PSTRING)
1773 				goto bad;
1774 			SET_LENGTH(PSTRING_4_BE);
1775 			break;
1776 		case CHAR_PSTRING_4_LE:
1777 			switch (m->type) {
1778 			case FILE_PSTRING:
1779 			case FILE_REGEX:
1780 				break;
1781 			default:
1782 				goto bad;
1783 			}
1784 			SET_LENGTH(PSTRING_4_LE);
1785 			break;
1786 		case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1787 			if (m->type != FILE_PSTRING)
1788 				goto bad;
1789 			m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1790 			break;
1791 		default:
1792 		bad:
1793 			if (ms->flags & MAGIC_CHECK)
1794 				file_magwarn(ms, "string modifier `%c' "
1795 					"invalid", *l);
1796 			goto out;
1797 		}
1798 		/* allow multiple '/' for readability */
1799 		if (l[1] == '/' && !isspace((unsigned char)l[2]))
1800 			l++;
1801 	}
1802 	if (string_modifier_check(ms, m) == -1)
1803 		goto out;
1804 	*lp = l;
1805 	return 0;
1806 out:
1807 	*lp = l;
1808 	return -1;
1809 }
1810 
1811 /*
1812  * parse one line from magic file, put into magic[index++] if valid
1813  */
1814 private int
1815 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1816     size_t lineno, int action)
1817 {
1818 #ifdef ENABLE_CONDITIONALS
1819 	static uint32_t last_cont_level = 0;
1820 #endif
1821 	size_t i;
1822 	struct magic *m;
1823 	const char *l = line;
1824 	char *t;
1825 	int op;
1826 	uint32_t cont_level;
1827 	int32_t diff;
1828 
1829 	cont_level = 0;
1830 
1831 	/*
1832 	 * Parse the offset.
1833 	 */
1834 	while (*l == '>') {
1835 		++l;		/* step over */
1836 		cont_level++;
1837 	}
1838 #ifdef ENABLE_CONDITIONALS
1839 	if (cont_level == 0 || cont_level > last_cont_level)
1840 		if (file_check_mem(ms, cont_level) == -1)
1841 			return -1;
1842 	last_cont_level = cont_level;
1843 #endif
1844 	if (cont_level != 0) {
1845 		if (me->mp == NULL) {
1846 			file_magerror(ms, "No current entry for continuation");
1847 			return -1;
1848 		}
1849 		if (me->cont_count == 0) {
1850 			file_magerror(ms, "Continuations present with 0 count");
1851 			return -1;
1852 		}
1853 		m = &me->mp[me->cont_count - 1];
1854 		diff = (int32_t)cont_level - (int32_t)m->cont_level;
1855 		if (diff > 1)
1856 			file_magwarn(ms, "New continuation level %u is more "
1857 			    "than one larger than current level %u", cont_level,
1858 			    m->cont_level);
1859 		if (me->cont_count == me->max_count) {
1860 			struct magic *nm;
1861 			size_t cnt = me->max_count + ALLOC_CHUNK;
1862 			if ((nm = CAST(struct magic *, realloc(me->mp,
1863 			    sizeof(*nm) * cnt))) == NULL) {
1864 				file_oomem(ms, sizeof(*nm) * cnt);
1865 				return -1;
1866 			}
1867 			me->mp = m = nm;
1868 			me->max_count = CAST(uint32_t, cnt);
1869 		}
1870 		m = &me->mp[me->cont_count++];
1871 		(void)memset(m, 0, sizeof(*m));
1872 		m->cont_level = cont_level;
1873 	} else {
1874 		static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1875 		if (me->mp != NULL)
1876 			return 1;
1877 		if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1878 			file_oomem(ms, len);
1879 			return -1;
1880 		}
1881 		me->mp = m;
1882 		me->max_count = ALLOC_CHUNK;
1883 		(void)memset(m, 0, sizeof(*m));
1884 		m->factor_op = FILE_FACTOR_OP_NONE;
1885 		m->cont_level = 0;
1886 		me->cont_count = 1;
1887 	}
1888 	m->lineno = CAST(uint32_t, lineno);
1889 
1890 	if (*l == '&') {  /* m->cont_level == 0 checked below. */
1891                 ++l;            /* step over */
1892                 m->flag |= OFFADD;
1893         }
1894 	if (*l == '(') {
1895 		++l;		/* step over */
1896 		m->flag |= INDIR;
1897 		if (m->flag & OFFADD)
1898 			m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1899 
1900 		if (*l == '&') {  /* m->cont_level == 0 checked below */
1901 			++l;            /* step over */
1902 			m->flag |= OFFADD;
1903 		}
1904 	}
1905 	/* Indirect offsets are not valid at level 0. */
1906 	if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1907 		if (ms->flags & MAGIC_CHECK)
1908 			file_magwarn(ms, "relative offset at level 0");
1909 		return -1;
1910 	}
1911 
1912 	/* get offset, then skip over it */
1913 	m->offset = (int32_t)strtol(l, &t, 0);
1914         if (l == t) {
1915 		if (ms->flags & MAGIC_CHECK)
1916 			file_magwarn(ms, "offset `%s' invalid", l);
1917 		return -1;
1918 	}
1919 #if 0
1920         if (m->offset < 0 && cont_level != 0 &&
1921 	    (m->flag & (OFFADD | INDIROFFADD)) == 0) {
1922 		if (ms->flags & MAGIC_CHECK) {
1923 			file_magwarn(ms,
1924 			    "negative direct offset `%s' at level %u",
1925 			    l, cont_level);
1926 		}
1927 		return -1;
1928 	}
1929 #endif
1930         l = t;
1931 
1932 	if (m->flag & INDIR) {
1933 		m->in_type = FILE_LONG;
1934 		m->in_offset = 0;
1935 		m->in_op = 0;
1936 		/*
1937 		 * read [.,lbs][+-]nnnnn)
1938 		 */
1939 		if (*l == '.' || *l == ',') {
1940 			if (*l == ',')
1941 				m->in_op |= FILE_OPSIGNED;
1942 			l++;
1943 			switch (*l) {
1944 			case 'l':
1945 				m->in_type = FILE_LELONG;
1946 				break;
1947 			case 'L':
1948 				m->in_type = FILE_BELONG;
1949 				break;
1950 			case 'm':
1951 				m->in_type = FILE_MELONG;
1952 				break;
1953 			case 'h':
1954 			case 's':
1955 				m->in_type = FILE_LESHORT;
1956 				break;
1957 			case 'H':
1958 			case 'S':
1959 				m->in_type = FILE_BESHORT;
1960 				break;
1961 			case 'c':
1962 			case 'b':
1963 			case 'C':
1964 			case 'B':
1965 				m->in_type = FILE_BYTE;
1966 				break;
1967 			case 'e':
1968 			case 'f':
1969 			case 'g':
1970 				m->in_type = FILE_LEDOUBLE;
1971 				break;
1972 			case 'E':
1973 			case 'F':
1974 			case 'G':
1975 				m->in_type = FILE_BEDOUBLE;
1976 				break;
1977 			case 'i':
1978 				m->in_type = FILE_LEID3;
1979 				break;
1980 			case 'I':
1981 				m->in_type = FILE_BEID3;
1982 				break;
1983 			case 'q':
1984 				m->in_type = FILE_LEQUAD;
1985 				break;
1986 			case 'Q':
1987 				m->in_type = FILE_BEQUAD;
1988 				break;
1989 			default:
1990 				if (ms->flags & MAGIC_CHECK)
1991 					file_magwarn(ms,
1992 					    "indirect offset type `%c' invalid",
1993 					    *l);
1994 				return -1;
1995 			}
1996 			l++;
1997 		}
1998 
1999 		if (*l == '~') {
2000 			m->in_op |= FILE_OPINVERSE;
2001 			l++;
2002 		}
2003 		if ((op = get_op(*l)) != -1) {
2004 			m->in_op |= op;
2005 			l++;
2006 		}
2007 		if (*l == '(') {
2008 			m->in_op |= FILE_OPINDIRECT;
2009 			l++;
2010 		}
2011 		if (isdigit((unsigned char)*l) || *l == '-') {
2012 			m->in_offset = (int32_t)strtol(l, &t, 0);
2013 			if (l == t) {
2014 				if (ms->flags & MAGIC_CHECK)
2015 					file_magwarn(ms,
2016 					    "in_offset `%s' invalid", l);
2017 				return -1;
2018 			}
2019 			l = t;
2020 		}
2021 		if (*l++ != ')' ||
2022 		    ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
2023 			if (ms->flags & MAGIC_CHECK)
2024 				file_magwarn(ms,
2025 				    "missing ')' in indirect offset");
2026 			return -1;
2027 		}
2028 	}
2029 	EATAB;
2030 
2031 #ifdef ENABLE_CONDITIONALS
2032 	m->cond = get_cond(l, &l);
2033 	if (check_cond(ms, m->cond, cont_level) == -1)
2034 		return -1;
2035 
2036 	EATAB;
2037 #endif
2038 
2039 	/*
2040 	 * Parse the type.
2041 	 */
2042 	if (*l == 'u') {
2043 		/*
2044 		 * Try it as a keyword type prefixed by "u"; match what
2045 		 * follows the "u".  If that fails, try it as an SUS
2046 		 * integer type.
2047 		 */
2048 		m->type = get_type(type_tbl, l + 1, &l);
2049 		if (m->type == FILE_INVALID) {
2050 			/*
2051 			 * Not a keyword type; parse it as an SUS type,
2052 			 * 'u' possibly followed by a number or C/S/L.
2053 			 */
2054 			m->type = get_standard_integer_type(l, &l);
2055 		}
2056 		/* It's unsigned. */
2057 		if (m->type != FILE_INVALID)
2058 			m->flag |= UNSIGNED;
2059 	} else {
2060 		/*
2061 		 * Try it as a keyword type.  If that fails, try it as
2062 		 * an SUS integer type if it begins with "d" or as an
2063 		 * SUS string type if it begins with "s".  In any case,
2064 		 * it's not unsigned.
2065 		 */
2066 		m->type = get_type(type_tbl, l, &l);
2067 		if (m->type == FILE_INVALID) {
2068 			/*
2069 			 * Not a keyword type; parse it as an SUS type,
2070 			 * either 'd' possibly followed by a number or
2071 			 * C/S/L, or just 's'.
2072 			 */
2073 			if (*l == 'd')
2074 				m->type = get_standard_integer_type(l, &l);
2075 			else if (*l == 's' && !isalpha((unsigned char)l[1])) {
2076 				m->type = FILE_STRING;
2077 				++l;
2078 			}
2079 		}
2080 	}
2081 
2082 	if (m->type == FILE_INVALID) {
2083 		/* Not found - try it as a special keyword. */
2084 		m->type = get_type(special_tbl, l, &l);
2085 	}
2086 
2087 	if (m->type == FILE_INVALID) {
2088 		if (ms->flags & MAGIC_CHECK)
2089 			file_magwarn(ms, "type `%s' invalid", l);
2090 		return -1;
2091 	}
2092 
2093 	/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2094 	/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2095 
2096 	m->mask_op = 0;
2097 	if (*l == '~') {
2098 		if (!IS_STRING(m->type))
2099 			m->mask_op |= FILE_OPINVERSE;
2100 		else if (ms->flags & MAGIC_CHECK)
2101 			file_magwarn(ms, "'~' invalid for string types");
2102 		++l;
2103 	}
2104 	m->str_range = 0;
2105 	m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2106 	if ((op = get_op(*l)) != -1) {
2107 		if (IS_STRING(m->type)) {
2108 			int r;
2109 
2110 			if (op != FILE_OPDIVIDE) {
2111 				if (ms->flags & MAGIC_CHECK)
2112 					file_magwarn(ms,
2113 					    "invalid string/indirect op: "
2114 					    "`%c'", *t);
2115 				return -1;
2116 			}
2117 
2118 			if (m->type == FILE_INDIRECT)
2119 				r = parse_indirect_modifier(ms, m, &l);
2120 			else
2121 				r = parse_string_modifier(ms, m, &l);
2122 			if (r == -1)
2123 				return -1;
2124 		} else
2125 			parse_op_modifier(ms, m, &l, op);
2126 	}
2127 
2128 	/*
2129 	 * We used to set mask to all 1's here, instead let's just not do
2130 	 * anything if mask = 0 (unless you have a better idea)
2131 	 */
2132 	EATAB;
2133 
2134 	switch (*l) {
2135 	case '>':
2136 	case '<':
2137   		m->reln = *l;
2138   		++l;
2139 		if (*l == '=') {
2140 			if (ms->flags & MAGIC_CHECK) {
2141 				file_magwarn(ms, "%c= not supported",
2142 				    m->reln);
2143 				return -1;
2144 			}
2145 		   ++l;
2146 		}
2147 		break;
2148 	/* Old-style anding: "0 byte &0x80 dynamically linked" */
2149 	case '&':
2150 	case '^':
2151 	case '=':
2152   		m->reln = *l;
2153   		++l;
2154 		if (*l == '=') {
2155 		   /* HP compat: ignore &= etc. */
2156 		   ++l;
2157 		}
2158 		break;
2159 	case '!':
2160 		m->reln = *l;
2161 		++l;
2162 		break;
2163 	default:
2164   		m->reln = '=';	/* the default relation */
2165 		if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2166 		    isspace((unsigned char)l[1])) || !l[1])) {
2167 			m->reln = *l;
2168 			++l;
2169 		}
2170 		break;
2171 	}
2172 	/*
2173 	 * Grab the value part, except for an 'x' reln.
2174 	 */
2175 	if (m->reln != 'x' && getvalue(ms, m, &l, action))
2176 		return -1;
2177 
2178 	/*
2179 	 * TODO finish this macro and start using it!
2180 	 * #define offsetcheck {if (offset > ms->bytes_max -1)
2181 	 *	magwarn("offset too big"); }
2182 	 */
2183 
2184 	/*
2185 	 * Now get last part - the description
2186 	 */
2187 	EATAB;
2188 	if (l[0] == '\b') {
2189 		++l;
2190 		m->flag |= NOSPACE;
2191 	} else if ((l[0] == '\\') && (l[1] == 'b')) {
2192 		++l;
2193 		++l;
2194 		m->flag |= NOSPACE;
2195 	}
2196 	for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2197 		continue;
2198 	if (i == sizeof(m->desc)) {
2199 		m->desc[sizeof(m->desc) - 1] = '\0';
2200 		if (ms->flags & MAGIC_CHECK)
2201 			file_magwarn(ms, "description `%s' truncated", m->desc);
2202 	}
2203 
2204         /*
2205 	 * We only do this check while compiling, or if any of the magic
2206 	 * files were not compiled.
2207          */
2208         if (ms->flags & MAGIC_CHECK) {
2209 		if (check_format(ms, m) == -1)
2210 			return -1;
2211 	}
2212 #ifndef COMPILE_ONLY
2213 	if (action == FILE_CHECK) {
2214 		file_mdump(m);
2215 	}
2216 #endif
2217 	m->mimetype[0] = '\0';		/* initialise MIME type to none */
2218 	return 0;
2219 }
2220 
2221 /*
2222  * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2223  * if valid
2224  */
2225 private int
2226 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2227 {
2228 	const char *l = line;
2229 	char *el;
2230 	unsigned long factor;
2231 	struct magic *m = &me->mp[0];
2232 
2233 	if (m->factor_op != FILE_FACTOR_OP_NONE) {
2234 		file_magwarn(ms,
2235 		    "Current entry already has a strength type: %c %d",
2236 		    m->factor_op, m->factor);
2237 		return -1;
2238 	}
2239 	if (m->type == FILE_NAME) {
2240 		file_magwarn(ms, "%s: Strength setting is not supported in "
2241 		    "\"name\" magic entries", m->value.s);
2242 		return -1;
2243 	}
2244 	EATAB;
2245 	switch (*l) {
2246 	case FILE_FACTOR_OP_NONE:
2247 	case FILE_FACTOR_OP_PLUS:
2248 	case FILE_FACTOR_OP_MINUS:
2249 	case FILE_FACTOR_OP_TIMES:
2250 	case FILE_FACTOR_OP_DIV:
2251 		m->factor_op = *l++;
2252 		break;
2253 	default:
2254 		file_magwarn(ms, "Unknown factor op `%c'", *l);
2255 		return -1;
2256 	}
2257 	EATAB;
2258 	factor = strtoul(l, &el, 0);
2259 	if (factor > 255) {
2260 		file_magwarn(ms, "Too large factor `%lu'", factor);
2261 		goto out;
2262 	}
2263 	if (*el && !isspace((unsigned char)*el)) {
2264 		file_magwarn(ms, "Bad factor `%s'", l);
2265 		goto out;
2266 	}
2267 	m->factor = (uint8_t)factor;
2268 	if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2269 		file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2270 		    m->factor_op, m->factor);
2271 		goto out;
2272 	}
2273 	return 0;
2274 out:
2275 	m->factor_op = FILE_FACTOR_OP_NONE;
2276 	m->factor = 0;
2277 	return -1;
2278 }
2279 
2280 private int
2281 goodchar(unsigned char x, const char *extra)
2282 {
2283 	return (isascii(x) && isalnum(x)) || strchr(extra, x);
2284 }
2285 
2286 private int
2287 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2288     off_t off, size_t len, const char *name, const char *extra, int nt)
2289 {
2290 	size_t i;
2291 	const char *l = line;
2292 	struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2293 	char *buf = CAST(char *, CAST(void *, m)) + off;
2294 
2295 	if (buf[0] != '\0') {
2296 		len = nt ? strlen(buf) : len;
2297 		file_magwarn(ms, "Current entry already has a %s type "
2298 		    "`%.*s', new type `%s'", name, (int)len, buf, l);
2299 		return -1;
2300 	}
2301 
2302 	if (*m->desc == '\0') {
2303 		file_magwarn(ms, "Current entry does not yet have a "
2304 		    "description for adding a %s type", name);
2305 		return -1;
2306 	}
2307 
2308 	EATAB;
2309 	for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2310 		continue;
2311 
2312 	if (i == len && *l) {
2313 		if (nt)
2314 			buf[len - 1] = '\0';
2315 		if (ms->flags & MAGIC_CHECK)
2316 			file_magwarn(ms, "%s type `%s' truncated %"
2317 			    SIZE_T_FORMAT "u", name, line, i);
2318 	} else {
2319 		if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2320 			file_magwarn(ms, "%s type `%s' has bad char '%c'",
2321 			    name, line, *l);
2322 		if (nt)
2323 			buf[i] = '\0';
2324 	}
2325 
2326 	if (i > 0)
2327 		return 0;
2328 
2329 	file_magerror(ms, "Bad magic entry '%s'", line);
2330 	return -1;
2331 }
2332 
2333 /*
2334  * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2335  * magic[index - 1]
2336  */
2337 private int
2338 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2339 {
2340 	struct magic *m = &me->mp[0];
2341 
2342 	return parse_extra(ms, me, line,
2343 	    CAST(off_t, offsetof(struct magic, apple)),
2344 	    sizeof(m->apple), "APPLE", "!+-./?", 0);
2345 }
2346 
2347 /*
2348  * Parse a comma-separated list of extensions
2349  */
2350 private int
2351 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2352 {
2353 	struct magic *m = &me->mp[0];
2354 
2355 	return parse_extra(ms, me, line,
2356 	    CAST(off_t, offsetof(struct magic, ext)),
2357 	    sizeof(m->ext), "EXTENSION", ",!+-/@?_$", 0);
2358 }
2359 
2360 /*
2361  * parse a MIME annotation line from magic file, put into magic[index - 1]
2362  * if valid
2363  */
2364 private int
2365 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2366 {
2367 	struct magic *m = &me->mp[0];
2368 
2369 	return parse_extra(ms, me, line,
2370 	    CAST(off_t, offsetof(struct magic, mimetype)),
2371 	    sizeof(m->mimetype), "MIME", "+-/.$?:{}", 1);
2372 }
2373 
2374 private int
2375 check_format_type(const char *ptr, int type, const char **estr)
2376 {
2377 	int quad = 0, h;
2378 	size_t len, cnt;
2379 	if (*ptr == '\0') {
2380 		/* Missing format string; bad */
2381 		*estr = "missing format spec";
2382 		return -1;
2383 	}
2384 
2385 	switch (file_formats[type]) {
2386 	case FILE_FMT_QUAD:
2387 		quad = 1;
2388 		/*FALLTHROUGH*/
2389 	case FILE_FMT_NUM:
2390 		if (quad == 0) {
2391 			switch (type) {
2392 			case FILE_BYTE:
2393 				h = 2;
2394 				break;
2395 			case FILE_SHORT:
2396 			case FILE_BESHORT:
2397 			case FILE_LESHORT:
2398 				h = 1;
2399 				break;
2400 			case FILE_LONG:
2401 			case FILE_BELONG:
2402 			case FILE_LELONG:
2403 			case FILE_MELONG:
2404 			case FILE_LEID3:
2405 			case FILE_BEID3:
2406 			case FILE_INDIRECT:
2407 				h = 0;
2408 				break;
2409 			default:
2410 				abort();
2411 			}
2412 		} else
2413 			h = 0;
2414 		if (*ptr == '-')
2415 			ptr++;
2416 		if (*ptr == '.')
2417 			ptr++;
2418 		if (*ptr == '#')
2419 			ptr++;
2420 #define CHECKLEN() do { \
2421 	for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
2422 		len = len * 10 + (*ptr - '0'); \
2423 	if (cnt > 5 || len > 1024) \
2424 		goto toolong; \
2425 } while (/*CONSTCOND*/0)
2426 
2427 		CHECKLEN();
2428 		if (*ptr == '.')
2429 			ptr++;
2430 		CHECKLEN();
2431 		if (quad) {
2432 			if (*ptr++ != 'l')
2433 				goto invalid;
2434 			if (*ptr++ != 'l')
2435 				goto invalid;
2436 		}
2437 
2438 		switch (*ptr++) {
2439 #ifdef STRICT_FORMAT 	/* "long" formats are int formats for us */
2440 		/* so don't accept the 'l' modifier */
2441 		case 'l':
2442 			switch (*ptr++) {
2443 			case 'i':
2444 			case 'd':
2445 			case 'u':
2446 			case 'o':
2447 			case 'x':
2448 			case 'X':
2449 				if (h == 0)
2450 					return 0;
2451 				/*FALLTHROUGH*/
2452 			default:
2453 				goto invalid;
2454 			}
2455 
2456 		/*
2457 		 * Don't accept h and hh modifiers. They make writing
2458 		 * magic entries more complicated, for very little benefit
2459 		 */
2460 		case 'h':
2461 			if (h-- <= 0)
2462 				goto invalid;
2463 			switch (*ptr++) {
2464 			case 'h':
2465 				if (h-- <= 0)
2466 					goto invalid;
2467 				switch (*ptr++) {
2468 				case 'i':
2469 				case 'd':
2470 				case 'u':
2471 				case 'o':
2472 				case 'x':
2473 				case 'X':
2474 					return 0;
2475 				default:
2476 					goto invalid;
2477 				}
2478 			case 'i':
2479 			case 'd':
2480 			case 'u':
2481 			case 'o':
2482 			case 'x':
2483 			case 'X':
2484 				if (h == 0)
2485 					return 0;
2486 				/*FALLTHROUGH*/
2487 			default:
2488 				goto invalid;
2489 			}
2490 #endif
2491 		case 'c':
2492 			if (h == 2)
2493 				return 0;
2494 			goto invalid;
2495 		case 'i':
2496 		case 'd':
2497 		case 'u':
2498 		case 'o':
2499 		case 'x':
2500 		case 'X':
2501 #ifdef STRICT_FORMAT
2502 			if (h == 0)
2503 				return 0;
2504 			/*FALLTHROUGH*/
2505 #else
2506 			return 0;
2507 #endif
2508 		default:
2509 			goto invalid;
2510 		}
2511 
2512 	case FILE_FMT_FLOAT:
2513 	case FILE_FMT_DOUBLE:
2514 		if (*ptr == '-')
2515 			ptr++;
2516 		if (*ptr == '.')
2517 			ptr++;
2518 		CHECKLEN();
2519 		if (*ptr == '.')
2520 			ptr++;
2521 		CHECKLEN();
2522 		switch (*ptr++) {
2523 		case 'e':
2524 		case 'E':
2525 		case 'f':
2526 		case 'F':
2527 		case 'g':
2528 		case 'G':
2529 			return 0;
2530 
2531 		default:
2532 			goto invalid;
2533 		}
2534 
2535 
2536 	case FILE_FMT_STR:
2537 		if (*ptr == '-')
2538 			ptr++;
2539 		while (isdigit((unsigned char )*ptr))
2540 			ptr++;
2541 		if (*ptr == '.') {
2542 			ptr++;
2543 			while (isdigit((unsigned char )*ptr))
2544 				ptr++;
2545 		}
2546 
2547 		switch (*ptr++) {
2548 		case 's':
2549 			return 0;
2550 		default:
2551 			goto invalid;
2552 		}
2553 
2554 	default:
2555 		/* internal error */
2556 		abort();
2557 	}
2558 invalid:
2559 	*estr = "not valid";
2560 toolong:
2561 	*estr = "too long";
2562 	return -1;
2563 }
2564 
2565 /*
2566  * Check that the optional printf format in description matches
2567  * the type of the magic.
2568  */
2569 private int
2570 check_format(struct magic_set *ms, struct magic *m)
2571 {
2572 	char *ptr;
2573 	const char *estr;
2574 
2575 	for (ptr = m->desc; *ptr; ptr++)
2576 		if (*ptr == '%')
2577 			break;
2578 	if (*ptr == '\0') {
2579 		/* No format string; ok */
2580 		return 1;
2581 	}
2582 
2583 	assert(file_nformats == file_nnames);
2584 
2585 	if (m->type >= file_nformats) {
2586 		file_magwarn(ms, "Internal error inconsistency between "
2587 		    "m->type and format strings");
2588 		return -1;
2589 	}
2590 	if (file_formats[m->type] == FILE_FMT_NONE) {
2591 		file_magwarn(ms, "No format string for `%s' with description "
2592 		    "`%s'", m->desc, file_names[m->type]);
2593 		return -1;
2594 	}
2595 
2596 	ptr++;
2597 	if (check_format_type(ptr, m->type, &estr) == -1) {
2598 		/*
2599 		 * TODO: this error message is unhelpful if the format
2600 		 * string is not one character long
2601 		 */
2602 		file_magwarn(ms, "Printf format is %s for type "
2603 		    "`%s' in description `%s'", estr,
2604 		    file_names[m->type], m->desc);
2605 		return -1;
2606 	}
2607 
2608 	for (; *ptr; ptr++) {
2609 		if (*ptr == '%') {
2610 			file_magwarn(ms,
2611 			    "Too many format strings (should have at most one) "
2612 			    "for `%s' with description `%s'",
2613 			    file_names[m->type], m->desc);
2614 			return -1;
2615 		}
2616 	}
2617 	return 0;
2618 }
2619 
2620 /*
2621  * Read a numeric value from a pointer, into the value union of a magic
2622  * pointer, according to the magic type.  Update the string pointer to point
2623  * just after the number read.  Return 0 for success, non-zero for failure.
2624  */
2625 private int
2626 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2627 {
2628 	char *ep;
2629 	uint64_t ull;
2630 
2631 	switch (m->type) {
2632 	case FILE_BESTRING16:
2633 	case FILE_LESTRING16:
2634 	case FILE_STRING:
2635 	case FILE_PSTRING:
2636 	case FILE_REGEX:
2637 	case FILE_SEARCH:
2638 	case FILE_NAME:
2639 	case FILE_USE:
2640 	case FILE_DER:
2641 		*p = getstr(ms, m, *p, action == FILE_COMPILE);
2642 		if (*p == NULL) {
2643 			if (ms->flags & MAGIC_CHECK)
2644 				file_magwarn(ms, "cannot get string from `%s'",
2645 				    m->value.s);
2646 			return -1;
2647 		}
2648 		if (m->type == FILE_REGEX) {
2649 			file_regex_t rx;
2650 			int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2651 			if (rc) {
2652 				if (ms->flags & MAGIC_CHECK)
2653 					file_regerror(&rx, rc, ms);
2654 			}
2655 			file_regfree(&rx);
2656 			return rc ? -1 : 0;
2657 		}
2658 		return 0;
2659 	default:
2660 		if (m->reln == 'x')
2661 			return 0;
2662 		break;
2663 	}
2664 
2665 	switch (m->type) {
2666 	case FILE_FLOAT:
2667 	case FILE_BEFLOAT:
2668 	case FILE_LEFLOAT:
2669 		errno = 0;
2670 #ifdef HAVE_STRTOF
2671 		m->value.f = strtof(*p, &ep);
2672 #else
2673 		m->value.f = (float)strtod(*p, &ep);
2674 #endif
2675 		if (errno == 0)
2676 			*p = ep;
2677 		return 0;
2678 	case FILE_DOUBLE:
2679 	case FILE_BEDOUBLE:
2680 	case FILE_LEDOUBLE:
2681 		errno = 0;
2682 		m->value.d = strtod(*p, &ep);
2683 		if (errno == 0)
2684 			*p = ep;
2685 		return 0;
2686 	default:
2687 		errno = 0;
2688 		ull = (uint64_t)strtoull(*p, &ep, 0);
2689 		m->value.q = file_signextend(ms, m, ull);
2690 		if (*p == ep) {
2691 			file_magwarn(ms, "Unparseable number `%s'", *p);
2692 		} else {
2693 			size_t ts = typesize(m->type);
2694 			uint64_t x;
2695 			const char *q;
2696 
2697 			if (ts == (size_t)~0) {
2698 				file_magwarn(ms,
2699 				    "Expected numeric type got `%s'",
2700 				    type_tbl[m->type].name);
2701 			}
2702 			for (q = *p; isspace((unsigned char)*q); q++)
2703 				continue;
2704 			if (*q == '-')
2705 				ull = -(int64_t)ull;
2706 			switch (ts) {
2707 			case 1:
2708 				x = (uint64_t)(ull & ~0xffULL);
2709 				break;
2710 			case 2:
2711 				x = (uint64_t)(ull & ~0xffffULL);
2712 				break;
2713 			case 4:
2714 				x = (uint64_t)(ull & ~0xffffffffULL);
2715 				break;
2716 			case 8:
2717 				x = 0;
2718 				break;
2719 			default:
2720 				abort();
2721 			}
2722 			if (x) {
2723 				file_magwarn(ms, "Overflow for numeric"
2724 				    " type `%s' value %#" PRIx64,
2725 				    type_tbl[m->type].name, ull);
2726 			}
2727 		}
2728 		if (errno == 0) {
2729 			*p = ep;
2730 			eatsize(p);
2731 		}
2732 		return 0;
2733 	}
2734 }
2735 
2736 /*
2737  * Convert a string containing C character escapes.  Stop at an unescaped
2738  * space or tab.
2739  * Copy the converted version to "m->value.s", and the length in m->vallen.
2740  * Return updated scan pointer as function result. Warn if set.
2741  */
2742 private const char *
2743 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2744 {
2745 	const char *origs = s;
2746 	char	*p = m->value.s;
2747 	size_t  plen = sizeof(m->value.s);
2748 	char 	*origp = p;
2749 	char	*pmax = p + plen - 1;
2750 	int	c;
2751 	int	val;
2752 
2753 	while ((c = *s++) != '\0') {
2754 		if (isspace((unsigned char) c))
2755 			break;
2756 		if (p >= pmax) {
2757 			file_error(ms, 0, "string too long: `%s'", origs);
2758 			return NULL;
2759 		}
2760 		if (c == '\\') {
2761 			switch(c = *s++) {
2762 
2763 			case '\0':
2764 				if (warn)
2765 					file_magwarn(ms, "incomplete escape");
2766 				s--;
2767 				goto out;
2768 
2769 			case '\t':
2770 				if (warn) {
2771 					file_magwarn(ms,
2772 					    "escaped tab found, use \\t instead");
2773 					warn = 0;	/* already did */
2774 				}
2775 				/*FALLTHROUGH*/
2776 			default:
2777 				if (warn) {
2778 					if (isprint((unsigned char)c)) {
2779 						/* Allow escaping of
2780 						 * ``relations'' */
2781 						if (strchr("<>&^=!", c) == NULL
2782 						    && (m->type != FILE_REGEX ||
2783 						    strchr("[]().*?^$|{}", c)
2784 						    == NULL)) {
2785 							file_magwarn(ms, "no "
2786 							    "need to escape "
2787 							    "`%c'", c);
2788 						}
2789 					} else {
2790 						file_magwarn(ms,
2791 						    "unknown escape sequence: "
2792 						    "\\%03o", c);
2793 					}
2794 				}
2795 				/*FALLTHROUGH*/
2796 			/* space, perhaps force people to use \040? */
2797 			case ' ':
2798 #if 0
2799 			/*
2800 			 * Other things people escape, but shouldn't need to,
2801 			 * so we disallow them
2802 			 */
2803 			case '\'':
2804 			case '"':
2805 			case '?':
2806 #endif
2807 			/* Relations */
2808 			case '>':
2809 			case '<':
2810 			case '&':
2811 			case '^':
2812 			case '=':
2813 			case '!':
2814 			/* and baskslash itself */
2815 			case '\\':
2816 				*p++ = (char) c;
2817 				break;
2818 
2819 			case 'a':
2820 				*p++ = '\a';
2821 				break;
2822 
2823 			case 'b':
2824 				*p++ = '\b';
2825 				break;
2826 
2827 			case 'f':
2828 				*p++ = '\f';
2829 				break;
2830 
2831 			case 'n':
2832 				*p++ = '\n';
2833 				break;
2834 
2835 			case 'r':
2836 				*p++ = '\r';
2837 				break;
2838 
2839 			case 't':
2840 				*p++ = '\t';
2841 				break;
2842 
2843 			case 'v':
2844 				*p++ = '\v';
2845 				break;
2846 
2847 			/* \ and up to 3 octal digits */
2848 			case '0':
2849 			case '1':
2850 			case '2':
2851 			case '3':
2852 			case '4':
2853 			case '5':
2854 			case '6':
2855 			case '7':
2856 				val = c - '0';
2857 				c = *s++;  /* try for 2 */
2858 				if (c >= '0' && c <= '7') {
2859 					val = (val << 3) | (c - '0');
2860 					c = *s++;  /* try for 3 */
2861 					if (c >= '0' && c <= '7')
2862 						val = (val << 3) | (c-'0');
2863 					else
2864 						--s;
2865 				}
2866 				else
2867 					--s;
2868 				*p++ = (char)val;
2869 				break;
2870 
2871 			/* \x and up to 2 hex digits */
2872 			case 'x':
2873 				val = 'x';	/* Default if no digits */
2874 				c = hextoint(*s++);	/* Get next char */
2875 				if (c >= 0) {
2876 					val = c;
2877 					c = hextoint(*s++);
2878 					if (c >= 0)
2879 						val = (val << 4) + c;
2880 					else
2881 						--s;
2882 				} else
2883 					--s;
2884 				*p++ = (char)val;
2885 				break;
2886 			}
2887 		} else
2888 			*p++ = (char)c;
2889 	}
2890 	--s;
2891 out:
2892 	*p = '\0';
2893 	m->vallen = CAST(unsigned char, (p - origp));
2894 	if (m->type == FILE_PSTRING)
2895 		m->vallen += (unsigned char)file_pstring_length_size(m);
2896 	return s;
2897 }
2898 
2899 
2900 /* Single hex char to int; -1 if not a hex char. */
2901 private int
2902 hextoint(int c)
2903 {
2904 	if (!isascii((unsigned char) c))
2905 		return -1;
2906 	if (isdigit((unsigned char) c))
2907 		return c - '0';
2908 	if ((c >= 'a') && (c <= 'f'))
2909 		return c + 10 - 'a';
2910 	if (( c>= 'A') && (c <= 'F'))
2911 		return c + 10 - 'A';
2912 	return -1;
2913 }
2914 
2915 
2916 /*
2917  * Print a string containing C character escapes.
2918  */
2919 protected void
2920 file_showstr(FILE *fp, const char *s, size_t len)
2921 {
2922 	char	c;
2923 
2924 	for (;;) {
2925 		if (len == ~0U) {
2926 			c = *s++;
2927 			if (c == '\0')
2928 				break;
2929 		}
2930 		else  {
2931 			if (len-- == 0)
2932 				break;
2933 			c = *s++;
2934 		}
2935 		if (c >= 040 && c <= 0176)	/* TODO isprint && !iscntrl */
2936 			(void) fputc(c, fp);
2937 		else {
2938 			(void) fputc('\\', fp);
2939 			switch (c) {
2940 			case '\a':
2941 				(void) fputc('a', fp);
2942 				break;
2943 
2944 			case '\b':
2945 				(void) fputc('b', fp);
2946 				break;
2947 
2948 			case '\f':
2949 				(void) fputc('f', fp);
2950 				break;
2951 
2952 			case '\n':
2953 				(void) fputc('n', fp);
2954 				break;
2955 
2956 			case '\r':
2957 				(void) fputc('r', fp);
2958 				break;
2959 
2960 			case '\t':
2961 				(void) fputc('t', fp);
2962 				break;
2963 
2964 			case '\v':
2965 				(void) fputc('v', fp);
2966 				break;
2967 
2968 			default:
2969 				(void) fprintf(fp, "%.3o", c & 0377);
2970 				break;
2971 			}
2972 		}
2973 	}
2974 }
2975 
2976 /*
2977  * eatsize(): Eat the size spec from a number [eg. 10UL]
2978  */
2979 private void
2980 eatsize(const char **p)
2981 {
2982 	const char *l = *p;
2983 
2984 	if (LOWCASE(*l) == 'u')
2985 		l++;
2986 
2987 	switch (LOWCASE(*l)) {
2988 	case 'l':    /* long */
2989 	case 's':    /* short */
2990 	case 'h':    /* short */
2991 	case 'b':    /* char/byte */
2992 	case 'c':    /* char/byte */
2993 		l++;
2994 		/*FALLTHROUGH*/
2995 	default:
2996 		break;
2997 	}
2998 
2999 	*p = l;
3000 }
3001 
3002 /*
3003  * handle a buffer containing a compiled file.
3004  */
3005 private struct magic_map *
3006 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
3007 {
3008 	struct magic_map *map;
3009 
3010 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
3011 		file_oomem(ms, sizeof(*map));
3012 		return NULL;
3013 	}
3014 	map->len = len;
3015 	map->p = buf;
3016 	map->type = MAP_TYPE_USER;
3017 	if (check_buffer(ms, map, "buffer") != 0) {
3018 		apprentice_unmap(map);
3019 		return NULL;
3020 	}
3021 	return map;
3022 }
3023 
3024 /*
3025  * handle a compiled file.
3026  */
3027 
3028 private struct magic_map *
3029 apprentice_map(struct magic_set *ms, const char *fn)
3030 {
3031 	int fd;
3032 	struct stat st;
3033 	char *dbname = NULL;
3034 	struct magic_map *map;
3035 	struct magic_map *rv = NULL;
3036 
3037 	fd = -1;
3038 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
3039 		file_oomem(ms, sizeof(*map));
3040 		goto error;
3041 	}
3042 	map->type = MAP_TYPE_USER;	/* unspecified */
3043 
3044 	dbname = mkdbname(ms, fn, 0);
3045 	if (dbname == NULL)
3046 		goto error;
3047 
3048 	if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
3049 		goto error;
3050 
3051 	if (fstat(fd, &st) == -1) {
3052 		file_error(ms, errno, "cannot stat `%s'", dbname);
3053 		goto error;
3054 	}
3055 	if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
3056 		file_error(ms, 0, "file `%s' is too %s", dbname,
3057 		    st.st_size < 8 ? "small" : "large");
3058 		goto error;
3059 	}
3060 
3061 	map->len = (size_t)st.st_size;
3062 #ifdef QUICK
3063 	map->type = MAP_TYPE_MMAP;
3064 	if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
3065 	    MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
3066 		file_error(ms, errno, "cannot map `%s'", dbname);
3067 		goto error;
3068 	}
3069 #else
3070 	map->type = MAP_TYPE_MALLOC;
3071 	if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
3072 		file_oomem(ms, map->len);
3073 		goto error;
3074 	}
3075 	if (read(fd, map->p, map->len) != (ssize_t)map->len) {
3076 		file_badread(ms);
3077 		goto error;
3078 	}
3079 #define RET	1
3080 #endif
3081 	(void)close(fd);
3082 	fd = -1;
3083 
3084 	if (check_buffer(ms, map, dbname) != 0) {
3085 		rv = (struct magic_map *)-1;
3086 		goto error;
3087 	}
3088 #ifdef QUICK
3089 	if (mprotect(map->p, (size_t)st.st_size, PROT_READ) == -1) {
3090 		file_error(ms, errno, "cannot mprotect `%s'", dbname);
3091 		goto error;
3092 	}
3093 #endif
3094 
3095 	free(dbname);
3096 	return map;
3097 
3098 error:
3099 	if (fd != -1)
3100 		(void)close(fd);
3101 	apprentice_unmap(map);
3102 	free(dbname);
3103 	return rv;
3104 }
3105 
3106 private int
3107 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
3108 {
3109 	uint32_t *ptr;
3110 	uint32_t entries, nentries;
3111 	uint32_t version;
3112 	int i, needsbyteswap;
3113 
3114 	ptr = CAST(uint32_t *, map->p);
3115 	if (*ptr != MAGICNO) {
3116 		if (swap4(*ptr) != MAGICNO) {
3117 			file_error(ms, 0, "bad magic in `%s'", dbname);
3118 			return -1;
3119 		}
3120 		needsbyteswap = 1;
3121 	} else
3122 		needsbyteswap = 0;
3123 	if (needsbyteswap)
3124 		version = swap4(ptr[1]);
3125 	else
3126 		version = ptr[1];
3127 	if (version != VERSIONNO) {
3128 		file_error(ms, 0, "File %s supports only version %d magic "
3129 		    "files. `%s' is version %d", VERSION,
3130 		    VERSIONNO, dbname, version);
3131 		return -1;
3132 	}
3133 	entries = (uint32_t)(map->len / sizeof(struct magic));
3134 	if ((entries * sizeof(struct magic)) != map->len) {
3135 		file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
3136 		    "a multiple of %" SIZE_T_FORMAT "u",
3137 		    dbname, map->len, sizeof(struct magic));
3138 		return -1;
3139 	}
3140 	map->magic[0] = CAST(struct magic *, map->p) + 1;
3141 	nentries = 0;
3142 	for (i = 0; i < MAGIC_SETS; i++) {
3143 		if (needsbyteswap)
3144 			map->nmagic[i] = swap4(ptr[i + 2]);
3145 		else
3146 			map->nmagic[i] = ptr[i + 2];
3147 		if (i != MAGIC_SETS - 1)
3148 			map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3149 		nentries += map->nmagic[i];
3150 	}
3151 	if (entries != nentries + 1) {
3152 		file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3153 		    dbname, entries, nentries + 1);
3154 		return -1;
3155 	}
3156 	if (needsbyteswap)
3157 		for (i = 0; i < MAGIC_SETS; i++)
3158 			byteswap(map->magic[i], map->nmagic[i]);
3159 	return 0;
3160 }
3161 
3162 /*
3163  * handle an mmaped file.
3164  */
3165 private int
3166 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3167 {
3168 	static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3169 	static const size_t m = sizeof(**map->magic);
3170 	int fd = -1;
3171 	size_t len;
3172 	char *dbname;
3173 	int rv = -1;
3174 	uint32_t i;
3175 	union {
3176 		struct magic m;
3177 		uint32_t h[2 + MAGIC_SETS];
3178 	} hdr;
3179 
3180 	dbname = mkdbname(ms, fn, 1);
3181 
3182 	if (dbname == NULL)
3183 		goto out;
3184 
3185 	if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3186 	{
3187 		file_error(ms, errno, "cannot open `%s'", dbname);
3188 		goto out;
3189 	}
3190 	memset(&hdr, 0, sizeof(hdr));
3191 	hdr.h[0] = MAGICNO;
3192 	hdr.h[1] = VERSIONNO;
3193 	memcpy(hdr.h + 2, map->nmagic, nm);
3194 
3195 	if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3196 		file_error(ms, errno, "error writing `%s'", dbname);
3197 		goto out2;
3198 	}
3199 
3200 	for (i = 0; i < MAGIC_SETS; i++) {
3201 		len = m * map->nmagic[i];
3202 		if (write(fd, map->magic[i], len) != (ssize_t)len) {
3203 			file_error(ms, errno, "error writing `%s'", dbname);
3204 			goto out2;
3205 		}
3206 	}
3207 
3208 	rv = 0;
3209 out2:
3210 	if (fd != -1)
3211 		(void)close(fd);
3212 out:
3213 	apprentice_unmap(map);
3214 	free(dbname);
3215 	return rv;
3216 }
3217 
3218 private const char ext[] = ".mgc";
3219 /*
3220  * make a dbname
3221  */
3222 private char *
3223 mkdbname(struct magic_set *ms, const char *fn, int strip)
3224 {
3225 	const char *p, *q;
3226 	char *buf;
3227 
3228 	if (strip) {
3229 		if ((p = strrchr(fn, '/')) != NULL)
3230 			fn = ++p;
3231 	}
3232 
3233 	for (q = fn; *q; q++)
3234 		continue;
3235 	/* Look for .mgc */
3236 	for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3237 		if (*p != *q)
3238 			break;
3239 
3240 	/* Did not find .mgc, restore q */
3241 	if (p >= ext)
3242 		while (*q)
3243 			q++;
3244 
3245 	q++;
3246 	/* Compatibility with old code that looked in .mime */
3247 	if (ms->flags & MAGIC_MIME) {
3248 		if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3249 			return NULL;
3250 		if (access(buf, R_OK) != -1) {
3251 			ms->flags &= MAGIC_MIME_TYPE;
3252 			return buf;
3253 		}
3254 		free(buf);
3255 	}
3256 	if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3257 		return NULL;
3258 
3259 	/* Compatibility with old code that looked in .mime */
3260 	if (strstr(fn, ".mime") != NULL)
3261 		ms->flags &= MAGIC_MIME_TYPE;
3262 	return buf;
3263 }
3264 
3265 /*
3266  * Byteswap an mmap'ed file if needed
3267  */
3268 private void
3269 byteswap(struct magic *magic, uint32_t nmagic)
3270 {
3271 	uint32_t i;
3272 	for (i = 0; i < nmagic; i++)
3273 		bs1(&magic[i]);
3274 }
3275 
3276 /*
3277  * swap a short
3278  */
3279 private uint16_t
3280 swap2(uint16_t sv)
3281 {
3282 	uint16_t rv;
3283 	uint8_t *s = (uint8_t *)(void *)&sv;
3284 	uint8_t *d = (uint8_t *)(void *)&rv;
3285 	d[0] = s[1];
3286 	d[1] = s[0];
3287 	return rv;
3288 }
3289 
3290 /*
3291  * swap an int
3292  */
3293 private uint32_t
3294 swap4(uint32_t sv)
3295 {
3296 	uint32_t rv;
3297 	uint8_t *s = (uint8_t *)(void *)&sv;
3298 	uint8_t *d = (uint8_t *)(void *)&rv;
3299 	d[0] = s[3];
3300 	d[1] = s[2];
3301 	d[2] = s[1];
3302 	d[3] = s[0];
3303 	return rv;
3304 }
3305 
3306 /*
3307  * swap a quad
3308  */
3309 private uint64_t
3310 swap8(uint64_t sv)
3311 {
3312 	uint64_t rv;
3313 	uint8_t *s = (uint8_t *)(void *)&sv;
3314 	uint8_t *d = (uint8_t *)(void *)&rv;
3315 #if 0
3316 	d[0] = s[3];
3317 	d[1] = s[2];
3318 	d[2] = s[1];
3319 	d[3] = s[0];
3320 	d[4] = s[7];
3321 	d[5] = s[6];
3322 	d[6] = s[5];
3323 	d[7] = s[4];
3324 #else
3325 	d[0] = s[7];
3326 	d[1] = s[6];
3327 	d[2] = s[5];
3328 	d[3] = s[4];
3329 	d[4] = s[3];
3330 	d[5] = s[2];
3331 	d[6] = s[1];
3332 	d[7] = s[0];
3333 #endif
3334 	return rv;
3335 }
3336 
3337 /*
3338  * byteswap a single magic entry
3339  */
3340 private void
3341 bs1(struct magic *m)
3342 {
3343 	m->cont_level = swap2(m->cont_level);
3344 	m->offset = swap4((uint32_t)m->offset);
3345 	m->in_offset = swap4((uint32_t)m->in_offset);
3346 	m->lineno = swap4((uint32_t)m->lineno);
3347 	if (IS_STRING(m->type)) {
3348 		m->str_range = swap4(m->str_range);
3349 		m->str_flags = swap4(m->str_flags);
3350 	}
3351 	else {
3352 		m->value.q = swap8(m->value.q);
3353 		m->num_mask = swap8(m->num_mask);
3354 	}
3355 }
3356 
3357 protected size_t
3358 file_pstring_length_size(const struct magic *m)
3359 {
3360 	switch (m->str_flags & PSTRING_LEN) {
3361 	case PSTRING_1_LE:
3362 		return 1;
3363 	case PSTRING_2_LE:
3364 	case PSTRING_2_BE:
3365 		return 2;
3366 	case PSTRING_4_LE:
3367 	case PSTRING_4_BE:
3368 		return 4;
3369 	default:
3370 		abort();	/* Impossible */
3371 		return 1;
3372 	}
3373 }
3374 protected size_t
3375 file_pstring_get_length(const struct magic *m, const char *ss)
3376 {
3377 	size_t len = 0;
3378 	const unsigned char *s = (const unsigned char *)ss;
3379 	unsigned int s3, s2, s1, s0;
3380 
3381 	switch (m->str_flags & PSTRING_LEN) {
3382 	case PSTRING_1_LE:
3383 		len = *s;
3384 		break;
3385 	case PSTRING_2_LE:
3386 		s0 = s[0];
3387 		s1 = s[1];
3388 		len = (s1 << 8) | s0;
3389 		break;
3390 	case PSTRING_2_BE:
3391 		s0 = s[0];
3392 		s1 = s[1];
3393 		len = (s0 << 8) | s1;
3394 		break;
3395 	case PSTRING_4_LE:
3396 		s0 = s[0];
3397 		s1 = s[1];
3398 		s2 = s[2];
3399 		s3 = s[3];
3400 		len = (s3 << 24) | (s2 << 16) | (s1 << 8) | s0;
3401 		break;
3402 	case PSTRING_4_BE:
3403 		s0 = s[0];
3404 		s1 = s[1];
3405 		s2 = s[2];
3406 		s3 = s[3];
3407 		len = (s0 << 24) | (s1 << 16) | (s2 << 8) | s3;
3408 		break;
3409 	default:
3410 		abort();	/* Impossible */
3411 	}
3412 
3413 	if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3414 		len -= file_pstring_length_size(m);
3415 
3416 	return len;
3417 }
3418 
3419 protected int
3420 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3421 {
3422 	uint32_t i, j;
3423 	struct mlist *mlist, *ml;
3424 
3425 	mlist = ms->mlist[1];
3426 
3427 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
3428 		struct magic *ma = ml->magic;
3429 		uint32_t nma = ml->nmagic;
3430 		for (i = 0; i < nma; i++) {
3431 			if (ma[i].type != FILE_NAME)
3432 				continue;
3433 			if (strcmp(ma[i].value.s, name) == 0) {
3434 				v->magic = &ma[i];
3435 				for (j = i + 1; j < nma; j++)
3436 				    if (ma[j].cont_level == 0)
3437 					    break;
3438 				v->nmagic = j - i;
3439 				return 0;
3440 			}
3441 		}
3442 	}
3443 	return -1;
3444 }
3445