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