aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/libmagic/src/apprentice.c
blob: ca22186695fc5edbdd3e05184cde6b3884a236e8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
/*
 * Copyright (c) Ian F. Darwin 1986-1995.
 * Software written by Ian F. Darwin and others;
 * maintained 1995-present by Christos Zoulas and others.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice immediately at the beginning of the file, without modification,
 *    this list of conditions, and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
/*
 * apprentice - make one pass through /etc/magic, learning its secrets.
 */

#include "file.h"

#ifndef	lint
FILE_RCSID("@(#)$File: apprentice.c,v 1.342 2023/07/17 14:38:35 christos Exp $")
#endif	/* lint */

#include "magic.h"
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#ifdef QUICK
#include <sys/mman.h>
#endif
#include <dirent.h>
#include <limits.h>
#ifdef HAVE_BYTESWAP_H
#include <byteswap.h>
#endif
#ifdef HAVE_SYS_BSWAP_H
#error #include <sys/bswap.h>
#endif


#define	EATAB {while (isascii(CAST(unsigned char, *l)) && \
		      isspace(CAST(unsigned char, *l)))  ++l;}
#define LOWCASE(l) (isupper(CAST(unsigned char, l)) ? \
			tolower(CAST(unsigned char, l)) : (l))
/*
 * Work around a bug in headers on Digital Unix.
 * At least confirmed for: OSF1 V4.0 878
 */
#if defined(__osf__) && defined(__DECC)
#ifdef MAP_FAILED
#undef MAP_FAILED
#endif
#endif

#ifndef MAP_FAILED
#define MAP_FAILED (void *) -1
#endif

#ifndef MAP_FILE
#define MAP_FILE 0
#endif

#define ALLOC_CHUNK	CAST(size_t, 10)
#define ALLOC_INCR	CAST(size_t, 200)

#define MAP_TYPE_USER	0
#define MAP_TYPE_MALLOC	1
#define MAP_TYPE_MMAP	2

struct magic_entry {
	struct magic *mp;
	uint32_t cont_count;
	uint32_t max_count;
};

struct magic_entry_set {
	struct magic_entry *me;
	uint32_t count;
	uint32_t max;
};

struct magic_map {
	void *p;
	size_t len;
	int type;
	struct magic *magic[MAGIC_SETS];
	uint32_t nmagic[MAGIC_SETS];
};

int file_formats[FILE_NAMES_SIZE];
const size_t file_nformats = FILE_NAMES_SIZE;
const char *file_names[FILE_NAMES_SIZE];
const size_t file_nnames = FILE_NAMES_SIZE;

file_private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
file_private int hextoint(int);
file_private const char *getstr(struct magic_set *, struct magic *, const char *,
    int);
file_private int parse(struct magic_set *, struct magic_entry *, const char *,
    size_t, int);
file_private void eatsize(const char **);
file_private int apprentice_1(struct magic_set *, const char *, int);
file_private ssize_t apprentice_magic_strength_1(const struct magic *);
file_private int apprentice_sort(const void *, const void *);
file_private void apprentice_list(struct mlist *, int );
file_private struct magic_map *apprentice_load(struct magic_set *,
    const char *, int);
file_private struct mlist *mlist_alloc(void);
file_private void mlist_free_all(struct magic_set *);
file_private void mlist_free(struct mlist *);
file_private void byteswap(struct magic *, uint32_t);
file_private void bs1(struct magic *);

#if defined(HAVE_BYTESWAP_H)
#define swap2(x)	bswap_16(x)
#define swap4(x)	bswap_32(x)
#define swap8(x)	bswap_64(x)
#elif defined(HAVE_SYS_BSWAP_H)
#define swap2(x)	bswap16(x)
#define swap4(x)	bswap32(x)
#define swap8(x)	bswap64(x)
#else
file_private uint16_t swap2(uint16_t);
file_private uint32_t swap4(uint32_t);
file_private uint64_t swap8(uint64_t);
#endif

file_private char *mkdbname(struct magic_set *, const char *, int);
file_private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
    size_t);
file_private struct magic_map *apprentice_map(struct magic_set *, const char *);
file_private int check_buffer(struct magic_set *, struct magic_map *, const char *);
file_private void apprentice_unmap(struct magic_map *);
file_private int apprentice_compile(struct magic_set *, struct magic_map *,
    const char *);
file_private int check_format_type(const char *, int, const char **);
file_private int check_format(struct magic_set *, struct magic *);
file_private int get_op(char);
file_private int parse_mime(struct magic_set *, struct magic_entry *, const char *,
    size_t);
file_private int parse_strength(struct magic_set *, struct magic_entry *,
    const char *, size_t);
file_private int parse_apple(struct magic_set *, struct magic_entry *, const char *,
    size_t);
file_private int parse_ext(struct magic_set *, struct magic_entry *, const char *,
    size_t);


file_private size_t magicsize = sizeof(struct magic);

file_private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";

file_private struct {
	const char *name;
	size_t len;
	int (*fun)(struct magic_set *, struct magic_entry *, const char *,
	    size_t);
} bang[] = {
#define	DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
	DECLARE_FIELD(mime),
	DECLARE_FIELD(apple),
	DECLARE_FIELD(ext),
	DECLARE_FIELD(strength),
#undef	DECLARE_FIELD
	{ NULL, 0, NULL }
};

#ifdef COMPILE_ONLY

int main(int, char *[]);

int
main(int argc, char *argv[])
{
	int ret;
	struct magic_set *ms;
	char *progname;

	if ((progname = strrchr(argv[0], '/')) != NULL)
		progname++;
	else
		progname = argv[0];

	if (argc != 2) {
		(void)fprintf(stderr, "Usage: %s file\n", progname);
		return 1;
	}

	if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
		return 1;
	}
	ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
	if (ret == 1)
		(void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
	magic_close(ms);
	return ret;
}
#endif /* COMPILE_ONLY */

struct type_tbl_s {
	const char name[16];
	const size_t len;
	const int type;
	const int format;
};

/*
 * XXX - the actual Single UNIX Specification says that "long" means "long",
 * as in the C data type, but we treat it as meaning "4-byte integer".
 * Given that the OS X version of file 5.04 did the same, I guess that passes
 * the actual test; having "long" be dependent on how big a "long" is on
 * the machine running "file" is silly.
 */
static const struct type_tbl_s type_tbl[] = {
# define XX(s)		s, (sizeof(s) - 1)
# define XX_NULL	"", 0
	{ XX("invalid"),	FILE_INVALID,		FILE_FMT_NONE },
	{ XX("byte"),		FILE_BYTE,		FILE_FMT_NUM },
	{ XX("short"),		FILE_SHORT,		FILE_FMT_NUM },
	{ XX("default"),	FILE_DEFAULT,		FILE_FMT_NONE },
	{ XX("long"),		FILE_LONG,		FILE_FMT_NUM },
	{ XX("string"),		FILE_STRING,		FILE_FMT_STR },
	{ XX("date"),		FILE_DATE,		FILE_FMT_STR },
	{ XX("beshort"),	FILE_BESHORT,		FILE_FMT_NUM },
	{ XX("belong"),		FILE_BELONG,		FILE_FMT_NUM },
	{ XX("bedate"),		FILE_BEDATE,		FILE_FMT_STR },
	{ XX("leshort"),	FILE_LESHORT,		FILE_FMT_NUM },
	{ XX("lelong"),		FILE_LELONG,		FILE_FMT_NUM },
	{ XX("ledate"),		FILE_LEDATE,		FILE_FMT_STR },
	{ XX("pstring"),	FILE_PSTRING,		FILE_FMT_STR },
	{ XX("ldate"),		FILE_LDATE,		FILE_FMT_STR },
	{ XX("beldate"),	FILE_BELDATE,		FILE_FMT_STR },
	{ XX("leldate"),	FILE_LELDATE,		FILE_FMT_STR },
	{ XX("regex"),		FILE_REGEX,		FILE_FMT_STR },
	{ XX("bestring16"),	FILE_BESTRING16,	FILE_FMT_STR },
	{ XX("lestring16"),	FILE_LESTRING16,	FILE_FMT_STR },
	{ XX("search"),		FILE_SEARCH,		FILE_FMT_STR },
	{ XX("medate"),		FILE_MEDATE,		FILE_FMT_STR },
	{ XX("meldate"),	FILE_MELDATE,		FILE_FMT_STR },
	{ XX("melong"),		FILE_MELONG,		FILE_FMT_NUM },
	{ XX("quad"),		FILE_QUAD,		FILE_FMT_QUAD },
	{ XX("lequad"),		FILE_LEQUAD,		FILE_FMT_QUAD },
	{ XX("bequad"),		FILE_BEQUAD,		FILE_FMT_QUAD },
	{ XX("qdate"),		FILE_QDATE,		FILE_FMT_STR },
	{ XX("leqdate"),	FILE_LEQDATE,		FILE_FMT_STR },
	{ XX("beqdate"),	FILE_BEQDATE,		FILE_FMT_STR },
	{ XX("qldate"),		FILE_QLDATE,		FILE_FMT_STR },
	{ XX("leqldate"),	FILE_LEQLDATE,		FILE_FMT_STR },
	{ XX("beqldate"),	FILE_BEQLDATE,		FILE_FMT_STR },
	{ XX("float"),		FILE_FLOAT,		FILE_FMT_FLOAT },
	{ XX("befloat"),	FILE_BEFLOAT,		FILE_FMT_FLOAT },
	{ XX("lefloat"),	FILE_LEFLOAT,		FILE_FMT_FLOAT },
	{ XX("double"),		FILE_DOUBLE,		FILE_FMT_DOUBLE },
	{ XX("bedouble"),	FILE_BEDOUBLE,		FILE_FMT_DOUBLE },
	{ XX("ledouble"),	FILE_LEDOUBLE,		FILE_FMT_DOUBLE },
	{ XX("leid3"),		FILE_LEID3,		FILE_FMT_NUM },
	{ XX("beid3"),		FILE_BEID3,		FILE_FMT_NUM },
	{ XX("indirect"),	FILE_INDIRECT,		FILE_FMT_NUM },
	{ XX("qwdate"),		FILE_QWDATE,		FILE_FMT_STR },
	{ XX("leqwdate"),	FILE_LEQWDATE,		FILE_FMT_STR },
	{ XX("beqwdate"),	FILE_BEQWDATE,		FILE_FMT_STR },
	{ XX("name"),		FILE_NAME,		FILE_FMT_NONE },
	{ XX("use"),		FILE_USE,		FILE_FMT_NONE },
	{ XX("clear"),		FILE_CLEAR,		FILE_FMT_NONE },
	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
	{ XX("guid"),		FILE_GUID,		FILE_FMT_STR },
	{ XX("offset"),		FILE_OFFSET,		FILE_FMT_QUAD },
	{ XX("bevarint"),	FILE_BEVARINT,		FILE_FMT_STR },
	{ XX("levarint"),	FILE_LEVARINT,		FILE_FMT_STR },
	{ XX("msdosdate"),	FILE_MSDOSDATE,		FILE_FMT_STR },
	{ XX("lemsdosdate"),	FILE_LEMSDOSDATE,	FILE_FMT_STR },
	{ XX("bemsdosdate"),	FILE_BEMSDOSDATE,	FILE_FMT_STR },
	{ XX("msdostime"),	FILE_MSDOSTIME,		FILE_FMT_STR },
	{ XX("lemsdostime"),	FILE_LEMSDOSTIME,	FILE_FMT_STR },
	{ XX("bemsdostime"),	FILE_BEMSDOSTIME,	FILE_FMT_STR },
	{ XX("octal"),		FILE_OCTAL,		FILE_FMT_STR },
	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
};

/*
 * These are not types, and cannot be preceded by "u" to make them
 * unsigned.
 */
static const struct type_tbl_s special_tbl[] = {
	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
	{ XX("name"),		FILE_NAME,		FILE_FMT_STR },
	{ XX("use"),		FILE_USE,		FILE_FMT_STR },
	{ XX("octal"),		FILE_OCTAL,		FILE_FMT_STR },
	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
};
# undef XX
# undef XX_NULL

file_private int
get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
{
	const struct type_tbl_s *p;

	for (p = tbl; p->len; p++) {
		if (strncmp(l, p->name, p->len) == 0) {
			if (t)
				*t = l + p->len;
			break;
		}
	}
	return p->type;
}

file_private off_t
maxoff_t(void) {
	if (/*CONSTCOND*/sizeof(off_t) == sizeof(int))
		return CAST(off_t, INT_MAX);
	if (/*CONSTCOND*/sizeof(off_t) == sizeof(long))
		return CAST(off_t, LONG_MAX);
	return 0x7fffffff;
}

file_private int
get_standard_integer_type(const char *l, const char **t)
{
	int type;

	if (isalpha(CAST(unsigned char, l[1]))) {
		switch (l[1]) {
		case 'C':
			/* "dC" and "uC" */
			type = FILE_BYTE;
			break;
		case 'S':
			/* "dS" and "uS" */
			type = FILE_SHORT;
			break;
		case 'I':
		case 'L':
			/*
			 * "dI", "dL", "uI", and "uL".
			 *
			 * XXX - the actual Single UNIX Specification says
			 * that "L" means "long", as in the C data type,
			 * but we treat it as meaning "4-byte integer".
			 * Given that the OS X version of file 5.04 did
			 * the same, I guess that passes the actual SUS
			 * validation suite; having "dL" be dependent on
			 * how big a "long" is on the machine running
			 * "file" is silly.
			 */
			type = FILE_LONG;
			break;
		case 'Q':
			/* "dQ" and "uQ" */
			type = FILE_QUAD;
			break;
		default:
			/* "d{anything else}", "u{anything else}" */
			return FILE_INVALID;
		}
		l += 2;
	} else if (isdigit(CAST(unsigned char, l[1]))) {
		/*
		 * "d{num}" and "u{num}"; we only support {num} values
		 * of 1, 2, 4, and 8 - the Single UNIX Specification
		 * doesn't say anything about whether arbitrary
		 * values should be supported, but both the Solaris 10
		 * and OS X Mountain Lion versions of file passed the
		 * Single UNIX Specification validation suite, and
		 * neither of them support values bigger than 8 or
		 * non-power-of-2 values.
		 */
		if (isdigit(CAST(unsigned char, l[2]))) {
			/* Multi-digit, so > 9 */
			return FILE_INVALID;
		}
		switch (l[1]) {
		case '1':
			type = FILE_BYTE;
			break;
		case '2':
			type = FILE_SHORT;
			break;
		case '4':
			type = FILE_LONG;
			break;
		case '8':
			type = FILE_QUAD;
			break;
		default:
			/* XXX - what about 3, 5, 6, or 7? */
			return FILE_INVALID;
		}
		l += 2;
	} else {
		/*
		 * "d" or "u" by itself.
		 */
		type = FILE_LONG;
		++l;
	}
	if (t)
		*t = l;
	return type;
}

file_private void
init_file_tables(void)
{
	static int done = 0;
	const struct type_tbl_s *p;

	if (done)
		return;
	done++;

	for (p = type_tbl; p->len; p++) {
		assert(p->type < FILE_NAMES_SIZE);
		file_names[p->type] = p->name;
		file_formats[p->type] = p->format;
	}
	assert(p - type_tbl == FILE_NAMES_SIZE);
}

file_private int
add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
{
	struct mlist *ml;

	mlp->map = NULL;
	if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
		return -1;

	ml->map = idx == 0 ? map : NULL;
	ml->magic = map->magic[idx];
	ml->nmagic = map->nmagic[idx];
	if (ml->nmagic) {
		ml->magic_rxcomp = CAST(file_regex_t **,
		    calloc(ml->nmagic, sizeof(*ml->magic_rxcomp)));
		if (ml->magic_rxcomp == NULL) {
			free(ml);
			return -1;
		}
	} else
		ml->magic_rxcomp = NULL;
	mlp->prev->next = ml;
	ml->prev = mlp->prev;
	ml->next = mlp;
	mlp->prev = ml;
	return 0;
}

/*
 * Handle one file or directory.
 */
file_private int
apprentice_1(struct magic_set *ms, const char *fn, int action)
{
	struct magic_map *map;
#ifndef COMPILE_ONLY
	size_t i;
#endif

	if (magicsize != FILE_MAGICSIZE) {
		file_error(ms, 0, "magic element size %lu != %lu",
		    CAST(unsigned long, sizeof(*map->magic[0])),
		    CAST(unsigned long, FILE_MAGICSIZE));
		return -1;
	}

	if (action == FILE_COMPILE) {
		map = apprentice_load(ms, fn, action);
		if (map == NULL)
			return -1;
		return apprentice_compile(ms, map, fn);
	}

#ifndef COMPILE_ONLY
	map = apprentice_map(ms, fn);
	if (map == NULL) {
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(NULL, "using regular magic file `%s'", fn);
		map = apprentice_load(ms, fn, action);
		if (map == NULL)
			return -1;
	}

	for (i = 0; i < MAGIC_SETS; i++) {
		if (add_mlist(ms->mlist[i], map, i) == -1) {
			/* failed to add to any list, free explicitly */
			if (i == 0)
				apprentice_unmap(map);
			else
				mlist_free_all(ms);
			file_oomem(ms, sizeof(*ms->mlist[0]));
			return -1;
		}
	}

	if (action == FILE_LIST) {
		for (i = 0; i < MAGIC_SETS; i++) {
			printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
			    i);
			apprentice_list(ms->mlist[i], BINTEST);
			printf("Text patterns:\n");
			apprentice_list(ms->mlist[i], TEXTTEST);
		}
	}
	return 0;
#else
	return 0;
#endif /* COMPILE_ONLY */
}

file_protected void
file_ms_free(struct magic_set *ms)
{
	size_t i;
	if (ms == NULL)
		return;
	for (i = 0; i < MAGIC_SETS; i++)
		mlist_free(ms->mlist[i]);
	free(ms->o.pbuf);
	free(ms->o.buf);
	free(ms->c.li);
#ifdef USE_C_LOCALE
	freelocale(ms->c_lc_ctype);
#endif
	free(ms);
}

file_protected struct magic_set *
file_ms_alloc(int flags)
{
	struct magic_set *ms;
	size_t i, len;

	if ((ms = CAST(struct magic_set *, calloc(CAST(size_t, 1u),
	    sizeof(*ms)))) == NULL)
		return NULL;

	if (magic_setflags(ms, flags) == -1) {
		errno = EINVAL;
		goto free;
	}

	ms->o.buf = ms->o.pbuf = NULL;
	ms->o.blen = 0;
	len = (ms->c.len = 10) * sizeof(*ms->c.li);

	if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
		goto free;

	ms->event_flags = 0;
	ms->error = -1;
	for (i = 0; i < MAGIC_SETS; i++)
		ms->mlist[i] = NULL;
	ms->file = "unknown";
	ms->line = 0;
	ms->indir_max = FILE_INDIR_MAX;
	ms->name_max = FILE_NAME_MAX;
	ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
	ms->elf_shsize_max = FILE_ELF_SHSIZE_MAX;
	ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
	ms->elf_notes_max = FILE_ELF_NOTES_MAX;
	ms->regex_max = FILE_REGEX_MAX;
	ms->bytes_max = FILE_BYTES_MAX;
	ms->encoding_max = FILE_ENCODING_MAX;
#ifdef USE_C_LOCALE
	ms->c_lc_ctype = newlocale(LC_CTYPE_MASK, "C", 0);
	assert(ms->c_lc_ctype != NULL);
#endif
	return ms;
free:
	free(ms);
	return NULL;
}

file_private void
apprentice_unmap(struct magic_map *map)
{
	size_t i;
	char *p;
	if (map == NULL)
		return;

	switch (map->type) {
	case MAP_TYPE_USER:
		break;
	case MAP_TYPE_MALLOC:
		p = CAST(char *, map->p);
		for (i = 0; i < MAGIC_SETS; i++) {
			char *b = RCAST(char *, map->magic[i]);
			if (p != NULL && b >= p && b <= p + map->len)
				continue;
			free(b);
		}
		free(p);
		break;
#ifdef QUICK
	case MAP_TYPE_MMAP:
		if (map->p && map->p != MAP_FAILED)
			(void)munmap(map->p, map->len);
		break;
#endif
	default:
		fprintf(stderr, "Bad map type %d", map->type);
		abort();
	}
	free(map);
}

file_private struct mlist *
mlist_alloc(void)
{
	struct mlist *mlist;
	if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
		return NULL;
	}
	mlist->next = mlist->prev = mlist;
	return mlist;
}

file_private void
mlist_free_all(struct magic_set *ms)
{
	size_t i;

	for (i = 0; i < MAGIC_SETS; i++) {
		mlist_free(ms->mlist[i]);
		ms->mlist[i] = NULL;
	}
}

file_private void
mlist_free_one(struct mlist *ml)
{
	size_t i;

	if (ml->map)
		apprentice_unmap(CAST(struct magic_map *, ml->map));

	for (i = 0; i < ml->nmagic; ++i) {
		if (ml->magic_rxcomp[i]) {
			file_regfree(ml->magic_rxcomp[i]);
			free(ml->magic_rxcomp[i]);
			ml->magic_rxcomp[i] = NULL;
		}
	}
	free(ml->magic_rxcomp);
	ml->magic_rxcomp = NULL;
	free(ml);
}

file_private void
mlist_free(struct mlist *mlist)
{
	struct mlist *ml, *next;

	if (mlist == NULL)
		return;

	for (ml = mlist->next; ml != mlist;) {
		next = ml->next;
		mlist_free_one(ml);
		ml = next;
	}
	mlist_free_one(mlist);
}

#ifndef COMPILE_ONLY
/* void **bufs: an array of compiled magic files */
file_protected int
buffer_apprentice(struct magic_set *ms, struct magic **bufs,
    size_t *sizes, size_t nbufs)
{
	size_t i, j;
	struct magic_map *map;

	if (nbufs == 0)
		return -1;

	(void)file_reset(ms, 0);

	init_file_tables();

	for (i = 0; i < MAGIC_SETS; i++) {
		mlist_free(ms->mlist[i]);
		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
			file_oomem(ms, sizeof(*ms->mlist[0]));
			goto fail;
		}
	}

	for (i = 0; i < nbufs; i++) {
		map = apprentice_buf(ms, bufs[i], sizes[i]);
		if (map == NULL)
			goto fail;

		for (j = 0; j < MAGIC_SETS; j++) {
			if (add_mlist(ms->mlist[j], map, j) == -1) {
				file_oomem(ms, sizeof(*ms->mlist[0]));
				goto fail;
			}
		}
	}

	return 0;
fail:
	mlist_free_all(ms);
	return -1;
}
#endif

/* const char *fn: list of magic files and directories */
file_protected int
file_apprentice(struct magic_set *ms, const char *fn, int action)
{
	char *p, *mfn;
	int fileerr, errs = -1;
	size_t i, j;

	(void)file_reset(ms, 0);

	if ((fn = magic_getpath(fn, action)) == NULL)
		return -1;

	init_file_tables();

	if ((mfn = strdup(fn)) == NULL) {
		file_oomem(ms, strlen(fn));
		return -1;
	}

	for (i = 0; i < MAGIC_SETS; i++) {
		mlist_free(ms->mlist[i]);
		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
			file_oomem(ms, sizeof(*ms->mlist[0]));
			for (j = 0; j < i; j++) {
				mlist_free(ms->mlist[j]);
				ms->mlist[j] = NULL;
			}
			free(mfn);
			return -1;
		}
	}
	fn = mfn;

	while (fn) {
		p = CCAST(char *, strchr(fn, PATHSEP));
		if (p)
			*p++ = '\0';
		if (*fn == '\0')
			break;
		fileerr = apprentice_1(ms, fn, action);
		errs = MAX(errs, fileerr);
		fn = p;
	}

	free(mfn);

	if (errs == -1) {
		for (i = 0; i < MAGIC_SETS; i++) {
			mlist_free(ms->mlist[i]);
			ms->mlist[i] = NULL;
		}
		file_error(ms, 0, "could not find any valid magic files!");
		return -1;
	}

#if 0
	/*
	 * Always leave the database loaded
	 */
	if (action == FILE_LOAD)
		return 0;

	for (i = 0; i < MAGIC_SETS; i++) {
		mlist_free(ms->mlist[i]);
		ms->mlist[i] = NULL;
	}
#endif

	switch (action) {
	case FILE_LOAD:
	case FILE_COMPILE:
	case FILE_CHECK:
	case FILE_LIST:
		return 0;
	default:
		file_error(ms, 0, "Invalid action %d", action);
		return -1;
	}
}

/*
 * Compute the real length of a magic expression, for the purposes
 * of determining how "strong" a magic expression is (approximating
 * how specific its matches are):
 *	- magic characters count 0 unless escaped.
 *	- [] expressions count 1
 *	- {} expressions count 0
 *	- regular characters or escaped magic characters count 1
 *	- 0 length expressions count as one
 */
file_private size_t
nonmagic(const char *str)
{
	const char *p;
	size_t rv = 0;

	for (p = str; *p; p++)
		switch (*p) {
		case '\\':	/* Escaped anything counts 1 */
			if (!*++p)
				p--;
			rv++;
			continue;
		case '?':	/* Magic characters count 0 */
		case '*':
		case '.':
		case '+':
		case '^':
		case '$':
			continue;
		case '[':	/* Bracketed expressions count 1 the ']' */
			while (*p && *p != ']')
				p++;
			p--;
			continue;
		case '{':	/* Braced expressions count 0 */
			while (*p && *p != '}')
				p++;
			if (!*p)
				p--;
			continue;
		default:	/* Anything else counts 1 */
			rv++;
			continue;
		}

	return rv == 0 ? 1 : rv;	/* Return at least 1 */
}


file_private size_t
typesize(int type)
{
	switch (type) {
	case FILE_BYTE:
		return 1;

	case FILE_SHORT:
	case FILE_LESHORT:
	case FILE_BESHORT:
	case FILE_MSDOSDATE:
	case FILE_BEMSDOSDATE:
	case FILE_LEMSDOSDATE:
	case FILE_MSDOSTIME:
	case FILE_BEMSDOSTIME:
	case FILE_LEMSDOSTIME:
		return 2;

	case FILE_LONG:
	case FILE_LELONG:
	case FILE_BELONG:
	case FILE_MELONG:
		return 4;

	case FILE_DATE:
	case FILE_LEDATE:
	case FILE_BEDATE:
	case FILE_MEDATE:
	case FILE_LDATE:
	case FILE_LELDATE:
	case FILE_BELDATE:
	case FILE_MELDATE:
	case FILE_FLOAT:
	case FILE_BEFLOAT:
	case FILE_LEFLOAT:
	case FILE_BEID3:
	case FILE_LEID3:
		return 4;

	case FILE_QUAD:
	case FILE_BEQUAD:
	case FILE_LEQUAD:
	case FILE_QDATE:
	case FILE_LEQDATE:
	case FILE_BEQDATE:
	case FILE_QLDATE:
	case FILE_LEQLDATE:
	case FILE_BEQLDATE:
	case FILE_QWDATE:
	case FILE_LEQWDATE:
	case FILE_BEQWDATE:
	case FILE_DOUBLE:
	case FILE_BEDOUBLE:
	case FILE_LEDOUBLE:
	case FILE_OFFSET:
	case FILE_BEVARINT:
	case FILE_LEVARINT:
		return 8;

	case FILE_GUID:
		return 16;

	default:
		return FILE_BADSIZE;
	}
}

/*
 * Get weight of this magic entry, for sorting purposes.
 */
file_private ssize_t
apprentice_magic_strength_1(const struct magic *m)
{
#define MULT 10U
	size_t ts, v;
	ssize_t val = 2 * MULT;	/* baseline strength */

	switch (m->type) {
	case FILE_DEFAULT:	/* make sure this sorts last */
		if (m->factor_op != FILE_FACTOR_OP_NONE) {
			file_magwarn(NULL, "Usupported factor_op in default %d",
			    m->factor_op);
		}
		return 0;

	case FILE_BYTE:
	case FILE_SHORT:
	case FILE_LESHORT:
	case FILE_BESHORT:
	case FILE_LONG:
	case FILE_LELONG:
	case FILE_BELONG:
	case FILE_MELONG:
	case FILE_DATE:
	case FILE_LEDATE:
	case FILE_BEDATE:
	case FILE_MEDATE:
	case FILE_LDATE:
	case FILE_LELDATE:
	case FILE_BELDATE:
	case FILE_MELDATE:
	case FILE_FLOAT:
	case FILE_BEFLOAT:
	case FILE_LEFLOAT:
	case FILE_QUAD:
	case FILE_BEQUAD:
	case FILE_LEQUAD:
	case FILE_QDATE:
	case FILE_LEQDATE:
	case FILE_BEQDATE:
	case FILE_QLDATE:
	case FILE_LEQLDATE:
	case FILE_BEQLDATE:
	case FILE_QWDATE:
	case FILE_LEQWDATE:
	case FILE_BEQWDATE:
	case FILE_DOUBLE:
	case FILE_BEDOUBLE:
	case FILE_LEDOUBLE:
	case FILE_BEVARINT:
	case FILE_LEVARINT:
	case FILE_GUID:
	case FILE_BEID3:
	case FILE_LEID3:
	case FILE_OFFSET:
	case FILE_MSDOSDATE:
	case FILE_BEMSDOSDATE:
	case FILE_LEMSDOSDATE:
	case FILE_MSDOSTIME:
	case FILE_BEMSDOSTIME:
	case FILE_LEMSDOSTIME:
		ts = typesize(m->type);
		if (ts == FILE_BADSIZE) {
			(void)fprintf(stderr, "Bad size for type %d\n",
			    m->type);
			abort();
		}
		val += ts * MULT;
		break;

	case FILE_PSTRING:
	case FILE_STRING:
	case FILE_OCTAL:
		val += m->vallen * MULT;
		break;

	case FILE_BESTRING16:
	case FILE_LESTRING16:
		val += m->vallen * MULT / 2;
		break;

	case FILE_SEARCH:
		if (m->vallen == 0)
			break;
		val += m->vallen * MAX(MULT / m->vallen, 1);
		break;

	case FILE_REGEX:
		v = nonmagic(m->value.s);
		val += v * MAX(MULT / v, 1);
		break;

	case FILE_INDIRECT:
	case FILE_NAME:
	case FILE_USE:
	case FILE_CLEAR:
		break;

	case FILE_DER:
		val += MULT;
		break;

	default:
		(void)fprintf(stderr, "Bad type %d\n", m->type);
		abort();
	}

	switch (m->reln) {
	case 'x':	/* matches anything penalize */
	case '!':       /* matches almost anything penalize */
		val = 0;
		break;

	case '=':	/* Exact match, prefer */
		val += MULT;
		break;

	case '>':
	case '<':	/* comparison match reduce strength */
		val -= 2 * MULT;
		break;

	case '^':
	case '&':	/* masking bits, we could count them too */
		val -= MULT;
		break;

	default:
		(void)fprintf(stderr, "Bad relation %c\n", m->reln);
		abort();
	}

	return val;
}


/*ARGSUSED*/
file_protected size_t
file_magic_strength(const struct magic *m,
    size_t nmagic __attribute__((__unused__)))
{
	ssize_t val = apprentice_magic_strength_1(m);

#ifdef notyet
	if (m->desc[0] == '\0') {
		size_t i;
		/*
		 * Magic entries with no description get their continuations
		 * added
		 */
		for (i = 1; m[i].cont_level != 0 && i < MIN(nmagic, 3); i++) {
			ssize_t v = apprentice_magic_strength_1(&m[i]) >>
			    (i + 1);
			val += v;
			if (m[i].desc[0] != '\0')
				break;
		}
	}
#endif

	switch (m->factor_op) {
	case FILE_FACTOR_OP_NONE:
		break;
	case FILE_FACTOR_OP_PLUS:
		val += m->factor;
		break;
	case FILE_FACTOR_OP_MINUS:
		val -= m->factor;
		break;
	case FILE_FACTOR_OP_TIMES:
		val *= m->factor;
		break;
	case FILE_FACTOR_OP_DIV:
		val /= m->factor;
		break;
	default:
		(void)fprintf(stderr, "Bad factor_op %u\n", m->factor_op);
		abort();
	}

	if (val <= 0)	/* ensure we only return 0 for FILE_DEFAULT */
		val = 1;

#ifndef notyet
	/*
	 * Magic entries with no description get a bonus because they depend
	 * on subsequent magic entries to print something.
	 */
	if (m->desc[0] == '\0')
		val++;
#endif

	return val;
}

/*
 * Sort callback for sorting entries by "strength" (basically length)
 */
file_private int
apprentice_sort(const void *a, const void *b)
{
	const struct magic_entry *ma = CAST(const struct magic_entry *, a);
	const struct magic_entry *mb = CAST(const struct magic_entry *, b);
	size_t sa = file_magic_strength(ma->mp, ma->cont_count);
	size_t sb = file_magic_strength(mb->mp, mb->cont_count);
	if (sa == sb)
		return 0;
	else if (sa > sb)
		return -1;
	else
		return 1;
}

/*
 * Shows sorted patterns list in the order which is used for the matching
 */
file_private void
apprentice_list(struct mlist *mlist, int mode)
{
	uint32_t magindex, descindex, mimeindex, lineindex;
	struct mlist *ml;
	for (ml = mlist->next; ml != mlist; ml = ml->next) {
		for (magindex = 0; magindex < ml->nmagic; magindex++) {
			struct magic *m = &ml->magic[magindex];
			if ((m->flag & mode) != mode) {
				/* Skip sub-tests */
				while (magindex + 1 < ml->nmagic &&
				       ml->magic[magindex + 1].cont_level != 0)
					++magindex;
				continue; /* Skip to next top-level test*/
			}

			/*
			 * Try to iterate over the tree until we find item with
			 * description/mimetype.
			 */
			lineindex = descindex = mimeindex = magindex;
			for (; magindex + 1 < ml->nmagic &&
			   ml->magic[magindex + 1].cont_level != 0;
			   magindex++) {
				uint32_t mi = magindex + 1;
				if (*ml->magic[descindex].desc == '\0'
				    && *ml->magic[mi].desc)
					descindex = mi;
				if (*ml->magic[mimeindex].mimetype == '\0'
				    && *ml->magic[mi].mimetype)
					mimeindex = mi;
			}

			printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
			    file_magic_strength(m, ml->nmagic - magindex),
			    ml->magic[lineindex].lineno,
			    ml->magic[descindex].desc,
			    ml->magic[mimeindex].mimetype);
		}
	}
}

file_private void
set_test_type(struct magic *mstart, struct magic *m)
{
	switch (m->type) {
	case FILE_BYTE:
	case FILE_SHORT:
	case FILE_LONG:
	case FILE_DATE:
	case FILE_BESHORT:
	case FILE_BELONG:
	case FILE_BEDATE:
	case FILE_LESHORT:
	case FILE_LELONG:
	case FILE_LEDATE:
	case FILE_LDATE:
	case FILE_BELDATE:
	case FILE_LELDATE:
	case FILE_MEDATE:
	case FILE_MELDATE:
	case FILE_MELONG:
	case FILE_QUAD:
	case FILE_LEQUAD:
	case FILE_BEQUAD:
	case FILE_QDATE:
	case FILE_LEQDATE:
	case FILE_BEQDATE:
	case FILE_QLDATE:
	case FILE_LEQLDATE:
	case FILE_BEQLDATE:
	case FILE_QWDATE:
	case FILE_LEQWDATE:
	case FILE_BEQWDATE:
	case FILE_FLOAT:
	case FILE_BEFLOAT:
	case FILE_LEFLOAT:
	case FILE_DOUBLE:
	case FILE_BEDOUBLE:
	case FILE_LEDOUBLE:
	case FILE_BEVARINT:
	case FILE_LEVARINT:
	case FILE_DER:
	case FILE_GUID:
	case FILE_OFFSET:
	case FILE_MSDOSDATE:
	case FILE_BEMSDOSDATE:
	case FILE_LEMSDOSDATE:
	case FILE_MSDOSTIME:
	case FILE_BEMSDOSTIME:
	case FILE_LEMSDOSTIME:
	case FILE_OCTAL:
		mstart->flag |= BINTEST;
		break;
	case FILE_STRING:
	case FILE_PSTRING:
	case FILE_BESTRING16:
	case FILE_LESTRING16:
		/* Allow text overrides */
		if (mstart->str_flags & STRING_TEXTTEST)
			mstart->flag |= TEXTTEST;
		else
			mstart->flag |= BINTEST;
		break;
	case FILE_REGEX:
	case FILE_SEARCH:
		/* Check for override */
		if (mstart->str_flags & STRING_BINTEST)
			mstart->flag |= BINTEST;
		if (mstart->str_flags & STRING_TEXTTEST)
			mstart->flag |= TEXTTEST;

		if (mstart->flag & (TEXTTEST|BINTEST))
			break;

		/* binary test if pattern is not text */
		if (file_looks_utf8(m->value.us, CAST(size_t, m->vallen), NULL,
		    NULL) <= 0)
			mstart->flag |= BINTEST;
		else
			mstart->flag |= TEXTTEST;
		break;
	case FILE_DEFAULT:
		/* can't deduce anything; we shouldn't see this at the
		   top level anyway */
		break;
	case FILE_INVALID:
	default:
		/* invalid search type, but no need to complain here */
		break;
	}
}

file_private int
addentry(struct magic_set *ms, struct magic_entry *me,
   struct magic_entry_set *mset)
{
	size_t i = me->mp->type == FILE_NAME ? 1 : 0;
	if (mset[i].me == NULL || mset[i].count == mset[i].max) {
		struct magic_entry *mp;

		size_t incr = mset[i].max + ALLOC_INCR;
		if ((mp = CAST(struct magic_entry *,
		    realloc(mset[i].me, sizeof(*mp) * incr))) ==
		    NULL) {
			file_oomem(ms, sizeof(*mp) * incr);
			return -1;
		}
		(void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
		    ALLOC_INCR);
		mset[i].me = mp;
		mset[i].max = CAST(uint32_t, incr);
		assert(mset[i].max == incr);
	}
	mset[i].me[mset[i].count++] = *me;
	memset(me, 0, sizeof(*me));
	return 0;
}

/*
 * Load and parse one file.
 */
file_private void
load_1(struct magic_set *ms, int action, const char *fn, int *errs,
   struct magic_entry_set *mset)
{
	size_t lineno = 0, llen = 0;
	char *line = NULL;
	ssize_t len;
	struct magic_entry me;

	FILE *f = fopen(ms->file = fn, "r");
	if (f == NULL) {
		if (errno != ENOENT)
			file_error(ms, errno, "cannot read magic file `%s'",
				   fn);
		(*errs)++;
		return;
	}

	memset(&me, 0, sizeof(me));
	/* read and parse this file */
	for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
	    ms->line++) {
		if (len == 0) /* null line, garbage, etc */
			continue;
		if (line[len - 1] == '\n') {
			lineno++;
			line[len - 1] = '\0'; /* delete newline */
		}
		switch (line[0]) {
		case '\0':	/* empty, do not parse */
		case '#':	/* comment, do not parse */
			continue;
		case '!':
			if (line[1] == ':') {
				size_t i;

				for (i = 0; bang[i].name != NULL; i++) {
					if (CAST(size_t, len - 2) > bang[i].len &&
					    memcmp(bang[i].name, line + 2,
					    bang[i].len) == 0)
						break;
				}
				if (bang[i].name == NULL) {
					file_error(ms, 0,
					    "Unknown !: entry `%s'", line);
					(*errs)++;
					continue;
				}
				if (me.mp == NULL) {
					file_error(ms, 0,
					    "No current entry for :!%s type",
						bang[i].name);
					(*errs)++;
					continue;
				}
				if ((*bang[i].fun)(ms, &me,
				    line + bang[i].len + 2, 
				    len - bang[i].len - 2) != 0) {
					(*errs)++;
					continue;
				}
				continue;
			}
			/*FALLTHROUGH*/
		default:
		again:
			switch (parse(ms, &me, line, lineno, action)) {
			case 0:
				continue;
			case 1:
				(void)addentry(ms, &me, mset);
				goto again;
			default:
				(*errs)++;
				break;
			}
		}
	}
	if (me.mp)
		(void)addentry(ms, &me, mset);
	free(line);
	(void)fclose(f);
}

/*
 * parse a file or directory of files
 * const char *fn: name of magic file or directory
 */
file_private int
cmpstrp(const void *p1, const void *p2)
{
        return strcmp(*RCAST(char *const *, p1), *RCAST(char *const *, p2));
}


file_private uint32_t
set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
    uint32_t starttest)
{
	static const char text[] = "text";
	static const char binary[] = "binary";
	static const size_t len = sizeof(text);

	uint32_t i = starttest;

	do {
		set_test_type(me[starttest].mp, me[i].mp);
		if ((ms->flags & MAGIC_DEBUG) == 0)
			continue;
		(void)fprintf(stderr, "%s%s%s: %s\n",
		    me[i].mp->mimetype,
		    me[i].mp->mimetype[0] == '\0' ? "" : "; ",
		    me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
		    me[i].mp->flag & BINTEST ? binary : text);
		if (me[i].mp->flag & BINTEST) {
			char *p = strstr(me[i].mp->desc, text);
			if (p && (p == me[i].mp->desc ||
			    isspace(CAST(unsigned char, p[-1]))) &&
			    (p + len - me[i].mp->desc == MAXstring
			    || (p[len] == '\0' ||
			    isspace(CAST(unsigned char, p[len])))))
				(void)fprintf(stderr, "*** Possible "
				    "binary test for text type\n");
		}
	} while (++i < nme && me[i].mp->cont_level != 0);
	return i;
}

file_private void
set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
{
	uint32_t i;
	for (i = 0; i < nme; i++) {
		if (me[i].mp->cont_level == 0 &&
		    me[i].mp->type == FILE_DEFAULT) {
			while (++i < nme)
				if (me[i].mp->cont_level == 0)
					break;
			if (i != nme) {
				/* XXX - Ugh! */
				ms->line = me[i].mp->lineno;
				file_magwarn(ms,
				    "level 0 \"default\" did not sort last");
			}
			return;
		}
	}
}

file_private int
coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
    struct magic **ma, uint32_t *nma)
{
	uint32_t i, mentrycount = 0;
	size_t slen;

	for (i = 0; i < nme; i++)
		mentrycount += me[i].cont_count;

	if (mentrycount == 0) {
		*ma = NULL;
		*nma = 0;
		return 0;
	}

	slen = sizeof(**ma) * mentrycount;
	if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
		file_oomem(ms, slen);
		return -1;
	}

	mentrycount = 0;
	for (i = 0; i < nme; i++) {
		(void)memcpy(*ma + mentrycount, me[i].mp,
		    me[i].cont_count * sizeof(**ma));
		mentrycount += me[i].cont_count;
	}
	*nma = mentrycount;
	return 0;
}

file_private void
magic_entry_free(struct magic_entry *me, uint32_t nme)
{
	uint32_t i;
	if (me == NULL)
		return;
	for (i = 0; i < nme; i++)
		free(me[i].mp);
	free(me);
}

file_private struct magic_map *
apprentice_load(struct magic_set *ms, const char *fn, int action)
{
	int errs = 0;
	uint32_t i, j;
	size_t files = 0, maxfiles = 0;
	char **filearr = NULL, *mfn;
	struct stat st;
	struct magic_map *map;
	struct magic_entry_set mset[MAGIC_SETS];
	DIR *dir;
	struct dirent *d;

	memset(mset, 0, sizeof(mset));
	ms->flags |= MAGIC_CHECK;	/* Enable checks for parsed files */


	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
	{
		file_oomem(ms, sizeof(*map));
		return NULL;
	}
	map->type = MAP_TYPE_MALLOC;

	/* print silly verbose header for USG compat. */
	if (action == FILE_CHECK)
		(void)fprintf(stderr, "%s\n", usg_hdr);

	/* load directory or file */
	if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
		dir = opendir(fn);
		if (!dir) {
			errs++;
			goto out;
		}
		while ((d = readdir(dir)) != NULL) {
			if (d->d_name[0] == '.')
				continue;
			if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
				file_oomem(ms,
				    strlen(fn) + strlen(d->d_name) + 2);
				errs++;
				closedir(dir);
				goto out;
			}
			if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
				free(mfn);
				continue;
			}
			if (files >= maxfiles) {
				size_t mlen;
				char **nfilearr;
				maxfiles = (maxfiles + 1) * 2;
				mlen = maxfiles * sizeof(*filearr);
				if ((nfilearr = CAST(char **,
				    realloc(filearr, mlen))) == NULL) {
					file_oomem(ms, mlen);
					free(mfn);
					closedir(dir);
					errs++;
					goto out;
				}
				filearr = nfilearr;
			}
			filearr[files++] = mfn;
		}
		closedir(dir);
		if (filearr) {
			qsort(filearr, files, sizeof(*filearr), cmpstrp);
			for (i = 0; i < files; i++) {
				load_1(ms, action, filearr[i], &errs, mset);
				free(filearr[i]);
			}
			free(filearr);
			filearr = NULL;
		}
	} else
		load_1(ms, action, fn, &errs, mset);
	if (errs)
		goto out;

	for (j = 0; j < MAGIC_SETS; j++) {
		/* Set types of tests */
		for (i = 0; i < mset[j].count; ) {
			if (mset[j].me[i].mp->cont_level != 0) {
				i++;
				continue;
			}
			i = set_text_binary(ms, mset[j].me, mset[j].count, i);
		}
		if (mset[j].me)
			qsort(mset[j].me, mset[j].count, sizeof(*mset[0].me),
			    apprentice_sort);

		/*
		 * Make sure that any level 0 "default" line is last
		 * (if one exists).
		 */
		set_last_default(ms, mset[j].me, mset[j].count);

		/* coalesce per file arrays into a single one, if needed */
		if (mset[j].count == 0)
			continue;

		if (coalesce_entries(ms, mset[j].me, mset[j].count,
		    &map->magic[j], &map->nmagic[j]) == -1) {
			errs++;
			goto out;
		}
	}

out:
	free(filearr);
	for (j = 0; j < MAGIC_SETS; j++)
		magic_entry_free(mset[j].me, mset[j].count);

	if (errs) {
		apprentice_unmap(map);
		return NULL;
	}
	return map;
}

/*
 * extend the sign bit if the comparison is to be signed
 */
file_protected uint64_t
file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
{
	if (!(m->flag & UNSIGNED)) {
		switch(m->type) {
		/*
		 * Do not remove the casts below.  They are
		 * vital.  When later compared with the data,
		 * the sign extension must have happened.
		 */
		case FILE_BYTE:
			v = CAST(signed char,  v);
			break;
		case FILE_SHORT:
		case FILE_BESHORT:
		case FILE_LESHORT:
			v = CAST(short, v);
			break;
		case FILE_DATE:
		case FILE_BEDATE:
		case FILE_LEDATE:
		case FILE_MEDATE:
		case FILE_LDATE:
		case FILE_BELDATE:
		case FILE_LELDATE:
		case FILE_MELDATE:
		case FILE_LONG:
		case FILE_BELONG:
		case FILE_LELONG:
		case FILE_MELONG:
		case FILE_FLOAT:
		case FILE_BEFLOAT:
		case FILE_LEFLOAT:
		case FILE_MSDOSDATE:
		case FILE_BEMSDOSDATE:
		case FILE_LEMSDOSDATE:
		case FILE_MSDOSTIME:
		case FILE_BEMSDOSTIME:
		case FILE_LEMSDOSTIME:
			v = CAST(int32_t, v);
			break;
		case FILE_QUAD:
		case FILE_BEQUAD:
		case FILE_LEQUAD:
		case FILE_QDATE:
		case FILE_QLDATE:
		case FILE_QWDATE:
		case FILE_BEQDATE:
		case FILE_BEQLDATE:
		case FILE_BEQWDATE:
		case FILE_LEQDATE:
		case FILE_LEQLDATE:
		case FILE_LEQWDATE:
		case FILE_DOUBLE:
		case FILE_BEDOUBLE:
		case FILE_LEDOUBLE:
		case FILE_OFFSET:
		case FILE_BEVARINT:
		case FILE_LEVARINT:
			v = CAST(int64_t, v);
			break;
		case FILE_STRING:
		case FILE_PSTRING:
		case FILE_BESTRING16:
		case FILE_LESTRING16:
		case FILE_REGEX:
		case FILE_SEARCH:
		case FILE_DEFAULT:
		case FILE_INDIRECT:
		case FILE_NAME:
		case FILE_USE:
		case FILE_CLEAR:
		case FILE_DER:
		case FILE_GUID:
		case FILE_OCTAL:
			break;
		default:
			if (ms->flags & MAGIC_CHECK)
			    file_magwarn(ms, "cannot happen: m->type=%d\n",
				    m->type);
			return FILE_BADSIZE;
		}
	}
	return v;
}

file_private int
string_modifier_check(struct magic_set *ms, struct magic *m)
{
	if ((ms->flags & MAGIC_CHECK) == 0)
		return 0;

	if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
	    (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
		file_magwarn(ms,
		    "'/BHhLl' modifiers are only allowed for pascal strings\n");
		return -1;
	}
	switch (m->type) {
	case FILE_BESTRING16:
	case FILE_LESTRING16:
		if (m->str_flags != 0) {
			file_magwarn(ms,
			    "no modifiers allowed for 16-bit strings\n");
			return -1;
		}
		break;
	case FILE_STRING:
	case FILE_PSTRING:
		if ((m->str_flags & REGEX_OFFSET_START) != 0) {
			file_magwarn(ms,
			    "'/%c' only allowed on regex and search\n",
			    CHAR_REGEX_OFFSET_START);
			return -1;
		}
		break;
	case FILE_SEARCH:
		if (m->str_range == 0) {
			file_magwarn(ms,
			    "missing range; defaulting to %d\n",
                            STRING_DEFAULT_RANGE);
			m->str_range = STRING_DEFAULT_RANGE;
			return -1;
		}
		break;
	case FILE_REGEX:
		if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
			file_magwarn(ms, "'/%c' not allowed on regex\n",
			    CHAR_COMPACT_WHITESPACE);
			return -1;
		}
		if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
			file_magwarn(ms, "'/%c' not allowed on regex\n",
			    CHAR_COMPACT_OPTIONAL_WHITESPACE);
			return -1;
		}
		break;
	default:
		file_magwarn(ms, "coding error: m->type=%d\n",
		    m->type);
		return -1;
	}
	return 0;
}

file_private int
get_op(char c)
{
	switch (c) {
	case '&':
		return FILE_OPAND;
	case '|':
		return FILE_OPOR;
	case '^':
		return FILE_OPXOR;
	case '+':
		return FILE_OPADD;
	case '-':
		return FILE_OPMINUS;
	case '*':
		return FILE_OPMULTIPLY;
	case '/':
		return FILE_OPDIVIDE;
	case '%':
		return FILE_OPMODULO;
	default:
		return -1;
	}
}

#ifdef ENABLE_CONDITIONALS
file_private int
get_cond(const char *l, const char **t)
{
	static const struct cond_tbl_s {
		char name[8];
		size_t len;
		int cond;
	} cond_tbl[] = {
		{ "if",		2,	COND_IF },
		{ "elif",	4,	COND_ELIF },
		{ "else",	4,	COND_ELSE },
		{ "",		0,	COND_NONE },
	};
	const struct cond_tbl_s *p;

	for (p = cond_tbl; p->len; p++) {
		if (strncmp(l, p->name, p->len) == 0 &&
		    isspace(CAST(unsigned char, l[p->len]))) {
			if (t)
				*t = l + p->len;
			break;
		}
	}
	return p->cond;
}

file_private int
check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
{
	int last_cond;
	last_cond = ms->c.li[cont_level].last_cond;

	switch (cond) {
	case COND_IF:
		if (last_cond != COND_NONE && last_cond != COND_ELIF) {
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "syntax error: `if'");
			return -1;
		}
		last_cond = COND_IF;
		break;

	case COND_ELIF:
		if (last_cond != COND_IF && last_cond != COND_ELIF) {
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "syntax error: `elif'");
			return -1;
		}
		last_cond = COND_ELIF;
		break;

	case COND_ELSE:
		if (last_cond != COND_IF && last_cond != COND_ELIF) {
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "syntax error: `else'");
			return -1;
		}
		last_cond = COND_NONE;
		break;

	case COND_NONE:
		last_cond = COND_NONE;
		break;
	}

	ms->c.li[cont_level].last_cond = last_cond;
	return 0;
}
#endif /* ENABLE_CONDITIONALS */

file_private int
parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
{
	const char *l = *lp;

	while (!isspace(CAST(unsigned char, *++l)))
		switch (*l) {
		case CHAR_INDIRECT_RELATIVE:
			m->str_flags |= INDIRECT_RELATIVE;
			break;
		default:
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "indirect modifier `%c' "
					"invalid", *l);
			*lp = l;
			return -1;
		}
	*lp = l;
	return 0;
}

file_private void
parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
    int op)
{
	const char *l = *lp;
	char *t;
	uint64_t val;

	++l;
	m->mask_op |= op;
	val = CAST(uint64_t, strtoull(l, &t, 0));
	l = t;
	m->num_mask = file_signextend(ms, m, val);
	eatsize(&l);
	*lp = l;
}

file_private int
parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
{
	const char *l = *lp;
	char *t;
	int have_range = 0;

	while (!isspace(CAST(unsigned char, *++l))) {
		switch (*l) {
		case '0':  case '1':  case '2':
		case '3':  case '4':  case '5':
		case '6':  case '7':  case '8':
		case '9':
			if (have_range && (ms->flags & MAGIC_CHECK))
				file_magwarn(ms, "multiple ranges");
			have_range = 1;
			m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
			if (m->str_range == 0)
				file_magwarn(ms, "zero range");
			l = t - 1;
			break;
		case CHAR_COMPACT_WHITESPACE:
			m->str_flags |= STRING_COMPACT_WHITESPACE;
			break;
		case CHAR_COMPACT_OPTIONAL_WHITESPACE:
			m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
			break;
		case CHAR_IGNORE_LOWERCASE:
			m->str_flags |= STRING_IGNORE_LOWERCASE;
			break;
		case CHAR_IGNORE_UPPERCASE:
			m->str_flags |= STRING_IGNORE_UPPERCASE;
			break;
		case CHAR_REGEX_OFFSET_START:
			m->str_flags |= REGEX_OFFSET_START;
			break;
		case CHAR_BINTEST:
			m->str_flags |= STRING_BINTEST;
			break;
		case CHAR_TEXTTEST:
			m->str_flags |= STRING_TEXTTEST;
			break;
		case CHAR_TRIM:
			m->str_flags |= STRING_TRIM;
			break;
		case CHAR_FULL_WORD:
			m->str_flags |= STRING_FULL_WORD;
			break;
		case CHAR_PSTRING_1_LE:
#define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
			if (m->type != FILE_PSTRING)
				goto bad;
			SET_LENGTH(PSTRING_1_LE);
			break;
		case CHAR_PSTRING_2_BE:
			if (m->type != FILE_PSTRING)
				goto bad;
			SET_LENGTH(PSTRING_2_BE);
			break;
		case CHAR_PSTRING_2_LE:
			if (m->type != FILE_PSTRING)
				goto bad;
			SET_LENGTH(PSTRING_2_LE);
			break;
		case CHAR_PSTRING_4_BE:
			if (m->type != FILE_PSTRING)
				goto bad;
			SET_LENGTH(PSTRING_4_BE);
			break;
		case CHAR_PSTRING_4_LE:
			switch (m->type) {
			case FILE_PSTRING:
			case FILE_REGEX:
				break;
			default:
				goto bad;
			}
			SET_LENGTH(PSTRING_4_LE);
			break;
		case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
			if (m->type != FILE_PSTRING)
				goto bad;
			m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
			break;
		default:
		bad:
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "string modifier `%c' "
					"invalid", *l);
			goto out;
		}
		/* allow multiple '/' for readability */
		if (l[1] == '/' && !isspace(CAST(unsigned char, l[2])))
			l++;
	}
	if (string_modifier_check(ms, m) == -1)
		goto out;
	*lp = l;
	return 0;
out:
	*lp = l;
	return -1;
}

/*
 * parse one line from magic file, put into magic[index++] if valid
 */
file_private int
parse(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t lineno, int action)
{
#ifdef ENABLE_CONDITIONALS
	static uint32_t last_cont_level = 0;
#endif
	size_t i;
	struct magic *m;
	const char *l = line;
	char *t;
	int op;
	uint32_t cont_level;
	int32_t diff;

	cont_level = 0;

	/*
	 * Parse the offset.
	 */
	while (*l == '>') {
		++l;		/* step over */
		cont_level++;
	}
#ifdef ENABLE_CONDITIONALS
	if (cont_level == 0 || cont_level > last_cont_level)
		if (file_check_mem(ms, cont_level) == -1)
			return -1;
	last_cont_level = cont_level;
#endif
	if (cont_level != 0) {
		if (me->mp == NULL) {
			file_magerror(ms, "No current entry for continuation");
			return -1;
		}
		if (me->cont_count == 0) {
			file_magerror(ms, "Continuations present with 0 count");
			return -1;
		}
		m = &me->mp[me->cont_count - 1];
		diff = CAST(int32_t, cont_level) - CAST(int32_t, m->cont_level);
		if (diff > 1)
			file_magwarn(ms, "New continuation level %u is more "
			    "than one larger than current level %u", cont_level,
			    m->cont_level);
		if (me->cont_count == me->max_count) {
			struct magic *nm;
			size_t cnt = me->max_count + ALLOC_CHUNK;
			if ((nm = CAST(struct magic *, realloc(me->mp,
			    sizeof(*nm) * cnt))) == NULL) {
				file_oomem(ms, sizeof(*nm) * cnt);
				return -1;
			}
			me->mp = nm;
			me->max_count = CAST(uint32_t, cnt);
		}
		m = &me->mp[me->cont_count++];
		(void)memset(m, 0, sizeof(*m));
		m->cont_level = cont_level;
	} else {
		static const size_t len = sizeof(*m) * ALLOC_CHUNK;
		if (me->mp != NULL)
			return 1;
		if ((m = CAST(struct magic *, malloc(len))) == NULL) {
			file_oomem(ms, len);
			return -1;
		}
		me->mp = m;
		me->max_count = ALLOC_CHUNK;
		(void)memset(m, 0, sizeof(*m));
		m->factor_op = FILE_FACTOR_OP_NONE;
		m->cont_level = 0;
		me->cont_count = 1;
	}
	m->lineno = CAST(uint32_t, lineno);

	if (*l == '&') {  /* m->cont_level == 0 checked below. */
                ++l;            /* step over */
                m->flag |= OFFADD;
        }
	if (*l == '(') {
		++l;		/* step over */
		m->flag |= INDIR;
		if (m->flag & OFFADD)
			m->flag = (m->flag & ~OFFADD) | INDIROFFADD;

		if (*l == '&') {  /* m->cont_level == 0 checked below */
			++l;            /* step over */
			m->flag |= OFFADD;
		}
	}
	/* Indirect offsets are not valid at level 0. */
	if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "relative offset at level 0");
		return -1;
	}

	/* get offset, then skip over it */
	if (*l == '-') {
		++l;            /* step over */
		m->flag |= OFFNEGATIVE;
	}
	m->offset = CAST(int32_t, strtol(l, &t, 0));
        if (l == t) {
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "offset `%s' invalid", l);
		return -1;
	}

        l = t;

	if (m->flag & INDIR) {
		m->in_type = FILE_LONG;
		m->in_offset = 0;
		m->in_op = 0;
		/*
		 * read [.,lbs][+-]nnnnn)
		 */
		if (*l == '.' || *l == ',') {
			if (*l == ',')
				m->in_op |= FILE_OPSIGNED;
			l++;
			switch (*l) {
			case 'l':
				m->in_type = FILE_LELONG;
				break;
			case 'L':
				m->in_type = FILE_BELONG;
				break;
			case 'm':
				m->in_type = FILE_MELONG;
				break;
			case 'h':
			case 's':
				m->in_type = FILE_LESHORT;
				break;
			case 'H':
			case 'S':
				m->in_type = FILE_BESHORT;
				break;
			case 'c':
			case 'b':
			case 'C':
			case 'B':
				m->in_type = FILE_BYTE;
				break;
			case 'e':
			case 'f':
			case 'g':
				m->in_type = FILE_LEDOUBLE;
				break;
			case 'E':
			case 'F':
			case 'G':
				m->in_type = FILE_BEDOUBLE;
				break;
			case 'i':
				m->in_type = FILE_LEID3;
				break;
			case 'I':
				m->in_type = FILE_BEID3;
				break;
			case 'o':
				m->in_type = FILE_OCTAL;
				break;
			case 'q':
				m->in_type = FILE_LEQUAD;
				break;
			case 'Q':
				m->in_type = FILE_BEQUAD;
				break;
			default:
				if (ms->flags & MAGIC_CHECK)
					file_magwarn(ms,
					    "indirect offset type `%c' invalid",
					    *l);
				return -1;
			}
			l++;
		}

		if (*l == '~') {
			m->in_op |= FILE_OPINVERSE;
			l++;
		}
		if ((op = get_op(*l)) != -1) {
			m->in_op |= op;
			l++;
		}
		if (*l == '(') {
			m->in_op |= FILE_OPINDIRECT;
			l++;
		}
		if (isdigit(CAST(unsigned char, *l)) || *l == '-') {
			m->in_offset = CAST(int32_t, strtol(l, &t, 0));
			if (l == t) {
				if (ms->flags & MAGIC_CHECK)
					file_magwarn(ms,
					    "in_offset `%s' invalid", l);
				return -1;
			}
			l = t;
		}
		if (*l++ != ')' ||
		    ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms,
				    "missing ')' in indirect offset");
			return -1;
		}
	}
	EATAB;

#ifdef ENABLE_CONDITIONALS
	m->cond = get_cond(l, &l);
	if (check_cond(ms, m->cond, cont_level) == -1)
		return -1;

	EATAB;
#endif

	/*
	 * Parse the type.
	 */
	if (*l == 'u') {
		/*
		 * Try it as a keyword type prefixed by "u"; match what
		 * follows the "u".  If that fails, try it as an SUS
		 * integer type.
		 */
		m->type = get_type(type_tbl, l + 1, &l);
		if (m->type == FILE_INVALID) {
			/*
			 * Not a keyword type; parse it as an SUS type,
			 * 'u' possibly followed by a number or C/S/L.
			 */
			m->type = get_standard_integer_type(l, &l);
		}
		/* It's unsigned. */
		if (m->type != FILE_INVALID)
			m->flag |= UNSIGNED;
	} else {
		/*
		 * Try it as a keyword type.  If that fails, try it as
		 * an SUS integer type if it begins with "d" or as an
		 * SUS string type if it begins with "s".  In any case,
		 * it's not unsigned.
		 */
		m->type = get_type(type_tbl, l, &l);
		if (m->type == FILE_INVALID) {
			/*
			 * Not a keyword type; parse it as an SUS type,
			 * either 'd' possibly followed by a number or
			 * C/S/L, or just 's'.
			 */
			if (*l == 'd')
				m->type = get_standard_integer_type(l, &l);
			else if (*l == 's'
			    && !isalpha(CAST(unsigned char, l[1]))) {
				m->type = FILE_STRING;
				++l;
			}
		}
	}

	if (m->type == FILE_INVALID) {
		/* Not found - try it as a special keyword. */
		m->type = get_type(special_tbl, l, &l);
	}

	if (m->type == FILE_INVALID) {
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "type `%s' invalid", l);
		return -1;
	}

	if (m->type == FILE_NAME && cont_level != 0) {
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "`name%s' entries can only be "
			    "declared at top level", l);
		return -1;
	}

	/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
	/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */

	m->mask_op = 0;
	if (*l == '~') {
		if (!IS_STRING(m->type))
			m->mask_op |= FILE_OPINVERSE;
		else if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "'~' invalid for string types");
		++l;
	}
	m->str_range = 0;
	m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
	if ((op = get_op(*l)) != -1) {
		if (IS_STRING(m->type)) {
			int r;

			if (op != FILE_OPDIVIDE) {
				if (ms->flags & MAGIC_CHECK)
					file_magwarn(ms,
					    "invalid string/indirect op: "
					    "`%c'", *t);
				return -1;
			}

			if (m->type == FILE_INDIRECT)
				r = parse_indirect_modifier(ms, m, &l);
			else
				r = parse_string_modifier(ms, m, &l);
			if (r == -1)
				return -1;
		} else
			parse_op_modifier(ms, m, &l, op);
	}

	/*
	 * We used to set mask to all 1's here, instead let's just not do
	 * anything if mask = 0 (unless you have a better idea)
	 */
	EATAB;

	switch (*l) {
	case '>':
	case '<':
  		m->reln = *l;
  		++l;
		if (*l == '=') {
			if (ms->flags & MAGIC_CHECK) {
				file_magwarn(ms, "%c= not supported",
				    m->reln);
				return -1;
			}
		   ++l;
		}
		break;
	/* Old-style anding: "0 byte &0x80 dynamically linked" */
	case '&':
	case '^':
	case '=':
  		m->reln = *l;
  		++l;
		if (*l == '=') {
		   /* HP compat: ignore &= etc. */
		   ++l;
		}
		break;
	case '!':
		m->reln = *l;
		++l;
		break;
	default:
  		m->reln = '=';	/* the default relation */
		if (*l == 'x' && ((isascii(CAST(unsigned char, l[1])) &&
		    isspace(CAST(unsigned char, l[1]))) || !l[1])) {
			m->reln = *l;
			++l;
		}
		break;
	}
	/*
	 * Grab the value part, except for an 'x' reln.
	 */
	if (m->reln != 'x' && getvalue(ms, m, &l, action))
		return -1;

	/*
	 * TODO finish this macro and start using it!
	 * #define offsetcheck {if (offset > ms->bytes_max -1)
	 *	magwarn("offset too big"); }
	 */

	/*
	 * Now get last part - the description
	 */
	EATAB;
	if (l[0] == '\b') {
		++l;
		m->flag |= NOSPACE;
	} else if ((l[0] == '\\') && (l[1] == 'b')) {
		++l;
		++l;
		m->flag |= NOSPACE;
	}
	for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
		continue;
	if (i == sizeof(m->desc)) {
		m->desc[sizeof(m->desc) - 1] = '\0';
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "description `%s' truncated", m->desc);
	}

        /*
	 * We only do this check while compiling, or if any of the magic
	 * files were not compiled.
         */
        if (ms->flags & MAGIC_CHECK) {
		if (check_format(ms, m) == -1)
			return -1;
	}
#ifndef COMPILE_ONLY
	if (action == FILE_CHECK) {
		file_mdump(m);
	}
#endif
	m->mimetype[0] = '\0';		/* initialise MIME type to none */
	return 0;
}

/*
 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
 * if valid
 */
/*ARGSUSED*/
file_private int
parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t len __attribute__((__unused__)))
{
	const char *l = line;
	char *el;
	unsigned long factor;
	char sbuf[512];
	struct magic *m = &me->mp[0];

	if (m->factor_op != FILE_FACTOR_OP_NONE) {
		file_magwarn(ms,
		    "Current entry already has a strength type: %c %d",
		    m->factor_op, m->factor);
		return -1;
	}
	if (m->type == FILE_NAME) {
		file_magwarn(ms, "%s: Strength setting is not supported in "
		    "\"name\" magic entries",
		    file_printable(ms, sbuf, sizeof(sbuf), m->value.s,
		    sizeof(m->value.s)));
		return -1;
	}
	EATAB;
	switch (*l) {
	case FILE_FACTOR_OP_NONE:
		break;
	case FILE_FACTOR_OP_PLUS:
	case FILE_FACTOR_OP_MINUS:
	case FILE_FACTOR_OP_TIMES:
	case FILE_FACTOR_OP_DIV:
		m->factor_op = *l++;
		break;
	default:
		file_magwarn(ms, "Unknown factor op `%c'", *l);
		return -1;
	}
	EATAB;
	factor = strtoul(l, &el, 0);
	if (factor > 255) {
		file_magwarn(ms, "Too large factor `%lu'", factor);
		goto out;
	}
	if (*el && !isspace(CAST(unsigned char, *el))) {
		file_magwarn(ms, "Bad factor `%s'", l);
		goto out;
	}
	m->factor = CAST(uint8_t, factor);
	if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
		file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
		    m->factor_op, m->factor);
		goto out;
	}
	return 0;
out:
	m->factor_op = FILE_FACTOR_OP_NONE;
	m->factor = 0;
	return -1;
}

file_private int
goodchar(unsigned char x, const char *extra)
{
	return (isascii(x) && isalnum(x)) || strchr(extra, x);
}

file_private int
parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t llen, off_t off, size_t len, const char *name, const char *extra,
    int nt)
{
	size_t i;
	const char *l = line;
	struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
	char *buf = CAST(char *, CAST(void *, m)) + off;

	if (buf[0] != '\0') {
		len = nt ? strlen(buf) : len;
		file_magwarn(ms, "Current entry already has a %s type "
		    "`%.*s', new type `%s'", name, CAST(int, len), buf, l);
		return -1;
	}

	if (*m->desc == '\0') {
		file_magwarn(ms, "Current entry does not yet have a "
		    "description for adding a %s type", name);
		return -1;
	}

	EATAB;
	for (i = 0; *l && i < llen && i < len && goodchar(*l, extra);
	    buf[i++] = *l++)
		continue;

	if (i == len && *l) {
		if (nt)
			buf[len - 1] = '\0';
		if (ms->flags & MAGIC_CHECK)
			file_magwarn(ms, "%s type `%s' truncated %"
			    SIZE_T_FORMAT "u", name, line, i);
	} else {
		if (!isspace(CAST(unsigned char, *l)) && !goodchar(*l, extra))
			file_magwarn(ms, "%s type `%s' has bad char '%c'",
			    name, line, *l);
		if (nt)
			buf[i] = '\0';
	}

	if (i > 0)
		return 0;

	file_magerror(ms, "Bad magic entry '%s'", line);
	return -1;
}

/*
 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
 * magic[index - 1]
 */
file_private int
parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t len)
{
	return parse_extra(ms, me, line, len,
	    CAST(off_t, offsetof(struct magic, apple)),
	    sizeof(me->mp[0].apple), "APPLE", "!+-./?", 0);
}

/*
 * Parse a comma-separated list of extensions
 */
file_private int
parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t len)
{
	return parse_extra(ms, me, line, len,
	    CAST(off_t, offsetof(struct magic, ext)),
	    sizeof(me->mp[0].ext), "EXTENSION", ",!+-/@?_$&~", 0);
	    /* & for b&w */
	    /* ~ for journal~ */
}

/*
 * parse a MIME annotation line from magic file, put into magic[index - 1]
 * if valid
 */
file_private int
parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line,
    size_t len)
{
	return parse_extra(ms, me, line, len,
	    CAST(off_t, offsetof(struct magic, mimetype)),
	    sizeof(me->mp[0].mimetype), "MIME", "+-/.$?:{}", 1);
}

file_private int
check_format_type(const char *ptr, int type, const char **estr)
{
	int quad = 0, h;
	size_t len, cnt;
	if (*ptr == '\0') {
		/* Missing format string; bad */
		*estr = "missing format spec";
		return -1;
	}

	switch (file_formats[type]) {
	case FILE_FMT_QUAD:
		quad = 1;
		/*FALLTHROUGH*/
	case FILE_FMT_NUM:
		if (quad == 0) {
			switch (type) {
			case FILE_BYTE:
				h = 2;
				break;
			case FILE_SHORT:
			case FILE_BESHORT:
			case FILE_LESHORT:
				h = 1;
				break;
			case FILE_LONG:
			case FILE_BELONG:
			case FILE_LELONG:
			case FILE_MELONG:
			case FILE_LEID3:
			case FILE_BEID3:
			case FILE_INDIRECT:
				h = 0;
				break;
			default:
				fprintf(stderr, "Bad number format %d", type);
				abort();
			}
		} else
			h = 0;
		while (*ptr && strchr("-.#", *ptr) != NULL)
			ptr++;
#define CHECKLEN() do { \
	for (len = cnt = 0; isdigit(CAST(unsigned char, *ptr)); ptr++, cnt++) \
		len = len * 10 + (*ptr - '0'); \
	if (cnt > 5 || len > 1024) \
		goto toolong; \
} while (/*CONSTCOND*/0)

		CHECKLEN();
		if (*ptr == '.')
			ptr++;
		CHECKLEN();
		if (quad) {
			if (*ptr++ != 'l')
				goto invalid;
			if (*ptr++ != 'l')
				goto invalid;
		}

		switch (*ptr++) {
#ifdef STRICT_FORMAT 	/* "long" formats are int formats for us */
		/* so don't accept the 'l' modifier */
		case 'l':
			switch (*ptr++) {
			case 'i':
			case 'd':
			case 'u':
			case 'o':
			case 'x':
			case 'X':
				if (h == 0)
					return 0;
				/*FALLTHROUGH*/
			default:
				goto invalid;
			}

		/*
		 * Don't accept h and hh modifiers. They make writing
		 * magic entries more complicated, for very little benefit
		 */
		case 'h':
			if (h-- <= 0)
				goto invalid;
			switch (*ptr++) {
			case 'h':
				if (h-- <= 0)
					goto invalid;
				switch (*ptr++) {
				case 'i':
				case 'd':
				case 'u':
				case 'o':
				case 'x':
				case 'X':
					return 0;
				default:
					goto invalid;
				}
			case 'i':
			case 'd':
			case 'u':
			case 'o':
			case 'x':
			case 'X':
				if (h == 0)
					return 0;
				/*FALLTHROUGH*/
			default:
				goto invalid;
			}
#endif
		case 'c':
			if (h == 2)
				return 0;
			goto invalid;
		case 'i':
		case 'd':
		case 'u':
		case 'o':
		case 'x':
		case 'X':
#ifdef STRICT_FORMAT
			if (h == 0)
				return 0;
			/*FALLTHROUGH*/
#else
			return 0;
#endif
		default:
			goto invalid;
		}

	case FILE_FMT_FLOAT:
	case FILE_FMT_DOUBLE:
		if (*ptr == '-')
			ptr++;
		if (*ptr == '.')
			ptr++;
		CHECKLEN();
		if (*ptr == '.')
			ptr++;
		CHECKLEN();
		switch (*ptr++) {
		case 'e':
		case 'E':
		case 'f':
		case 'F':
		case 'g':
		case 'G':
			return 0;

		default:
			goto invalid;
		}


	case FILE_FMT_STR:
		if (*ptr == '-')
			ptr++;
		while (isdigit(CAST(unsigned char, *ptr)))
			ptr++;
		if (*ptr == '.') {
			ptr++;
			while (isdigit(CAST(unsigned char , *ptr)))
				ptr++;
		}

		switch (*ptr++) {
		case 's':
			return 0;
		default:
			goto invalid;
		}

	default:
		/* internal error */
		fprintf(stderr, "Bad file format %d", type);
		abort();
	}
invalid:
	*estr = "not valid";
	return -1;
toolong:
	*estr = "too long";
	return -1;
}

/*
 * Check that the optional printf format in description matches
 * the type of the magic.
 */
file_private int
check_format(struct magic_set *ms, struct magic *m)
{
	char *ptr;
	const char *estr;

	for (ptr = m->desc; *ptr; ptr++)
		if (*ptr == '%')
			break;
	if (*ptr == '\0') {
		/* No format string; ok */
		return 1;
	}

	assert(file_nformats == file_nnames);

	if (m->type >= file_nformats) {
		file_magwarn(ms, "Internal error inconsistency between "
		    "m->type and format strings");
		return -1;
	}
	if (file_formats[m->type] == FILE_FMT_NONE) {
		file_magwarn(ms, "No format string for `%s' with description "
		    "`%s'", m->desc, file_names[m->type]);
		return -1;
	}

	ptr++;
	if (check_format_type(ptr, m->type, &estr) == -1) {
		/*
		 * TODO: this error message is unhelpful if the format
		 * string is not one character long
		 */
		file_magwarn(ms, "Printf format is %s for type "
		    "`%s' in description `%s'", estr,
		    file_names[m->type], m->desc);
		return -1;
	}

	for (; *ptr; ptr++) {
		if (*ptr == '%') {
			file_magwarn(ms,
			    "Too many format strings (should have at most one) "
			    "for `%s' with description `%s'",
			    file_names[m->type], m->desc);
			return -1;
		}
	}
	return 0;
}

/*
 * Read a numeric value from a pointer, into the value union of a magic
 * pointer, according to the magic type.  Update the string pointer to point
 * just after the number read.  Return 0 for success, non-zero for failure.
 */
file_private int
getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
{
	char *ep;
	uint64_t ull;
	int y;

	switch (m->type) {
	case FILE_BESTRING16:
	case FILE_LESTRING16:
	case FILE_STRING:
	case FILE_PSTRING:
	case FILE_REGEX:
	case FILE_SEARCH:
	case FILE_NAME:
	case FILE_USE:
	case FILE_DER:
	case FILE_OCTAL:
		*p = getstr(ms, m, *p, action == FILE_COMPILE);
		if (*p == NULL) {
			if (ms->flags & MAGIC_CHECK)
				file_magwarn(ms, "cannot get string from `%s'",
				    m->value.s);
			return -1;
		}
		if (m->type == FILE_REGEX) {
			file_regex_t rx;
			int rc =
			    file_regcomp(ms, &rx, m->value.s, REG_EXTENDED);
			if (rc == 0) {
				file_regfree(&rx);
			}
			return rc ? -1 : 0;
		}
		return 0;
	default:
		if (m->reln == 'x')
			return 0;
		break;
	}

	switch (m->type) {
	case FILE_FLOAT:
	case FILE_BEFLOAT:
	case FILE_LEFLOAT:
		errno = 0;
#ifdef HAVE_STRTOF
		m->value.f = strtof(*p, &ep);
#else
		m->value.f = (float)strtod(*p, &ep);
#endif
		if (errno == 0)
			*p = ep;
		return 0;
	case FILE_DOUBLE:
	case FILE_BEDOUBLE:
	case FILE_LEDOUBLE:
		errno = 0;
		m->value.d = strtod(*p, &ep);
		if (errno == 0)
			*p = ep;
		return 0;
	case FILE_GUID:
		if (file_parse_guid(*p, m->value.guid) == -1)
			return -1;
		*p += FILE_GUID_SIZE - 1;
		return 0;
	default:
		errno = 0;
		ull = CAST(uint64_t, strtoull(*p, &ep, 0));
		m->value.q = file_signextend(ms, m, ull);
		if (*p == ep) {
			file_magwarn(ms, "Unparsable number `%s'", *p);
			return -1;
		} else {
			size_t ts = typesize(m->type);
			uint64_t x;
			const char *q;

			if (ts == FILE_BADSIZE) {
				file_magwarn(ms,
				    "Expected numeric type got `%s'",
				    type_tbl[m->type].name);
				return -1;
			}
			for (q = *p; isspace(CAST(unsigned char, *q)); q++)
				continue;
			if (*q == '-' && ull != UINT64_MAX)
				ull = -CAST(int64_t, ull);
			switch (ts) {
			case 1:
				x = CAST(uint64_t, ull & ~0xffULL);
				y = (x & ~0xffULL) != ~0xffULL;
				break;
			case 2:
				x = CAST(uint64_t, ull & ~0xffffULL);
				y = (x & ~0xffffULL) != ~0xffffULL;
				break;
			case 4:
				x = CAST(uint64_t, ull & ~0xffffffffULL);
				y = (x & ~0xffffffffULL) != ~0xffffffffULL;
				break;
			case 8:
				x = 0;
				y = 0;
				break;
			default:
				fprintf(stderr, "Bad width %zu", ts);
				abort();
			}
			if (x && y) {
				file_magwarn(ms, "Overflow for numeric"
				    " type `%s' value %#" PRIx64,
				    type_tbl[m->type].name, ull);
				return -1;
			}
		}
		if (errno == 0) {
			*p = ep;
			eatsize(p);
		}
		return 0;
	}
}

/*
 * Convert a string containing C character escapes.  Stop at an unescaped
 * space or tab.
 * Copy the converted version to "m->value.s", and the length in m->vallen.
 * Return updated scan pointer as function result. Warn if set.
 */
file_private const char *
getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
{
	const char *origs = s;
	char	*p = m->value.s;
	size_t  plen = sizeof(m->value.s);
	char 	*origp = p;
	char	*pmax = p + plen - 1;
	int	c;
	int	val;
	size_t	bracket_nesting = 0;

	while ((c = *s++) != '\0') {
		if (isspace(CAST(unsigned char, c)))
			break;
		if (p >= pmax) {
			file_error(ms, 0, "string too long: `%s'", origs);
			return NULL;
		}
		if (c != '\\') {
		    if (c == '[') {
			    bracket_nesting++;
		    }
		    if (c == ']' && bracket_nesting > 0) {
			    bracket_nesting--;
		    }
		    *p++ = CAST(char, c);
		    continue;
		}
		switch(c = *s++) {

		case '\0':
			if (warn)
				file_magwarn(ms, "incomplete escape");
			s--;
			goto out;
		case '.':
			if (m->type == FILE_REGEX &&
			    bracket_nesting == 0 && warn) {
				file_magwarn(ms, "escaped dot ('.') found, "
				    "use \\\\. instead");
			}
			warn = 0; /* already did */
			/*FALLTHROUGH*/
		case '\t':
			if (warn) {
				file_magwarn(ms,
				    "escaped tab found, use \\\\t instead");
				warn = 0;	/* already did */
			}
			/*FALLTHROUGH*/
		default:
			if (warn) {
				if (isprint(CAST(unsigned char, c))) {
					/* Allow escaping of
					 * ``relations'' */
					if (strchr("<>&^=!", c) == NULL
					    && (m->type != FILE_REGEX ||
					    strchr("[]().*?^$|{}", c)
					    == NULL)) {
						file_magwarn(ms, "no "
						    "need to escape "
						    "`%c'", c);
					}
				} else {
					file_magwarn(ms,
					    "unknown escape sequence: "
					    "\\%03o", c);
				}
			}
			/*FALLTHROUGH*/
		/* space, perhaps force people to use \040? */
		case ' ':
#if 0
		/*
		 * Other things people escape, but shouldn't need to,
		 * so we disallow them
		 */
		case '\'':
		case '"':
		case '?':
#endif
		/* Relations */
		case '>':
		case '<':
		case '&':
		case '^':
		case '=':
		case '!':
		/* and backslash itself */
		case '\\':
			*p++ = CAST(char, c);
			break;

		case 'a':
			*p++ = '\a';
			break;

		case 'b':
			*p++ = '\b';
			break;

		case 'f':
			*p++ = '\f';
			break;

		case 'n':
			*p++ = '\n';
			break;

		case 'r':
			*p++ = '\r';
			break;

		case 't':
			*p++ = '\t';
			break;

		case 'v':
			*p++ = '\v';
			break;

		/* \ and up to 3 octal digits */
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
			val = c - '0';
			c = *s++;  /* try for 2 */
			if (c >= '0' && c <= '7') {
				val = (val << 3) | (c - '0');
				c = *s++;  /* try for 3 */
				if (c >= '0' && c <= '7')
					val = (val << 3) | (c-'0');
				else
					--s;
			}
			else
				--s;
			*p++ = CAST(char, val);
			break;

		/* \x and up to 2 hex digits */
		case 'x':
			val = 'x';	/* Default if no digits */
			c = hextoint(*s++);	/* Get next char */
			if (c >= 0) {
				val = c;
				c = hextoint(*s++);
				if (c >= 0)
					val = (val << 4) + c;
				else
					--s;
			} else
				--s;
			*p++ = CAST(char, val);
			break;
		}
	}
	--s;
out:
	*p = '\0';
	m->vallen = CAST(unsigned char, (p - origp));
	if (m->type == FILE_PSTRING) {
		size_t l =  file_pstring_length_size(ms, m);
		if (l == FILE_BADSIZE)
			return NULL;
		m->vallen += CAST(unsigned char, l);
	}
	return s;
}


/* Single hex char to int; -1 if not a hex char. */
file_private int
hextoint(int c)
{
	if (!isascii(CAST(unsigned char, c)))
		return -1;
	if (isdigit(CAST(unsigned char, c)))
		return c - '0';
	if ((c >= 'a') && (c <= 'f'))
		return c + 10 - 'a';
	if (( c>= 'A') && (c <= 'F'))
		return c + 10 - 'A';
	return -1;
}


/*
 * Print a string containing C character escapes.
 */
file_protected void
file_showstr(FILE *fp, const char *s, size_t len)
{
	char	c;

	for (;;) {
		if (len == FILE_BADSIZE) {
			c = *s++;
			if (c == '\0')
				break;
		}
		else  {
			if (len-- == 0)
				break;
			c = *s++;
		}
		if (c >= 040 && c <= 0176)	/* TODO isprint && !iscntrl */
			(void) fputc(c, fp);
		else {
			(void) fputc('\\', fp);
			switch (c) {
			case '\a':
				(void) fputc('a', fp);
				break;

			case '\b':
				(void) fputc('b', fp);
				break;

			case '\f':
				(void) fputc('f', fp);
				break;

			case '\n':
				(void) fputc('n', fp);
				break;

			case '\r':
				(void) fputc('r', fp);
				break;

			case '\t':
				(void) fputc('t', fp);
				break;

			case '\v':
				(void) fputc('v', fp);
				break;

			default:
				(void) fprintf(fp, "%.3o", c & 0377);
				break;
			}
		}
	}
}

/*
 * eatsize(): Eat the size spec from a number [eg. 10UL]
 */
file_private void
eatsize(const char **p)
{
	const char *l = *p;

	if (LOWCASE(*l) == 'u')
		l++;

	switch (LOWCASE(*l)) {
	case 'l':    /* long */
	case 's':    /* short */
	case 'h':    /* short */
	case 'b':    /* char/byte */
	case 'c':    /* char/byte */
		l++;
		/*FALLTHROUGH*/
	default:
		break;
	}

	*p = l;
}

/*
 * handle a buffer containing a compiled file.
 */
file_private struct magic_map *
apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
{
	struct magic_map *map;

	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
		file_oomem(ms, sizeof(*map));
		return NULL;
	}
	map->len = len;
	map->p = buf;
	map->type = MAP_TYPE_USER;
	if (check_buffer(ms, map, "buffer") != 0) {
		apprentice_unmap(map);
		return NULL;
	}
	return map;
}

/*
 * handle a compiled file.
 */

file_private struct magic_map *
apprentice_map(struct magic_set *ms, const char *fn)
{
	int fd;
	struct stat st;
	char *dbname = NULL;
	struct magic_map *map;
	struct magic_map *rv = NULL;

	fd = -1;
	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
		file_oomem(ms, sizeof(*map));
		goto error;
	}
	map->type = MAP_TYPE_USER;	/* unspecified */

	if (strncmp(fn, "res@", 4) == 0) {
		map->type = MAP_TYPE_MALLOC;
		_magic_read_res(fn + 4, &map->p, &map->len);
		if (map->p == NULL) {
			file_error(ms, 0, "cannot read_res %s", fn);
			goto error;
		}
		if (check_buffer(ms, map, fn) != 0) {
			goto error;
		}
		return map;
	}

	dbname = mkdbname(ms, fn, 0);
	if (dbname == NULL)
		goto error;

	if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
		goto error;

	if (fstat(fd, &st) == -1) {
		file_error(ms, errno, "cannot stat `%s'", dbname);
		goto error;
	}
	if (st.st_size < 8 || st.st_size > maxoff_t()) {
		file_error(ms, 0, "file `%s' is too %s", dbname,
		    st.st_size < 8 ? "small" : "large");
		goto error;
	}

	map->len = CAST(size_t, st.st_size);
#ifdef QUICK
	map->type = MAP_TYPE_MMAP;
	if ((map->p = mmap(0, CAST(size_t, st.st_size), PROT_READ|PROT_WRITE,
	    MAP_PRIVATE|MAP_FILE, fd, CAST(off_t, 0))) == MAP_FAILED) {
		file_error(ms, errno, "cannot map `%s'", dbname);
		goto error;
	}
#else
	map->type = MAP_TYPE_MALLOC;
	if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
		file_oomem(ms, map->len);
		goto error;
	}
	if (read(fd, map->p, map->len) != (ssize_t)map->len) {
		file_badread(ms);
		goto error;
	}
#endif
	(void)close(fd);
	fd = -1;

	if (check_buffer(ms, map, dbname) != 0) {
		goto error;
	}
#ifdef QUICK
	if (mprotect(map->p, CAST(size_t, st.st_size), PROT_READ) == -1) {
		file_error(ms, errno, "cannot mprotect `%s'", dbname);
		goto error;
	}
#endif

	free(dbname);
	return map;

error:
	if (fd != -1)
		(void)close(fd);
	apprentice_unmap(map);
	free(dbname);
	return rv;
}

file_private int
check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
{
	uint32_t *ptr;
	uint32_t entries, nentries;
	uint32_t version;
	int i, needsbyteswap;

	ptr = CAST(uint32_t *, map->p);
	if (*ptr != MAGICNO) {
		if (swap4(*ptr) != MAGICNO) {
			file_error(ms, 0, "bad magic in `%s'", dbname);
			return -1;
		}
		needsbyteswap = 1;
	} else
		needsbyteswap = 0;
	if (needsbyteswap)
		version = swap4(ptr[1]);
	else
		version = ptr[1];
	if (version != VERSIONNO) {
		file_error(ms, 0, "File %s supports only version %d magic "
		    "files. `%s' is version %d", VERSION,
		    VERSIONNO, dbname, version);
		return -1;
	}
	entries = CAST(uint32_t, map->len / sizeof(struct magic));
	if ((entries * sizeof(struct magic)) != map->len) {
		file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
		    "a multiple of %" SIZE_T_FORMAT "u",
		    dbname, map->len, sizeof(struct magic));
		return -1;
	}
	map->magic[0] = CAST(struct magic *, map->p) + 1;
	nentries = 0;
	for (i = 0; i < MAGIC_SETS; i++) {
		if (needsbyteswap)
			map->nmagic[i] = swap4(ptr[i + 2]);
		else
			map->nmagic[i] = ptr[i + 2];
		if (i != MAGIC_SETS - 1)
			map->magic[i + 1] = map->magic[i] + map->nmagic[i];
		nentries += map->nmagic[i];
	}
	if (entries != nentries + 1) {
		file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
		    dbname, entries, nentries + 1);
		return -1;
	}
	if (needsbyteswap)
		for (i = 0; i < MAGIC_SETS; i++)
			byteswap(map->magic[i], map->nmagic[i]);
	return 0;
}

/*
 * handle an mmaped file.
 */
file_private int
apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
{
	static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
	static const size_t m = sizeof(**map->magic);
	int fd = -1;
	size_t len;
	char *dbname;
	int rv = -1;
	uint32_t i;
	union {
		struct magic m;
		uint32_t h[2 + MAGIC_SETS];
	} hdr;

	dbname = mkdbname(ms, fn, 1);

	if (dbname == NULL)
		goto out;

	if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
	{
		file_error(ms, errno, "cannot open `%s'", dbname);
		goto out;
	}
	memset(&hdr, 0, sizeof(hdr));
	hdr.h[0] = MAGICNO;
	hdr.h[1] = VERSIONNO;
	memcpy(hdr.h + 2, map->nmagic, nm);

	if (write(fd, &hdr, sizeof(hdr)) != CAST(ssize_t, sizeof(hdr))) {
		file_error(ms, errno, "error writing `%s'", dbname);
		goto out2;
	}

	for (i = 0; i < MAGIC_SETS; i++) {
		len = m * map->nmagic[i];
		if (write(fd, map->magic[i], len) != CAST(ssize_t, len)) {
			file_error(ms, errno, "error writing `%s'", dbname);
			goto out2;
		}
	}

	rv = 0;
out2:
	if (fd != -1)
		(void)close(fd);
out:
	apprentice_unmap(map);
	free(dbname);
	return rv;
}

file_private const char ext[] = ".mgc";
/*
 * make a dbname
 */
file_private char *
mkdbname(struct magic_set *ms, const char *fn, int strip)
{
	const char *p, *q;
	char *buf;

	if (strip) {
		if ((p = strrchr(fn, '/')) != NULL)
			fn = ++p;
	}

	for (q = fn; *q; q++)
		continue;
	/* Look for .mgc */
	for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
		if (*p != *q)
			break;

	/* Did not find .mgc, restore q */
	if (p >= ext)
		while (*q)
			q++;

	q++;
	/* Compatibility with old code that looked in .mime */
	if (ms->flags & MAGIC_MIME) {
		if (asprintf(&buf, "%.*s.mime%s", CAST(int, q - fn), fn, ext)
		    < 0)
			return NULL;
		if (access(buf, R_OK) != -1) {
			ms->flags &= MAGIC_MIME_TYPE;
			return buf;
		}
		free(buf);
	}
	if (asprintf(&buf, "%.*s%s", CAST(int, q - fn), fn, ext) < 0)
		return NULL;

	/* Compatibility with old code that looked in .mime */
	if (strstr(fn, ".mime") != NULL)
		ms->flags &= MAGIC_MIME_TYPE;
	return buf;
}

/*
 * Byteswap an mmap'ed file if needed
 */
file_private void
byteswap(struct magic *magic, uint32_t nmagic)
{
	uint32_t i;
	for (i = 0; i < nmagic; i++)
		bs1(&magic[i]);
}

#if !defined(HAVE_BYTESWAP_H) && !defined(HAVE_SYS_BSWAP_H)
/*
 * swap a short
 */
file_private uint16_t
swap2(uint16_t sv)
{
	uint16_t rv;
	uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv));
	uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv));
	d[0] = s[1];
	d[1] = s[0];
	return rv;
}

/*
 * swap an int
 */
file_private uint32_t
swap4(uint32_t sv)
{
	uint32_t rv;
	uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv));
	uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv));
	d[0] = s[3];
	d[1] = s[2];
	d[2] = s[1];
	d[3] = s[0];
	return rv;
}

/*
 * swap a quad
 */
file_private uint64_t
swap8(uint64_t sv)
{
	uint64_t rv;
	uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv));
	uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv));
# if 0
	d[0] = s[3];
	d[1] = s[2];
	d[2] = s[1];
	d[3] = s[0];
	d[4] = s[7];
	d[5] = s[6];
	d[6] = s[5];
	d[7] = s[4];
# else
	d[0] = s[7];
	d[1] = s[6];
	d[2] = s[5];
	d[3] = s[4];
	d[4] = s[3];
	d[5] = s[2];
	d[6] = s[1];
	d[7] = s[0];
# endif
	return rv;
}
#endif

file_protected uintmax_t 
file_varint2uintmax_t(const unsigned char *us, int t, size_t *l)
{
        uintmax_t x = 0;
        const unsigned char *c;
        if (t == FILE_LEVARINT) {
                for (c = us; *c; c++) {
                        if ((*c & 0x80) == 0)
                                break;
                }
		if (l)
			*l = c - us + 1;
                for (; c >= us; c--) {
                        x |= *c & 0x7f;
                        x <<= 7;
                }
        } else {
                for (c = us; *c; c++) {
			x |= *c & 0x7f;
			if ((*c & 0x80) == 0)
				break;
			x <<= 7;
                }
		if (l)
			*l = c - us + 1;
        }
	return x;
}


/*
 * byteswap a single magic entry
 */
file_private void
bs1(struct magic *m)
{
	m->cont_level = swap2(m->cont_level);
	m->offset = swap4(CAST(uint32_t, m->offset));
	m->in_offset = swap4(CAST(uint32_t, m->in_offset));
	m->lineno = swap4(CAST(uint32_t, m->lineno));
	if (IS_STRING(m->type)) {
		m->str_range = swap4(m->str_range);
		m->str_flags = swap4(m->str_flags);
	}
	else {
		m->value.q = swap8(m->value.q);
		m->num_mask = swap8(m->num_mask);
	}
}

file_protected size_t
file_pstring_length_size(struct magic_set *ms, const struct magic *m)
{
	switch (m->str_flags & PSTRING_LEN) {
	case PSTRING_1_LE:
		return 1;
	case PSTRING_2_LE:
	case PSTRING_2_BE:
		return 2;
	case PSTRING_4_LE:
	case PSTRING_4_BE:
		return 4;
	default:
		file_error(ms, 0, "corrupt magic file "
		    "(bad pascal string length %d)",
		    m->str_flags & PSTRING_LEN);
		return FILE_BADSIZE;
	}
}
file_protected size_t
file_pstring_get_length(struct magic_set *ms, const struct magic *m,
    const char *ss)
{
	size_t len = 0;
	const unsigned char *s = RCAST(const unsigned char *, ss);
	unsigned int s3, s2, s1, s0;

	switch (m->str_flags & PSTRING_LEN) {
	case PSTRING_1_LE:
		len = *s;
		break;
	case PSTRING_2_LE:
		s0 = s[0];
		s1 = s[1];
		len = (s1 << 8) | s0;
		break;
	case PSTRING_2_BE:
		s0 = s[0];
		s1 = s[1];
		len = (s0 << 8) | s1;
		break;
	case PSTRING_4_LE:
		s0 = s[0];
		s1 = s[1];
		s2 = s[2];
		s3 = s[3];
		len = (s3 << 24) | (s2 << 16) | (s1 << 8) | s0;
		break;
	case PSTRING_4_BE:
		s0 = s[0];
		s1 = s[1];
		s2 = s[2];
		s3 = s[3];
		len = (s0 << 24) | (s1 << 16) | (s2 << 8) | s3;
		break;
	default:
		file_error(ms, 0, "corrupt magic file "
		    "(bad pascal string length %d)",
		    m->str_flags & PSTRING_LEN);
		return FILE_BADSIZE;
	}

	if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF) {
		size_t l = file_pstring_length_size(ms, m);
		if (l == FILE_BADSIZE)
			return l;
		len -= l;
	}

	return len;
}

file_protected int
file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
{
	uint32_t i, j;
	struct mlist *mlist, *ml;

	mlist = ms->mlist[1];

	for (ml = mlist->next; ml != mlist; ml = ml->next) {
		struct magic *ma = ml->magic;
		for (i = 0; i < ml->nmagic; i++) {
			if (ma[i].type != FILE_NAME)
				continue;
			if (strcmp(ma[i].value.s, name) == 0) {
				v->magic = &ma[i];
				v->magic_rxcomp = &(ml->magic_rxcomp[i]);
				for (j = i + 1; j < ml->nmagic; j++)
				    if (ma[j].cont_level == 0)
					    break;
				v->nmagic = j - i;
				return 0;
			}
		}
	}
	return -1;
}