tzh
2024-08-22 c7d0944258c7d0943aa7b2211498fd612971ce27
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
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
/* Authors: Steve Lawrence <slawrence@tresys.com>
 *
 * Functions to convert policy module to CIL
 *
 * Copyright (C) 2015 Tresys Technology, LLC
 * Copyright (C) 2017 Mellanox Technologies Inc.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
 
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <libgen.h>
#include <netinet/in.h>
#ifndef IPPROTO_DCCP
#define IPPROTO_DCCP 33
#endif
#ifndef IPPROTO_SCTP
#define IPPROTO_SCTP 132
#endif
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include <sepol/module.h>
#include <sepol/module_to_cil.h>
#include <sepol/policydb/conditional.h>
#include <sepol/policydb/hashtab.h>
#include <sepol/policydb/polcaps.h>
#include <sepol/policydb/policydb.h>
#include <sepol/policydb/services.h>
#include <sepol/policydb/util.h>
 
#include "kernel_to_common.h"
#include "private.h"
 
#ifdef __GNUC__
#  define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
#  define UNUSED(x) UNUSED_ ## x
#endif
 
FILE *out_file;
 
#define STACK_SIZE 16
#define DEFAULT_LEVEL "systemlow"
#define DEFAULT_OBJECT "object_r"
#define GEN_REQUIRE_ATTR "cil_gen_require" /* Also in libsepol/cil/src/cil_post.c */
#define TYPEATTR_INFIX "_typeattr_"        /* Also in libsepol/cil/src/cil_post.c */
#define ROLEATTR_INFIX "_roleattr_"
 
__attribute__ ((format(printf, 1, 2)))
static void log_err(const char *fmt, ...)
{
   va_list argptr;
   va_start(argptr, fmt);
   if (vfprintf(stderr, fmt, argptr) < 0) {
       _exit(EXIT_FAILURE);
   }
   va_end(argptr);
   if (fprintf(stderr, "\n") < 0) {
       _exit(EXIT_FAILURE);
   }
}
 
static void cil_indent(int indent)
{
   if (fprintf(out_file, "%*s", indent * 4, "") < 0) {
       log_err("Failed to write to output");
       _exit(EXIT_FAILURE);
   }
}
 
__attribute__ ((format(printf, 1, 2)))
static void cil_printf(const char *fmt, ...) {
   va_list argptr;
   va_start(argptr, fmt);
   if (vfprintf(out_file, fmt, argptr) < 0) {
       log_err("Failed to write to output");
       _exit(EXIT_FAILURE);
   }
   va_end(argptr);
}
 
__attribute__ ((format(printf, 2, 3)))
static void cil_println(int indent, const char *fmt, ...)
{
   cil_indent(indent);
   va_list argptr;
   va_start(argptr, fmt);
   if (vfprintf(out_file, fmt, argptr) < 0) {
       log_err("Failed to write to output");
       _exit(EXIT_FAILURE);
   }
   va_end(argptr);
   if (fprintf(out_file, "\n") < 0) {
       log_err("Failed to write to output");
       _exit(EXIT_FAILURE);
   }
}
 
static int get_line(char **start, char *end, char **line)
{
   int rc = 1;
   char *p = NULL;
   size_t len = 0;
 
   *line = NULL;
 
   for (p = *start; p < end && isspace(*p); p++);
 
   *start = p;
 
   for (len = 0; p < end && *p != '\n' && *p != '\0'; p++, len++);
 
   if (zero_or_saturated(len)) {
       rc = 0;
       goto exit;
   }
 
   *line = malloc(len+1);
   if (*line == NULL) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
 
   memcpy(*line, *start, len);
   (*line)[len] = '\0';
 
   *start = p;
 
   return rc;
 
exit:
   *start = NULL;
   return rc;
}
 
struct map_args {
   struct policydb *pdb;
   struct avrule_block *block;
   struct stack *decl_stack;
   int scope;
   int indent;
   int sym_index;
};
 
struct stack {
    void **stack;
    int pos;
    int size;
};
 
struct role_list_node {
   char *role_name;
   role_datum_t *role;
};
 
struct attr_list_node {
   char *attr_name;
   int is_type;
   void *set;
};
 
struct list_node {
   void *data;
   struct list_node *next;
};
 
struct list {
   struct list_node *head;
};
 
/* A linked list of all roles stored in the pdb
 * which is iterated to determine types associated
 * with each role when printing role_type statements
 */
static struct list *role_list;
 
static void list_destroy(struct list **list)
{
   struct list_node *curr = (*list)->head;
   struct list_node *tmp;
 
   while (curr != NULL) {
       tmp = curr->next;
       free(curr);
       curr = tmp;
   }
 
   free(*list);
   *list = NULL;
}
 
static void role_list_destroy(void)
{
   struct list_node *curr;
 
   if (role_list == NULL) {
       return;
   }
   curr = role_list->head;
 
   while (curr != NULL) {
       free(curr->data);
       curr->data = NULL;
       curr = curr->next;
   }
 
   list_destroy(&role_list);
}
 
static void attr_list_destroy(struct list **attr_list)
{
   if (attr_list == NULL || *attr_list == NULL) {
       return;
   }
 
   struct list_node *curr = (*attr_list)->head;
   struct attr_list_node *attr;
 
   while (curr != NULL) {
       attr = curr->data;
       if (attr != NULL) {
           free(attr->attr_name);
       }
 
       free(curr->data);
       curr->data = NULL;
       curr = curr->next;
   }
 
   list_destroy(attr_list);
}
 
static int list_init(struct list **list)
{
   struct list *l = calloc(1, sizeof(*l));
   if (l == NULL) {
       return -1;
   }
 
   *list = l;
   return 0;
}
 
static int list_prepend(struct list *list, void *data)
{
   int rc = -1;
   struct list_node *node = calloc(1, sizeof(*node));
   if (node == NULL) {
       goto exit;
   }
 
   node->data = data;
   node->next = list->head;
   list->head = node;
 
   rc = 0;
 
exit:
   return rc;
}
 
static int roles_gather_map(char *key, void *data, void *args)
{
   struct role_list_node *role_node;
   role_datum_t *role = data;
   int rc = -1;
 
   role_node = calloc(1, sizeof(*role_node));
   if (role_node == NULL) {
       return rc;
   }
 
   role_node->role_name = key;
   role_node->role = role;
 
   rc = list_prepend((struct list *)args, role_node);
   if (rc != 0)
       free(role_node);
   return rc;
}
 
static int role_list_create(hashtab_t roles_tab)
{
   int rc = -1;
 
   rc = list_init(&role_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = hashtab_map(roles_tab, roles_gather_map, role_list);
 
exit:
   return rc;
}
 
// array of lists, where each list contains all the aliases defined in the scope at index i
static struct list **typealias_lists;
static uint32_t typealias_lists_len;
 
static int typealiases_gather_map(char *key, void *data, void *arg)
{
   int rc = -1;
   struct type_datum *type = data;
   struct policydb *pdb = arg;
   struct scope_datum *scope;
   uint32_t len;
   uint32_t scope_id;
 
   if (type->primary != 1) {
       scope = hashtab_search(pdb->scope[SYM_TYPES].table, key);
       if (scope == NULL) {
           return -1;
       }
 
       len = scope->decl_ids_len;
       if (len > 0) {
           scope_id = scope->decl_ids[len-1];
           if (typealias_lists[scope_id] == NULL) {
               rc = list_init(&typealias_lists[scope_id]);
               if (rc != 0) {
                   goto exit;
               }
           }
           /* As typealias_lists[scope_id] does not hold the
            * ownership of its items (typealias_list_destroy does
            * not free the list items), "key" does not need to be
            * strdup'ed before it is inserted in the list.
            */
           list_prepend(typealias_lists[scope_id], key);
       }
   }
 
   return 0;
 
exit:
   return rc;
}
 
static void typealias_list_destroy(void)
{
   uint32_t i;
   for (i = 0; i < typealias_lists_len; i++) {
       if (typealias_lists[i] != NULL) {
           list_destroy(&typealias_lists[i]);
       }
   }
   typealias_lists_len = 0;
   free(typealias_lists);
   typealias_lists = NULL;
}
 
static int typealias_list_create(struct policydb *pdb)
{
   uint32_t max_decl_id = 0;
   struct avrule_decl *decl;
   struct avrule_block *block;
   uint32_t rc = -1;
 
   for (block = pdb->global; block != NULL; block = block->next) {
       decl = block->branch_list;
       if (decl != NULL && decl->decl_id > max_decl_id) {
           max_decl_id = decl->decl_id;
       }
   }
 
   typealias_lists = calloc(max_decl_id + 1, sizeof(*typealias_lists));
   typealias_lists_len = max_decl_id + 1;
 
   rc = hashtab_map(pdb->p_types.table, typealiases_gather_map, pdb);
   if (rc != 0) {
       goto exit;
   }
 
   return 0;
 
exit:
   typealias_list_destroy();
 
   return rc;
}
 
 
static int stack_destroy(struct stack **stack)
{
   if (stack == NULL || *stack == NULL) {
       return 0;
   }
 
   free((*stack)->stack);
   free(*stack);
   *stack = NULL;
 
   return 0;
}
 
static int stack_init(struct stack **stack)
{
   int rc = -1;
   struct stack *s = calloc(1, sizeof(*s));
   if (s == NULL) {
       goto exit;
   }
 
   s->stack = malloc(sizeof(*s->stack) * STACK_SIZE);
   if (s->stack == NULL) {
       goto exit;
   }
 
   s->pos = -1;
   s->size = STACK_SIZE;
 
   *stack = s;
 
   return 0;
 
exit:
   stack_destroy(&s);
   return rc;
}
 
static int stack_push(struct stack *stack, void *ptr)
{
   int rc = -1;
   void *new_stack;
 
   if (stack->pos + 1 == stack->size) {
       new_stack = realloc(stack->stack, sizeof(*stack->stack) * (stack->size * 2));
       if (new_stack == NULL) {
           goto exit;
       }
       stack->stack = new_stack;
       stack->size *= 2;
   }
 
   stack->pos++;
   stack->stack[stack->pos] = ptr;
 
   rc = 0;
exit:
   return rc;
}
 
static void *stack_pop(struct stack *stack)
{
   if (stack->pos == -1) {
       return NULL;
   }
 
   stack->pos--;
   return stack->stack[stack->pos + 1];
}
 
static void *stack_peek(struct stack *stack)
{
   if (stack->pos == -1) {
       return NULL;
   }
 
   return stack->stack[stack->pos];
}
 
static int is_id_in_scope_with_start(struct policydb *pdb, struct stack *decl_stack, int start, uint32_t symbol_type, char *id)
{
   int i;
   uint32_t j;
   struct avrule_decl *decl;
   struct scope_datum *scope;
 
   scope = hashtab_search(pdb->scope[symbol_type].table, id);
   if (scope == NULL) {
       return 0;
   }
 
   for (i = start; i >= 0; i--) {
       decl = decl_stack->stack[i];
 
       for (j = 0; j < scope->decl_ids_len; j++) {
           if (scope->decl_ids[j] == decl->decl_id) {
               return 1;
           }
       }
   }
 
   return 0;
}
 
static int is_id_in_ancestor_scope(struct policydb *pdb, struct stack *decl_stack, char *type, uint32_t symbol_type)
{
   int start = decl_stack->pos - 1;
 
   return is_id_in_scope_with_start(pdb, decl_stack, start, symbol_type, type);
}
 
static int is_id_in_scope(struct policydb *pdb, struct stack *decl_stack, char *type, uint32_t symbol_type)
{
   int start = decl_stack->pos;
 
   return is_id_in_scope_with_start(pdb, decl_stack, start, symbol_type, type);
}
 
static int semantic_level_to_cil(struct policydb *pdb, int sens_offset, struct mls_semantic_level *level)
{
   struct mls_semantic_cat *cat;
 
   cil_printf("(%s ", pdb->p_sens_val_to_name[level->sens - sens_offset]);
 
   if (level->cat != NULL) {
       cil_printf("(");
   }
 
   for (cat = level->cat; cat != NULL; cat = cat->next) {
       if (cat->low == cat->high) {
           cil_printf("%s", pdb->p_cat_val_to_name[cat->low - 1]);
       } else {
           cil_printf("range %s %s", pdb->p_cat_val_to_name[cat->low - 1], pdb->p_cat_val_to_name[cat->high - 1]);
       }
 
       if (cat->next != NULL) {
           cil_printf(" ");
       }
   }
 
   if (level->cat != NULL) {
       cil_printf(")");
   }
 
   cil_printf(")");
 
   return 0;
}
 
static int avrule_to_cil(int indent, struct policydb *pdb, uint32_t type, const char *src, const char *tgt, const struct class_perm_node *classperms)
{
   int rc = -1;
   const char *rule;
   const struct class_perm_node *classperm;
   char *perms;
 
   switch (type) {
   case AVRULE_ALLOWED:
       rule = "allow";
       break;
   case AVRULE_AUDITALLOW:
       rule = "auditallow";
       break;
   case AVRULE_AUDITDENY:
       rule = "auditdenty";
       break;
   case AVRULE_DONTAUDIT:
       rule = "dontaudit";
       break;
   case AVRULE_NEVERALLOW:
       rule = "neverallow";
       break;
   case AVRULE_TRANSITION:
       rule = "typetransition";
       break;
   case AVRULE_MEMBER:
       rule = "typemember";
       break;
   case AVRULE_CHANGE:
       rule = "typechange";
       break;
   default:
       log_err("Unknown avrule type: %i", type);
       rc = -1;
       goto exit;
   }
 
   for (classperm = classperms; classperm != NULL; classperm = classperm->next) {
       if (type & AVRULE_AV) {
           perms = sepol_av_to_string(pdb, classperm->tclass, classperm->data);
           if (perms == NULL) {
               log_err("Failed to generate permission string");
               rc = -1;
               goto exit;
           }
           cil_println(indent, "(%s %s %s (%s (%s)))",
                   rule, src, tgt,
                   pdb->p_class_val_to_name[classperm->tclass - 1],
                   perms + 1);
       } else {
           cil_println(indent, "(%s %s %s %s %s)",
                   rule, src, tgt,
                   pdb->p_class_val_to_name[classperm->tclass - 1],
                   pdb->p_type_val_to_name[classperm->data - 1]);
       }
   }
 
   return 0;
 
exit:
   return rc;
}
 
#define next_bit_in_range(i, p) ((i + 1 < sizeof(p)*8) && xperm_test((i + 1), p))
 
static int xperms_to_cil(const av_extended_perms_t *xperms)
{
   uint16_t value;
   uint16_t low_bit;
   uint16_t low_value;
   unsigned int bit;
   unsigned int in_range = 0;
   int first = 1;
 
   if ((xperms->specified != AVTAB_XPERMS_IOCTLFUNCTION)
       && (xperms->specified != AVTAB_XPERMS_IOCTLDRIVER))
       return -1;
 
   for (bit = 0; bit < sizeof(xperms->perms)*8; bit++) {
       if (!xperm_test(bit, xperms->perms))
           continue;
 
       if (in_range && next_bit_in_range(bit, xperms->perms)) {
           /* continue until high value found */
           continue;
       } else if (next_bit_in_range(bit, xperms->perms)) {
           /* low value */
           low_bit = bit;
           in_range = 1;
           continue;
       }
 
       if (!first)
           cil_printf(" ");
       else
           first = 0;
 
       if (xperms->specified & AVTAB_XPERMS_IOCTLFUNCTION) {
           value = xperms->driver<<8 | bit;
           if (in_range) {
               low_value = xperms->driver<<8 | low_bit;
               cil_printf("(range 0x%hx 0x%hx)", low_value, value);
               in_range = 0;
           } else {
               cil_printf("0x%hx", value);
           }
       } else if (xperms->specified & AVTAB_XPERMS_IOCTLDRIVER) {
           value = bit << 8;
           if (in_range) {
               low_value = low_bit << 8;
               cil_printf("(range 0x%hx 0x%hx)", low_value, (uint16_t) (value|0xff));
               in_range = 0;
           } else {
               cil_printf("(range 0x%hx 0x%hx)", value, (uint16_t) (value|0xff));
           }
       }
   }
 
   return 0;
}
 
static int avrulex_to_cil(int indent, struct policydb *pdb, uint32_t type, const char *src, const char *tgt, const class_perm_node_t *classperms, const av_extended_perms_t *xperms)
{
   int rc = -1;
   const char *rule;
   const struct class_perm_node *classperm;
 
   switch (type) {
   case AVRULE_XPERMS_ALLOWED:
       rule = "allowx";
       break;
   case AVRULE_XPERMS_AUDITALLOW:
       rule = "auditallowx";
       break;
   case AVRULE_XPERMS_DONTAUDIT:
       rule = "dontauditx";
       break;
   case AVRULE_XPERMS_NEVERALLOW:
       rule = "neverallowx";
       break;
   default:
       log_err("Unknown avrule xperm type: %i", type);
       rc = -1;
       goto exit;
   }
 
   for (classperm = classperms; classperm != NULL; classperm = classperm->next) {
       cil_indent(indent);
       cil_printf("(%s %s %s (%s %s (", rule, src, tgt,
              "ioctl", pdb->p_class_val_to_name[classperm->tclass - 1]);
       xperms_to_cil(xperms);
       cil_printf(")))\n");
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int num_digits(int n)
{
   int num = 1;
   while (n >= 10) {
       n /= 10;
       num++;
   }
   return num;
}
 
static int ebitmap_to_cil(struct policydb *pdb, struct ebitmap *map, int type)
{
   struct ebitmap_node *node;
   uint32_t i;
   char **val_to_name = pdb->sym_val_to_name[type];
 
   ebitmap_for_each_bit(map, node, i) {
       if (!ebitmap_get_bit(map, i)) {
           continue;
       }
       cil_printf("%s ", val_to_name[i]);
   }
 
   return 0;
}
 
static char *get_new_attr_name(struct policydb *pdb, int is_type)
{
   static unsigned int num_attrs = 0;
   int len, rlen;
   const char *infix;
   char *attr_name = NULL;
 
   num_attrs++;
 
   if (is_type) {
       infix = TYPEATTR_INFIX;
   } else {
       infix = ROLEATTR_INFIX;
   }
 
   len = strlen(pdb->name) + strlen(infix) + num_digits(num_attrs) + 1;
   attr_name = malloc(len);
   if (!attr_name) {
       log_err("Out of memory");
       goto exit;
   }
 
   rlen = snprintf(attr_name, len, "%s%s%i", pdb->name, infix, num_attrs);
   if (rlen < 0 || rlen >= len) {
       log_err("Failed to generate attribute name");
       free(attr_name);
       attr_name = NULL;
       goto exit;
   }
 
exit:
   return attr_name;
}
 
static int cil_add_attr_to_list(struct list *attr_list, char *attr_name, int is_type, void *set)
{
   struct attr_list_node *attr_list_node = NULL;
   int rc = 0;
 
   attr_list_node = calloc(1, sizeof(*attr_list_node));
   if (attr_list_node == NULL) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
 
   rc = list_prepend(attr_list, attr_list_node);
   if (rc != 0) {
       goto exit;
   }
 
   attr_list_node->attr_name = attr_name;
   attr_list_node->is_type = is_type;
   attr_list_node->set = set;
 
   return rc;
 
exit:
   free(attr_list_node);
   return rc;
}
 
static int cil_print_attr_strs(int indent, struct policydb *pdb, int is_type, void *set, char *attr_name)
{
   // CIL doesn't support anonymous positive/negative/complemented sets.  So
   // instead we create a CIL type/roleattributeset that matches the set. If
   // the set has a negative set, then convert it to is (P & !N), where P is
   // the list of members in the positive set and N is the list of members
   // in the negative set. Additionally, if the set is complemented, then wrap
   // the whole thing with a negation.
 
   struct ebitmap_node *node;
   struct ebitmap *pos, *neg;
   uint32_t flags;
   unsigned i;
   struct type_set *ts;
   struct role_set *rs;
   int has_positive, has_negative;
   const char *kind;
   char **val_to_name;
   int rc = 0;
 
   if (is_type) {
       kind = "type";
       val_to_name = pdb->p_type_val_to_name;
       ts = (struct type_set *)set;
       pos = &ts->types;
       neg = &ts->negset;
       flags = ts->flags;
       has_positive = pos && (ebitmap_length(pos) > 0);
       has_negative = neg && (ebitmap_length(neg) > 0);
   } else {
       kind = "role";
       val_to_name = pdb->p_role_val_to_name;
       rs = (struct role_set *)set;
       pos = &rs->roles;
       neg = NULL;
       flags = rs->flags;
       has_positive = pos && (ebitmap_length(pos) > 0);
       has_negative = 0;
   }
 
   cil_println(indent, "(%sattribute %s)", kind, attr_name);
   cil_indent(indent);
   cil_printf("(%sattributeset %s ", kind, attr_name);
 
   if (flags & TYPE_STAR) {
       cil_printf("(all)");
   }
 
   if (flags & TYPE_COMP) {
       cil_printf("(not ");
   }
 
   if (has_positive && has_negative) {
       cil_printf("(and ");
   }
 
   if (has_positive) {
       cil_printf("(");
       ebitmap_for_each_bit(pos, node, i) {
           if (!ebitmap_get_bit(pos, i)) {
               continue;
           }
           cil_printf("%s ", val_to_name[i]);
       }
       cil_printf(") ");
   }
 
   if (has_negative) {
       cil_printf("(not (");
 
       ebitmap_for_each_bit(neg, node, i) {
           if (!ebitmap_get_bit(neg, i)) {
               continue;
           }
           cil_printf("%s ", val_to_name[i]);
       }
 
       cil_printf("))");
   }
 
   if (has_positive && has_negative) {
       cil_printf(")");
   }
 
   if (flags & TYPE_COMP) {
       cil_printf(")");
   }
 
   cil_printf(")\n");
 
   return rc;
}
 
static int cil_print_attr_list(int indent, struct policydb *pdb, struct list *attr_list)
{
   struct list_node *curr;
   struct attr_list_node *node;
   int rc = 0;
 
   for (curr = attr_list->head; curr != NULL; curr = curr->next) {
       node = curr->data;
       rc = cil_print_attr_strs(indent, pdb, node->is_type, node->set, node->attr_name);
       if (rc != 0) {
           return rc;
       }
   }
 
   return rc;
}
 
static char *search_attr_list(struct list *attr_list, int is_type, void *set)
{
   struct list_node *curr;
   struct attr_list_node *node;
   struct role_set *rs1 = NULL, *rs2;
   struct type_set *ts1 = NULL, *ts2;
 
   if (is_type) {
       ts1 = (struct type_set *)set;
   } else {
       rs1 = (struct role_set *)set;
   }
 
   for (curr = attr_list->head; curr != NULL; curr = curr->next) {
       node = curr->data;
       if (node->is_type != is_type)
           continue;
       if (ts1) {
           ts2 = (struct type_set *)node->set;
           if (ts1->flags != ts2->flags)
               continue;
           if (ebitmap_cmp(&ts1->negset, &ts2->negset) == 0)
               continue;
           if (ebitmap_cmp(&ts1->types, &ts2->types) == 0)
               continue;
           return node->attr_name;
       } else {
           rs2 = (struct role_set *)node->set;
           if (rs1->flags != rs2->flags)
               continue;
           if (ebitmap_cmp(&rs1->roles, &rs2->roles) == 0)
               continue;
           return node->attr_name;
       }
   }
 
   return NULL;
}
 
static int set_to_names(struct policydb *pdb, int is_type, void *set, struct list *attr_list, char ***names, int *num_names)
{
   char *attr_name = NULL;
   int rc = 0;
 
   *names = NULL;
   *num_names = 0;
 
   attr_name = search_attr_list(attr_list, is_type, set);
 
   if (!attr_name) {
       attr_name = get_new_attr_name(pdb, is_type);
       if (!attr_name) {
           rc = -1;
           goto exit;
       }
 
       rc = cil_add_attr_to_list(attr_list, attr_name, is_type, set);
       if (rc != 0) {
           free(attr_name);
           goto exit;
       }
   }
 
   *names = malloc(sizeof(char *));
   if (!*names) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
   *names[0] = attr_name;
   *num_names = 1;
 
exit:
   return rc;
}
 
static int ebitmap_to_names(struct ebitmap *map, char **vals_to_names, char ***names, int *num_names)
{
   int rc = 0;
   struct ebitmap_node *node;
   uint32_t i;
   uint32_t num;
   char **name_arr;
 
   num = 0;
   ebitmap_for_each_bit(map, node, i) {
       if (ebitmap_get_bit(map, i)) {
           if (num >= UINT32_MAX / sizeof(*name_arr)) {
               log_err("Overflow");
               rc = -1;
               goto exit;
           }
           num++;
       }
   }
 
   if (!num) {
       *names = NULL;
       *num_names = 0;
       goto exit;
   }
 
   name_arr = malloc(sizeof(*name_arr) * num);
   if (name_arr == NULL) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
 
   num = 0;
   ebitmap_for_each_bit(map, node, i) {
       if (ebitmap_get_bit(map, i)) {
           name_arr[num] = vals_to_names[i];
           num++;
       }
   }
 
   *names = name_arr;
   *num_names = num;
 
exit:
   return rc;
}
 
static int process_roleset(struct policydb *pdb, struct role_set *rs, struct list *attr_list, char ***names, int *num_names)
{
   int rc = 0;
 
   *names = NULL;
   *num_names = 0;
 
   if (rs->flags) {
       rc = set_to_names(pdb, 0, &rs->roles, attr_list, names, num_names);
       if (rc != 0) {
           goto exit;
       }
   } else {
       rc = ebitmap_to_names(&rs->roles, pdb->p_role_val_to_name, names, num_names);
       if (rc != 0) {
           goto exit;
       }
   }
 
exit:
   return rc;
}
 
static int process_typeset(struct policydb *pdb, struct type_set *ts, struct list *attr_list, char ***names, int *num_names)
{
   int rc = 0;
 
   *names = NULL;
   *num_names = 0;
 
   if (ebitmap_length(&ts->negset) > 0 || ts->flags != 0) {
       rc = set_to_names(pdb, 1, ts, attr_list, names, num_names);
       if (rc != 0) {
           goto exit;
       }
   } else {
       rc = ebitmap_to_names(&ts->types, pdb->p_type_val_to_name, names, num_names);
       if (rc != 0) {
           goto exit;
       }
   }
 
exit:
   return rc;
}
 
static void names_destroy(char ***names, int *num_names)
{
   free(*names);
   *names = NULL;
   *num_names = 0;
}
 
static int roletype_role_in_ancestor_to_cil(struct policydb *pdb, struct stack *decl_stack, char *type_name, int indent)
{
   struct list_node *curr;
   char **tnames = NULL;
   int num_tnames, i;
   struct role_list_node *role_node = NULL;
   int rc;
   struct type_set *ts;
   struct list *attr_list = NULL;
 
   rc = list_init(&attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   for (curr = role_list->head; curr != NULL; curr = curr->next) {
       role_node = curr->data;
       if (!is_id_in_ancestor_scope(pdb, decl_stack, role_node->role_name, SYM_ROLES)) {
           continue;
       }
 
       ts = &role_node->role->types;
       rc = process_typeset(pdb, ts, attr_list, &tnames, &num_tnames);
       if (rc != 0) {
           goto exit;
       }
       for (i = 0; i < num_tnames; i++) {
           if (!strcmp(type_name, tnames[i])) {
               cil_println(indent, "(roletype %s %s)", role_node->role_name, type_name);
           }
       }
       names_destroy(&tnames, &num_tnames);
   }
 
   rc = cil_print_attr_list(indent, pdb, attr_list);
   if (rc != 0) {
       goto exit;
   }
 
exit:
   attr_list_destroy(&attr_list);
   return rc;
}
 
 
static int name_list_to_string(char **names, int num_names, char **string)
{
   // create a space separated string of the names
   int rc = -1;
   size_t len = 0;
   int i;
   char *str;
   char *strpos;
 
   for (i = 0; i < num_names; i++) {
       len += strlen(names[i]);
       if (len < strlen(names[i])) {
           log_err("Overflow");
           return -1;
       }
   }
 
   // add spaces + null terminator
   len += num_names;
   if (len < (size_t)num_names) {
       log_err("Overflow");
       return -1;
   }
 
   if (!len) {
       log_err("Empty list");
       return -1;
   }
 
   str = malloc(len);
   if (str == NULL) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
   str[0] = 0;
 
   strpos = str;
 
   for (i = 0; i < num_names; i++) {
       strpos = stpcpy(strpos, names[i]);
       if (i < num_names - 1) {
           *strpos++ = ' ';
       }
   }
 
   *string = str;
 
   return 0;
exit:
   free(str);
   return rc;
}
 
static int avrule_list_to_cil(int indent, struct policydb *pdb, struct avrule *avrule_list, struct list *attr_list)
{
   int rc = -1;
   struct avrule *avrule;
   char **snames = NULL;
   char **tnames = NULL;
   int s, t, num_snames, num_tnames;
   struct type_set *ts;
 
   for (avrule = avrule_list; avrule != NULL; avrule = avrule->next) {
       if ((avrule->specified & (AVRULE_NEVERALLOW|AVRULE_XPERMS_NEVERALLOW)) &&
           avrule->source_filename) {
           cil_println(0, ";;* lmx %lu %s\n",avrule->source_line, avrule->source_filename);
       }
 
       ts = &avrule->stypes;
       rc = process_typeset(pdb, ts, attr_list, &snames, &num_snames);
       if (rc != 0) {
           goto exit;
       }
 
       ts = &avrule->ttypes;
       rc = process_typeset(pdb, ts, attr_list, &tnames, &num_tnames);
       if (rc != 0) {
           goto exit;
       }
 
       for (s = 0; s < num_snames; s++) {
           for (t = 0; t < num_tnames; t++) {
               if (avrule->specified & AVRULE_XPERMS) {
                   rc = avrulex_to_cil(indent, pdb, avrule->specified, snames[s], tnames[t], avrule->perms, avrule->xperms);
               } else {
                   rc = avrule_to_cil(indent, pdb, avrule->specified, snames[s], tnames[t], avrule->perms);
               }
               if (rc != 0) {
                   goto exit;
               }
           }
 
           if (avrule->flags & RULE_SELF) {
               if (avrule->specified & AVRULE_XPERMS) {
                   rc = avrulex_to_cil(indent, pdb, avrule->specified, snames[s], "self", avrule->perms, avrule->xperms);
               } else {
                   rc = avrule_to_cil(indent, pdb, avrule->specified, snames[s], "self", avrule->perms);
               }
               if (rc != 0) {
                   goto exit;
               }
           }
       }
 
       names_destroy(&snames, &num_snames);
       names_destroy(&tnames, &num_tnames);
 
       if ((avrule->specified & (AVRULE_NEVERALLOW|AVRULE_XPERMS_NEVERALLOW)) &&
           avrule->source_filename) {
           cil_println(0, ";;* lme\n");
       }
   }
 
   return 0;
 
exit:
   names_destroy(&snames, &num_snames);
   names_destroy(&tnames, &num_tnames);
 
   return rc;
}
 
static int cond_expr_to_cil(int indent, struct policydb *pdb, struct cond_expr *cond_expr, uint32_t flags)
{
   int rc = 0;
   struct cond_expr *curr;
   struct stack *stack = NULL;
   int len = 0;
   int rlen;
   char *new_val = NULL;
   char *val1 = NULL;
   char *val2 = NULL;
   int num_params;
   const char *op;
   const char *fmt_str;
   const char *type;
 
   rc = stack_init(&stack);
   if (rc != 0) {
       log_err("Out of memory");
       goto exit;
   }
 
   for (curr = cond_expr; curr != NULL; curr = curr->next) {
       if (curr->expr_type == COND_BOOL) {
           val1 = pdb->p_bool_val_to_name[curr->bool - 1];
           // length of boolean + 2 parens + null terminator
           len = strlen(val1) + 2 + 1;
           new_val = malloc(len);
           if (new_val == NULL) {
               log_err("Out of memory");
               rc = -1;
               goto exit;
           }
           rlen = snprintf(new_val, len, "(%s)", val1);
           if (rlen < 0 || rlen >= len) {
               log_err("Failed to generate conditional expression");
               rc = -1;
               goto exit;
           }
       } else {
           switch(curr->expr_type) {
           case COND_NOT:    op = "not";    break;
           case COND_OR:    op = "or";    break;
           case COND_AND:    op = "and";    break;
           case COND_XOR:    op = "xor";    break;
           case COND_EQ:    op = "eq";    break;
           case COND_NEQ:    op = "neq";    break;
           default:
               rc = -1;
               goto exit;
           }
 
           num_params = curr->expr_type == COND_NOT ? 1 : 2;
 
           if (num_params == 1) {
               val1 = stack_pop(stack);
               val2 = strdup("");
               if (val2 == NULL) {
                   log_err("Out of memory");
                   rc = -1;
                   goto exit;
               }
               fmt_str = "(%s %s)";
           } else {
               val2 = stack_pop(stack);
               val1 = stack_pop(stack);
               fmt_str = "(%s %s %s)";
           }
 
           if (val1 == NULL || val2 == NULL) {
               log_err("Invalid conditional expression");
               rc = -1;
               goto exit;
           }
 
           // length = length of parameters +
           //          length of operator +
           //          1 space preceeding each parameter +
           //          2 parens around the whole expression
           //          + null terminator
           len = strlen(val1) + strlen(val2) + strlen(op) + (num_params * 1) + 2 + 1;
           new_val = malloc(len);
           if (new_val == NULL) {
               log_err("Out of memory");
               rc = -1;
               goto exit;
           }
 
           // although we always supply val2 and there isn't always a 2nd
           // value, it should only be used when there are actually two values
           // in the format strings
           rlen = snprintf(new_val, len, fmt_str, op, val1, val2);
           if (rlen < 0 || rlen >= len) {
               log_err("Failed to generate conditional expression");
               rc = -1;
               goto exit;
           }
 
           free(val1);
           free(val2);
           val1 = NULL;
           val2 = NULL;
       }
 
       rc = stack_push(stack, new_val);
       if (rc != 0) {
           log_err("Out of memory");
           goto exit;
       }
       new_val = NULL;
   }
 
   if (flags & COND_NODE_FLAGS_TUNABLE) {
       type = "tunableif";
   } else {
       type = "booleanif";
   }
 
   val1 = stack_pop(stack);
   if (val1 == NULL || stack_peek(stack) != NULL) {
       log_err("Invalid conditional expression");
       rc = -1;
       goto exit;
   }
 
   cil_println(indent, "(%s %s", type, val1);
   free(val1);
   val1 = NULL;
 
   rc = 0;
 
exit:
   free(new_val);
   free(val1);
   free(val2);
   if (stack != NULL) {
       while ((val1 = stack_pop(stack)) != NULL) {
           free(val1);
       }
       stack_destroy(&stack);
   }
   return rc;
}
 
static int cond_list_to_cil(int indent, struct policydb *pdb, struct cond_node *cond_list, struct list *attr_list)
{
   int rc = 0;
   struct cond_node *cond;
 
   for (cond = cond_list; cond != NULL; cond = cond->next) {
 
       rc = cond_expr_to_cil(indent, pdb, cond->expr, cond->flags);
       if (rc != 0) {
           goto exit;
       }
 
       if (cond->avtrue_list != NULL) {
           cil_println(indent + 1, "(true");
           rc = avrule_list_to_cil(indent + 2, pdb, cond->avtrue_list, attr_list);
           if (rc != 0) {
               goto exit;
           }
           cil_println(indent + 1, ")");
       }
 
       if (cond->avfalse_list != NULL) {
           cil_println(indent + 1, "(false");
           rc = avrule_list_to_cil(indent + 2, pdb, cond->avfalse_list, attr_list);
           if (rc != 0) {
               goto exit;
           }
           cil_println(indent + 1, ")");
       }
 
       cil_println(indent, ")");
   }
 
exit:
   return rc;
}
 
static int role_trans_to_cil(int indent, struct policydb *pdb, struct role_trans_rule *rules, struct list *role_attr_list, struct list *type_attr_list)
{
   int rc = 0;
   struct role_trans_rule *rule;
   char **role_names = NULL;
   int num_role_names = 0;
   int role;
   char **type_names = NULL;
   int num_type_names = 0;
   int type;
   uint32_t i;
   struct ebitmap_node *node;
   struct type_set *ts;
   struct role_set *rs;
 
   for (rule = rules; rule != NULL; rule = rule->next) {
       rs = &rule->roles;
       rc = process_roleset(pdb, rs, role_attr_list, &role_names, &num_role_names);
       if (rc != 0) {
           goto exit;
       }
 
       ts = &rule->types;
       rc = process_typeset(pdb, ts, type_attr_list, &type_names, &num_type_names);
       if (rc != 0) {
           goto exit;
       }
 
       for (role = 0; role < num_role_names; role++) {
           for (type = 0; type < num_type_names; type++) {
               ebitmap_for_each_bit(&rule->classes, node, i) {
                   if (!ebitmap_get_bit(&rule->classes, i)) {
                       continue;
                   }
                   cil_println(indent, "(roletransition %s %s %s %s)",
                           role_names[role], type_names[type],
                           pdb->p_class_val_to_name[i],
                           pdb->p_role_val_to_name[rule->new_role - 1]);
               }
           }
       }
 
       names_destroy(&role_names, &num_role_names);
       names_destroy(&type_names, &num_type_names);
   }
 
exit:
   names_destroy(&role_names, &num_role_names);
   names_destroy(&type_names, &num_type_names);
 
   return rc;
}
 
static int role_allows_to_cil(int indent, struct policydb *pdb, struct role_allow_rule *rules, struct list *attr_list)
{
   int rc = -1;
   struct role_allow_rule *rule;
   char **roles = NULL;
   int num_roles = 0;
   char **new_roles = NULL;
   int num_new_roles = 0;
   int i,j;
   struct role_set *rs;
 
   for (rule = rules; rule != NULL; rule = rule->next) {
       rs = &rule->roles;
       rc = process_roleset(pdb, rs, attr_list, &roles, &num_roles);
       if (rc != 0) {
           goto exit;
       }
 
       rs = &rule->new_roles;
       rc = process_roleset(pdb, rs, attr_list, &new_roles, &num_new_roles);
       if (rc != 0) {
           goto exit;
       }
 
       for (i = 0; i < num_roles; i++) {
           for (j = 0; j < num_new_roles; j++) {
               cil_println(indent, "(roleallow %s %s)", roles[i], new_roles[j]);
           }
       }
 
       names_destroy(&roles, &num_roles);
       names_destroy(&new_roles, &num_new_roles);
   }
 
   rc = 0;
 
exit:
   names_destroy(&roles, &num_roles);
   names_destroy(&new_roles, &num_new_roles);
 
   return rc;
}
 
static int range_trans_to_cil(int indent, struct policydb *pdb, struct range_trans_rule *rules, struct list *attr_list)
{
   int rc = -1;
   struct range_trans_rule *rule;
   char **stypes = NULL;
   int num_stypes = 0;
   int stype;
   char **ttypes = NULL;
   int num_ttypes = 0;
   int ttype;
   struct ebitmap_node *node;
   uint32_t i;
   struct type_set *ts;
 
   if (!pdb->mls) {
       return 0;
   }
 
   for (rule = rules; rule != NULL; rule = rule->next) {
       ts = &rule->stypes;
       rc = process_typeset(pdb, ts, attr_list, &stypes, &num_stypes);
       if (rc != 0) {
           goto exit;
       }
 
       ts = &rule->ttypes;
       rc = process_typeset(pdb, ts, attr_list, &ttypes, &num_ttypes);
       if (rc != 0) {
           goto exit;
       }
 
       for (stype = 0; stype < num_stypes; stype++) {
           for (ttype = 0; ttype < num_ttypes; ttype++) {
               ebitmap_for_each_bit(&rule->tclasses, node, i) {
                   if (!ebitmap_get_bit(&rule->tclasses, i)) {
                       continue;
                   }
 
                   cil_indent(indent);
                   cil_printf("(rangetransition %s %s %s ", stypes[stype], ttypes[ttype], pdb->p_class_val_to_name[i]);
 
                   cil_printf("(");
 
                   rc = semantic_level_to_cil(pdb, 1, &rule->trange.level[0]);
                   if (rc != 0) {
                       goto exit;
                   }
 
                   cil_printf(" ");
 
                   rc = semantic_level_to_cil(pdb, 1, &rule->trange.level[1]);
                   if (rc != 0) {
                       goto exit;
                   }
 
                   cil_printf("))\n");
               }
 
           }
       }
 
       names_destroy(&stypes, &num_stypes);
       names_destroy(&ttypes, &num_ttypes);
   }
 
   rc = 0;
 
exit:
   names_destroy(&stypes, &num_stypes);
   names_destroy(&ttypes, &num_ttypes);
 
   return rc;
}
 
static int filename_trans_to_cil(int indent, struct policydb *pdb, struct filename_trans_rule *rules, struct list *attr_list)
{
   int rc = -1;
   char **stypes = NULL;
   int num_stypes = 0;
   int stype;
   char **ttypes = NULL;
   int num_ttypes = 0;
   int ttype;
   struct type_set *ts;
   struct filename_trans_rule *rule;
 
   for (rule = rules; rule != NULL; rule = rule->next) {
       ts = &rule->stypes;
       rc = process_typeset(pdb, ts, attr_list, &stypes, &num_stypes);
       if (rc != 0) {
           goto exit;
       }
 
       ts = &rule->ttypes;
       rc = process_typeset(pdb, ts, attr_list, &ttypes, &num_ttypes);
       if (rc != 0) {
           goto exit;
       }
 
       for (stype = 0; stype < num_stypes; stype++) {
           for (ttype = 0; ttype < num_ttypes; ttype++) {
               cil_println(indent, "(typetransition %s %s %s \"%s\" %s)",
                       stypes[stype], ttypes[ttype],
                       pdb->p_class_val_to_name[rule->tclass - 1],
                       rule->name,
                       pdb->p_type_val_to_name[rule->otype - 1]);
           }
       }
 
       names_destroy(&stypes, &num_stypes);
       names_destroy(&ttypes, &num_ttypes);
   }
 
   rc = 0;
exit:
   names_destroy(&stypes, &num_stypes);
   names_destroy(&ttypes, &num_ttypes);
 
   return rc;
}
 
struct class_perm_datum {
   char *name;
   uint32_t val;
};
 
struct class_perm_array {
   struct class_perm_datum *perms;
   uint32_t count;
};
 
static int class_perm_to_array(char *key, void *data, void *args)
{
   struct class_perm_array *arr = args;
   struct perm_datum *datum = data;
   arr->perms[arr->count].name = key;
   arr->perms[arr->count].val = datum->s.value;
   arr->count++;
 
   return 0;
}
 
static int class_perm_cmp(const void *a, const void *b)
{
   const struct class_perm_datum *aa = a;
   const struct class_perm_datum *bb = b;
 
   return aa->val - bb->val;
}
 
static int common_to_cil(char *key, void *data, void *UNUSED(arg))
{
   int rc = -1;
   struct common_datum *common = data;
   struct class_perm_array arr;
   uint32_t i;
 
   arr.count = 0;
   arr.perms = calloc(common->permissions.nprim, sizeof(*arr.perms));
   if (arr.perms == NULL) {
       goto exit;
   }
   rc = hashtab_map(common->permissions.table, class_perm_to_array, &arr);
   if (rc != 0) {
       goto exit;
   }
 
   qsort(arr.perms, arr.count, sizeof(*arr.perms), class_perm_cmp);
 
   cil_printf("(common %s (", key);
   for (i = 0; i < arr.count; i++) {
       cil_printf("%s ", arr.perms[i].name);
   }
   cil_printf("))\n");
 
   rc = 0;
 
exit:
   free(arr.perms);
   return rc;
}
 
 
static int constraint_expr_to_string(struct policydb *pdb, struct constraint_expr *exprs, char **expr_string)
{
   int rc = -1;
   struct constraint_expr *expr;
   struct stack *stack = NULL;
   int len = 0;
   int rlen;
   char *new_val = NULL;
   char *val1 = NULL;
   char *val2 = NULL;
   uint32_t num_params;
   const char *op;
   const char *fmt_str;
   const char *attr1;
   const char *attr2;
   char *names = NULL;
   char **name_list = NULL;
   int num_names = 0;
   struct type_set *ts;
 
   rc = stack_init(&stack);
   if (rc != 0) {
       goto exit;
   }
 
   for (expr = exprs; expr != NULL; expr = expr->next) {
       if (expr->expr_type == CEXPR_ATTR || expr->expr_type == CEXPR_NAMES) {
           switch (expr->op) {
           case CEXPR_EQ:      op = "eq";     break;
           case CEXPR_NEQ:     op = "neq";    break;
           case CEXPR_DOM:     op = "dom";    break;
           case CEXPR_DOMBY:   op = "domby";  break;
           case CEXPR_INCOMP:  op = "incomp"; break;
           default:
               log_err("Unknown constraint operator type: %i", expr->op);
               rc = -1;
               goto exit;
           }
 
           switch (expr->attr) {
           case CEXPR_USER:                 attr1 = "u1"; attr2 = "u2"; break;
           case CEXPR_USER | CEXPR_TARGET:  attr1 = "u2"; attr2 = "";   break;
           case CEXPR_USER | CEXPR_XTARGET: attr1 = "u3"; attr2 = "";   break;
           case CEXPR_ROLE:                 attr1 = "r1"; attr2 = "r2"; break;
           case CEXPR_ROLE | CEXPR_TARGET:  attr1 = "r2"; attr2 = "";   break;
           case CEXPR_ROLE | CEXPR_XTARGET: attr1 = "r3"; attr2 = "";   break;
           case CEXPR_TYPE:                 attr1 = "t1"; attr2 = "";   break;
           case CEXPR_TYPE | CEXPR_TARGET:  attr1 = "t2"; attr2 = "";   break;
           case CEXPR_TYPE | CEXPR_XTARGET: attr1 = "t3"; attr2 = "";   break;
           case CEXPR_L1L2:                 attr1 = "l1"; attr2 = "l2"; break;
           case CEXPR_L1H2:                 attr1 = "l1"; attr2 = "h2"; break;
           case CEXPR_H1L2:                 attr1 = "h1"; attr2 = "l2"; break;
           case CEXPR_H1H2:                 attr1 = "h1"; attr2 = "h2"; break;
           case CEXPR_L1H1:                 attr1 = "l1"; attr2 = "h1"; break;
           case CEXPR_L2H2:                 attr1 = "l2"; attr2 = "h2"; break;
           default:
               log_err("Unknown expression attribute type: %i", expr->attr);
               rc = -1;
               goto exit;
           }
 
           if (expr->expr_type == CEXPR_ATTR) {
               // length of values/attrs + 2 separating spaces + 2 parens + null terminator
               len = strlen(op) + strlen(attr1) + strlen(attr2) + 2 + 2 + 1;
               new_val = malloc(len);
               if (new_val == NULL) {
                   log_err("Out of memory");
                   rc = -1;
                   goto exit;
               }
               rlen = snprintf(new_val, len, "(%s %s %s)", op, attr1, attr2);
               if (rlen < 0 || rlen >= len) {
                   log_err("Failed to generate constraint expression");
                   rc = -1;
                   goto exit;
               }
           } else {
               if (expr->attr & CEXPR_TYPE) {
                   ts = expr->type_names;
                   rc = ebitmap_to_names(&ts->types, pdb->p_type_val_to_name, &name_list, &num_names);
                   if (rc != 0) {
                       goto exit;
                   }
               } else if (expr->attr & CEXPR_USER) {
                   rc = ebitmap_to_names(&expr->names, pdb->p_user_val_to_name, &name_list, &num_names);
                   if (rc != 0) {
                       goto exit;
                   }
               } else if (expr->attr & CEXPR_ROLE) {
                   rc = ebitmap_to_names(&expr->names, pdb->p_role_val_to_name, &name_list, &num_names);
                   if (rc != 0) {
                       goto exit;
                   }
               }
               rc = name_list_to_string(name_list, num_names, &names);
               if (rc != 0) {
                   goto exit;
               }
 
               // length of values/oper + 2 spaces + 2 parens + null terminator
               len = strlen(op) + strlen(attr1) +  strlen(names) + 2 + 2 + 1;
               new_val = malloc(len);
               if (new_val == NULL) {
                   log_err("Out of memory");
                   rc = -1;
                   goto exit;
               }
               rlen = snprintf(new_val, len, "(%s %s %s)", op, attr1, names);
               if (rlen < 0 || rlen >= len) {
                   log_err("Failed to generate constraint expression");
                   rc = -1;
                   goto exit;
               }
 
               names_destroy(&name_list, &num_names);
               free(names);
               names = NULL;
           }
       } else {
           switch (expr->expr_type) {
           case CEXPR_NOT: op = "not"; break;
           case CEXPR_AND: op = "and"; break;
           case CEXPR_OR:  op = "or"; break;
           default:
               log_err("Unknown constraint expression type: %i", expr->expr_type);
               rc = -1;
               goto exit;
           }
 
           num_params = expr->expr_type == CEXPR_NOT ? 1 : 2;
 
           if (num_params == 1) {
               val1 = stack_pop(stack);
               val2 = strdup("");
               if (val2 == NULL) {
                   log_err("Out of memory");
                   rc = -1;
                   goto exit;
               }
               fmt_str = "(%s %s)";
           } else {
               val2 = stack_pop(stack);
               val1 = stack_pop(stack);
               fmt_str = "(%s %s %s)";
           }
 
           if (val1 == NULL || val2 == NULL) {
               log_err("Invalid constraint expression");
               rc = -1;
               goto exit;
           }
 
           // length = length of parameters +
           //          length of operator +
           //          1 space preceeding each parameter +
           //          2 parens around the whole expression
           //          + null terminator
           len = strlen(val1) + strlen(val2) + strlen(op) + (num_params * 1) + 2 + 1;
           new_val = malloc(len);
           if (new_val == NULL) {
               log_err("Out of memory");
               rc = -1;
               goto exit;
           }
 
           // although we always supply val2 and there isn't always a 2nd
           // value, it should only be used when there are actually two values
           // in the format strings
           rlen = snprintf(new_val, len, fmt_str, op, val1, val2);
           if (rlen < 0 || rlen >= len) {
               log_err("Failed to generate constraint expression");
               rc = -1;
               goto exit;
           }
 
           free(val1);
           free(val2);
           val1 = NULL;
           val2 = NULL;
       }
 
       rc = stack_push(stack, new_val);
       if (rc != 0) {
           log_err("Out of memory");
           goto exit;
       }
 
       new_val = NULL;
   }
 
   new_val = stack_pop(stack);
   if (new_val == NULL || stack_peek(stack) != NULL) {
       log_err("Invalid constraint expression");
       rc = -1;
       goto exit;
   }
 
   *expr_string = new_val;
   new_val = NULL;
 
   rc = 0;
 
exit:
   names_destroy(&name_list, &num_names);
   free(names);
 
   free(new_val);
   free(val1);
   free(val2);
   if (stack != NULL) {
       while ((val1 = stack_pop(stack)) != NULL) {
           free(val1);
       }
       stack_destroy(&stack);
   }
 
   return rc;
}
 
 
static int constraints_to_cil(int indent, struct policydb *pdb, char *classkey, struct class_datum *class, struct constraint_node *constraints, int is_constraint)
{
   int rc = -1;
   struct constraint_node *node;
   char *expr = NULL;
   const char *mls;
   char *perms;
 
   mls = pdb->mls ? "mls" : "";
 
   for (node = constraints; node != NULL; node = node->next) {
 
       rc = constraint_expr_to_string(pdb, node->expr, &expr);
       if (rc != 0) {
           goto exit;
       }
 
       if (is_constraint) {
           perms = sepol_av_to_string(pdb, class->s.value, node->permissions);
           cil_println(indent, "(%sconstrain (%s (%s)) %s)", mls, classkey, perms + 1, expr);
       } else {
           cil_println(indent, "(%svalidatetrans %s %s)", mls, classkey, expr);
       }
 
       free(expr);
       expr = NULL;
   }
 
   rc = 0;
 
exit:
   free(expr);
   return rc;
}
 
static int class_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *UNUSED(decl_stack), char *key, void *datum, int scope)
{
   int rc = -1;
   struct class_datum *class = datum;
   const char *dflt;
   struct class_perm_array arr;
   uint32_t i;
 
   if (scope == SCOPE_REQ) {
       return 0;
   }
 
   arr.count = 0;
   arr.perms = calloc(class->permissions.nprim, sizeof(*arr.perms));
   if (arr.perms == NULL) {
       goto exit;
   }
   rc = hashtab_map(class->permissions.table, class_perm_to_array, &arr);
   if (rc != 0) {
       goto exit;
   }
 
   qsort(arr.perms, arr.count, sizeof(*arr.perms), class_perm_cmp);
 
   cil_indent(indent);
   cil_printf("(class %s (", key);
   for (i = 0; i < arr.count; i++) {
       cil_printf("%s ", arr.perms[i].name);
   }
   cil_printf("))\n");
 
   if (class->comkey != NULL) {
       cil_println(indent, "(classcommon %s %s)", key, class->comkey);
   }
 
   if (class->default_user != 0) {
       switch (class->default_user) {
       case DEFAULT_SOURCE:    dflt = "source";    break;
       case DEFAULT_TARGET:    dflt = "target";    break;
       default:
           log_err("Unknown default user value: %i", class->default_user);
           rc = -1;
           goto exit;
       }
       cil_println(indent, "(defaultuser %s %s)", key, dflt);
   }
 
   if (class->default_role != 0) {
       switch (class->default_role) {
       case DEFAULT_SOURCE:    dflt = "source";    break;
       case DEFAULT_TARGET:    dflt = "target";    break;
       default:
           log_err("Unknown default role value: %i", class->default_role);
           rc = -1;
           goto exit;
       }
       cil_println(indent, "(defaultrole %s %s)", key, dflt);
   }
 
   if (class->default_type != 0) {
       switch (class->default_type) {
       case DEFAULT_SOURCE:    dflt = "source";    break;
       case DEFAULT_TARGET:    dflt = "target";    break;
       default:
           log_err("Unknown default type value: %i", class->default_type);
           rc = -1;
           goto exit;
       }
       cil_println(indent, "(defaulttype %s %s)", key, dflt);
   }
 
   if (class->default_range != 0) {
       switch (class->default_range) {
       case DEFAULT_SOURCE_LOW:        dflt = "source low";    break;
       case DEFAULT_SOURCE_HIGH:        dflt = "source high";    break;
       case DEFAULT_SOURCE_LOW_HIGH:    dflt = "source low-high";    break;
       case DEFAULT_TARGET_LOW:        dflt = "target low";    break;
       case DEFAULT_TARGET_HIGH:        dflt = "target high";    break;
       case DEFAULT_TARGET_LOW_HIGH:    dflt = "target low-high";    break;
       default:
           log_err("Unknown default range value: %i", class->default_range);
           rc = -1;
           goto exit;
       }
       cil_println(indent, "(defaultrange %s %s)", key, dflt);
 
   }
 
   if (class->constraints != NULL) {
       rc = constraints_to_cil(indent, pdb, key, class, class->constraints, 1);
       if (rc != 0) {
           goto exit;
       }
   }
 
   if (class->validatetrans != NULL) {
       rc = constraints_to_cil(indent, pdb, key, class, class->validatetrans, 0);
       if (rc != 0) {
           goto exit;
       }
   }
 
   rc = 0;
 
exit:
   free(arr.perms);
   return rc;
}
 
static int class_order_to_cil(int indent, struct policydb *pdb, struct ebitmap order)
{
   struct ebitmap_node *node;
   uint32_t i;
 
   if (ebitmap_cardinality(&order) == 0) {
       return 0;
   }
 
   cil_indent(indent);
   cil_printf("(classorder (");
 
   ebitmap_for_each_bit(&order, node, i) {
       if (!ebitmap_get_bit(&order, i)) {
           continue;
       }
       cil_printf("%s ", pdb->sym_val_to_name[SYM_CLASSES][i]);
   }
 
   cil_printf("))\n");
 
   return 0;
}
 
static int role_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *decl_stack, char *key, void *datum, int scope)
{
   int rc = -1;
   struct ebitmap_node *node;
   uint32_t i;
   int j;
   char **types = NULL;
   int num_types = 0;
   struct role_datum *role = datum;
   struct type_set *ts;
   struct list *attr_list = NULL;
 
   rc = list_init(&attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   if (scope == SCOPE_REQ) {
       // if a role/roleattr is in the REQ scope, then it could cause an
       // optional block to fail, even if it is never used. However in CIL,
       // symbols must be used in order to cause an optional block to fail. So
       // for symbols in the REQ scope, add them to a roleattribute as a way
       // to 'use' them in the optional without affecting the resulting policy.
       cil_println(indent, "(roleattributeset " GEN_REQUIRE_ATTR " %s)", key);
   }
 
   switch (role->flavor) {
   case ROLE_ROLE:
       if (scope == SCOPE_DECL) {
           // Only declare certain roles if we are reading a base module.
           // These roles are defined in the base module and sometimes in
           // other non-base modules. If we generated the roles regardless of
           // the policy type, it would result in duplicate declarations,
           // which isn't allowed in CIL. Patches have been made to refpolicy
           // to remove these duplicate role declarations, but we need to be
           // backwards compatible and support older policies. Since we know
           // these roles are always declared in base, only print them when we
           // see them in the base module. If the declarations appear in a
           // non-base module, ignore their declarations.
           //
           // Note that this is a hack, and if a policy author does not define
           // one of these roles in base, the declaration will not appear in
           // the resulting policy, likely resulting in a compilation error in
           // CIL.
           //
           // To make things more complicated, the auditadm_r and secadm_r
           // roles could actually be in either the base module or a non-base
           // module, or both. So we can't rely on this same behavior. So for
           // these roles, don't declare them here, even if they are in a base
           // or non-base module. Instead we will just declare them in the
           // base module elsewhere.
           int is_base_role = (!strcmp(key, "user_r") ||
                               !strcmp(key, "staff_r") ||
                               !strcmp(key, "sysadm_r") ||
                               !strcmp(key, "system_r") ||
                               !strcmp(key, "unconfined_r"));
           int is_builtin_role = (!strcmp(key, "auditadm_r") ||
                                  !strcmp(key, "secadm_r"));
           if ((is_base_role && pdb->policy_type == SEPOL_POLICY_BASE) ||
               (!is_base_role && !is_builtin_role)) {
               cil_println(indent, "(role %s)", key);
           }
       }
 
       if (ebitmap_cardinality(&role->dominates) > 1) {
           log_err("Warning: role 'dominance' statement unsupported in CIL. Dropping from output.");
       }
 
       ts = &role->types;
       rc = process_typeset(pdb, ts, attr_list, &types, &num_types);
       if (rc != 0) {
           goto exit;
       }
 
       for (j = 0; j < num_types; j++) {
           if (is_id_in_scope(pdb, decl_stack, types[j], SYM_TYPES)) {
               cil_println(indent, "(roletype %s %s)", key, types[j]);
           }
       }
 
       if (role->bounds > 0) {
           cil_println(indent, "(rolebounds %s %s)", key, pdb->p_role_val_to_name[role->bounds - 1]);
       }
       break;
 
   case ROLE_ATTRIB:
       if (scope == SCOPE_DECL) {
           cil_println(indent, "(roleattribute %s)", key);
       }
 
       if (ebitmap_cardinality(&role->roles) > 0) {
           cil_indent(indent);
           cil_printf("(roleattributeset %s (", key);
           ebitmap_for_each_bit(&role->roles, node, i) {
               if (!ebitmap_get_bit(&role->roles, i)) {
                   continue;
               }
               cil_printf("%s ", pdb->p_role_val_to_name[i]);
           }
           cil_printf("))\n");
       }
 
       ts = &role->types;
       rc = process_typeset(pdb, ts, attr_list, &types, &num_types);
       if (rc != 0) {
           goto exit;
       }
 
 
       for (j = 0; j < num_types; j++) {
           if (is_id_in_scope(pdb, decl_stack, types[j], SYM_TYPES)) {
               cil_println(indent, "(roletype %s %s)", key, types[j]);
           }
       }
 
       break;
 
   default:
       log_err("Unknown role type: %i", role->flavor);
       rc = -1;
       goto exit;
   }
 
   rc = cil_print_attr_list(indent, pdb, attr_list);
   if (rc != 0) {
       goto exit;
   }
 
exit:
   attr_list_destroy(&attr_list);
   names_destroy(&types, &num_types);
 
   return rc;
}
 
static int type_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *decl_stack, char *key, void *datum, int scope)
{
   int rc = -1;
   struct type_datum *type = datum;
 
   if (scope == SCOPE_REQ) {
       // if a type/typeattr is in the REQ scope, then it could cause an
       // optional block to fail, even if it is never used. However in CIL,
       // symbols must be used in order to cause an optional block to fail. So
       // for symbols in the REQ scope, add them to a typeattribute as a way
       // to 'use' them in the optional without affecting the resulting policy.
       cil_println(indent, "(typeattributeset " GEN_REQUIRE_ATTR " %s)", key);
   }
 
   rc = roletype_role_in_ancestor_to_cil(pdb, decl_stack, key, indent);
   if (rc != 0) {
       goto exit;
   }
 
   switch(type->flavor) {
   case TYPE_TYPE:
       if (scope == SCOPE_DECL) {
           cil_println(indent, "(type %s)", key);
           // object_r is implicit in checkmodule, but not with CIL,
           // create it as part of base
           cil_println(indent, "(roletype " DEFAULT_OBJECT " %s)", key);
       }
 
       if (type->flags & TYPE_FLAGS_PERMISSIVE) {
           cil_println(indent, "(typepermissive %s)", key);
       }
 
       if (type->bounds > 0) {
           cil_println(indent, "(typebounds %s %s)", pdb->p_type_val_to_name[type->bounds - 1], key);
       }
       break;
   case TYPE_ATTRIB:
       if (scope == SCOPE_DECL) {
           cil_println(indent, "(typeattribute %s)", key);
       }
 
       if (type->flags & TYPE_FLAGS_EXPAND_ATTR) {
           cil_indent(indent);
           cil_printf("(expandtypeattribute (%s) ", key);
           if (type->flags & TYPE_FLAGS_EXPAND_ATTR_TRUE) {
               cil_printf("true");
           } else if (type->flags & TYPE_FLAGS_EXPAND_ATTR_FALSE) {
               cil_printf("false");
           }
           cil_printf(")\n");
       }
 
       if (ebitmap_cardinality(&type->types) > 0) {
           cil_indent(indent);
           cil_printf("(typeattributeset %s (", key);
           ebitmap_to_cil(pdb, &type->types, SYM_TYPES);
           cil_printf("))\n");
       }
       break;
   case TYPE_ALIAS:
       break;
   default:
       log_err("Unknown flavor (%i) of type %s", type->flavor, key);
       rc = -1;
       goto exit;
   }
 
   rc = 0;
 
exit:
   return rc;
}
 
static int user_to_cil(int indent, struct policydb *pdb, struct avrule_block *block, struct stack *UNUSED(decl_stack), char *key, void *datum,  int scope)
{
   struct user_datum *user = datum;
   struct ebitmap roles = user->roles.roles;
   struct mls_semantic_level level = user->dfltlevel;
   struct mls_semantic_range range = user->range;
   struct ebitmap_node *node;
   uint32_t i;
   int sens_offset = 1;
 
   if (scope == SCOPE_DECL) {
       cil_println(indent, "(user %s)", key);
       // object_r is implicit in checkmodule, but not with CIL, create it
       // as part of base
       cil_println(indent, "(userrole %s " DEFAULT_OBJECT ")", key);
   }
 
   ebitmap_for_each_bit(&roles, node, i) {
       if (!ebitmap_get_bit(&roles, i)) {
           continue;
       }
       cil_println(indent, "(userrole %s %s)", key, pdb->p_role_val_to_name[i]);
   }
 
   if (block->flags & AVRULE_OPTIONAL) {
       // sensitivites in user statements in optionals do not have the
       // standard -1 offset
       sens_offset = 0;
   }
 
   cil_indent(indent);
   cil_printf("(userlevel %s ", key);
   if (pdb->mls) {
       semantic_level_to_cil(pdb, sens_offset, &level);
   } else {
       cil_printf(DEFAULT_LEVEL);
   }
   cil_printf(")\n");
 
   cil_indent(indent);
   cil_printf("(userrange %s (", key);
   if (pdb->mls) {
       semantic_level_to_cil(pdb, sens_offset, &range.level[0]);
       cil_printf(" ");
       semantic_level_to_cil(pdb, sens_offset, &range.level[1]);
   } else {
       cil_printf(DEFAULT_LEVEL " " DEFAULT_LEVEL);
   }
   cil_printf("))\n");
 
 
   return 0;
}
 
static int boolean_to_cil(int indent, struct policydb *UNUSED(pdb), struct avrule_block *UNUSED(block), struct stack *UNUSED(decl_stack), char *key, void *datum,  int scope)
{
   struct cond_bool_datum *boolean = datum;
   const char *type;
 
   if (scope == SCOPE_DECL) {
       if (boolean->flags & COND_BOOL_FLAGS_TUNABLE) {
           type = "tunable";
       } else {
           type = "boolean";
       }
 
       cil_println(indent, "(%s %s %s)", type, key, boolean->state ? "true" : "false");
   }
 
   return 0;
}
 
static int sens_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *UNUSED(decl_stack), char *key, void *datum, int scope)
{
   struct level_datum *level = datum;
 
   if (scope == SCOPE_DECL) {
       if (!level->isalias) {
           cil_println(indent, "(sensitivity %s)", key);
       } else {
           cil_println(indent, "(sensitivityalias %s)", key);
           cil_println(indent, "(sensitivityaliasactual %s %s)", key, pdb->p_sens_val_to_name[level->level->sens - 1]);
       }
   }
 
   if (ebitmap_cardinality(&level->level->cat) > 0) {
       cil_indent(indent);
       cil_printf("(sensitivitycategory %s (", key);
       ebitmap_to_cil(pdb, &level->level->cat, SYM_CATS);
       cil_printf("))\n");
   }
 
   return 0;
}
 
static int sens_order_to_cil(int indent, struct policydb *pdb, struct ebitmap order)
{
   struct ebitmap_node *node;
   uint32_t i;
 
   if (ebitmap_cardinality(&order) == 0) {
       return 0;
   }
 
   cil_indent(indent);
   cil_printf("(sensitivityorder (");
 
   ebitmap_for_each_bit(&order, node, i) {
       if (!ebitmap_get_bit(&order, i)) {
           continue;
       }
       cil_printf("%s ", pdb->p_sens_val_to_name[i]);
   }
 
   cil_printf("))\n");
 
   return 0;
}
 
static int cat_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *UNUSED(decl_stack), char *key, void *datum,  int scope)
{
   struct cat_datum *cat = datum;
 
   if (scope == SCOPE_REQ) {
       return 0;
   }
 
   if (!cat->isalias) {
       cil_println(indent, "(category %s)", key);
   } else {
       cil_println(indent, "(categoryalias %s)", key);
       cil_println(indent, "(categoryaliasactual %s %s)", key, pdb->p_cat_val_to_name[cat->s.value - 1]);
   }
 
   return 0;
}
 
static int cat_order_to_cil(int indent, struct policydb *pdb, struct ebitmap order)
{
   int rc = -1;
   struct ebitmap_node *node;
   uint32_t i;
 
   if (ebitmap_cardinality(&order) == 0) {
       rc = 0;
       goto exit;
   }
 
   cil_indent(indent);
   cil_printf("(categoryorder (");
 
   ebitmap_for_each_bit(&order, node, i) {
       if (!ebitmap_get_bit(&order, i)) {
           continue;
       }
       cil_printf("%s ", pdb->p_cat_val_to_name[i]);
   }
 
   cil_printf("))\n");
 
   return 0;
exit:
   return rc;
}
 
static int polcaps_to_cil(struct policydb *pdb)
{
   int rc = -1;
   struct ebitmap *map;
   struct ebitmap_node *node;
   uint32_t i;
   const char *name;
 
   map = &pdb->policycaps;
 
   ebitmap_for_each_bit(map, node, i) {
       if (!ebitmap_get_bit(map, i)) {
           continue;
       }
       name = sepol_polcap_getname(i);
       if (name == NULL) {
           log_err("Unknown policy capability id: %i", i);
           rc = -1;
           goto exit;
       }
 
       cil_println(0, "(policycap %s)", name);
   }
 
   return 0;
exit:
   return rc;
}
 
static int level_to_cil(struct policydb *pdb, struct mls_level *level)
{
   struct ebitmap *map = &level->cat;
 
   cil_printf("(%s", pdb->p_sens_val_to_name[level->sens - 1]);
 
   if (ebitmap_cardinality(map) > 0) {
       cil_printf("(");
       ebitmap_to_cil(pdb, map, SYM_CATS);
       cil_printf(")");
   }
 
   cil_printf(")");
 
   return 0;
}
 
static int context_to_cil(struct policydb *pdb, struct context_struct *con)
{
   cil_printf("(%s %s %s (",
       pdb->p_user_val_to_name[con->user - 1],
       pdb->p_role_val_to_name[con->role - 1],
       pdb->p_type_val_to_name[con->type - 1]);
 
   if (pdb->mls) {
       level_to_cil(pdb, &con->range.level[0]);
       cil_printf(" ");
       level_to_cil(pdb, &con->range.level[1]);
   } else {
       cil_printf(DEFAULT_LEVEL);
       cil_printf(" ");
       cil_printf(DEFAULT_LEVEL);
   }
 
   cil_printf("))");
 
   return 0;
}
 
static int ocontext_isid_to_cil(struct policydb *pdb, const char *const *sid_to_string,
               unsigned num_sids, struct ocontext *isids)
{
   int rc = -1;
 
   struct ocontext *isid;
 
   struct sid_item {
       char *sid_key;
       struct sid_item *next;
   };
 
   struct sid_item *head = NULL;
   struct sid_item *item = NULL;
   char *sid;
   char unknown[18];
   unsigned i;
 
   for (isid = isids; isid != NULL; isid = isid->next) {
       i = isid->sid[0];
       if (i < num_sids) {
           sid = (char*)sid_to_string[i];
       } else {
           snprintf(unknown, 18, "%s%u", "UNKNOWN", i);
           sid = unknown;
       }
       cil_println(0, "(sid %s)", sid);
       cil_printf("(sidcontext %s ", sid);
       context_to_cil(pdb, &isid->context[0]);
       cil_printf(")\n");
 
       // get the sid names in the correct order (reverse from the isids
       // ocontext) for sidorder statement
       item = malloc(sizeof(*item));
       if (item == NULL) {
           log_err("Out of memory");
           rc = -1;
           goto exit;
       }
       item->sid_key = strdup(sid);
       item->next = head;
       head = item;
   }
 
   if (head != NULL) {
       cil_printf("(sidorder (");
       for (item = head; item != NULL; item = item->next) {
           cil_printf("%s ", item->sid_key);
       }
       cil_printf("))\n");
   }
 
   rc = 0;
 
exit:
   while(head) {
       item = head;
       head = item->next;
       free(item->sid_key);
       free(item);
   }
   return rc;
}
 
static int ocontext_selinux_isid_to_cil(struct policydb *pdb, struct ocontext *isids)
{
   int rc = -1;
 
   rc = ocontext_isid_to_cil(pdb, selinux_sid_to_str, SELINUX_SID_SZ, isids);
   if (rc != 0) {
       goto exit;
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int ocontext_selinux_fs_to_cil(struct policydb *UNUSED(pdb), struct ocontext *fss)
{
   if (fss != NULL) {
       log_err("Warning: 'fscon' statement unsupported in CIL. Dropping from output.");
   }
 
   return 0;
}
 
static int ocontext_selinux_port_to_cil(struct policydb *pdb, struct ocontext *portcons)
{
   int rc = -1;
   struct ocontext *portcon;
   const char *protocol;
   uint16_t high;
   uint16_t low;
 
   for (portcon = portcons; portcon != NULL; portcon = portcon->next) {
 
       switch (portcon->u.port.protocol) {
       case IPPROTO_TCP: protocol = "tcp"; break;
       case IPPROTO_UDP: protocol = "udp"; break;
       case IPPROTO_DCCP: protocol = "dccp"; break;
       case IPPROTO_SCTP: protocol = "sctp"; break;
       default:
           log_err("Unknown portcon protocol: %i", portcon->u.port.protocol);
           rc = -1;
           goto exit;
       }
 
       low = portcon->u.port.low_port;
       high = portcon->u.port.high_port;
 
       if (low == high) {
           cil_printf("(portcon %s %i ", protocol, low);
       } else {
           cil_printf("(portcon %s (%i %i) ", protocol, low, high);
       }
 
       context_to_cil(pdb, &portcon->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
exit:
   return rc;
}
 
static int ocontext_selinux_ibpkey_to_cil(struct policydb *pdb,
                   struct ocontext *ibpkeycons)
{
   int rc = -1;
   struct ocontext *ibpkeycon;
   char subnet_prefix_str[INET6_ADDRSTRLEN];
   struct in6_addr subnet_prefix = IN6ADDR_ANY_INIT;
   uint16_t high;
   uint16_t low;
 
   for (ibpkeycon = ibpkeycons; ibpkeycon; ibpkeycon = ibpkeycon->next) {
       low = ibpkeycon->u.ibpkey.low_pkey;
       high = ibpkeycon->u.ibpkey.high_pkey;
       memcpy(&subnet_prefix.s6_addr, &ibpkeycon->u.ibpkey.subnet_prefix,
              sizeof(ibpkeycon->u.ibpkey.subnet_prefix));
 
       if (inet_ntop(AF_INET6, &subnet_prefix.s6_addr,
                 subnet_prefix_str, INET6_ADDRSTRLEN) == NULL) {
           log_err("ibpkeycon subnet_prefix is invalid: %s",
               strerror(errno));
           rc = -1;
           goto exit;
       }
 
       if (low == high)
           cil_printf("(ibpkeycon %s %i ", subnet_prefix_str, low);
       else
           cil_printf("(ibpkeycon %s (%i %i) ", subnet_prefix_str, low,
                  high);
 
       context_to_cil(pdb, &ibpkeycon->context[0]);
 
       cil_printf(")\n");
   }
   return 0;
exit:
   return rc;
}
 
static int ocontext_selinux_netif_to_cil(struct policydb *pdb, struct ocontext *netifs)
{
   struct ocontext *netif;
 
   for (netif = netifs; netif != NULL; netif = netif->next) {
       cil_printf("(netifcon %s ", netif->u.name);
       context_to_cil(pdb, &netif->context[0]);
 
       cil_printf(" ");
       context_to_cil(pdb, &netif->context[1]);
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontext_selinux_node_to_cil(struct policydb *pdb, struct ocontext *nodes)
{
   int rc = -1;
   struct ocontext *node;
   char addr[INET_ADDRSTRLEN];
   char mask[INET_ADDRSTRLEN];
 
   for (node = nodes; node != NULL; node = node->next) {
       if (inet_ntop(AF_INET, &node->u.node.addr, addr, INET_ADDRSTRLEN) == NULL) {
           log_err("Nodecon address is invalid: %s", strerror(errno));
           rc = -1;
           goto exit;
       }
 
       if (inet_ntop(AF_INET, &node->u.node.mask, mask, INET_ADDRSTRLEN) == NULL) {
           log_err("Nodecon mask is invalid: %s", strerror(errno));
           rc = -1;
           goto exit;
       }
 
       cil_printf("(nodecon (%s) (%s) ", addr, mask);
 
       context_to_cil(pdb, &node->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
exit:
   return rc;
}
 
static int ocontext_selinux_node6_to_cil(struct policydb *pdb, struct ocontext *nodes)
{
   int rc = -1;
   struct ocontext *node;
   char addr[INET6_ADDRSTRLEN];
   char mask[INET6_ADDRSTRLEN];
 
   for (node = nodes; node != NULL; node = node->next) {
       if (inet_ntop(AF_INET6, &node->u.node6.addr, addr, INET6_ADDRSTRLEN) == NULL) {
           log_err("Nodecon address is invalid: %s", strerror(errno));
           rc = -1;
           goto exit;
       }
 
       if (inet_ntop(AF_INET6, &node->u.node6.mask, mask, INET6_ADDRSTRLEN) == NULL) {
           log_err("Nodecon mask is invalid: %s", strerror(errno));
           rc = -1;
           goto exit;
       }
 
       cil_printf("(nodecon (%s) (%s) ", addr, mask);
 
       context_to_cil(pdb, &node->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
exit:
   return rc;
}
 
static int ocontext_selinux_ibendport_to_cil(struct policydb *pdb, struct ocontext *ibendports)
{
   struct ocontext *ibendport;
 
   for (ibendport = ibendports; ibendport; ibendport = ibendport->next) {
       cil_printf("(ibendportcon %s %u ", ibendport->u.ibendport.dev_name, ibendport->u.ibendport.port);
       context_to_cil(pdb, &ibendport->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontext_selinux_fsuse_to_cil(struct policydb *pdb, struct ocontext *fsuses)
{
   int rc = -1;
   struct ocontext *fsuse;
   const char *behavior;
 
 
   for (fsuse = fsuses; fsuse != NULL; fsuse = fsuse->next) {
       switch (fsuse->v.behavior) {
       case SECURITY_FS_USE_XATTR: behavior = "xattr"; break;
       case SECURITY_FS_USE_TRANS: behavior = "trans"; break;
       case SECURITY_FS_USE_TASK:  behavior = "task"; break;
       default:
           log_err("Unknown fsuse behavior: %i", fsuse->v.behavior);
           rc = -1;
           goto exit;
       }
 
       cil_printf("(fsuse %s %s ", behavior, fsuse->u.name);
 
       context_to_cil(pdb, &fsuse->context[0]);
 
       cil_printf(")\n");
 
   }
 
   return 0;
exit:
   return rc;
}
 
 
static int ocontext_xen_isid_to_cil(struct policydb *pdb, struct ocontext *isids)
{
   int rc = -1;
 
   rc = ocontext_isid_to_cil(pdb, xen_sid_to_str, XEN_SID_SZ, isids);
   if (rc != 0) {
       goto exit;
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int ocontext_xen_pirq_to_cil(struct policydb *pdb, struct ocontext *pirqs)
{
   struct ocontext *pirq;
 
   for (pirq = pirqs; pirq != NULL; pirq = pirq->next) {
       cil_printf("(pirqcon %i ", pirq->u.pirq);
       context_to_cil(pdb, &pirq->context[0]);
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontext_xen_ioport_to_cil(struct policydb *pdb, struct ocontext *ioports)
{
   struct ocontext *ioport;
   uint32_t low;
   uint32_t high;
 
   for (ioport = ioports; ioport != NULL; ioport = ioport->next) {
       low = ioport->u.ioport.low_ioport;
       high = ioport->u.ioport.high_ioport;
 
       if (low == high) {
           cil_printf("(ioportcon 0x%x ", low);
       } else {
           cil_printf("(ioportcon (0x%x 0x%x) ", low, high);
       }
 
       context_to_cil(pdb, &ioport->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontext_xen_iomem_to_cil(struct policydb *pdb, struct ocontext *iomems)
{
   struct ocontext *iomem;
   uint64_t low;
   uint64_t high;
 
   for (iomem = iomems; iomem != NULL; iomem = iomem->next) {
       low = iomem->u.iomem.low_iomem;
       high = iomem->u.iomem.high_iomem;
 
       if (low == high) {
           cil_printf("(iomemcon 0x%"PRIx64" ", low);
       } else {
           cil_printf("(iomemcon (0x%"PRIx64" 0x%"PRIx64") ", low, high);
       }
 
       context_to_cil(pdb, &iomem->context[0]);
 
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontext_xen_pcidevice_to_cil(struct policydb *pdb, struct ocontext *pcids)
{
   struct ocontext *pcid;
 
   for (pcid = pcids; pcid != NULL; pcid = pcid->next) {
       cil_printf("(pcidevicecon 0x%lx ", (unsigned long)pcid->u.device);
       context_to_cil(pdb, &pcid->context[0]);
       cil_printf(")\n");
   }
 
   return 0;
}
 
static int ocontexts_to_cil(struct policydb *pdb)
{
   int rc = -1;
   int ocon;
 
   static int (**ocon_funcs)(struct policydb *pdb, struct ocontext *ocon);
   static int (*ocon_selinux_funcs[OCON_NUM])(struct policydb *pdb, struct ocontext *ocon) = {
       ocontext_selinux_isid_to_cil,
       ocontext_selinux_fs_to_cil,
       ocontext_selinux_port_to_cil,
       ocontext_selinux_netif_to_cil,
       ocontext_selinux_node_to_cil,
       ocontext_selinux_fsuse_to_cil,
       ocontext_selinux_node6_to_cil,
       ocontext_selinux_ibpkey_to_cil,
       ocontext_selinux_ibendport_to_cil,
   };
   static int (*ocon_xen_funcs[OCON_NUM])(struct policydb *pdb, struct ocontext *ocon) = {
       ocontext_xen_isid_to_cil,
       ocontext_xen_pirq_to_cil,
       ocontext_xen_ioport_to_cil,
       ocontext_xen_iomem_to_cil,
       ocontext_xen_pcidevice_to_cil,
       NULL,
       NULL,
   };
 
   switch (pdb->target_platform) {
   case SEPOL_TARGET_SELINUX:
       ocon_funcs = ocon_selinux_funcs;
       break;
   case SEPOL_TARGET_XEN:
       ocon_funcs = ocon_xen_funcs;
       break;
   default:
       log_err("Unknown target platform: %i", pdb->target_platform);
       rc = -1;
       goto exit;
   }
 
   for (ocon = 0; ocon < OCON_NUM; ocon++) {
       if (ocon_funcs[ocon] != NULL) {
           rc = ocon_funcs[ocon](pdb, pdb->ocontexts[ocon]);
           if (rc != 0) {
               goto exit;
           }
       }
   }
 
   return 0;
exit:
   return rc;
}
 
static int genfscon_to_cil(struct policydb *pdb)
{
   struct genfs *genfs;
   struct ocontext *ocon;
 
   for (genfs = pdb->genfs; genfs != NULL; genfs = genfs->next) {
       for (ocon = genfs->head; ocon != NULL; ocon = ocon->next) {
           cil_printf("(genfscon %s %s ", genfs->fstype, ocon->u.name);
           context_to_cil(pdb, &ocon->context[0]);
           cil_printf(")\n");
       }
   }
 
   return 0;
}
 
static int level_string_to_cil(char *levelstr)
{
   int rc = -1;
   char *sens = NULL;
   char *cats = NULL;
   int matched;
   char *saveptr = NULL;
   char *token = NULL;
   char *ranged = NULL;
 
   matched = tokenize(levelstr, ':', 2, &sens, &cats);
   if (matched < 1 || matched > 2) {
       log_err("Invalid level: %s", levelstr);
       rc = -1;
       goto exit;
   }
 
   cil_printf("(%s", sens);
 
   if (matched == 2) {
       cil_printf("(");
       token = strtok_r(cats, ",", &saveptr);
       while (token != NULL) {
           ranged = strchr(token, '.');
           if (ranged == NULL) {
               cil_printf("%s ", token);
           } else {
               *ranged = '\0';
               cil_printf("(range %s %s) ", token, ranged + 1);
           }
           token = strtok_r(NULL, ",", &saveptr);
       }
       cil_printf(")");
   }
 
   cil_printf(")");
 
   rc = 0;
exit:
   free(sens);
   free(cats);
   return rc;
}
 
static int level_range_string_to_cil(char *levelrangestr)
{
   char *ranged = NULL;
   char *low;
   char *high;
 
   ranged = strchr(levelrangestr, '-');
   if (ranged == NULL) {
       low = high = levelrangestr;
   } else {
       *ranged = '\0';
       low = levelrangestr;
       high = ranged + 1;
   }
 
   level_string_to_cil(low);
   cil_printf(" ");
   level_string_to_cil(high);
 
   return 0;
}
 
static int context_string_to_cil(char *contextstr)
{
   int rc = -1;
   int matched;
   char *user = NULL;
   char *role = NULL;
   char *type = NULL;
   char *level = NULL;
 
   matched = tokenize(contextstr, ':', 4, &user, &role, &type, &level);
   if (matched < 3 || matched > 4) {
       log_err("Invalid context: %s", contextstr);
       rc = -1;
       goto exit;
   }
 
   cil_printf("(%s %s %s (", user, role, type);
 
   if (matched == 3) {
       cil_printf(DEFAULT_LEVEL);
       cil_printf(" ");
       cil_printf(DEFAULT_LEVEL);
   } else {
       level_range_string_to_cil(level);
   }
 
   cil_printf("))");
 
   rc = 0;
 
exit:
   free(user);
   free(role);
   free(type);
   free(level);
 
   return rc;
}
 
static int seusers_to_cil(struct sepol_module_package *mod_pkg)
{
   int rc = -1;
   char *seusers = sepol_module_package_get_seusers(mod_pkg);
   size_t seusers_len = sepol_module_package_get_seusers_len(mod_pkg);
   char *cur = seusers;
   char *end = seusers + seusers_len;
   char *line = NULL;
   char *user = NULL;
   char *seuser = NULL;
   char *level = NULL;
   char *tmp = NULL;
   int matched;
 
   if (seusers_len == 0) {
       return 0;
   }
 
   while ((rc = get_line(&cur, end, &line)) > 0) {
       tmp = line;
       while (isspace(*tmp)) {
           tmp++;
       }
 
       if (tmp[0] == '#' || tmp[0] == '\0') {
           free(line);
           line = NULL;
           continue;
       }
 
       matched = tokenize(tmp, ':', 3, &user, &seuser, &level);
 
       if (matched < 2 || matched > 3) {
           log_err("Invalid seuser line: %s", line);
           rc = -1;
           goto exit;
       }
 
       if (!strcmp(user, "__default__")) {
           cil_printf("(selinuxuserdefault %s (", seuser);
       } else {
           cil_printf("(selinuxuser %s %s (", user, seuser);
       }
 
       switch (matched) {
       case 2:
           cil_printf("systemlow systemlow");
           break;
       case 3:
           level_range_string_to_cil(level);
           break;
       }
 
       cil_printf("))\n");
 
       free(user);
       free(seuser);
       free(level);
       free(line);
       user = seuser = level = NULL;
   }
 
   if (rc == -1) {
       cil_printf("Failed to read seusers\n");
       goto exit;
   }
 
   rc = 0;
exit:
   free(line);
   free(user);
   free(seuser);
   free(level);
 
   return rc;
}
 
static int netfilter_contexts_to_cil(struct sepol_module_package *mod_pkg)
{
   size_t netcons_len = sepol_module_package_get_netfilter_contexts_len(mod_pkg);
 
   if (netcons_len > 0) {
       log_err("Warning: netfilter_contexts are unsupported in CIL. Dropping from output.");
   }
 
   return 0;
}
 
static int user_extra_to_cil(struct sepol_module_package *mod_pkg)
{
   int rc = -1;
   char *userx = sepol_module_package_get_user_extra(mod_pkg);
   size_t userx_len = sepol_module_package_get_user_extra_len(mod_pkg);
   char *cur = userx;
   char *end = userx + userx_len;
   char *line;
   int matched;
   char *user = NULL;
   char *prefix = NULL;
   int prefix_len = 0;
   char *user_str = NULL;
   char *prefix_str = NULL;
   char *eol = NULL;
   char *tmp = NULL;
 
   if (userx_len == 0) {
       return 0;
   }
 
   while ((rc = get_line(&cur, end, &line)) > 0) {
       tmp = line;
       while (isspace(*tmp)) {
           tmp++;
       }
 
       if (tmp[0] == '#' || tmp[0] == '\0') {
           free(line);
           line = NULL;
           continue;
       }
 
       matched = tokenize(tmp, ' ', 4, &user_str, &user, &prefix_str, &prefix);
       if (matched != 4) {
           rc = -1;
           log_err("Invalid user extra line: %s", line);
           goto exit;
       }
 
       prefix_len = strlen(prefix);
       eol = prefix + prefix_len - 1;
       if (*eol != ';' || strcmp(user_str, "user") || strcmp(prefix_str, "prefix")) {
           rc = -1;
           log_err("Invalid user extra line: %s", line);
           goto exit;
       }
       *eol = '\0';
 
       cil_println(0, "(userprefix %s %s)", user, prefix);
       free(user);
       free(prefix);
       free(line);
       free(user_str);
       free(prefix_str);
       user = prefix = line = user_str = prefix_str = NULL;
   }
 
   if (rc == -1) {
       cil_printf("Failed to read user_extra\n");
       goto exit;
   }
 
   rc = 0;
exit:
   free(line);
   free(user);
   free(prefix);
 
   return rc;
}
 
static int file_contexts_to_cil(struct sepol_module_package *mod_pkg)
{
   int rc = -1;
   char *fc = sepol_module_package_get_file_contexts(mod_pkg);
   size_t fc_len = sepol_module_package_get_file_contexts_len(mod_pkg);
   char *cur = fc;
   char *end = fc + fc_len;
   char *line = NULL;
   int matched;
   char *regex = NULL;
   char *mode = NULL;
   char *context = NULL;
   const char *cilmode;
   char *tmp = NULL;
 
   if (fc_len == 0) {
       return 0;
   }
 
   while ((rc = get_line(&cur, end, &line)) > 0) {
       tmp = line;
       while (isspace(*tmp)) {
           tmp++;
       }
 
       if (tmp[0] == '#' || tmp[0] == '\0') {
           free(line);
           line = NULL;
           continue;
       }
 
       matched = tokenize(tmp, ' ', 3, &regex, &mode, &context);
       if (matched < 2 || matched > 3) {
           rc = -1;
           log_err("Invalid file context line: %s", line);
           goto exit;
       }
 
       if (matched == 2) {
           context = mode;
           mode = NULL;
       }
 
       if (mode == NULL) {
           cilmode = "any";
       } else if (!strcmp(mode, "--")) {
           cilmode = "file";
       } else if (!strcmp(mode, "-d")) {
           cilmode = "dir";
       } else if (!strcmp(mode, "-c")) {
           cilmode = "char";
       } else if (!strcmp(mode, "-b")) {
           cilmode = "block";
       } else if (!strcmp(mode, "-s")) {
           cilmode = "socket";
       } else if (!strcmp(mode, "-p")) {
           cilmode = "pipe";
       } else if (!strcmp(mode, "-l")) {
           cilmode = "symlink";
       } else {
           rc = -1;
           log_err("Invalid mode in file context line: %s", line);
           goto exit;
       }
 
       cil_printf("(filecon \"%s\" %s ", regex, cilmode);
 
       if (!strcmp(context, "<<none>>")) {
           cil_printf("()");
       } else {
           context_string_to_cil(context);
       }
 
       cil_printf(")\n");
 
       free(regex);
       free(mode);
       free(context);
       free(line);
       regex = mode = context = line = NULL;
   }
 
   if (rc == -1) {
       cil_printf("Failed to read file_contexts_to_cil\n");
       goto exit;
   }
 
   rc = 0;
exit:
   free(line);
   free(regex);
   free(mode);
   free(context);
 
   return rc;
}
 
 
static int (*func_to_cil[SYM_NUM])(int indent, struct policydb *pdb, struct avrule_block *block, struct stack *decl_stack, char *key, void *datum, int scope) = {
   NULL,    // commons, only stored in the global symtab, handled elsewhere
   class_to_cil,
   role_to_cil,
   type_to_cil,
   user_to_cil,
   boolean_to_cil,
   sens_to_cil,
   cat_to_cil
};
 
static int typealiases_to_cil(int indent, struct policydb *pdb, struct avrule_block *UNUSED(block), struct stack *decl_stack)
{
   struct type_datum *alias_datum;
   char *alias_name;
   char *type_name;
   struct list_node *curr;
   struct avrule_decl *decl = stack_peek(decl_stack);
   struct list *alias_list = typealias_lists[decl->decl_id];
   int rc = -1;
 
   if (alias_list == NULL) {
       return 0;
   }
 
   for (curr = alias_list->head; curr != NULL; curr = curr->next) {
       alias_name = curr->data;
       alias_datum = hashtab_search(pdb->p_types.table, alias_name);
       if (alias_datum == NULL) {
           rc = -1;
           goto exit;
       }
       if (alias_datum->flavor == TYPE_ALIAS) {
           type_name = pdb->p_type_val_to_name[alias_datum->primary - 1];
       } else {
           type_name = pdb->p_type_val_to_name[alias_datum->s.value - 1];
       }
       cil_println(indent, "(typealias %s)", alias_name);
       cil_println(indent, "(typealiasactual %s %s)", alias_name, type_name);
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int declared_scopes_to_cil(int indent, struct policydb *pdb, struct avrule_block *block, struct stack *decl_stack)
{
   int rc = -1;
   struct ebitmap map;
   struct ebitmap_node *node;
   unsigned int i;
   char * key;
   struct scope_datum *scope;
   int sym;
   void *datum;
   struct avrule_decl *decl = stack_peek(decl_stack);
 
   for (sym = 0; sym < SYM_NUM; sym++) {
       if (func_to_cil[sym] == NULL) {
           continue;
       }
 
       map = decl->declared.scope[sym];
       ebitmap_for_each_bit(&map, node, i) {
           if (!ebitmap_get_bit(&map, i)) {
               continue;
           }
           key = pdb->sym_val_to_name[sym][i];
           datum = hashtab_search(pdb->symtab[sym].table, key);
           if (datum == NULL) {
               rc = -1;
               goto exit;
           }
           scope = hashtab_search(pdb->scope[sym].table, key);
           if (scope == NULL) {
               rc = -1;
               goto exit;
           }
           rc = func_to_cil[sym](indent, pdb, block, decl_stack, key, datum, scope->scope);
           if (rc != 0) {
               goto exit;
           }
       }
 
       if (sym == SYM_CATS) {
           rc = cat_order_to_cil(indent, pdb, map);
           if (rc != 0) {
               goto exit;
           }
       }
 
       if (sym == SYM_LEVELS) {
           rc = sens_order_to_cil(indent, pdb, map);
           if (rc != 0) {
               goto exit;
           }
       }
 
       if (sym == SYM_CLASSES) {
           rc = class_order_to_cil(indent, pdb, map);
           if (rc != 0) {
               goto exit;
           }
       }
   }
 
   return 0;
exit:
   return rc;
}
 
static int required_scopes_to_cil(int indent, struct policydb *pdb, struct avrule_block *block, struct stack *decl_stack)
{
   int rc = -1;
   struct ebitmap map;
   struct ebitmap_node *node;
   unsigned int i;
   unsigned int j;
   char * key;
   int sym;
   void *datum;
   struct avrule_decl *decl = stack_peek(decl_stack);
   struct scope_datum *scope_datum;
 
   for (sym = 0; sym < SYM_NUM; sym++) {
       if (func_to_cil[sym] == NULL) {
           continue;
       }
 
       map = decl->required.scope[sym];
       ebitmap_for_each_bit(&map, node, i) {
           if (!ebitmap_get_bit(&map, i)) {
               continue;
           }
           key = pdb->sym_val_to_name[sym][i];
 
           scope_datum = hashtab_search(pdb->scope[sym].table, key);
           if (scope_datum == NULL) {
               rc = -1;
               goto exit;
           }
           for (j = 0; j < scope_datum->decl_ids_len; j++) {
               if (scope_datum->decl_ids[j] == decl->decl_id) {
                   break;
               }
           }
           if (j >= scope_datum->decl_ids_len) {
               // Symbols required in the global scope are also in the
               // required scope ebitmap of all avrule decls (i.e. required
               // in all optionals). So we need to look at the scopes of each
               // symbol in this avrule_decl to determine if it actually is
               // required in this decl, or if it's just required in the
               // global scope. If we got here, then this symbol is not
               // actually required in this scope, so skip it.
               continue;
           }
 
           datum = hashtab_search(pdb->symtab[sym].table, key);
           if (datum == NULL) {
               rc = -1;
               goto exit;
           }
           rc = func_to_cil[sym](indent, pdb, block, decl_stack, key, datum, SCOPE_REQ);
           if (rc != 0) {
               goto exit;
           }
       }
   }
 
   return 0;
exit:
   return rc;
}
 
 
static int additive_scopes_to_cil_map(char *key, void *data, void *arg)
{
   int rc = -1;
   struct map_args *args = arg;
 
   rc = func_to_cil[args->sym_index](args->indent, args->pdb, args->block, args->decl_stack, key, data, SCOPE_REQ);
   if (rc != 0) {
       goto exit;
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int additive_scopes_to_cil(int indent, struct policydb *pdb, struct avrule_block *block, struct stack *decl_stack)
{
   int rc = -1;
   struct map_args args;
   args.pdb = pdb;
   args.block = block;
   args.decl_stack = decl_stack;
   args.indent = indent;
   struct avrule_decl *decl = stack_peek(decl_stack);
 
   for (args.sym_index = 0; args.sym_index < SYM_NUM; args.sym_index++) {
       if (func_to_cil[args.sym_index] == NULL) {
           continue;
       }
       rc = hashtab_map(decl->symtab[args.sym_index].table, additive_scopes_to_cil_map, &args);
       if (rc != 0) {
           goto exit;
       }
   }
 
   return 0;
 
exit:
   return rc;
}
 
static int is_scope_superset(struct scope_index *sup, struct scope_index *sub)
{
   // returns 1 if sup is a superset of sub, returns 0 otherwise
 
   int rc = 0;
 
   uint32_t i;
   struct ebitmap sup_map;
   struct ebitmap sub_map;
   struct ebitmap res;
 
   ebitmap_init(&res);
 
   for (i = 0; i < SYM_NUM; i++) {
       sup_map = sup->scope[i];
       sub_map = sub->scope[i];
 
       ebitmap_and(&res, &sup_map, &sub_map);
       if (!ebitmap_cmp(&res, &sub_map)) {
           goto exit;
       }
       ebitmap_destroy(&res);
   }
 
   if (sup->class_perms_len < sub->class_perms_len) {
       goto exit;
   }
 
   for (i = 0; i < sub->class_perms_len; i++) {
       sup_map = sup->class_perms_map[i];
       sub_map = sub->class_perms_map[i];
 
       ebitmap_and(&res, &sup_map, &sub_map);
       if (!ebitmap_cmp(&res, &sub_map)) {
           goto exit;
       }
       ebitmap_destroy(&res);
   }
 
   rc = 1;
 
exit:
 
   ebitmap_destroy(&res);
   return rc;
}
 
static int block_to_cil(struct policydb *pdb, struct avrule_block *block, struct stack *stack, int indent)
{
   int rc = -1;
   struct avrule_decl *decl;
   struct list *type_attr_list = NULL;
   struct list *role_attr_list = NULL;
 
   decl = block->branch_list;
 
   rc = list_init(&type_attr_list);
   if (rc != 0) {
       goto exit;
   }
   rc = list_init(&role_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = typealiases_to_cil(indent, pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   rc = declared_scopes_to_cil(indent, pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   rc = required_scopes_to_cil(indent, pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   rc = additive_scopes_to_cil(indent, pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   rc = avrule_list_to_cil(indent, pdb, decl->avrules, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = role_trans_to_cil(indent, pdb, decl->role_tr_rules, role_attr_list, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = role_allows_to_cil(indent, pdb, decl->role_allow_rules, role_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = range_trans_to_cil(indent, pdb, decl->range_tr_rules, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = filename_trans_to_cil(indent, pdb, decl->filename_trans_rules, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = cond_list_to_cil(indent, pdb, decl->cond_list, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
   rc = cil_print_attr_list(indent, pdb, type_attr_list);
   if (rc != 0) {
       goto exit;
   }
   rc = cil_print_attr_list(indent, pdb, role_attr_list);
   if (rc != 0) {
       goto exit;
   }
 
exit:
   attr_list_destroy(&type_attr_list);
   attr_list_destroy(&role_attr_list);
 
   return rc;
}
 
static int module_block_to_cil(struct policydb *pdb, struct avrule_block *block, struct stack *stack, int *indent)
{
   int rc = 0;
   struct avrule_decl *decl;
   struct avrule_decl *decl_tmp;
 
   decl = block->branch_list;
   if (decl == NULL) {
       goto exit;
   }
 
   if (decl->next != NULL) {
       log_err("Warning: 'else' blocks in optional statements are unsupported in CIL. Dropping from output.");
   }
 
   if (block->flags & AVRULE_OPTIONAL) {
       while (stack->pos > 0) {
           decl_tmp = stack_peek(stack);
           if (is_scope_superset(&decl->required, &decl_tmp->required)) {
               break;
           }
 
           stack_pop(stack);
           (*indent)--;
           cil_println(*indent, ")");
       }
 
       cil_println(*indent, "(optional %s_optional_%i", pdb->name, decl->decl_id);
       (*indent)++;
   }
 
   stack_push(stack, decl);
 
   rc = block_to_cil(pdb, block, stack, *indent);
   if (rc != 0) {
       goto exit;
   }
 
exit:
   return rc;
}
 
static int global_block_to_cil(struct policydb *pdb, struct avrule_block *block, struct stack *stack)
{
   int rc = 0;
   struct avrule_decl *decl;
 
   decl = block->branch_list;
   if (decl == NULL) {
       goto exit;
   }
 
   if (decl->next != NULL) {
       log_err("Warning: 'else' not allowed in global block. Dropping from output.");
   }
 
   stack_push(stack, decl);
 
   // type aliases and commons are only stored in the global symtab.
   // However, to get scoping correct, we assume they are in the
   // global block
   rc = hashtab_map(pdb->p_commons.table, common_to_cil, NULL);
   if (rc != 0) {
       goto exit;
   }
 
   rc = block_to_cil(pdb, block, stack, 0);
   if (rc != 0) {
       goto exit;
   }
 
exit:
   return rc;
}
 
static int blocks_to_cil(struct policydb *pdb)
{
   int rc = -1;
   struct avrule_block *block;
   int indent = 0;
   struct stack *stack = NULL;
 
   rc = stack_init(&stack);
   if (rc != 0) {
       goto exit;
   }
 
   block = pdb->global;
   rc = global_block_to_cil(pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   for (block = block->next; block != NULL; block = block->next) {
       rc = module_block_to_cil(pdb, block, stack, &indent);
       if (rc != 0) {
           goto exit;
       }
   }
 
   while (indent > 0) {
       indent--;
       cil_println(indent, ")");
   }
 
exit:
   stack_destroy(&stack);
 
   return rc;
}
 
static int linked_block_to_cil(struct policydb *pdb, struct avrule_block *block, struct stack *stack)
{
   int rc = 0;
   struct avrule_decl *decl;
 
   decl = block->branch_list;
   if (decl == NULL) {
       goto exit;
   }
 
   if (!decl->enabled) {
       if (decl->next != NULL) {
           decl = decl->next;
       } else {
           goto exit;
       }
   }
 
   stack_push(stack, decl);
 
   rc = block_to_cil(pdb, block, stack, 0);
   if (rc != 0) {
       goto exit;
   }
 
   stack_pop(stack);
 
exit:
   return rc;
}
 
static int linked_blocks_to_cil(struct policydb *pdb)
{
   // Convert base module that has been linked to CIL
   // Since it is linked, all optional blocks have been resolved
   int rc = -1;
   struct avrule_block *block;
   struct stack *stack = NULL;
 
   rc = stack_init(&stack);
   if (rc != 0) {
       goto exit;
   }
 
   block = pdb->global;
   rc = global_block_to_cil(pdb, block, stack);
   if (rc != 0) {
       goto exit;
   }
 
   for (block = block->next; block != NULL; block = block->next) {
       rc = linked_block_to_cil(pdb, block, stack);
       if (rc != 0) {
           goto exit;
       }
   }
 
exit:
   stack_destroy(&stack);
 
   return rc;
}
 
static int handle_unknown_to_cil(struct policydb *pdb)
{
   int rc = -1;
   const char *hu;
 
   switch (pdb->handle_unknown) {
   case SEPOL_DENY_UNKNOWN:
       hu = "deny";
       break;
   case SEPOL_REJECT_UNKNOWN:
       hu = "reject";
       break;
   case SEPOL_ALLOW_UNKNOWN:
       hu = "allow";
       break;
   default:
       log_err("Unknown value for handle-unknown: %i", pdb->handle_unknown);
       rc = -1;
       goto exit;
   }
 
   cil_println(0, "(handleunknown %s)", hu);
 
   return 0;
 
exit:
   return rc;
}
 
static int generate_mls(struct policydb *pdb)
{
   const char *mls_str = pdb->mls ? "true" : "false";
   cil_println(0, "(mls %s)", mls_str);
 
   return 0;
}
 
static int generate_default_level(void)
{
   cil_println(0, "(sensitivity s0)");
   cil_println(0, "(sensitivityorder (s0))");
   cil_println(0, "(level " DEFAULT_LEVEL " (s0))");
 
   return 0;
}
 
static int generate_default_object(void)
{
   cil_println(0, "(role " DEFAULT_OBJECT ")");
 
   return 0;
}
 
static int generate_builtin_roles(void)
{
   // due to inconsistentencies between policies and CIL not allowing
   // duplicate roles, some roles are always created, regardless of if they
   // are declared in modules or not
   cil_println(0, "(role auditadm_r)");
   cil_println(0, "(role secadm_r)");
 
   return 0;
}
 
static int generate_gen_require_attribute(void)
{
   cil_println(0, "(typeattribute " GEN_REQUIRE_ATTR ")");
   cil_println(0, "(roleattribute " GEN_REQUIRE_ATTR ")");
 
   return 0;
}
 
static int fix_module_name(struct policydb *pdb)
{
   char *letter;
   int rc = -1;
 
   // The base module doesn't have its name set, but we use that for some
   // autogenerated names, like optionals and attributes, to prevent naming
   // collisions. However, they sometimes need to be fixed up.
 
   // the base module isn't given a name, so just call it "base"
   if (pdb->policy_type == POLICY_BASE) {
       pdb->name = strdup("base");
       if (pdb->name == NULL) {
           log_err("Out of memory");
           rc = -1;
           goto exit;
       }
   }
 
   // CIL is more restrictive in module names than checkmodule. Convert bad
   // characters to underscores
   for (letter = pdb->name; *letter != '\0'; letter++) {
       if (isalnum(*letter)) {
           continue;
       }
 
       *letter = '_';
   }
 
   return 0;
exit:
   return rc;
}
 
int sepol_module_policydb_to_cil(FILE *fp, struct policydb *pdb, int linked)
{
   int rc = -1;
 
   out_file = fp;
 
   if (pdb == NULL) {
       rc = 0;
       goto exit;
   }
 
   if (pdb->policy_type != SEPOL_POLICY_BASE &&
       pdb->policy_type != SEPOL_POLICY_MOD) {
       log_err("Policy pakcage is not a base or module");
       rc = -1;
       goto exit;
   }
 
   rc = fix_module_name(pdb);
   if (rc != 0) {
       goto exit;
   }
 
   if (pdb->policy_type == SEPOL_POLICY_BASE && !pdb->mls) {
       // If this is a base non-mls policy, we need to define a default level
       // range that can be used for contexts by other non-mls modules, since
       // CIL requires that all contexts have a range, even if they are
       // ignored as in non-mls policies
       rc = generate_default_level();
       if (rc != 0) {
           goto exit;
       }
   }
 
   if (pdb->policy_type == SEPOL_POLICY_BASE) {
       // object_r is implicit in checkmodule, but not with CIL, create it
       // as part of base
       rc = generate_default_object();
       if (rc != 0) {
           goto exit;
       }
 
       rc = generate_builtin_roles();
       if (rc != 0) {
           goto exit;
       }
 
       // default attribute to be used to mimic gen_require in CIL
       rc = generate_gen_require_attribute();
       if (rc != 0) {
           goto exit;
       }
 
       // handle_unknown is used from only the base module
       rc = handle_unknown_to_cil(pdb);
       if (rc != 0) {
           goto exit;
       }
 
       // mls is used from only the base module
       rc = generate_mls(pdb);
       if (rc != 0) {
           goto exit;
       }
   }
 
   rc = role_list_create(pdb->p_roles.table);
   if (rc != 0) {
       goto exit;
   }
 
   rc = typealias_list_create(pdb);
   if (rc != 0) {
       goto exit;
   }
 
   rc = polcaps_to_cil(pdb);
   if (rc != 0) {
       goto exit;
   }
 
   rc = ocontexts_to_cil(pdb);
   if (rc != 0) {
       goto exit;
   }
 
   rc = genfscon_to_cil(pdb);
   if (rc != 0) {
       goto exit;
   }
 
   // now print everything that is scoped
   if (linked) {
       rc = linked_blocks_to_cil(pdb);
   } else {
       rc = blocks_to_cil(pdb);
   }
   if (rc != 0) {
       goto exit;
   }
 
   rc = 0;
 
exit:
   role_list_destroy();
   typealias_list_destroy();
 
   return rc;
}
 
int sepol_module_package_to_cil(FILE *fp, struct sepol_module_package *mod_pkg)
{
   int rc = -1;
   struct sepol_policydb *pdb;
 
   out_file = fp;
 
   pdb = sepol_module_package_get_policy(mod_pkg);
   if (pdb == NULL) {
       log_err("Failed to get policydb");
       rc = -1;
       goto exit;
   }
 
   rc = sepol_module_policydb_to_cil(fp, &pdb->p, 0);
   if (rc != 0) {
       goto exit;
   }
 
   rc = seusers_to_cil(mod_pkg);
   if (rc != 0) {
       goto exit;
   }
 
   rc = netfilter_contexts_to_cil(mod_pkg);
   if (rc != 0) {
       goto exit;
   }
 
   rc = user_extra_to_cil(mod_pkg);
   if (rc != 0) {
       goto exit;
   }
 
   rc = file_contexts_to_cil(mod_pkg);
   if (rc != 0) {
       goto exit;
   }
 
   rc = 0;
 
exit:
   return rc;
}
 
static int fp_to_buffer(FILE *fp, char **data, size_t *data_len)
{
   int rc = -1;
   char *d = NULL;
   size_t d_len = 0;
   size_t read_len = 0;
   size_t max_len = 1 << 17; // start at 128KB, this is enough to hold about half of all the existing pp files
 
   d = malloc(max_len);
   if (d == NULL) {
       log_err("Out of memory");
       rc = -1;
       goto exit;
   }
 
   while ((read_len = fread(d + d_len, 1, max_len - d_len, fp)) > 0) {
       d_len += read_len;
       if (d_len == max_len) {
           max_len *= 2;
           d = realloc(d, max_len);
           if (d == NULL) {
               log_err("Out of memory");
               rc = -1;
               goto exit;
           }
       }
   }
 
   if (ferror(fp) != 0) {
       log_err("Failed to read pp file");
       rc = -1;
       goto exit;
   }
 
   *data = d;
   *data_len = d_len;
 
   return 0;
 
exit:
   free(d);
   return rc;
}
 
int sepol_ppfile_to_module_package(FILE *fp, struct sepol_module_package **mod_pkg)
{
   int rc = -1;
   struct sepol_policy_file *pf = NULL;
   struct sepol_module_package *pkg = NULL;
   char *data = NULL;
   size_t data_len;
   int fd;
   struct stat sb;
 
   rc = sepol_policy_file_create(&pf);
   if (rc != 0) {
       log_err("Failed to create policy file");
       goto exit;
   }
 
   fd = fileno(fp);
   if (fstat(fd, &sb) == -1) {
       rc = -1;
       goto exit;
   }
 
   if (S_ISFIFO(sb.st_mode) || S_ISSOCK(sb.st_mode)) {
       // libsepol fails when trying to read a policy package from a pipe or a
       // socket due its use of lseek. In this case, read the data into a
       // buffer and provide that to libsepol
       rc = fp_to_buffer(fp, &data, &data_len);
       if (rc != 0) {
           goto exit;
       }
 
       sepol_policy_file_set_mem(pf, data, data_len);
   } else {
       sepol_policy_file_set_fp(pf, fp);
   }
 
   rc = sepol_module_package_create(&pkg);
   if (rc != 0) {
       log_err("Failed to create module package");
       goto exit;
   }
 
   rc = sepol_module_package_read(pkg, pf, 0);
   if (rc != 0) {
       log_err("Failed to read policy package");
       goto exit;
   }
 
   *mod_pkg = pkg;
 
exit:
   free(data);
 
   sepol_policy_file_free(pf);
 
   if (rc != 0) {
       sepol_module_package_free(pkg);
   }
 
   return rc;
}